-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.go
70 lines (60 loc) · 1.67 KB
/
pool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"context"
"net/http"
"time"
log "github.com/sirupsen/logrus"
)
func fillPool(ctx context.Context, WarmContainers chan<- runningContainer) {
for {
select {
case <-ctx.Done():
// WarmContainers will be cleaned up.
return
default:
container, err := createContainer(ctx)
if err != nil {
log.WithError(err).Error("Failed to create container")
time.Sleep(time.Second)
continue
}
log.WithField("containerID", container.containerID).Info("New container created and started")
err = waitForContainerToBoot(ctx, container)
if err != nil {
log.WithError(err).Error("Container not available")
_ = container.shutDown(ctx)
continue
}
// Add the new container to the pool.
// If the pool is full, this line will block until a slot is available.
WarmContainers <- *container
}
}
}
func waitForContainerToBoot(ctx context.Context, container *runningContainer) error {
// If the container is not available after 10s, move on.
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
// Query the endpoint until it provides a valid response.
for {
select {
case <-ctx.Done():
// Timeout reached.
return ctx.Err()
default:
res, err := http.Get("http://" + container.addr + "/_/health")
if err != nil {
log.WithError(err).Error("Container agent not ready yet")
time.Sleep(time.Second)
continue
}
if res.StatusCode != 200 {
log.WithField("containerID", container.containerID).Info("Container agent not ready yet")
} else {
log.WithField("containerID", container.containerID).Info("Container agent ready")
return nil
}
time.Sleep(time.Second)
}
}
}