-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathstorage_volume.go
2954 lines (2364 loc) · 77.1 KB
/
storage_volume.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 (
"errors"
"fmt"
"io"
"net/url"
"os"
"path"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/canonical/lxd/client"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
cli "github.com/canonical/lxd/shared/cmd"
"github.com/canonical/lxd/shared/i18n"
"github.com/canonical/lxd/shared/ioprogress"
"github.com/canonical/lxd/shared/termios"
"github.com/canonical/lxd/shared/units"
)
type volumeColumn struct {
Name string
Data func(api.StorageVolume, api.StorageVolumeState) string
NeedsState bool
}
type cmdStorageVolume struct {
global *cmdGlobal
storage *cmdStorage
flagDestinationTarget string
}
func parseVolume(defaultType string, name string) (volName string, volType string) {
fields := strings.SplitN(name, "/", 2)
if len(fields) == 1 {
volName, volType = fields[0], defaultType
} else if len(fields) == 2 && !slices.Contains([]string{"custom", "image", "container", "virtual-machine"}, fields[0]) {
volName, volType = name, defaultType
} else {
volName, volType = fields[1], fields[0]
}
return volName, volType
}
func (c *cmdStorageVolume) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("volume")
cmd.Short = i18n.G("Manage storage volumes")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage storage volumes
Unless specified through a prefix, all volume operations affect "custom" (user created) volumes.`))
// Attach
storageVolumeAttachCmd := cmdStorageVolumeAttach{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeAttachCmd.command())
// Attach profile
storageVolumeAttachProfileCmd := cmdStorageVolumeAttachProfile{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeAttachProfileCmd.command())
// Copy
storageVolumeCopyCmd := cmdStorageVolumeCopy{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeCopyCmd.command())
// Create
storageVolumeCreateCmd := cmdStorageVolumeCreate{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeCreateCmd.command())
// Delete
storageVolumeDeleteCmd := cmdStorageVolumeDelete{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeDeleteCmd.command())
// Detach
storageVolumeDetachCmd := cmdStorageVolumeDetach{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeDetachCmd.command())
// Detach profile
storageVolumeDetachProfileCmd := cmdStorageVolumeDetachProfile{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeDetachProfileCmd.command())
// Edit
storageVolumeEditCmd := cmdStorageVolumeEdit{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeEditCmd.command())
// Export
storageVolumeExportCmd := cmdStorageVolumeExport{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeExportCmd.command())
// Get
storageVolumeGetCmd := cmdStorageVolumeGet{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeGetCmd.command())
// Import
storageVolumeImportCmd := cmdStorageVolumeImport{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeImportCmd.command())
// Info
storageVolumeInfoCmd := cmdStorageVolumeInfo{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeInfoCmd.command())
// List
storageVolumeListCmd := cmdStorageVolumeList{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeListCmd.command())
// Rename
storageVolumeRenameCmd := cmdStorageVolumeRename{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeRenameCmd.command())
// Move
storageVolumeMoveCmd := cmdStorageVolumeMove{global: c.global, storage: c.storage, storageVolume: c, storageVolumeCopy: &storageVolumeCopyCmd, storageVolumeRename: &storageVolumeRenameCmd}
cmd.AddCommand(storageVolumeMoveCmd.command())
// Set
storageVolumeSetCmd := cmdStorageVolumeSet{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeSetCmd.command())
// Show
storageVolumeShowCmd := cmdStorageVolumeShow{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeShowCmd.command())
// Snapshot
storageVolumeSnapshotCmd := cmdStorageVolumeSnapshot{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeSnapshotCmd.command())
// Restore
storageVolumeRestoreCmd := cmdStorageVolumeRestore{global: c.global, storage: c.storage, storageVolume: c}
cmd.AddCommand(storageVolumeRestoreCmd.command())
// Unset
storageVolumeUnsetCmd := cmdStorageVolumeUnset{global: c.global, storage: c.storage, storageVolume: c, storageVolumeSet: &storageVolumeSetCmd}
cmd.AddCommand(storageVolumeUnsetCmd.command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
func (c *cmdStorageVolume) parseVolumeWithPool(name string) (volumeName string, poolName string) {
fields := strings.SplitN(name, "/", 2)
if len(fields) == 1 {
return fields[0], ""
}
return fields[1], fields[0]
}
// Attach.
type cmdStorageVolumeAttach struct {
global *cmdGlobal
storage *cmdStorage
storageVolume *cmdStorageVolume
}
func (c *cmdStorageVolumeAttach) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("attach", i18n.G("[<remote>:]<pool> [<type>/]<volume> <instance> [<device name>] [<path>]"))
cmd.Short = i18n.G("Attach new storage volumes to instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Attach new storage volumes to instances
<type> must be one of "custom" or "virtual-machine"`))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpStoragePools(toComplete, false)
}
if len(args) == 1 {
return c.global.cmpStoragePoolVolumes(args[0], "custom")
}
if len(args) == 2 {
return c.global.cmpInstanceNamesFromRemote(args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdStorageVolumeAttach) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 3, 5)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing pool name"))
}
volName, volType := parseVolume("custom", args[1])
if volType != "custom" && volType != "virtual-machine" {
return errors.New(i18n.G(`Only "custom" and "virtual-machine" volumes can be attached to instances`))
}
// Attach the volume
devPath := ""
devName := ""
if len(args) == 3 {
devName = args[1]
} else if len(args) == 4 {
client := resource.server
// Use the provided target.
if c.storage.flagTarget != "" && client.IsClustered() {
client = client.UseTarget(c.storage.flagTarget)
}
vol, _, err := client.GetStoragePoolVolume(resource.name, volType, volName)
if err != nil {
return err
}
switch vol.ContentType {
case "block", "iso":
devName = args[3]
case "filesystem":
// If using a filesystem volume, the path must also be provided as the fourth argument.
if !strings.HasPrefix(args[3], "/") {
devPath = path.Join("/", args[3])
} else {
devPath = args[3]
}
devName = args[1]
default:
return errors.New(i18n.G("Unsupported content type for attaching to instances"))
}
} else if len(args) == 5 {
// Path and device name have been given to us.
devName = args[3]
devPath = args[4]
}
// Prepare the instance's device entry
device := map[string]string{
"type": "disk",
"pool": resource.name,
"source": volName,
"path": devPath,
}
// Only specify sourcetype when not the default
if volType != "custom" {
device["source.type"] = volType
}
// Add the device to the instance
err = instanceDeviceAdd(resource.server, args[2], devName, device)
if err != nil {
return err
}
return nil
}
// Attach profile.
type cmdStorageVolumeAttachProfile struct {
global *cmdGlobal
storage *cmdStorage
storageVolume *cmdStorageVolume
}
func (c *cmdStorageVolumeAttachProfile) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("attach-profile", i18n.G("[<remote:>]<pool> [<type>/]<volume> <profile> [<device name>] [<path>]"))
cmd.Short = i18n.G("Attach new storage volumes to profiles")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Attach new storage volumes to profiles
<type> must be one of "custom" or "virtual-machine"`))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpStoragePools(toComplete, false)
}
if len(args) == 1 {
return c.global.cmpStoragePoolVolumes(args[0], "custom")
}
if len(args) == 2 {
return c.global.cmpProfileNamesFromRemote(args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdStorageVolumeAttachProfile) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 3, 5)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing pool name"))
}
// Attach the volume
devPath := ""
devName := ""
if len(args) == 3 {
devName = args[1]
} else if len(args) == 4 {
// Only the path has been given to us.
devPath = args[3]
devName = args[1]
} else if len(args) == 5 {
// Path and device name have been given to us.
devName = args[3]
devPath = args[4]
}
volName, volType := parseVolume("custom", args[1])
if volType != "custom" && volType != "virtual-machine" {
return errors.New(i18n.G(`Only "custom" and "virtual-machine" volumes can be attached to profiles`))
}
// Check if the requested storage volume actually exists
vol, _, err := resource.server.GetStoragePoolVolume(resource.name, volType, volName)
if err != nil {
return err
}
// Prepare the instance's device entry
device := map[string]string{
"type": "disk",
"pool": resource.name,
"source": volName,
}
// Ignore path for block volumes
if vol.ContentType != "block" {
device["path"] = devPath
}
// Only specify sourcetype when not the default
if volType != "custom" {
device["source.type"] = volType
}
// Add the device to the instance
err = profileDeviceAdd(resource.server, args[2], devName, device)
if err != nil {
return err
}
return nil
}
// Copy.
type cmdStorageVolumeCopy struct {
global *cmdGlobal
storage *cmdStorage
storageVolume *cmdStorageVolume
flagMode string
flagVolumeOnly bool
flagTargetProject string
flagRefresh bool
}
func (c *cmdStorageVolumeCopy) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("copy", i18n.G("[<remote>:]<pool>/<volume>[/<snapshot>] [<remote>:]<pool>/<volume>"))
cmd.Aliases = []string{"cp"}
cmd.Short = i18n.G("Copy storage volumes")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Copy storage volumes`))
cmd.Flags().StringVar(&c.flagMode, "mode", "pull", i18n.G("Transfer mode. One of pull (default), push or relay.")+"``")
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.Flags().StringVar(&c.storageVolume.flagDestinationTarget, "destination-target", "", i18n.G("Destination cluster member name")+"``")
cmd.Flags().BoolVar(&c.flagVolumeOnly, "volume-only", false, i18n.G("Copy the volume without its snapshots"))
cmd.Flags().StringVar(&c.flagTargetProject, "target-project", "", i18n.G("Copy to a project different from the source")+"``")
cmd.Flags().BoolVar(&c.flagRefresh, "refresh", false, i18n.G("Refresh and update the existing storage volume copies"))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpStoragePoolWithVolume(toComplete)
}
if len(args) == 1 {
completions, directive := c.global.cmpStoragePools(toComplete, true)
for i, completion := range completions {
if !strings.Contains(completion, ":") {
completions[i] = completion + "/"
}
}
return completions, directive
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdStorageVolumeCopy) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, 2)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0], args[1])
if err != nil {
return err
}
// Source
srcResource := resources[0]
if srcResource.name == "" {
return errors.New(i18n.G("Missing source volume name"))
}
srcServer := srcResource.server
srcPath := srcResource.name
// If the source server is standalone then --target cannot be provided.
if c.storage.flagTarget != "" && !srcServer.IsClustered() {
return errors.New(i18n.G("Cannot set --target when source server is not clustered"))
}
// Get source pool and volume name
srcVolName, srcVolPool := c.storageVolume.parseVolumeWithPool(srcPath)
if srcVolPool == "" {
return errors.New(i18n.G("No storage pool for source volume specified"))
}
if c.storage.flagTarget != "" {
srcServer = srcServer.UseTarget(c.storage.flagTarget)
}
// Check if requested storage volume exists.
srcVolParentName, srcVolSnapName, srcIsSnapshot := api.GetParentAndSnapshotName(srcVolName)
srcVol, _, err := srcServer.GetStoragePoolVolume(srcVolPool, "custom", srcVolParentName)
if err != nil {
return err
}
if srcIsSnapshot && c.flagVolumeOnly {
return fmt.Errorf("Cannot set --volume-only when copying a snapshot")
}
// If the volume is in local storage, set the target to its location (or provide a helpful error
// message if the target is incorrect). If the volume is in remote storage (and the source server is clustered) we
// can use any provided target. Note that for standalone servers, this will set the target to "none".
if srcVol.Location != "" && srcVol.Location != "none" {
if c.storage.flagTarget != "" && c.storage.flagTarget != srcVol.Location {
return fmt.Errorf(i18n.G("Given target %q does not match source volume location %q"), c.storage.flagTarget, srcVol.Location)
}
srcServer = srcServer.UseTarget(srcVol.Location)
} else if c.storage.flagTarget != "" && srcServer.IsClustered() {
srcServer = srcServer.UseTarget(c.storage.flagTarget)
}
// Destination
dstResource := resources[1]
dstServer := dstResource.server
dstPath := dstResource.name
// We can always set the destination target if the destination server is clustered (for local storage volumes this
// places the volume on the target member, for remote volumes this does nothing).
if c.storageVolume.flagDestinationTarget != "" {
if !dstServer.IsClustered() {
return errors.New(i18n.G("Cannot set --destination-target when destination server is not clustered"))
}
dstServer = dstServer.UseTarget(c.storageVolume.flagDestinationTarget)
}
// Get destination pool and volume name
// TODO: Make is possible to run lxc storage volume copy pool/vol/snap new-pool/new-vol/new-snap
dstVolName, dstVolPool := c.storageVolume.parseVolumeWithPool(dstPath)
if dstVolPool == "" {
return errors.New(i18n.G("No storage pool for target volume specified"))
}
// Parse the mode
mode := "pull"
if c.flagMode != "" {
mode = c.flagMode
}
var op lxd.RemoteOperation
// Messages
opMsg := i18n.G("Copying the storage volume: %s")
finalMsg := i18n.G("Storage volume copied successfully!")
if cmd.Name() == "move" {
opMsg = i18n.G("Moving the storage volume: %s")
finalMsg = i18n.G("Storage volume moved successfully!")
}
// If source is a snapshot get source snapshot volume info and apply to the srcVol.
if srcIsSnapshot {
srcVolSnapshot, _, err := srcServer.GetStoragePoolVolumeSnapshot(srcVolPool, "custom", srcVolParentName, srcVolSnapName)
if err != nil {
return err
}
// Copy info from source snapshot into source volume used for new volume.
srcVol.Name = srcVolName
srcVol.Config = srcVolSnapshot.Config
srcVol.Description = srcVolSnapshot.Description
}
if cmd.Name() == "move" && srcServer == dstServer {
args := &lxd.StoragePoolVolumeMoveArgs{}
args.Name = dstVolName
args.Mode = mode
args.VolumeOnly = false
args.Project = c.flagTargetProject
op, err = dstServer.MoveStoragePoolVolume(dstVolPool, srcServer, srcVolPool, *srcVol, args)
if err != nil {
return err
}
} else {
args := &lxd.StoragePoolVolumeCopyArgs{}
args.Name = dstVolName
args.Mode = mode
args.VolumeOnly = c.flagVolumeOnly
args.Refresh = c.flagRefresh
if c.flagTargetProject != "" {
dstServer = dstServer.UseProject(c.flagTargetProject)
}
op, err = dstServer.CopyStoragePoolVolume(dstVolPool, srcServer, srcVolPool, *srcVol, args)
if err != nil {
return err
}
}
// Register progress handler
progress := cli.ProgressRenderer{
Format: opMsg,
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
// Wait for operation to finish
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return err
}
if cmd.Name() == "move" && srcServer != dstServer {
if srcIsSnapshot {
_, err = srcServer.DeleteStoragePoolVolumeSnapshot(srcVolPool, srcVol.Type, srcVolParentName, srcVolSnapName)
} else {
err = srcServer.DeleteStoragePoolVolume(srcVolPool, srcVol.Type, srcVolName)
}
if err != nil {
progress.Done("")
return fmt.Errorf("Failed deleting source volume after copy: %w", err)
}
}
progress.Done(finalMsg)
return nil
}
// Create.
type cmdStorageVolumeCreate struct {
global *cmdGlobal
storage *cmdStorage
storageVolume *cmdStorageVolume
flagContentType string
}
func (c *cmdStorageVolumeCreate) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("create", i18n.G("[<remote>:]<pool> <volume> [key=value...]"))
cmd.Short = i18n.G("Create new custom storage volumes")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Create new custom storage volumes`))
cmd.Example = cli.FormatSection("", i18n.G(`lxc storage volume create p1 v1
lxc storage volume create p1 v1 < config.yaml
Create storage volume v1 for pool p1 with configuration from config.yaml.`))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.Flags().StringVar(&c.flagContentType, "type", "filesystem", i18n.G("Content type, block or filesystem")+"``")
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpStoragePools(toComplete, false)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdStorageVolumeCreate) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, -1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing pool name"))
}
client := resource.server
var volumePut api.StorageVolumePut
if !termios.IsTerminal(getStdinFd()) {
contents, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
err = yaml.UnmarshalStrict(contents, &volumePut)
if err != nil {
return err
}
}
// Parse the input
volName, volType := parseVolume("custom", args[1])
// Create the storage volume entry
vol := api.StorageVolumesPost{
Name: volName,
Type: volType,
ContentType: c.flagContentType,
StorageVolumePut: volumePut,
}
if volumePut.Config == nil {
vol.Config = map[string]string{}
}
for i := 2; i < len(args); i++ {
entry := strings.SplitN(args[i], "=", 2)
if len(entry) < 2 {
return fmt.Errorf(i18n.G("Bad key=value pair: %s"), entry)
}
vol.Config[entry[0]] = entry[1]
}
// If a target was specified, create the volume on the given member.
if c.storage.flagTarget != "" {
client = client.UseTarget(c.storage.flagTarget)
}
err = client.CreateStoragePoolVolume(resource.name, vol)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Storage volume %s created")+"\n", args[1])
}
return nil
}
// Delete.
type cmdStorageVolumeDelete struct {
global *cmdGlobal
storage *cmdStorage
storageVolume *cmdStorageVolume
}
func (c *cmdStorageVolumeDelete) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("delete", i18n.G("[<remote>:]<pool> <volume>[/<snapshot>]"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Delete storage volumes")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Delete storage volumes`))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpStoragePools(toComplete, false)
}
if len(args) == 1 {
return c.global.cmpStoragePoolVolumes(args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdStorageVolumeDelete) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, 2)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing pool name"))
}
client := resource.server
// Parse the input
volName, volType := parseVolume("custom", args[1])
// If a target was specified, delete the volume on the given member.
if c.storage.flagTarget != "" {
client = client.UseTarget(c.storage.flagTarget)
}
fields := strings.SplitN(volName, "/", 2)
if len(fields) == 2 {
// Delete the snapshot
op, err := client.DeleteStoragePoolVolumeSnapshot(resource.name, volType, fields[0], fields[1])
if err != nil {
return err
}
err = op.Wait()
if err != nil {
return err
}
} else {
// Delete the volume
err := client.DeleteStoragePoolVolume(resource.name, volType, volName)
if err != nil {
return err
}
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Storage volume %s deleted")+"\n", args[1])
}
return nil
}
// Detach.
type cmdStorageVolumeDetach struct {
global *cmdGlobal
storage *cmdStorage
storageVolume *cmdStorageVolume
}
func (c *cmdStorageVolumeDetach) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("detach", i18n.G("[<remote>:]<pool> [<type>/]<volume> <instance> [<device name>]"))
cmd.Short = i18n.G("Detach storage volumes from instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Detach storage volumes from instances`))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpStoragePools(toComplete, false)
}
if len(args) == 1 {
return c.global.cmpStoragePoolVolumes(args[0], "custom")
}
if len(args) == 2 {
return c.global.cmpStoragePoolVolumeInstances(args[0], args[1])
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdStorageVolumeDetach) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 3, 4)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing pool name"))
}
// Detach storage volumes
devName := ""
if len(args) == 4 {
devName = args[3]
}
// Get the instance entry
inst, etag, err := resource.server.GetInstance(args[2])
if err != nil {
return err
}
volName, volType := parseVolume("custom", args[1])
// Find the device
if devName == "" {
for n, d := range inst.Devices {
sourceType := "custom"
if d["source.type"] != "" {
sourceType = d["source.type"]
}
if d["type"] == "disk" && d["pool"] == resource.name && volType == sourceType && volName == d["source"] {
if devName != "" {
return errors.New(i18n.G("More than one device matches, specify the device name"))
}
devName = n
}
}
}
if devName == "" {
return errors.New(i18n.G("No device found for this storage volume"))
}
_, ok := inst.Devices[devName]
if !ok {
return errors.New(i18n.G("The specified device doesn't exist"))
}
// Remove the device
delete(inst.Devices, devName)
op, err := resource.server.UpdateInstance(args[2], inst.Writable(), etag)
if err != nil {
return err
}
return op.Wait()
}
// Detach profile.
type cmdStorageVolumeDetachProfile struct {
global *cmdGlobal
storage *cmdStorage
storageVolume *cmdStorageVolume
}
func (c *cmdStorageVolumeDetachProfile) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("detach-profile", i18n.G("[<remote:>]<pool> [<type>/]<volume> <profile> [<device name>]"))
cmd.Short = i18n.G("Detach storage volumes from profiles")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Detach storage volumes from profiles`))
cmd.RunE = c.run
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpStoragePools(toComplete, false)
}
if len(args) == 1 {
return c.global.cmpStoragePoolVolumes(args[0], "custom")
}
if len(args) == 2 {
return c.global.cmpStoragePoolVolumeProfiles(args[0], args[1])
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdStorageVolumeDetachProfile) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 3, 4)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing pool name"))
}
devName := ""
if len(args) > 3 {
devName = args[3]
}
// Get the profile entry
profile, etag, err := resource.server.GetProfile(args[2])
if err != nil {
return err
}
volName, volType := parseVolume("custom", args[1])
// Find the device
if devName == "" {
for n, d := range profile.Devices {
sourceType := "custom"
if d["source.type"] != "" {
sourceType = d["source.type"]
}
if d["type"] == "disk" && d["pool"] == resource.name && volType == sourceType && volName == d["source"] {
if devName != "" {
return errors.New(i18n.G("More than one device matches, specify the device name"))
}
devName = n
}
}
}