forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lxd_containers.go
1826 lines (1479 loc) · 48.6 KB
/
lxd_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 lxd
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/gorilla/websocket"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/cancel"
"github.com/lxc/lxd/shared/ioprogress"
"github.com/lxc/lxd/shared/units"
)
// Container handling functions
// GetContainerNames returns a list of container names
func (r *ProtocolLXD) GetContainerNames() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/containers", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
names := []string{}
for _, url := range urls {
fields := strings.Split(url, "/containers/")
names = append(names, fields[len(fields)-1])
}
return names, nil
}
// GetContainers returns a list of containers
func (r *ProtocolLXD) GetContainers() ([]api.Container, error) {
containers := []api.Container{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/containers?recursion=1", nil, "", &containers)
if err != nil {
return nil, err
}
return containers, nil
}
// GetContainersFull returns a list of containers including snapshots, backups and state
func (r *ProtocolLXD) GetContainersFull() ([]api.ContainerFull, error) {
containers := []api.ContainerFull{}
if !r.HasExtension("container_full") {
return nil, fmt.Errorf("The server is missing the required \"container_full\" API extension")
}
// Fetch the raw value
_, err := r.queryStruct("GET", "/containers?recursion=2", nil, "", &containers)
if err != nil {
return nil, err
}
return containers, nil
}
// GetContainer returns the container entry for the provided name
func (r *ProtocolLXD) GetContainer(name string) (*api.Container, string, error) {
container := api.Container{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s", url.PathEscape(name)), nil, "", &container)
if err != nil {
return nil, "", err
}
return &container, etag, nil
}
// CreateContainerFromBackup is a convenience function to make it easier to
// create a container from a backup
func (r *ProtocolLXD) CreateContainerFromBackup(args ContainerBackupArgs) (Operation, error) {
if !r.HasExtension("container_backup") {
return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension")
}
if args.PoolName == "" {
// Send the request
op, _, err := r.queryOperation("POST", "/containers", args.BackupFile, "")
if err != nil {
return nil, err
}
return op, nil
}
if !r.HasExtension("container_backup_override_pool") {
return nil, fmt.Errorf("The server is missing the required \"container_backup_override_pool\" API extension")
}
// Prepare the HTTP request
reqURL, err := r.setQueryAttributes(fmt.Sprintf("%s/1.0/containers", r.httpHost))
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", reqURL, args.BackupFile)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set("X-LXD-pool", args.PoolName)
// Set the user agent
if r.httpUserAgent != "" {
req.Header.Set("User-Agent", r.httpUserAgent)
}
// Send the request
resp, err := r.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Handle errors
response, _, err := lxdParseResponse(resp)
if err != nil {
return nil, err
}
// Get to the operation
respOperation, err := response.MetadataAsOperation()
if err != nil {
return nil, err
}
// Setup an Operation wrapper
op := operation{
Operation: *respOperation,
r: r,
chActive: make(chan bool),
}
return &op, nil
}
// CreateContainer requests that LXD creates a new container
func (r *ProtocolLXD) CreateContainer(container api.ContainersPost) (Operation, error) {
if container.Source.ContainerOnly {
if !r.HasExtension("container_only_migration") {
return nil, fmt.Errorf("The server is missing the required \"container_only_migration\" API extension")
}
}
// Send the request
op, _, err := r.queryOperation("POST", "/containers", container, "")
if err != nil {
return nil, err
}
return op, nil
}
func (r *ProtocolLXD) tryCreateContainer(req api.ContainersPost, urls []string) (RemoteOperation, error) {
if len(urls) == 0 {
return nil, fmt.Errorf("The source server isn't listening on the network")
}
rop := remoteOperation{
chDone: make(chan bool),
}
operation := req.Source.Operation
// Forward targetOp to remote op
go func() {
success := false
errors := map[string]error{}
for _, serverURL := range urls {
if operation == "" {
req.Source.Server = serverURL
} else {
req.Source.Operation = fmt.Sprintf("%s/1.0/operations/%s", serverURL, url.PathEscape(operation))
}
op, err := r.CreateContainer(req)
if err != nil {
errors[serverURL] = err
continue
}
rop.targetOp = op
for _, handler := range rop.handlers {
rop.targetOp.AddHandler(handler)
}
err = rop.targetOp.Wait()
if err != nil {
errors[serverURL] = err
continue
}
success = true
break
}
if !success {
rop.err = remoteOperationError("Failed container creation", errors)
}
close(rop.chDone)
}()
return &rop, nil
}
// CreateContainerFromImage is a convenience function to make it easier to create a container from an existing image
func (r *ProtocolLXD) CreateContainerFromImage(source ImageServer, image api.Image, req api.ContainersPost) (RemoteOperation, error) {
// Set the minimal source fields
req.Source.Type = "image"
// Optimization for the local image case
if r == source {
// Always use fingerprints for local case
req.Source.Fingerprint = image.Fingerprint
req.Source.Alias = ""
op, err := r.CreateContainer(req)
if err != nil {
return nil, err
}
rop := remoteOperation{
targetOp: op,
chDone: make(chan bool),
}
// Forward targetOp to remote op
go func() {
rop.err = rop.targetOp.Wait()
close(rop.chDone)
}()
return &rop, nil
}
// Minimal source fields for remote image
req.Source.Mode = "pull"
// If we have an alias and the image is public, use that
if req.Source.Alias != "" && image.Public {
req.Source.Fingerprint = ""
} else {
req.Source.Fingerprint = image.Fingerprint
req.Source.Alias = ""
}
// Get source server connection information
info, err := source.GetConnectionInfo()
if err != nil {
return nil, err
}
req.Source.Protocol = info.Protocol
req.Source.Certificate = info.Certificate
// Generate secret token if needed
if !image.Public {
secret, err := source.GetImageSecret(image.Fingerprint)
if err != nil {
return nil, err
}
req.Source.Secret = secret
}
return r.tryCreateContainer(req, info.Addresses)
}
// CopyContainer copies a container from a remote server. Additional options can be passed using ContainerCopyArgs
func (r *ProtocolLXD) CopyContainer(source InstanceServer, container api.Container, args *ContainerCopyArgs) (RemoteOperation, error) {
// Base request
req := api.ContainersPost{
Name: container.Name,
ContainerPut: container.Writable(),
}
req.Source.BaseImage = container.Config["volatile.base_image"]
// Process the copy arguments
if args != nil {
// Sanity checks
if args.ContainerOnly {
if !r.HasExtension("container_only_migration") {
return nil, fmt.Errorf("The target server is missing the required \"container_only_migration\" API extension")
}
if !source.HasExtension("container_only_migration") {
return nil, fmt.Errorf("The source server is missing the required \"container_only_migration\" API extension")
}
}
if shared.StringInSlice(args.Mode, []string{"push", "relay"}) {
if !r.HasExtension("container_push") {
return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension")
}
if !source.HasExtension("container_push") {
return nil, fmt.Errorf("The source server is missing the required \"container_push\" API extension")
}
}
if args.Mode == "push" && !source.HasExtension("container_push_target") {
return nil, fmt.Errorf("The source server is missing the required \"container_push_target\" API extension")
}
if args.Refresh {
if !r.HasExtension("container_incremental_copy") {
return nil, fmt.Errorf("The target server is missing the required \"container_incremental_copy\" API extension")
}
if !source.HasExtension("container_incremental_copy") {
return nil, fmt.Errorf("The source server is missing the required \"container_incremental_copy\" API extension")
}
}
// Allow overriding the target name
if args.Name != "" {
req.Name = args.Name
}
req.Source.Live = args.Live
req.Source.ContainerOnly = args.ContainerOnly
req.Source.Refresh = args.Refresh
}
if req.Source.Live {
req.Source.Live = container.StatusCode == api.Running
}
sourceInfo, err := source.GetConnectionInfo()
if err != nil {
return nil, fmt.Errorf("Failed to get source connection info: %v", err)
}
destInfo, err := r.GetConnectionInfo()
if err != nil {
return nil, fmt.Errorf("Failed to get destination connection info: %v", err)
}
// Optimization for the local copy case
if destInfo.URL == sourceInfo.URL && destInfo.SocketPath == sourceInfo.SocketPath && (!r.IsClustered() || container.Location == r.clusterTarget || r.HasExtension("cluster_internal_copy")) {
// Project handling
if destInfo.Project != sourceInfo.Project {
if !r.HasExtension("container_copy_project") {
return nil, fmt.Errorf("The server is missing the required \"container_copy_project\" API extension")
}
req.Source.Project = sourceInfo.Project
}
// Local copy source fields
req.Source.Type = "copy"
req.Source.Source = container.Name
// Copy the container
op, err := r.CreateContainer(req)
if err != nil {
return nil, err
}
rop := remoteOperation{
targetOp: op,
chDone: make(chan bool),
}
// Forward targetOp to remote op
go func() {
rop.err = rop.targetOp.Wait()
close(rop.chDone)
}()
return &rop, nil
}
// Source request
sourceReq := api.ContainerPost{
Migration: true,
Live: req.Source.Live,
ContainerOnly: req.Source.ContainerOnly,
}
// Push mode migration
if args != nil && args.Mode == "push" {
// Get target server connection information
info, err := r.GetConnectionInfo()
if err != nil {
return nil, err
}
// Create the container
req.Source.Type = "migration"
req.Source.Mode = "push"
req.Source.Refresh = args.Refresh
op, err := r.CreateContainer(req)
if err != nil {
return nil, err
}
opAPI := op.Get()
targetSecrets := map[string]string{}
for k, v := range opAPI.Metadata {
targetSecrets[k] = v.(string)
}
// Prepare the source request
target := api.ContainerPostTarget{}
target.Operation = opAPI.ID
target.Websockets = targetSecrets
target.Certificate = info.Certificate
sourceReq.Target = &target
return r.tryMigrateContainer(source, container.Name, sourceReq, info.Addresses)
}
// Get source server connection information
info, err := source.GetConnectionInfo()
if err != nil {
return nil, err
}
op, err := source.MigrateContainer(container.Name, sourceReq)
if err != nil {
return nil, err
}
opAPI := op.Get()
sourceSecrets := map[string]string{}
for k, v := range opAPI.Metadata {
sourceSecrets[k] = v.(string)
}
// Relay mode migration
if args != nil && args.Mode == "relay" {
// Push copy source fields
req.Source.Type = "migration"
req.Source.Mode = "push"
// Start the process
targetOp, err := r.CreateContainer(req)
if err != nil {
return nil, err
}
targetOpAPI := targetOp.Get()
// Extract the websockets
targetSecrets := map[string]string{}
for k, v := range targetOpAPI.Metadata {
targetSecrets[k] = v.(string)
}
// Launch the relay
err = r.proxyMigration(targetOp.(*operation), targetSecrets, source, op.(*operation), sourceSecrets)
if err != nil {
return nil, err
}
// Prepare a tracking operation
rop := remoteOperation{
targetOp: targetOp,
chDone: make(chan bool),
}
// Forward targetOp to remote op
go func() {
rop.err = rop.targetOp.Wait()
close(rop.chDone)
}()
return &rop, nil
}
// Pull mode migration
req.Source.Type = "migration"
req.Source.Mode = "pull"
req.Source.Operation = opAPI.ID
req.Source.Websockets = sourceSecrets
req.Source.Certificate = info.Certificate
return r.tryCreateContainer(req, info.Addresses)
}
// UpdateContainer updates the container definition
func (r *ProtocolLXD) UpdateContainer(name string, container api.ContainerPut, ETag string) (Operation, error) {
// Send the request
op, _, err := r.queryOperation("PUT", fmt.Sprintf("/containers/%s", url.PathEscape(name)), container, ETag)
if err != nil {
return nil, err
}
return op, nil
}
// RenameContainer requests that LXD renames the container
func (r *ProtocolLXD) RenameContainer(name string, container api.ContainerPost) (Operation, error) {
// Sanity check
if container.Migration {
return nil, fmt.Errorf("Can't ask for a migration through RenameContainer")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s", url.PathEscape(name)), container, "")
if err != nil {
return nil, err
}
return op, nil
}
func (r *ProtocolLXD) tryMigrateContainer(source InstanceServer, name string, req api.ContainerPost, urls []string) (RemoteOperation, error) {
if len(urls) == 0 {
return nil, fmt.Errorf("The target server isn't listening on the network")
}
rop := remoteOperation{
chDone: make(chan bool),
}
operation := req.Target.Operation
// Forward targetOp to remote op
go func() {
success := false
errors := map[string]error{}
for _, serverURL := range urls {
req.Target.Operation = fmt.Sprintf("%s/1.0/operations/%s", serverURL, url.PathEscape(operation))
op, err := source.MigrateContainer(name, req)
if err != nil {
errors[serverURL] = err
continue
}
rop.targetOp = op
for _, handler := range rop.handlers {
rop.targetOp.AddHandler(handler)
}
err = rop.targetOp.Wait()
if err != nil {
errors[serverURL] = err
continue
}
success = true
break
}
if !success {
rop.err = remoteOperationError("Failed container migration", errors)
}
close(rop.chDone)
}()
return &rop, nil
}
// MigrateContainer requests that LXD prepares for a container migration
func (r *ProtocolLXD) MigrateContainer(name string, container api.ContainerPost) (Operation, error) {
if container.ContainerOnly {
if !r.HasExtension("container_only_migration") {
return nil, fmt.Errorf("The server is missing the required \"container_only_migration\" API extension")
}
}
// Sanity check
if !container.Migration {
return nil, fmt.Errorf("Can't ask for a rename through MigrateContainer")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s", url.PathEscape(name)), container, "")
if err != nil {
return nil, err
}
return op, nil
}
// DeleteContainer requests that LXD deletes the container
func (r *ProtocolLXD) DeleteContainer(name string) (Operation, error) {
// Send the request
op, _, err := r.queryOperation("DELETE", fmt.Sprintf("/containers/%s", url.PathEscape(name)), nil, "")
if err != nil {
return nil, err
}
return op, nil
}
// ExecContainer requests that LXD spawns a command inside the container
func (r *ProtocolLXD) ExecContainer(containerName string, exec api.ContainerExecPost, args *ContainerExecArgs) (Operation, error) {
if exec.RecordOutput {
if !r.HasExtension("container_exec_recording") {
return nil, fmt.Errorf("The server is missing the required \"container_exec_recording\" API extension")
}
}
if exec.User > 0 || exec.Group > 0 || exec.Cwd != "" {
if !r.HasExtension("container_exec_user_group_cwd") {
return nil, fmt.Errorf("The server is missing the required \"container_exec_user_group_cwd\" API extension")
}
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/exec", url.PathEscape(containerName)), exec, "")
if err != nil {
return nil, err
}
opAPI := op.Get()
// Process additional arguments
if args != nil {
// Parse the fds
fds := map[string]string{}
value, ok := opAPI.Metadata["fds"]
if ok {
values := value.(map[string]interface{})
for k, v := range values {
fds[k] = v.(string)
}
}
// Call the control handler with a connection to the control socket
if args.Control != nil && fds["control"] != "" {
conn, err := r.GetOperationWebsocket(opAPI.ID, fds["control"])
if err != nil {
return nil, err
}
go args.Control(conn)
}
if exec.Interactive {
// Handle interactive sections
if args.Stdin != nil && args.Stdout != nil {
// Connect to the websocket
conn, err := r.GetOperationWebsocket(opAPI.ID, fds["0"])
if err != nil {
return nil, err
}
// And attach stdin and stdout to it
go func() {
shared.WebsocketSendStream(conn, args.Stdin, -1)
<-shared.WebsocketRecvStream(args.Stdout, conn)
conn.Close()
if args.DataDone != nil {
close(args.DataDone)
}
}()
} else {
if args.DataDone != nil {
close(args.DataDone)
}
}
} else {
// Handle non-interactive sessions
dones := map[int]chan bool{}
conns := []*websocket.Conn{}
// Handle stdin
if fds["0"] != "" {
conn, err := r.GetOperationWebsocket(opAPI.ID, fds["0"])
if err != nil {
return nil, err
}
conns = append(conns, conn)
dones[0] = shared.WebsocketSendStream(conn, args.Stdin, -1)
}
// Handle stdout
if fds["1"] != "" {
conn, err := r.GetOperationWebsocket(opAPI.ID, fds["1"])
if err != nil {
return nil, err
}
conns = append(conns, conn)
dones[1] = shared.WebsocketRecvStream(args.Stdout, conn)
}
// Handle stderr
if fds["2"] != "" {
conn, err := r.GetOperationWebsocket(opAPI.ID, fds["2"])
if err != nil {
return nil, err
}
conns = append(conns, conn)
dones[2] = shared.WebsocketRecvStream(args.Stderr, conn)
}
// Wait for everything to be done
go func() {
for i, chDone := range dones {
// Skip stdin, dealing with it separately below
if i == 0 {
continue
}
<-chDone
}
if fds["0"] != "" {
if args.Stdin != nil {
args.Stdin.Close()
}
// Empty the stdin channel but don't block on it as
// stdin may be stuck in Read()
go func() {
<-dones[0]
}()
}
for _, conn := range conns {
conn.Close()
}
if args.DataDone != nil {
close(args.DataDone)
}
}()
}
}
return op, nil
}
// GetContainerFile retrieves the provided path from the container
func (r *ProtocolLXD) GetContainerFile(containerName string, path string) (io.ReadCloser, *ContainerFileResponse, error) {
// Prepare the HTTP request
requestURL, err := shared.URLEncode(
fmt.Sprintf("%s/1.0/containers/%s/files", r.httpHost, url.PathEscape(containerName)),
map[string]string{"path": path})
if err != nil {
return nil, nil, err
}
requestURL, err = r.setQueryAttributes(requestURL)
if err != nil {
return nil, nil, err
}
req, err := http.NewRequest("GET", requestURL, nil)
if err != nil {
return nil, nil, err
}
// Set the user agent
if r.httpUserAgent != "" {
req.Header.Set("User-Agent", r.httpUserAgent)
}
// Send the request
resp, err := r.do(req)
if err != nil {
return nil, nil, err
}
// Check the return value for a cleaner error
if resp.StatusCode != http.StatusOK {
_, _, err := lxdParseResponse(resp)
if err != nil {
return nil, nil, err
}
}
// Parse the headers
uid, gid, mode, fileType, _ := shared.ParseLXDFileHeaders(resp.Header)
fileResp := ContainerFileResponse{
UID: uid,
GID: gid,
Mode: mode,
Type: fileType,
}
if fileResp.Type == "directory" {
// Decode the response
response := api.Response{}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&response)
if err != nil {
return nil, nil, err
}
// Get the file list
entries := []string{}
err = response.MetadataAsStruct(&entries)
if err != nil {
return nil, nil, err
}
fileResp.Entries = entries
return nil, &fileResp, err
}
return resp.Body, &fileResp, err
}
// CreateContainerFile tells LXD to create a file in the container
func (r *ProtocolLXD) CreateContainerFile(containerName string, path string, args ContainerFileArgs) error {
if args.Type == "directory" {
if !r.HasExtension("directory_manipulation") {
return fmt.Errorf("The server is missing the required \"directory_manipulation\" API extension")
}
}
if args.Type == "symlink" {
if !r.HasExtension("file_symlinks") {
return fmt.Errorf("The server is missing the required \"file_symlinks\" API extension")
}
}
if args.WriteMode == "append" {
if !r.HasExtension("file_append") {
return fmt.Errorf("The server is missing the required \"file_append\" API extension")
}
}
// Prepare the HTTP request
requestURL := fmt.Sprintf("%s/1.0/containers/%s/files?path=%s", r.httpHost, url.PathEscape(containerName), url.QueryEscape(path))
requestURL, err := r.setQueryAttributes(requestURL)
if err != nil {
return err
}
req, err := http.NewRequest("POST", requestURL, args.Content)
if err != nil {
return err
}
// Set the user agent
if r.httpUserAgent != "" {
req.Header.Set("User-Agent", r.httpUserAgent)
}
// Set the various headers
if args.UID > -1 {
req.Header.Set("X-LXD-uid", fmt.Sprintf("%d", args.UID))
}
if args.GID > -1 {
req.Header.Set("X-LXD-gid", fmt.Sprintf("%d", args.GID))
}
if args.Mode > -1 {
req.Header.Set("X-LXD-mode", fmt.Sprintf("%04o", args.Mode))
}
if args.Type != "" {
req.Header.Set("X-LXD-type", args.Type)
}
if args.WriteMode != "" {
req.Header.Set("X-LXD-write", args.WriteMode)
}
// Send the request
resp, err := r.do(req)
if err != nil {
return err
}
// Check the return value for a cleaner error
_, _, err = lxdParseResponse(resp)
if err != nil {
return err
}
return nil
}
// DeleteContainerFile deletes a file in the container
func (r *ProtocolLXD) DeleteContainerFile(containerName string, path string) error {
if !r.HasExtension("file_delete") {
return fmt.Errorf("The server is missing the required \"file_delete\" API extension")
}
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/containers/%s/files?path=%s", url.PathEscape(containerName), url.QueryEscape(path)), nil, "")
if err != nil {
return err
}
return nil
}
// GetContainerSnapshotNames returns a list of snapshot names for the container
func (r *ProtocolLXD) GetContainerSnapshotNames(containerName string) ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/snapshots", url.PathEscape(containerName)), nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
names := []string{}
for _, uri := range urls {
fields := strings.Split(uri, fmt.Sprintf("/containers/%s/snapshots/", url.PathEscape(containerName)))
names = append(names, fields[len(fields)-1])
}
return names, nil
}
// GetContainerSnapshots returns a list of snapshots for the container
func (r *ProtocolLXD) GetContainerSnapshots(containerName string) ([]api.ContainerSnapshot, error) {
snapshots := []api.ContainerSnapshot{}
// Fetch the raw value
_, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/snapshots?recursion=1", url.PathEscape(containerName)), nil, "", &snapshots)
if err != nil {
return nil, err
}
return snapshots, nil
}
// GetContainerSnapshot returns a Snapshot struct for the provided container and snapshot names
func (r *ProtocolLXD) GetContainerSnapshot(containerName string, name string) (*api.ContainerSnapshot, string, error) {
snapshot := api.ContainerSnapshot{}
// Fetch the raw value
etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/snapshots/%s", url.PathEscape(containerName), url.PathEscape(name)), nil, "", &snapshot)
if err != nil {
return nil, "", err
}
return &snapshot, etag, nil
}
// CreateContainerSnapshot requests that LXD creates a new snapshot for the container
func (r *ProtocolLXD) CreateContainerSnapshot(containerName string, snapshot api.ContainerSnapshotsPost) (Operation, error) {
// Validate the request
if snapshot.ExpiresAt != nil && !r.HasExtension("snapshot_expiry_creation") {
return nil, fmt.Errorf("The server is missing the required \"snapshot_expiry_creation\" API extension")
}
// Send the request
op, _, err := r.queryOperation("POST", fmt.Sprintf("/containers/%s/snapshots", url.PathEscape(containerName)), snapshot, "")
if err != nil {
return nil, err
}
return op, nil
}
// CopyContainerSnapshot copies a snapshot from a remote server into a new container. Additional options can be passed using ContainerCopyArgs
func (r *ProtocolLXD) CopyContainerSnapshot(source InstanceServer, containerName string, snapshot api.ContainerSnapshot, args *ContainerSnapshotCopyArgs) (RemoteOperation, error) {
// Backward compatibility (with broken Name field)
fields := strings.Split(snapshot.Name, shared.SnapshotDelimiter)
cName := containerName
sName := fields[len(fields)-1]
// Base request
req := api.ContainersPost{
Name: cName,
ContainerPut: api.ContainerPut{
Architecture: snapshot.Architecture,
Config: snapshot.Config,
Devices: snapshot.Devices,
Ephemeral: snapshot.Ephemeral,
Profiles: snapshot.Profiles,
},
}
if snapshot.Stateful && args.Live {
if !r.HasExtension("container_snapshot_stateful_migration") {
return nil, fmt.Errorf("The server is missing the required \"container_snapshot_stateful_migration\" API extension")