-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
2068 lines (1869 loc) · 56.7 KB
/
server.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 (
"encoding/json"
"errors"
"fmt"
"github.com/dotcloud/docker/archive"
"github.com/dotcloud/docker/auth"
"github.com/dotcloud/docker/engine"
"github.com/dotcloud/docker/pkg/graphdb"
"github.com/dotcloud/docker/registry"
"github.com/dotcloud/docker/utils"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
func (srv *Server) Close() error {
return srv.runtime.Close()
}
func init() {
engine.Register("initapi", jobInitApi)
}
// jobInitApi runs the remote api server `srv` as a daemon,
// Only one api server can run at the same time - this is enforced by a pidfile.
// The signals SIGINT, SIGQUIT and SIGTERM are intercepted for cleanup.
func jobInitApi(job *engine.Job) engine.Status {
job.Logf("Creating server")
// FIXME: ImportEnv deprecates ConfigFromJob
srv, err := NewServer(job.Eng, ConfigFromJob(job))
if err != nil {
job.Error(err)
return engine.StatusErr
}
if srv.runtime.config.Pidfile != "" {
job.Logf("Creating pidfile")
if err := utils.CreatePidFile(srv.runtime.config.Pidfile); err != nil {
// FIXME: do we need fatal here instead of returning a job error?
log.Fatal(err)
}
}
job.Logf("Setting up signal traps")
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
sig := <-c
log.Printf("Received signal '%v', exiting\n", sig)
utils.RemovePidFile(srv.runtime.config.Pidfile)
srv.Close()
os.Exit(0)
}()
job.Eng.Hack_SetGlobalVar("httpapi.server", srv)
job.Eng.Hack_SetGlobalVar("httpapi.runtime", srv.runtime)
// https://github.com/dotcloud/docker/issues/2768
if srv.runtime.networkManager.bridgeNetwork != nil {
job.Eng.Hack_SetGlobalVar("httpapi.bridgeIP", srv.runtime.networkManager.bridgeNetwork.IP)
}
if err := job.Eng.Register("export", srv.ContainerExport); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("create", srv.ContainerCreate); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("stop", srv.ContainerStop); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("start", srv.ContainerStart); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("kill", srv.ContainerKill); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("serveapi", srv.ListenAndServe); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("wait", srv.ContainerWait); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("tag", srv.ImageTag); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("resize", srv.ContainerResize); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("commit", srv.ContainerCommit); err != nil {
job.Error(err)
return engine.StatusErr
}
if err := job.Eng.Register("info", srv.DockerInfo); err != nil {
job.Error(err)
return engine.StatusErr
}
return engine.StatusOK
}
func (srv *Server) ListenAndServe(job *engine.Job) engine.Status {
protoAddrs := job.Args
chErrors := make(chan error, len(protoAddrs))
for _, protoAddr := range protoAddrs {
protoAddrParts := strings.SplitN(protoAddr, "://", 2)
switch protoAddrParts[0] {
case "unix":
if err := syscall.Unlink(protoAddrParts[1]); err != nil && !os.IsNotExist(err) {
log.Fatal(err)
}
case "tcp":
if !strings.HasPrefix(protoAddrParts[1], "127.0.0.1") {
log.Println("/!\\ DON'T BIND ON ANOTHER IP ADDRESS THAN 127.0.0.1 IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
}
default:
job.Errorf("Invalid protocol format.")
return engine.StatusErr
}
go func() {
// FIXME: merge Server.ListenAndServe with ListenAndServe
chErrors <- ListenAndServe(protoAddrParts[0], protoAddrParts[1], srv, job.GetenvBool("Logging"))
}()
}
for i := 0; i < len(protoAddrs); i += 1 {
err := <-chErrors
if err != nil {
job.Error(err)
return engine.StatusErr
}
}
return engine.StatusOK
}
// simpleVersionInfo is a simple implementation of
// the interface VersionInfo, which is used
// to provide version information for some product,
// component, etc. It stores the product name and the version
// in string and returns them on calls to Name() and Version().
type simpleVersionInfo struct {
name string
version string
}
func (v *simpleVersionInfo) Name() string {
return v.name
}
func (v *simpleVersionInfo) Version() string {
return v.version
}
// ContainerKill send signal to the container
// If no signal is given (sig 0), then Kill with SIGKILL and wait
// for the container to exit.
// If a signal is given, then just send it to the container and return.
func (srv *Server) ContainerKill(job *engine.Job) engine.Status {
if n := len(job.Args); n < 1 || n > 2 {
job.Errorf("Usage: %s CONTAINER [SIGNAL]", job.Name)
return engine.StatusErr
}
name := job.Args[0]
var sig uint64
if len(job.Args) == 2 && job.Args[1] != "" {
var err error
// The largest legal signal is 31, so let's parse on 5 bits
sig, err = strconv.ParseUint(job.Args[1], 10, 5)
if err != nil {
job.Errorf("Invalid signal: %s", job.Args[1])
return engine.StatusErr
}
}
if container := srv.runtime.Get(name); container != nil {
// If no signal is passed, perform regular Kill (SIGKILL + wait())
if sig == 0 {
if err := container.Kill(); err != nil {
job.Errorf("Cannot kill container %s: %s", name, err)
return engine.StatusErr
}
srv.LogEvent("kill", container.ID, srv.runtime.repositories.ImageName(container.Image))
} else {
// Otherwise, just send the requested signal
if err := container.kill(int(sig)); err != nil {
job.Errorf("Cannot kill container %s: %s", name, err)
return engine.StatusErr
}
// FIXME: Add event for signals
}
} else {
job.Errorf("No such container: %s", name)
return engine.StatusErr
}
return engine.StatusOK
}
func (srv *Server) ContainerExport(job *engine.Job) engine.Status {
if len(job.Args) != 1 {
job.Errorf("Usage: %s container_id", job.Name)
return engine.StatusErr
}
name := job.Args[0]
if container := srv.runtime.Get(name); container != nil {
data, err := container.Export()
if err != nil {
job.Errorf("%s: %s", name, err)
return engine.StatusErr
}
// Stream the entire contents of the container (basically a volatile snapshot)
if _, err := io.Copy(job.Stdout, data); err != nil {
job.Errorf("%s: %s", name, err)
return engine.StatusErr
}
// FIXME: factor job-specific LogEvent to engine.Job.Run()
srv.LogEvent("export", container.ID, srv.runtime.repositories.ImageName(container.Image))
return engine.StatusOK
}
job.Errorf("No such container: %s", name)
return engine.StatusErr
}
// ImageExport exports all images with the given tag. All versions
// containing the same tag are exported. The resulting output is an
// uncompressed tar ball.
// name is the set of tags to export.
// out is the writer where the images are written to.
func (srv *Server) ImageExport(name string, out io.Writer) error {
// get image json
tempdir, err := ioutil.TempDir("", "docker-export-")
if err != nil {
return err
}
defer os.RemoveAll(tempdir)
utils.Debugf("Serializing %s", name)
rootRepo, err := srv.runtime.repositories.Get(name)
if err != nil {
return err
}
if rootRepo != nil {
for _, id := range rootRepo {
image, err := srv.ImageInspect(id)
if err != nil {
return err
}
if err := srv.exportImage(image, tempdir); err != nil {
return err
}
}
// write repositories
rootRepoMap := map[string]Repository{}
rootRepoMap[name] = rootRepo
rootRepoJson, _ := json.Marshal(rootRepoMap)
if err := ioutil.WriteFile(path.Join(tempdir, "repositories"), rootRepoJson, os.ModeAppend); err != nil {
return err
}
} else {
image, err := srv.ImageInspect(name)
if err != nil {
return err
}
if err := srv.exportImage(image, tempdir); err != nil {
return err
}
}
fs, err := archive.Tar(tempdir, archive.Uncompressed)
if err != nil {
return err
}
if _, err := io.Copy(out, fs); err != nil {
return err
}
return nil
}
func (srv *Server) exportImage(image *Image, tempdir string) error {
for i := image; i != nil; {
// temporary directory
tmpImageDir := path.Join(tempdir, i.ID)
if err := os.Mkdir(tmpImageDir, os.ModeDir); err != nil {
if os.IsExist(err) {
return nil
}
return err
}
var version = "1.0"
var versionBuf = []byte(version)
if err := ioutil.WriteFile(path.Join(tmpImageDir, "VERSION"), versionBuf, os.ModeAppend); err != nil {
return err
}
// serialize json
b, err := json.Marshal(i)
if err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(tmpImageDir, "json"), b, os.ModeAppend); err != nil {
return err
}
// serialize filesystem
fs, err := i.TarLayer()
if err != nil {
return err
}
fsTar, err := os.Create(path.Join(tmpImageDir, "layer.tar"))
if err != nil {
return err
}
if _, err = io.Copy(fsTar, fs); err != nil {
return err
}
fsTar.Close()
// find parent
if i.Parent != "" {
i, err = srv.ImageInspect(i.Parent)
if err != nil {
return err
}
} else {
i = nil
}
}
return nil
}
// Loads a set of images into the repository. This is the complementary of ImageExport.
// The input stream is an uncompressed tar ball containing images and metadata.
func (srv *Server) ImageLoad(in io.Reader) error {
tmpImageDir, err := ioutil.TempDir("", "docker-import-")
if err != nil {
return err
}
defer os.RemoveAll(tmpImageDir)
var (
repoTarFile = path.Join(tmpImageDir, "repo.tar")
repoDir = path.Join(tmpImageDir, "repo")
)
tarFile, err := os.Create(repoTarFile)
if err != nil {
return err
}
if _, err := io.Copy(tarFile, in); err != nil {
return err
}
tarFile.Close()
repoFile, err := os.Open(repoTarFile)
if err != nil {
return err
}
if err := os.Mkdir(repoDir, os.ModeDir); err != nil {
return err
}
if err := archive.Untar(repoFile, repoDir, nil); err != nil {
return err
}
dirs, err := ioutil.ReadDir(repoDir)
if err != nil {
return err
}
for _, d := range dirs {
if d.IsDir() {
if err := srv.recursiveLoad(d.Name(), tmpImageDir); err != nil {
return err
}
}
}
repositoriesJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", "repositories"))
if err == nil {
repositories := map[string]Repository{}
if err := json.Unmarshal(repositoriesJson, &repositories); err != nil {
return err
}
for imageName, tagMap := range repositories {
for tag, address := range tagMap {
if err := srv.runtime.repositories.Set(imageName, tag, address, true); err != nil {
return err
}
}
}
} else if !os.IsNotExist(err) {
return err
}
return nil
}
func (srv *Server) recursiveLoad(address, tmpImageDir string) error {
if _, err := srv.ImageInspect(address); err != nil {
utils.Debugf("Loading %s", address)
imageJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", address, "json"))
if err != nil {
utils.Debugf("Error reading json", err)
return err
}
layer, err := os.Open(path.Join(tmpImageDir, "repo", address, "layer.tar"))
if err != nil {
utils.Debugf("Error reading embedded tar", err)
return err
}
img, err := NewImgJSON(imageJson)
if err != nil {
utils.Debugf("Error unmarshalling json", err)
return err
}
if img.Parent != "" {
if !srv.runtime.graph.Exists(img.Parent) {
if err := srv.recursiveLoad(img.Parent, tmpImageDir); err != nil {
return err
}
}
}
if err := srv.runtime.graph.Register(imageJson, layer, img); err != nil {
return err
}
}
utils.Debugf("Completed processing %s", address)
return nil
}
func (srv *Server) ImagesSearch(term string) ([]registry.SearchResult, error) {
r, err := registry.NewRegistry(nil, srv.HTTPRequestFactory(nil), auth.IndexServerAddress())
if err != nil {
return nil, err
}
results, err := r.SearchRepositories(term)
if err != nil {
return nil, err
}
return results.Results, nil
}
func (srv *Server) ImageInsert(name, url, path string, out io.Writer, sf *utils.StreamFormatter) error {
out = utils.NewWriteFlusher(out)
img, err := srv.runtime.repositories.LookupImage(name)
if err != nil {
return err
}
file, err := utils.Download(url)
if err != nil {
return err
}
defer file.Body.Close()
config, _, _, err := ParseRun([]string{img.ID, "echo", "insert", url, path}, srv.runtime.capabilities)
if err != nil {
return err
}
c, _, err := srv.runtime.Create(config, "")
if err != nil {
return err
}
if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, sf, false, "", "Downloading"), path); err != nil {
return err
}
// FIXME: Handle custom repo, tag comment, author
img, err = srv.runtime.Commit(c, "", "", img.Comment, img.Author, nil)
if err != nil {
return err
}
out.Write(sf.FormatStatus(img.ID, ""))
return nil
}
func (srv *Server) ImagesViz(out io.Writer) error {
images, _ := srv.runtime.graph.Map()
if images == nil {
return nil
}
out.Write([]byte("digraph docker {\n"))
var (
parentImage *Image
err error
)
for _, image := range images {
parentImage, err = image.GetParent()
if err != nil {
return fmt.Errorf("Error while getting parent image: %v", err)
}
if parentImage != nil {
out.Write([]byte(" \"" + parentImage.ID + "\" -> \"" + image.ID + "\"\n"))
} else {
out.Write([]byte(" base -> \"" + image.ID + "\" [style=invis]\n"))
}
}
reporefs := make(map[string][]string)
for name, repository := range srv.runtime.repositories.Repositories {
for tag, id := range repository {
reporefs[utils.TruncateID(id)] = append(reporefs[utils.TruncateID(id)], fmt.Sprintf("%s:%s", name, tag))
}
}
for id, repos := range reporefs {
out.Write([]byte(" \"" + id + "\" [label=\"" + id + "\\n" + strings.Join(repos, "\\n") + "\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n"))
}
out.Write([]byte(" base [style=invisible]\n}\n"))
return nil
}
func (srv *Server) Images(all bool, filter string) ([]APIImages, error) {
var (
allImages map[string]*Image
err error
)
if all {
allImages, err = srv.runtime.graph.Map()
} else {
allImages, err = srv.runtime.graph.Heads()
}
if err != nil {
return nil, err
}
lookup := make(map[string]APIImages)
for name, repository := range srv.runtime.repositories.Repositories {
if filter != "" {
if match, _ := path.Match(filter, name); !match {
continue
}
}
for tag, id := range repository {
image, err := srv.runtime.graph.Get(id)
if err != nil {
log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
continue
}
if out, exists := lookup[id]; exists {
out.RepoTags = append(out.RepoTags, fmt.Sprintf("%s:%s", name, tag))
lookup[id] = out
} else {
var out APIImages
delete(allImages, id)
out.ParentId = image.Parent
out.RepoTags = []string{fmt.Sprintf("%s:%s", name, tag)}
out.ID = image.ID
out.Created = image.Created.Unix()
out.Size = image.Size
out.VirtualSize = image.getParentsSize(0) + image.Size
lookup[id] = out
}
}
}
outs := make([]APIImages, 0, len(lookup))
for _, value := range lookup {
outs = append(outs, value)
}
// Display images which aren't part of a repository/tag
if filter == "" {
for _, image := range allImages {
var out APIImages
out.ID = image.ID
out.ParentId = image.Parent
out.RepoTags = []string{"<none>:<none>"}
out.Created = image.Created.Unix()
out.Size = image.Size
out.VirtualSize = image.getParentsSize(0) + image.Size
outs = append(outs, out)
}
}
sortImagesByCreationAndTag(outs)
return outs, nil
}
func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
images, _ := srv.runtime.graph.Map()
var imgcount int
if images == nil {
imgcount = 0
} else {
imgcount = len(images)
}
lxcVersion := ""
if output, err := exec.Command("lxc-version").CombinedOutput(); err == nil {
outputStr := string(output)
if len(strings.SplitN(outputStr, ":", 2)) == 2 {
lxcVersion = strings.TrimSpace(strings.SplitN(string(output), ":", 2)[1])
}
}
kernelVersion := "<unknown>"
if kv, err := utils.GetKernelVersion(); err == nil {
kernelVersion = kv.String()
}
// if we still have the original dockerinit binary from before we copied it locally, let's return the path to that, since that's more intuitive (the copied path is trivial to derive by hand given VERSION)
initPath := utils.DockerInitPath("")
if initPath == "" {
// if that fails, we'll just return the path from the runtime
initPath = srv.runtime.sysInitPath
}
v := &engine.Env{}
v.SetInt("Containers", len(srv.runtime.List()))
v.SetInt("Images", imgcount)
v.Set("Driver", srv.runtime.driver.String())
v.SetJson("DriverStatus", srv.runtime.driver.Status())
v.SetBool("MemoryLimit", srv.runtime.capabilities.MemoryLimit)
v.SetBool("SwapLimit", srv.runtime.capabilities.SwapLimit)
v.SetBool("IPv4Forwarding", !srv.runtime.capabilities.IPv4ForwardingDisabled)
v.SetBool("Debug", os.Getenv("DEBUG") != "")
v.SetInt("NFd", utils.GetTotalUsedFds())
v.SetInt("NGoroutines", runtime.NumGoroutine())
v.Set("LXCVersion", lxcVersion)
v.SetInt("NEventsListener", len(srv.events))
v.Set("KernelVersion", kernelVersion)
v.Set("IndexServerAddress", auth.IndexServerAddress())
v.Set("InitSha1", utils.INITSHA1)
v.Set("InitPath", initPath)
if _, err := v.WriteTo(job.Stdout); err != nil {
job.Error(err)
return engine.StatusErr
}
return engine.StatusOK
}
func (srv *Server) ImageHistory(name string) ([]APIHistory, error) {
image, err := srv.runtime.repositories.LookupImage(name)
if err != nil {
return nil, err
}
lookupMap := make(map[string][]string)
for name, repository := range srv.runtime.repositories.Repositories {
for tag, id := range repository {
// If the ID already has a reverse lookup, do not update it unless for "latest"
if _, exists := lookupMap[id]; !exists {
lookupMap[id] = []string{}
}
lookupMap[id] = append(lookupMap[id], name+":"+tag)
}
}
outs := []APIHistory{} //produce [] when empty instead of 'null'
err = image.WalkHistory(func(img *Image) error {
var out APIHistory
out.ID = img.ID
out.Created = img.Created.Unix()
out.CreatedBy = strings.Join(img.ContainerConfig.Cmd, " ")
out.Tags = lookupMap[img.ID]
out.Size = img.Size
outs = append(outs, out)
return nil
})
return outs, nil
}
func (srv *Server) ContainerTop(name, psArgs string) (*APITop, error) {
if container := srv.runtime.Get(name); container != nil {
if !container.State.IsRunning() {
return nil, fmt.Errorf("Container %s is not running", name)
}
pids, err := utils.GetPidsForContainer(container.ID)
if err != nil {
return nil, err
}
if len(psArgs) == 0 {
psArgs = "-ef"
}
output, err := exec.Command("ps", psArgs).Output()
if err != nil {
return nil, fmt.Errorf("Error running ps: %s", err)
}
lines := strings.Split(string(output), "\n")
header := strings.Fields(lines[0])
procs := APITop{
Titles: header,
}
pidIndex := -1
for i, name := range header {
if name == "PID" {
pidIndex = i
}
}
if pidIndex == -1 {
return nil, errors.New("Couldn't find PID field in ps output")
}
for _, line := range lines[1:] {
if len(line) == 0 {
continue
}
fields := strings.Fields(line)
p, err := strconv.Atoi(fields[pidIndex])
if err != nil {
return nil, fmt.Errorf("Unexpected pid '%s': %s", fields[pidIndex], err)
}
for _, pid := range pids {
if pid == p {
// Make sure number of fields equals number of header titles
// merging "overhanging" fields
processes := fields[:len(procs.Titles)-1]
processes = append(processes, strings.Join(fields[len(procs.Titles)-1:], " "))
procs.Processes = append(procs.Processes, processes)
}
}
}
return &procs, nil
}
return nil, fmt.Errorf("No such container: %s", name)
}
func (srv *Server) ContainerChanges(name string) ([]archive.Change, error) {
if container := srv.runtime.Get(name); container != nil {
return container.Changes()
}
return nil, fmt.Errorf("No such container: %s", name)
}
func (srv *Server) Containers(all, size bool, n int, since, before string) []APIContainers {
var foundBefore bool
var displayed int
out := []APIContainers{}
names := map[string][]string{}
srv.runtime.containerGraph.Walk("/", func(p string, e *graphdb.Entity) error {
names[e.ID()] = append(names[e.ID()], p)
return nil
}, -1)
for _, container := range srv.runtime.List() {
if !container.State.IsRunning() && !all && n == -1 && since == "" && before == "" {
continue
}
if before != "" && !foundBefore {
if container.ID == before || utils.TruncateID(container.ID) == before {
foundBefore = true
}
continue
}
if displayed == n {
break
}
if container.ID == since || utils.TruncateID(container.ID) == since {
break
}
displayed++
c := createAPIContainer(names[container.ID], container, size, srv.runtime)
out = append(out, c)
}
return out
}
func createAPIContainer(names []string, container *Container, size bool, runtime *Runtime) APIContainers {
c := APIContainers{
ID: container.ID,
}
c.Names = names
c.Image = runtime.repositories.ImageName(container.Image)
c.Command = fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
c.Created = container.Created.Unix()
c.Status = container.State.String()
c.Ports = container.NetworkSettings.PortMappingAPI()
if size {
c.SizeRw, c.SizeRootFs = container.GetSize()
}
return c
}
func (srv *Server) ContainerCommit(job *engine.Job) engine.Status {
if len(job.Args) != 1 {
job.Errorf("Not enough arguments. Usage: %s CONTAINER\n", job.Name)
return engine.StatusErr
}
name := job.Args[0]
container := srv.runtime.Get(name)
if container == nil {
job.Errorf("No such container: %s", name)
return engine.StatusErr
}
var config Config
if err := job.GetenvJson("config", &config); err != nil {
job.Error(err)
return engine.StatusErr
}
img, err := srv.runtime.Commit(container, job.Getenv("repo"), job.Getenv("tag"), job.Getenv("comment"), job.Getenv("author"), &config)
if err != nil {
job.Error(err)
return engine.StatusErr
}
job.Printf("%s\n", img.ID)
return engine.StatusOK
}
func (srv *Server) ImageTag(job *engine.Job) engine.Status {
if len(job.Args) != 2 && len(job.Args) != 3 {
job.Errorf("Usage: %s IMAGE REPOSITORY [TAG]\n", job.Name)
return engine.StatusErr
}
var tag string
if len(job.Args) == 3 {
tag = job.Args[2]
}
if err := srv.runtime.repositories.Set(job.Args[1], tag, job.Args[0], job.GetenvBool("force")); err != nil {
job.Error(err)
return engine.StatusErr
}
return engine.StatusOK
}
func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoint string, token []string, sf *utils.StreamFormatter) error {
history, err := r.GetRemoteHistory(imgID, endpoint, token)
if err != nil {
return err
}
out.Write(sf.FormatProgress(utils.TruncateID(imgID), "Pulling dependent layers", nil))
// FIXME: Try to stream the images?
// FIXME: Launch the getRemoteImage() in goroutines
for i := len(history) - 1; i >= 0; i-- {
id := history[i]
// ensure no two downloads of the same layer happen at the same time
if c, err := srv.poolAdd("pull", "layer:"+id); err != nil {
utils.Errorf("Image (id: %s) pull is already running, skipping: %v", id, err)
<-c
}
defer srv.poolRemove("pull", "layer:"+id)
if !srv.runtime.graph.Exists(id) {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Pulling metadata", nil))
imgJSON, imgSize, err := r.GetRemoteImageJSON(id, endpoint, token)
if err != nil {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Error pulling dependent layers", nil))
// FIXME: Keep going in case of error?
return err
}
img, err := NewImgJSON(imgJSON)
if err != nil {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Error pulling dependent layers", nil))
return fmt.Errorf("Failed to parse json: %s", err)
}
// Get the layer
out.Write(sf.FormatProgress(utils.TruncateID(id), "Pulling fs layer", nil))
layer, err := r.GetRemoteImageLayer(img.ID, endpoint, token)
if err != nil {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Error pulling dependent layers", nil))
return err
}
defer layer.Close()
if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf, false, utils.TruncateID(id), "Downloading"), img); err != nil {
out.Write(sf.FormatProgress(utils.TruncateID(id), "Error downloading dependent layers", nil))
return err
}
}
out.Write(sf.FormatProgress(utils.TruncateID(id), "Download complete", nil))
}
return nil
}
func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, localName, remoteName, askedTag string, sf *utils.StreamFormatter, parallel bool) error {
out.Write(sf.FormatStatus("", "Pulling repository %s", localName))
repoData, err := r.GetRepositoryData(remoteName)
if err != nil {
return err
}
utils.Debugf("Retrieving the tag list")
tagsList, err := r.GetRemoteTags(repoData.Endpoints, remoteName, repoData.Tokens)
if err != nil {
utils.Errorf("%v", err)
return err
}
for tag, id := range tagsList {
repoData.ImgList[id] = ®istry.ImgData{
ID: id,
Tag: tag,
Checksum: "",
}
}
utils.Debugf("Registering tags")
// If no tag has been specified, pull them all
if askedTag == "" {
for tag, id := range tagsList {
repoData.ImgList[id].Tag = tag
}
} else {
// Otherwise, check that the tag exists and use only that one
id, exists := tagsList[askedTag]
if !exists {
return fmt.Errorf("Tag %s not found in repository %s", askedTag, localName)
}
repoData.ImgList[id].Tag = askedTag
}
errors := make(chan error)
for _, image := range repoData.ImgList {
downloadImage := func(img *registry.ImgData) {
if askedTag != "" && img.Tag != askedTag {
utils.Debugf("(%s) does not match %s (id: %s), skipping", img.Tag, askedTag, img.ID)
if parallel {
errors <- nil
}
return
}
if img.Tag == "" {
utils.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID)
if parallel {
errors <- nil
}
return
}
// ensure no two downloads of the same image happen at the same time
if c, err := srv.poolAdd("pull", "img:"+img.ID); err != nil {
if c != nil {
out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Layer already being pulled by another client. Waiting.", nil))
<-c
out.Write(sf.FormatProgress(utils.TruncateID(img.ID), "Download complete", nil))
} else {
utils.Errorf("Image (id: %s) pull is already running, skipping: %v", img.ID, err)
}
if parallel {
errors <- nil
}
return
}
defer srv.poolRemove("pull", "img:"+img.ID)
out.Write(sf.FormatProgress(utils.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s", img.Tag, localName), nil))
success := false
var lastErr error
for _, ep := range repoData.Endpoints {
out.Write(sf.FormatProgress(utils.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, endpoint: %s", img.Tag, localName, ep), nil))
if err := srv.pullImage(r, out, img.ID, ep, repoData.Tokens, sf); err != nil {
// Its not ideal that only the last error is returned, it would be better to concatenate the errors.
// As the error is also given to the output stream the user will see the error.
lastErr = err
out.Write(sf.FormatProgress(utils.TruncateID(img.ID), fmt.Sprintf("Error pulling image (%s) from %s, endpoint: %s, %s", img.Tag, localName, ep, err), nil))
continue
}
success = true
break
}
if !success {
out.Write(sf.FormatProgress(utils.TruncateID(img.ID), fmt.Sprintf("Error pulling image (%s) from %s, %s", img.Tag, localName, lastErr), nil))