-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathclient.go
1547 lines (1424 loc) · 45.8 KB
/
client.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
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dockerclient
import (
"archive/tar"
"bufio"
"bytes"
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
dockerregistrytypes "github.com/docker/docker/api/types/registry"
docker "github.com/fsouza/go-dockerclient"
"k8s.io/klog"
"github.com/openshift/imagebuilder"
"github.com/openshift/imagebuilder/dockerfile/parser"
"github.com/openshift/imagebuilder/imageprogress"
)
// NewClientFromEnv is exposed to simplify getting a client when vendoring this library.
func NewClientFromEnv() (*docker.Client, error) {
return docker.NewClientFromEnv()
}
// Mount represents a binding between the current system and the destination client
type Mount struct {
SourcePath string
DestinationPath string
}
// ClientExecutor can run Docker builds from a Docker client.
type ClientExecutor struct {
// Name is an optional name for this executor.
Name string
// Named is a map of other named executors.
Named map[string]*ClientExecutor
// TempDir is the temporary directory to use for storing file
// contents. If unset, the default temporary directory for the
// system will be used.
TempDir string
// Client is a client to a Docker daemon.
Client *docker.Client
// Directory is the context directory to build from, will use
// the current working directory if not set. Ignored if
// ContextArchive is set.
Directory string
// A compressed or uncompressed tar archive that should be used
// as the build context.
ContextArchive string
// Excludes are a list of file patterns that should be excluded
// from the context. Will be set to the contents of the
// .dockerignore file if nil.
Excludes []string
// Tag is an optional value to tag the resulting built image.
Tag string
// Additional tags is an optional array of other tags to apply
// to the image.
AdditionalTags []string
// AllowPull when set will pull images that are not present on
// the daemon.
AllowPull bool
// IgnoreUnrecognizedInstructions, if true, allows instructions
// that are not yet supported to be ignored (will be printed)
IgnoreUnrecognizedInstructions bool
// StrictVolumeOwnership if true will fail the build if a RUN
// command follows a VOLUME command, since this client cannot
// guarantee that the restored contents of the VOLUME directory
// will have the right permissions.
StrictVolumeOwnership bool
// TransientMounts are a set of mounts from outside the build
// to the inside that will not be part of the final image. Any
// content created inside the mount's destinationPath will be
// omitted from the final image.
TransientMounts []Mount
// The path within the container to perform the transient mount.
ContainerTransientMount string
// The streams used for canonical output.
Out, ErrOut io.Writer
// Container is optional and can be set to a container to use as
// the execution environment for a build.
Container *docker.Container
// Command, if set, will be used as the entrypoint for the new
// container. This is ignored if Container is set.
Command []string
// Image is optional and may be set to control which image is used
// as a base for this build. Otherwise the FROM value from the
// Dockerfile is read (will be pulled if not locally present).
Image *docker.Image
// Committed is optional and is used to track a temporary image, if one
// was created, that was based on the container as its stage ended.
Committed *docker.Image
// AuthFn will handle authenticating any docker pulls if Image
// is set to nil.
AuthFn func(name string) ([]dockerregistrytypes.AuthConfig, bool)
// HostConfig is used to start the container (if necessary).
HostConfig *docker.HostConfig
// LogFn is an optional command to log information to the end user
LogFn func(format string, args ...interface{})
// Deferred is a list of operations that must be cleaned up at
// the end of execution. Use Release() to invoke all of these.
Deferred []func() error
// Volumes handles saving and restoring volumes after RUN
// commands are executed.
Volumes *ContainerVolumeTracker
}
// NoAuthFn can be used for AuthFn when no authentication is required in Docker.
func NoAuthFn(string) ([]dockerregistrytypes.AuthConfig, bool) {
return nil, false
}
// NewClientExecutor creates a client executor.
func NewClientExecutor(client *docker.Client) *ClientExecutor {
return &ClientExecutor{
Client: client,
LogFn: func(string, ...interface{}) {},
ContainerTransientMount: "/.imagebuilder-transient-mount",
}
}
// DefaultExcludes reads the default list of excluded file patterns from the
// context directory's .containerignore file if it exists, or from the context
// directory's .dockerignore file, if it exists.
func (e *ClientExecutor) DefaultExcludes() error {
var err error
e.Excludes, err = imagebuilder.ParseDockerignore(e.Directory)
return err
}
// WithName creates a new child executor that will be used whenever a COPY statement
// uses --from=NAME or --from=POSITION.
func (e *ClientExecutor) WithName(name string, position int) *ClientExecutor {
if e.Named == nil {
e.Named = make(map[string]*ClientExecutor)
}
e.Deferred = append([]func() error{func() error {
stage, ok := e.Named[strconv.Itoa(position)]
if !ok {
return fmt.Errorf("error finding stage %d", position)
}
errs := stage.Release()
if len(errs) > 0 {
return fmt.Errorf("%v", errs)
}
return nil
}}, e.Deferred...)
copied := *e
copied.Name = name
copied.Container = nil
copied.Deferred = nil
copied.Image = nil
copied.Volumes = nil
copied.Committed = nil
child := &copied
e.Named[name] = child
e.Named[strconv.Itoa(position)] = child
return child
}
// Stages executes all of the provided stages, starting from the base image. It returns the executor of the last stage
// or an error if a stage fails.
func (e *ClientExecutor) Stages(b *imagebuilder.Builder, stages imagebuilder.Stages, from string) (*ClientExecutor, error) {
var stageExecutor *ClientExecutor
for i, stage := range stages {
stageExecutor = e.WithName(stage.Name, stage.Position)
var stageFrom string
if i == 0 {
stageFrom = from
} else {
from, err := b.From(stage.Node)
if err != nil {
return nil, fmt.Errorf("error: Determining base image: %v", err)
}
if prereq := e.Named[from]; prereq != nil {
b, ok := stages.ByName(from)
if !ok {
return nil, fmt.Errorf("error: Unable to find stage %s builder", from)
}
if prereq.Committed == nil {
config := b.Builder.Config()
if prereq.Container.State.Running {
klog.V(4).Infof("Stopping container %s ...", prereq.Container.ID)
if err := e.Client.StopContainer(prereq.Container.ID, 0); err != nil {
return nil, fmt.Errorf("unable to stop build container: %v", err)
}
prereq.Container.State.Running = false
// Starting the container may perform escaping of args, so to be consistent
// we also set that here
config.ArgsEscaped = true
}
image, err := e.Client.CommitContainer(docker.CommitContainerOptions{
Container: prereq.Container.ID,
Run: config,
})
if err != nil {
return nil, fmt.Errorf("unable to commit stage %s container: %v", from, err)
}
klog.V(4).Infof("Committed %s to %s as basis for image %q: %#v", prereq.Container.ID, image.ID, from, config)
// deleting this image will fail with an "image has dependent child images" error
// if it ends up being an ancestor of the final image, so don't bother returning
// errors from this specific removeImage() call
prereq.Deferred = append([]func() error{func() error { e.removeImage(image.ID); return nil }}, prereq.Deferred...)
prereq.Committed = image
}
klog.V(4).Infof("Using image %s based on previous stage %s as image", prereq.Committed.ID, from)
from = prereq.Committed.ID
}
stageFrom = from
}
if err := stageExecutor.Prepare(stage.Builder, stage.Node, stageFrom); err != nil {
return nil, fmt.Errorf("error: preparing stage using %q as base: %v", stageFrom, err)
}
if err := stageExecutor.Execute(stage.Builder, stage.Node); err != nil {
return nil, fmt.Errorf("error: running stage: %v", err)
}
// remember the outcome of the stage execution on the container config in case
// another stage needs to access incremental state
stageExecutor.Container.Config = stage.Builder.Config()
}
return stageExecutor, nil
}
// Build is a helper method to perform a Docker build against the
// provided Docker client. It will load the image if not specified,
// create a container if one does not already exist, and start a
// container if the Dockerfile contains RUN commands. It will cleanup
// any containers it creates directly, and set the e.Committed.ID field
// to the generated image.
func (e *ClientExecutor) Build(b *imagebuilder.Builder, node *parser.Node, from string) error {
defer e.Release()
if err := e.Prepare(b, node, from); err != nil {
return err
}
if err := e.Execute(b, node); err != nil {
return err
}
return e.Commit(b)
}
func (e *ClientExecutor) Prepare(b *imagebuilder.Builder, node *parser.Node, from string) error {
var err error
// identify the base image
if len(from) == 0 {
from, err = b.From(node)
if err != nil {
return err
}
}
// load the image
if e.Image == nil {
if from == imagebuilder.NoBaseImageSpecifier {
if runtime.GOOS == "windows" {
return fmt.Errorf("building from scratch images is not supported")
}
from, err = e.CreateScratchImage()
if err != nil {
return fmt.Errorf("unable to create a scratch image for this build: %v", err)
}
e.Deferred = append([]func() error{func() error { return e.removeImage(from) }}, e.Deferred...)
}
klog.V(4).Infof("Retrieving image %q", from)
e.Image, err = e.LoadImageWithPlatform(from, b.Platform)
if err != nil {
return err
}
}
// update the builder with any information from the image, including ONBUILD
// statements
if err := b.FromImage(e.Image, node); err != nil {
return err
}
b.RunConfig.Image = from
if len(e.Name) > 0 {
e.LogFn("FROM %s as %s", from, e.Name)
} else {
e.LogFn("FROM %s", from)
}
klog.V(4).Infof("step: FROM %s as %s", from, e.Name)
b.Excludes = e.Excludes
var sharedMount string
defaultShell := b.RunConfig.Shell
if len(defaultShell) == 0 {
defaultShell = []string{"/bin/sh", "-c"}
}
// create a container to execute in, if necessary
mustStart := b.RequiresStart(node)
if e.Container == nil {
opts := docker.CreateContainerOptions{
Config: &docker.Config{
Image: from,
},
HostConfig: &docker.HostConfig{},
}
if e.HostConfig != nil {
opts.HostConfig = e.HostConfig
}
originalBinds := opts.HostConfig.Binds
if mustStart {
// Transient mounts only make sense on images that will be running processes
if len(e.TransientMounts) > 0 {
volumeName, err := randSeq(imageSafeCharacters, 24)
if err != nil {
return err
}
v, err := e.Client.CreateVolume(docker.CreateVolumeOptions{Name: volumeName})
if err != nil {
return fmt.Errorf("unable to create volume to mount secrets: %v", err)
}
e.Deferred = append([]func() error{func() error { return e.Client.RemoveVolume(volumeName) }}, e.Deferred...)
sharedMount = v.Mountpoint
opts.HostConfig.Binds = append(opts.HostConfig.Binds, volumeName+":"+e.ContainerTransientMount)
}
// TODO: windows support
if len(e.Command) > 0 {
opts.Config.Cmd = e.Command
opts.Config.Entrypoint = nil
} else {
// TODO; replace me with a better default command
opts.Config.Cmd = []string{"# (imagebuilder)\n/bin/sleep 86400"}
opts.Config.Entrypoint = append([]string{}, defaultShell...)
}
}
if len(opts.Config.Cmd) == 0 {
opts.Config.Entrypoint = append(append([]string{}, defaultShell...), "#(imagebuilder)")
}
// copy any source content into the temporary mount path
if mustStart && len(e.TransientMounts) > 0 {
if len(sharedMount) == 0 {
return fmt.Errorf("no mount point available for temporary mounts")
}
binds, err := e.PopulateTransientMounts(opts, e.TransientMounts, sharedMount)
if err != nil {
return err
}
opts.HostConfig.Binds = append(originalBinds, binds...)
}
klog.V(4).Infof("Creating container with %#v %#v", opts.Config, opts.HostConfig)
container, err := e.Client.CreateContainer(opts)
if err != nil {
return fmt.Errorf("unable to create build container: %v", err)
}
e.Container = container
e.Deferred = append([]func() error{func() error { return e.removeContainer(container.ID) }}, e.Deferred...)
}
// TODO: lazy start
if mustStart && !e.Container.State.Running {
if err := e.Client.StartContainer(e.Container.ID, nil); err != nil {
return fmt.Errorf("unable to start build container: %v", err)
}
e.Container.State.Running = true
// TODO: is this racy? may have to loop wait in the actual run step
}
return nil
}
// Execute performs all of the provided steps against the initialized container. May be
// invoked multiple times for a given container.
func (e *ClientExecutor) Execute(b *imagebuilder.Builder, node *parser.Node) error {
for i, child := range node.Children {
step := b.Step()
if err := step.Resolve(child); err != nil {
return err
}
klog.V(4).Infof("step: %s", step.Original)
if e.LogFn != nil {
// original may have unescaped %, so perform fmt escaping
e.LogFn(strings.Replace(step.Original, "%", "%%", -1))
}
noRunsRemaining := !b.RequiresStart(&parser.Node{Children: node.Children[i+1:]})
if err := b.Run(step, e, noRunsRemaining); err != nil {
return err
}
}
return nil
}
// Commit saves the completed build as an image with the provided tag. It will
// stop the container, commit the image, and then remove the container.
func (e *ClientExecutor) Commit(b *imagebuilder.Builder) error {
config := b.Config()
if e.Container.State.Running {
klog.V(4).Infof("Stopping container %s ...", e.Container.ID)
if err := e.Client.StopContainer(e.Container.ID, 0); err != nil {
return fmt.Errorf("unable to stop build container: %v", err)
}
e.Container.State.Running = false
// Starting the container may perform escaping of args, so to be consistent
// we also set that here
config.ArgsEscaped = true
}
var repository, tag string
if len(e.Tag) > 0 {
repository, tag = docker.ParseRepositoryTag(e.Tag)
klog.V(4).Infof("Committing built container %s as image %q: %#v", e.Container.ID, e.Tag, config)
if e.LogFn != nil {
e.LogFn("Committing changes to %s ...", e.Tag)
}
} else {
klog.V(4).Infof("Committing built container %s: %#v", e.Container.ID, config)
if e.LogFn != nil {
e.LogFn("Committing changes ...")
}
}
defer func() {
for _, err := range e.Release() {
e.LogFn("Unable to cleanup: %v", err)
}
}()
image, err := e.Client.CommitContainer(docker.CommitContainerOptions{
Author: b.Author,
Container: e.Container.ID,
Run: config,
Repository: repository,
Tag: tag,
})
if err != nil {
return fmt.Errorf("unable to commit build container: %v", err)
}
e.Committed = image
klog.V(4).Infof("Committed %s to %s", e.Container.ID, image.ID)
if len(e.Tag) > 0 {
for _, s := range e.AdditionalTags {
repository, tag := docker.ParseRepositoryTag(s)
err := e.Client.TagImage(image.ID, docker.TagImageOptions{
Repo: repository,
Tag: tag,
})
if err != nil {
e.Deferred = append([]func() error{func() error { return e.removeImage(image.ID) }}, e.Deferred...)
return fmt.Errorf("unable to tag %q: %v", s, err)
}
e.LogFn("Tagged as %s", s)
}
}
if e.LogFn != nil {
e.LogFn("Done")
}
return nil
}
func (e *ClientExecutor) PopulateTransientMounts(opts docker.CreateContainerOptions, transientMounts []Mount, sharedMount string) ([]string, error) {
container, err := e.Client.CreateContainer(opts)
if err != nil {
return nil, fmt.Errorf("unable to create transient container: %v", err)
}
defer e.removeContainer(container.ID)
var copies []imagebuilder.Copy
for i, mount := range transientMounts {
copies = append(copies, imagebuilder.Copy{
FromFS: true,
Src: []string{mount.SourcePath},
Dest: filepath.Join(e.ContainerTransientMount, strconv.Itoa(i)),
})
}
if err := e.CopyContainer(container, nil, copies...); err != nil {
return nil, fmt.Errorf("unable to copy transient context into container: %v", err)
}
// mount individual items temporarily
var binds []string
for i, mount := range e.TransientMounts {
binds = append(binds, fmt.Sprintf("%s:%s:%s", filepath.Join(sharedMount, strconv.Itoa(i)), mount.DestinationPath, "ro"))
}
return binds, nil
}
// Release deletes any items started by this executor.
func (e *ClientExecutor) Release() []error {
errs := e.Volumes.Release()
for _, fn := range e.Deferred {
if err := fn(); err != nil {
errs = append(errs, err)
}
}
e.Deferred = nil
return errs
}
// removeContainer removes the provided container ID
func (e *ClientExecutor) removeContainer(id string) error {
e.Client.StopContainer(id, 0)
err := e.Client.RemoveContainer(docker.RemoveContainerOptions{
ID: id,
RemoveVolumes: true,
Force: true,
})
if _, ok := err.(*docker.NoSuchContainer); err != nil && !ok {
return fmt.Errorf("unable to cleanup container %s: %v", id, err)
}
return nil
}
// removeImage removes the provided image ID
func (e *ClientExecutor) removeImage(id string) error {
if err := e.Client.RemoveImageExtended(id, docker.RemoveImageOptions{
Force: true,
}); err != nil {
return fmt.Errorf("unable to clean up image %s: %v", id, err)
}
return nil
}
// CreateScratchImage creates a new, zero byte layer that is identical to "scratch"
// except that the resulting image will have two layers.
func (e *ClientExecutor) CreateScratchImage() (string, error) {
random, err := randSeq(imageSafeCharacters, 24)
if err != nil {
return "", err
}
name := fmt.Sprintf("scratch%s", random)
buf := &bytes.Buffer{}
w := tar.NewWriter(buf)
w.Close()
return name, e.Client.ImportImage(docker.ImportImageOptions{
Repository: name,
Source: "-",
InputStream: buf,
})
}
// imageSafeCharacters are characters allowed to be part of a Docker image name.
const imageSafeCharacters = "abcdefghijklmnopqrstuvwxyz0123456789"
// randSeq returns a sequence of random characters drawn from source. It returns
// an error if cryptographic randomness is not available or source is more than 255
// characters.
func randSeq(source string, n int) (string, error) {
if len(source) > 255 {
return "", fmt.Errorf("source must be less than 256 bytes long")
}
random := make([]byte, n)
if _, err := io.ReadFull(rand.Reader, random); err != nil {
return "", err
}
for i := range random {
random[i] = source[random[i]%byte(len(source))]
}
return string(random), nil
}
// LoadImage checks the client for an image matching from. If not found,
// attempts to pull the image and then tries to inspect again.
func (e *ClientExecutor) LoadImage(from string) (*docker.Image, error) {
return e.LoadImageWithPlatform(from, "")
}
// LoadImage checks the client for an image matching from. If not found,
// attempts to pull the image with specified platform string.
func (e *ClientExecutor) LoadImageWithPlatform(from string, platform string) (*docker.Image, error) {
image, err := e.Client.InspectImage(from)
if err == nil {
return image, nil
}
if err != docker.ErrNoSuchImage {
return nil, err
}
if !e.AllowPull {
klog.V(4).Infof("image %s did not exist", from)
return nil, docker.ErrNoSuchImage
}
repository, tag := docker.ParseRepositoryTag(from)
if len(tag) == 0 {
tag = "latest"
}
klog.V(4).Infof("attempting to pull %s with auth from repository %s:%s", from, repository, tag)
// TODO: we may want to abstract looping over multiple credentials
auth, _ := e.AuthFn(repository)
if len(auth) == 0 {
auth = append(auth, dockerregistrytypes.AuthConfig{})
}
if e.LogFn != nil {
e.LogFn("Image %s was not found, pulling ...", from)
}
var lastErr error
outputProgress := func(s string) {
e.LogFn("%s", s)
}
for _, config := range auth {
// TODO: handle IDs?
var pullErr error
func() { // A scope for defer
pullWriter := imageprogress.NewPullWriter(outputProgress)
defer func() {
err := pullWriter.Close()
if pullErr == nil {
pullErr = err
}
}()
pullImageOptions := docker.PullImageOptions{
Repository: repository,
Tag: tag,
OutputStream: pullWriter,
Platform: platform,
RawJSONStream: true,
}
if klog.V(5) {
pullImageOptions.OutputStream = os.Stderr
pullImageOptions.RawJSONStream = false
}
authConfig := docker.AuthConfiguration{Username: config.Username, ServerAddress: config.ServerAddress, Password: config.Password}
pullErr = e.Client.PullImage(pullImageOptions, authConfig)
}()
if pullErr == nil {
break
}
lastErr = pullErr
continue
}
if lastErr != nil {
return nil, fmt.Errorf("unable to pull image (from: %s, tag: %s): %v", repository, tag, lastErr)
}
return e.Client.InspectImage(from)
}
func (e *ClientExecutor) Preserve(path string) error {
if e.Volumes == nil {
e.Volumes = NewContainerVolumeTracker()
}
if err := e.EnsureContainerPath(path); err != nil {
return err
}
e.Volumes.Add(path)
return nil
}
func (e *ClientExecutor) EnsureContainerPath(path string) error {
return e.createOrReplaceContainerPathWithOwner(path, 0, 0, nil)
}
func (e *ClientExecutor) EnsureContainerPathAs(path, user string, mode *os.FileMode) error {
uid, gid := 0, 0
u, g, err := e.getUser(user)
if err == nil {
uid = u
gid = g
}
return e.createOrReplaceContainerPathWithOwner(path, uid, gid, mode)
}
func (e *ClientExecutor) createOrReplaceContainerPathWithOwner(path string, uid, gid int, mode *os.FileMode) error {
if mode == nil {
m := os.FileMode(0755)
mode = &m
}
createPath := func(dest string) error {
var writerErr error
if !strings.HasSuffix(dest, "/") {
dest = dest + "/"
}
reader, writer := io.Pipe()
opts := docker.UploadToContainerOptions{
InputStream: reader,
Path: "/",
Context: context.TODO(),
}
go func() {
defer writer.Close()
tarball := tar.NewWriter(writer)
defer tarball.Close()
writerErr = tarball.WriteHeader(&tar.Header{
Name: dest,
Typeflag: tar.TypeDir,
Mode: int64(*mode),
Uid: uid,
Gid: gid,
})
}()
klog.V(4).Infof("Uploading empty archive to %q", dest)
err := e.Client.UploadToContainer(e.Container.ID, opts)
if err != nil {
return fmt.Errorf("unable to ensure existence of preserved path %s: %v", dest, err)
}
if writerErr != nil {
return fmt.Errorf("error generating tarball to ensure existence of preserved path %s: %v", dest, writerErr)
}
return nil
}
readPath := func(dest string) error {
if !strings.HasSuffix(dest, "/") {
dest = dest + "/"
}
err := e.Client.DownloadFromContainer(e.Container.ID, docker.DownloadFromContainerOptions{
Path: dest,
OutputStream: ioutil.Discard,
})
return err
}
var pathsToCreate []string
pathToCheck := path
for {
if err := readPath(pathToCheck); err != nil {
pathsToCreate = append([]string{pathToCheck}, pathsToCreate...)
}
if filepath.Dir(pathToCheck) == pathToCheck {
break
}
pathToCheck = filepath.Dir(pathToCheck)
}
for _, path := range pathsToCreate {
if err := createPath(path); err != nil {
return fmt.Errorf("error creating container directory %s: %v", path, err)
}
}
return nil
}
func (e *ClientExecutor) UnrecognizedInstruction(step *imagebuilder.Step) error {
if e.IgnoreUnrecognizedInstructions {
e.LogFn("warning: Unknown instruction: %s", strings.ToUpper(step.Command))
return nil
}
return fmt.Errorf("Unknown instruction: %s", strings.ToUpper(step.Command))
}
// Run executes a single Run command against the current container using exec().
// Since exec does not allow ENV or WORKINGDIR to be set, we force the execution of
// the user command into a shell and perform those operations before. Since RUN
// requires /bin/sh, we can use both 'cd' and 'export'.
func (e *ClientExecutor) Run(run imagebuilder.Run, config docker.Config) error {
if len(run.Files) > 0 {
return fmt.Errorf("Heredoc syntax is not supported")
}
if len(run.Mounts) > 0 {
return fmt.Errorf("RUN --mount not supported")
}
if run.Network != "" {
return fmt.Errorf("RUN --network not supported")
}
args := make([]string, len(run.Args))
copy(args, run.Args)
defaultShell := config.Shell
if len(defaultShell) == 0 {
if runtime.GOOS == "windows" {
defaultShell = []string{"cmd", "/S", "/C"}
} else {
defaultShell = []string{"/bin/sh", "-c"}
}
}
if runtime.GOOS == "windows" {
if len(config.WorkingDir) > 0 {
args[0] = fmt.Sprintf("cd %s && %s", imagebuilder.BashQuote(config.WorkingDir), args[0])
}
// TODO: implement windows ENV
args = append(defaultShell, args...)
} else {
if run.Shell {
if len(config.WorkingDir) > 0 {
args[0] = fmt.Sprintf("cd %s && %s", imagebuilder.BashQuote(config.WorkingDir), args[0])
}
if len(config.Env) > 0 {
args[0] = imagebuilder.ExportEnv(config.Env) + args[0]
}
args = append(defaultShell, args...)
} else {
switch {
case len(config.WorkingDir) == 0 && len(config.Env) == 0:
// no change necessary
case len(args) > 0:
setup := "exec \"$@\""
if len(config.WorkingDir) > 0 {
setup = fmt.Sprintf("cd %s && %s", imagebuilder.BashQuote(config.WorkingDir), setup)
}
if len(config.Env) > 0 {
setup = imagebuilder.ExportEnv(config.Env) + setup
}
newArgs := make([]string, 0, len(args)+4)
newArgs = append(newArgs, defaultShell...)
newArgs = append(newArgs, setup, "")
newArgs = append(newArgs, args...)
args = newArgs
}
}
}
if e.StrictVolumeOwnership && !e.Volumes.Empty() {
return fmt.Errorf("a RUN command was executed after a VOLUME command, which may result in ownership information being lost")
}
if err := e.Volumes.Save(e.Container.ID, e.TempDir, e.Client); err != nil {
return err
}
config.Cmd = args
klog.V(4).Infof("Running %#v inside of %s as user %s", config.Cmd, e.Container.ID, config.User)
exec, err := e.Client.CreateExec(docker.CreateExecOptions{
Cmd: config.Cmd,
Container: e.Container.ID,
AttachStdout: true,
AttachStderr: true,
User: config.User,
})
if err != nil {
return err
}
if err := e.Client.StartExec(exec.ID, docker.StartExecOptions{
OutputStream: e.Out,
ErrorStream: e.ErrOut,
}); err != nil {
return err
}
status, err := e.Client.InspectExec(exec.ID)
if err != nil {
return err
}
if status.ExitCode != 0 {
klog.V(4).Infof("Failed command (code %d): %v", status.ExitCode, args)
return fmt.Errorf("running '%s' failed with exit code %d", strings.Join(run.Args, " "), status.ExitCode)
}
if err := e.Volumes.Restore(e.Container.ID, e.Client); err != nil {
return err
}
return nil
}
// Copy implements the executor copy function.
func (e *ClientExecutor) Copy(excludes []string, copies ...imagebuilder.Copy) error {
// copying content into a volume invalidates the archived state of any given directory
for _, copy := range copies {
if copy.Checksum != "" {
return fmt.Errorf("ADD --checksum not supported")
}
if copy.Link {
return fmt.Errorf("ADD or COPY --link not supported")
}
if copy.Parents {
return fmt.Errorf("COPY --parents not supported")
}
if copy.KeepGitDir {
return fmt.Errorf("ADD --keep-git-dir not supported")
}
if len(copy.Excludes) > 0 {
return fmt.Errorf("ADD or COPY --exclude not supported")
}
if len(copy.Files) > 0 {
return fmt.Errorf("Heredoc syntax is not supported")
}
e.Volumes.Invalidate(copy.Dest)
}
return e.CopyContainer(e.Container, excludes, copies...)
}
func (e *ClientExecutor) findMissingParents(container *docker.Container, dest string) (parents []string, err error) {
destParent := filepath.Clean(dest)
for filepath.Dir(destParent) != destParent {
exists, err := isContainerPathDirectory(e.Client, container.ID, destParent)
if err != nil {
return nil, err
}
if !exists {
parents = append(parents, destParent)
}
destParent = filepath.Dir(destParent)
}
return parents, nil
}
func (e *ClientExecutor) getUser(userspec string) (int, int, error) {
readFile := func(path string) ([]byte, error) {
var buffer, contents bytes.Buffer
if err := e.Client.DownloadFromContainer(e.Container.ID, docker.DownloadFromContainerOptions{
OutputStream: &buffer,
Path: path,
Context: context.TODO(),
}); err != nil {
return nil, err
}
tr := tar.NewReader(&buffer)
hdr, err := tr.Next()
if err != nil {
return nil, err
}
if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {
return nil, fmt.Errorf("expected %q to be a regular file, but it was of type %q", path, string(hdr.Typeflag))
}
if filepath.FromSlash(hdr.Name) != filepath.Base(path) {
return nil, fmt.Errorf("error reading contents of %q: got %q instead", path, hdr.Name)
}
n, err := io.Copy(&contents, tr)
if err != nil {
return nil, fmt.Errorf("error reading contents of %q: %v", path, err)
}
if n != hdr.Size {
return nil, fmt.Errorf("size mismatch reading contents of %q: %v", path, err)
}
hdr, err = tr.Next()
if err != nil && !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("error reading archive of %q: %v", path, err)
}
if err == nil {
return nil, fmt.Errorf("got unexpected extra content while reading archive of %q: %v", path, err)
}
return contents.Bytes(), nil
}
parse := func(file []byte, matchField int, key string, numFields, readField int) (string, error) {
var value *string
scanner := bufio.NewScanner(bytes.NewReader(file))
for scanner.Scan() {
line := scanner.Text()
fields := strings.SplitN(line, ":", numFields)
if len(fields) != numFields {
return "", fmt.Errorf("error parsing line %q: incorrect number of fields", line)
}
if fields[matchField] != key {
continue
}
v := fields[readField]
value = &v
}
if err := scanner.Err(); err != nil {
return "", fmt.Errorf("error scanning file: %v", err)
}
if value == nil {
return "", os.ErrNotExist
}
return *value, nil
}
spec := strings.SplitN(userspec, ":", 2)
if len(spec) == 2 {
parsedUid, err := strconv.ParseUint(spec[0], 10, 32)
if err != nil {
// maybe it's a user name? look up the UID
passwdFile, err := readFile("/etc/passwd")
if err != nil {
return -1, -1, err
}
uid, err := parse(passwdFile, 0, spec[0], 7, 2)
if err != nil {
return -1, -1, fmt.Errorf("error reading UID value from passwd file for --chown=%s: %v", spec[0], err)
}
parsedUid, err = strconv.ParseUint(uid, 10, 32)
if err != nil {
return -1, -1, fmt.Errorf("error parsing UID value %q from passwd file for --chown=%s", uid, userspec)
}
}
parsedGid, err := strconv.ParseUint(spec[1], 10, 32)