/
docker.go
1148 lines (1031 loc) · 39.2 KB
/
docker.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 docker
import (
"archive/tar"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
dockertypes "github.com/docker/docker/api/types"
dockercontainer "github.com/docker/docker/api/types/container"
dockernetwork "github.com/docker/docker/api/types/network"
dockerapi "github.com/docker/docker/client"
dockermessage "github.com/docker/docker/pkg/jsonmessage"
dockerstdcopy "github.com/docker/docker/pkg/stdcopy"
"github.com/docker/go-connections/tlsconfig"
"golang.org/x/net/context"
"github.com/openshift/source-to-image/pkg/api"
"github.com/openshift/source-to-image/pkg/api/constants"
s2ierr "github.com/openshift/source-to-image/pkg/errors"
s2itar "github.com/openshift/source-to-image/pkg/tar"
"github.com/openshift/source-to-image/pkg/util"
"github.com/openshift/source-to-image/pkg/util/fs"
"github.com/openshift/source-to-image/pkg/util/interrupt"
)
const (
// DefaultDestination is the destination where the artifacts will be placed
// if DestinationLabel was not specified.
DefaultDestination = "/tmp"
// DefaultTag is the image tag, being applied if none is specified.
DefaultTag = "latest"
// DefaultDockerTimeout specifies a timeout for Docker API calls. When this
// timeout is reached, certain Docker API calls might error out.
DefaultDockerTimeout = 2 * time.Minute
// DefaultShmSize is the default shared memory size to use (in bytes) if not specified.
DefaultShmSize = int64(1024 * 1024 * 64)
// DefaultPullRetryDelay is the default pull image retry interval
DefaultPullRetryDelay = 5 * time.Second
// DefaultPullRetryCount is the default pull image retry times
DefaultPullRetryCount = 6
)
var (
// RetriableErrors is a set of strings that indicate that an retriable error occurred.
RetriableErrors = []string{
"ping attempt failed with error",
"is already in progress",
"connection reset by peer",
"transport closed before response was received",
"connection refused",
}
)
// containerNamePrefix prefixes the name of containers launched by S2I. We
// cannot reuse the prefix "k8s" because we don't want the containers to be
// managed by a kubelet.
const containerNamePrefix = "s2i"
// containerName creates names for Docker containers launched by S2I. It is
// meant to resemble Kubernetes' pkg/kubelet/dockertools.BuildDockerName.
func containerName(image string) string {
//Initialize seed
rand.Seed(time.Now().UnixNano())
uid := fmt.Sprintf("%08x", rand.Uint32())
// Replace invalid characters for container name with underscores.
image = strings.Map(func(r rune) rune {
if ('0' <= r && r <= '9') || ('A' <= r && r <= 'Z') || ('a' <= r && r <= 'z') {
return r
}
return '_'
}, image)
return fmt.Sprintf("%s_%s_%s", containerNamePrefix, image, uid)
}
// Docker is the interface between STI and the docker engine-api.
// It contains higher level operations called from the STI
// build or usage commands
type Docker interface {
IsImageInLocalRegistry(name string) (bool, error)
IsImageOnBuild(string) bool
GetOnBuild(string) ([]string, error)
RemoveContainer(id string) error
GetScriptsURL(name string) (string, error)
GetAssembleInputFiles(string) (string, error)
GetAssembleRuntimeUser(string) (string, error)
RunContainer(opts RunContainerOptions) error
GetImageID(name string) (string, error)
GetImageWorkdir(name string) (string, error)
CommitContainer(opts CommitContainerOptions) (string, error)
RemoveImage(name string) error
CheckImage(name string) (*api.Image, error)
PullImage(name string) (*api.Image, error)
CheckAndPullImage(name string) (*api.Image, error)
BuildImage(opts BuildImageOptions) error
GetImageUser(name string) (string, error)
GetImageEntrypoint(name string) ([]string, error)
GetLabels(name string) (map[string]string, error)
UploadToContainer(fs fs.FileSystem, srcPath, destPath, container string) error
UploadToContainerWithTarWriter(fs fs.FileSystem, srcPath, destPath, container string, makeTarWriter func(io.Writer) s2itar.Writer) error
DownloadFromContainer(containerPath string, w io.Writer, container string) error
Version() (dockertypes.Version, error)
CheckReachable() error
}
// Client contains all methods used when interacting directly with docker engine-api
type Client interface {
ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error)
ContainerCommit(ctx context.Context, container string, options dockertypes.ContainerCommitOptions) (dockertypes.IDResponse, error)
ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error)
ContainerInspect(ctx context.Context, container string) (dockertypes.ContainerJSON, error)
ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error
ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error
ContainerKill(ctx context.Context, container, signal string) error
ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error)
CopyToContainer(ctx context.Context, container, path string, content io.Reader, opts dockertypes.CopyToContainerOptions) error
CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, dockertypes.ContainerPathStat, error)
ImageBuild(ctx context.Context, buildContext io.Reader, options dockertypes.ImageBuildOptions) (dockertypes.ImageBuildResponse, error)
ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error)
ImagePull(ctx context.Context, ref string, options dockertypes.ImagePullOptions) (io.ReadCloser, error)
ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error)
ServerVersion(ctx context.Context) (dockertypes.Version, error)
}
type stiDocker struct {
client Client
pullAuth dockertypes.AuthConfig
}
// InspectImage returns the image information and its raw representation.
func (d stiDocker) InspectImage(name string) (*dockertypes.ImageInspect, error) {
ctx, cancel := getDefaultContext()
defer cancel()
resp, _, err := d.client.ImageInspectWithRaw(ctx, name)
if err != nil {
return nil, err
}
return &resp, nil
}
// PostExecutor is an interface which provides a PostExecute function
type PostExecutor interface {
PostExecute(containerID, destination string) error
}
// PullResult is the result returned by the PullImage function
type PullResult struct {
OnBuild bool
Image *api.Image
}
// RunContainerOptions are options passed in to the RunContainer method
type RunContainerOptions struct {
Image string
PullImage bool
PullAuth api.AuthConfig
ExternalScripts bool
ScriptsURL string
Destination string
Env []string
AddHost []string
// Entrypoint will be used to override the default entrypoint
// for the image if it has one. If the image has no entrypoint,
// this value is ignored.
Entrypoint []string
Stdin io.ReadCloser
Stdout io.WriteCloser
Stderr io.WriteCloser
OnStart func(containerID string) error
PostExec PostExecutor
TargetImage bool
NetworkMode string
User string
CGroupLimits *api.CGroupLimits
CapDrop []string
Binds []string
Command string
CommandOverrides func(originalCmd string) string
// CommandExplicit provides a full control on the CMD directive.
// It won't modified in any way and will be passed to the docker as-is.
// Use this option when you want to use arbitrary command as CMD directive.
// In this case you can't use Command because 1) it's just a string
// 2) it will be modified by prepending base dir and cleaned by the path.Join().
// You also can't use CommandOverrides because 1) it's a string
// 2) it only gets applied when Command equals to "assemble" or "usage" script
// AND script is inside of the tar archive.
CommandExplicit []string
// SecurityOpt is passed through as security options to the underlying container.
SecurityOpt []string
}
// asDockerConfig converts a RunContainerOptions into a Config understood by the
// docker client
func (rco RunContainerOptions) asDockerConfig() dockercontainer.Config {
return dockercontainer.Config{
Image: getImageName(rco.Image),
User: rco.User,
Env: rco.Env,
Entrypoint: rco.Entrypoint,
OpenStdin: rco.Stdin != nil,
StdinOnce: rco.Stdin != nil,
AttachStdout: rco.Stdout != nil,
}
}
// asDockerHostConfig converts a RunContainerOptions into a HostConfig
// understood by the docker client
func (rco RunContainerOptions) asDockerHostConfig() dockercontainer.HostConfig {
hostConfig := dockercontainer.HostConfig{
CapDrop: rco.CapDrop,
PublishAllPorts: rco.TargetImage,
NetworkMode: dockercontainer.NetworkMode(rco.NetworkMode),
Binds: rco.Binds,
ExtraHosts: rco.AddHost,
SecurityOpt: rco.SecurityOpt,
}
if rco.CGroupLimits != nil {
hostConfig.Resources.Memory = rco.CGroupLimits.MemoryLimitBytes
hostConfig.Resources.MemorySwap = rco.CGroupLimits.MemorySwap
hostConfig.Resources.CgroupParent = rco.CGroupLimits.Parent
}
return hostConfig
}
// asDockerCreateContainerOptions converts a RunContainerOptions into a
// ContainerCreateConfig understood by the docker client
func (rco RunContainerOptions) asDockerCreateContainerOptions() dockertypes.ContainerCreateConfig {
config := rco.asDockerConfig()
hostConfig := rco.asDockerHostConfig()
return dockertypes.ContainerCreateConfig{
Name: containerName(rco.Image),
Config: &config,
HostConfig: &hostConfig,
}
}
// asDockerAttachToContainerOptions converts a RunContainerOptions into a
// ContainerAttachOptions understood by the docker client
func (rco RunContainerOptions) asDockerAttachToContainerOptions() dockertypes.ContainerAttachOptions {
return dockertypes.ContainerAttachOptions{
Stdin: rco.Stdin != nil,
Stdout: rco.Stdout != nil,
Stderr: rco.Stderr != nil,
Stream: rco.Stdout != nil,
}
}
// CommitContainerOptions are options passed in to the CommitContainer method
type CommitContainerOptions struct {
ContainerID string
Repository string
User string
Command []string
Env []string
Entrypoint []string
Labels map[string]string
}
// BuildImageOptions are options passed in to the BuildImage method
type BuildImageOptions struct {
Name string
Stdin io.Reader
Stdout io.WriteCloser
CGroupLimits *api.CGroupLimits
}
// NewEngineAPIClient creates a new Docker engine API client
func NewEngineAPIClient(config *api.DockerConfig) (*dockerapi.Client, error) {
var httpClient *http.Client
if config.UseTLS || config.TLSVerify {
tlscOptions := tlsconfig.Options{
InsecureSkipVerify: !config.TLSVerify,
}
if _, err := os.Stat(config.CAFile); !os.IsNotExist(err) {
tlscOptions.CAFile = config.CAFile
}
if _, err := os.Stat(config.CertFile); !os.IsNotExist(err) {
tlscOptions.CertFile = config.CertFile
}
if _, err := os.Stat(config.KeyFile); !os.IsNotExist(err) {
tlscOptions.KeyFile = config.KeyFile
}
tlsc, err := tlsconfig.Client(tlscOptions)
if err != nil {
return nil, err
}
httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsc,
},
}
}
return dockerapi.NewClient(config.Endpoint, os.Getenv("DOCKER_API_VERSION"), httpClient, nil)
}
// New creates a new implementation of the STI Docker interface
func New(client Client, auth api.AuthConfig) Docker {
return &stiDocker{
client: client,
pullAuth: dockertypes.AuthConfig{
Username: auth.Username,
Password: auth.Password,
Email: auth.Email,
ServerAddress: auth.ServerAddress,
},
}
}
func getDefaultContext() (context.Context, context.CancelFunc) {
// the intention is: all docker API calls with the exception of known long-
// running calls (ContainerWait, ImagePull, ImageBuild, ImageCommit) must complete within a
// certain timeout otherwise we bail.
return context.WithTimeout(context.Background(), DefaultDockerTimeout)
}
// GetImageWorkdir returns the WORKDIR property for the given image name.
// When the WORKDIR is not set or empty, return "/" instead.
func (d *stiDocker) GetImageWorkdir(name string) (string, error) {
resp, err := d.InspectImage(name)
if err != nil {
return "", err
}
workdir := resp.Config.WorkingDir
if len(workdir) == 0 {
// This is a default destination used by UploadToContainer when the WORKDIR
// is not set or it is empty. To show user where the injections will end up,
// we set this to "/".
workdir = "/"
}
return workdir, nil
}
// GetImageEntrypoint returns the ENTRYPOINT property for the given image name.
func (d *stiDocker) GetImageEntrypoint(name string) ([]string, error) {
image, err := d.InspectImage(name)
if err != nil {
return nil, err
}
return image.Config.Entrypoint, nil
}
// UploadToContainer uploads artifacts to the container.
func (d *stiDocker) UploadToContainer(fs fs.FileSystem, src, dest, container string) error {
makeWorldWritable := func(writer io.Writer) s2itar.Writer {
return s2itar.ChmodAdapter{Writer: tar.NewWriter(writer), NewFileMode: 0666, NewExecFileMode: 0666, NewDirMode: 0777}
}
return d.UploadToContainerWithTarWriter(fs, src, dest, container, makeWorldWritable)
}
// UploadToContainerWithTarWriter uploads artifacts to the container.
// If the source is a directory, then all files and sub-folders are copied into
// the destination (which has to be directory as well).
// If the source is a single file, then the file copied into destination (which
// has to be full path to a file inside the container).
func (d *stiDocker) UploadToContainerWithTarWriter(fs fs.FileSystem, src, dest, container string, makeTarWriter func(io.Writer) s2itar.Writer) error {
destPath := filepath.Dir(dest)
r, w := io.Pipe()
go func() {
tarWriter := makeTarWriter(w)
tarWriter = s2itar.RenameAdapter{Writer: tarWriter, Old: filepath.Base(src), New: filepath.Base(dest)}
err := s2itar.New(fs).CreateTarStreamToTarWriter(src, true, tarWriter, nil)
if err == nil {
err = tarWriter.Close()
}
w.CloseWithError(err)
}()
log.V(3).Infof("Uploading %q to %q ...", src, destPath)
ctx, cancel := getDefaultContext()
defer cancel()
err := d.client.CopyToContainer(ctx, container, destPath, r, dockertypes.CopyToContainerOptions{})
if err != nil {
log.V(0).Infof("error: Uploading to container failed: %v", err)
}
return err
}
// DownloadFromContainer downloads file (or directory) from the container.
func (d *stiDocker) DownloadFromContainer(containerPath string, w io.Writer, container string) error {
ctx, cancel := getDefaultContext()
defer cancel()
readCloser, _, err := d.client.CopyFromContainer(ctx, container, containerPath)
if err != nil {
return err
}
defer readCloser.Close()
_, err = io.Copy(w, readCloser)
return err
}
// IsImageInLocalRegistry determines whether the supplied image is in the local registry.
func (d *stiDocker) IsImageInLocalRegistry(name string) (bool, error) {
name = getImageName(name)
resp, err := d.InspectImage(name)
if resp != nil {
return true, nil
}
if err != nil && !dockerapi.IsErrNotFound(err) {
return false, s2ierr.NewInspectImageError(name, err)
}
return false, nil
}
// GetImageUser finds and retrieves the user associated with
// an image if one has been specified
func (d *stiDocker) GetImageUser(name string) (string, error) {
name = getImageName(name)
resp, err := d.InspectImage(name)
if err != nil {
log.V(4).Infof("error inspecting image %s: %v", name, err)
return "", s2ierr.NewInspectImageError(name, err)
}
user := resp.Config.User
return user, nil
}
// Version returns information of the docker client and server host
func (d *stiDocker) Version() (dockertypes.Version, error) {
ctx, cancel := getDefaultContext()
defer cancel()
return d.client.ServerVersion(ctx)
}
// IsImageOnBuild provides information about whether the Docker image has
// OnBuild instruction recorded in the Image Config.
func (d *stiDocker) IsImageOnBuild(name string) bool {
onbuild, err := d.GetOnBuild(name)
return err == nil && len(onbuild) > 0
}
// GetOnBuild returns the set of ONBUILD Dockerfile commands to execute
// for the given image
func (d *stiDocker) GetOnBuild(name string) ([]string, error) {
name = getImageName(name)
resp, err := d.InspectImage(name)
if err != nil {
log.V(4).Infof("error inspecting image %s: %v", name, err)
return nil, s2ierr.NewInspectImageError(name, err)
}
return resp.Config.OnBuild, nil
}
// CheckAndPullImage pulls an image into the local registry if not present
// and returns the image metadata
func (d *stiDocker) CheckAndPullImage(name string) (*api.Image, error) {
name = getImageName(name)
displayName := name
if !log.Is(3) {
// For less verbose log levels (less than 3), shorten long iamge names like:
// "centos/php-56-centos7@sha256:51c3e2b08bd9fadefccd6ec42288680d6d7f861bdbfbd2d8d24960621e4e27f5"
// to include just enough characters to differentiate the build from others in the docker repository:
// "centos/php-56-centos7@sha256:51c3e2b08bd..."
// 18 characters is somewhat arbitrary, but should be enough to avoid a name collision.
split := strings.Split(name, "@")
if len(split) > 1 && len(split[1]) > 18 {
displayName = split[0] + "@" + split[1][:18] + "..."
}
}
image, err := d.CheckImage(name)
if err != nil && !strings.Contains(err.(s2ierr.Error).Details.Error(), "No such image") {
return nil, err
}
if image == nil {
log.V(1).Infof("Image %q not available locally, pulling ...", displayName)
return d.PullImage(name)
}
log.V(3).Infof("Using locally available image %q", displayName)
return image, nil
}
// CheckImage checks image from the local registry.
func (d *stiDocker) CheckImage(name string) (*api.Image, error) {
name = getImageName(name)
inspect, err := d.InspectImage(name)
if err != nil {
log.V(4).Infof("error inspecting image %s: %v", name, err)
return nil, s2ierr.NewInspectImageError(name, err)
}
if inspect != nil {
image := &api.Image{}
updateImageWithInspect(image, inspect)
return image, nil
}
return nil, nil
}
func base64EncodeAuth(auth dockertypes.AuthConfig) (string, error) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(auth); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(buf.Bytes()), nil
}
// PullImage pulls an image into the local registry
func (d *stiDocker) PullImage(name string) (*api.Image, error) {
name = getImageName(name)
// RegistryAuth is the base64 encoded credentials for the registry
base64Auth, err := base64EncodeAuth(d.pullAuth)
if err != nil {
return nil, s2ierr.NewPullImageError(name, err)
}
var retriableError = false
for retries := 0; retries <= DefaultPullRetryCount; retries++ {
err = util.TimeoutAfter(DefaultDockerTimeout, fmt.Sprintf("pulling image %q", name), func(timer *time.Timer) error {
resp, pullErr := d.client.ImagePull(context.Background(), name, dockertypes.ImagePullOptions{RegistryAuth: base64Auth})
if pullErr != nil {
return pullErr
}
defer resp.Close()
decoder := json.NewDecoder(resp)
for {
if !timer.Stop() {
return &util.TimeoutError{}
}
timer.Reset(DefaultDockerTimeout)
var msg dockermessage.JSONMessage
pullErr = decoder.Decode(&msg)
if pullErr == io.EOF {
return nil
}
if pullErr != nil {
return pullErr
}
if msg.Error != nil {
return msg.Error
}
if msg.Progress != nil {
log.V(4).Infof("pulling image %s: %s", name, msg.Progress.String())
}
}
})
if err == nil {
break
}
log.V(0).Infof("pulling image error : %v", err)
errMsg := fmt.Sprintf("%s", err)
for _, errorString := range RetriableErrors {
if strings.Contains(errMsg, errorString) {
retriableError = true
break
}
}
if !retriableError {
return nil, s2ierr.NewPullImageError(name, err)
}
log.V(0).Infof("retrying in %s ...", DefaultPullRetryDelay)
time.Sleep(DefaultPullRetryDelay)
}
inspectResp, err := d.InspectImage(name)
if err != nil {
return nil, s2ierr.NewPullImageError(name, err)
}
if inspectResp != nil {
image := &api.Image{}
updateImageWithInspect(image, inspectResp)
return image, nil
}
return nil, nil
}
func updateImageWithInspect(image *api.Image, inspect *dockertypes.ImageInspect) {
image.ID = inspect.ID
if inspect.Config != nil {
image.Config = &api.ContainerConfig{
Labels: inspect.Config.Labels,
Env: inspect.Config.Env,
}
}
if inspect.ContainerConfig != nil {
image.ContainerConfig = &api.ContainerConfig{
Labels: inspect.ContainerConfig.Labels,
Env: inspect.ContainerConfig.Env,
}
}
}
// RemoveContainer removes a container and its associated volumes.
func (d *stiDocker) RemoveContainer(id string) error {
ctx, cancel := getDefaultContext()
defer cancel()
opts := dockertypes.ContainerRemoveOptions{
RemoveVolumes: true,
}
return d.client.ContainerRemove(ctx, id, opts)
}
// KillContainer kills a container.
func (d *stiDocker) KillContainer(id string) error {
ctx, cancel := getDefaultContext()
defer cancel()
return d.client.ContainerKill(ctx, id, "SIGKILL")
}
// GetLabels retrieves the labels of the given image.
func (d *stiDocker) GetLabels(name string) (map[string]string, error) {
name = getImageName(name)
resp, err := d.InspectImage(name)
if err != nil {
log.V(4).Infof("error inspecting image %s: %v", name, err)
return nil, s2ierr.NewInspectImageError(name, err)
}
return resp.Config.Labels, nil
}
// getImageName checks the image name and adds DefaultTag if none is specified
func getImageName(name string) string {
_, tag, id := parseRepositoryTag(name)
if len(tag) == 0 && len(id) == 0 {
//_, tag, _ := parseRepositoryTag(name)
//if len(tag) == 0 {
return strings.Join([]string{name, DefaultTag}, ":")
}
return name
}
// getLabel gets label's value from the image metadata
func getLabel(image *api.Image, name string) string {
if value, ok := image.Config.Labels[name]; ok {
return value
}
return ""
}
// getVariable gets environment variable's value from the image metadata
func getVariable(image *api.Image, name string) string {
envName := name + "="
for _, v := range image.Config.Env {
if strings.HasPrefix(v, envName) {
return strings.TrimSpace(v[len(envName):])
}
}
return ""
}
// GetScriptsURL finds a scripts-url label on the given image.
func (d *stiDocker) GetScriptsURL(image string) (string, error) {
imageMetadata, err := d.CheckAndPullImage(image)
if err != nil {
return "", err
}
return getScriptsURL(imageMetadata), nil
}
// GetAssembleInputFiles finds a io.openshift.s2i.assemble-input-files label on the given image.
func (d *stiDocker) GetAssembleInputFiles(image string) (string, error) {
imageMetadata, err := d.CheckAndPullImage(image)
if err != nil {
return "", err
}
label := getLabel(imageMetadata, constants.AssembleInputFilesLabel)
if len(label) == 0 {
log.V(0).Infof("warning: Image %q does not contain a value for the %s label", image, constants.AssembleInputFilesLabel)
} else {
log.V(3).Infof("Image %q contains %s set to %q", image, constants.AssembleInputFilesLabel, label)
}
return label, nil
}
// GetAssembleRuntimeUser finds a io.openshift.s2i.assemble-runtime-user label on the given image.
func (d *stiDocker) GetAssembleRuntimeUser(image string) (string, error) {
imageMetadata, err := d.CheckAndPullImage(image)
if err != nil {
return "", err
}
return getLabel(imageMetadata, constants.AssembleRuntimeUserLabel), nil
}
// getScriptsURL finds a scripts url label in the image metadata
func getScriptsURL(image *api.Image) string {
if image == nil {
return ""
}
scriptsURL := getLabel(image, constants.ScriptsURLLabel)
// For backward compatibility, support the old label schema
if len(scriptsURL) == 0 {
scriptsURL = getLabel(image, constants.DeprecatedScriptsURLLabel)
if len(scriptsURL) > 0 {
log.V(0).Infof("warning: Image %s uses deprecated label '%s', please migrate it to %s instead!",
image.ID, constants.DeprecatedScriptsURLLabel, constants.ScriptsURLLabel)
}
}
if len(scriptsURL) == 0 {
scriptsURL = getVariable(image, constants.ScriptsURLEnvironment)
if len(scriptsURL) != 0 {
log.V(0).Infof("warning: Image %s uses deprecated environment variable %s, please migrate it to %s label instead!",
image.ID, constants.ScriptsURLEnvironment, constants.ScriptsURLLabel)
}
}
if len(scriptsURL) == 0 {
log.V(0).Infof("warning: Image %s does not contain a value for the %s label", image.ID, constants.ScriptsURLLabel)
} else {
log.V(2).Infof("Image %s contains %s set to %q", image.ID, constants.ScriptsURLLabel, scriptsURL)
}
return scriptsURL
}
// getDestination finds a destination label in the image metadata
func getDestination(image *api.Image) string {
if val := getLabel(image, constants.DestinationLabel); len(val) != 0 {
return val
}
// For backward compatibility, support the old label schema
if val := getLabel(image, constants.DeprecatedDestinationLabel); len(val) != 0 {
log.V(0).Infof("warning: Image %s uses deprecated label '%s', please migrate it to %s instead!",
image.ID, constants.DeprecatedDestinationLabel, constants.DestinationLabel)
return val
}
if val := getVariable(image, constants.LocationEnvironment); len(val) != 0 {
log.V(0).Infof("warning: Image %s uses deprecated environment variable %s, please migrate it to %s label instead!",
image.ID, constants.LocationEnvironment, constants.DestinationLabel)
return val
}
// default directory if none is specified
return DefaultDestination
}
func constructCommand(opts RunContainerOptions, imageMetadata *api.Image, tarDestination string) []string {
// base directory for all S2I commands
commandBaseDir := determineCommandBaseDir(opts, imageMetadata, tarDestination)
// NOTE: We use path.Join instead of filepath.Join to avoid converting the
// path to UNC (Windows) format as we always run this inside container.
binaryToRun := path.Join(commandBaseDir, opts.Command)
// when calling assemble script with Stdin parameter set (the tar file)
// we need to first untar the whole archive and only then call the assemble script
if opts.Stdin != nil && (opts.Command == constants.Assemble || opts.Command == constants.Usage) {
untarAndRun := fmt.Sprintf("tar -C %s -xf - && %s", tarDestination, binaryToRun)
resultedCommand := untarAndRun
if opts.CommandOverrides != nil {
resultedCommand = opts.CommandOverrides(untarAndRun)
}
return []string{"/bin/sh", "-c", resultedCommand}
}
return []string{binaryToRun}
}
func determineTarDestinationDir(opts RunContainerOptions, imageMetadata *api.Image) string {
if len(opts.Destination) != 0 {
return opts.Destination
}
return getDestination(imageMetadata)
}
func determineCommandBaseDir(opts RunContainerOptions, imageMetadata *api.Image, tarDestination string) string {
if opts.ExternalScripts {
// for external scripts we must always append 'scripts' because this is
// the default subdirectory inside tar for them
// NOTE: We use path.Join instead of filepath.Join to avoid converting the
// path to UNC (Windows) format as we always run this inside container.
log.V(2).Infof("Both scripts and untarred source will be placed in '%s'", tarDestination)
return path.Join(tarDestination, "scripts")
}
// for internal scripts we can have separate path for scripts and untar operation destination
scriptsURL := opts.ScriptsURL
if len(scriptsURL) == 0 {
scriptsURL = getScriptsURL(imageMetadata)
}
commandBaseDir := strings.TrimPrefix(scriptsURL, "image://")
log.V(2).Infof("Base directory for S2I scripts is '%s'. Untarring destination is '%s'.",
commandBaseDir, tarDestination)
return commandBaseDir
}
// dumpContainerInfo dumps information about a running container (port/IP/etc).
func dumpContainerInfo(container dockercontainer.ContainerCreateCreatedBody, d *stiDocker, image string) {
ctx, cancel := getDefaultContext()
defer cancel()
containerJSON, err := d.client.ContainerInspect(ctx, container.ID)
if err != nil {
return
}
liveports := "\n\nPort Bindings: "
for port, bindings := range containerJSON.NetworkSettings.NetworkSettingsBase.Ports {
liveports = liveports + "\n Container Port: " + string(port)
liveports = liveports + "\n Public Host / Port Mappings:"
for _, binding := range bindings {
liveports = liveports + "\n IP: " + binding.HostIP + " Port: " + binding.HostPort
}
}
liveports = liveports + "\n"
log.V(0).Infof("\n\n\n\n\nThe image %s has been started in container %s as a result of the --run=true option. The container's stdout/stderr will be redirected to this command's log output to help you validate its behavior. You can also inspect the container with docker commands if you like. If the container is set up to stay running, you will have to Ctrl-C to exit this command, which should also stop the container %s. This particular invocation attempts to run with the port mappings %+v \n\n\n\n\n", image, container.ID, container.ID, liveports)
}
// redirectResponseToOutputStream handles incoming streamed data from a
// container on a "hijacked" connection. If tty is true, expect multiplexed
// streams. Rules: 1) if you ask for streamed data from a container, you have
// to read it, otherwise sooner or later the container will block writing it.
// 2) if you're receiving multiplexed data, you have to actively read both
// streams in parallel, otherwise in the case of non-interleaved data, you, and
// then the container, will block.
func (d *stiDocker) redirectResponseToOutputStream(tty bool, outputStream, errorStream io.Writer, resp io.Reader) error {
if outputStream == nil {
outputStream = ioutil.Discard
}
if errorStream == nil {
errorStream = ioutil.Discard
}
var err error
if tty {
_, err = io.Copy(outputStream, resp)
} else {
_, err = dockerstdcopy.StdCopy(outputStream, errorStream, resp)
}
return err
}
// holdHijackedConnection pumps data up to the container's stdin, and runs a
// goroutine to pump data down from the container's stdout and stderr. it holds
// open the HijackedResponse until all of this is done. Caller's responsibility
// to close resp, as well as outputStream and errorStream if appropriate.
func (d *stiDocker) holdHijackedConnection(tty bool, opts *RunContainerOptions, resp dockertypes.HijackedResponse) error {
receiveStdout := make(chan error, 1)
if opts.Stdout != nil || opts.Stderr != nil {
go func() {
err := d.redirectResponseToOutputStream(tty, opts.Stdout, opts.Stderr, resp.Reader)
if opts.Stdout != nil {
opts.Stdout.Close()
opts.Stdout = nil
}
if opts.Stderr != nil {
opts.Stderr.Close()
opts.Stderr = nil
}
receiveStdout <- err
}()
} else {
receiveStdout <- nil
}
if opts.Stdin != nil {
_, err := io.Copy(resp.Conn, opts.Stdin)
opts.Stdin.Close()
opts.Stdin = nil
if err != nil {
<-receiveStdout
return err
}
}
err := resp.CloseWrite()
if err != nil {
<-receiveStdout
return err
}
// Hang around until the streaming is over - either when the server closes
// the connection, or someone locally closes resp.
return <-receiveStdout
}
// RunContainer creates and starts a container using the image specified in opts
// with the ability to stream input and/or output. Any non-nil
// opts.Std{in,out,err} will be closed upon return.
func (d *stiDocker) RunContainer(opts RunContainerOptions) error {
// Guarantee that Std{in,out,err} are closed upon return, including under
// error circumstances. In normal circumstances, holdHijackedConnection
// should do this for us.
defer func() {
if opts.Stdin != nil {
opts.Stdin.Close()
}
if opts.Stdout != nil {
opts.Stdout.Close()
}
if opts.Stderr != nil {
opts.Stderr.Close()
}
}()
createOpts := opts.asDockerCreateContainerOptions()
// get info about the specified image
image := createOpts.Config.Image
inspect, err := d.InspectImage(image)
imageMetadata := &api.Image{}
if err == nil {
updateImageWithInspect(imageMetadata, inspect)
if opts.PullImage {
_, err = d.CheckAndPullImage(image)
}
}
if err != nil {
log.V(0).Infof("error: Unable to get image metadata for %s: %v", image, err)
return err
}
entrypoint, err := d.GetImageEntrypoint(image)
if err != nil {
return fmt.Errorf("could not get entrypoint of %q image: %v", image, err)
}
// If the image has an entrypoint already defined,
// it will be overridden either by DefaultEntrypoint,
// or by the value in opts.Entrypoint.
// If the image does not have an entrypoint, but
// opts.Entrypoint is supplied, opts.Entrypoint will
// be respected.
if len(entrypoint) != 0 && len(opts.Entrypoint) == 0 {
opts.Entrypoint = DefaultEntrypoint
}
// tarDestination will be passed as location to PostExecute function
// and will be used as the prefix for the CMD (scripts/run)
var tarDestination string
var cmd []string
if !opts.TargetImage {
if len(opts.CommandExplicit) != 0 {
cmd = opts.CommandExplicit
} else {
tarDestination = determineTarDestinationDir(opts, imageMetadata)
cmd = constructCommand(opts, imageMetadata, tarDestination)
}
log.V(5).Infof("Setting %q command for container ...", strings.Join(cmd, " "))
}
createOpts.Config.Cmd = cmd
if createOpts.HostConfig != nil && createOpts.HostConfig.ShmSize <= 0 {
createOpts.HostConfig.ShmSize = DefaultShmSize
}
// Create a new container.
log.V(2).Infof("Creating container with options {Name:%q Config:%+v HostConfig:%+v} ...", createOpts.Name, *util.SafeForLoggingContainerConfig(createOpts.Config), createOpts.HostConfig)
ctx, cancel := getDefaultContext()
defer cancel()
container, err := d.client.ContainerCreate(ctx, createOpts.Config, createOpts.HostConfig, createOpts.NetworkingConfig, createOpts.Name)
if err != nil {
return err
}
// Container was created, so we defer its removal, and also remove it if we get a SIGINT/SIGTERM/SIGQUIT/SIGHUP.
removeContainer := func() {
log.V(4).Infof("Removing container %q ...", container.ID)
killErr := d.KillContainer(container.ID)
if removeErr := d.RemoveContainer(container.ID); removeErr != nil {
if killErr != nil {
log.V(0).Infof("warning: Failed to kill container %q: %v", container.ID, killErr)
}
log.V(0).Infof("warning: Failed to remove container %q: %v", container.ID, removeErr)
} else {
log.V(4).Infof("Removed container %q", container.ID)
}
}
dumpStack := func(signal os.Signal) {
if signal == syscall.SIGQUIT {
buf := make([]byte, 1<<16)
runtime.Stack(buf, true)
fmt.Printf("%s", buf)
}
os.Exit(2)
}