Debian Codegraph @

container.go

raw symbols SCIP
1 // Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved.
2 // Use of this source code is governed by a LGPLv2.1
3 // license that can be found in the LICENSE file.
4
5 //go:build linux && cgo
6 // +build linux,cgo
7
8 package lxc
9
10 // #include <lxc/lxccontainer.h>
11 // #include <lxc/version.h>
12 // #include "lxc-binding.h"
13 import "C"
14
15 import (
16 "fmt"
17 "io/ioutil"
18 "os"
19 "os/exec"
20 "path"
21 "path/filepath"
22 "strconv"
23 "strings"
24 "sync"
25 "syscall"
26 "time"
27 "unsafe"
28
29 "golang.org/x/sys/unix"
30 )
31
32 // Container struct
33 type Container struct {
34 mu sync.RWMutex
35 container *C.struct_lxc_container
36
37 verbosity Verbosity
38 }
39
40 // Snapshot struct
41 type Snapshot struct {
42 Name string
43 CommentPath string
44 Timestamp string
45 Path string
46 }
47
48 const (
49 isDefined = 1 << iota
50 isNotDefined
51 isRunning
52 isNotRunning
53 isPrivileged
54 isUnprivileged
55 isGreaterEqualThanLXC11
56 isGreaterEqualThanLXC20
57 )
58
59 func (c *Container) makeSure(flags int) error {
60 if flags&isDefined != 0 && !c.defined() {
61 return fmt.Errorf("%s: %q", ErrNotDefined, c.name())
62 }
63
64 if flags&isNotDefined != 0 && c.defined() {
65 return fmt.Errorf("%s: %q", ErrAlreadyDefined, c.name())
66 }
67
68 if flags&isRunning != 0 && !c.running() {
69 return fmt.Errorf("%s: %q", ErrNotRunning, c.name())
70 }
71
72 if flags&isNotRunning != 0 && c.running() {
73 return fmt.Errorf("%s: %q", ErrAlreadyRunning, c.name())
74 }
75
76 if flags&isPrivileged != 0 && os.Geteuid() != 0 {
77 return ErrMethodNotAllowed
78 }
79
80 if flags&isGreaterEqualThanLXC11 != 0 && !VersionAtLeast(1, 1, 0) {
81 return ErrNotSupported
82 }
83
84 if flags&isGreaterEqualThanLXC20 != 0 && !VersionAtLeast(2, 0, 0) {
85 return ErrNotSupported
86 }
87
88 return nil
89 }
90
91 func (c *Container) cgroupItemAsByteSize(filename string, missing error) (ByteSize, error) {
92 size, err := strconv.ParseFloat(c.cgroupItem(filename)[0], 64)
93 if err != nil {
94 return -1, missing
95 }
96 return ByteSize(size), nil
97 }
98
99 func (c *Container) setCgroupItemWithByteSize(filename string, limit ByteSize, missing error) error {
100 if err := c.setCgroupItem(filename, fmt.Sprintf("%.f", limit)); err != nil {
101 return missing
102 }
103 return nil
104 }
105
106 // Release decrements the reference counter of the container object.
107 // nil on success or if reference was successfully dropped and container has been freed, and ErrReleaseFailed on error.
108 func (c *Container) Release() error {
109 c.mu.Lock()
110 defer c.mu.Unlock()
111
112 if C.lxc_container_put(c.container) == -1 {
113 return ErrReleaseFailed
114 }
115
116 c.container = nil
117
118 return nil
119 }
120
121 func (c *Container) name() string {
122 if c.container == nil {
123 return ""
124 }
125
126 return C.GoString(c.container.name)
127 }
128
129 // Name returns the name of the container.
130 func (c *Container) Name() string {
131 c.mu.RLock()
132 defer c.mu.RUnlock()
133
134 return c.name()
135 }
136
137 // String returns the string representation of container.
138 func (c *Container) String() string {
139 c.mu.RLock()
140 defer c.mu.RUnlock()
141
142 return path.Join(c.configPath(), c.name())
143 }
144
145 // Caller needs to hold the lock
146 func (c *Container) defined() bool {
147 if c.container == nil {
148 return false
149 }
150
151 return bool(C.go_lxc_defined(c.container))
152 }
153
154 // Defined returns true if the container is already defined.
155 func (c *Container) Defined() bool {
156 c.mu.RLock()
157 defer c.mu.RUnlock()
158
159 return c.defined()
160 }
161
162 // Caller needs to hold the lock
163 func (c *Container) running() bool {
164 if c.container == nil {
165 return false
166 }
167
168 return bool(C.go_lxc_running(c.container))
169 }
170
171 // Running returns true if the container is already running.
172 func (c *Container) Running() bool {
173 c.mu.RLock()
174 defer c.mu.RUnlock()
175
176 return c.running()
177 }
178
179 // Controllable returns true if the caller can control the container.
180 func (c *Container) Controllable() bool {
181 c.mu.RLock()
182 defer c.mu.RUnlock()
183
184 if c.container == nil {
185 return false
186 }
187
188 return bool(C.go_lxc_may_control(c.container))
189 }
190
191 // CreateSnapshot creates a new snapshot.
192 func (c *Container) CreateSnapshot() (*Snapshot, error) {
193 c.mu.Lock()
194 defer c.mu.Unlock()
195
196 if c.container == nil {
197 return nil, ErrNotDefined
198 }
199
200 if err := c.makeSure(isDefined | isNotRunning); err != nil {
201 return nil, err
202 }
203
204 ret := int(C.go_lxc_snapshot(c.container))
205 if ret < 0 {
206 return nil, ErrCreateSnapshotFailed
207 }
208 return &Snapshot{Name: fmt.Sprintf("snap%d", ret)}, nil
209 }
210
211 // RestoreSnapshot creates a new container based on a snapshot.
212 func (c *Container) RestoreSnapshot(snapshot Snapshot, name string) error {
213 c.mu.Lock()
214 defer c.mu.Unlock()
215
216 if c.container == nil {
217 return ErrNotDefined
218 }
219
220 if err := c.makeSure(isDefined); err != nil {
221 return err
222 }
223
224 cname := C.CString(name)
225 defer C.free(unsafe.Pointer(cname))
226
227 csnapname := C.CString(snapshot.Name)
228 defer C.free(unsafe.Pointer(csnapname))
229
230 if !bool(C.go_lxc_snapshot_restore(c.container, csnapname, cname)) {
231 return ErrRestoreSnapshotFailed
232 }
233 return nil
234 }
235
236 // DestroySnapshot destroys the specified snapshot.
237 func (c *Container) DestroySnapshot(snapshot Snapshot) error {
238 c.mu.Lock()
239 defer c.mu.Unlock()
240
241 if c.container == nil {
242 return ErrNotDefined
243 }
244
245 if err := c.makeSure(isDefined); err != nil {
246 return err
247 }
248
249 csnapname := C.CString(snapshot.Name)
250 defer C.free(unsafe.Pointer(csnapname))
251
252 if !bool(C.go_lxc_snapshot_destroy(c.container, csnapname)) {
253 return ErrDestroySnapshotFailed
254 }
255 return nil
256 }
257
258 // DestroyAllSnapshots destroys all the snapshot.
259 func (c *Container) DestroyAllSnapshots() error {
260 c.mu.Lock()
261 defer c.mu.Unlock()
262
263 if c.container == nil {
264 return ErrNotDefined
265 }
266
267 if err := c.makeSure(isDefined | isGreaterEqualThanLXC11); err != nil {
268 return err
269 }
270
271 if !bool(C.go_lxc_snapshot_destroy_all(c.container)) {
272 return ErrDestroyAllSnapshotsFailed
273 }
274 return nil
275 }
276
277 // Snapshots returns the list of container snapshots.
278 func (c *Container) Snapshots() ([]Snapshot, error) {
279 c.mu.RLock()
280 defer c.mu.RUnlock()
281
282 if c.container == nil {
283 return nil, ErrNotDefined
284 }
285
286 if err := c.makeSure(isDefined); err != nil {
287 return nil, err
288 }
289
290 var csnapshots *C.struct_lxc_snapshot
291
292 size := int(C.go_lxc_snapshot_list(c.container, &csnapshots))
293 defer freeSnapshots(csnapshots, size)
294
295 if size < 1 {
296 return nil, ErrNoSnapshot
297 }
298
299 gosnapshots := (*[(1 << 26) - 1]C.struct_lxc_snapshot)(unsafe.Pointer(csnapshots))[:size:size]
300 snapshots := make([]Snapshot, size, size)
301 for i := 0; i < size; i++ {
302 snapshots[i] = Snapshot{
303 Name: C.GoString(gosnapshots[i].name),
304 Timestamp: C.GoString(gosnapshots[i].timestamp),
305 CommentPath: C.GoString(gosnapshots[i].comment_pathname),
306 Path: C.GoString(gosnapshots[i].lxcpath),
307 }
308 }
309
310 return snapshots, nil
311 }
312
313 // Caller needs to hold the lock
314 func (c *Container) state() State {
315 if c.container == nil {
316 return StateMap["STOPPED"]
317 }
318
319 return StateMap[C.GoString(C.go_lxc_state(c.container))]
320 }
321
322 // State returns the state of the container.
323 func (c *Container) State() State {
324 c.mu.RLock()
325 defer c.mu.RUnlock()
326
327 return c.state()
328 }
329
330 // InitPid returns the process ID of the container's init process
331 // seen from outside the container.
332 func (c *Container) InitPid() int {
333 c.mu.RLock()
334 defer c.mu.RUnlock()
335
336 if c.container == nil {
337 return -1
338 }
339
340 return int(C.go_lxc_init_pid(c.container))
341 }
342
343 // InitPidFd returns the pidfd of the container's init process.
344 func (c *Container) InitPidFd() (*os.File, error) {
345 c.mu.RLock()
346 defer c.mu.RUnlock()
347
348 if c.container == nil {
349 return nil, ErrNotDefined
350 }
351
352 pidfd := int(C.go_lxc_init_pidfd(c.container))
353 if pidfd < 0 {
354 return nil, unix.Errno(unix.EBADF)
355 }
356
357 return os.NewFile(uintptr(pidfd), "[pidfd]"), nil
358 }
359
360 // DevptsFd returns the pidfd of the container's init process.
361 func (c *Container) DevptsFd() (*os.File, error) {
362 c.mu.RLock()
363 defer c.mu.RUnlock()
364
365 if c.container == nil {
366 return nil, ErrNotDefined
367 }
368
369 devptsFd := int(C.go_lxc_devpts_fd(c.container))
370 if devptsFd < 0 {
371 return nil, unix.Errno(unix.EBADF)
372 }
373
374 return os.NewFile(uintptr(devptsFd), "/dev/pts/ptmx"), nil
375 }
376
377 // SeccompNotifyFd returns the seccomp notify fd of the container.
378 func (c *Container) SeccompNotifyFd() (*os.File, error) {
379 c.mu.RLock()
380 defer c.mu.RUnlock()
381
382 if c.container == nil {
383 return nil, ErrNotDefined
384 }
385
386 notifyFd := int(C.go_lxc_seccomp_notify_fd(c.container))
387 if notifyFd < 0 {
388 return nil, unix.Errno(unix.EBADF)
389 }
390
391 return os.NewFile(uintptr(notifyFd), "seccomp notify"), nil
392 }
393
394 // SeccompNotifyFdActive returns the seccomp notify fd of the running container.
395 func (c *Container) SeccompNotifyFdActive() (*os.File, error) {
396 c.mu.RLock()
397 defer c.mu.RUnlock()
398
399 if c.container == nil {
400 return nil, ErrNotDefined
401 }
402
403 notifyFd := int(C.go_lxc_seccomp_notify_fd_active(c.container))
404 if notifyFd < 0 {
405 return nil, unix.Errno(unix.EBADF)
406 }
407
408 return os.NewFile(uintptr(notifyFd), "seccomp notify"), nil
409 }
410
411 // SetTimeout sets the response receive timeout for commands
412 func (c *Container) SetTimeout(timeout time.Duration) error {
413 c.mu.Lock()
414 defer c.mu.Unlock()
415
416 if c.container == nil {
417 return ErrNotDefined
418 }
419
420 ret := int(C.go_lxc_set_timeout(c.container, C.int(timeout.Seconds())))
421 if ret < 0 {
422 return unix.Errno(-ret)
423 }
424
425 return nil
426 }
427
428 // Daemonize returns true if the container wished to be daemonized.
429 func (c *Container) Daemonize() bool {
430 c.mu.RLock()
431 defer c.mu.RUnlock()
432
433 if c.container == nil {
434 return false
435 }
436
437 return bool(c.container.daemonize)
438 }
439
440 // WantDaemonize determines if the container wants to run daemonized.
441 func (c *Container) WantDaemonize(state bool) error {
442 c.mu.Lock()
443 defer c.mu.Unlock()
444
445 if c.container == nil {
446 return ErrNotDefined
447 }
448
449 if !bool(C.go_lxc_want_daemonize(c.container, C.bool(state))) {
450 return ErrDaemonizeFailed
451 }
452 return nil
453 }
454
455 // WantCloseAllFds determines whether container wishes all file descriptors
456 // to be closed on startup.
457 func (c *Container) WantCloseAllFds(state bool) error {
458 c.mu.Lock()
459 defer c.mu.Unlock()
460
461 if c.container == nil {
462 return ErrNotDefined
463 }
464
465 if !bool(C.go_lxc_want_close_all_fds(c.container, C.bool(state))) {
466 return ErrCloseAllFdsFailed
467 }
468 return nil
469 }
470
471 // SetVerbosity sets the verbosity level of some API calls
472 func (c *Container) SetVerbosity(verbosity Verbosity) {
473 c.mu.Lock()
474 defer c.mu.Unlock()
475
476 c.verbosity = verbosity
477 }
478
479 // Freeze freezes the running container.
480 func (c *Container) Freeze() error {
481 c.mu.Lock()
482 defer c.mu.Unlock()
483
484 if c.container == nil {
485 return ErrNotDefined
486 }
487
488 // check the state using lockless version
489 if c.state() == FROZEN {
490 return ErrAlreadyFrozen
491 }
492
493 if !bool(C.go_lxc_freeze(c.container)) {
494 return ErrFreezeFailed
495 }
496
497 return nil
498 }
499
500 // Unfreeze thaws the frozen container.
501 func (c *Container) Unfreeze() error {
502 c.mu.Lock()
503 defer c.mu.Unlock()
504
505 if c.container == nil {
506 return ErrNotDefined
507 }
508
509 if err := c.makeSure(isRunning); err != nil {
510 return err
511 }
512
513 // check the state using lockless version
514 if c.state() != FROZEN {
515 return ErrNotFrozen
516 }
517
518 if !bool(C.go_lxc_unfreeze(c.container)) {
519 return ErrUnfreezeFailed
520 }
521
522 return nil
523 }
524
525 // Create creates the container using given TemplateOptions
526 func (c *Container) Create(options TemplateOptions) error {
527 c.mu.Lock()
528 defer c.mu.Unlock()
529
530 if err := c.makeSure(isNotDefined); err != nil {
531 return err
532 }
533
534 bdevspecs := buildBdevSpecs(options.BackendSpecs)
535
536 // use download template if not set
537 if options.Template == "" {
538 options.Template = "download"
539 }
540
541 // use Directory backend if not set
542 if options.Backend == 0 {
543 options.Backend = Directory
544 }
545
546 var args []string
547 if options.Template == "download" {
548 // required parameters
549 if options.Distro == "" || options.Release == "" || options.Arch == "" {
550 return ErrInsufficientNumberOfArguments
551 }
552 args = append(args, "--dist", options.Distro, "--release", options.Release, "--arch", options.Arch)
553
554 // optional arguments
555 if options.Variant != "" {
556 args = append(args, "--variant", options.Variant)
557 }
558 if options.Server != "" {
559 args = append(args, "--server", options.Server)
560 }
561 if options.KeyID != "" {
562 args = append(args, "--keyid", options.KeyID)
563 }
564 if options.KeyServer != "" {
565 args = append(args, "--keyserver", options.KeyServer)
566 }
567 if options.DisableGPGValidation {
568 args = append(args, "--no-validate")
569 }
570 if options.FlushCache {
571 args = append(args, "--flush-cache")
572 }
573 if options.ForceCache {
574 args = append(args, "--force-cache")
575 }
576 } else {
577 // optional arguments
578 if options.Release != "" {
579 args = append(args, "--release", options.Release)
580 }
581 if options.Arch != "" {
582 args = append(args, "--arch", options.Arch)
583 }
584 if options.FlushCache {
585 args = append(args, "--flush-cache")
586 }
587 }
588
589 if options.ExtraArgs != nil {
590 args = append(args, options.ExtraArgs...)
591 }
592
593 ctemplate := C.CString(options.Template)
594 defer C.free(unsafe.Pointer(ctemplate))
595
596 cbackend := C.CString(options.Backend.String())
597 defer C.free(unsafe.Pointer(cbackend))
598
599 ret := false
600 if args != nil {
601 cargs := makeNullTerminatedArgs(args)
602 if cargs == nil {
603 return ErrAllocationFailed
604 }
605 defer freeNullTerminatedArgs(cargs, len(args))
606
607 ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, bdevspecs, C.int(c.verbosity), cargs))
608 } else {
609 ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, bdevspecs, C.int(c.verbosity), nil))
610 }
611
612 if !ret {
613 return ErrCreateFailed
614 }
615 return nil
616 }
617
618 // Start starts the container.
619 func (c *Container) Start() error {
620 c.mu.Lock()
621 defer c.mu.Unlock()
622
623 if c.container == nil {
624 return ErrNotDefined
625 }
626
627 if err := c.makeSure(isNotRunning); err != nil {
628 return err
629 }
630
631 if !bool(C.go_lxc_start(c.container, 0, nil)) {
632 return ErrStartFailed
633 }
634 return nil
635 }
636
637 // StartWithArgs starts the container using given arguments.
638 func (c *Container) StartWithArgs(args []string) error {
639 c.mu.Lock()
640 defer c.mu.Unlock()
641
642 if c.container == nil {
643 return ErrNotDefined
644 }
645
646 if err := c.makeSure(isNotRunning); err != nil {
647 return err
648 }
649
650 if args != nil {
651 if !bool(C.go_lxc_start(c.container, 0, makeNullTerminatedArgs(args))) {
652 return ErrStartFailed
653 }
654 } else {
655 if !bool(C.go_lxc_start(c.container, 0, nil)) {
656 return ErrStartFailed
657 }
658 }
659
660 return nil
661 }
662
663 // StartExecute starts a container. It runs a minimal init as PID 1 and the
664 // requested program as the second process.
665 func (c *Container) StartExecute(args []string) error {
666 c.mu.Lock()
667 defer c.mu.Unlock()
668
669 if c.container == nil {
670 return ErrNotDefined
671 }
672
673 if err := c.makeSure(isNotRunning); err != nil {
674 return err
675 }
676
677 if args != nil {
678 if !bool(C.go_lxc_start(c.container, 1, makeNullTerminatedArgs(args))) {
679 return ErrStartFailed
680 }
681 } else {
682 if !bool(C.go_lxc_start(c.container, 1, nil)) {
683 return ErrStartFailed
684 }
685 }
686
687 return nil
688 }
689
690 // Execute executes the given command in a temporary container.
691 func (c *Container) Execute(args ...string) ([]byte, error) {
692 c.mu.Lock()
693 defer c.mu.Unlock()
694
695 if err := c.makeSure(isNotDefined); err != nil {
696 return nil, err
697 }
698
699 os.MkdirAll(filepath.Join(c.configPath(), c.name()), 0700)
700 c.saveConfigFile(filepath.Join(c.configPath(), c.name(), "config"))
701 defer os.RemoveAll(filepath.Join(c.configPath(), c.name()))
702
703 cargs := []string{"lxc-execute", "-n", c.name(), "-P", c.configPath(), "--"}
704 cargs = append(cargs, args...)
705
706 // FIXME: Go runtime and src/lxc/start.c signal_handler are not playing nice together so use lxc-execute for now
707 // go-nuts thread: https://groups.google.com/forum/#!msg/golang-nuts/h9GbvfYv83w/5Ly_jvOr86wJ
708 output, err := exec.Command(cargs[0], cargs[1:]...).CombinedOutput()
709 if err != nil {
710 // Do not suppress stderr if the exit code != 0. Return with err.
711 if len(output) > 1 {
712 return output, ErrExecuteFailed
713 }
714
715 return nil, ErrExecuteFailed
716 }
717
718 return output, nil
719 }
720
721 // Stop stops the container.
722 func (c *Container) Stop() error {
723 c.mu.Lock()
724 defer c.mu.Unlock()
725
726 if c.container == nil {
727 return ErrNotDefined
728 }
729
730 if err := c.makeSure(isRunning); err != nil {
731 return err
732 }
733
734 if !bool(C.go_lxc_stop(c.container)) {
735 return ErrStopFailed
736 }
737 return nil
738 }
739
740 // Reboot reboots the container.
741 func (c *Container) Reboot() error {
742 c.mu.Lock()
743 defer c.mu.Unlock()
744
745 if c.container == nil {
746 return ErrNotDefined
747 }
748
749 if err := c.makeSure(isRunning); err != nil {
750 return err
751 }
752
753 if !bool(C.go_lxc_reboot(c.container)) {
754 return ErrRebootFailed
755 }
756 return nil
757 }
758
759 // Shutdown shuts down the container.
760 func (c *Container) Shutdown(timeout time.Duration) error {
761 c.mu.Lock()
762 defer c.mu.Unlock()
763
764 if c.container == nil {
765 return ErrNotDefined
766 }
767
768 if err := c.makeSure(isRunning); err != nil {
769 return err
770 }
771
772 if !bool(C.go_lxc_shutdown(c.container, C.int(timeout.Seconds()))) {
773 return ErrShutdownFailed
774 }
775 return nil
776 }
777
778 // Destroy destroys the container.
779 func (c *Container) Destroy() error {
780 c.mu.Lock()
781 defer c.mu.Unlock()
782
783 if c.container == nil {
784 return ErrNotDefined
785 }
786
787 if err := c.makeSure(isDefined | isNotRunning); err != nil {
788 return err
789 }
790
791 if !bool(C.go_lxc_destroy(c.container)) {
792 return ErrDestroyFailed
793 }
794 return nil
795 }
796
797 // DestroyWithAllSnapshots destroys the container and its snapshots
798 func (c *Container) DestroyWithAllSnapshots() error {
799 c.mu.Lock()
800 defer c.mu.Unlock()
801
802 if c.container == nil {
803 return ErrNotDefined
804 }
805
806 if err := c.makeSure(isDefined | isNotRunning | isGreaterEqualThanLXC11); err != nil {
807 return err
808 }
809
810 if !bool(C.go_lxc_destroy_with_snapshots(c.container)) {
811 return ErrDestroyWithAllSnapshotsFailed
812 }
813 return nil
814 }
815
816 // Clone clones the container using given arguments with specified backend.
817 func (c *Container) Clone(name string, options CloneOptions) error {
818 c.mu.Lock()
819 defer c.mu.Unlock()
820
821 // FIXME: bdevdata, newsize and hookargs
822 //
823 // bdevdata:
824 // zfs requires zfsroot
825 // lvm requires lvname/vgname/thinpool as well as fstype and fssize
826 // btrfs requires nothing
827 // dir requires nothing
828 //
829 // newsize: for blockdev-backed backingstores
830 //
831 // hookargs: additional arguments to pass to the clone hook script
832 if err := c.makeSure(isDefined | isNotRunning); err != nil {
833 return err
834 }
835
836 // use Directory backend if not set
837 if options.Backend == 0 {
838 options.Backend = Directory
839 }
840
841 var flags int
842 if options.KeepName {
843 flags |= C.LXC_CLONE_KEEPNAME
844 }
845 if options.KeepMAC {
846 flags |= C.LXC_CLONE_KEEPMACADDR
847 }
848 if options.Snapshot {
849 flags |= C.LXC_CLONE_SNAPSHOT
850 }
851
852 cname := C.CString(name)
853 defer C.free(unsafe.Pointer(cname))
854
855 cbackend := C.CString(options.Backend.String())
856 defer C.free(unsafe.Pointer(cbackend))
857
858 if options.ConfigPath != "" {
859 clxcpath := C.CString(options.ConfigPath)
860 defer C.free(unsafe.Pointer(clxcpath))
861
862 if !bool(C.go_lxc_clone(c.container, cname, clxcpath, C.int(flags), cbackend)) {
863 return ErrCloneFailed
864 }
865 } else {
866 if !bool(C.go_lxc_clone(c.container, cname, nil, C.int(flags), cbackend)) {
867 return ErrCloneFailed
868 }
869 }
870 return nil
871 }
872
873 // Rename renames the container.
874 func (c *Container) Rename(name string) error {
875 c.mu.Lock()
876 defer c.mu.Unlock()
877
878 if c.container == nil {
879 return ErrNotDefined
880 }
881
882 if err := c.makeSure(isDefined | isNotRunning); err != nil {
883 return err
884 }
885
886 cname := C.CString(name)
887 defer C.free(unsafe.Pointer(cname))
888
889 if !bool(C.go_lxc_rename(c.container, cname)) {
890 return ErrRenameFailed
891 }
892 return nil
893 }
894
895 // Wait waits for container to reach a particular state.
896 func (c *Container) Wait(state State, timeout time.Duration) bool {
897 c.mu.Lock()
898 defer c.mu.Unlock()
899
900 if c.container == nil {
901 return false
902 }
903
904 cstate := C.CString(state.String())
905 defer C.free(unsafe.Pointer(cstate))
906
907 return bool(C.go_lxc_wait(c.container, cstate, C.int(timeout.Seconds())))
908 }
909
910 // ConfigFileName returns the container's configuration file's name.
911 func (c *Container) ConfigFileName() string {
912 c.mu.RLock()
913 defer c.mu.RUnlock()
914
915 if c.container == nil {
916 return ""
917 }
918
919 // allocated in lxc.c
920 configFileName := C.go_lxc_config_file_name(c.container)
921 defer C.free(unsafe.Pointer(configFileName))
922
923 return C.GoString(configFileName)
924 }
925
926 func (c *Container) configItem(key string) []string {
927 if c.container == nil {
928 return nil
929 }
930
931 ckey := C.CString(key)
932 defer C.free(unsafe.Pointer(ckey))
933
934 // allocated in lxc.c
935 configItem := C.go_lxc_get_config_item(c.container, ckey)
936 defer C.free(unsafe.Pointer(configItem))
937
938 ret := strings.TrimSpace(C.GoString(configItem))
939 return strings.Split(ret, "\n")
940 }
941
942 // ConfigItem returns the value of the given config item.
943 func (c *Container) ConfigItem(key string) []string {
944 c.mu.RLock()
945 defer c.mu.RUnlock()
946
947 return c.configItem(key)
948 }
949
950 func (c *Container) setConfigItem(key string, value string) error {
951 if c.container == nil {
952 return ErrNotDefined
953 }
954
955 ckey := C.CString(key)
956 defer C.free(unsafe.Pointer(ckey))
957
958 cvalue := C.CString(value)
959 defer C.free(unsafe.Pointer(cvalue))
960
961 if !bool(C.go_lxc_set_config_item(c.container, ckey, cvalue)) {
962 return ErrSettingConfigItemFailed
963 }
964 return nil
965 }
966
967 // SetConfigItem sets the value of the given config item.
968 func (c *Container) SetConfigItem(key string, value string) error {
969 c.mu.Lock()
970 defer c.mu.Unlock()
971
972 return c.setConfigItem(key, value)
973 }
974
975 func (c *Container) runningConfigItem(key string) []string {
976 if c.container == nil {
977 return nil
978 }
979
980 ckey := C.CString(key)
981 defer C.free(unsafe.Pointer(ckey))
982
983 // allocated in lxc.c
984 configItem := C.go_lxc_get_running_config_item(c.container, ckey)
985 defer C.free(unsafe.Pointer(configItem))
986
987 ret := strings.TrimSpace(C.GoString(configItem))
988 return strings.Split(ret, "\n")
989 }
990
991 // RunningConfigItem returns the value of the given config item.
992 func (c *Container) RunningConfigItem(key string) []string {
993 c.mu.RLock()
994 defer c.mu.RUnlock()
995
996 return c.runningConfigItem(key)
997 }
998
999 func (c *Container) cgroupItem(key string) []string {
1000 if c.container == nil {
1001 return nil
1002 }
1003
1004 ckey := C.CString(key)
1005 defer C.free(unsafe.Pointer(ckey))
1006
1007 // allocated in lxc.c
1008 cgroupItem := C.go_lxc_get_cgroup_item(c.container, ckey)
1009 defer C.free(unsafe.Pointer(cgroupItem))
1010
1011 ret := strings.TrimSpace(C.GoString(cgroupItem))
1012 return strings.Split(ret, "\n")
1013 }
1014
1015 func (c *Container) setCgroupItem(key string, value string) error {
1016 if c.container == nil {
1017 return ErrNotDefined
1018 }
1019
1020 ckey := C.CString(key)
1021 defer C.free(unsafe.Pointer(ckey))
1022
1023 cvalue := C.CString(value)
1024 defer C.free(unsafe.Pointer(cvalue))
1025
1026 if !bool(C.go_lxc_set_cgroup_item(c.container, ckey, cvalue)) {
1027 return ErrSettingCgroupItemFailed
1028 }
1029 return nil
1030 }
1031
1032 // CgroupItem returns the value of the given cgroup subsystem value.
1033 func (c *Container) CgroupItem(key string) []string {
1034 c.mu.RLock()
1035 defer c.mu.RUnlock()
1036
1037 return c.cgroupItem(key)
1038 }
1039
1040 // SetCgroupItem sets the value of given cgroup subsystem value.
1041 func (c *Container) SetCgroupItem(key string, value string) error {
1042 c.mu.Lock()
1043 defer c.mu.Unlock()
1044
1045 return c.setCgroupItem(key, value)
1046 }
1047
1048 // ClearConfig completely clears the containers in-memory configuration.
1049 func (c *Container) ClearConfig() {
1050 c.mu.Lock()
1051 defer c.mu.Unlock()
1052
1053 if c.container == nil {
1054 return
1055 }
1056
1057 C.go_lxc_clear_config(c.container)
1058 }
1059
1060 // ClearConfigItem clears the value of given config item.
1061 func (c *Container) ClearConfigItem(key string) error {
1062 c.mu.Lock()
1063 defer c.mu.Unlock()
1064
1065 if c.container == nil {
1066 return ErrNotDefined
1067 }
1068
1069 ckey := C.CString(key)
1070 defer C.free(unsafe.Pointer(ckey))
1071
1072 if !bool(C.go_lxc_clear_config_item(c.container, ckey)) {
1073 return ErrClearingConfigItemFailed
1074 }
1075 return nil
1076 }
1077
1078 // ConfigKeys returns the names of the config items.
1079 func (c *Container) ConfigKeys(key ...string) []string {
1080 c.mu.RLock()
1081 defer c.mu.RUnlock()
1082
1083 if c.container == nil {
1084 return nil
1085 }
1086
1087 var ret string
1088 if key != nil && len(key) == 1 {
1089 ckey := C.CString(key[0])
1090 defer C.free(unsafe.Pointer(ckey))
1091
1092 // allocated in lxc.c
1093 keys := C.go_lxc_get_keys(c.container, ckey)
1094 defer C.free(unsafe.Pointer(keys))
1095
1096 ret = strings.TrimSpace(C.GoString(keys))
1097 } else {
1098 // allocated in lxc.c
1099 keys := C.go_lxc_get_keys(c.container, nil)
1100 defer C.free(unsafe.Pointer(keys))
1101
1102 ret = strings.TrimSpace(C.GoString(keys))
1103 }
1104
1105 return strings.Split(ret, "\n")
1106 }
1107
1108 // LoadConfigFile loads the configuration file from given path.
1109 func (c *Container) LoadConfigFile(path string) error {
1110 c.mu.Lock()
1111 defer c.mu.Unlock()
1112
1113 if c.container == nil {
1114 return ErrNotDefined
1115 }
1116
1117 cpath := C.CString(path)
1118 defer C.free(unsafe.Pointer(cpath))
1119
1120 if !bool(C.go_lxc_load_config(c.container, cpath)) {
1121 return ErrLoadConfigFailed
1122 }
1123 return nil
1124 }
1125
1126 func (c *Container) saveConfigFile(path string) error {
1127 if c.container == nil {
1128 return ErrNotDefined
1129 }
1130
1131 cpath := C.CString(path)
1132 defer C.free(unsafe.Pointer(cpath))
1133
1134 if !bool(C.go_lxc_save_config(c.container, cpath)) {
1135 return ErrSaveConfigFailed
1136 }
1137 return nil
1138 }
1139
1140 // SaveConfigFile saves the configuration file to given path.
1141 func (c *Container) SaveConfigFile(path string) error {
1142 c.mu.Lock()
1143 defer c.mu.Unlock()
1144
1145 return c.saveConfigFile(path)
1146 }
1147
1148 func (c *Container) configPath() string {
1149 if c.container == nil {
1150 return ""
1151 }
1152
1153 return C.GoString(C.go_lxc_get_config_path(c.container))
1154 }
1155
1156 // ConfigPath returns the configuration file's path.
1157 func (c *Container) ConfigPath() string {
1158 c.mu.RLock()
1159 defer c.mu.RUnlock()
1160
1161 return c.configPath()
1162 }
1163
1164 // SetConfigPath sets the configuration file's path.
1165 func (c *Container) SetConfigPath(path string) error {
1166 c.mu.Lock()
1167 defer c.mu.Unlock()
1168
1169 if c.container == nil {
1170 return ErrNotDefined
1171 }
1172
1173 cpath := C.CString(path)
1174 defer C.free(unsafe.Pointer(cpath))
1175
1176 if !bool(C.go_lxc_set_config_path(c.container, cpath)) {
1177 return ErrSettingConfigPathFailed
1178 }
1179 return nil
1180 }
1181
1182 // MemoryUsage returns memory usage of the container in bytes.
1183 func (c *Container) MemoryUsage() (ByteSize, error) {
1184 c.mu.RLock()
1185 defer c.mu.RUnlock()
1186
1187 if err := c.makeSure(isRunning); err != nil {
1188 return -1, err
1189 }
1190
1191 return c.cgroupItemAsByteSize("memory.usage_in_bytes", ErrMemLimit)
1192 }
1193
1194 // MemoryLimit returns memory limit of the container in bytes.
1195 func (c *Container) MemoryLimit() (ByteSize, error) {
1196 c.mu.RLock()
1197 defer c.mu.RUnlock()
1198
1199 if err := c.makeSure(isRunning); err != nil {
1200 return -1, err
1201 }
1202
1203 return c.cgroupItemAsByteSize("memory.limit_in_bytes", ErrMemLimit)
1204 }
1205
1206 // SetMemoryLimit sets memory limit of the container in bytes.
1207 func (c *Container) SetMemoryLimit(limit ByteSize) error {
1208 c.mu.Lock()
1209 defer c.mu.Unlock()
1210
1211 if err := c.makeSure(isRunning); err != nil {
1212 return err
1213 }
1214
1215 return c.setCgroupItemWithByteSize("memory.limit_in_bytes", limit, ErrSettingMemoryLimitFailed)
1216 }
1217
1218 // SoftMemoryLimit returns soft memory limit of the container in bytes.
1219 func (c *Container) SoftMemoryLimit() (ByteSize, error) {
1220 c.mu.RLock()
1221 defer c.mu.RUnlock()
1222
1223 if err := c.makeSure(isRunning); err != nil {
1224 return -1, err
1225 }
1226
1227 return c.cgroupItemAsByteSize("memory.soft_limit_in_bytes", ErrSoftMemLimit)
1228 }
1229
1230 // SetSoftMemoryLimit sets soft memory limit of the container in bytes.
1231 func (c *Container) SetSoftMemoryLimit(limit ByteSize) error {
1232 c.mu.Lock()
1233 defer c.mu.Unlock()
1234
1235 if err := c.makeSure(isRunning); err != nil {
1236 return err
1237 }
1238
1239 return c.setCgroupItemWithByteSize("memory.soft_limit_in_bytes", limit, ErrSettingSoftMemoryLimitFailed)
1240 }
1241
1242 // KernelMemoryUsage returns current kernel memory allocation of the container in bytes.
1243 func (c *Container) KernelMemoryUsage() (ByteSize, error) {
1244 c.mu.RLock()
1245 defer c.mu.RUnlock()
1246
1247 if err := c.makeSure(isRunning); err != nil {
1248 return -1, err
1249 }
1250
1251 return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit)
1252 }
1253
1254 // KernelMemoryLimit returns kernel memory limit of the container in bytes.
1255 func (c *Container) KernelMemoryLimit() (ByteSize, error) {
1256 c.mu.RLock()
1257 defer c.mu.RUnlock()
1258
1259 if err := c.makeSure(isRunning); err != nil {
1260 return -1, err
1261 }
1262
1263 return c.cgroupItemAsByteSize("memory.kmem.limit_in_bytes", ErrKMemLimit)
1264 }
1265
1266 // SetKernelMemoryLimit sets kernel memory limit of the container in bytes.
1267 func (c *Container) SetKernelMemoryLimit(limit ByteSize) error {
1268 c.mu.Lock()
1269 defer c.mu.Unlock()
1270
1271 if err := c.makeSure(isRunning); err != nil {
1272 return err
1273 }
1274
1275 return c.setCgroupItemWithByteSize("memory.kmem.limit_in_bytes", limit, ErrSettingKMemoryLimitFailed)
1276 }
1277
1278 // MemorySwapUsage returns memory+swap usage of the container in bytes.
1279 func (c *Container) MemorySwapUsage() (ByteSize, error) {
1280 c.mu.RLock()
1281 defer c.mu.RUnlock()
1282
1283 if err := c.makeSure(isRunning); err != nil {
1284 return -1, err
1285 }
1286
1287 return c.cgroupItemAsByteSize("memory.memsw.usage_in_bytes", ErrMemorySwapLimit)
1288 }
1289
1290 // MemorySwapLimit returns the memory+swap limit of the container in bytes.
1291 func (c *Container) MemorySwapLimit() (ByteSize, error) {
1292 c.mu.RLock()
1293 defer c.mu.RUnlock()
1294
1295 if err := c.makeSure(isRunning); err != nil {
1296 return -1, err
1297 }
1298
1299 return c.cgroupItemAsByteSize("memory.memsw.limit_in_bytes", ErrMemorySwapLimit)
1300 }
1301
1302 // SetMemorySwapLimit sets memory+swap limit of the container in bytes.
1303 func (c *Container) SetMemorySwapLimit(limit ByteSize) error {
1304 c.mu.Lock()
1305 defer c.mu.Unlock()
1306
1307 if err := c.makeSure(isRunning); err != nil {
1308 return err
1309 }
1310
1311 return c.setCgroupItemWithByteSize("memory.memsw.limit_in_bytes", limit, ErrSettingMemorySwapLimitFailed)
1312 }
1313
1314 // BlkioUsage returns number of bytes transferred to/from the disk by the container.
1315 func (c *Container) BlkioUsage() (ByteSize, error) {
1316 c.mu.RLock()
1317 defer c.mu.RUnlock()
1318
1319 if err := c.makeSure(isRunning); err != nil {
1320 return -1, err
1321 }
1322
1323 ioServiceBytes := c.cgroupItem("blkio.throttle.io_service_bytes")
1324 if ioServiceBytes[0] == "" {
1325 return 0, nil
1326 }
1327
1328 for _, v := range ioServiceBytes {
1329 b := strings.Split(v, " ")
1330 if b[0] == "Total" {
1331 blkioUsed, err := strconv.ParseFloat(b[1], 64)
1332 if err != nil {
1333 return -1, err
1334 }
1335 return ByteSize(blkioUsed), nil
1336 }
1337 }
1338 return -1, ErrBlkioUsage
1339 }
1340
1341 // CPUTime returns the total CPU time (in nanoseconds) consumed by all tasks
1342 // in this cgroup (including tasks lower in the hierarchy).
1343 func (c *Container) CPUTime() (time.Duration, error) {
1344 c.mu.RLock()
1345 defer c.mu.RUnlock()
1346
1347 if err := c.makeSure(isRunning); err != nil {
1348 return -1, err
1349 }
1350
1351 usage := c.cgroupItem("cpuacct.usage")
1352 if usage[0] == "" {
1353 return 0, nil
1354 }
1355
1356 cpuUsage, err := strconv.ParseInt(usage[0], 10, 64)
1357 if err != nil {
1358 return -1, err
1359 }
1360 return time.Duration(cpuUsage), nil
1361 }
1362
1363 // CPUTimePerCPU returns the CPU time (in nanoseconds) consumed on each CPU by
1364 // all tasks in this cgroup (including tasks lower in the hierarchy).
1365 func (c *Container) CPUTimePerCPU() (map[int]time.Duration, error) {
1366 c.mu.RLock()
1367 defer c.mu.RUnlock()
1368
1369 if err := c.makeSure(isRunning); err != nil {
1370 return nil, err
1371 }
1372
1373 usagePerCPU := c.cgroupItem("cpuacct.usage_percpu")
1374 if usagePerCPU[0] == "" {
1375 return map[int]time.Duration{0: 0}, nil
1376 }
1377
1378 cpuTimes := make(map[int]time.Duration)
1379 for i, v := range strings.Split(usagePerCPU[0], " ") {
1380 cpuUsage, err := strconv.ParseInt(v, 10, 64)
1381 if err != nil {
1382 return nil, err
1383 }
1384 cpuTimes[i] = time.Duration(cpuUsage)
1385 }
1386 return cpuTimes, nil
1387 }
1388
1389 // CPUStats returns the number of CPU cycles (in the units defined by USER_HZ on the system)
1390 // consumed by tasks in this cgroup and its children in both user mode and system (kernel) mode.
1391 func (c *Container) CPUStats() (map[string]int64, error) {
1392 c.mu.RLock()
1393 defer c.mu.RUnlock()
1394
1395 if err := c.makeSure(isRunning); err != nil {
1396 return nil, err
1397 }
1398
1399 stat := c.cgroupItem("cpuacct.stat")
1400 if stat[0] == "" {
1401 return map[string]int64{"user": 0, "system": 0}, nil
1402 }
1403
1404 user, err := strconv.ParseInt(strings.Split(stat[0], "user ")[1], 10, 64)
1405 if err != nil {
1406 return nil, err
1407 }
1408 system, err := strconv.ParseInt(strings.Split(stat[1], "system ")[1], 10, 64)
1409 if err != nil {
1410 return nil, err
1411 }
1412
1413 return map[string]int64{"user": user, "system": system}, nil
1414 }
1415
1416 // ConsoleFd allocates a console tty from container
1417 // ttynum: tty number to attempt to allocate or -1 to allocate the first available tty
1418 //
1419 // Returns "ttyfd" on success, -1 on failure. The returned "ttyfd" is
1420 // used to keep the tty allocated. The caller should close "ttyfd" to
1421 // indicate that it is done with the allocated console so that it can
1422 // be allocated by another caller.
1423 func (c *Container) ConsoleFd(ttynum int) (int, error) {
1424 c.mu.Lock()
1425 defer c.mu.Unlock()
1426
1427 if c.container == nil {
1428 return -1, ErrNotDefined
1429 }
1430
1431 // FIXME: Make idiomatic
1432 if err := c.makeSure(isRunning); err != nil {
1433 return -1, err
1434 }
1435
1436 ret := int(C.go_lxc_console_getfd(c.container, C.int(ttynum)))
1437 if ret < 0 {
1438 return ret, ErrAttachFailed
1439 }
1440 return ret, nil
1441 }
1442
1443 // Console allocates and runs a console tty from container
1444 //
1445 // This function will not return until the console has been exited by the user.
1446 func (c *Container) Console(options ConsoleOptions) error {
1447 c.mu.Lock()
1448 defer c.mu.Unlock()
1449
1450 if c.container == nil {
1451 return ErrNotDefined
1452 }
1453
1454 if err := c.makeSure(isRunning); err != nil {
1455 return err
1456 }
1457
1458 ret := bool(C.go_lxc_console(c.container,
1459 C.int(options.Tty),
1460 C.int(options.StdinFd),
1461 C.int(options.StdoutFd),
1462 C.int(options.StderrFd),
1463 C.int(options.EscapeCharacter)))
1464
1465 if !ret {
1466 return ErrAttachFailed
1467 }
1468 return nil
1469 }
1470
1471 // AttachShell attaches a shell to the container.
1472 // It clears all environment variables before attaching.
1473 func (c *Container) AttachShell(options AttachOptions) error {
1474 c.mu.Lock()
1475 defer c.mu.Unlock()
1476
1477 if c.container == nil {
1478 return ErrNotDefined
1479 }
1480
1481 if err := c.makeSure(isRunning); err != nil {
1482 return err
1483 }
1484
1485 cenv := makeNullTerminatedArgs(options.Env)
1486 if cenv == nil {
1487 return ErrAllocationFailed
1488 }
1489 defer freeNullTerminatedArgs(cenv, len(options.Env))
1490
1491 cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep)
1492 if cenvToKeep == nil {
1493 return ErrAllocationFailed
1494 }
1495 defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep))
1496
1497 cwd := C.CString(options.Cwd)
1498 defer C.free(unsafe.Pointer(cwd))
1499
1500 groups := makeGroups(options.Groups)
1501
1502 ret := int(C.go_lxc_attach(c.container,
1503 C.bool(options.ClearEnv),
1504 C.int(options.Namespaces),
1505 C.long(options.Arch),
1506 C.uid_t(options.UID),
1507 C.gid_t(options.GID),
1508 groups,
1509 C.int(options.StdinFd),
1510 C.int(options.StdoutFd),
1511 C.int(options.StderrFd),
1512 cwd,
1513 cenv,
1514 cenvToKeep,
1515 C.int(attachFlags(options)),
1516 ))
1517 if ret < 0 {
1518 return ErrAttachFailed
1519 }
1520 return nil
1521 }
1522
1523 func attachFlags(opts AttachOptions) int {
1524 flags := C.LXC_ATTACH_DEFAULT
1525
1526 if opts.RemountSysProc {
1527 flags |= C.LXC_ATTACH_REMOUNT_PROC_SYS
1528 }
1529
1530 if opts.ElevatedPrivileges {
1531 flags &^= (C.LXC_ATTACH_MOVE_TO_CGROUP | C.LXC_ATTACH_DROP_CAPABILITIES | C.LXC_ATTACH_LSM_EXEC)
1532 }
1533 return flags
1534 }
1535
1536 func makeGroups(groups []int) C.struct_lxc_groups_t {
1537 if len(groups) == 0 {
1538 return C.struct_lxc_groups_t{size: 0, list: nil}
1539 }
1540 l := make([]C.gid_t, len(groups))
1541 for i, g := range groups {
1542 l[i] = C.gid_t(g)
1543 }
1544 return C.struct_lxc_groups_t{size: C.size_t(len(groups)), list: &l[0]}
1545 }
1546
1547 func (c *Container) runCommandStatus(args []string, options AttachOptions) (int, error) {
1548 if c.container == nil {
1549 return -1, ErrNotDefined
1550 }
1551
1552 if len(args) == 0 {
1553 return -1, ErrInsufficientNumberOfArguments
1554 }
1555
1556 if err := c.makeSure(isRunning); err != nil {
1557 return -1, err
1558 }
1559
1560 cargs := makeNullTerminatedArgs(args)
1561 if cargs == nil {
1562 return -1, ErrAllocationFailed
1563 }
1564 defer freeNullTerminatedArgs(cargs, len(args))
1565
1566 cenv := makeNullTerminatedArgs(options.Env)
1567 if cenv == nil {
1568 return -1, ErrAllocationFailed
1569 }
1570 defer freeNullTerminatedArgs(cenv, len(options.Env))
1571
1572 cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep)
1573 if cenvToKeep == nil {
1574 return -1, ErrAllocationFailed
1575 }
1576 defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep))
1577
1578 cwd := C.CString(options.Cwd)
1579 defer C.free(unsafe.Pointer(cwd))
1580
1581 groups := makeGroups(options.Groups)
1582
1583 ret := int(C.go_lxc_attach_run_wait(
1584 c.container,
1585 C.bool(options.ClearEnv),
1586 C.int(options.Namespaces),
1587 C.long(options.Arch),
1588 C.uid_t(options.UID),
1589 C.gid_t(options.GID),
1590 groups,
1591 C.int(options.StdinFd),
1592 C.int(options.StdoutFd),
1593 C.int(options.StderrFd),
1594 cwd,
1595 cenv,
1596 cenvToKeep,
1597 cargs,
1598 C.int(attachFlags(options)),
1599 ))
1600
1601 if ret < 0 {
1602 return ret, nil
1603 }
1604
1605 // Mirror the behavior of WEXITSTATUS().
1606 return int((ret & 0xFF00) >> 8), nil
1607 }
1608
1609 // RunCommandStatus attachs a shell and runs the command within the container.
1610 // The process will wait for the command to finish and return the result of
1611 // waitpid(), i.e. the process' exit status. An error is returned only when
1612 // invocation of the command completely fails.
1613 func (c *Container) RunCommandStatus(args []string, options AttachOptions) (int, error) {
1614 c.mu.Lock()
1615 defer c.mu.Unlock()
1616
1617 return c.runCommandStatus(args, options)
1618 }
1619
1620 // RunCommandNoWait runs the given command and returns without waiting it to finish.
1621 func (c *Container) RunCommandNoWait(args []string, options AttachOptions) (int, error) {
1622 c.mu.Lock()
1623 defer c.mu.Unlock()
1624
1625 if len(args) == 0 {
1626 return -1, ErrInsufficientNumberOfArguments
1627 }
1628
1629 if err := c.makeSure(isRunning); err != nil {
1630 return -1, err
1631 }
1632
1633 cargs := makeNullTerminatedArgs(args)
1634 if cargs == nil {
1635 return -1, ErrAllocationFailed
1636 }
1637 defer freeNullTerminatedArgs(cargs, len(args))
1638
1639 cenv := makeNullTerminatedArgs(options.Env)
1640 if cenv == nil {
1641 return -1, ErrAllocationFailed
1642 }
1643 defer freeNullTerminatedArgs(cenv, len(options.Env))
1644
1645 cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep)
1646 if cenvToKeep == nil {
1647 return -1, ErrAllocationFailed
1648 }
1649 defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep))
1650
1651 cwd := C.CString(options.Cwd)
1652 defer C.free(unsafe.Pointer(cwd))
1653
1654 groups := makeGroups(options.Groups)
1655
1656 var attachedPid C.pid_t
1657 ret := int(C.go_lxc_attach_no_wait(
1658 c.container,
1659 C.bool(options.ClearEnv),
1660 C.int(options.Namespaces),
1661 C.long(options.Arch),
1662 C.uid_t(options.UID),
1663 C.gid_t(options.GID),
1664 groups,
1665 C.int(options.StdinFd),
1666 C.int(options.StdoutFd),
1667 C.int(options.StderrFd),
1668 cwd,
1669 cenv,
1670 cenvToKeep,
1671 cargs,
1672 &attachedPid,
1673 C.int(attachFlags(options)),
1674 ))
1675
1676 if ret < 0 {
1677 return ret, ErrAttachFailed
1678 }
1679
1680 return int(attachedPid), nil
1681 }
1682
1683 // RunCommand attachs a shell and runs the command within the container.
1684 // The process will wait for the command to finish and return a success status. An error
1685 // is returned only when invocation of the command completely fails.
1686 func (c *Container) RunCommand(args []string, options AttachOptions) (bool, error) {
1687 c.mu.Lock()
1688 defer c.mu.Unlock()
1689
1690 ret, err := c.runCommandStatus(args, options)
1691 if err != nil {
1692 return false, err
1693 }
1694 if ret < 0 {
1695 return false, ErrAttachFailed
1696 }
1697 return ret == 0, nil
1698 }
1699
1700 // Interfaces returns the names of the network interfaces.
1701 func (c *Container) Interfaces() ([]string, error) {
1702 c.mu.RLock()
1703 defer c.mu.RUnlock()
1704
1705 if c.container == nil {
1706 return nil, ErrNotDefined
1707 }
1708
1709 if err := c.makeSure(isRunning); err != nil {
1710 return nil, err
1711 }
1712
1713 result := C.go_lxc_get_interfaces(c.container)
1714 if result == nil {
1715 return nil, ErrInterfaces
1716 }
1717 return convertArgs(result), nil
1718 }
1719
1720 // InterfaceStats returns the stats about container's network interfaces
1721 func (c *Container) InterfaceStats() (map[string]map[string]ByteSize, error) {
1722 c.mu.RLock()
1723 defer c.mu.RUnlock()
1724
1725 if err := c.makeSure(isRunning); err != nil {
1726 return nil, err
1727 }
1728
1729 var interfaceName string
1730
1731 statistics := make(map[string]map[string]ByteSize)
1732
1733 netPrefix := "lxc.net"
1734 if !VersionAtLeast(2, 1, 0) {
1735 netPrefix = "lxc.network"
1736 }
1737
1738 for i := 0; i < len(c.configItem(netPrefix)); i++ {
1739 interfaceType := c.runningConfigItem(fmt.Sprintf("%s.%d.type", netPrefix, i))
1740 if interfaceType == nil {
1741 continue
1742 }
1743
1744 if interfaceType[0] == "veth" {
1745 interfaceName = c.runningConfigItem(fmt.Sprintf("%s.%d.veth.pair", netPrefix, i))[0]
1746 } else {
1747 interfaceName = c.runningConfigItem(fmt.Sprintf("%s.%d.link", netPrefix, i))[0]
1748 }
1749
1750 for _, v := range []string{"rx", "tx"} {
1751 /* tx and rx are reversed from the host vs container */
1752 content, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/net/%s/statistics/%s_bytes", interfaceName, v))
1753 if err != nil {
1754 return nil, err
1755 }
1756
1757 bytes, err := strconv.ParseInt(strings.Split(string(content), "\n")[0], 10, 64)
1758 if err != nil {
1759 return nil, err
1760 }
1761
1762 if statistics[interfaceName] == nil {
1763 statistics[interfaceName] = make(map[string]ByteSize)
1764 }
1765 statistics[interfaceName][v] = ByteSize(bytes)
1766 }
1767 }
1768
1769 return statistics, nil
1770 }
1771
1772 // IPAddress returns the IP address of the given network interface.
1773 func (c *Container) IPAddress(interfaceName string) ([]string, error) {
1774 c.mu.RLock()
1775 defer c.mu.RUnlock()
1776
1777 if c.container == nil {
1778 return nil, ErrNotDefined
1779 }
1780
1781 if err := c.makeSure(isRunning); err != nil {
1782 return nil, err
1783 }
1784
1785 cinterface := C.CString(interfaceName)
1786 defer C.free(unsafe.Pointer(cinterface))
1787
1788 result := C.go_lxc_get_ips(c.container, cinterface, nil, 0)
1789 if result == nil {
1790 return nil, ErrIPAddress
1791 }
1792 return convertArgs(result), nil
1793 }
1794
1795 // IPv4Address returns the IPv4 address of the given network interface.
1796 func (c *Container) IPv4Address(interfaceName string) ([]string, error) {
1797 c.mu.RLock()
1798 defer c.mu.RUnlock()
1799
1800 if c.container == nil {
1801 return nil, ErrNotDefined
1802 }
1803
1804 if err := c.makeSure(isRunning); err != nil {
1805 return nil, err
1806 }
1807
1808 cinterface := C.CString(interfaceName)
1809 defer C.free(unsafe.Pointer(cinterface))
1810
1811 cfamily := C.CString("inet")
1812 defer C.free(unsafe.Pointer(cfamily))
1813
1814 result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0)
1815 if result == nil {
1816 return nil, ErrIPv4Addresses
1817 }
1818 return convertArgs(result), nil
1819 }
1820
1821 // IPv6Address returns the IPv6 address of the given network interface.
1822 func (c *Container) IPv6Address(interfaceName string) ([]string, error) {
1823 c.mu.RLock()
1824 defer c.mu.RUnlock()
1825
1826 if c.container == nil {
1827 return nil, ErrNotDefined
1828 }
1829
1830 if err := c.makeSure(isRunning); err != nil {
1831 return nil, err
1832 }
1833
1834 cinterface := C.CString(interfaceName)
1835 defer C.free(unsafe.Pointer(cinterface))
1836
1837 cfamily := C.CString("inet6")
1838 defer C.free(unsafe.Pointer(cfamily))
1839
1840 result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0)
1841 if result == nil {
1842 return nil, ErrIPv6Addresses
1843 }
1844 return convertArgs(result), nil
1845 }
1846
1847 // WaitIPAddresses waits until IPAddresses call returns something or time outs
1848 func (c *Container) WaitIPAddresses(timeout time.Duration) ([]string, error) {
1849 c.mu.RLock()
1850 defer c.mu.RUnlock()
1851
1852 now := time.Now()
1853 for {
1854 if result, err := c.ipAddresses(); err == nil && len(result) > 0 {
1855 return result, nil
1856 }
1857 // Python API sleeps 1 second as well
1858 time.Sleep(1 * time.Second)
1859
1860 if time.Since(now) >= timeout {
1861 return nil, ErrIPAddresses
1862 }
1863 }
1864 }
1865
1866 func (c *Container) ipAddresses() ([]string, error) {
1867 if c.container == nil {
1868 return nil, ErrNotDefined
1869 }
1870
1871 if err := c.makeSure(isRunning); err != nil {
1872 return nil, err
1873 }
1874
1875 result := C.go_lxc_get_ips(c.container, nil, nil, 0)
1876 if result == nil {
1877 return nil, ErrIPAddresses
1878 }
1879 return convertArgs(result), nil
1880
1881 }
1882
1883 // IPAddresses returns all IP addresses.
1884 func (c *Container) IPAddresses() ([]string, error) {
1885 c.mu.RLock()
1886 defer c.mu.RUnlock()
1887
1888 return c.ipAddresses()
1889 }
1890
1891 // IPv4Addresses returns all IPv4 addresses.
1892 func (c *Container) IPv4Addresses() ([]string, error) {
1893 c.mu.RLock()
1894 defer c.mu.RUnlock()
1895
1896 if c.container == nil {
1897 return nil, ErrNotDefined
1898 }
1899
1900 if err := c.makeSure(isRunning); err != nil {
1901 return nil, err
1902 }
1903
1904 cfamily := C.CString("inet")
1905 defer C.free(unsafe.Pointer(cfamily))
1906
1907 result := C.go_lxc_get_ips(c.container, nil, cfamily, 0)
1908 if result == nil {
1909 return nil, ErrIPv4Addresses
1910 }
1911 return convertArgs(result), nil
1912 }
1913
1914 // IPv6Addresses returns all IPv6 addresses.
1915 func (c *Container) IPv6Addresses() ([]string, error) {
1916 c.mu.RLock()
1917 defer c.mu.RUnlock()
1918
1919 if c.container == nil {
1920 return nil, ErrNotDefined
1921 }
1922
1923 if err := c.makeSure(isRunning); err != nil {
1924 return nil, err
1925 }
1926
1927 cfamily := C.CString("inet6")
1928 defer C.free(unsafe.Pointer(cfamily))
1929
1930 result := C.go_lxc_get_ips(c.container, nil, cfamily, 0)
1931 if result == nil {
1932 return nil, ErrIPv6Addresses
1933 }
1934 return convertArgs(result), nil
1935 }
1936
1937 // LogFile returns the name of the logfile.
1938 func (c *Container) LogFile() string {
1939 c.mu.RLock()
1940 defer c.mu.RUnlock()
1941
1942 if VersionAtLeast(2, 1, 0) {
1943 return c.configItem("lxc.log.file")[0]
1944 }
1945
1946 return c.configItem("lxc.logfile")[0]
1947 }
1948
1949 // SetLogFile sets the name of the logfile.
1950 func (c *Container) SetLogFile(filename string) error {
1951 c.mu.Lock()
1952 defer c.mu.Unlock()
1953
1954 var err error
1955 if VersionAtLeast(2, 1, 0) {
1956 err = c.setConfigItem("lxc.log.file", filename)
1957 } else {
1958 err = c.setConfigItem("lxc.logfile", filename)
1959 }
1960 if err != nil {
1961 return err
1962 }
1963
1964 return nil
1965 }
1966
1967 // LogLevel returns the level of the logfile.
1968 func (c *Container) LogLevel() LogLevel {
1969 c.mu.RLock()
1970 defer c.mu.RUnlock()
1971
1972 if VersionAtLeast(2, 1, 0) {
1973 return logLevelMap[c.configItem("lxc.log.level")[0]]
1974 }
1975
1976 return logLevelMap[c.configItem("lxc.loglevel")[0]]
1977 }
1978
1979 // SetLogLevel sets the level of the logfile.
1980 func (c *Container) SetLogLevel(level LogLevel) error {
1981 c.mu.Lock()
1982 defer c.mu.Unlock()
1983
1984 var err error
1985 if VersionAtLeast(2, 1, 0) {
1986 err = c.setConfigItem("lxc.log.level", level.String())
1987 } else {
1988 err = c.setConfigItem("lxc.loglevel", level.String())
1989 }
1990 if err != nil {
1991 return err
1992 }
1993 return nil
1994 }
1995
1996 // AddDeviceNode adds specified device to the container.
1997 func (c *Container) AddDeviceNode(source string, destination ...string) error {
1998 c.mu.Lock()
1999 defer c.mu.Unlock()
2000
2001 if c.container == nil {
2002 return ErrNotDefined
2003 }
2004
2005 if err := c.makeSure(isRunning | isPrivileged); err != nil {
2006 return err
2007 }
2008
2009 csource := C.CString(source)
2010 defer C.free(unsafe.Pointer(csource))
2011
2012 if destination != nil && len(destination) == 1 {
2013 cdestination := C.CString(destination[0])
2014 defer C.free(unsafe.Pointer(cdestination))
2015
2016 if !bool(C.go_lxc_add_device_node(c.container, csource, cdestination)) {
2017 return ErrAddDeviceNodeFailed
2018 }
2019 return nil
2020 }
2021
2022 if !bool(C.go_lxc_add_device_node(c.container, csource, nil)) {
2023 return ErrAddDeviceNodeFailed
2024 }
2025 return nil
2026 }
2027
2028 // RemoveDeviceNode removes the specified device from the container.
2029 func (c *Container) RemoveDeviceNode(source string, destination ...string) error {
2030 c.mu.Lock()
2031 defer c.mu.Unlock()
2032
2033 if c.container == nil {
2034 return ErrNotDefined
2035 }
2036
2037 if err := c.makeSure(isRunning | isPrivileged); err != nil {
2038 return err
2039 }
2040
2041 csource := C.CString(source)
2042 defer C.free(unsafe.Pointer(csource))
2043
2044 if destination != nil && len(destination) == 1 {
2045 cdestination := C.CString(destination[0])
2046 defer C.free(unsafe.Pointer(cdestination))
2047
2048 if !bool(C.go_lxc_remove_device_node(c.container, csource, cdestination)) {
2049 return ErrRemoveDeviceNodeFailed
2050 }
2051 return nil
2052 }
2053
2054 if !bool(C.go_lxc_remove_device_node(c.container, csource, nil)) {
2055 return ErrRemoveDeviceNodeFailed
2056 }
2057 return nil
2058 }
2059
2060 // Checkpoint checkpoints the container.
2061 func (c *Container) Checkpoint(opts CheckpointOptions) error {
2062 c.mu.Lock()
2063 defer c.mu.Unlock()
2064
2065 if c.container == nil {
2066 return ErrNotDefined
2067 }
2068
2069 if err := c.makeSure(isRunning | isGreaterEqualThanLXC11); err != nil {
2070 return err
2071 }
2072
2073 cdirectory := C.CString(opts.Directory)
2074 defer C.free(unsafe.Pointer(cdirectory))
2075
2076 cstop := C.bool(opts.Stop)
2077 cverbose := C.bool(opts.Verbose)
2078
2079 if !C.go_lxc_checkpoint(c.container, cdirectory, cstop, cverbose) {
2080 return ErrCheckpointFailed
2081 }
2082 return nil
2083 }
2084
2085 // Restore restores the container from a checkpoint.
2086 func (c *Container) Restore(opts RestoreOptions) error {
2087 c.mu.Lock()
2088 defer c.mu.Unlock()
2089
2090 if c.container == nil {
2091 return ErrNotDefined
2092 }
2093
2094 if err := c.makeSure(isGreaterEqualThanLXC11); err != nil {
2095 return err
2096 }
2097
2098 cdirectory := C.CString(opts.Directory)
2099 defer C.free(unsafe.Pointer(cdirectory))
2100
2101 cverbose := C.bool(opts.Verbose)
2102
2103 if !C.bool(C.go_lxc_restore(c.container, cdirectory, cverbose)) {
2104 return ErrRestoreFailed
2105 }
2106 return nil
2107 }
2108
2109 // Migrate migrates the container.
2110 func (c *Container) Migrate(cmd uint, opts MigrateOptions) error {
2111 c.mu.Lock()
2112 defer c.mu.Unlock()
2113
2114 if c.container == nil {
2115 return ErrNotDefined
2116 }
2117
2118 if err := c.makeSure(isGreaterEqualThanLXC20); err != nil {
2119 return err
2120 }
2121
2122 if cmd != MIGRATE_RESTORE {
2123 if err := c.makeSure(isRunning); err != nil {
2124 return err
2125 }
2126 }
2127
2128 cdirectory := C.CString(opts.Directory)
2129 defer C.free(unsafe.Pointer(cdirectory))
2130
2131 var cpredumpdir *C.char
2132
2133 if opts.PredumpDir != "" {
2134 cpredumpdir = C.CString(opts.PredumpDir)
2135 defer C.free(unsafe.Pointer(cpredumpdir))
2136 }
2137
2138 /* Since we can't do conditional compilation here, we allocate the
2139 * "extras" struct and then merge them in the C code.
2140 */
2141 copts := C.struct_migrate_opts{
2142 directory: cdirectory,
2143 verbose: C.bool(opts.Verbose),
2144 stop: C.bool(opts.Stop),
2145 predump_dir: cpredumpdir,
2146 }
2147
2148 var cActionScript *C.char
2149 if opts.ActionScript != "" {
2150 cActionScript = C.CString(opts.ActionScript)
2151 defer C.free(unsafe.Pointer(cActionScript))
2152 }
2153
2154 extras := C.struct_extra_migrate_opts{
2155 preserves_inodes: C.bool(opts.PreservesInodes),
2156 action_script: cActionScript,
2157 ghost_limit: C.uint64_t(opts.GhostLimit),
2158 features_to_check: C.uint64_t(opts.FeaturesToCheck),
2159 }
2160
2161 ret := C.int(C.go_lxc_migrate(c.container, C.uint(cmd), &copts, &extras))
2162 if ret != 0 {
2163 return fmt.Errorf("migration failed %d", ret)
2164 }
2165
2166 return nil
2167 }
2168
2169 // AttachInterface attaches specified netdev to the container.
2170 func (c *Container) AttachInterface(source, destination string) error {
2171 c.mu.Lock()
2172 defer c.mu.Unlock()
2173
2174 if c.container == nil {
2175 return ErrNotDefined
2176 }
2177
2178 if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil {
2179 return err
2180 }
2181
2182 csource := C.CString(source)
2183 defer C.free(unsafe.Pointer(csource))
2184
2185 cdestination := C.CString(destination)
2186 defer C.free(unsafe.Pointer(cdestination))
2187
2188 if !bool(C.go_lxc_attach_interface(c.container, csource, cdestination)) {
2189 return ErrAttachInterfaceFailed
2190 }
2191 return nil
2192 }
2193
2194 // DetachInterface detaches specified netdev from the container.
2195 func (c *Container) DetachInterface(source string) error {
2196 c.mu.Lock()
2197 defer c.mu.Unlock()
2198
2199 if c.container == nil {
2200 return ErrNotDefined
2201 }
2202
2203 if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil {
2204 return err
2205 }
2206
2207 csource := C.CString(source)
2208 defer C.free(unsafe.Pointer(csource))
2209
2210 if !bool(C.go_lxc_detach_interface(c.container, csource, nil)) {
2211 return ErrDetachInterfaceFailed
2212 }
2213 return nil
2214 }
2215
2216 // DetachInterfaceRename detaches specified netdev from the container and renames it.
2217 func (c *Container) DetachInterfaceRename(source, target string) error {
2218 c.mu.Lock()
2219 defer c.mu.Unlock()
2220
2221 if c.container == nil {
2222 return ErrNotDefined
2223 }
2224
2225 if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil {
2226 return err
2227 }
2228
2229 csource := C.CString(source)
2230 defer C.free(unsafe.Pointer(csource))
2231
2232 ctarget := C.CString(target)
2233 defer C.free(unsafe.Pointer(ctarget))
2234
2235 if !bool(C.go_lxc_detach_interface(c.container, csource, ctarget)) {
2236 return ErrDetachInterfaceFailed
2237 }
2238 return nil
2239 }
2240
2241 // ConsoleLog allows to perform operations on the container's in-memory console
2242 // buffer.
2243 func (c *Container) ConsoleLog(opt ConsoleLogOptions) ([]byte, error) {
2244 c.mu.Lock()
2245 defer c.mu.Unlock()
2246
2247 if c.container == nil {
2248 return nil, ErrNotDefined
2249 }
2250
2251 cl := C.struct_lxc_console_log{
2252 clear: C.bool(opt.ClearLog),
2253 read: C.bool(opt.ReadLog),
2254 data: nil,
2255 }
2256 // CGO is a fickle little beast:
2257 // We need to manually allocate memory here that we pass to C. If we
2258 // were to pass a GO pointer by passing a C.uint64_t pointer we'd end in
2259 // the situation where we have a GO pointer that points to a GO pointer.
2260 // Go will freak out when this happens. So give C its own memory.
2261 var buf unsafe.Pointer
2262 buf = C.malloc(C.sizeof_uint64_t)
2263 if buf == nil {
2264 return nil, syscall.ENOMEM
2265 }
2266 defer C.free(buf)
2267
2268 cl.read_max = (*C.uint64_t)(buf)
2269 *cl.read_max = C.uint64_t(opt.ReadMax)
2270
2271 ret := C.go_lxc_console_log(c.container, &cl)
2272 if ret < 0 {
2273 return nil, syscall.Errno(-ret)
2274 }
2275
2276 numBytes := C.int(*cl.read_max)
2277 if C.uint64_t(numBytes) != *cl.read_max {
2278 return nil, syscall.ERANGE
2279 }
2280
2281 return C.GoBytes(unsafe.Pointer(cl.data), numBytes), nil
2282 }
2283
2284 // ErrorNum returns the error_num field of the container.
2285 func (c *Container) ErrorNum() int {
2286 if c.container == nil {
2287 return -1
2288 }
2289
2290 cError := C.go_lxc_error_num(c.container)
2291 return int(cError)
2292 }
2293
2294 func buildBdevSpecs(o *BackendStoreSpecs) *C.struct_bdev_specs {
2295 if o == nil {
2296 return nil
2297 }
2298
2299 // bdev_specs:
2300 // zfs requires zfsroot
2301 // lvm requires lvname/vgname/thinpool as well as fstype and fssize
2302 // btrfs requires nothing
2303 // dir requires nothing
2304
2305 specs := C.struct_bdev_specs{}
2306
2307 if o.FSType != "" {
2308 fstype := C.CString(o.FSType)
2309 specs.fstype = fstype
2310 defer C.free(unsafe.Pointer(fstype))
2311 }
2312
2313 if o.FSSize > 0 {
2314 specs.fssize = C.uint64_t(o.FSSize)
2315 }
2316
2317 if o.ZFS.Root != "" {
2318 zfsroot := C.CString(o.ZFS.Root)
2319 specs.zfs.zfsroot = zfsroot
2320 defer C.free(unsafe.Pointer(zfsroot))
2321 }
2322
2323 if o.LVM.VG != "" {
2324 vg := C.CString(o.LVM.VG)
2325 specs.lvm.vg = vg
2326 defer C.free(unsafe.Pointer(vg))
2327 }
2328
2329 if o.LVM.Thinpool != "" {
2330 lv := C.CString(o.LVM.Thinpool)
2331 specs.lvm.thinpool = lv
2332 defer C.free(unsafe.Pointer(lv))
2333 }
2334
2335 if o.RBD.Name != "" {
2336 lv := C.CString(o.RBD.Name)
2337 specs.rbd.rbdname = lv
2338 defer C.free(unsafe.Pointer(lv))
2339 }
2340
2341 if o.RBD.Pool != "" {
2342 lv := C.CString(o.RBD.Pool)
2343 specs.rbd.rbdpool = lv
2344 defer C.free(unsafe.Pointer(lv))
2345 }
2346
2347 if o.Dir != nil {
2348 dir := C.CString(*o.Dir)
2349 specs.dir = dir
2350 defer C.free(unsafe.Pointer(dir))
2351 }
2352
2353 return &specs
2354 }