-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmoby.go
More file actions
316 lines (288 loc) · 7.32 KB
/
Copy pathmoby.go
File metadata and controls
316 lines (288 loc) · 7.32 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package main
import (
"context"
"fmt"
"io"
"net"
"net/netip"
"os"
"strings"
"time"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/client"
)
const label = "devdb"
func newClient() (*client.Client, error) {
// if DOCKER_HOST is set, use it
if os.Getenv("DOCKER_HOST") != "" {
return client.New(client.FromEnv)
}
// try common socket paths in order
sockets := []string{
// Docker
"/var/run/docker.sock",
// Podman rootless
fmt.Sprintf("/run/user/%d/podman/podman.sock", os.Getuid()),
// Podman rootful
"/run/podman/podman.sock",
}
for _, sock := range sockets {
connnection, err := net.Dial("unix", sock)
if err == nil {
connnection.Close()
return client.New(client.WithHost("unix://" + sock))
}
}
return nil, fmt.Errorf("no container runtime found — is Docker or Podman running?")
}
func pullImage(ctx context.Context, cli *client.Client, ref string) error {
fmt.Fprintf(os.Stderr, "pulling %s...\n", ref)
out, err := cli.ImagePull(ctx, ref, client.ImagePullOptions{})
if err != nil {
return err
}
defer out.Close()
io.Copy(io.Discard, out)
return nil
}
func killExisting(
ctx context.Context,
cli *client.Client,
name string,
port int,
) error {
f := client.Filters{}.Add("label", label)
containers, err := cli.ContainerList(ctx, client.ContainerListOptions{
All: true,
Filters: f,
})
if err != nil {
return err
}
for _, c := range containers.Items {
// always kill by name match
if c.Labels[label] == name {
kill(ctx, cli, c.ID)
continue
}
// also kill anything on the same port
for _, p := range c.Ports {
if int(p.PublicPort) == port {
kill(ctx, cli, c.ID)
break
}
}
}
return nil
}
func kill(ctx context.Context, cli *client.Client, id string) {
fmt.Fprintf(os.Stderr, "removing existing container %s...\n", id[:12])
cli.ContainerStop(ctx, id, client.ContainerStopOptions{})
cli.ContainerRemove(ctx, id, client.ContainerRemoveOptions{
Force: true,
RemoveVolumes: true,
})
}
func listContainers(ctx context.Context, cli *client.Client) error {
f := client.Filters{}.Add("label", label)
f = f.Add("label", label)
containers, err := cli.ContainerList(ctx, client.ContainerListOptions{
All: true,
Filters: f,
})
if err != nil {
return err
}
for _, c := range containers.Items {
fmt.Printf("%-20s %-15s %s\n", c.Labels[label], c.Image, c.State)
}
return nil
}
func runContainer(
context context.Context,
cli *client.Client,
config RunConfig,
profile DBProfile,
) error {
name := generateName(config)
if profile.defaults != nil {
config = profile.defaults(config)
name = config.name
}
if profile.validate != nil {
if err := profile.validate(config); err != nil {
return err
}
}
if config.host == "" {
config.host = "localhost"
}
if config.port == 0 {
config.port = profile.port
}
if config.user == "" {
config.user = name
}
if config.pass == "" {
config.pass = name
}
version := config.version
if version == "" {
version = profile.latest
}
tag, ok := profile.versions[version]
if !ok {
return fmt.Errorf("unsupported version %q for %s", version, config.db)
}
ref := profile.image + ":" + tag
if err := killExisting(context, cli, name, config.port); err != nil {
return err
}
if err := pullImage(context, cli, ref); err != nil {
return err
}
port_str := fmt.Sprintf("%d/tcp", profile.port)
port, err := network.ParsePort(port_str)
if err != nil {
return fmt.Errorf("invalid port %s: %w", port_str, err)
}
result, err := cli.ContainerCreate(context, client.ContainerCreateOptions{
Name: "devdb-" + name,
Config: &container.Config{
Image: ref,
Hostname: "devdb-" + name,
Env: toEnvSlice(profile.env(config)),
Labels: map[string]string{
label: name,
},
},
HostConfig: &container.HostConfig{
Privileged: profile.privileged,
Binds: makeVolumes(profile.volumes, "devdb-"+name),
PortBindings: network.PortMap{
network.Port(port): []network.PortBinding{{
HostIP: netip.MustParseAddr("127.0.0.1"),
HostPort: fmt.Sprintf("%d", config.port)}},
},
},
})
if err != nil {
return err
}
_, err = cli.ContainerStart(context, result.ID, client.ContainerStartOptions{})
if err != nil {
return err
}
if err := ready(context, cli, result.ID, config, profile); err != nil {
return err
}
fmt.Println(renderDSN(profile.dsn, config))
return nil
}
func toEnvSlice(env map[string]string) []string {
out := make([]string, 0, len(env))
for k, v := range env {
out = append(out, k+"="+v)
}
return out
}
func makeVolumes(volumes []string, containerName string) []string {
out := make([]string, 0, len(volumes))
for _, v := range volumes {
volName := containerName + strings.ReplaceAll(v, "/", "-")
out = append(out, volName+":"+v)
}
return out
}
func ready(
context context.Context,
cli *client.Client,
containerID string,
config RunConfig,
profile DBProfile,
) error {
deadline := time.Now().Add(profile.readyin)
address := fmt.Sprintf("%s:%d", config.host, config.port)
// phase 1: wait for port
fmt.Fprintf(os.Stderr, "waiting for %s...\n", address)
for time.Now().Before(deadline) {
remaining := time.Until(deadline).Round(time.Second)
fmt.Fprintf(os.Stderr, "waiting for %s... (%s left)\n", address, remaining)
conn, err := net.DialTimeout("tcp", address, 1*time.Second)
if err == nil {
conn.Close()
break
}
time.Sleep(1 * time.Second)
}
if time.Now().After(deadline) {
return fmt.Errorf("timed out waiting for %s", address)
}
// phase 2: readyCheck exec if defined
if profile.readyon == nil {
return nil
}
command := profile.readyon(config)
fmt.Fprintf(os.Stderr, "waiting for database to be ready...\n")
for time.Now().Before(deadline) {
left := time.Until(deadline).Round(time.Second)
fmt.Fprintf(os.Stderr, "waiting for database to be ready... (%s left)\n", left)
exit, err := execInContainer(context, cli, containerID, command)
if err == nil && exit == 0 {
return nil
}
time.Sleep(5 * time.Second)
}
dumpLogs(context, cli, containerID)
return fmt.Errorf("timed out waiting for database to be ready")
}
func dumpLogs(context context.Context, cli *client.Client, containerID string) {
fmt.Fprintln(os.Stderr, "--- container logs ---")
result, err := cli.ContainerLogs(context, containerID, client.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Tail: "50",
})
if err != nil {
fmt.Fprintf(os.Stderr, "could not get logs: %v\n", err)
return
}
defer result.Close()
io.Copy(os.Stderr, result)
fmt.Fprintln(os.Stderr, "--- end logs ---")
}
func execInContainer(
ctx context.Context,
cli *client.Client,
containerID string,
command []string,
) (int, error) {
exec, err := cli.ExecCreate(ctx, containerID, client.ExecCreateOptions{
Cmd: command,
AttachStdout: false,
AttachStderr: false,
})
if err != nil {
return -1, err
}
_, err = cli.ExecStart(ctx, exec.ID, client.ExecStartOptions{
Detach: true,
})
if err != nil {
return -1, err
}
// poll with a per-attempt timeout
timeout := time.Now().Add(10 * time.Second)
for time.Now().Before(timeout) {
inspect, err := cli.ExecInspect(ctx, exec.ID, client.ExecInspectOptions{})
if err != nil {
return -1, err
}
if !inspect.Running {
return inspect.ExitCode, nil
}
time.Sleep(100 * time.Millisecond)
}
return -1, fmt.Errorf("exec timed out")
}