forked from sandia-minimega/minimega
/
container.go
1850 lines (1565 loc) · 45.9 KB
/
container.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
// Copyright 2015-2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain
// rights in this software.
// NOTES:
// debian hosts need 'cgroup_enable=memory' added to the kernel command line.
// See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534964
//
// posix capabilities. See:
// linux/include/linux/capability.h
// https://github.com/torvalds/linux/blob/master/include/linux/capability.h
// https://github.com/torvalds/linux/blob/master/include/uapi/linux/capability.h
//
// includes code from:
// https://github.com/syndtr/gocapability/blob/master/capability/capability_linux.go
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
log "minilog"
"net"
"os"
"os/exec"
"path/filepath"
"ron"
"strconv"
"strings"
"sync"
"syscall"
"text/tabwriter"
"time"
"unsafe"
"github.com/kr/pty"
)
const (
CONTAINER_MAGIC = "CONTAINER"
CONTAINER_NONE = "CONTAINER_NONE"
CONTAINER_KILL_TIMEOUT = 5 * time.Second
// UnmountRetries is the maximum number of times to try to unmount a busy
// filesystem.
UnmountRetries = 10
)
const (
CAP_CHOWN = uint64(1) << 0
CAP_DAC_OVERRIDE = uint64(1) << 1
CAP_DAC_READ_SEARCH = uint64(1) << 2
CAP_FOWNER = uint64(1) << 3
CAP_FSETID = uint64(1) << 4
CAP_KILL = uint64(1) << 5
CAP_SETGID = uint64(1) << 6
CAP_SETUID = uint64(1) << 7
CAP_SETPCAP = uint64(1) << 8
CAP_LINUX_IMMUTABLE = uint64(1) << 9
CAP_NET_BIND_SERVICE = uint64(1) << 10
CAP_NET_BROADCAST = uint64(1) << 11
CAP_NET_ADMIN = uint64(1) << 12
CAP_NET_RAW = uint64(1) << 13
CAP_IPC_LOCK = uint64(1) << 14
CAP_IPC_OWNDER = uint64(1) << 15
CAP_SYS_MODULE = uint64(1) << 16
CAP_SYS_RAWIO = uint64(1) << 17
CAP_SYS_CHROOT = uint64(1) << 18
CAP_SYS_PTRACE = uint64(1) << 19
CAP_SYS_PACCT = uint64(1) << 20
CAP_SYS_ADMIN = uint64(1) << 21
CAP_SYS_BOOT = uint64(1) << 22
CAP_SYS_NICE = uint64(1) << 23
CAP_SYS_RESOURCE = uint64(1) << 24
CAP_SYS_TIME = uint64(1) << 25
CAP_SYS_TTY_CONFIG = uint64(1) << 26
CAP_MKNOD = uint64(1) << 27
CAP_LEASE = uint64(1) << 28
CAP_AUDIT_WRITE = uint64(1) << 29
CAP_AUDIT_CONTROL = uint64(1) << 30
CAP_SETFCAP = uint64(1) << 31
CAP_MAC_OVERRIDE = uint64(1) << 32
CAP_MAC_ADMIN = uint64(1) << 33
CAP_SYSLOG = uint64(1) << 34
CAP_WAKE_ALARM = uint64(1) << 35
CAP_BLOCK_SUSPEND = uint64(1) << 36
CAP_AUDIT_READ = uint64(1) << 37
CAP_LAST_CAP = 37
)
const (
CAPV3 = 0x20080522
)
// DEFAULT_CAPS represents capabilities necessary for a full-system container
// and nothing more
const (
DEFAULT_CAPS = CAP_CHOWN | CAP_DAC_OVERRIDE | CAP_FSETID | CAP_FOWNER | CAP_MKNOD | CAP_NET_RAW | CAP_SETGID | CAP_SETUID | CAP_SETFCAP | CAP_SETPCAP | CAP_NET_BIND_SERVICE | CAP_SYS_CHROOT | CAP_KILL | CAP_AUDIT_WRITE | CAP_NET_ADMIN | CAP_DAC_READ_SEARCH | CAP_AUDIT_CONTROL
)
type capHeader struct {
version uint32
pid int
}
type capData struct {
effective uint32
permitted uint32
inheritable uint32
}
// only bother with version 3
type cap struct {
header capHeader
data [2]capData
bounds [2]uint32
}
const CONTAINER_FLAGS = syscall.CLONE_NEWNET | syscall.CLONE_NEWIPC | syscall.CLONE_NEWNS | syscall.CLONE_NEWPID | syscall.CLONE_NEWUTS | syscall.CLONE_VFORK | syscall.SIGCHLD
var containerMaskedPaths = []string{
"/proc/kcore",
}
var containerReadOnlyPaths = []string{
"/proc/sys",
"/proc/sysrq-trigger",
"/proc/irq",
"/proc/bus",
}
var containerUUIDLink = "/sys/devices/virtual/dmi/id/product_uuid"
var containerLinks = [][2]string{
{"/proc/self/fd", "/dev/fd"},
{"/proc/self/0", "/dev/stdin"},
{"/proc/self/1", "/dev/stdout"},
{"/proc/self/2", "/dev/stderr"},
}
var containerDevices []string = []string{
"c 1:3 rwm", // null
"c 1:5 rwm", // zero
"c 1:7 rwm", // full
"c 5:0 rwm", // tty
"c 1:8 rwm", // random
"c 1:9 rwm", // urandom
"c *:* m", // mknod any character dev
"b *:* m", // mknod and block dev
"c 5:1 rwm", // /dev/console
"c 4:0 rwm", // /dev/tty0
"c 4:1 rwm", // /dev/tty1
"c 136:* rwm", // pts
"c 5:2 rwm", // ptmx
"c 10:200 rwm", // ?
}
type Dev struct {
Name string
Major int
Minor int
Type string
Mode int
}
var containerDeviceNames []*Dev = []*Dev{
&Dev{
Name: "/dev/null",
Major: 1,
Minor: 3,
Type: "c",
Mode: 438,
},
&Dev{
Name: "/dev/zero",
Major: 1,
Minor: 5,
Type: "c",
Mode: 438,
},
&Dev{
Name: "/dev/full",
Major: 1,
Minor: 7,
Type: "c",
Mode: 438,
},
&Dev{
Name: "/dev/tty",
Major: 5,
Minor: 0,
Type: "c",
Mode: 438,
},
&Dev{
Name: "/dev/random",
Major: 1,
Minor: 8,
Type: "c",
Mode: 438,
},
&Dev{
Name: "/dev/urandom",
Major: 1,
Minor: 9,
Type: "c",
Mode: 438,
},
}
type ContainerConfig struct {
// Configure the filesystem to use for launching a container. This should
// be a root filesystem for a linux distribution (containing /dev, /proc,
// /sys, etc.)
//
// Note: this configuration only applies to containers and must be specified.
FilesystemPath string
// Set a hostname for a container before launching the init program. If not
// set, the hostname will be the VM name. The hostname can also be set by
// the init program or other root process in the container.
//
// Note: this configuration only applies to containers.
Hostname string
// Set the init program and args to exec into upon container launch. This
// will be PID 1 in the container.
//
// Note: this configuration only applies to containers.
//
// Default: "/init"
Init []string
// Containers start in a highly restricted environment. vm config preinit
// allows running processes before isolation mechanisms are enabled. This
// occurs when the vm is launched and before the vm is put in the building
// state. preinit processes must finish before the vm will be allowed to
// start.
//
// Specifically, the preinit command will be run after entering namespaces,
// and mounting dependent filesystems, but before cgroups and root
// capabilities are set, and before entering the chroot. This means that
// the preinit command is run as root and can control the host.
//
// For example, to run a script that enables ip forwarding, which is not
// allowed during runtime because /proc is mounted read-only, add a preinit
// script:
//
// vm config preinit enable_ip_forwarding.sh
//
// Note: this configuration only applies to containers.
Preinit string
// Set the number of named pipes to include in the container for
// container-host communication. Named pipes will appear on the host in the
// instance directory for the container as fifoN, and on the container as
// /dev/fifos/fifoN.
//
// Fifos are created using mkfifo() and have all of the same usage
// constraints.
//
// Note: this configuration only applies to containers.
Fifos uint64
// Attach one or more volumes to a container. These directories will be
// mounted inside the container at the specified location.
//
// For example, to mount /scratch/data to /data inside the container:
//
// vm config volume /data /scratch/data
//
// Commands with the same <key> will overwrite previous volumes:
//
// vm config volume /data /scratch/data2
// vm config volume /data
// /scratch/data2
//
// Note: this configuration only applies to containers.
VolumePaths map[string]string
}
type ContainerVM struct {
*BaseVM // embed
ContainerConfig // embed
effectivePath string
ptyUnixListener net.Listener
ptyTCPListener net.Listener
netns string
ConsolePort int
scrollBack *byteFifo
consoleMultiWriter *mutableMultiWriter
}
// Ensure that ContainerVM implements the VM interface
var _ VM = (*ContainerVM)(nil)
var (
containerInitLock sync.Mutex
containerInitOnce bool
containerInitSuccess bool
)
func containerInit() error {
containerInitLock.Lock()
defer containerInitLock.Unlock()
if containerInitOnce {
return nil
}
containerInitOnce = true
// create minimega freezer and memory cgroups
log.Debug("cgroup init: %v", *f_cgroup)
cgroupFreezer := filepath.Join(*f_cgroup, "freezer", "minimega")
cgroupMemory := filepath.Join(*f_cgroup, "memory", "minimega")
cgroupDevices := filepath.Join(*f_cgroup, "devices", "minimega")
cgroupCPU := filepath.Join(*f_cgroup, "cpu", "minimega")
cgroups := []string{cgroupFreezer, cgroupMemory, cgroupDevices, cgroupCPU}
for _, cgroup := range cgroups {
if err := os.Mkdir(cgroup, 0755); err != nil {
return fmt.Errorf("cgroup mkdir: %v", err)
}
// inherit cpusets
if err := ioutil.WriteFile(filepath.Join(cgroup, "cgroup.clone_children"), []byte("1"), 0664); err != nil {
return fmt.Errorf("setting cgroup: %v", err)
}
}
if err := ioutil.WriteFile(filepath.Join(cgroupMemory, "memory.use_hierarchy"), []byte("1"), 0664); err != nil {
return fmt.Errorf("setting use_hierarchy: %v", err)
}
// clean potentially old cgroup noise
containerCleanCgroupDirs()
containerInitSuccess = true
return nil
}
func containerTeardown() {
cgroupFreezer := filepath.Join(*f_cgroup, "freezer", "minimega")
cgroupMemory := filepath.Join(*f_cgroup, "memory", "minimega")
cgroupDevices := filepath.Join(*f_cgroup, "devices", "minimega")
cgroupCPU := filepath.Join(*f_cgroup, "cpu", "minimega")
cgroups := []string{cgroupFreezer, cgroupMemory, cgroupDevices, cgroupCPU}
for _, cgroup := range cgroups {
if err := os.Remove(cgroup); err != nil {
if containerInitSuccess {
log.Errorln(err)
}
}
}
}
// golang can't easily support the typical clone+exec method of firing off a
// child process. We need a child process to do ample setup for containers
// *post* clone. We have two options - duplicate the forkAndExec shim in
// src/syscall to do a clone and get into a new minimega that can finish the
// container setup, or start a new minimega with an 'nsinit' C shim *before*
// the runtime starts. Docker and others use the latter, though it's not
// entirely clear why they don't just borrow the forkAndExec method. We'll use
// the forkAndExec method here.
//
// This function is a shim to finalize container setup from a running minimega
// parent. It expects to be called inside namespace isolations (mount, pid,
// etc...) with args: minimega CONTAINER hostname fsPath...
//
// A number of fds get passed to the child on specific fd numbers:
//
// 3: logging port, closed just before exec into init
// 4: closed by the child before exec to elect to be frozen
// 5: closed by the parent when the child returns to allow calling exec
// 6: stdin
// 7: stdout
// 8: stderr
//
// A number of arguments are passed on flag.Args to configure the container:
// 0 : CONTAINER
// 1 : instance path
// 2 : vm id
// 3 : hostname ("CONTAINER_NONE" if none)
// 4 : filesystem path
// 5 : vcpus
// 6 : memory in megabytes
// 7 : uuid
// 8 : number of fifos
// 9 : preinit program
// 10+: source:target volumes, `--` signifies end
// 11+ : init program and args (relative to filesystem path)
func containerShim() {
args := flag.Args()
if flag.NArg() < 11 { // 11 because init args can be nil
os.Exit(1)
}
// we log to fd(3), and close it before we move on to exec ourselves
logFile := os.NewFile(uintptr(3), "")
log.AddLogger("file", logFile, log.DEBUG, false)
log.Debug("containerShim: %v", args)
// get args
vmInstancePath := args[1]
vmID, err := strconv.Atoi(args[2])
if err != nil {
log.Fatalln(err)
}
vmHostname := args[3]
if vmHostname == CONTAINER_NONE {
vmHostname = ""
}
vmFSPath := args[4]
vmVCPUs, err := strconv.Atoi(args[5])
if err != nil {
log.Fatalln(err)
}
vmMemory, err := strconv.Atoi(args[6])
if err != nil {
log.Fatalln(err)
}
vmUUID := args[7]
vmFifos, err := strconv.Atoi(args[8])
if err != nil {
log.Fatalln(err)
}
vmPreinit := args[9]
// find `--` separator between vmVolumes and vmInit
var vmVolumes, vmInit []string
for i, v := range args[10:] {
if v == "--" {
vmInit = args[10+i+1:]
break
}
vmVolumes = append(vmVolumes, v)
}
log.Debug("vmVolumes: %v", vmVolumes)
log.Debug("vmInit: %v", vmInit)
// set hostname
log.Debug("vm %v hostname", vmID)
if vmHostname != "" {
if err := syscall.Sethostname([]byte(vmHostname)); err != nil {
log.Fatal("set hostname: %v", err)
}
}
// setup the root fs
log.Debug("vm %v containerSetupRoot", vmID)
err = containerSetupRoot(vmFSPath)
if err != nil {
log.Fatal("containerSetupRoot: %v", err)
}
// mount defaults
log.Debug("vm %v containerMountDefaults", vmID)
err = containerMountDefaults(vmFSPath)
if err != nil {
log.Fatal("containerMountDefaults: %v", err)
}
// mount volumes
log.Debug("vm %v containerMountVolumes", vmID)
err = containerMountVolumes(vmFSPath, vmVolumes)
if err != nil {
log.Fatal("containerMountVolumes: %v", err)
}
// mknod
log.Debug("vm %v containerMknodDevices", vmID)
err = containerMknodDevices(vmFSPath)
if err != nil {
log.Fatal("containerMknodDevices: %v", err)
}
// pseudoterminals
log.Debug("vm %v containerPtmx", vmID)
err = containerPtmx(vmFSPath)
if err != nil {
log.Fatal("containerPtmx: %v", err)
}
// preinit
if vmPreinit != CONTAINER_NONE {
log.Debug("preinit: %v", vmPreinit)
out, err := exec.Command(vmPreinit, vmPreinit).CombinedOutput()
if err != nil {
log.Fatal("containerPreinit: %v: %v", err, string(out))
}
if len(out) != 0 {
log.Debug("containerPreinit: %v", string(out))
}
}
// symlinks
log.Debug("vm %v containerSymlinks", vmID)
err = containerSymlinks(vmFSPath)
if err != nil {
log.Fatal("containerSymlinks: %v", err)
}
// remount key paths as read-only
log.Debug("vm %v containerRemountReadOnly", vmID)
err = containerRemountReadOnly(vmFSPath)
if err != nil {
log.Fatal("containerRemountReadOnly: %v", err)
}
// mask uuid path if possible - not all platforms have dmi
log.Debug("uuid bind mount: %v -> %v", vmUUID, containerUUIDLink)
err = syscall.Mount(vmUUID, filepath.Join(vmFSPath, containerUUIDLink), "", syscall.MS_BIND, "")
if err != nil {
log.Warn("containerUUIDLink: %v", err)
}
// bind mount fifos
log.Debug("vm %v containerFifos", vmID)
err = containerFifos(vmFSPath, vmInstancePath, vmFifos)
if err != nil {
log.Fatal("containerFifos: %v", err)
}
// mask paths
log.Debug("vm %v containerMaskPaths", vmID)
err = containerMaskPaths(vmFSPath)
if err != nil {
log.Fatal("containerMaskPaths: %v", err)
}
// setup cgroups for this vm
log.Debug("vm %v containerPopulateCgroups", vmID)
err = containerPopulateCgroups(vmID, vmVCPUs, vmMemory)
if err != nil {
log.Fatal("containerPopulateCgroups: %v", err)
}
// chdir
log.Debug("vm %v chdir", vmID)
err = syscall.Chdir(vmFSPath)
if err != nil {
log.Fatal("chdir: %v", err)
}
// attempt to chroot
log.Debug("vm %v containerChroot", vmID)
err = containerChroot(vmFSPath)
if err != nil {
log.Fatal("containerChroot: %v", err)
}
// set capabilities
log.Debug("vm %v containerSetCapabilities", vmID)
err = containerSetCapabilities()
if err != nil {
log.Fatal("containerSetCapabilities: %v", err)
}
// in order to synchronize freezing the container before we call init,
// we close fd(4) to signal the parent that we're ready to freeze. We
// then read fd(5) in order to block for the parent. The parent will
// freeze the child and close the other end of fd(5). Upon unfreezing,
// the read will fail and we can move on to exec.
log.Debug("sync for freezing")
sync1 := os.NewFile(uintptr(4), "")
sync2 := os.NewFile(uintptr(5), "")
sync1.Close()
var buf = make([]byte, 1)
sync2.Read(buf)
log.Debug("return from freezing")
// close fds we don't want in init
logFile.Close()
// GO!
log.Debug("vm %v exec: %v", vmID, vmInit)
err = syscall.Exec(vmInit[0], vmInit, nil)
if err != nil {
log.Fatal("Exec: %v", err)
}
// the new child process will exit and the parent will catch it
log.Fatalln("how did I get here?")
}
func containerFifos(vmFSPath string, vmInstancePath string, vmFifos int) error {
err := os.Mkdir(filepath.Join(vmFSPath, "/dev/fifos"), 0755)
if err != nil {
log.Errorln(err)
return nil
}
for i := 0; i < vmFifos; i++ {
src := filepath.Join(vmInstancePath, fmt.Sprintf("fifo%v", i))
_, err := os.Stat(src)
if err != nil {
log.Errorln(err)
return err
}
dst := filepath.Join(vmFSPath, fmt.Sprintf("/dev/fifos/fifo%v", i))
// dst must exist for bind mounting to work
f, err := os.Create(dst)
if err != nil {
log.Errorln(err)
return err
}
f.Close()
log.Debug("bind mounting: %v -> %v", src, dst)
err = syscall.Mount(src, dst, "", syscall.MS_BIND, "")
if err != nil {
log.Errorln(err)
return err
}
}
return nil
}
// Copy makes a deep copy and returns reference to the new struct.
func (old ContainerConfig) Copy() ContainerConfig {
// Copy all fields
res := old
// Make deep copy of volumes
res.VolumePaths = map[string]string{}
for k, v := range old.VolumePaths {
res.VolumePaths[k] = v
}
return res
}
func (vm *ContainerVM) Config() *BaseConfig {
return &vm.BaseConfig
}
func NewContainer(name, namespace string, config VMConfig) (*ContainerVM, error) {
vm := new(ContainerVM)
vm.BaseVM = NewBaseVM(name, namespace, config)
vm.Type = CONTAINER
vm.ContainerConfig = config.ContainerConfig.Copy() // deep-copy configured fields
// set hostname to VM's name if it's unspecified. note that the name arg
// may be the empty string but NewBaseVM populates vm.Name with a default
// value if that's the case.
if vm.Hostname == "" {
vm.Hostname = vm.Name
}
if vm.FilesystemPath == "" {
return nil, errors.New("unable to create container without a configured filesystem")
}
return vm, nil
}
func (vm *ContainerVM) Copy() VM {
vm.lock.Lock()
defer vm.lock.Unlock()
vm2 := new(ContainerVM)
// Make shallow copies of all fields
*vm2 = *vm
// Make deep copies
vm2.BaseVM = vm.BaseVM.copy()
vm2.ContainerConfig = vm.ContainerConfig.Copy()
return vm2
}
func (vm *ContainerVM) Launch() error {
defer vm.lock.Unlock()
return vm.launch()
}
func (vm *ContainerVM) Start() (err error) {
vm.lock.Lock()
defer vm.lock.Unlock()
if vm.State&VM_RUNNING != 0 {
return nil
}
if vm.State == VM_QUIT || vm.State == VM_ERROR {
log.Info("relaunching VM: %v", vm.ID)
// Create a new channel since we closed the other one to indicate that
// the VM should quit.
vm.kill = make(chan bool)
// Launch handles setting the VM to error state
if err := vm.launch(); err != nil {
return err
}
}
log.Info("starting VM: %v", vm.ID)
if err := vm.thaw(); err != nil {
return vm.setErrorf("unstartable: %v", err)
}
vm.setState(VM_RUNNING)
return nil
}
func (vm *ContainerVM) Stop() error {
vm.lock.Lock()
defer vm.lock.Unlock()
if vm.Name == "vince" {
return errors.New("vince is unstoppable")
}
if vm.State != VM_RUNNING {
return vmNotRunning(strconv.Itoa(vm.ID))
}
log.Info("stopping VM: %v", vm.ID)
if err := vm.freeze(); err != nil {
return vm.setErrorf("unstoppable: %v", err)
}
vm.setState(VM_PAUSED)
return nil
}
func (vm *ContainerVM) String() string {
return fmt.Sprintf("%s:%d:container", hostname, vm.ID)
}
func (vm *ContainerVM) Info(field string) (string, error) {
// If the field is handled by BaseVM, return it
if v, err := vm.BaseVM.Info(field); err == nil {
return v, nil
}
vm.lock.Lock()
defer vm.lock.Unlock()
switch field {
case "console_port":
return strconv.Itoa(vm.ConsolePort), nil
case "volume":
return marshal(vm.VolumePaths), nil
case "pid":
return strconv.Itoa(vm.Pid), nil
}
return vm.ContainerConfig.Info(field)
}
func (vm *ContainerVM) Conflicts(vm2 VM) error {
switch vm2 := vm2.(type) {
case *ContainerVM:
return vm.ConflictsContainer(vm2)
case *KvmVM:
return vm.BaseVM.conflicts(vm2.BaseVM)
}
return errors.New("unknown VM type")
}
// ConflictsContainer tests whether vm and vm2 share a filesystem and
// returns an error if one of them is not running in snapshot mode. Also
// checks whether the BaseVMs conflict.
func (vm *ContainerVM) ConflictsContainer(vm2 *ContainerVM) error {
vm.lock.Lock()
defer vm.lock.Unlock()
if vm.FilesystemPath == vm2.FilesystemPath && (!vm.Snapshot || !vm2.Snapshot) {
return fmt.Errorf("filesystem conflict with vm %v: %v", vm.Name, vm.FilesystemPath)
}
return vm.BaseVM.conflicts(vm2.BaseVM)
}
func (vm *ContainerVM) Screenshot(size int) ([]byte, error) {
return nil, errors.New("cannot take screenshot of container")
}
func (vm *ContainerConfig) String() string {
// create output
var o bytes.Buffer
w := new(tabwriter.Writer)
w.Init(&o, 5, 0, 1, ' ', 0)
fmt.Fprintln(&o, "Container configuration:")
fmt.Fprintf(w, "Filesystem Path:\t%v\n", vm.FilesystemPath)
fmt.Fprintf(w, "Hostname:\t%v\n", vm.Hostname)
fmt.Fprintf(w, "Init:\t%v\n", vm.Init)
fmt.Fprintf(w, "Pre-init:\t%v\n", vm.Preinit)
fmt.Fprintf(w, "FIFOs:\t%v\n", vm.Fifos)
fmt.Fprintf(w, "Volumes:\t\n")
for k, v := range vm.VolumePaths {
fmt.Fprintf(w, "\t%v -> %v\n", k, v)
}
w.Flush()
fmt.Fprintln(&o)
return o.String()
}
// launch is the low-level launch function for Container VMs. The caller should
// hold the VM's lock.
func (vm *ContainerVM) launch() error {
log.Info("launching vm: %v", vm.ID)
err := containerInit()
if err != nil || !containerInitSuccess {
return vm.setErrorf("cgroups are not initialized, cannot continue: %v", err)
}
// If this is the first time launching the VM, do the final configuration
// check, create a directory for it, and setup the FS.
if vm.State == VM_BUILDING {
if err := os.MkdirAll(vm.instancePath, os.FileMode(0700)); err != nil {
return vm.setErrorf("unable to create VM dir: %v", err)
}
if vm.Snapshot {
if err := vm.overlayMount(); err != nil {
return vm.setErrorf("overlayMount: %v", err)
}
} else {
vm.effectivePath = vm.FilesystemPath
}
if err := vm.createInstancePathAlias(); err != nil {
return vm.setErrorf("createInstancePathAlias: %v", err)
}
}
mustWrite(vm.path("name"), vm.Name)
// the child process will communicate with a fake console using pipes
// to mimic stdio, and a fourth pipe for logging before the child execs
// into the init program
// two additional pipes are needed to synchronize freezing the child
// before it enters the container
parentLog, childLog, err := os.Pipe()
if err != nil {
return vm.setErrorf("pipe: %v", err)
}
parentSync1, childSync1, err := os.Pipe()
if err != nil {
return vm.setErrorf("pipe: %v", err)
}
childSync2, parentSync2, err := os.Pipe()
if err != nil {
return vm.setErrorf("pipe: %v", err)
}
// create the uuid path that will bind mount into sysfs in the
// container
uuidPath := vm.path("uuid")
ioutil.WriteFile(uuidPath, []byte(vm.UUID+"\n"), 0400)
// create fifos
for i := uint64(0); i < vm.Fifos; i++ {
p := vm.path(fmt.Sprintf("fifo%v", i))
if err = syscall.Mkfifo(p, 0660); err != nil {
return vm.setErrorf("fifo: %v", err)
}
}
// 0 : minimega binary
// 1 : CONTAINER
// 2 : instance path
// 3 : vm id
// 4 : hostname ("CONTAINER_NONE" if none)
// 5 : filesystem path
// 6 : memory in megabytes
// 7 : uuid
// 8 : number of fifos
// 9 : init program (relative to filesystem path)
// 10: init args
hn := vm.Hostname
if hn == "" {
hn = CONTAINER_NONE
}
preinit := vm.Preinit
if preinit == "" {
preinit = CONTAINER_NONE
}
args := []string{
os.Args[0],
"-base",
*f_base,
CONTAINER_MAGIC,
vm.instancePath,
fmt.Sprintf("%v", vm.ID),
hn,
vm.effectivePath,
strconv.FormatUint(vm.VCPUs, 10),
strconv.FormatUint(vm.Memory, 10),
uuidPath,
fmt.Sprintf("%v", vm.Fifos),
preinit,
}
for k, v := range vm.VolumePaths {
// Create source:target pairs
// TODO: should probably handle spaces
args = append(args, fmt.Sprintf("%v:%v", v, k))
// create source directory if it doesn't exist
if err := os.MkdirAll(v, 0755); err != nil {
return vm.setErrorf("start container: %v", err)
}
}
// denotes end of volumes
args = append(args, "--")
args = append(args, vm.Init...)
// launch the container
cmd := &exec.Cmd{
Path: "/proc/self/exe",
Args: args,
ExtraFiles: []*os.File{
childLog,
childSync1,
childSync2,
},
SysProcAttr: &syscall.SysProcAttr{
Cloneflags: uintptr(CONTAINER_FLAGS),
},
}
// Start the child and give it a pty
pseudotty, err := pty.Start(cmd)
if err != nil {
vm.overlayUnmount()
return vm.setErrorf("start container: %v", err)
}
vm.Pid = cmd.Process.Pid
log.Debug("vm %v has pid %v", vm.ID, vm.Pid)
// log the child
childLog.Close()
log.LogAll(parentLog, log.DEBUG, "containerShim")
go vm.console(pseudotty)
// network creation for containers happens /after/ the container is
// started, as we need the PID in order to attach a veth to the container
// side of the network namespace. That means that unlike kvm vms, we MUST
// create/destroy taps on launch/kill boundaries (kvm destroys taps on
// flush).
if err = vm.launchNetwork(); err != nil {
log.Errorln(err)
}
childSync1.Close()
if err == nil {
// wait for the freezer notification
var buf = make([]byte, 1)
parentSync1.Read(buf)
err = vm.freeze()
parentSync2.Close()
} else {
parentSync1.Close()
parentSync2.Close()
}
if err != nil {
// Some error occurred.. clean up the process
cmd.Process.Kill()
vm.unlinkNetns()
return vm.setErrorf("%v", err)
}
// Channel to signal when the process has exited
errChan := make(chan error)
// Create goroutine to wait for process to exit
go func() {
defer close(errChan)
errChan <- cmd.Wait()