forked from lxc/go-lxc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
container.go
1677 lines (1351 loc) · 40 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 © 2013, 2014, The Go-LXC Authors. All rights reserved.
// Use of this source code is governed by a LGPLv2.1
// license that can be found in the LICENSE file.
// +build linux,cgo
package lxc
// #include <lxc/lxccontainer.h>
// #include <lxc/version.h>
// #include "lxc-binding.h"
import "C"
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"reflect"
"strconv"
"strings"
"sync"
"time"
"unsafe"
)
// Container struct
type Container struct {
container *C.struct_lxc_container
mu sync.RWMutex
verbosity Verbosity
}
// Snapshot struct
type Snapshot struct {
Name string
CommentPath string
Timestamp string
Path string
}
const (
isDefined = 1 << iota
isNotDefined
isRunning
isNotRunning
isPrivileged
isUnprivileged
isGreaterEqualThanLXC11
isGreaterEqualThanLXC20
)
func (c *Container) makeSure(flags int) error {
if flags&isDefined != 0 && !c.Defined() {
return ErrNotDefined
}
if flags&isNotDefined != 0 && c.Defined() {
return ErrAlreadyDefined
}
if flags&isRunning != 0 && !c.Running() {
return ErrNotRunning
}
if flags&isNotRunning != 0 && c.Running() {
return ErrAlreadyRunning
}
if flags&isPrivileged != 0 && os.Geteuid() != 0 {
return ErrMethodNotAllowed
}
if flags&isGreaterEqualThanLXC11 != 0 && !VersionAtLeast(1, 1, 0) {
return ErrNotSupported
}
if flags&isGreaterEqualThanLXC20 != 0 && !VersionAtLeast(2, 0, 0) {
return ErrNotSupported
}
return nil
}
func (c *Container) cgroupItemAsByteSize(filename string, missing error) (ByteSize, error) {
size, err := strconv.ParseFloat(c.CgroupItem(filename)[0], 64)
if err != nil {
return -1, missing
}
return ByteSize(size), nil
}
func (c *Container) setCgroupItemWithByteSize(filename string, limit ByteSize, missing error) error {
if err := c.SetCgroupItem(filename, fmt.Sprintf("%.f", limit)); err != nil {
return missing
}
return nil
}
// Name returns the name of the container.
func (c *Container) Name() string {
c.mu.RLock()
defer c.mu.RUnlock()
return C.GoString(c.container.name)
}
// Defined returns true if the container is already defined.
func (c *Container) Defined() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return bool(C.go_lxc_defined(c.container))
}
// Running returns true if the container is already running.
func (c *Container) Running() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return bool(C.go_lxc_running(c.container))
}
// Controllable returns true if the caller can control the container.
func (c *Container) Controllable() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return bool(C.go_lxc_may_control(c.container))
}
// CreateSnapshot creates a new snapshot.
func (c *Container) CreateSnapshot() (*Snapshot, error) {
if err := c.makeSure(isDefined | isNotRunning); err != nil {
return nil, err
}
c.mu.Lock()
defer c.mu.Unlock()
ret := int(C.go_lxc_snapshot(c.container))
if ret < 0 {
return nil, ErrCreateSnapshotFailed
}
return &Snapshot{Name: fmt.Sprintf("snap%d", ret)}, nil
}
// RestoreSnapshot creates a new container based on a snapshot.
func (c *Container) RestoreSnapshot(snapshot Snapshot, name string) error {
if err := c.makeSure(isDefined); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
csnapname := C.CString(snapshot.Name)
defer C.free(unsafe.Pointer(csnapname))
if !bool(C.go_lxc_snapshot_restore(c.container, csnapname, cname)) {
return ErrRestoreSnapshotFailed
}
return nil
}
// DestroySnapshot destroys the specified snapshot.
func (c *Container) DestroySnapshot(snapshot Snapshot) error {
if err := c.makeSure(isDefined); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
csnapname := C.CString(snapshot.Name)
defer C.free(unsafe.Pointer(csnapname))
if !bool(C.go_lxc_snapshot_destroy(c.container, csnapname)) {
return ErrDestroySnapshotFailed
}
return nil
}
// DestroyAllSnapshots destroys all the snapshot.
func (c *Container) DestroyAllSnapshots() error {
if err := c.makeSure(isDefined | isGreaterEqualThanLXC11); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_snapshot_destroy_all(c.container)) {
return ErrDestroyAllSnapshotsFailed
}
return nil
}
// Snapshots returns the list of container snapshots.
func (c *Container) Snapshots() ([]Snapshot, error) {
if err := c.makeSure(isDefined); err != nil {
return nil, err
}
c.mu.Lock()
defer c.mu.Unlock()
var csnapshots *C.struct_lxc_snapshot
size := int(C.go_lxc_snapshot_list(c.container, &csnapshots))
defer freeSnapshots(csnapshots, size)
if size < 1 {
return nil, ErrNoSnapshot
}
hdr := reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(csnapshots)),
Len: size,
Cap: size,
}
gosnapshots := *(*[]C.struct_lxc_snapshot)(unsafe.Pointer(&hdr))
snapshots := make([]Snapshot, size, size)
for i := 0; i < size; i++ {
snapshots[i] = Snapshot{
Name: C.GoString(gosnapshots[i].name),
Timestamp: C.GoString(gosnapshots[i].timestamp),
CommentPath: C.GoString(gosnapshots[i].comment_pathname),
Path: C.GoString(gosnapshots[i].lxcpath),
}
}
return snapshots, nil
}
// State returns the state of the container.
func (c *Container) State() State {
c.mu.RLock()
defer c.mu.RUnlock()
return StateMap[C.GoString(C.go_lxc_state(c.container))]
}
// InitPid returns the process ID of the container's init process
// seen from outside the container.
func (c *Container) InitPid() int {
c.mu.RLock()
defer c.mu.RUnlock()
return int(C.go_lxc_init_pid(c.container))
}
// Daemonize returns true if the container wished to be daemonized.
func (c *Container) Daemonize() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return bool(c.container.daemonize)
}
// WantDaemonize determines if the container wants to run daemonized.
func (c *Container) WantDaemonize(state bool) error {
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_want_daemonize(c.container, C.bool(state))) {
return ErrDaemonizeFailed
}
return nil
}
// WantCloseAllFds determines whether container wishes all file descriptors
// to be closed on startup.
func (c *Container) WantCloseAllFds(state bool) error {
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_want_close_all_fds(c.container, C.bool(state))) {
return ErrCloseAllFdsFailed
}
return nil
}
// SetVerbosity sets the verbosity level of some API calls
func (c *Container) SetVerbosity(verbosity Verbosity) {
c.mu.Lock()
defer c.mu.Unlock()
c.verbosity = verbosity
}
// Freeze freezes the running container.
func (c *Container) Freeze() error {
if err := c.makeSure(isRunning); err != nil {
return err
}
if c.State() == FROZEN {
return ErrAlreadyFrozen
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_freeze(c.container)) {
return ErrFreezeFailed
}
return nil
}
// Unfreeze thaws the frozen container.
func (c *Container) Unfreeze() error {
if err := c.makeSure(isRunning); err != nil {
return err
}
if c.State() != FROZEN {
return ErrNotFrozen
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_unfreeze(c.container)) {
return ErrUnfreezeFailed
}
return nil
}
// Create creates the container using given TemplateOptions
func (c *Container) Create(options TemplateOptions) error {
// FIXME: Support bdev_specs
//
// bdev_specs:
// zfs requires zfsroot
// lvm requires lvname/vgname/thinpool as well as fstype and fssize
// btrfs requires nothing
// dir requires nothing
if err := c.makeSure(isNotDefined); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
// use download template if not set
if options.Template == "" {
options.Template = "download"
}
// use Directory backend if not set
if options.Backend == 0 {
options.Backend = Directory
}
// unprivileged users are only allowed to use "download" template
if os.Geteuid() != 0 && options.Template != "download" {
return ErrTemplateNotAllowed
}
var args []string
if options.Template == "download" {
// required parameters
if options.Distro == "" || options.Release == "" || options.Arch == "" {
return ErrInsufficientNumberOfArguments
}
args = append(args, "--dist", options.Distro, "--release", options.Release, "--arch", options.Arch)
// optional arguments
if options.Variant != "" {
args = append(args, "--variant", options.Variant)
}
if options.Server != "" {
args = append(args, "--server", options.Server)
}
if options.KeyID != "" {
args = append(args, "--keyid", options.KeyID)
}
if options.KeyServer != "" {
args = append(args, "--keyserver", options.KeyServer)
}
if options.DisableGPGValidation {
args = append(args, "--no-validate")
}
if options.FlushCache {
args = append(args, "--flush-cache")
}
if options.ForceCache {
args = append(args, "--force-cache")
}
} else {
// optional arguments
if options.Release != "" {
args = append(args, "--release", options.Release)
}
if options.Arch != "" {
args = append(args, "--arch", options.Arch)
}
if options.FlushCache {
args = append(args, "--flush-cache")
}
}
if options.ExtraArgs != nil {
args = append(args, options.ExtraArgs...)
}
ctemplate := C.CString(options.Template)
defer C.free(unsafe.Pointer(ctemplate))
cbackend := C.CString(options.Backend.String())
defer C.free(unsafe.Pointer(cbackend))
ret := false
if args != nil {
cargs := makeNullTerminatedArgs(args)
if cargs == nil {
return ErrAllocationFailed
}
defer freeNullTerminatedArgs(cargs, len(args))
ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), cargs))
} else {
ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), nil))
}
if !ret {
return ErrCreateFailed
}
return nil
}
// Start starts the container.
func (c *Container) Start() error {
if err := c.makeSure(isNotRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_start(c.container, 0, nil)) {
return ErrStartFailed
}
return nil
}
func (c *Container) StartWithArgs(args []string) error {
if err := c.makeSure(isNotRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_start(c.container, 0, makeNullTerminatedArgs(args))) {
return ErrStartFailed
}
return nil
}
// Execute executes the given command in a temporary container.
func (c *Container) Execute(args ...string) ([]byte, error) {
if err := c.makeSure(isNotDefined); err != nil {
return nil, err
}
cargs := []string{"lxc-execute", "-n", c.Name(), "-P", c.ConfigPath(), "--"}
cargs = append(cargs, args...)
c.mu.Lock()
defer c.mu.Unlock()
// FIXME: Go runtime and src/lxc/start.c signal_handler are not playing nice together so use lxc-execute for now
// go-nuts thread: https://groups.google.com/forum/#!msg/golang-nuts/h9GbvfYv83w/5Ly_jvOr86wJ
output, err := exec.Command(cargs[0], cargs[1:]...).CombinedOutput()
if err != nil {
return nil, ErrExecuteFailed
}
return output, nil
/*
cargs := makeNullTerminatedArgs(args)
if cargs == nil {
return ErrAllocationFailed
}
defer freeNullTerminatedArgs(cargs, len(args))
if !bool(C.go_lxc_start(c.container, 1, cargs)) {
return ErrExecuteFailed
}
return nil
*/
}
// Stop stops the container.
func (c *Container) Stop() error {
if err := c.makeSure(isRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_stop(c.container)) {
return ErrStopFailed
}
return nil
}
// Reboot reboots the container.
func (c *Container) Reboot() error {
if err := c.makeSure(isRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_reboot(c.container)) {
return ErrRebootFailed
}
return nil
}
// Shutdown shuts down the container.
func (c *Container) Shutdown(timeout time.Duration) error {
if err := c.makeSure(isRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_shutdown(c.container, C.int(timeout.Seconds()))) {
return ErrShutdownFailed
}
return nil
}
// Destroy destroys the container.
func (c *Container) Destroy() error {
if err := c.makeSure(isDefined | isNotRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_destroy(c.container)) {
return ErrDestroyFailed
}
return nil
}
// DestroyWithAllSnapshots destroys the container and its snapshots
func (c *Container) DestroyWithAllSnapshots() error {
if err := c.makeSure(isDefined | isNotRunning | isGreaterEqualThanLXC11); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if !bool(C.go_lxc_destroy_with_snapshots(c.container)) {
return ErrDestroyWithAllSnapshotsFailed
}
return nil
}
// Clone clones the container using given arguments with specified backend.
func (c *Container) Clone(name string, options CloneOptions) error {
// FIXME: bdevdata, newsize and hookargs
//
// bdevdata:
// zfs requires zfsroot
// lvm requires lvname/vgname/thinpool as well as fstype and fssize
// btrfs requires nothing
// dir requires nothing
//
// newsize: for blockdev-backed backingstores
//
// hookargs: additional arguments to pass to the clone hook script
if err := c.makeSure(isDefined | isNotRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
// use Directory backend if not set
if options.Backend == 0 {
options.Backend = Directory
}
var flags int
if options.KeepName {
flags |= C.LXC_CLONE_KEEPNAME
}
if options.KeepMAC {
flags |= C.LXC_CLONE_KEEPMACADDR
}
if options.Snapshot {
flags |= C.LXC_CLONE_SNAPSHOT
}
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
cbackend := C.CString(options.Backend.String())
defer C.free(unsafe.Pointer(cbackend))
if options.ConfigPath != "" {
clxcpath := C.CString(options.ConfigPath)
defer C.free(unsafe.Pointer(clxcpath))
if !bool(C.go_lxc_clone(c.container, cname, clxcpath, C.int(flags), cbackend)) {
return ErrCloneFailed
}
} else {
if !bool(C.go_lxc_clone(c.container, cname, nil, C.int(flags), cbackend)) {
return ErrCloneFailed
}
}
return nil
}
// Rename renames the container.
func (c *Container) Rename(name string) error {
if err := c.makeSure(isDefined | isNotRunning); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
if !bool(C.go_lxc_rename(c.container, cname)) {
return ErrRenameFailed
}
return nil
}
// Wait waits for container to reach a particular state.
func (c *Container) Wait(state State, timeout time.Duration) bool {
c.mu.Lock()
defer c.mu.Unlock()
cstate := C.CString(state.String())
defer C.free(unsafe.Pointer(cstate))
return bool(C.go_lxc_wait(c.container, cstate, C.int(timeout.Seconds())))
}
// ConfigFileName returns the container's configuration file's name.
func (c *Container) ConfigFileName() string {
c.mu.RLock()
defer c.mu.RUnlock()
// allocated in lxc.c
configFileName := C.go_lxc_config_file_name(c.container)
defer C.free(unsafe.Pointer(configFileName))
return C.GoString(configFileName)
}
// ConfigItem returns the value of the given config item.
func (c *Container) ConfigItem(key string) []string {
c.mu.RLock()
defer c.mu.RUnlock()
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
// allocated in lxc.c
configItem := C.go_lxc_get_config_item(c.container, ckey)
defer C.free(unsafe.Pointer(configItem))
ret := strings.TrimSpace(C.GoString(configItem))
return strings.Split(ret, "\n")
}
// SetConfigItem sets the value of the given config item.
func (c *Container) SetConfigItem(key string, value string) error {
c.mu.Lock()
defer c.mu.Unlock()
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
cvalue := C.CString(value)
defer C.free(unsafe.Pointer(cvalue))
if !bool(C.go_lxc_set_config_item(c.container, ckey, cvalue)) {
return ErrSettingConfigItemFailed
}
return nil
}
// RunningConfigItem returns the value of the given config item.
func (c *Container) RunningConfigItem(key string) []string {
c.mu.RLock()
defer c.mu.RUnlock()
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
// allocated in lxc.c
configItem := C.go_lxc_get_running_config_item(c.container, ckey)
defer C.free(unsafe.Pointer(configItem))
ret := strings.TrimSpace(C.GoString(configItem))
return strings.Split(ret, "\n")
}
// CgroupItem returns the value of the given cgroup subsystem value.
func (c *Container) CgroupItem(key string) []string {
c.mu.RLock()
defer c.mu.RUnlock()
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
// allocated in lxc.c
cgroupItem := C.go_lxc_get_cgroup_item(c.container, ckey)
defer C.free(unsafe.Pointer(cgroupItem))
ret := strings.TrimSpace(C.GoString(cgroupItem))
return strings.Split(ret, "\n")
}
// SetCgroupItem sets the value of given cgroup subsystem value.
func (c *Container) SetCgroupItem(key string, value string) error {
c.mu.Lock()
defer c.mu.Unlock()
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
cvalue := C.CString(value)
defer C.free(unsafe.Pointer(cvalue))
if !bool(C.go_lxc_set_cgroup_item(c.container, ckey, cvalue)) {
return ErrSettingCgroupItemFailed
}
return nil
}
// ClearConfig completely clears the containers in-memory configuration.
func (c *Container) ClearConfig() {
c.mu.Lock()
defer c.mu.Unlock()
C.go_lxc_clear_config(c.container)
}
// ClearConfigItem clears the value of given config item.
func (c *Container) ClearConfigItem(key string) error {
c.mu.Lock()
defer c.mu.Unlock()
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
if !bool(C.go_lxc_clear_config_item(c.container, ckey)) {
return ErrClearingConfigItemFailed
}
return nil
}
// ConfigKeys returns the names of the config items.
func (c *Container) ConfigKeys(key ...string) []string {
c.mu.RLock()
defer c.mu.RUnlock()
var keys *_Ctype_char
if key != nil && len(key) == 1 {
ckey := C.CString(key[0])
defer C.free(unsafe.Pointer(ckey))
// allocated in lxc.c
keys = C.go_lxc_get_keys(c.container, ckey)
defer C.free(unsafe.Pointer(keys))
} else {
// allocated in lxc.c
keys = C.go_lxc_get_keys(c.container, nil)
defer C.free(unsafe.Pointer(keys))
}
ret := strings.TrimSpace(C.GoString(keys))
return strings.Split(ret, "\n")
}
// LoadConfigFile loads the configuration file from given path.
func (c *Container) LoadConfigFile(path string) error {
c.mu.Lock()
defer c.mu.Unlock()
cpath := C.CString(path)
defer C.free(unsafe.Pointer(cpath))
if !bool(C.go_lxc_load_config(c.container, cpath)) {
return ErrLoadConfigFailed
}
return nil
}
// SaveConfigFile saves the configuration file to given path.
func (c *Container) SaveConfigFile(path string) error {
c.mu.Lock()
defer c.mu.Unlock()
cpath := C.CString(path)
defer C.free(unsafe.Pointer(cpath))
if !bool(C.go_lxc_save_config(c.container, cpath)) {
return ErrSaveConfigFailed
}
return nil
}
// ConfigPath returns the configuration file's path.
func (c *Container) ConfigPath() string {
c.mu.RLock()
defer c.mu.RUnlock()
return C.GoString(C.go_lxc_get_config_path(c.container))
}
// SetConfigPath sets the configuration file's path.
func (c *Container) SetConfigPath(path string) error {
c.mu.Lock()
defer c.mu.Unlock()
cpath := C.CString(path)
defer C.free(unsafe.Pointer(cpath))
if !bool(C.go_lxc_set_config_path(c.container, cpath)) {
return ErrSettingConfigPathFailed
}
return nil
}
// MemoryUsage returns memory usage of the container in bytes.
func (c *Container) MemoryUsage() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
return c.cgroupItemAsByteSize("memory.usage_in_bytes", ErrMemLimit)
}
// MemoryLimit returns memory limit of the container in bytes.
func (c *Container) MemoryLimit() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
return c.cgroupItemAsByteSize("memory.limit_in_bytes", ErrMemLimit)
}
// SetMemoryLimit sets memory limit of the container in bytes.
func (c *Container) SetMemoryLimit(limit ByteSize) error {
if err := c.makeSure(isRunning); err != nil {
return err
}
return c.setCgroupItemWithByteSize("memory.limit_in_bytes", limit, ErrSettingMemoryLimitFailed)
}
// SoftMemoryLimit returns soft memory limit of the container in bytes.
func (c *Container) SoftMemoryLimit() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
return c.cgroupItemAsByteSize("memory.soft_limit_in_bytes", ErrSoftMemLimit)
}
// SetSoftMemoryLimit sets soft memory limit of the container in bytes.
func (c *Container) SetSoftMemoryLimit(limit ByteSize) error {
if err := c.makeSure(isRunning); err != nil {
return err
}
return c.setCgroupItemWithByteSize("memory.soft_limit_in_bytes", limit, ErrSettingSoftMemoryLimitFailed)
}
// KernelMemoryUsage returns current kernel memory allocation of the container in bytes.
func (c *Container) KernelMemoryUsage() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit)
}
// KernelMemoryLimit returns kernel memory limit of the container in bytes.
func (c *Container) KernelMemoryLimit() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit)
}
// SetKernelMemoryLimit sets kernel memory limit of the container in bytes.
func (c *Container) SetKernelMemoryLimit(limit ByteSize) error {
if err := c.makeSure(isRunning); err != nil {
return err
}
return c.setCgroupItemWithByteSize("memory.kmem.limit_in_bytes", limit, ErrSettingKMemoryLimitFailed)
}
// MemorySwapUsage returns memory+swap usage of the container in bytes.
func (c *Container) MemorySwapUsage() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
return c.cgroupItemAsByteSize("memory.memsw.usage_in_bytes", ErrMemorySwapLimit)
}
// MemorySwapLimit returns the memory+swap limit of the container in bytes.
func (c *Container) MemorySwapLimit() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
return c.cgroupItemAsByteSize("memory.memsw.limit_in_bytes", ErrMemorySwapLimit)
}
// SetMemorySwapLimit sets memory+swap limit of the container in bytes.
func (c *Container) SetMemorySwapLimit(limit ByteSize) error {
if err := c.makeSure(isRunning); err != nil {
return err
}
return c.setCgroupItemWithByteSize("memory.memsw.limit_in_bytes", limit, ErrSettingMemorySwapLimitFailed)
}
// BlkioUsage returns number of bytes transferred to/from the disk by the container.
func (c *Container) BlkioUsage() (ByteSize, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
c.mu.RLock()
defer c.mu.RUnlock()
for _, v := range c.CgroupItem("blkio.throttle.io_service_bytes") {
b := strings.Split(v, " ")
if b[0] == "Total" {
blkioUsed, err := strconv.ParseFloat(b[1], 64)
if err != nil {
return -1, err
}
return ByteSize(blkioUsed), nil
}
}
return -1, ErrBlkioUsage
}
// CPUTime returns the total CPU time (in nanoseconds) consumed by all tasks
// in this cgroup (including tasks lower in the hierarchy).
func (c *Container) CPUTime() (time.Duration, error) {
if err := c.makeSure(isRunning); err != nil {
return -1, err
}
c.mu.RLock()
defer c.mu.RUnlock()
cpuUsage, err := strconv.ParseInt(c.CgroupItem("cpuacct.usage")[0], 10, 64)
if err != nil {
return -1, err
}
return time.Duration(cpuUsage), nil
}
// CPUTimePerCPU returns the CPU time (in nanoseconds) consumed on each CPU by
// all tasks in this cgroup (including tasks lower in the hierarchy).
func (c *Container) CPUTimePerCPU() (map[int]time.Duration, error) {
if err := c.makeSure(isRunning); err != nil {
return nil, err
}
c.mu.RLock()
defer c.mu.RUnlock()
cpuTimes := make(map[int]time.Duration)