forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
containers.go
1969 lines (1660 loc) · 45.8 KB
/
containers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"crypto/rand"
"database/sql"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/big"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/dustinkirkland/golang-petname"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/lxc/lxd/lxd/migration"
"github.com/lxc/lxd/shared"
"gopkg.in/lxc/go-lxc.v2"
)
type containerType int
const (
cTypeRegular containerType = 0
cTypeSnapshot containerType = 1
)
func containersGet(d *Daemon, r *http.Request) Response {
for {
result, err := doContainersGet(d)
if err == nil {
return SyncResponse(true, result)
}
if !shared.IsDbLockedError(err) {
shared.Debugf("DBERR: containersGet: error %q\n", err)
return InternalError(err)
}
// 1 s may seem drastic, but we really don't want to thrash
// perhaps we should use a random amount
shared.Debugf("DBERR: containersGet, db is locked\n")
shared.PrintStack()
time.Sleep(1 * time.Second)
}
}
func doContainersGet(d *Daemon) ([]string, error) {
q := fmt.Sprintf("SELECT name FROM containers WHERE type=?")
inargs := []interface{}{cTypeRegular}
var container string
outfmt := []interface{}{container}
result, err := shared.DbQueryScan(d.db, q, inargs, outfmt)
str := []string{}
if err != nil {
return str, err
}
for _, r := range result {
container := string(r[0].(string))
url := fmt.Sprintf("/%s/containers/%s", shared.APIVersion, container)
str = append(str, url)
}
return str, nil
}
type containerImageSource struct {
Type string `json:"type"`
/* for "image" type */
Alias string `json:"alias"`
Fingerprint string `json:"fingerprint"`
Server string `json:"server"`
Secret string `json:"secret"`
/* for "migration" type */
Mode string `json:"mode"`
Operation string `json:"operation"`
Websockets map[string]string `json:"secrets"`
/* for "copy" type */
Source string `json:"source"`
}
type containerPostReq struct {
Name string `json:"name"`
Source containerImageSource `json:"source"`
Config map[string]string `json:"config"`
Profiles []string `json:"profiles"`
Ephemeral bool `json:"ephemeral"`
}
func containerWatchEphemeral(c *lxdContainer) {
go func() {
c.c.Wait(lxc.STOPPED, -1*time.Second)
c.c.Wait(lxc.RUNNING, 1*time.Second)
c.c.Wait(lxc.STOPPED, -1*time.Second)
_, err := dbGetContainerId(c.daemon.db, c.name)
if err != nil {
return
}
dbRemoveContainer(c.daemon, c.name)
containerDeleteSnapshots(c.daemon, c.name)
removeContainerPath(c.daemon, c.name)
}()
}
func containersWatch(d *Daemon) error {
q := fmt.Sprintf("SELECT name FROM containers WHERE type=?")
inargs := []interface{}{cTypeRegular}
var name string
outfmt := []interface{}{name}
result, err := shared.DbQueryScan(d.db, q, inargs, outfmt)
if err != nil {
return err
}
for _, r := range result {
container, err := newLxdContainer(string(r[0].(string)), d)
if err != nil {
return err
}
if container.ephemeral == true && container.c.State() != lxc.STOPPED {
containerWatchEphemeral(container)
}
}
return nil
}
func createFromImage(d *Daemon, req *containerPostReq) Response {
var hash string
var err error
var run func() shared.OperationResult
backing_fs, err := shared.GetFilesystem(d.lxcpath)
if err != nil {
return InternalError(err)
}
if req.Source.Alias != "" {
if req.Source.Mode == "pull" && req.Source.Server != "" {
hash, err = remoteGetImageFingerprint(d, req.Source.Server, req.Source.Alias)
if err != nil {
return InternalError(err)
}
} else {
_, iId, err := dbAliasGet(d, req.Source.Alias)
if err != nil {
return InternalError(err)
}
hash, err = dbImageGetById(d, iId)
if err != nil {
return InternalError(fmt.Errorf("Stale alias"))
}
}
} else if req.Source.Fingerprint != "" {
hash = req.Source.Fingerprint
} else {
return BadRequest(fmt.Errorf("must specify one of alias or fingerprint for init from image"))
}
if req.Source.Server != "" {
err := ensureLocalImage(d, req.Source.Server, hash, req.Source.Secret)
if err != nil {
return InternalError(err)
}
}
imgInfo, err := dbImageGet(d, hash, false)
if err != nil {
return SmartError(err)
}
hash = imgInfo.Fingerprint
dpath := shared.VarPath("lxc", req.Name)
if shared.PathExists(dpath) {
return InternalError(fmt.Errorf("Container exists"))
}
name := req.Name
if backing_fs == "btrfs" && shared.PathExists(fmt.Sprintf("%s.btrfs", shared.VarPath("images", hash))) {
run = shared.OperationWrap(func() error { return btrfsCopyImage(hash, name, d) })
} else {
rootfsPath := fmt.Sprintf("%s/rootfs", dpath)
err = os.MkdirAll(rootfsPath, 0700)
if err != nil {
return InternalError(fmt.Errorf("Error creating rootfs directory"))
}
run = shared.OperationWrap(func() error { return extractShiftRootfs(hash, name, d) })
}
_, err = dbCreateContainer(d, name, cTypeRegular, req.Config, req.Profiles, req.Ephemeral)
if err != nil {
removeContainerPath(d, name)
return SmartError(err)
}
resources := make(map[string][]string)
resources["containers"] = []string{req.Name}
return &asyncResponse{run: run, resources: resources}
}
func createFromNone(d *Daemon, req *containerPostReq) Response {
_, err := dbCreateContainer(d, req.Name, cTypeRegular, req.Config, req.Profiles, req.Ephemeral)
if err != nil {
return SmartError(err)
}
/* The container already exists, so don't do anything. */
run := shared.OperationWrap(func() error { return nil })
resources := make(map[string][]string)
resources["containers"] = []string{req.Name}
return &asyncResponse{run: run, resources: resources}
}
func createFromMigration(d *Daemon, req *containerPostReq) Response {
if req.Source.Mode != "pull" {
return NotImplemented
}
_, err := dbCreateContainer(d, req.Name, cTypeRegular, req.Config, req.Profiles, req.Ephemeral)
if err != nil {
return SmartError(err)
}
c, err := newLxdContainer(req.Name, d)
if err != nil {
removeContainer(d, req.Name)
return SmartError(err)
}
// rsync complaisn if the parent directory for the rootfs sync doesn't
// exist
dpath := shared.VarPath("lxc", req.Name)
if err := os.MkdirAll(dpath, 0700); err != nil {
removeContainer(d, req.Name)
return InternalError(err)
}
config, err := shared.GetTLSConfig(d.certf, d.keyf)
if err != nil {
removeContainer(d, req.Name)
return InternalError(err)
}
args := migration.MigrationSinkArgs{
Url: req.Source.Operation,
Dialer: websocket.Dialer{TLSClientConfig: config},
Container: c.c,
Secrets: req.Source.Websockets,
IdMap: d.idMap,
}
sink, err := migration.NewMigrationSink(&args)
if err != nil {
removeContainer(d, req.Name)
return BadRequest(err)
}
run := func() shared.OperationResult {
err := sink()
if err != nil {
removeContainer(d, req.Name)
}
return shared.OperationError(err)
}
resources := make(map[string][]string)
resources["containers"] = []string{req.Name}
return &asyncResponse{run: run, resources: resources}
}
func createFromCopy(d *Daemon, req *containerPostReq) Response {
if req.Source.Source == "" {
return BadRequest(fmt.Errorf("must specify a source container"))
}
// Make sure the source exists.
source, err := newLxdContainer(req.Source.Source, d)
if err != nil {
return SmartError(err)
}
if req.Config == nil {
req.Config = source.config
}
if req.Profiles == nil {
req.Profiles = source.profiles
}
_, err = dbCreateContainer(d, req.Name, cTypeRegular, req.Config, req.Profiles, req.Ephemeral)
if err != nil {
return SmartError(err)
}
dpath := shared.VarPath("lxc", req.Name)
if err := os.MkdirAll(dpath, 0700); err != nil {
removeContainer(d, req.Name)
return InternalError(err)
}
var oldPath string
if shared.IsSnapshot(req.Source.Source) {
snappieces := strings.SplitN(req.Source.Source, "/", 2)
oldPath = migration.AddSlash(shared.VarPath("lxc",
snappieces[0],
"snapshots",
snappieces[1],
"rootfs"))
} else {
oldPath = migration.AddSlash(shared.VarPath("lxc", req.Source.Source, "rootfs"))
}
newPath := fmt.Sprintf("%s/%s", dpath, "rootfs")
run := func() shared.OperationResult {
err := exec.Command("rsync", "-a", "--devices", oldPath, newPath).Run()
if err == nil && !source.isPrivileged() {
err = setUnprivUserAcl(d, dpath)
}
return shared.OperationError(err)
}
resources := make(map[string][]string)
resources["containers"] = []string{req.Name, req.Source.Source}
return &asyncResponse{run: run, resources: resources}
}
func containersPost(d *Daemon, r *http.Request) Response {
shared.Debugf("responding to create")
if d.idMap == nil {
return BadRequest(fmt.Errorf("shared's user has no subuids"))
}
req := containerPostReq{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return BadRequest(err)
}
if req.Name == "" {
req.Name = strings.ToLower(petname.Generate(2, "-"))
shared.Debugf("no name provided, creating %s", req.Name)
}
switch req.Source.Type {
case "image":
return createFromImage(d, &req)
case "none":
return createFromNone(d, &req)
case "migration":
return createFromMigration(d, &req)
case "copy":
return createFromCopy(d, &req)
default:
return BadRequest(fmt.Errorf("unknown source type %s", req.Source.Type))
}
}
func removeContainerPath(d *Daemon, name string) {
cpath := shared.VarPath("lxc", name)
backing_fs, err := shared.GetFilesystem(cpath)
if err != nil {
shared.Debugf("Error cleaning up %s: %s\n", cpath, err)
return
}
if backing_fs == "btrfs" {
exec.Command("btrfs", "subvolume", "delete", cpath).Run()
}
err = os.RemoveAll(cpath)
if err != nil {
shared.Debugf("Error cleaning up %s: %s\n", cpath, err)
}
}
func removeContainer(d *Daemon, name string) {
removeContainerPath(d, name)
dbRemoveContainer(d, name)
}
func btrfsCopyImage(hash string, name string, d *Daemon) error {
dpath := shared.VarPath("lxc", name)
imagefile := shared.VarPath("images", hash)
subvol := fmt.Sprintf("%s.btrfs", imagefile)
err := exec.Command("btrfs", "subvolume", "snapshot", subvol, dpath).Run()
if err != nil {
return err
}
rpath := shared.VarPath("lxc", name, "rootfs")
err = d.idMap.ShiftRootfs(rpath)
if err != nil {
shared.Debugf("Shift of rootfs %s failed: %s\n", rpath, err)
removeContainer(d, name)
return err
}
/* Set an acl so the container root can descend the container dir */
acl := fmt.Sprintf("%d:rx", d.idMap.Uidmin)
_, err = exec.Command("setfacl", "-m", acl, dpath).Output()
if err != nil {
shared.Debugf("Error adding acl for container root: start will likely fail\n")
}
return nil
}
func extractShiftRootfs(hash string, name string, d *Daemon) error {
/*
* We want to use archive/tar for this, but that doesn't appear
* to be working for us (see lxd/images.go)
* So for now, we extract the rootfs.tar.xz from the image
* tarball to /var/lib/lxd/lxc/container/rootfs.tar.xz, then
* extract that under /var/lib/lxd/lxc/container/rootfs/
*/
dpath := shared.VarPath("lxc", name)
imagefile := shared.VarPath("images", hash)
compression, _, err := detectCompression(imagefile)
if err != nil {
shared.Logf("Unkown compression type: %s", err)
removeContainer(d, name)
return err
}
args := []string{"-C", dpath, "--numeric-owner"}
switch compression {
case COMPRESSION_TAR:
args = append(args, "-xf")
case COMPRESSION_GZIP:
args = append(args, "-zxf")
case COMPRESSION_BZ2:
args = append(args, "--jxf")
case COMPRESSION_LZMA:
args = append(args, "--lzma", "-xf")
default:
args = append(args, "-Jxf")
}
args = append(args, imagefile, "rootfs")
output, err := exec.Command("tar", args...).Output()
if err != nil {
shared.Debugf("Untar of image: Output %s\nError %s\n", output, err)
removeContainer(d, name)
return err
}
rpath := shared.VarPath("lxc", name, "rootfs")
err = d.idMap.ShiftRootfs(rpath)
if err != nil {
shared.Debugf("Shift of rootfs %s failed: %s\n", rpath, err)
removeContainer(d, name)
return err
}
/* Set an acl so the container root can descend the container dir */
err = setUnprivUserAcl(d, dpath)
if err != nil {
shared.Debugf("Error adding acl for container root: start will likely fail\n")
}
return nil
}
func setUnprivUserAcl(d *Daemon, dpath string) error {
acl := fmt.Sprintf("%d:rx", d.idMap.Uidmin)
_, err := exec.Command("setfacl", "-m", acl, dpath).Output()
return err
}
func dbRemoveContainer(d *Daemon, name string) {
_, _ = shared.DbExec(d.db, "DELETE FROM containers WHERE name=?", name)
}
func dbGetContainerId(db *sql.DB, name string) (int, error) {
q := "SELECT id FROM containers WHERE name=?"
id := -1
arg1 := []interface{}{name}
arg2 := []interface{}{&id}
err := shared.DbQueryRowScan(db, q, arg1, arg2)
return id, err
}
func dbCreateContainer(d *Daemon, name string, ctype containerType, config map[string]string, profiles []string, ephem bool) (int, error) {
id, err := dbGetContainerId(d.db, name)
if err == nil {
return 0, DbErrAlreadyDefined
}
if profiles == nil {
profiles = []string{"default"}
}
tx, err := shared.DbBegin(d.db)
if err != nil {
return 0, err
}
ephem_int := 0
if ephem == true {
ephem_int = 1
}
str := fmt.Sprintf("INSERT INTO containers (name, architecture, type, ephemeral) VALUES (?, 1, %d, %d)",
ctype, ephem_int)
stmt, err := tx.Prepare(str)
if err != nil {
tx.Rollback()
return 0, err
}
defer stmt.Close()
result, err := stmt.Exec(name)
if err != nil {
tx.Rollback()
return 0, err
}
id64, err := result.LastInsertId()
if err != nil {
tx.Rollback()
return 0, fmt.Errorf("Error inserting %s into database", name)
}
// TODO: is this really int64? we should fix it everywhere if so
id = int(id64)
if err := dbInsertContainerConfig(tx, id, config); err != nil {
tx.Rollback()
return 0, err
}
if err := dbInsertProfiles(tx, id, profiles); err != nil {
tx.Rollback()
return 0, err
}
return id, shared.TxCommit(tx)
}
var containersCmd = Command{name: "containers", get: containersGet, post: containersPost}
func containerGet(d *Daemon, r *http.Request) Response {
name := mux.Vars(r)["name"]
//cId, err := dbGetContainerId(d.db, name) will need cId to get info
_, err := dbGetContainerId(d.db, name)
if err != nil {
return NotFound
}
c, err := newLxdContainer(name, d)
if err != nil {
return SmartError(err)
}
return SyncResponse(true, c.RenderState())
}
func containerDeleteSnapshots(d *Daemon, cname string) {
prefix := fmt.Sprintf("%s/", cname)
length := len(prefix)
q := "SELECT name, id FROM containers WHERE type=? AND SUBSTR(name,1,?)=?"
var id int
var sname string
inargs := []interface{}{cTypeSnapshot, length, prefix}
outfmt := []interface{}{sname, id}
results, err := shared.DbQueryScan(d.db, q, inargs, outfmt)
if err != nil {
return
}
var ids []int
backing_fs, err := shared.GetFilesystem(shared.VarPath("lxc", cname))
if err != nil {
shared.Debugf("Error cleaning up snapshots: %s\n", err)
return
}
for _, r := range results {
sname = r[0].(string)
id = r[1].(int)
ids = append(ids, id)
cdir := shared.VarPath("lxc", cname, "snapshots", sname)
if backing_fs == "btrfs" {
exec.Command("btrfs", "subvolume", "delete", cdir).Run()
}
os.RemoveAll(cdir)
}
for _, id := range ids {
_, _ = shared.DbExec(d.db, "DELETE FROM containers WHERE id=?", id)
}
return
}
type containerConfigReq struct {
Profiles []string `json:"profiles"`
Config map[string]string `json:"config"`
Devices shared.Devices `json:"devices"`
Restore string `json:"restore"`
}
func containerSnapRestore(id int, snap string) Response {
return NotImplemented
}
func dbClearContainerConfig(tx *sql.Tx, id int) error {
_, err := tx.Exec("DELETE FROM containers_config WHERE container_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM containers_profiles WHERE container_id=?", id)
if err != nil {
return err
}
_, err = tx.Exec(`DELETE FROM containers_devices_config WHERE id IN
(SELECT containers_devices_config.id
FROM containers_devices_config JOIN containers_devices
ON containers_devices_config.container_device_id=containers_devices.id
WHERE containers_devices.container_id=?)`, id)
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM containers_devices WHERE container_id=?", id)
return err
}
func dbInsertContainerConfig(tx *sql.Tx, id int, config map[string]string) error {
str := "INSERT INTO containers_config (container_id, key, value) values (?, ?, ?)"
stmt, err := tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
for k, v := range config {
if !ValidContainerConfigKey(k) {
return fmt.Errorf("Bad key: %s\n", k)
}
_, err = stmt.Exec(id, k, v)
if err != nil {
shared.Debugf("Error adding configuration item %s = %s to container %d\n",
k, v, id)
return err
}
}
return nil
}
func dbInsertProfiles(tx *sql.Tx, id int, profiles []string) error {
apply_order := 1
str := `INSERT INTO containers_profiles (container_id, profile_id, apply_order) VALUES
(?, (SELECT id FROM profiles WHERE name=?), ?);`
stmt, err := tx.Prepare(str)
if err != nil {
return err
}
defer stmt.Close()
for _, p := range profiles {
_, err = stmt.Exec(id, p, apply_order)
if err != nil {
shared.Debugf("Error adding profile %s to container: %s\n",
p, err)
return err
}
apply_order = apply_order + 1
}
return nil
}
// ExtractInterfaceFromConfigName returns "eth0" from "volatile.eth0.hwaddr",
// or an error if the key does not match this pattern.
func ExtractInterfaceFromConfigName(k string) (string, error) {
re := regexp.MustCompile("volatile\\.([^.]*)\\.hwaddr")
m := re.FindStringSubmatch(k)
if m != nil && len(m) > 1 {
return m[1], nil
}
return "", fmt.Errorf("%s did not match", k)
}
func ValidContainerConfigKey(k string) bool {
switch k {
case "limits.cpus":
return true
case "limits.memory":
return true
case "security.privileged":
return true
case "raw.apparmor":
return true
case "raw.lxc":
return true
}
if _, err := ExtractInterfaceFromConfigName(k); err == nil {
return true
}
return strings.HasPrefix(k, "user.")
}
func emptyProfile(l []string) bool {
if len(l) == 0 {
return true
}
if len(l) == 1 && l[0] == "" {
return true
}
return false
}
/*
* Update configuration, or, if 'restore:snapshot-name' is present, restore
* the named snapshot
*/
func containerPut(d *Daemon, r *http.Request) Response {
name := mux.Vars(r)["name"]
shared.Debugf("containerPut: called with name %s\n", name)
cId, err := dbGetContainerId(d.db, name)
if err != nil {
return NotFound
}
configRaw := containerConfigReq{}
if err := json.NewDecoder(r.Body).Decode(&configRaw); err != nil {
return BadRequest(err)
}
do := func() error {
tx, err := shared.DbBegin(d.db)
if err != nil {
return err
}
/* Update config or profiles */
if err = dbClearContainerConfig(tx, cId); err != nil {
shared.Debugf("Error clearing configuration for container %s\n", name)
tx.Rollback()
return err
}
if err = dbInsertContainerConfig(tx, cId, configRaw.Config); err != nil {
shared.Debugf("Error inserting configuration for container %s\n", name)
tx.Rollback()
return err
}
/* handle profiles */
if emptyProfile(configRaw.Profiles) {
_, err := tx.Exec("DELETE from containers_profiles where container_id=?", cId)
if err != nil {
tx.Rollback()
return err
}
} else {
if err := dbInsertProfiles(tx, cId, configRaw.Profiles); err != nil {
tx.Rollback()
return err
}
}
err = shared.AddDevices(tx, "container", cId, configRaw.Devices)
if err != nil {
tx.Rollback()
return err
}
return shared.TxCommit(tx)
}
return AsyncResponse(shared.OperationWrap(do), nil)
}
type containerPostBody struct {
Migration bool `json:"migration"`
Name string `json:"name"`
}
func containerPost(d *Daemon, r *http.Request) Response {
name := mux.Vars(r)["name"]
c, err := newLxdContainer(name, d)
if err != nil {
return SmartError(err)
}
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
return InternalError(err)
}
body := containerPostBody{}
if err := json.Unmarshal(buf, &body); err != nil {
return BadRequest(err)
}
if body.Migration {
ws, err := migration.NewMigrationSource(c.c)
if err != nil {
return InternalError(err)
}
return AsyncResponseWithWs(ws, nil)
} else {
if c.c.Running() {
return BadRequest(fmt.Errorf("renaming of running container not allowed"))
}
_, err := dbCreateContainer(d, body.Name, cTypeRegular, c.config, c.profiles, c.ephemeral)
if err != nil {
return SmartError(err)
}
run := func() error {
oldPath := fmt.Sprintf("%s/", shared.VarPath("lxc", c.name))
newPath := fmt.Sprintf("%s/", shared.VarPath("lxc", body.Name))
if err := os.Rename(oldPath, newPath); err != nil {
return err
}
removeContainer(d, c.name)
return nil
}
return AsyncResponse(shared.OperationWrap(run), nil)
}
}
func containerDelete(d *Daemon, r *http.Request) Response {
name := mux.Vars(r)["name"]
_, err := dbGetContainerId(d.db, name)
if err != nil {
return SmartError(err)
}
dbRemoveContainer(d, name)
rmdir := func() error {
containerDeleteSnapshots(d, name)
removeContainerPath(d, name)
return nil
}
return AsyncResponse(shared.OperationWrap(rmdir), nil)
}
var containerCmd = Command{name: "containers/{name}", get: containerGet, put: containerPut, delete: containerDelete, post: containerPost}
func containerStateGet(d *Daemon, r *http.Request) Response {
name := mux.Vars(r)["name"]
c, err := newLxdContainer(name, d)
if err != nil {
return SmartError(err)
}
return SyncResponse(true, c.RenderState().Status)
}
type containerStatePutReq struct {
Action string `json:"action"`
Timeout int `json:"timeout"`
Force bool `json:"force"`
}
type lxdContainer struct {
c *lxc.Container
daemon *Daemon
id int
name string
config map[string]string
profiles []string
devices shared.Devices
ephemeral bool
}
func (c *lxdContainer) RenderState() *shared.ContainerState {
return &shared.ContainerState{
Name: c.name,
Profiles: c.profiles,
Config: c.config,
Userdata: []byte{},
Status: shared.NewStatus(c.c, c.c.State()),
Devices: c.devices,
Ephemeral: c.ephemeral,
}
}
func (c *lxdContainer) Start() error {
err := c.c.Start()
if err == nil && c.ephemeral == true {
containerWatchEphemeral(c)
}
return err
}
func (c *lxdContainer) Reboot() error {
return c.c.Reboot()
}
func (c *lxdContainer) Freeze() error {
return c.c.Freeze()
}
func (c *lxdContainer) isPrivileged() bool {
switch strings.ToLower(c.config["security.privileged"]) {
case "1":
return true
case "true":
return true
}
return false
}
func (c *lxdContainer) Shutdown(timeout time.Duration) error {
return c.c.Shutdown(timeout)
}
func (c *lxdContainer) Stop() error {
return c.c.Stop()
}
func (c *lxdContainer) Unfreeze() error {
return c.c.Unfreeze()
}
func (d *lxdContainer) applyConfig(config map[string]string) error {
var err error
for k, v := range config {
switch k {
case "limits.cpus":
// TODO - Come up with a way to choose cpus for multiple
// containers
var vint int
count, err := fmt.Sscanf(v, "%d", &vint)
if err != nil {
return err
}
if count != 1 || vint < 0 || vint > 65000 {
return fmt.Errorf("Bad cpu limit: %s\n", v)
}
cpuset := fmt.Sprintf("0-%d", vint-1)
err = d.c.SetConfigItem("lxc.cgroup.cpuset.cpus", cpuset)
case "limits.memory":
err = d.c.SetConfigItem("lxc.cgroup.memory.limit_in_bytes", v)
default:
if strings.HasPrefix(k, "user.") {
// ignore for now
err = nil
}
/* Things like security.privileged need to be propagatged */
d.config[k] = v
}
if err != nil {
shared.Debugf("error setting %s: %q\n", k, err)
return err
}
}
if lxcConfig, ok := config["raw.lxc"]; ok {
f, err := ioutil.TempFile("", "lxd_config_")
if err != nil {
return err
}
err = shared.WriteAll(f, []byte(lxcConfig))
f.Close()
defer os.Remove(f.Name())
if err != nil {
return err
}