-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathupdater.go
More file actions
581 lines (499 loc) · 16.6 KB
/
updater.go
File metadata and controls
581 lines (499 loc) · 16.6 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package infra
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/dependabot/cli/internal/model"
"github.com/docker/cli/cli/streams"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/goware/prefixer"
"github.com/moby/moby/pkg/stdcopy"
)
const jobID = "cli"
const (
root = "root"
dependabot = "dependabot"
)
const (
guestInputDir = "/home/dependabot/dependabot-updater/job.json"
guestRepoDir = "/home/dependabot/dependabot-updater/repo"
caseSensitiveContainerRoot = "/dpdbot"
caseSensitiveRepoContentsPath = "/dpdbot/repo"
caseInsensitiveContainerRoot = "/nocase"
caseInsensitiveRepoContentsPath = "/nocase/repo"
StorageImageName = "ghcr.io/dependabot/dependabot-storage"
storageUser = "dpduser"
storagePass = "dpdpass"
)
type Updater struct {
cli *client.Client
containerID string
storageContainerID string
storageVolumes []string
// ExitCode is set once an Updater command has completed.
ExitCode *int
}
const (
certsPath = "/etc/ssl/certs"
dbotCert = "/usr/local/share/ca-certificates/dbot-ca.crt"
)
// NewUpdater starts the update container interactively running /bin/sh, so it does not stop.
func NewUpdater(ctx context.Context, cli *client.Client, net *Networks, params *RunParams, prox *Proxy, collector *Collector) (*Updater, error) {
containerCfg := &container.Config{
User: dependabot,
Image: params.UpdaterImage,
Cmd: []string{"/bin/sh"},
Tty: true, // prevent container from stopping
}
if params.CollectorConfigPath != "" {
containerCfg.Env = append(
containerCfg.Env,
[]string{
"OTEL_ENABLED=true",
fmt.Sprintf("OTEL_EXPORTER_OTLP_ENDPOINT=%s", collector.url),
}...)
}
hostCfg := &container.HostConfig{}
var err error
for _, v := range params.Volumes {
var local, remote string
var readOnly bool
local, remote, readOnly, err = mountOptions(v)
if err != nil {
return nil, err
}
hostCfg.Mounts = append(hostCfg.Mounts, mount.Mount{
Type: mount.TypeBind,
Source: local,
Target: remote,
ReadOnly: readOnly,
})
}
storageContainerID := ""
storageVolumes := []string{}
if params.Job.UseCaseInsensitiveFileSystem() {
storageContainerID, storageVolumes, err = createStorageVolumes(hostCfg, ctx, cli, net, params.StorageImage)
if err != nil {
return nil, fmt.Errorf("failed to create storage volumes: %w", err)
}
}
netCfg := &network.NetworkingConfig{
EndpointsConfig: map[string]*network.EndpointSettings{
net.noInternetName: {
NetworkID: net.NoInternet.ID,
},
},
}
updaterContainer, err := cli.ContainerCreate(ctx, containerCfg, hostCfg, netCfg, nil, "")
if err != nil {
return nil, fmt.Errorf("failed to create updater container: %w", err)
}
updater := &Updater{
cli: cli,
containerID: updaterContainer.ID,
storageContainerID: storageContainerID,
storageVolumes: storageVolumes,
}
if err = putUpdaterInputs(ctx, cli, prox.ca.Cert, updaterContainer.ID, params.Job); err != nil {
updater.Close()
return nil, err
}
if err = cli.ContainerStart(ctx, updaterContainer.ID, container.StartOptions{}); err != nil {
updater.Close()
return nil, fmt.Errorf("failed to start updater container: %w", err)
}
return updater, nil
}
func createStorageVolumes(hostCfg *container.HostConfig, ctx context.Context, cli *client.Client, net *Networks, storageImageName string) (storageContainerID string, volumeNames []string, err error) {
log.Printf("Preparing case insensitive filesystem")
// create container hosting the storage
storageContainerCfg := &container.Config{
User: root,
Image: storageImageName,
Tty: true, // prevent container from stopping
}
storageHostCfg := &container.HostConfig{}
storageNetCfg := &network.NetworkingConfig{
EndpointsConfig: map[string]*network.EndpointSettings{
net.noInternetName: {
NetworkID: net.NoInternet.ID, // no external access for this container
},
},
}
storageContainer, err := cli.ContainerCreate(ctx, storageContainerCfg, storageHostCfg, storageNetCfg, nil, "")
if err != nil {
err = fmt.Errorf("failed to create storage container: %w", err)
return
}
storageContainerID = storageContainer.ID
caseSensitiveVolumeName := "dpdbot-storage-" + storageContainer.ID[:12]
caseInsensitiveVolumeName := "dpdbot-nocase-" + storageContainer.ID[:12]
volumeNames = []string{caseSensitiveVolumeName, caseInsensitiveVolumeName}
defer func() {
if err != nil {
removeStorageVolume(cli, ctx, caseSensitiveVolumeName)
removeStorageVolume(cli, ctx, caseInsensitiveVolumeName)
}
}()
// start storage container
if err = cli.ContainerStart(ctx, storageContainer.ID, container.StartOptions{}); err != nil {
err = fmt.Errorf("failed to start storage container: %w", err)
return
}
// wait for port 445 to be listening on the storage container
log.Printf(" waiting for storage container port 445 to be ready")
err = waitForPort(ctx, cli, storageContainer.ID, 445)
if err != nil {
err = fmt.Errorf("failed to wait for storage container port 445: %w", err)
return
}
// add volume mounts from the storage container; container IP is needed because the host is making a direct connection and it has not been given internet access
inspect, err := cli.ContainerInspect(ctx, storageContainerID)
if err != nil {
err = fmt.Errorf("failed to inspect storage container: %w", err)
return
}
storageContainerAddress := inspect.NetworkSettings.Networks[net.noInternetName].IPAddress
addStorageMounts(hostCfg, storageContainerAddress, caseSensitiveVolumeName, caseSensitiveContainerRoot, caseInsensitiveVolumeName, caseInsensitiveContainerRoot)
return
}
func removeStorageVolume(cli *client.Client, ctx context.Context, name string) error {
listOptions := volume.ListOptions{
Filters: filters.NewArgs(
filters.KeyValuePair{Key: "name", Value: name},
),
}
ls, err := cli.VolumeList(ctx, listOptions)
if err != nil {
return err
}
for _, v := range ls.Volumes {
if v.Name == name {
err = cli.VolumeRemove(ctx, v.Name, true)
if err != nil {
return err
}
}
}
return nil
}
func addStorageMounts(hostCfg *container.HostConfig, storageContainerAddress string, caseSensitiveVolumeName, caseSensitiveContainerRoot, caseInsensitiveVolumeName, caseInsensitiveContainerRoot string) {
const cifsVolumeType = "cifs"
localShareName := fmt.Sprintf("//%s/dpdbot", storageContainerAddress)
connectionOptions := fmt.Sprintf("username=%s,password=%s,uid=1000,gid=1000", storageUser, storagePass)
// create case-sensitive layer
hostCfg.Mounts = append(hostCfg.Mounts, mount.Mount{
Type: mount.TypeVolume,
Source: caseSensitiveVolumeName,
Target: caseSensitiveContainerRoot,
VolumeOptions: &mount.VolumeOptions{
DriverConfig: &mount.Driver{
Name: "local",
Options: map[string]string{
"type": cifsVolumeType,
"device": localShareName,
"o": connectionOptions,
},
},
},
})
// create case-insensitive layer
hostCfg.Mounts = append(hostCfg.Mounts, mount.Mount{
Type: mount.TypeVolume,
Source: caseInsensitiveVolumeName,
Target: caseInsensitiveContainerRoot,
VolumeOptions: &mount.VolumeOptions{
DriverConfig: &mount.Driver{
Name: "local",
Options: map[string]string{
"type": cifsVolumeType,
"device": localShareName,
"o": fmt.Sprintf("nocase,%s", connectionOptions),
},
},
},
})
}
func putUpdaterInputs(ctx context.Context, cli *client.Client, cert, id string, job *model.Job) error {
opt := container.CopyToContainerOptions{}
if t, err := tarball(dbotCert, cert); err != nil {
return fmt.Errorf("failed to create cert tarball: %w", err)
} else if err = cli.CopyToContainer(ctx, id, "/", t, opt); err != nil {
return fmt.Errorf("failed to copy cert to container: %w", err)
}
data, err := JobFile{Job: job}.ToJSON()
if err != nil {
return fmt.Errorf("failed to marshal job file: %w", err)
}
if t, err := tarball(guestInputDir, data); err != nil {
return fmt.Errorf("failed create input tarball: %w", err)
} else if err = cli.CopyToContainer(ctx, id, "/", t, opt); err != nil {
return fmt.Errorf("failed to copy input to container: %w", err)
}
return nil
}
var ErrInvalidVolume = fmt.Errorf("invalid volume syntax")
func mountOptions(v string) (local, remote string, readOnly bool, err error) {
parts := strings.Split(v, ":")
if len(parts) < 2 || len(parts) > 3 {
return "", "", false, ErrInvalidVolume
}
local = parts[0]
remote = parts[1]
if len(parts) == 3 {
if parts[2] != "ro" {
return "", "", false, ErrInvalidVolume
}
readOnly = true
}
if !path.IsAbs(local) {
wd, _ := os.Getwd()
local = filepath.Clean(filepath.Join(wd, local))
}
return local, remote, readOnly, nil
}
func userEnv(proxyURL string, apiUrl string, job *model.Job, additionalEnvVars []string) []string {
envVars := []string{
"GITHUB_ACTIONS=true", // sets exit code when fetch fails
fmt.Sprintf("http_proxy=%s", proxyURL),
fmt.Sprintf("HTTP_PROXY=%s", proxyURL),
fmt.Sprintf("https_proxy=%s", proxyURL),
fmt.Sprintf("HTTPS_PROXY=%s", proxyURL),
fmt.Sprintf("DEPENDABOT_JOB_ID=%v", firstNonEmpty(os.Getenv("DEPENDABOT_JOB_ID"), jobID)),
fmt.Sprintf("DEPENDABOT_JOB_TOKEN=%v", ""),
fmt.Sprintf("DEPENDABOT_JOB_PATH=%v", guestInputDir),
fmt.Sprintf("DEPENDABOT_API_URL=%s", apiUrl),
fmt.Sprintf("SSL_CERT_FILE=%v/ca-certificates.crt", certsPath),
"UPDATER_DETERMINISTIC=true",
}
if job.UseCaseInsensitiveFileSystem() {
envVars = append(envVars, fmt.Sprintf("DEPENDABOT_CASE_INSENSITIVE_REPO_CONTENTS_PATH=%s", caseInsensitiveRepoContentsPath))
envVars = append(envVars, fmt.Sprintf("DEPENDABOT_REPO_CONTENTS_PATH=%s", caseSensitiveRepoContentsPath))
} else {
envVars = append(envVars, fmt.Sprintf("DEPENDABOT_REPO_CONTENTS_PATH=%s", guestRepoDir))
}
envVars = append(envVars, additionalEnvVars...)
return envVars
}
// RunShell executes an interactive shell, blocks until complete.
func (u *Updater) RunShell(ctx context.Context, proxyURL string, apiUrl string, job *model.Job, additionalEnvVars []string) error {
execCreate, err := u.cli.ContainerExecCreate(ctx, u.containerID, container.ExecOptions{
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Tty: true,
User: dependabot,
Env: append(userEnv(proxyURL, apiUrl, job, additionalEnvVars), "DEBUG=1"),
Cmd: []string{"/bin/bash"},
})
if err != nil {
return fmt.Errorf("failed to create exec: %w", err)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
execResp, err := u.cli.ContainerExecAttach(ctx, execCreate.ID, container.ExecAttachOptions{})
if err != nil {
return fmt.Errorf("failed to start exec: %w", err)
}
ch := make(chan struct{})
out := streams.NewOut(os.Stdout)
_ = out.SetRawTerminal()
in := streams.NewIn(os.Stdin)
_ = in.SetRawTerminal()
defer func() {
out.RestoreTerminal()
in.RestoreTerminal()
in.Close()
}()
go func() {
_, _ = stdcopy.StdCopy(out, os.Stderr, execResp.Reader)
ch <- struct{}{}
}()
go func() {
_, _ = io.Copy(execResp.Conn, in)
ch <- struct{}{}
}()
_ = MonitorTtySize(ctx, out, u.cli, execCreate.ID, true)
select {
case <-ctx.Done():
return ctx.Err()
case <-ch:
cancel()
}
return nil
}
// RunCmd executes the update scripts as the dependabot user, blocks until complete.
func (u *Updater) RunCmd(ctx context.Context, cmd, user string, env ...string) error {
execCreate, err := u.cli.ContainerExecCreate(ctx, u.containerID, container.ExecOptions{
AttachStdout: true,
AttachStderr: true,
User: user,
Env: env,
Cmd: []string{"/bin/sh", "-c", cmd},
})
if err != nil {
return fmt.Errorf("failed to create exec: %w", err)
}
execResp, err := u.cli.ContainerExecAttach(ctx, execCreate.ID, container.ExecAttachOptions{})
if err != nil {
return fmt.Errorf("failed to start exec: %w", err)
}
r, w := io.Pipe()
go func() {
_, _ = io.Copy(os.Stderr, prefixer.New(r, "updater | "))
}()
ch := make(chan struct{})
go func() {
_, _ = stdcopy.StdCopy(w, w, execResp.Reader)
ch <- struct{}{}
}()
// blocks until update is complete or ctl-c
select {
case <-ctx.Done():
return ctx.Err()
case <-ch:
}
// check the exit code of the command
execInspect, err := u.cli.ContainerExecInspect(ctx, execCreate.ID)
if err != nil {
return fmt.Errorf("failed to inspect exec: %w", err)
}
u.ExitCode = &execInspect.ExitCode
return nil
}
// Wait blocks until the condition is true.
func (u *Updater) Wait(ctx context.Context, condition container.WaitCondition) error {
wait, errCh := u.cli.ContainerWait(ctx, u.containerID, condition)
select {
case v := <-wait:
if v.StatusCode != 0 {
return fmt.Errorf("updater exited with code: %v", v.StatusCode)
}
case err := <-errCh:
return fmt.Errorf("updater error while waiting: %w", err)
}
return nil
}
// Close kills and deletes the container and deletes updater mount paths related to the run.
func (u *Updater) Close() (err error) {
defer func() {
removeErr := u.cli.ContainerRemove(context.Background(), u.containerID, container.RemoveOptions{Force: true})
if removeErr != nil {
err = fmt.Errorf("failed to remove proxy container: %w", removeErr)
}
for _, v := range u.storageVolumes {
removeErr = u.cli.VolumeRemove(context.Background(), v, true)
if removeErr != nil {
err = fmt.Errorf("failed to remove storage volume %s: %w", v, removeErr)
}
}
if u.storageContainerID != "" {
removeErr = u.cli.ContainerRemove(context.Background(), u.storageContainerID, container.RemoveOptions{Force: true})
if removeErr != nil {
err = fmt.Errorf("failed to remove storage container: %w", removeErr)
}
}
}()
// Handle non-zero exit codes.
containerInfo, inspectErr := u.cli.ContainerInspect(context.Background(), u.containerID)
if inspectErr != nil {
return fmt.Errorf("failed to inspect proxy container: %w", inspectErr)
}
if containerInfo.State.ExitCode != 0 {
return fmt.Errorf("updater container exited with non-zero exit code: %d", containerInfo.State.ExitCode)
}
return
}
// JobFile is the payload passed to file updater containers.
type JobFile struct {
Job *model.Job `json:"job"`
}
func (j JobFile) ToJSON() (string, error) {
data, err := json.Marshal(j)
return string(data), err
}
func tarball(name, contents string) (*bytes.Buffer, error) {
var buf bytes.Buffer
t := tar.NewWriter(&buf)
if err := addFileToArchive(t, name, 0777, contents); err != nil {
return nil, fmt.Errorf("adding file to archive: %w", err)
}
return &buf, t.Flush()
}
func addFileToArchive(tw *tar.Writer, name string, mode int64, content string) error {
header := &tar.Header{
Name: name,
Size: int64(len(content)),
Mode: mode,
}
err := tw.WriteHeader(header)
if err != nil {
return err
}
_, err = tw.Write([]byte(content))
if err != nil {
return err
}
return nil
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if v != "" {
return v
}
}
return ""
}
func waitForPort(ctx context.Context, cli *client.Client, containerID string, port int) error {
const maxAttempts = 5
const sleepDuration = time.Second
// check /proc/net/tcp for the requested port; n.b., it is hex encoded and 4 characters wide
testCmd := fmt.Sprintf("test -f /proc/net/tcp && grep ' *\\d+: [A-F0-9]{8}:%04X ' /proc/net/tcp >/dev/null 2>&1", port)
for i := range maxAttempts {
execCreate, err := cli.ContainerExecCreate(ctx, containerID, container.ExecOptions{
AttachStdout: false,
AttachStderr: false,
User: root,
Cmd: []string{"/bin/sh", "-c", testCmd},
})
if err != nil {
return fmt.Errorf("failed to create exec for port check: %w", err)
}
execResp, err := cli.ContainerExecAttach(ctx, execCreate.ID, container.ExecAttachOptions{})
if err != nil {
return fmt.Errorf("failed to attach to exec for port check: %w", err)
}
// wait for completion and check the exit code
execResp.Close()
execInspect, err := cli.ContainerExecInspect(ctx, execCreate.ID)
if err != nil {
return fmt.Errorf("failed to inspect exec: %w", err)
}
if execInspect.ExitCode == 0 {
// port is listening
log.Printf(" port %d is listening after %d attempts", port, i+1)
// in a few instances, the port is open but the service isn't yet ready for connections
// no more reliable method has been found, other than a short delay
time.Sleep(sleepDuration)
return nil
}
if i < maxAttempts-1 {
time.Sleep(sleepDuration)
}
}
return fmt.Errorf("port %d is not listening after %d attempts", port, maxAttempts)
}