forked from hyperhq/hyperd
/
pod.go
1115 lines (915 loc) · 25.8 KB
/
pod.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 daemon
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/docker/docker/daemon/logger"
"github.com/docker/docker/daemon/logger/jsonfilelog"
"github.com/docker/docker/pkg/version"
dockertypes "github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/container"
"github.com/docker/engine-api/types/strslice"
"github.com/golang/glog"
"github.com/hyperhq/hyper/servicediscovery"
"github.com/hyperhq/hyper/utils"
"github.com/hyperhq/runv/hypervisor"
"github.com/hyperhq/runv/hypervisor/pod"
"github.com/hyperhq/runv/hypervisor/types"
)
func (daemon *Daemon) StartPod(stdin io.ReadCloser, stdout io.WriteCloser, podId, vmId, tag string) (int, string, error) {
// we can only support 1024 Pods
if daemon.GetRunningPodNum() >= 1024 {
return -1, "", fmt.Errorf("Pod full, the maximum Pod is 1024!")
}
var ttys []*hypervisor.TtyIO = []*hypervisor.TtyIO{}
if tag != "" {
glog.V(1).Info("Pod Run with client terminal tag: ", tag)
ttys = append(ttys, &hypervisor.TtyIO{
Stdin: stdin,
Stdout: stdout,
ClientTag: tag,
Callback: make(chan *types.VmResponse, 1),
})
}
glog.Infof("pod:%s, vm:%s", podId, vmId)
// Do the status check for the given pod
daemon.PodList.Lock()
glog.V(2).Infof("lock PodList")
p, ok := daemon.PodList.Get(podId)
if !ok {
glog.V(2).Infof("unlock PodList")
daemon.PodList.Unlock()
return -1, "", fmt.Errorf("The pod(%s) can not be found, please create it first", podId)
}
var lazy bool = hypervisor.HDriver.SupportLazyMode() && vmId == ""
code, cause, err := daemon.StartPodWithLock(p, vmId, nil, lazy, types.VM_KEEP_NONE, ttys)
if err != nil {
glog.Error(err.Error())
glog.V(2).Infof("unlock PodList")
daemon.PodList.Unlock()
return -1, "", err
}
glog.V(2).Infof("unlock PodList")
daemon.PodList.Unlock()
if len(ttys) > 0 {
p.RLock()
tty, ok := p.ttyList[tag]
p.RUnlock()
if ok {
tty.WaitForFinish()
}
}
return code, cause, nil
}
//create pod if not exist
func (daemon *Daemon) RunPod(podId, podArgs, vmId string, config interface{}, lazy, autoremove bool, keep int, streams []*hypervisor.TtyIO) (int, string, error) {
daemon.PodList.Lock()
glog.V(2).Infof("lock PodList")
defer glog.V(2).Infof("unlock PodList")
defer daemon.PodList.Unlock()
glog.V(1).Infof("podArgs: %s", podArgs)
p, err := daemon.GetPod(podId, podArgs, autoremove)
if err != nil {
return -1, "", err
}
return daemon.StartPodWithLock(p, vmId, config, lazy, keep, streams)
}
func (daemon *Daemon) StartPodWithLock(p *Pod, vmId string, config interface{}, lazy bool, keep int, streams []*hypervisor.TtyIO) (int, string, error) {
if p.vm != nil {
return -1, "", fmt.Errorf("pod %s is already running", p.id)
}
vmResponse, err := p.Start(daemon, vmId, lazy, keep, streams)
if err != nil {
return -1, "", err
}
return vmResponse.Code, vmResponse.Cause, nil
}
// I'd like to move the remain part of this file to another file.
type Pod struct {
id string
status *hypervisor.PodStatus
spec *pod.UserPod
vm *hypervisor.Vm
ctnStartInfo []*hypervisor.ContainerInfo
volumes []*hypervisor.VolumeInfo
ttyList map[string]*hypervisor.TtyIO
sync.RWMutex
}
func NewPod(rawSpec []byte, id string, data interface{}, autoremove bool) (*Pod, error) {
var err error
p := &Pod{
id: id,
ttyList: make(map[string]*hypervisor.TtyIO),
}
if p.spec, err = pod.ProcessPodBytes(rawSpec); err != nil {
glog.V(1).Infof("Process POD file error: %s", err.Error())
return nil, err
}
if err = p.init(data, autoremove); err != nil {
return nil, err
}
return p, nil
}
func (p *Pod) GetVM(daemon *Daemon, id string, lazy bool, keep int) (err error) {
if p == nil || p.spec == nil {
return errors.New("Pod: unable to create VM without resource info.")
}
p.vm, err = daemon.GetVM(id, &p.spec.Resource, lazy, keep)
return
}
func (p *Pod) SetVM(id string, vm *hypervisor.Vm) {
p.status.Vm = id
p.vm = vm
}
func (p *Pod) KillVM(daemon *Daemon) {
if p.vm != nil {
daemon.KillVm(p.vm.Id)
p.vm = nil
}
}
func (p *Pod) Status() *hypervisor.PodStatus {
return p.status
}
func (p *Pod) DoCreate(daemon *Daemon) error {
jsons, err := p.tryLoadContainers(daemon)
if err != nil {
return err
}
if err = p.createNewContainers(daemon, jsons); err != nil {
return err
}
if err = p.parseContainerJsons(daemon, jsons); err != nil {
return err
}
if err = p.createVolumes(daemon); err != nil {
return err
}
if err = p.updateContainerStatus(jsons); err != nil {
return err
}
return nil
}
func (daemon *Daemon) CreatePod(podId, podArgs string, autoremove bool) (*Pod, error) {
// we can only support 1024 Pods
if daemon.GetRunningPodNum() >= 1024 {
return nil, fmt.Errorf("Pod full, the maximum Pod is 1024!")
}
if podId == "" {
podId = fmt.Sprintf("pod-%s", pod.RandStr(10, "alpha"))
}
return daemon.createPodInternal(podId, podArgs, autoremove, false)
}
func (daemon *Daemon) createPodInternal(podId, podArgs string, autoremove, withinLock bool) (*Pod, error) {
glog.V(2).Infof("podArgs: %s", podArgs)
pod, err := NewPod([]byte(podArgs), podId, daemon, autoremove)
if err != nil {
return nil, err
}
// Creation
if err = pod.DoCreate(daemon); err != nil {
return nil, err
}
if !withinLock {
daemon.PodList.Lock()
glog.V(2).Infof("lock PodList")
defer glog.V(2).Infof("unlock PodList")
defer daemon.PodList.Unlock()
}
if err = daemon.AddPod(pod, podArgs); err != nil {
return nil, err
}
return pod, nil
}
func (daemon *Daemon) SetPodLabels(podId string, override bool, labels map[string]string) error {
daemon.PodList.RLock()
glog.V(2).Infof("lock read of PodList")
defer daemon.PodList.RUnlock()
defer glog.V(2).Infof("unlock read of PodList")
var pod *Pod
if strings.Contains(podId, "pod-") {
var ok bool
pod, ok = daemon.PodList.Get(podId)
if !ok {
return fmt.Errorf("Can not get Pod info with pod ID(%s)", podId)
}
} else {
pod = daemon.PodList.GetByName(podId)
if pod == nil {
return fmt.Errorf("Can not get Pod info with pod name(%s)", podId)
}
}
if pod.spec.Labels == nil {
pod.spec.Labels = make(map[string]string)
}
for k := range labels {
if _, ok := pod.spec.Labels[k]; ok && !override {
return fmt.Errorf("Can't update label %s without override", k)
}
}
for k, v := range labels {
pod.spec.Labels[k] = v
}
spec, err := json.Marshal(pod.spec)
if err != nil {
return err
}
if err := daemon.WritePodToDB(pod.id, spec); err != nil {
return err
}
return nil
}
func (p *Pod) init(data interface{}, autoremove bool) error {
if err := p.spec.Validate(); err != nil {
return err
}
if err := p.preprocess(); err != nil {
return err
}
resPath := filepath.Join(DefaultResourcePath, p.id)
if err := os.MkdirAll(resPath, os.FileMode(0755)); err != nil {
glog.Error("cannot create resource dir ", resPath)
return err
}
status := hypervisor.NewPod(p.id, p.spec)
status.Handler.Handle = hyperHandlePodEvent
status.Handler.Data = data
status.Autoremove = autoremove
status.ResourcePath = resPath
p.status = status
return nil
}
func (p *Pod) preprocess() error {
if p.spec == nil {
return fmt.Errorf("No spec available for preprocess: %s", p.id)
}
if err := ParseServiceDiscovery(p.id, p.spec); err != nil {
return err
}
if err := p.setupServices(); err != nil {
return err
}
if err := p.setupEtcHosts(); err != nil {
return err
}
if err := p.setupDNS(); err != nil {
glog.Warning("Fail to prepare DNS for %s: %v", p.id, err)
return err
}
return nil
}
func (p *Pod) tryLoadContainers(daemon *Daemon) ([]*dockertypes.ContainerJSON, error) {
var (
containerJsons = make([]*dockertypes.ContainerJSON, len(p.spec.Containers))
rsp *dockertypes.ContainerJSON
ok bool
)
if ids, _ := daemon.GetPodContainersByName(p.id); ids != nil {
containerNames := make(map[string]int)
for idx, c := range p.spec.Containers {
containerNames[c.Name] = idx
}
for _, id := range ids {
if r, err := daemon.ContainerInspect(id, false, version.Version("1.21")); err == nil {
rsp, ok = r.(*dockertypes.ContainerJSON)
if !ok {
if glog.V(1) {
glog.Warningf("fail to load container %s for pod %s", id, p.id)
}
continue
}
n := strings.TrimLeft(rsp.Name, "/")
if idx, ok := containerNames[n]; ok {
glog.V(1).Infof("Found exist container %s (%s), pod: %s", n, id, p.id)
containerJsons[idx] = rsp
} else if glog.V(1) {
glog.Warningf("loaded container %s (%s) is not belongs to pod %s", n, id, p.id)
}
}
}
}
return containerJsons, nil
}
func (p *Pod) createNewContainers(daemon *Daemon, jsons []*dockertypes.ContainerJSON) error {
var (
ok bool
err error
ccs dockertypes.ContainerCreateResponse
rsp *dockertypes.ContainerJSON
r interface{}
cleanup = func(id string) {
if err != nil {
glog.V(1).Infof("rollback container %s of %s", id, p.id)
daemon.Daemon.ContainerRm(id, &dockertypes.ContainerRmConfig{})
}
}
)
for idx, c := range p.spec.Containers {
if jsons[idx] != nil {
glog.V(1).Infof("do not need to create container %s of pod %s[%d]", c.Name, p.id, idx)
continue
}
config := &container.Config{
Image: c.Image,
Cmd: strslice.New(c.Command...),
NetworkDisabled: true,
}
if len(c.Entrypoint) != 0 {
config.Entrypoint = strslice.New(c.Entrypoint...)
}
ccs, err = daemon.Daemon.ContainerCreate(dockertypes.ContainerCreateConfig{
Name: c.Name,
Config: config,
})
if err != nil {
glog.Error(err.Error())
return err
}
defer cleanup(ccs.ID)
glog.Infof("create container %s", ccs.ID)
if r, err = daemon.ContainerInspect(ccs.ID, false, version.Version("1.21")); err != nil {
return err
}
if rsp, ok = r.(*dockertypes.ContainerJSON); !ok {
err = fmt.Errorf("fail to unpack container json response for %s of %s", c.Name, p.id)
return err
}
jsons[idx] = rsp
}
return nil
}
func (p *Pod) parseContainerJsons(daemon *Daemon, jsons []*dockertypes.ContainerJSON) (err error) {
err = nil
p.ctnStartInfo = []*hypervisor.ContainerInfo{}
for i, c := range p.spec.Containers {
if jsons[i] == nil {
estr := fmt.Sprintf("container %s of pod %s does not have inspect json", c.Name, p.id)
glog.Error(estr)
return errors.New(estr)
}
var (
info *dockertypes.ContainerJSON = jsons[i]
ci *hypervisor.ContainerInfo = &hypervisor.ContainerInfo{}
)
if c.Name == "" {
c.Name = strings.TrimLeft(info.Name, "/")
}
if c.Image == "" {
c.Image = info.Config.Image
}
glog.Infof("container name %s, image %s", c.Name, c.Image)
mountId, err := GetMountIdByContainer(daemon.Storage.Type(), info.ID)
if err != nil {
estr := fmt.Sprintf("Cannot find mountID for container %s : %s", info.ID, err)
glog.Error(estr)
return errors.New(estr)
}
ci.Id = mountId
ci.Workdir = info.Config.WorkingDir
ci.Cmd = append([]string{info.Path}, info.Args...)
// We should ignore these two in runv, instead of clear them, but here is a work around
p.spec.Containers[i].Entrypoint = []string{}
p.spec.Containers[i].Command = []string{}
glog.Infof("container info config %v, Cmd %v, Args %v", info.Config, info.Config.Cmd.Slice(), info.Args)
env := make(map[string]string)
for _, v := range info.Config.Env {
env[v[:strings.Index(v, "=")]] = v[strings.Index(v, "=")+1:]
}
for _, e := range p.spec.Containers[i].Envs {
env[e.Env] = e.Value
}
ci.Envs = env
processImageVolumes(info, info.ID, p.spec, &p.spec.Containers[i])
p.ctnStartInfo = append(p.ctnStartInfo, ci)
glog.V(1).Infof("Container Info is \n%v", ci)
}
return nil
}
func GetMountIdByContainer(driver, cid string) (string, error) {
idPath := path.Join(utils.HYPER_ROOT, fmt.Sprintf("image/%s/layerdb/mounts/%s/mount-id", driver, cid))
if _, err := os.Stat(idPath); err != nil && os.IsNotExist(err) {
return "", err
}
id, err := ioutil.ReadFile(idPath)
if err != nil {
return "", err
}
return string(id), nil
}
func (p *Pod) createVolumes(daemon *Daemon) error {
var (
vol *hypervisor.VolumeInfo
err error
)
sd := daemon.Storage
for i := range p.spec.Volumes {
if p.spec.Volumes[i].Source == "" {
vol, err = sd.CreateVolume(daemon, p.id, p.spec.Volumes[i].Name)
if err != nil {
return err
}
p.spec.Volumes[i].Source = vol.Filepath
if sd.Type() != "devicemapper" {
p.spec.Volumes[i].Driver = "vfs"
} else {
// type other than doesn't need to be mounted
p.spec.Volumes[i].Driver = "raw"
}
}
}
return nil
}
func (p *Pod) updateContainerStatus(jsons []*dockertypes.ContainerJSON) error {
p.status.Containers = []*hypervisor.Container{}
for idx, c := range p.spec.Containers {
if jsons[idx] == nil {
estr := fmt.Sprintf("container %s of pod %s does not have inspect json", c.Name, p.id)
glog.Error(estr)
return errors.New(estr)
}
cmds := append([]string{jsons[idx].Path}, jsons[idx].Args...)
p.status.AddContainer(jsons[idx].ID, "/"+c.Name, jsons[idx].Image, cmds, types.S_POD_CREATED)
}
return nil
}
func processInjectFiles(container *pod.UserContainer, files map[string]pod.UserFile, sd Storage,
id, rootPath, sharedDir string) error {
for _, f := range container.Files {
targetPath := f.Path
if strings.HasSuffix(targetPath, "/") {
targetPath = targetPath + f.Filename
}
file, ok := files[f.Filename]
if !ok {
continue
}
var src io.Reader
if file.Uri != "" {
urisrc, err := utils.UriReader(file.Uri)
if err != nil {
return err
}
defer urisrc.Close()
src = urisrc
} else {
src = strings.NewReader(file.Contents)
}
switch file.Encoding {
case "base64":
src = base64.NewDecoder(base64.StdEncoding, src)
default:
}
err := sd.InjectFile(src, id, targetPath, sharedDir,
utils.PermInt(f.Perm), utils.UidInt(f.User), utils.UidInt(f.Group))
if err != nil {
glog.Error("got error when inject files ", err.Error())
return err
}
}
return nil
}
func processImageVolumes(config *dockertypes.ContainerJSON, id string, userPod *pod.UserPod, container *pod.UserContainer) {
if config.Config.Volumes == nil {
return
}
existed := make(map[string]bool)
for _, v := range container.Volumes {
existed[v.Path] = true
}
for tgt := range config.Config.Volumes {
if _, ok := existed[tgt]; ok {
continue
}
n := id + strings.Replace(tgt, "/", "_", -1)
v := pod.UserVolume{
Name: n,
Source: "",
}
r := pod.UserVolumeReference{
Volume: n,
Path: tgt,
ReadOnly: false,
}
userPod.Volumes = append(userPod.Volumes, v)
container.Volumes = append(container.Volumes, r)
}
}
func (p *Pod) setupServices() error {
err := servicediscovery.PrepareServices(p.spec, p.id)
if err != nil {
glog.Errorf("PrepareServices failed %s", err.Error())
}
return err
}
// PrepareEtcHosts sets /etc/hosts for each container
func (p *Pod) setupEtcHosts() (err error) {
var (
hostsVolumeName = "etchosts-volume"
hostVolumePath = ""
hostsPath = "/etc/hosts"
)
if p.spec == nil {
return
}
for idx, c := range p.spec.Containers {
insert := true
for _, v := range c.Volumes {
if v.Path == hostsPath {
insert = false
break
}
}
for _, f := range c.Files {
if f.Path == hostsPath {
insert = false
break
}
}
if !insert {
continue
}
if hostVolumePath == "" {
hostVolumePath, err = prepareHosts(p.id)
if err != nil {
return
}
p.spec.Volumes = append(p.spec.Volumes, pod.UserVolume{
Name: hostsVolumeName,
Source: hostVolumePath,
Driver: "vfs",
})
}
p.spec.Containers[idx].Volumes = append(c.Volumes, pod.UserVolumeReference{
Path: hostsPath,
Volume: hostsVolumeName,
ReadOnly: false,
})
}
return
}
/***
PrepareDNS() Set the resolv.conf of host to each container, except the following cases:
- if the pod has a `dns` field with values, the pod will follow the dns setup, and daemon
won't insert resolv.conf file into any containers
- if the pod has a `file` which source is uri "file:///etc/resolv.conf", this mean the user
will handle this file by himself/herself, daemon won't touch the dns setting even if the file
is not referenced by any containers. This could be a method to prevent the daemon from unwanted
setting the dns configuration
- if a container has a file config in the pod spec with `/etc/resolv.conf` as target `path`,
then this container won't be set as the file from hosts. Then a user can specify the content
of the file.
*/
func (p *Pod) setupDNS() (err error) {
err = nil
var (
resolvconf = "/etc/resolv.conf"
fileId = p.id + "-resolvconf"
)
if p.spec == nil {
estr := "No Spec available for insert a DNS configuration"
glog.V(1).Info(estr)
err = fmt.Errorf(estr)
return
}
if len(p.spec.Dns) > 0 {
glog.V(1).Info("Already has DNS config, bypass DNS insert")
return
}
if stat, e := os.Stat(resolvconf); e != nil || !stat.Mode().IsRegular() {
glog.V(1).Info("Host resolv.conf is not exist or not a regular file, do not insert DNS conf")
return
}
for _, src := range p.spec.Files {
if src.Uri == "file:///etc/resolv.conf" {
glog.V(1).Info("Already has resolv.conf configured, bypass DNS insert")
return
}
}
p.spec.Files = append(p.spec.Files, pod.UserFile{
Name: fileId,
Encoding: "raw",
Uri: "file://" + resolvconf,
})
for idx, c := range p.spec.Containers {
insert := true
for _, f := range c.Files {
if f.Path == resolvconf {
insert = false
break
}
}
if !insert {
continue
}
p.spec.Containers[idx].Files = append(c.Files, pod.UserFileReference{
Path: resolvconf,
Filename: fileId,
Perm: "0644",
})
}
return
}
func (p *Pod) setupMountsAndFiles(sd Storage) (err error) {
if len(p.ctnStartInfo) != len(p.spec.Containers) {
estr := fmt.Sprintf("Prepare error, pod %s does not get container infos well", p.id)
glog.Error(estr)
err = errors.New(estr)
return err
}
var (
sharedDir = path.Join(hypervisor.BaseDir, p.vm.Id, hypervisor.ShareDirTag)
files = make(map[string](pod.UserFile))
)
for _, f := range p.spec.Files {
files[f.Name] = f
}
for i, c := range p.status.Containers {
var (
ci *hypervisor.ContainerInfo
)
mountId := p.ctnStartInfo[i].Id
glog.Infof("container ID: %s, mountId %s\n", c.Id, mountId)
ci, err = sd.PrepareContainer(mountId, sharedDir)
if err != nil {
return err
}
err = processInjectFiles(&p.spec.Containers[i], files, sd, mountId, sd.RootPath(), sharedDir)
if err != nil {
return err
}
ci.Id = c.Id
ci.Cmd = p.ctnStartInfo[i].Cmd
ci.Envs = p.ctnStartInfo[i].Envs
ci.Entrypoint = p.ctnStartInfo[i].Entrypoint
ci.Workdir = p.ctnStartInfo[i].Workdir
p.ctnStartInfo[i] = ci
}
return nil
}
func (p *Pod) mountVolumes(daemon *Daemon, sd Storage) (err error) {
err = nil
p.volumes = []*hypervisor.VolumeInfo{}
var (
sharedDir = path.Join(hypervisor.BaseDir, p.vm.Id, hypervisor.ShareDirTag)
)
for _, v := range p.spec.Volumes {
var vol *hypervisor.VolumeInfo
if v.Source == "" {
err = fmt.Errorf("volume %s in pod %s is not created", v.Name, p.id)
return err
}
vol, err = ProbeExistingVolume(&v, sharedDir)
if err != nil {
return err
}
p.volumes = append(p.volumes, vol)
}
return nil
}
func (p *Pod) Prepare(daemon *Daemon) (err error) {
if err = p.setupMountsAndFiles(daemon.Storage); err != nil {
return
}
if err = p.mountVolumes(daemon, daemon.Storage); err != nil {
return
}
return nil
}
func stopLogger(mypod *hypervisor.PodStatus) {
for _, c := range mypod.Containers {
if c.Logs.Driver == nil {
continue
}
c.Logs.Driver.Close()
}
}
func (p *Pod) getLogger(daemon *Daemon) (err error) {
if p.spec.LogConfig.Type == "" {
p.spec.LogConfig.Type = daemon.DefaultLog.Type
p.spec.LogConfig.Config = daemon.DefaultLog.Config
}
if p.spec.LogConfig.Type == "none" {
return nil
}
var (
needLogger []int = []int{}
creator logger.Creator
)
for i, c := range p.status.Containers {
if c.Logs.Driver == nil {
needLogger = append(needLogger, i)
}
}
if len(needLogger) == 0 && p.status.Status == types.S_POD_RUNNING {
return nil
}
if err = logger.ValidateLogOpts(p.spec.LogConfig.Type, p.spec.LogConfig.Config); err != nil {
return
}
creator, err = logger.GetLogDriver(p.spec.LogConfig.Type)
if err != nil {
return
}
glog.V(1).Infof("configuring log driver [%s] for %s", p.spec.LogConfig.Type, p.id)
for i, c := range p.status.Containers {
ctx := logger.Context{
Config: p.spec.LogConfig.Config,
ContainerID: c.Id,
ContainerName: c.Name,
ContainerImageName: p.spec.Containers[i].Image,
ContainerCreated: time.Now(), //FIXME: should record creation time in PodStatus
}
if p.ctnStartInfo != nil && len(p.ctnStartInfo) > i {
ctx.ContainerEntrypoint = p.ctnStartInfo[i].Workdir
ctx.ContainerArgs = p.ctnStartInfo[i].Cmd
ctx.ContainerImageID = p.ctnStartInfo[i].Image
}
if p.spec.LogConfig.Type == jsonfilelog.Name {
ctx.LogPath = filepath.Join(p.status.ResourcePath, fmt.Sprintf("%s-json.log", c.Id))
glog.V(1).Info("configure container log to ", ctx.LogPath)
}
if c.Logs.Driver, err = creator(ctx); err != nil {
return
}
glog.V(1).Infof("configured logger for %s/%s (%s)", p.id, c.Id, c.Name)
}
return nil
}
func (p *Pod) startLogging(daemon *Daemon) (err error) {
err = nil
if err = p.getLogger(daemon); err != nil {
return
}
if p.spec.LogConfig.Type == "none" {
return nil
}
for _, c := range p.status.Containers {
var stdout, stderr io.Reader
tag := "log-" + utils.RandStr(8, "alphanum")
if stdout, stderr, err = p.vm.GetLogOutput(c.Id, tag, nil); err != nil {
return
}
c.Logs.Copier = logger.NewCopier(c.Id, map[string]io.Reader{"stdout": stdout, "stderr": stderr}, c.Logs.Driver)
c.Logs.Copier.Run()
if jl, ok := c.Logs.Driver.(*jsonfilelog.JSONFileLogger); ok {
c.Logs.LogPath = jl.LogPath()
}
}
return nil
}
func (p *Pod) AttachTtys(daemon *Daemon, streams []*hypervisor.TtyIO) (err error) {
ttyContainers := p.ctnStartInfo
if p.spec.Type == "service-discovery" {
ttyContainers = p.ctnStartInfo[1:]
}
for idx, str := range streams {
if idx >= len(ttyContainers) {
break
}
p.Lock()
p.ttyList[str.ClientTag] = str
p.Unlock()
err = p.vm.Attach(str, ttyContainers[idx].Id, nil)
if err != nil {
glog.Errorf("Failed to attach client %s before start pod", str.ClientTag)
return
}
glog.V(1).Infof("Attach client %s before start pod", str.ClientTag)
}
return nil
}
func (p *Pod) Start(daemon *Daemon, vmId string, lazy bool, keep int, streams []*hypervisor.TtyIO) (*types.VmResponse, error) {
var (
err error = nil
preparing bool = true
)
if p.status.Status == types.S_POD_RUNNING ||
(p.status.Type == "kubernetes" && p.status.Status != types.S_POD_CREATED) {
estr := fmt.Sprintf("invalid pod status for start %v", p.status.Status)
glog.Warning(estr)
return nil, errors.New(estr)
}
if err = p.GetVM(daemon, vmId, lazy, keep); err != nil {
return nil, err
}
defer func() {
if err != nil && preparing && vmId == "" {
p.KillVM(daemon)
}
}()
if err = p.Prepare(daemon); err != nil {
return nil, err
}
if err = p.startLogging(daemon); err != nil {
return nil, err
}