generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
container.go
283 lines (235 loc) · 6.97 KB
/
container.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package container
import (
"context"
"fmt"
"io"
"os"
"strconv"
"time"
"github.com/alecthomas/types/once"
"github.com/alecthomas/types/optional"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/TBD54566975/ftl/internal/log"
)
var dockerClient = once.Once(func(ctx context.Context) (*client.Client, error) {
return client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
})
func DoesExist(ctx context.Context, name string) (bool, error) {
cli, err := dockerClient.Get(ctx)
if err != nil {
return false, err
}
containers, err := cli.ContainerList(ctx, container.ListOptions{
All: true,
Filters: filters.NewArgs(filters.Arg("name", name)),
})
if err != nil {
return false, fmt.Errorf("failed to list containers: %w", err)
}
return len(containers) > 0, nil
}
// Pull pulls the given image.
func Pull(ctx context.Context, imageName string) error {
cli, err := dockerClient.Get(ctx)
if err != nil {
return err
}
reader, err := cli.ImagePull(ctx, imageName, image.PullOptions{})
if err != nil {
return fmt.Errorf("failed to pull %s image: %w", imageName, err)
}
defer reader.Close()
logger := log.FromContext(ctx)
_, err = io.Copy(logger.WriterAt(log.Info), reader)
if err != nil {
return fmt.Errorf("failed to stream pull: %w", err)
}
return nil
}
// Run starts a new detached container with the given image, name, port map, and (optional) volume mount.
func Run(ctx context.Context, image, name string, hostPort, containerPort int, volume optional.Option[string]) error {
cli, err := dockerClient.Get(ctx)
if err != nil {
return err
}
config := container.Config{
Image: image,
}
containerNatPort := nat.Port(fmt.Sprintf("%d/tcp", containerPort))
hostConfig := container.HostConfig{
RestartPolicy: container.RestartPolicy{
Name: container.RestartPolicyAlways,
},
PortBindings: nat.PortMap{
containerNatPort: []nat.PortBinding{
{
HostPort: strconv.Itoa(hostPort),
},
},
},
}
if v, ok := volume.Get(); ok {
hostConfig.Binds = []string{v}
}
created, err := cli.ContainerCreate(ctx, &config, &hostConfig, nil, nil, name)
if err != nil {
return fmt.Errorf("failed to create %s container: %w", name, err)
}
err = cli.ContainerStart(ctx, created.ID, container.StartOptions{})
if err != nil {
return fmt.Errorf("failed to start %s container: %w", name, err)
}
return nil
}
// RunDB runs a new detached postgres container with the given name and exposed port.
func RunDB(ctx context.Context, name string, port int) error {
cli, err := dockerClient.Get(ctx)
if err != nil {
return err
}
const containerName = "postgres"
exists, err := DoesExist(ctx, containerName)
if err != nil {
return err
}
if !exists {
err = Pull(ctx, "postgres:latest")
if err != nil {
return err
}
}
config := container.Config{
Image: "postgres:latest",
Env: []string{"POSTGRES_PASSWORD=secret"},
User: "postgres",
Cmd: []string{"postgres"},
Healthcheck: &container.HealthConfig{
Test: []string{"CMD-SHELL", "pg_isready"},
Interval: time.Second,
Retries: 60,
Timeout: 60 * time.Second,
StartPeriod: 80 * time.Second,
},
}
hostConfig := container.HostConfig{
RestartPolicy: container.RestartPolicy{
Name: container.RestartPolicyAlways,
},
PortBindings: nat.PortMap{
"5432/tcp": []nat.PortBinding{
{
HostPort: strconv.Itoa(port),
},
},
},
}
created, err := cli.ContainerCreate(ctx, &config, &hostConfig, nil, nil, name)
if err != nil {
return fmt.Errorf("failed to create db container: %w", err)
}
err = cli.ContainerStart(ctx, created.ID, container.StartOptions{})
if err != nil {
return fmt.Errorf("failed to start db container: %w", err)
}
return nil
}
// Start starts an existing container with the given name.
func Start(ctx context.Context, name string) error {
cli, err := dockerClient.Get(ctx)
if err != nil {
return err
}
err = cli.ContainerStart(ctx, name, container.StartOptions{})
if err != nil {
return fmt.Errorf("failed to start container: %w", err)
}
return nil
}
// Exec runs a command in the given container, stream to stderr. Return an error if the command fails.
func Exec(ctx context.Context, name string, command ...string) error {
logger := log.FromContext(ctx)
logger.Debugf("Running command %q in container %q", command, name)
cli, err := dockerClient.Get(ctx)
if err != nil {
return err
}
exec, err := cli.ContainerExecCreate(ctx, name, types.ExecConfig{
Cmd: command,
AttachStderr: true,
AttachStdout: true,
})
if err != nil {
return fmt.Errorf("failed to create exec: %w", err)
}
attach, err := cli.ContainerExecAttach(ctx, exec.ID, types.ExecStartCheck{})
if err != nil {
return fmt.Errorf("failed to attach exec: %w", err)
}
defer attach.Close()
_, err = io.Copy(os.Stderr, attach.Reader)
if err != nil {
return fmt.Errorf("failed to stream exec: %w", err)
}
err = cli.ContainerExecStart(ctx, exec.ID, types.ExecStartCheck{})
if err != nil {
return fmt.Errorf("failed to start exec: %w", err)
}
inspect, err := cli.ContainerExecInspect(ctx, exec.ID)
if err != nil {
return fmt.Errorf("failed to inspect exec: %w", err)
}
if inspect.ExitCode != 0 {
return fmt.Errorf("exec failed with exit code %d", inspect.ExitCode)
}
return nil
}
// GetContainerPort returns the host TCP port of the given container's exposed port.
func GetContainerPort(ctx context.Context, name string, port int) (int, error) {
cli, err := dockerClient.Get(ctx)
if err != nil {
return 0, err
}
inspect, err := cli.ContainerInspect(ctx, name)
if err != nil {
return 0, fmt.Errorf("failed to inspect container: %w", err)
}
containerPort := fmt.Sprintf("%d/tcp", port)
hostPort, ok := inspect.NetworkSettings.Ports[nat.Port(containerPort)]
if !ok {
return 0, fmt.Errorf("container port %q not found", containerPort)
}
if len(hostPort) == 0 {
return 0, fmt.Errorf("container port %q not bound", containerPort)
}
return nat.Port(hostPort[0].HostPort).Int(), nil
}
// PollContainerHealth polls the given container until it is healthy or the timeout is reached.
func PollContainerHealth(ctx context.Context, containerName string, timeout time.Duration) error {
logger := log.FromContext(ctx)
logger.Debugf("Waiting for %s to be healthy", containerName)
cli, err := dockerClient.Get(ctx)
if err != nil {
return err
}
pollCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
for {
select {
case <-pollCtx.Done():
return fmt.Errorf("timed out waiting for container to be healthy: %w", pollCtx.Err())
case <-time.After(100 * time.Millisecond):
inspect, err := cli.ContainerInspect(pollCtx, containerName)
if err != nil {
return fmt.Errorf("failed to inspect container: %w", err)
}
if inspect.State.Health.Status == types.Healthy {
return nil
}
}
}
}