Debian Codegraph @

dockerclient/client.go

raw ◀ ▶
2 Debian patches touch this file
1 package dockerclient
2
3 import (
4 "archive/tar"
5 "bufio"
6 "bytes"
7 "context"
8 "crypto/rand"
9 "errors"
10 "fmt"
11 "io"
12 "os"
13 "path/filepath"
14 "runtime"
15 "sort"
16 "strconv"
17 "strings"
18
19 docker "github.com/fsouza/go-dockerclient"
•20 dockerregistrytypes "github.com/docker/docker/api/types/registry"
•21 "k8s.io/klog/v2"
22
23 "github.com/openshift/imagebuilder"
24 "github.com/openshift/imagebuilder/dockerfile/parser"
25 "github.com/openshift/imagebuilder/imageprogress"
26 "github.com/tonistiigi/dchapes-mode"
27 )
28
29 // NewClientFromEnv is exposed to simplify getting a client when vendoring this library.
30 func NewClientFromEnv() (*docker.Client, error) {
31 return docker.NewClientFromEnv()
32 }
33
34 // Mount represents a binding between the current system and the destination client
35 type Mount struct {
36 SourcePath string
37 DestinationPath string
38 }
39
40 // ClientExecutor can run Docker builds from a Docker client.
41 type ClientExecutor struct {
42 // Name is an optional name for this executor.
43 Name string
44 // Named is a map of other named executors.
45 Named map[string]*ClientExecutor
46
47 // TempDir is the temporary directory to use for storing file
48 // contents. If unset, the default temporary directory for the
49 // system will be used.
50 TempDir string
51 // Client is a client to a Docker daemon.
52 Client *docker.Client
53 // Directory is the context directory to build from, will use
54 // the current working directory if not set. Ignored if
55 // ContextArchive is set.
56 Directory string
57 // A compressed or uncompressed tar archive that should be used
58 // as the build context.
59 ContextArchive string
60 // Excludes are a list of file patterns that should be excluded
61 // from the context. Will be set to the contents of the
62 // .dockerignore file if nil.
63 Excludes []string
64 // Tag is an optional value to tag the resulting built image.
65 Tag string
66 // Additional tags is an optional array of other tags to apply
67 // to the image.
68 AdditionalTags []string
69 // AllowPull when set will pull images that are not present on
70 // the daemon.
71 AllowPull bool
72 // IgnoreUnrecognizedInstructions, if true, allows instructions
73 // that are not yet supported to be ignored (will be printed)
74 IgnoreUnrecognizedInstructions bool
75 // StrictVolumeOwnership if true will fail the build if a RUN
76 // command follows a VOLUME command, since this client cannot
77 // guarantee that the restored contents of the VOLUME directory
78 // will have the right permissions.
79 StrictVolumeOwnership bool
80 // TransientMounts are a set of mounts from outside the build
81 // to the inside that will not be part of the final image. Any
82 // content created inside the mount's destinationPath will be
83 // omitted from the final image.
84 TransientMounts []Mount
85
86 // The path within the container to perform the transient mount.
87 ContainerTransientMount string
88
89 // The streams used for canonical output.
90 Out, ErrOut io.Writer
91
92 // Container is optional and can be set to a container to use as
93 // the execution environment for a build.
94 Container *docker.Container
95 // Command, if set, will be used as the entrypoint for the new
96 // container. This is ignored if Container is set.
97 Command []string
98 // Image is optional and may be set to control which image is used
99 // as a base for this build. Otherwise the FROM value from the
100 // Dockerfile is read (will be pulled if not locally present).
101 Image *docker.Image
102 // Committed is optional and is used to track a temporary image, if one
103 // was created, that was based on the container as its stage ended.
104 Committed *docker.Image
105
106 // AuthFn will handle authenticating any docker pulls if Image
107 // is set to nil.
108 AuthFn func(name string) ([]dockerregistrytypes.AuthConfig, bool)
109 // HostConfig is used to start the container (if necessary).
110 HostConfig *docker.HostConfig
111 // LogFn is an optional command to log information to the end user
112 LogFn func(format string, args ...interface{})
113
114 // Deferred is a list of operations that must be cleaned up at
115 // the end of execution. Use Release() to invoke all of these.
116 Deferred []func() error
117
118 // Volumes handles saving and restoring volumes after RUN
119 // commands are executed.
120 Volumes *ContainerVolumeTracker
121 }
122
123 // NoAuthFn can be used for AuthFn when no authentication is required in Docker.
124 func NoAuthFn(string) ([]dockerregistrytypes.AuthConfig, bool) {
125 return nil, false
126 }
127
128 // NewClientExecutor creates a client executor.
129 func NewClientExecutor(client *docker.Client) *ClientExecutor {
130 return &ClientExecutor{
131 Client: client,
132 LogFn: func(string, ...interface{}) {},
133
134 ContainerTransientMount: "/.imagebuilder-transient-mount",
135 }
136 }
137
138 // DefaultExcludes reads the default list of excluded file patterns from the
139 // context directory's .containerignore file if it exists, or from the context
140 // directory's .dockerignore file, if it exists.
141 func (e *ClientExecutor) DefaultExcludes() error {
142 var err error
143 e.Excludes, err = imagebuilder.ParseDockerignore(e.Directory)
144 return err
145 }
146
147 // WithName creates a new child executor that will be used whenever a COPY statement
148 // uses --from=NAME or --from=POSITION.
149 func (e *ClientExecutor) WithName(name string, position int) *ClientExecutor {
150 if e.Named == nil {
151 e.Named = make(map[string]*ClientExecutor)
152 }
153 e.Deferred = append([]func() error{func() error {
154 stage, ok := e.Named[strconv.Itoa(position)]
155 if !ok {
156 return fmt.Errorf("error finding stage %d", position)
157 }
158 errs := stage.Release()
159 if len(errs) > 0 {
160 return fmt.Errorf("%v", errs)
161 }
162 return nil
163 }}, e.Deferred...)
164
165 copied := *e
166 copied.Name = name
167 copied.Container = nil
168 copied.Deferred = nil
169 copied.Image = nil
170 copied.Volumes = nil
171 copied.Committed = nil
172
173 child := &copied
174 e.Named[name] = child
175 e.Named[strconv.Itoa(position)] = child
176 return child
177 }
178
179 // Stages executes all of the provided stages, starting from the base image. It returns the executor of the last stage
180 // or an error if a stage fails.
181 func (e *ClientExecutor) Stages(b *imagebuilder.Builder, stages imagebuilder.Stages, from string) (*ClientExecutor, error) {
182 var stageExecutor *ClientExecutor
183 for i, stage := range stages {
184 stageExecutor = e.WithName(stage.Name, stage.Position)
185
186 var stageFrom string
187 if i == 0 {
188 stageFrom = from
189 } else {
190 from, err := b.From(stage.Node)
191 if err != nil {
192 return nil, fmt.Errorf("error: Determining base image: %v", err)
193 }
194 if b.After != "" {
195 return nil, fmt.Errorf("the --after flag in FROM is not supported by the dockerclient executor")
196 }
197 if prereq := e.Named[from]; prereq != nil {
198 b, ok := stages[:i].ByName(from)
199 if !ok {
200 return nil, fmt.Errorf("error: Unable to find stage %s builder", from)
201 }
202 if prereq.Committed == nil {
203 config := b.Builder.Config()
204 if prereq.Container.State.Running {
205 klog.V(4).Infof("Stopping container %s ...", prereq.Container.ID)
206 if err := e.Client.StopContainer(prereq.Container.ID, 0); err != nil {
207 return nil, fmt.Errorf("unable to stop build container: %v", err)
208 }
209 prereq.Container.State.Running = false
210 // Starting the container may perform escaping of args, so to be consistent
211 // we also set that here
212 config.ArgsEscaped = true
213 }
214 image, err := e.Client.CommitContainer(docker.CommitContainerOptions{
215 Container: prereq.Container.ID,
216 Run: config,
217 })
218 if err != nil {
219 return nil, fmt.Errorf("unable to commit stage %s container: %v", from, err)
220 }
221 klog.V(4).Infof("Committed %s to %s as basis for image %q: %#v", prereq.Container.ID, image.ID, from, config)
222 // deleting this image will fail with an "image has dependent child images" error
223 // if it ends up being an ancestor of the final image, so don't bother returning
224 // errors from this specific removeImage() call
225 prereq.Deferred = append([]func() error{func() error { e.removeImage(image.ID); return nil }}, prereq.Deferred...)
226 prereq.Committed = image
227 }
228 klog.V(4).Infof("Using image %s based on previous stage %s as image", prereq.Committed.ID, from)
229 from = prereq.Committed.ID
230 }
231 stageFrom = from
232 }
233
234 if err := stageExecutor.Prepare(stage.Builder, stage.Node, stageFrom); err != nil {
235 return nil, fmt.Errorf("error: preparing stage using %q as base: %v", stageFrom, err)
236 }
237 if err := stageExecutor.Execute(stage.Builder, stage.Node); err != nil {
238 return nil, fmt.Errorf("error: running stage: %v", err)
239 }
240
241 // remember the outcome of the stage execution on the container config in case
242 // another stage needs to access incremental state
243 stageExecutor.Container.Config = stage.Builder.Config()
244 }
245 return stageExecutor, nil
246 }
247
248 // Build is a helper method to perform a Docker build against the
249 // provided Docker client. It will load the image if not specified,
250 // create a container if one does not already exist, and start a
251 // container if the Dockerfile contains RUN commands. It will cleanup
252 // any containers it creates directly, and set the e.Committed.ID field
253 // to the generated image.
254 func (e *ClientExecutor) Build(b *imagebuilder.Builder, node *parser.Node, from string) error {
255 defer e.Release()
256 if err := e.Prepare(b, node, from); err != nil {
257 return err
258 }
259 if err := e.Execute(b, node); err != nil {
260 return err
261 }
262 return e.Commit(b)
263 }
264
265 func (e *ClientExecutor) Prepare(b *imagebuilder.Builder, node *parser.Node, from string) error {
266 var err error
267
268 // identify the base image
269 if len(from) == 0 {
270 from, err = b.From(node)
271 if err != nil {
272 return err
273 }
274 if b.After != "" {
275 return fmt.Errorf("the --after flag in FROM is not supported by the dockerclient executor")
276 }
277 }
278
279 // load the image
280 if e.Image == nil {
281 if from == imagebuilder.NoBaseImageSpecifier {
282 if runtime.GOOS == "windows" {
283 return fmt.Errorf("building from scratch images is not supported")
284 }
285 from, err = e.CreateScratchImage()
286 if err != nil {
287 return fmt.Errorf("unable to create a scratch image for this build: %v", err)
288 }
289 e.Deferred = append([]func() error{func() error { return e.removeImage(from) }}, e.Deferred...)
290 }
291 klog.V(4).Infof("Retrieving image %q", from)
292 e.Image, err = e.LoadImageWithPlatform(from, b.Platform)
293 if err != nil {
294 return err
295 }
296 }
297
298 // update the builder with any information from the image, including ONBUILD
299 // statements
300 if err := b.FromImage(e.Image, node); err != nil {
301 return err
302 }
303
304 b.RunConfig.Image = from
305 if len(e.Name) > 0 {
306 e.LogFn("FROM %s as %s", from, e.Name)
307 } else {
308 e.LogFn("FROM %s", from)
309 }
310 klog.V(4).Infof("step: FROM %s as %s", from, e.Name)
311
312 b.Excludes = e.Excludes
313
314 var sharedMount string
315
316 defaultShell := b.RunConfig.Shell
317 if len(defaultShell) == 0 {
318 defaultShell = []string{"/bin/sh", "-c"}
319 }
320
321 // create a container to execute in, if necessary
322 mustStart := b.RequiresStart(node)
323 if e.Container == nil {
324 opts := docker.CreateContainerOptions{
325 Config: &docker.Config{
326 Image: from,
327 },
328 HostConfig: &docker.HostConfig{},
329 }
330 if e.HostConfig != nil {
331 opts.HostConfig = e.HostConfig
332 }
333 originalBinds := opts.HostConfig.Binds
334
335 if mustStart {
336 // Transient mounts only make sense on images that will be running processes
337 if len(e.TransientMounts) > 0 {
338 volumeName, err := randSeq(imageSafeCharacters, 24)
339 if err != nil {
340 return err
341 }
342 v, err := e.Client.CreateVolume(docker.CreateVolumeOptions{Name: volumeName})
343 if err != nil {
344 return fmt.Errorf("unable to create volume to mount secrets: %v", err)
345 }
346 e.Deferred = append([]func() error{func() error { return e.Client.RemoveVolume(volumeName) }}, e.Deferred...)
347 sharedMount = v.Mountpoint
348 opts.HostConfig.Binds = append(opts.HostConfig.Binds, volumeName+":"+e.ContainerTransientMount)
349 }
350
351 // TODO: windows support
352 if len(e.Command) > 0 {
353 opts.Config.Cmd = e.Command
354 opts.Config.Entrypoint = nil
355 } else {
356 // TODO; replace me with a better default command
357 opts.Config.Cmd = []string{"# (imagebuilder)\n/bin/sleep 86400"}
358 opts.Config.Entrypoint = append([]string{}, defaultShell...)
359 }
360 }
361
362 if len(opts.Config.Cmd) == 0 {
363 opts.Config.Entrypoint = append(append([]string{}, defaultShell...), "#(imagebuilder)")
364 }
365
366 // copy any source content into the temporary mount path
367 if mustStart && len(e.TransientMounts) > 0 {
368 if len(sharedMount) == 0 {
369 return fmt.Errorf("no mount point available for temporary mounts")
370 }
371 binds, err := e.PopulateTransientMounts(opts, e.TransientMounts, sharedMount)
372 if err != nil {
373 return err
374 }
375 opts.HostConfig.Binds = append(originalBinds, binds...)
376 }
377
378 klog.V(4).Infof("Creating container with %#v %#v", opts.Config, opts.HostConfig)
379 container, err := e.Client.CreateContainer(opts)
380 if err != nil {
381 return fmt.Errorf("unable to create build container: %v", err)
382 }
383 e.Container = container
384 e.Deferred = append([]func() error{func() error { return e.removeContainer(container.ID) }}, e.Deferred...)
385 }
386
387 // TODO: lazy start
388 if mustStart && !e.Container.State.Running {
389 if err := e.Client.StartContainer(e.Container.ID, nil); err != nil {
390 return fmt.Errorf("unable to start build container: %v", err)
391 }
392 e.Container.State.Running = true
393 // TODO: is this racy? may have to loop wait in the actual run step
394 }
395 return nil
396 }
397
398 // Execute performs all of the provided steps against the initialized container. May be
399 // invoked multiple times for a given container.
400 func (e *ClientExecutor) Execute(b *imagebuilder.Builder, node *parser.Node) error {
401 for i, child := range node.Children {
402 step := b.Step()
403 if err := step.Resolve(child); err != nil {
404 return err
405 }
406 klog.V(4).Infof("step: %s", step.Original)
407 if e.LogFn != nil {
408 // original may have unescaped %, so perform fmt escaping
409 e.LogFn(strings.Replace(step.Original, "%", "%%", -1))
410 }
411 noRunsRemaining := !b.RequiresStart(&parser.Node{Children: node.Children[i+1:]})
412
413 if err := b.Run(step, e, noRunsRemaining); err != nil {
414 return err
415 }
416 }
417
418 return nil
419 }
420
421 // Commit saves the completed build as an image with the provided tag. It will
422 // stop the container, commit the image, and then remove the container.
423 func (e *ClientExecutor) Commit(b *imagebuilder.Builder) error {
424 config := b.Config()
425
426 if e.Container.State.Running {
427 klog.V(4).Infof("Stopping container %s ...", e.Container.ID)
428 if err := e.Client.StopContainer(e.Container.ID, 0); err != nil {
429 return fmt.Errorf("unable to stop build container: %v", err)
430 }
431 e.Container.State.Running = false
432 // Starting the container may perform escaping of args, so to be consistent
433 // we also set that here
434 config.ArgsEscaped = true
435 }
436
437 var repository, tag string
438 if len(e.Tag) > 0 {
439 repository, tag = docker.ParseRepositoryTag(e.Tag)
440 klog.V(4).Infof("Committing built container %s as image %q: %#v", e.Container.ID, e.Tag, config)
441 if e.LogFn != nil {
442 e.LogFn("Committing changes to %s ...", e.Tag)
443 }
444 } else {
445 klog.V(4).Infof("Committing built container %s: %#v", e.Container.ID, config)
446 if e.LogFn != nil {
447 e.LogFn("Committing changes ...")
448 }
449 }
450
451 defer func() {
452 for _, err := range e.Release() {
453 e.LogFn("Unable to cleanup: %v", err)
454 }
455 }()
456
457 image, err := e.Client.CommitContainer(docker.CommitContainerOptions{
458 Author: b.Author,
459 Container: e.Container.ID,
460 Run: config,
461 Repository: repository,
462 Tag: tag,
463 })
464 if err != nil {
465 return fmt.Errorf("unable to commit build container: %v", err)
466 }
467
468 e.Committed = image
469 klog.V(4).Infof("Committed %s to %s", e.Container.ID, image.ID)
470
471 if len(e.Tag) > 0 {
472 for _, s := range e.AdditionalTags {
473 repository, tag := docker.ParseRepositoryTag(s)
474 err := e.Client.TagImage(image.ID, docker.TagImageOptions{
475 Repo: repository,
476 Tag: tag,
477 })
478 if err != nil {
479 e.Deferred = append([]func() error{func() error { return e.removeImage(image.ID) }}, e.Deferred...)
480 return fmt.Errorf("unable to tag %q: %v", s, err)
481 }
482 e.LogFn("Tagged as %s", s)
483 }
484 }
485
486 if e.LogFn != nil {
487 e.LogFn("Done")
488 }
489 return nil
490 }
491
492 func (e *ClientExecutor) PopulateTransientMounts(opts docker.CreateContainerOptions, transientMounts []Mount, sharedMount string) ([]string, error) {
493 container, err := e.Client.CreateContainer(opts)
494 if err != nil {
495 return nil, fmt.Errorf("unable to create transient container: %v", err)
496 }
497 defer e.removeContainer(container.ID)
498
499 var copies []imagebuilder.Copy
500 for i, mount := range transientMounts {
501 copies = append(copies, imagebuilder.Copy{
502 FromFS: true,
503 Src: []string{mount.SourcePath},
504 Dest: filepath.Join(e.ContainerTransientMount, strconv.Itoa(i)),
505 })
506 }
507 if err := e.CopyContainer(container, nil, copies...); err != nil {
508 return nil, fmt.Errorf("unable to copy transient context into container: %v", err)
509 }
510
511 // mount individual items temporarily
512 var binds []string
513 for i, mount := range e.TransientMounts {
514 binds = append(binds, fmt.Sprintf("%s:%s:%s", filepath.Join(sharedMount, strconv.Itoa(i)), mount.DestinationPath, "ro"))
515 }
516 return binds, nil
517 }
518
519 // Release deletes any items started by this executor.
520 func (e *ClientExecutor) Release() []error {
521 errs := e.Volumes.Release()
522 for _, fn := range e.Deferred {
523 if err := fn(); err != nil {
524 errs = append(errs, err)
525 }
526 }
527 e.Deferred = nil
528 return errs
529 }
530
531 // removeContainer removes the provided container ID
532 func (e *ClientExecutor) removeContainer(id string) error {
533 e.Client.StopContainer(id, 0)
534 err := e.Client.RemoveContainer(docker.RemoveContainerOptions{
535 ID: id,
536 RemoveVolumes: true,
537 Force: true,
538 })
539 if _, ok := err.(*docker.NoSuchContainer); err != nil && !ok {
540 return fmt.Errorf("unable to cleanup container %s: %v", id, err)
541 }
542 return nil
543 }
544
545 // removeImage removes the provided image ID
546 func (e *ClientExecutor) removeImage(id string) error {
547 if err := e.Client.RemoveImageExtended(id, docker.RemoveImageOptions{
548 Force: true,
549 }); err != nil {
550 return fmt.Errorf("unable to clean up image %s: %v", id, err)
551 }
552 return nil
553 }
554
555 // CreateScratchImage creates a new, zero byte layer that is identical to "scratch"
556 // except that the resulting image will have two layers.
557 func (e *ClientExecutor) CreateScratchImage() (string, error) {
558 random, err := randSeq(imageSafeCharacters, 24)
559 if err != nil {
560 return "", err
561 }
562 name := fmt.Sprintf("scratch%s", random)
563
564 buf := &bytes.Buffer{}
565 w := tar.NewWriter(buf)
566 w.Close()
567
568 return name, e.Client.ImportImage(docker.ImportImageOptions{
569 Repository: name,
570 Source: "-",
571 InputStream: buf,
572 })
573 }
574
575 // imageSafeCharacters are characters allowed to be part of a Docker image name.
576 const imageSafeCharacters = "abcdefghijklmnopqrstuvwxyz0123456789"
577
578 // randSeq returns a sequence of random characters drawn from source. It returns
579 // an error if cryptographic randomness is not available or source is more than 255
580 // characters.
581 func randSeq(source string, n int) (string, error) {
582 if len(source) > 255 {
583 return "", fmt.Errorf("source must be less than 256 bytes long")
584 }
585 random := make([]byte, n)
586 if _, err := io.ReadFull(rand.Reader, random); err != nil {
587 return "", err
588 }
589 for i := range random {
590 random[i] = source[random[i]%byte(len(source))]
591 }
592 return string(random), nil
593 }
594
595 // LoadImage checks the client for an image matching from. If not found,
596 // attempts to pull the image and then tries to inspect again.
597 func (e *ClientExecutor) LoadImage(from string) (*docker.Image, error) {
598 return e.LoadImageWithPlatform(from, "")
599 }
600
601 // LoadImage checks the client for an image matching from. If not found,
602 // attempts to pull the image with specified platform string.
603 func (e *ClientExecutor) LoadImageWithPlatform(from string, platform string) (*docker.Image, error) {
604 image, err := e.Client.InspectImage(from)
605 if err == nil {
606 return image, nil
607 }
608 if err != docker.ErrNoSuchImage {
609 return nil, err
610 }
611
612 if !e.AllowPull {
613 klog.V(4).Infof("image %s did not exist", from)
614 return nil, docker.ErrNoSuchImage
615 }
616
617 repository, tag := docker.ParseRepositoryTag(from)
618 if len(tag) == 0 {
619 tag = "latest"
620 }
621
622 klog.V(4).Infof("attempting to pull %s with auth from repository %s:%s", from, repository, tag)
623
624 // TODO: we may want to abstract looping over multiple credentials
625 auth, _ := e.AuthFn(repository)
626 if len(auth) == 0 {
627 auth = append(auth, dockerregistrytypes.AuthConfig{})
628 }
629
630 if e.LogFn != nil {
631 e.LogFn("Image %s was not found, pulling ...", from)
632 }
633
634 var lastErr error
635 outputProgress := func(s string) {
636 e.LogFn("%s", s)
637 }
638 for _, config := range auth {
639 // TODO: handle IDs?
640 var pullErr error
641 func() { // A scope for defer
642 pullWriter := imageprogress.NewPullWriter(outputProgress)
643 defer func() {
644 err := pullWriter.Close()
645 if pullErr == nil {
646 pullErr = err
647 }
648 }()
649
650 pullImageOptions := docker.PullImageOptions{
651 Repository: repository,
652 Tag: tag,
653 OutputStream: pullWriter,
654 Platform: platform,
655 RawJSONStream: true,
656 }
•657 if klog.V(5).Enabled() {
658 pullImageOptions.OutputStream = os.Stderr
659 pullImageOptions.RawJSONStream = false
660 }
661 authConfig := docker.AuthConfiguration{Username: config.Username, ServerAddress: config.ServerAddress, Password: config.Password}
662 pullErr = e.Client.PullImage(pullImageOptions, authConfig)
663 }()
664 if pullErr == nil {
665 break
666 }
667 lastErr = pullErr
668 continue
669 }
670 if lastErr != nil {
671 return nil, fmt.Errorf("unable to pull image (from: %s, tag: %s): %v", repository, tag, lastErr)
672 }
673
674 return e.Client.InspectImage(from)
675 }
676
677 func (e *ClientExecutor) Preserve(path string) error {
678 if e.Volumes == nil {
679 e.Volumes = NewContainerVolumeTracker()
680 }
681
682 if err := e.EnsureContainerPath(path); err != nil {
683 return err
684 }
685
686 e.Volumes.Add(path)
687 return nil
688 }
689
690 func (e *ClientExecutor) EnsureContainerPath(path string) error {
691 return e.createOrReplaceContainerPathWithOwner(path, 0, 0, nil)
692 }
693
694 func (e *ClientExecutor) EnsureContainerPathAs(path, user string, mode *os.FileMode) error {
695 uid, gid := 0, 0
696
697 u, g, err := e.getUser(user)
698 if err == nil {
699 uid = u
700 gid = g
701 }
702
703 return e.createOrReplaceContainerPathWithOwner(path, uid, gid, mode)
704 }
705
706 func (e *ClientExecutor) createOrReplaceContainerPathWithOwner(path string, uid, gid int, mode *os.FileMode) error {
707 if mode == nil {
708 m := os.FileMode(0755)
709 mode = &m
710 }
711 createPath := func(dest string) error {
712 var writerErr error
713 if !strings.HasSuffix(dest, "/") {
714 dest = dest + "/"
715 }
716 reader, writer := io.Pipe()
717 opts := docker.UploadToContainerOptions{
718 InputStream: reader,
719 Path: "/",
720 Context: context.TODO(),
721 }
722 go func() {
723 defer writer.Close()
724 tarball := tar.NewWriter(writer)
725 defer tarball.Close()
726 writerErr = tarball.WriteHeader(&tar.Header{
727 Name: dest,
728 Typeflag: tar.TypeDir,
729 Mode: int64(*mode),
730 Uid: uid,
731 Gid: gid,
732 })
733 }()
734 klog.V(4).Infof("Uploading empty archive to %q", dest)
735 err := e.Client.UploadToContainer(e.Container.ID, opts)
736 if err != nil {
737 return fmt.Errorf("unable to ensure existence of preserved path %s: %v", dest, err)
738 }
739 if writerErr != nil {
740 return fmt.Errorf("error generating tarball to ensure existence of preserved path %s: %v", dest, writerErr)
741 }
742 return nil
743 }
744 readPath := func(dest string) error {
745 if !strings.HasSuffix(dest, "/") {
746 dest = dest + "/"
747 }
748 err := e.Client.DownloadFromContainer(e.Container.ID, docker.DownloadFromContainerOptions{
749 Path: dest,
750 OutputStream: io.Discard,
751 })
752 return err
753 }
754 var pathsToCreate []string
755 pathToCheck := path
756 for {
757 if err := readPath(pathToCheck); err != nil {
758 pathsToCreate = append([]string{pathToCheck}, pathsToCreate...)
759 }
760 if filepath.Dir(pathToCheck) == pathToCheck {
761 break
762 }
763 pathToCheck = filepath.Dir(pathToCheck)
764 }
765 for _, path := range pathsToCreate {
766 if err := createPath(path); err != nil {
767 return fmt.Errorf("error creating container directory %s: %v", path, err)
768 }
769 }
770 return nil
771 }
772
773 func (e *ClientExecutor) UnrecognizedInstruction(step *imagebuilder.Step) error {
774 if e.IgnoreUnrecognizedInstructions {
775 e.LogFn("warning: Unknown instruction: %s", strings.ToUpper(step.Command))
776 return nil
777 }
778 return fmt.Errorf("Unknown instruction: %s", strings.ToUpper(step.Command))
779 }
780
781 // Run executes a single Run command against the current container using exec().
782 // Since exec does not allow ENV or WORKINGDIR to be set, we force the execution of
783 // the user command into a shell and perform those operations before. Since RUN
784 // requires /bin/sh, we can use both 'cd' and 'export'.
785 func (e *ClientExecutor) Run(run imagebuilder.Run, config docker.Config) error {
786 if len(run.Files) > 0 {
787 return fmt.Errorf("Heredoc syntax is not supported")
788 }
789 if len(run.Mounts) > 0 {
790 return fmt.Errorf("RUN --mount not supported")
791 }
792 if run.Network != "" {
793 return fmt.Errorf("RUN --network not supported")
794 }
795
796 args := make([]string, len(run.Args))
797 copy(args, run.Args)
798
799 defaultShell := config.Shell
800 if len(defaultShell) == 0 {
801 if runtime.GOOS == "windows" {
802 defaultShell = []string{"cmd", "/S", "/C"}
803 } else {
804 defaultShell = []string{"/bin/sh", "-c"}
805 }
806 }
807 if runtime.GOOS == "windows" {
808 if len(config.WorkingDir) > 0 {
809 args[0] = fmt.Sprintf("cd %s && %s", imagebuilder.BashQuote(config.WorkingDir), args[0])
810 }
811 // TODO: implement windows ENV
812 args = append(defaultShell, args...)
813 } else {
814 if run.Shell {
815 if len(config.WorkingDir) > 0 {
816 args[0] = fmt.Sprintf("cd %s && %s", imagebuilder.BashQuote(config.WorkingDir), args[0])
817 }
818 if len(config.Env) > 0 {
819 args[0] = imagebuilder.ExportEnv(config.Env) + args[0]
820 }
821 args = append(defaultShell, args...)
822 } else {
823 switch {
824 case len(config.WorkingDir) == 0 && len(config.Env) == 0:
825 // no change necessary
826 case len(args) > 0:
827 setup := "exec \"$@\""
828 if len(config.WorkingDir) > 0 {
829 setup = fmt.Sprintf("cd %s && %s", imagebuilder.BashQuote(config.WorkingDir), setup)
830 }
831 if len(config.Env) > 0 {
832 setup = imagebuilder.ExportEnv(config.Env) + setup
833 }
834 newArgs := make([]string, 0, len(args)+4)
835 newArgs = append(newArgs, defaultShell...)
836 newArgs = append(newArgs, setup, "")
837 newArgs = append(newArgs, args...)
838 args = newArgs
839 }
840 }
841 }
842
843 if e.StrictVolumeOwnership && !e.Volumes.Empty() {
844 return fmt.Errorf("a RUN command was executed after a VOLUME command, which may result in ownership information being lost")
845 }
846 if err := e.Volumes.Save(e.Container.ID, e.TempDir, e.Client); err != nil {
847 return err
848 }
849
850 config.Cmd = args
851 klog.V(4).Infof("Running %#v inside of %s as user %s", config.Cmd, e.Container.ID, config.User)
852 exec, err := e.Client.CreateExec(docker.CreateExecOptions{
853 Cmd: config.Cmd,
854 Container: e.Container.ID,
855 AttachStdout: true,
856 AttachStderr: true,
857 User: config.User,
858 })
859 if err != nil {
860 return err
861 }
862 if err := e.Client.StartExec(exec.ID, docker.StartExecOptions{
863 OutputStream: e.Out,
864 ErrorStream: e.ErrOut,
865 }); err != nil {
866 return err
867 }
868 status, err := e.Client.InspectExec(exec.ID)
869 if err != nil {
870 return err
871 }
872 if status.ExitCode != 0 {
873 klog.V(4).Infof("Failed command (code %d): %v", status.ExitCode, args)
874 return fmt.Errorf("running '%s' failed with exit code %d", strings.Join(run.Args, " "), status.ExitCode)
875 }
876
877 if err := e.Volumes.Restore(e.Container.ID, e.Client); err != nil {
878 return err
879 }
880
881 return nil
882 }
883
884 // Copy implements the executor copy function.
885 func (e *ClientExecutor) Copy(excludes []string, copies ...imagebuilder.Copy) error {
886 // copying content into a volume invalidates the archived state of any given directory
887 for _, copy := range copies {
888 if copy.Checksum != "" {
889 return fmt.Errorf("ADD --checksum not supported")
890 }
891 if copy.Link {
892 return fmt.Errorf("ADD or COPY --link not supported")
893 }
894 if copy.Parents {
895 return fmt.Errorf("COPY --parents not supported")
896 }
897 if copy.KeepGitDir {
898 return fmt.Errorf("ADD --keep-git-dir not supported")
899 }
900 if len(copy.Excludes) > 0 {
901 return fmt.Errorf("ADD or COPY --exclude not supported")
902 }
903 if len(copy.Files) > 0 {
904 return fmt.Errorf("Heredoc syntax is not supported")
905 }
906 e.Volumes.Invalidate(copy.Dest)
907 }
908
909 return e.CopyContainer(e.Container, excludes, copies...)
910 }
911
912 func (e *ClientExecutor) findMissingParents(container *docker.Container, dest string) (parents []string, err error) {
913 destParent := filepath.Clean(dest)
914 for filepath.Dir(destParent) != destParent {
915 exists, err := isContainerPathDirectory(e.Client, container.ID, destParent)
916 if err != nil {
917 return nil, err
918 }
919 if !exists {
920 parents = append(parents, destParent)
921 }
922 destParent = filepath.Dir(destParent)
923 }
924 return parents, nil
925 }
926
927 func (e *ClientExecutor) getUser(userspec string) (int, int, error) {
928 readFile := func(path string) ([]byte, error) {
929 var buffer, contents bytes.Buffer
930 if err := e.Client.DownloadFromContainer(e.Container.ID, docker.DownloadFromContainerOptions{
931 OutputStream: &buffer,
932 Path: path,
933 Context: context.TODO(),
934 }); err != nil {
935 return nil, err
936 }
937 tr := tar.NewReader(&buffer)
938 hdr, err := tr.Next()
939 if err != nil {
940 return nil, err
941 }
942 if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {
943 return nil, fmt.Errorf("expected %q to be a regular file, but it was of type %q", path, string(hdr.Typeflag))
944 }
945 if filepath.FromSlash(hdr.Name) != filepath.Base(path) {
946 return nil, fmt.Errorf("error reading contents of %q: got %q instead", path, hdr.Name)
947 }
948 n, err := io.Copy(&contents, tr)
949 if err != nil {
950 return nil, fmt.Errorf("error reading contents of %q: %v", path, err)
951 }
952 if n != hdr.Size {
953 return nil, fmt.Errorf("size mismatch reading contents of %q: %v", path, err)
954 }
955 hdr, err = tr.Next()
956 if err != nil && !errors.Is(err, io.EOF) {
957 return nil, fmt.Errorf("error reading archive of %q: %v", path, err)
958 }
959 if err == nil {
960 return nil, fmt.Errorf("got unexpected extra content while reading archive of %q: %v", path, err)
961 }
962 return contents.Bytes(), nil
963 }
964 parse := func(file []byte, matchField int, key string, numFields, readField int) (string, error) {
965 var value *string
966 scanner := bufio.NewScanner(bytes.NewReader(file))
967 for scanner.Scan() {
968 line := scanner.Text()
969 fields := strings.SplitN(line, ":", numFields)
970 if len(fields) != numFields {
971 return "", fmt.Errorf("error parsing line %q: incorrect number of fields", line)
972 }
973 if fields[matchField] != key {
974 continue
975 }
976 v := fields[readField]
977 value = &v
978 }
979 if err := scanner.Err(); err != nil {
980 return "", fmt.Errorf("error scanning file: %v", err)
981 }
982 if value == nil {
983 return "", os.ErrNotExist
984 }
985 return *value, nil
986 }
987
988 spec := strings.SplitN(userspec, ":", 2)
989 if len(spec) == 2 {
990 parsedUid, err := strconv.ParseUint(spec[0], 10, 32)
991 if err != nil {
992 // maybe it's a user name? look up the UID
993 passwdFile, err := readFile("/etc/passwd")
994 if err != nil {
995 return -1, -1, err
996 }
997 uid, err := parse(passwdFile, 0, spec[0], 7, 2)
998 if err != nil {
999 return -1, -1, fmt.Errorf("error reading UID value from passwd file for --chown=%s: %v", spec[0], err)
1000 }
1001 parsedUid, err = strconv.ParseUint(uid, 10, 32)
1002 if err != nil {
1003 return -1, -1, fmt.Errorf("error parsing UID value %q from passwd file for --chown=%s", uid, userspec)
1004 }
1005 }
1006 parsedGid, err := strconv.ParseUint(spec[1], 10, 32)
1007 if err != nil {
1008 // maybe it's a group name? look up the GID
1009 groupFile, err := readFile("/etc/group")
1010 if err != nil {
1011 return -1, -1, err
1012 }
1013 gid, err := parse(groupFile, 0, spec[1], 4, 2)
1014 if err != nil {
1015 return -1, -1, err
1016 }
1017 parsedGid, err = strconv.ParseUint(gid, 10, 32)
1018 if err != nil {
1019 return -1, -1, fmt.Errorf("error parsing GID value %q from group file for --chown=%s", gid, userspec)
1020 }
1021 }
1022 return int(parsedUid), int(parsedGid), nil
1023 }
1024
1025 var parsedUid, parsedGid uint64
1026 if id, err := strconv.ParseUint(spec[0], 10, 32); err == nil {
1027 // it's an ID. use it as both the UID and the GID
1028 parsedUid = id
1029 parsedGid = id
1030 } else {
1031 // it's a user name, we'll need to look up their UID and primary GID
1032 passwdFile, err := readFile("/etc/passwd")
1033 if err != nil {
1034 return -1, -1, err
1035 }
1036 // read the UID and primary GID
1037 uid, err := parse(passwdFile, 0, spec[0], 7, 2)
1038 if err != nil {
1039 return -1, -1, fmt.Errorf("error reading UID value from /etc/passwd for --chown=%s", userspec)
1040 }
1041 gid, err := parse(passwdFile, 0, spec[0], 7, 3)
1042 if err != nil {
1043 return -1, -1, fmt.Errorf("error reading GID value from /etc/passwd for --chown=%s", userspec)
1044 }
1045 if parsedUid, err = strconv.ParseUint(uid, 10, 32); err != nil {
1046 return -1, -1, fmt.Errorf("error parsing UID value %q from /etc/passwd for --chown=%s", uid, userspec)
1047 }
1048 if parsedGid, err = strconv.ParseUint(gid, 10, 32); err != nil {
1049 return -1, -1, fmt.Errorf("error parsing GID value %q from /etc/passwd for --chown=%s", gid, userspec)
1050 }
1051 }
1052 return int(parsedUid), int(parsedGid), nil
1053 }
1054
1055 // applyChmod rewrites h's permission bits per set, preserving the file-type
1056 // bits. It goes through h.FileInfo().Mode() so symbolic clauses see a correct
1057 // os.FileMode (ModeDir, and setuid/setgid/sticky in their flag positions),
1058 // then maps the result back onto the tar header's unix convention
1059 // (setuid/setgid/sticky at 0o4000/0o2000/0o1000). An absolute (numeric or
1060 // "=") mode replaces the permission and special bits entirely, matching
1061 // chmod(1).
1062 func applyChmod(h *tar.Header, set mode.Set) {
1063 fm := set.Apply(h.FileInfo().Mode())
1064 h.Mode = (h.Mode &^ 0o7777) | int64(fm.Perm())
1065 if fm&os.ModeSetuid != 0 {
1066 h.Mode |= 0o4000
1067 }
1068 if fm&os.ModeSetgid != 0 {
1069 h.Mode |= 0o2000
1070 }
1071 if fm&os.ModeSticky != 0 {
1072 h.Mode |= 0o1000
1073 }
1074 }
1075
1076 // CopyContainer copies the provided content into a destination container.
1077 func (e *ClientExecutor) CopyContainer(container *docker.Container, excludes []string, copies ...imagebuilder.Copy) error {
1078 chownUid, chownGid := -1, -1
1079 chown := func(h *tar.Header, r io.Reader) (data []byte, update bool, skip bool, err error) {
1080 if chownUid != -1 {
1081 h.Uid = chownUid
1082 }
1083 if chownGid != -1 {
1084 h.Gid = chownGid
1085 }
1086 if (h.Uid > 0x1fffff || h.Gid > 0x1fffff) && h.Format == tar.FormatUSTAR {
1087 h.Format = tar.FormatPAX
1088 }
1089 return nil, false, false, nil
1090 }
1091 for _, c := range copies {
1092 var chmod func(h *tar.Header, r io.Reader) (data []byte, update bool, skip bool, err error)
1093 if c.Chmod != "" {
1094 parsed, err := mode.Parse(c.Chmod)
1095 if err != nil {
1096 return fmt.Errorf("invalid chmod %q: %w", c.Chmod, err)
1097 }
1098 chmod = func(h *tar.Header, r io.Reader) (data []byte, update bool, skip bool, err error) {
1099 applyChmod(h, parsed)
1100 return nil, false, false, nil
1101 }
1102 }
1103 chownUid, chownGid = -1, -1
1104 if c.Chown != "" {
1105 var err error
1106 chownUid, chownGid, err = e.getUser(c.Chown)
1107 if err != nil {
1108 return err
1109 }
1110 }
1111 // TODO: reuse source
1112 for _, src := range c.Src {
1113 if src == "" {
1114 src = "*"
1115 }
1116 assumeDstIsDirectory := len(c.Src) > 1
1117 repeatThisSrc:
1118 klog.V(4).Infof("Archiving %s download=%t fromFS=%t from=%s", src, c.Download, c.FromFS, c.From)
1119 var r io.Reader
1120 var closer io.Closer
1121 var err error
1122 if len(c.From) > 0 {
1123 if !assumeDstIsDirectory {
1124 var err error
1125 if assumeDstIsDirectory, err = e.isContainerGlobMultiple(e.Client, c.From, src); err != nil {
1126 return err
1127 }
1128 }
1129 r, closer, err = e.archiveFromContainer(c.From, src, c.Dest, assumeDstIsDirectory)
1130 } else {
1131 r, closer, err = e.Archive(c.FromFS, src, c.Dest, c.Download, excludes)
1132 }
1133 if err != nil {
1134 return err
1135 }
1136 asOwner := ""
1137 if c.Chown != "" {
1138 asOwner = fmt.Sprintf(" as %d:%d", chownUid, chownGid)
1139 // the daemon would implicitly create missing
1140 // directories with the wrong ownership, so
1141 // check for any that don't exist and create
1142 // them ourselves
1143 missingParents, err := e.findMissingParents(container, c.Dest)
1144 if err != nil {
1145 return err
1146 }
1147 if len(missingParents) > 0 {
1148 sort.Strings(missingParents)
1149 klog.V(5).Infof("Uploading directories %v to %s%s", missingParents, container.ID, asOwner)
1150 for _, missingParent := range missingParents {
1151 if err := e.createOrReplaceContainerPathWithOwner(missingParent, chownUid, chownGid, nil); err != nil {
1152 return err
1153 }
1154 }
1155 }
1156 filtered, err := transformArchive(r, false, chown)
1157 if err != nil {
1158 return err
1159 }
1160 r = filtered
1161 }
1162 if c.Chmod != "" {
1163 filtered, err := transformArchive(r, false, chmod)
1164 if err != nil {
1165 return err
1166 }
1167 r = filtered
1168 }
1169 klog.V(5).Infof("Uploading to %s%s at %s", container.ID, asOwner, c.Dest)
•1170 if klog.V(6).Enabled() {
1171 logArchiveOutput(r, "Archive file for %s")
1172 }
1173 // add a workaround allow us to notice if a
1174 // dstNeedsToBeDirectoryError was returned while
1175 // attempting to read the data we're uploading,
1176 // indicating that we thought the content would be just
1177 // one item, but it actually isn't
1178 reader := &readErrorWrapper{Reader: r}
1179 r = reader
1180 err = e.Client.UploadToContainer(container.ID, docker.UploadToContainerOptions{
1181 InputStream: r,
1182 Path: "/",
1183 })
1184 if err := closer.Close(); err != nil {
1185 klog.Errorf("Error while closing stream container copy stream %s: %v", container.ID, err)
1186 }
1187 if err != nil {
1188 if errors.Is(reader.err, dstNeedsToBeDirectoryError) && !assumeDstIsDirectory {
1189 assumeDstIsDirectory = true
1190 goto repeatThisSrc
1191 }
1192 if apiErr, ok := err.(*docker.Error); ok && apiErr.Status == 404 {
1193 klog.V(4).Infof("path %s did not exist in container %s: %v", src, container.ID, err)
1194 }
1195 return err
1196 }
1197 }
1198 }
1199 return nil
1200 }
1201
1202 type readErrorWrapper struct {
1203 io.Reader
1204 err error
1205 }
1206
1207 func (r *readErrorWrapper) Read(p []byte) (n int, err error) {
1208 n, r.err = r.Reader.Read(p)
1209 return n, r.err
1210 }
1211
1212 type closers []func() error
1213
1214 func (c closers) Close() error {
1215 var lastErr error
1216 for _, fn := range c {
1217 if err := fn(); err != nil {
1218 lastErr = err
1219 }
1220 }
1221 return lastErr
1222 }
1223
1224 func (e *ClientExecutor) archiveFromContainer(from string, src, dst string, multipleSources bool) (io.Reader, io.Closer, error) {
1225 var containerID string
1226 if other, ok := e.Named[from]; ok {
1227 if other.Container == nil {
1228 return nil, nil, fmt.Errorf("the stage %q has not been built yet", from)
1229 }
1230 klog.V(5).Infof("Using container %s as input for archive request", other.Container.ID)
1231 containerID = other.Container.ID
1232 } else {
1233 klog.V(5).Infof("Creating a container temporarily for image input from %q in %s", from, src)
1234 _, err := e.LoadImage(from)
1235 if err != nil {
1236 return nil, nil, err
1237 }
1238 c, err := e.Client.CreateContainer(docker.CreateContainerOptions{
1239 Config: &docker.Config{
1240 Image: from,
1241 },
1242 })
1243 if err != nil {
1244 return nil, nil, err
1245 }
1246 containerID = c.ID
1247 e.Deferred = append([]func() error{func() error { return e.removeContainer(containerID) }}, e.Deferred...)
1248 }
1249
1250 check := newDirectoryCheck(e.Client, e.Container.ID)
1251 pr, pw := io.Pipe()
1252 var archiveRoot string
1253 fetch := func(pw *io.PipeWriter) {
1254 klog.V(6).Infof("Download from container %s at path %s", containerID, archiveRoot)
1255 err := e.Client.DownloadFromContainer(containerID, docker.DownloadFromContainerOptions{
1256 OutputStream: pw,
1257 Path: archiveRoot,
1258 })
1259 pw.CloseWithError(err)
1260 }
1261 ar, archiveRoot, err := archiveFromContainer(pr, src, dst, nil, check, fetch, multipleSources)
1262 if err != nil {
1263 pr.Close()
1264 pw.Close()
1265 return nil, nil, err
1266 }
1267 closer := newCloser(func() error {
1268 err2 := pr.Close()
1269 err3 := ar.Close()
1270 if err3 != nil {
1271 return err3
1272 }
1273 return err2
1274 })
1275 go fetch(pw)
1276 return &readCloser{Reader: ar, Closer: closer}, pr, nil
1277 }
1278
1279 func (e *ClientExecutor) isContainerGlobMultiple(client *docker.Client, from, glob string) (bool, error) {
1280 reader, closer, err := e.archiveFromContainer(from, glob, "/ignored", true)
1281 if err != nil {
1282 return false, nil
1283 }
1284
1285 defer closer.Close()
1286 tr := tar.NewReader(reader)
1287
1288 h, err := tr.Next()
1289 if err != nil {
1290 if err == io.EOF {
1291 err = nil
1292 } else {
1293 if apiErr, ok := err.(*docker.Error); ok && apiErr.Status == 404 {
1294 klog.V(4).Infof("path %s did not exist in container %s: %v", glob, e.Container.ID, err)
1295 err = nil
1296 }
1297 }
1298 return false, err
1299 }
1300
1301 klog.V(4).Infof("Retrieved first header from %s using glob %s: %#v", from, glob, h)
1302
1303 h, err = tr.Next()
1304 if err != nil {
1305 if err == io.EOF {
1306 err = nil
1307 }
1308 return false, err
1309 }
1310
1311 klog.V(4).Infof("Retrieved second header from %s using glob %s: %#v", from, glob, h)
1312
1313 // take the remainder of the input and discard it
1314 go func() {
1315 n, err := io.Copy(io.Discard, reader)
1316 if n > 0 || err != nil {
1317 klog.V(6).Infof("Discarded %d bytes from end of from glob check, and got error: %v", n, err)
1318 }
1319 }()
1320
1321 return true, nil
1322 }
1323
1324 func (e *ClientExecutor) Archive(fromFS bool, src, dst string, allowDownload bool, excludes []string) (io.Reader, io.Closer, error) {
1325 var check DirectoryCheck
1326 if e.Container != nil {
1327 check = newDirectoryCheck(e.Client, e.Container.ID)
1328 }
1329 if isURL(src) {
1330 if !allowDownload {
1331 return nil, nil, fmt.Errorf("source can't be a URL")
1332 }
1333 klog.V(5).Infof("Archiving %s -> %s from URL", src, dst)
1334 return archiveFromURL(src, dst, e.TempDir, check)
1335 }
1336 // the input is from the filesystem, use the source as the input
1337 if fromFS {
1338 klog.V(5).Infof("Archiving %s %s -> %s from a filesystem location", src, ".", dst)
1339 return archiveFromDisk(src, ".", dst, allowDownload, excludes, check)
1340 }
1341 // if the context is in archive form, read from it without decompressing
1342 if len(e.ContextArchive) > 0 {
1343 klog.V(5).Infof("Archiving %s %s -> %s from context archive", e.ContextArchive, src, dst)
1344 return archiveFromFile(e.ContextArchive, src, dst, excludes, check)
1345 }
1346 // if the context is a directory, we only allow relative includes
1347 klog.V(5).Infof("Archiving %q %q -> %q from disk", e.Directory, src, dst)
1348 return archiveFromDisk(e.Directory, src, dst, allowDownload, excludes, check)
1349 }
1350
1351 // ContainerVolumeTracker manages tracking archives of specific paths inside a container.
1352 type ContainerVolumeTracker struct {
1353 paths map[string]string
1354 errs []error
1355 }
1356
1357 func NewContainerVolumeTracker() *ContainerVolumeTracker {
1358 return &ContainerVolumeTracker{
1359 paths: make(map[string]string),
1360 }
1361 }
1362
1363 // Empty returns true if the tracker is not watching any paths
1364 func (t *ContainerVolumeTracker) Empty() bool {
1365 return t == nil || len(t.paths) == 0
1366 }
1367
1368 // Add tracks path unless it already is being tracked.
1369 func (t *ContainerVolumeTracker) Add(path string) {
1370 if _, ok := t.paths[path]; !ok {
1371 t.paths[path] = ""
1372 }
1373 }
1374
1375 // Release removes any stored snapshots
1376 func (t *ContainerVolumeTracker) Release() []error {
1377 if t == nil {
1378 return nil
1379 }
1380 for path := range t.paths {
1381 t.ReleasePath(path)
1382 }
1383 return t.errs
1384 }
1385
1386 func (t *ContainerVolumeTracker) ReleasePath(path string) {
1387 if t == nil {
1388 return
1389 }
1390 if archivePath, ok := t.paths[path]; ok && len(archivePath) > 0 {
1391 err := os.Remove(archivePath)
1392 if err != nil && !os.IsNotExist(err) {
1393 t.errs = append(t.errs, err)
1394 }
1395 klog.V(5).Infof("Releasing path %s (%v)", path, err)
1396 t.paths[path] = ""
1397 }
1398 }
1399
1400 func (t *ContainerVolumeTracker) Invalidate(path string) {
1401 if t == nil {
1402 return
1403 }
1404 set := imagebuilder.VolumeSet{}
1405 set.Add(path)
1406 for path := range t.paths {
1407 if set.Covers(path) {
1408 t.ReleasePath(path)
1409 }
1410 }
1411 }
1412
1413 // Save ensures that all paths tracked underneath this container are archived or
1414 // returns an error.
1415 func (t *ContainerVolumeTracker) Save(containerID, tempDir string, client *docker.Client) error {
1416 if t == nil {
1417 return nil
1418 }
1419 set := imagebuilder.VolumeSet{}
1420 for dest := range t.paths {
1421 set.Add(dest)
1422 }
1423 // remove archive paths that are covered by other paths
1424 for dest := range t.paths {
1425 if !set.Has(dest) {
1426 t.ReleasePath(dest)
1427 delete(t.paths, dest)
1428 }
1429 }
1430 for dest, archivePath := range t.paths {
1431 if len(archivePath) > 0 {
1432 continue
1433 }
1434 archivePath, err := snapshotPath(dest, containerID, tempDir, client)
1435 if err != nil {
1436 return err
1437 }
1438 t.paths[dest] = archivePath
1439 }
1440 return nil
1441 }
1442
1443 // filterTarPipe transforms a tar file as it is streamed, calling fn on each header in the file.
1444 // If fn returns false, the file is skipped. If an error occurs it is returned.
1445 func filterTarPipe(w *tar.Writer, r *tar.Reader, fn func(*tar.Header) bool) error {
1446 for {
1447 h, err := r.Next()
1448 if err != nil {
1449 return err
1450 }
1451 if fn(h) {
1452 if err := w.WriteHeader(h); err != nil {
1453 return err
1454 }
1455 if _, err := io.Copy(w, r); err != nil {
1456 return err
1457 }
1458 } else {
1459 if _, err := io.Copy(io.Discard, r); err != nil {
1460 return err
1461 }
1462 }
1463 }
1464 }
1465
1466 // snapshotPath preserves the contents of path in container containerID as a temporary
1467 // archive, returning either an error or the path of the archived file.
1468 func snapshotPath(path, containerID, tempDir string, client *docker.Client) (string, error) {
1469 f, err := os.CreateTemp(tempDir, "archived-path")
1470 if err != nil {
1471 return "", err
1472 }
1473 klog.V(4).Infof("Snapshot %s for later use under %s", path, f.Name())
1474
1475 r, w := io.Pipe()
1476 tr := tar.NewReader(r)
1477 tw := tar.NewWriter(f)
1478 go func() {
1479 err := filterTarPipe(tw, tr, func(h *tar.Header) bool {
1480 if i := strings.Index(h.Name, "/"); i != -1 {
1481 h.Name = h.Name[i+1:]
1482 }
1483 return len(h.Name) > 0
1484 })
1485 if err == nil || errors.Is(err, io.EOF) {
1486 tw.Flush()
1487 w.Close()
1488 klog.V(5).Infof("Snapshot rewritten from %s", path)
1489 return
1490 }
1491 klog.V(5).Infof("Snapshot of %s failed: %v", path, err)
1492 w.CloseWithError(err)
1493 }()
1494
1495 if !strings.HasSuffix(path, "/") {
1496 path += "/"
1497 }
1498 err = client.DownloadFromContainer(containerID, docker.DownloadFromContainerOptions{
1499 Path: path,
1500 OutputStream: w,
1501 })
1502 f.Close()
1503 if err != nil {
1504 os.Remove(f.Name())
1505 return "", err
1506 }
1507 return f.Name(), nil
1508 }
1509
1510 // Restore ensures the paths managed by t exactly match the container. This requires running
1511 // exec as a user that can delete contents from the container. It will return an error if
1512 // any client operation fails.
1513 func (t *ContainerVolumeTracker) Restore(containerID string, client *docker.Client) error {
1514 if t == nil {
1515 return nil
1516 }
1517 for dest, archivePath := range t.paths {
1518 if len(archivePath) == 0 {
1519 return fmt.Errorf("path %s does not have an archive and cannot be restored", dest)
1520 }
1521 klog.V(4).Infof("Restoring contents of %s from %s", dest, archivePath)
1522 if !strings.HasSuffix(dest, "/") {
1523 dest = dest + "/"
1524 }
1525 exec, err := client.CreateExec(docker.CreateExecOptions{
1526 Container: containerID,
1527 Cmd: []string{"/bin/sh", "-c", "rm -rf $@", "", dest + "*"},
1528 User: "0",
1529 })
1530 if err != nil {
1531 return fmt.Errorf("unable to setup clearing preserved path %s: %v", dest, err)
1532 }
1533 if err := client.StartExec(exec.ID, docker.StartExecOptions{}); err != nil {
1534 return fmt.Errorf("unable to clear preserved path %s: %v", dest, err)
1535 }
1536 var status *docker.ExecInspect
1537 for status == nil {
1538 status, err = client.InspectExec(exec.ID)
1539 if err != nil {
1540 break
1541 }
1542 if !status.Running {
1543 break
1544 }
1545 status = nil
1546 }
1547 if err != nil {
1548 return fmt.Errorf("clearing preserved path %s did not succeed: %v", dest, err)
1549 }
1550 if status.ExitCode != 0 {
1551 return fmt.Errorf("clearing preserved path %s failed with exit code %d", dest, status.ExitCode)
1552 }
1553 err = func() error {
1554 f, err := os.Open(archivePath)
1555 if err != nil {
1556 return fmt.Errorf("unable to open archive %s for preserved path %s: %v", archivePath, dest, err)
1557 }
1558 defer f.Close()
1559 if err := client.UploadToContainer(containerID, docker.UploadToContainerOptions{
1560 InputStream: f,
1561 Path: dest,
1562 }); err != nil {
1563 return fmt.Errorf("unable to upload preserved contents from %s to %s: %v", archivePath, dest, err)
1564 }
1565 return nil
1566 }()
1567 if err != nil {
1568 return err
1569 }
1570 }
1571 return nil
1572 }