-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker_utils.go
1495 lines (1310 loc) · 40.7 KB
/
docker_utils.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 main
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/docker/docker/opts"
"github.com/docker/docker/pkg/httputils"
"github.com/docker/docker/pkg/integration"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/stringutils"
"github.com/docker/engine-api/types"
"github.com/docker/go-connections/tlsconfig"
"github.com/docker/go-units"
"github.com/go-check/check"
)
func init() {
cmd := exec.Command(dockerBinary, "images")
cmd.Env = appendBaseEnv(true)
out, err := cmd.CombinedOutput()
if err != nil {
panic(fmt.Errorf("err=%v\nout=%s\n", err, out))
}
lines := strings.Split(string(out), "\n")[1:]
for _, l := range lines {
if l == "" {
continue
}
fields := strings.Fields(l)
imgTag := fields[0] + ":" + fields[1]
// just for case if we have dangling images in tested daemon
if imgTag != "<none>:<none>" {
protectedImages[imgTag] = struct{}{}
}
}
// Obtain the daemon platform so that it can be used by tests to make
// intelligent decisions about how to configure themselves, and validate
// that the target platform is valid.
res, _, err := sockRequestRaw("GET", "/version", nil, "application/json")
if err != nil || res == nil || (res != nil && res.StatusCode != http.StatusOK) {
panic(fmt.Errorf("Init failed to get version: %v. Res=%v", err.Error(), res))
}
svrHeader, _ := httputils.ParseServerHeader(res.Header.Get("Server"))
daemonPlatform = svrHeader.OS
if daemonPlatform != "linux" && daemonPlatform != "windows" {
panic("Cannot run tests against platform: " + daemonPlatform)
}
// On Windows, extract out the version as we need to make selective
// decisions during integration testing as and when features are implemented.
if daemonPlatform == "windows" {
if body, err := ioutil.ReadAll(res.Body); err == nil {
var server types.Version
if err := json.Unmarshal(body, &server); err == nil {
// eg in "10.0 10550 (10550.1000.amd64fre.branch.date-time)" we want 10550
windowsDaemonKV, _ = strconv.Atoi(strings.Split(server.KernelVersion, " ")[1])
}
}
}
// Now we know the daemon platform, can set paths used by tests.
_, body, err := sockRequest("GET", "/info", nil)
if err != nil {
panic(err)
}
var info types.Info
err = json.Unmarshal(body, &info)
daemonStorageDriver = info.Driver
dockerBasePath = info.DockerRootDir
volumesConfigPath = filepath.Join(dockerBasePath, "volumes")
containerStoragePath = filepath.Join(dockerBasePath, "containers")
// Make sure in context of daemon, not the local platform. Note we can't
// use filepath.FromSlash or ToSlash here as they are a no-op on Unix.
if daemonPlatform == "windows" {
volumesConfigPath = strings.Replace(volumesConfigPath, `/`, `\`, -1)
containerStoragePath = strings.Replace(containerStoragePath, `/`, `\`, -1)
} else {
volumesConfigPath = strings.Replace(volumesConfigPath, `\`, `/`, -1)
containerStoragePath = strings.Replace(containerStoragePath, `\`, `/`, -1)
}
}
func convertBasesize(basesizeBytes int64) (int64, error) {
basesize := units.HumanSize(float64(basesizeBytes))
basesize = strings.Trim(basesize, " ")[:len(basesize)-3]
basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64)
if err != nil {
return 0, err
}
return int64(basesizeFloat) * 1024 * 1024 * 1024, nil
}
func daemonHost() string {
daemonURLStr := "unix://" + opts.DefaultUnixSocket
if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
daemonURLStr = daemonHostVar
}
return daemonURLStr
}
func getTLSConfig() (*tls.Config, error) {
dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
if dockerCertPath == "" {
return nil, fmt.Errorf("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
}
option := &tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, "ca.pem"),
CertFile: filepath.Join(dockerCertPath, "cert.pem"),
KeyFile: filepath.Join(dockerCertPath, "key.pem"),
}
tlsConfig, err := tlsconfig.Client(*option)
if err != nil {
return nil, err
}
return tlsConfig, nil
}
func sockConn(timeout time.Duration) (net.Conn, error) {
daemon := daemonHost()
daemonURL, err := url.Parse(daemon)
if err != nil {
return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
}
var c net.Conn
switch daemonURL.Scheme {
case "npipe":
return npipeDial(daemonURL.Path, timeout)
case "unix":
return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
case "tcp":
if os.Getenv("DOCKER_TLS_VERIFY") != "" {
// Setup the socket TLS configuration.
tlsConfig, err := getTLSConfig()
if err != nil {
return nil, err
}
dialer := &net.Dialer{Timeout: timeout}
return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
}
return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
default:
return c, fmt.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
}
}
func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) {
jsonData := bytes.NewBuffer(nil)
if err := json.NewEncoder(jsonData).Encode(data); err != nil {
return -1, nil, err
}
res, body, err := sockRequestRaw(method, endpoint, jsonData, "application/json")
if err != nil {
return -1, nil, err
}
b, err := readBody(body)
return res.StatusCode, b, err
}
func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) {
req, client, err := newRequestClient(method, endpoint, data, ct)
if err != nil {
return nil, nil, err
}
resp, err := client.Do(req)
if err != nil {
client.Close()
return nil, nil, err
}
body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
defer resp.Body.Close()
return client.Close()
})
return resp, body, nil
}
func sockRequestHijack(method, endpoint string, data io.Reader, ct string) (net.Conn, *bufio.Reader, error) {
req, client, err := newRequestClient(method, endpoint, data, ct)
if err != nil {
return nil, nil, err
}
client.Do(req)
conn, br := client.Hijack()
return conn, br, nil
}
func newRequestClient(method, endpoint string, data io.Reader, ct string) (*http.Request, *httputil.ClientConn, error) {
c, err := sockConn(time.Duration(10 * time.Second))
if err != nil {
return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
}
client := httputil.NewClientConn(c, nil)
req, err := http.NewRequest(method, endpoint, data)
if err != nil {
client.Close()
return nil, nil, fmt.Errorf("could not create new request: %v", err)
}
if ct != "" {
req.Header.Set("Content-Type", ct)
}
return req, client, nil
}
func readBody(b io.ReadCloser) ([]byte, error) {
defer b.Close()
return ioutil.ReadAll(b)
}
func deleteContainer(container string) error {
container = strings.TrimSpace(strings.Replace(container, "\n", " ", -1))
rmArgs := strings.Split(fmt.Sprintf("rm -fv %v", container), " ")
exitCode, err := runCommand(exec.Command(dockerBinary, rmArgs...))
// set error manually if not set
if exitCode != 0 && err == nil {
err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero")
}
return err
}
func getAllContainers() (string, error) {
getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a")
out, exitCode, err := runCommandWithOutput(getContainersCmd)
if exitCode != 0 && err == nil {
err = fmt.Errorf("failed to get a list of containers: %v\n", out)
}
return out, err
}
func deleteAllContainers() error {
containers, err := getAllContainers()
if err != nil {
fmt.Println(containers)
return err
}
if containers != "" {
if err = deleteContainer(containers); err != nil {
return err
}
}
return nil
}
func deleteAllNetworks() error {
networks, err := getAllNetworks()
if err != nil {
return err
}
var errors []string
for _, n := range networks {
if n.Name == "bridge" || n.Name == "none" || n.Name == "host" {
continue
}
status, b, err := sockRequest("DELETE", "/networks/"+n.Name, nil)
if err != nil {
errors = append(errors, err.Error())
continue
}
if status != http.StatusNoContent {
errors = append(errors, fmt.Sprintf("error deleting network %s: %s", n.Name, string(b)))
}
}
if len(errors) > 0 {
return fmt.Errorf(strings.Join(errors, "\n"))
}
return nil
}
func getAllNetworks() ([]types.NetworkResource, error) {
var networks []types.NetworkResource
_, b, err := sockRequest("GET", "/networks", nil)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &networks); err != nil {
return nil, err
}
return networks, nil
}
func deleteAllVolumes() error {
volumes, err := getAllVolumes()
if err != nil {
return err
}
var errors []string
for _, v := range volumes {
status, b, err := sockRequest("DELETE", "/volumes/"+v.Name, nil)
if err != nil {
errors = append(errors, err.Error())
continue
}
if status != http.StatusNoContent {
errors = append(errors, fmt.Sprintf("error deleting volume %s: %s", v.Name, string(b)))
}
}
if len(errors) > 0 {
return fmt.Errorf(strings.Join(errors, "\n"))
}
return nil
}
func getAllVolumes() ([]*types.Volume, error) {
var volumes types.VolumesListResponse
_, b, err := sockRequest("GET", "/volumes", nil)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &volumes); err != nil {
return nil, err
}
return volumes.Volumes, nil
}
var protectedImages = map[string]struct{}{}
func deleteAllImages() error {
cmd := exec.Command(dockerBinary, "images")
cmd.Env = appendBaseEnv(true)
out, err := cmd.CombinedOutput()
if err != nil {
return err
}
lines := strings.Split(string(out), "\n")[1:]
var imgs []string
for _, l := range lines {
if l == "" {
continue
}
fields := strings.Fields(l)
imgTag := fields[0] + ":" + fields[1]
if _, ok := protectedImages[imgTag]; !ok {
if fields[0] == "<none>" {
imgs = append(imgs, fields[2])
continue
}
imgs = append(imgs, imgTag)
}
}
if len(imgs) == 0 {
return nil
}
args := append([]string{"rmi", "-f"}, imgs...)
if err := exec.Command(dockerBinary, args...).Run(); err != nil {
return err
}
return nil
}
func getPausedContainers() (string, error) {
getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
out, exitCode, err := runCommandWithOutput(getPausedContainersCmd)
if exitCode != 0 && err == nil {
err = fmt.Errorf("failed to get a list of paused containers: %v\n", out)
}
return out, err
}
func getSliceOfPausedContainers() ([]string, error) {
out, err := getPausedContainers()
if err == nil {
if len(out) == 0 {
return nil, err
}
slice := strings.Split(strings.TrimSpace(out), "\n")
return slice, err
}
return []string{out}, err
}
func unpauseContainer(container string) error {
unpauseCmd := exec.Command(dockerBinary, "unpause", container)
exitCode, err := runCommand(unpauseCmd)
if exitCode != 0 && err == nil {
err = fmt.Errorf("failed to unpause container")
}
return nil
}
func unpauseAllContainers() error {
containers, err := getPausedContainers()
if err != nil {
fmt.Println(containers)
return err
}
containers = strings.Replace(containers, "\n", " ", -1)
containers = strings.Trim(containers, " ")
containerList := strings.Split(containers, " ")
for _, value := range containerList {
if err = unpauseContainer(value); err != nil {
return err
}
}
return nil
}
func deleteImages(images ...string) error {
args := []string{"rmi", "-f"}
args = append(args, images...)
rmiCmd := exec.Command(dockerBinary, args...)
exitCode, err := runCommand(rmiCmd)
// set error manually if not set
if exitCode != 0 && err == nil {
err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero")
}
return err
}
func imageExists(image string) error {
inspectCmd := exec.Command(dockerBinary, "inspect", image)
exitCode, err := runCommand(inspectCmd)
if exitCode != 0 && err == nil {
err = fmt.Errorf("couldn't find image %q", image)
}
return err
}
func pullImageIfNotExist(image string) error {
if err := imageExists(image); err != nil {
pullCmd := exec.Command(dockerBinary, "pull", image)
_, exitCode, err := runCommandWithOutput(pullCmd)
if err != nil || exitCode != 0 {
return fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err)
}
}
return nil
}
func dockerCmdWithError(args ...string) (string, int, error) {
if err := validateArgs(args...); err != nil {
return "", 0, err
}
return integration.DockerCmdWithError(dockerBinary, args...)
}
func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) {
if err := validateArgs(args...); err != nil {
c.Fatalf(err.Error())
}
return integration.DockerCmdWithStdoutStderr(dockerBinary, c, args...)
}
func dockerCmd(c *check.C, args ...string) (string, int) {
if err := validateArgs(args...); err != nil {
c.Fatalf(err.Error())
}
return integration.DockerCmd(dockerBinary, c, args...)
}
// execute a docker command with a timeout
func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) {
if err := validateArgs(args...); err != nil {
return "", 0, err
}
return integration.DockerCmdWithTimeout(dockerBinary, timeout, args...)
}
// execute a docker command in a directory
func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) {
if err := validateArgs(args...); err != nil {
c.Fatalf(err.Error())
}
return integration.DockerCmdInDir(dockerBinary, path, args...)
}
// execute a docker command in a directory with a timeout
func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) {
if err := validateArgs(args...); err != nil {
return "", 0, err
}
return integration.DockerCmdInDirWithTimeout(dockerBinary, timeout, path, args...)
}
// validateArgs is a checker to ensure tests are not running commands which are
// not supported on platforms. Specifically on Windows this is 'busybox top'.
func validateArgs(args ...string) error {
if daemonPlatform != "windows" {
return nil
}
foundBusybox := -1
for key, value := range args {
if strings.ToLower(value) == "busybox" {
foundBusybox = key
}
if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
return errors.New("Cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
}
}
return nil
}
// find the State.ExitCode in container metadata
func findContainerExitCode(c *check.C, name string, vargs ...string) string {
args := append(vargs, "inspect", "--format='{{ .State.ExitCode }} {{ .State.Error }}'", name)
cmd := exec.Command(dockerBinary, args...)
out, _, err := runCommandWithOutput(cmd)
if err != nil {
c.Fatal(err, out)
}
return out
}
func findContainerIP(c *check.C, id string, network string) string {
out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id)
return strings.Trim(out, " \r\n'")
}
func getContainerCount() (int, error) {
const containers = "Containers:"
cmd := exec.Command(dockerBinary, "info")
out, _, err := runCommandWithOutput(cmd)
if err != nil {
return 0, err
}
lines := strings.Split(out, "\n")
for _, line := range lines {
if strings.Contains(line, containers) {
output := strings.TrimSpace(line)
output = strings.TrimLeft(output, containers)
output = strings.Trim(output, " ")
containerCount, err := strconv.Atoi(output)
if err != nil {
return 0, err
}
return containerCount, nil
}
}
return 0, fmt.Errorf("couldn't find the Container count in the output")
}
// FakeContext creates directories that can be used as a build context
type FakeContext struct {
Dir string
}
// Add a file at a path, creating directories where necessary
func (f *FakeContext) Add(file, content string) error {
return f.addFile(file, []byte(content))
}
func (f *FakeContext) addFile(file string, content []byte) error {
filepath := path.Join(f.Dir, file)
dirpath := path.Dir(filepath)
if dirpath != "." {
if err := os.MkdirAll(dirpath, 0755); err != nil {
return err
}
}
return ioutil.WriteFile(filepath, content, 0644)
}
// Delete a file at a path
func (f *FakeContext) Delete(file string) error {
filepath := path.Join(f.Dir, file)
return os.RemoveAll(filepath)
}
// Close deletes the context
func (f *FakeContext) Close() error {
return os.RemoveAll(f.Dir)
}
func fakeContextFromNewTempDir() (*FakeContext, error) {
tmp, err := ioutil.TempDir("", "fake-context")
if err != nil {
return nil, err
}
if err := os.Chmod(tmp, 0755); err != nil {
return nil, err
}
return fakeContextFromDir(tmp), nil
}
func fakeContextFromDir(dir string) *FakeContext {
return &FakeContext{dir}
}
func fakeContextWithFiles(files map[string]string) (*FakeContext, error) {
ctx, err := fakeContextFromNewTempDir()
if err != nil {
return nil, err
}
for file, content := range files {
if err := ctx.Add(file, content); err != nil {
ctx.Close()
return nil, err
}
}
return ctx, nil
}
func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error {
if err := ctx.Add("Dockerfile", dockerfile); err != nil {
ctx.Close()
return err
}
return nil
}
func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) {
ctx, err := fakeContextWithFiles(files)
if err != nil {
return nil, err
}
if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
return nil, err
}
return ctx, nil
}
// FakeStorage is a static file server. It might be running locally or remotely
// on test host.
type FakeStorage interface {
Close() error
URL() string
CtxDir() string
}
func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) {
ctx, err := fakeContextFromNewTempDir()
if err != nil {
return nil, err
}
for name, content := range archives {
if err := ctx.addFile(name, content.Bytes()); err != nil {
return nil, err
}
}
return fakeStorageWithContext(ctx)
}
// fakeStorage returns either a local or remote (at daemon machine) file server
func fakeStorage(files map[string]string) (FakeStorage, error) {
ctx, err := fakeContextWithFiles(files)
if err != nil {
return nil, err
}
return fakeStorageWithContext(ctx)
}
// fakeStorageWithContext returns either a local or remote (at daemon machine) file server
func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) {
if isLocalDaemon {
return newLocalFakeStorage(ctx)
}
return newRemoteFileServer(ctx)
}
// localFileStorage is a file storage on the running machine
type localFileStorage struct {
*FakeContext
*httptest.Server
}
func (s *localFileStorage) URL() string {
return s.Server.URL
}
func (s *localFileStorage) CtxDir() string {
return s.FakeContext.Dir
}
func (s *localFileStorage) Close() error {
defer s.Server.Close()
return s.FakeContext.Close()
}
func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) {
handler := http.FileServer(http.Dir(ctx.Dir))
server := httptest.NewServer(handler)
return &localFileStorage{
FakeContext: ctx,
Server: server,
}, nil
}
// remoteFileServer is a containerized static file server started on the remote
// testing machine to be used in URL-accepting docker build functionality.
type remoteFileServer struct {
host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712
container string
image string
ctx *FakeContext
}
func (f *remoteFileServer) URL() string {
u := url.URL{
Scheme: "http",
Host: f.host}
return u.String()
}
func (f *remoteFileServer) CtxDir() string {
return f.ctx.Dir
}
func (f *remoteFileServer) Close() error {
defer func() {
if f.ctx != nil {
f.ctx.Close()
}
if f.image != "" {
deleteImages(f.image)
}
}()
if f.container == "" {
return nil
}
return deleteContainer(f.container)
}
func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) {
var (
image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10)))
)
// Build the image
if err := fakeContextAddDockerfile(ctx, `FROM httpserver
COPY . /static`); err != nil {
return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err)
}
if _, err := buildImageFromContext(image, ctx, false); err != nil {
return nil, fmt.Errorf("failed building file storage container image: %v", err)
}
// Start the container
runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image)
if out, ec, err := runCommandWithOutput(runCmd); err != nil {
return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err)
}
// Find out the system assigned port
out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp"))
if err != nil {
return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out)
}
fileserverHostPort := strings.Trim(out, "\n")
_, port, err := net.SplitHostPort(fileserverHostPort)
if err != nil {
return nil, fmt.Errorf("unable to parse file server host:port: %v", err)
}
dockerHostURL, err := url.Parse(daemonHost())
if err != nil {
return nil, fmt.Errorf("unable to parse daemon host URL: %v", err)
}
host, _, err := net.SplitHostPort(dockerHostURL.Host)
if err != nil {
return nil, fmt.Errorf("unable to parse docker daemon host:port: %v", err)
}
return &remoteFileServer{
container: container,
image: image,
host: fmt.Sprintf("%s:%s", host, port),
ctx: ctx}, nil
}
func inspectFieldAndMarshall(c *check.C, name, field string, output interface{}) {
str := inspectFieldJSON(c, name, field)
err := json.Unmarshal([]byte(str), output)
if c != nil {
c.Assert(err, check.IsNil, check.Commentf("failed to unmarshal: %v", err))
}
}
func inspectFilter(name, filter string) (string, error) {
format := fmt.Sprintf("{{%s}}", filter)
inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name)
out, exitCode, err := runCommandWithOutput(inspectCmd)
if err != nil || exitCode != 0 {
return "", fmt.Errorf("failed to inspect %s: %s", name, out)
}
return strings.TrimSpace(out), nil
}
func inspectFieldWithError(name, field string) (string, error) {
return inspectFilter(name, fmt.Sprintf(".%s", field))
}
func inspectField(c *check.C, name, field string) string {
out, err := inspectFilter(name, fmt.Sprintf(".%s", field))
if c != nil {
c.Assert(err, check.IsNil)
}
return out
}
func inspectFieldJSON(c *check.C, name, field string) string {
out, err := inspectFilter(name, fmt.Sprintf("json .%s", field))
if c != nil {
c.Assert(err, check.IsNil)
}
return out
}
func inspectFieldMap(c *check.C, name, path, field string) string {
out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field))
if c != nil {
c.Assert(err, check.IsNil)
}
return out
}
func inspectMountSourceField(name, destination string) (string, error) {
m, err := inspectMountPoint(name, destination)
if err != nil {
return "", err
}
return m.Source, nil
}
func inspectMountPoint(name, destination string) (types.MountPoint, error) {
out, err := inspectFilter(name, "json .Mounts")
if err != nil {
return types.MountPoint{}, err
}
return inspectMountPointJSON(out, destination)
}
var errMountNotFound = errors.New("mount point not found")
func inspectMountPointJSON(j, destination string) (types.MountPoint, error) {
var mp []types.MountPoint
if err := unmarshalJSON([]byte(j), &mp); err != nil {
return types.MountPoint{}, err
}
var m *types.MountPoint
for _, c := range mp {
if c.Destination == destination {
m = &c
break
}
}
if m == nil {
return types.MountPoint{}, errMountNotFound
}
return *m, nil
}
func inspectImage(name, filter string) (string, error) {
args := []string{"inspect", "--type", "image"}
if filter != "" {
format := fmt.Sprintf("{{%s}}", filter)
args = append(args, "-f", format)
}
args = append(args, name)
inspectCmd := exec.Command(dockerBinary, args...)
out, exitCode, err := runCommandWithOutput(inspectCmd)
if err != nil || exitCode != 0 {
return "", fmt.Errorf("failed to inspect %s: %s", name, out)
}
return strings.TrimSpace(out), nil
}
func getIDByName(name string) (string, error) {
return inspectFieldWithError(name, "Id")
}
// getContainerState returns the exit code of the container
// and true if it's running
// the exit code should be ignored if it's running
func getContainerState(c *check.C, id string) (int, bool, error) {
var (
exitStatus int
running bool
)
out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id)
if exitCode != 0 {
return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out)
}
out = strings.Trim(out, "\n")
splitOutput := strings.Split(out, " ")
if len(splitOutput) != 2 {
return 0, false, fmt.Errorf("failed to get container state: output is broken")
}
if splitOutput[0] == "true" {
running = true
}
if n, err := strconv.Atoi(splitOutput[1]); err == nil {
exitStatus = n
} else {
return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer")
}
return exitStatus, running, nil
}
func buildImageCmd(name, dockerfile string, useCache bool, buildFlags ...string) *exec.Cmd {
args := []string{"build", "-t", name}
if !useCache {
args = append(args, "--no-cache")
}
args = append(args, buildFlags...)
args = append(args, "-")
buildCmd := exec.Command(dockerBinary, args...)
buildCmd.Stdin = strings.NewReader(dockerfile)
return buildCmd
}
func buildImageWithOut(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, error) {
buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
out, exitCode, err := runCommandWithOutput(buildCmd)
if err != nil || exitCode != 0 {
return "", out, fmt.Errorf("failed to build the image: %s", out)
}
id, err := getIDByName(name)
if err != nil {
return "", out, err
}
return id, out, nil
}
func buildImageWithStdoutStderr(name, dockerfile string, useCache bool, buildFlags ...string) (string, string, string, error) {
buildCmd := buildImageCmd(name, dockerfile, useCache, buildFlags...)
stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd)
if err != nil || exitCode != 0 {
return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout)
}
id, err := getIDByName(name)
if err != nil {
return "", stdout, stderr, err
}
return id, stdout, stderr, nil
}
func buildImage(name, dockerfile string, useCache bool, buildFlags ...string) (string, error) {
id, _, err := buildImageWithOut(name, dockerfile, useCache, buildFlags...)
return id, err
}
func buildImageFromContext(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, error) {
id, _, err := buildImageFromContextWithOut(name, ctx, useCache, buildFlags...)
if err != nil {
return "", err
}
return id, nil
}
func buildImageFromContextWithOut(name string, ctx *FakeContext, useCache bool, buildFlags ...string) (string, string, error) {
args := []string{"build", "-t", name}
if !useCache {
args = append(args, "--no-cache")
}
args = append(args, buildFlags...)
args = append(args, ".")
buildCmd := exec.Command(dockerBinary, args...)
buildCmd.Dir = ctx.Dir
out, exitCode, err := runCommandWithOutput(buildCmd)
if err != nil || exitCode != 0 {