forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.go
808 lines (642 loc) · 18.4 KB
/
storage.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
package main
import (
"fmt"
"io/ioutil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/lxc/lxd/lxc/utils"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
cli "github.com/lxc/lxd/shared/cmd"
"github.com/lxc/lxd/shared/i18n"
"github.com/lxc/lxd/shared/termios"
"github.com/lxc/lxd/shared/units"
)
type cmdStorage struct {
global *cmdGlobal
flagTarget string
}
func (c *cmdStorage) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("storage")
cmd.Short = i18n.G("Manage storage pools and volumes")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage storage pools and volumes`))
// Create
storageCreateCmd := cmdStorageCreate{global: c.global, storage: c}
cmd.AddCommand(storageCreateCmd.Command())
// Delete
storageDeleteCmd := cmdStorageDelete{global: c.global, storage: c}
cmd.AddCommand(storageDeleteCmd.Command())
// Edit
storageEditCmd := cmdStorageEdit{global: c.global, storage: c}
cmd.AddCommand(storageEditCmd.Command())
// Get
storageGetCmd := cmdStorageGet{global: c.global, storage: c}
cmd.AddCommand(storageGetCmd.Command())
// Info
storageInfoCmd := cmdStorageInfo{global: c.global, storage: c}
cmd.AddCommand(storageInfoCmd.Command())
// List
storageListCmd := cmdStorageList{global: c.global, storage: c}
cmd.AddCommand(storageListCmd.Command())
// Set
storageSetCmd := cmdStorageSet{global: c.global, storage: c}
cmd.AddCommand(storageSetCmd.Command())
// Show
storageShowCmd := cmdStorageShow{global: c.global, storage: c}
cmd.AddCommand(storageShowCmd.Command())
// Unset
storageUnsetCmd := cmdStorageUnset{global: c.global, storage: c, storageSet: &storageSetCmd}
cmd.AddCommand(storageUnsetCmd.Command())
// Volume
storageVolumeCmd := cmdStorageVolume{global: c.global, storage: c}
cmd.AddCommand(storageVolumeCmd.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
}
// Create.
type cmdStorageCreate struct {
global *cmdGlobal
storage *cmdStorage
}
func (c *cmdStorageCreate) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("create", i18n.G("[<remote>:]<pool> <driver> [key=value...]"))
cmd.Short = i18n.G("Create storage pools")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Create storage pools`))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageCreate) 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]
client := resource.server
// Create the new storage pool entry
pool := api.StoragePoolsPost{}
pool.Name = resource.name
pool.Config = map[string]string{}
pool.Driver = args[1]
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)
}
pool.Config[entry[0]] = entry[1]
}
// If a target member was specified the API won't actually create the
// pool, but only define it as pending in the database.
if c.storage.flagTarget != "" {
client = client.UseTarget(c.storage.flagTarget)
}
// Create the pool
err = client.CreateStoragePool(pool)
if err != nil {
return err
}
if !c.global.flagQuiet {
if c.storage.flagTarget != "" {
fmt.Printf(i18n.G("Storage pool %s pending on member %s")+"\n", resource.name, c.storage.flagTarget)
} else {
fmt.Printf(i18n.G("Storage pool %s created")+"\n", resource.name)
}
}
return nil
}
// Delete.
type cmdStorageDelete struct {
global *cmdGlobal
storage *cmdStorage
}
func (c *cmdStorageDelete) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("delete", i18n.G("[<remote>:]<pool>"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Delete storage pools")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Delete storage pools`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageDelete) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 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 fmt.Errorf(i18n.G("Missing pool name"))
}
// Delete the pool
err = resource.server.DeleteStoragePool(resource.name)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Storage pool %s deleted")+"\n", resource.name)
}
return nil
}
// Edit.
type cmdStorageEdit struct {
global *cmdGlobal
storage *cmdStorage
}
func (c *cmdStorageEdit) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("edit", i18n.G("[<remote>:]<pool>"))
cmd.Short = i18n.G("Edit storage pool configurations as YAML")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Edit storage pool configurations as YAML`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc storage edit [<remote>:]<pool> < pool.yaml
Update a storage pool using the content of pool.yaml.`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageEdit) helpTemplate() string {
return i18n.G(
`### This is a YAML representation of a storage pool.
### Any line starting with a '#' will be ignored.
###
### A storage pool consists of a set of configuration items.
###
### An example would look like:
### name: default
### driver: zfs
### used_by: []
### config:
### size: "61203283968"
### source: /home/chb/mnt/lxd_test/default.img
### zfs.pool_name: default`)
}
func (c *cmdStorageEdit) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 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 fmt.Errorf(i18n.G("Missing pool name"))
}
// If stdin isn't a terminal, read text from it
if !termios.IsTerminal(getStdinFd()) {
contents, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
newdata := api.StoragePoolPut{}
err = yaml.Unmarshal(contents, &newdata)
if err != nil {
return err
}
return resource.server.UpdateStoragePool(resource.name, newdata, "")
}
// Extract the current value
pool, etag, err := resource.server.GetStoragePool(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&pool)
if err != nil {
return err
}
// Spawn the editor
content, err := shared.TextEditor("", []byte(c.helpTemplate()+"\n\n"+string(data)))
if err != nil {
return err
}
for {
// Parse the text received from the editor
newdata := api.StoragePoolPut{}
err = yaml.Unmarshal(content, &newdata)
if err == nil {
err = resource.server.UpdateStoragePool(resource.name, newdata, etag)
}
// Respawn the editor
if err != nil {
fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err)
fmt.Println(i18n.G("Press enter to open the editor again or ctrl+c to abort change"))
_, err := os.Stdin.Read(make([]byte, 1))
if err != nil {
return err
}
content, err = shared.TextEditor("", content)
if err != nil {
return err
}
continue
}
break
}
return nil
}
// Get.
type cmdStorageGet struct {
global *cmdGlobal
storage *cmdStorage
}
func (c *cmdStorageGet) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("get", i18n.G("[<remote>:]<pool> <key>"))
cmd.Short = i18n.G("Get values for storage pool configuration keys")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Get values for storage pool configuration keys`))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageGet) 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 fmt.Errorf(i18n.G("Missing pool name"))
}
// If a target member was specified, we return also member-specific config values.
if c.storage.flagTarget != "" {
resource.server = resource.server.UseTarget(c.storage.flagTarget)
}
// Get the property
resp, _, err := resource.server.GetStoragePool(resource.name)
if err != nil {
return err
}
for k, v := range resp.Config {
if k == args[1] {
fmt.Printf("%s\n", v)
}
}
return nil
}
// Info.
type cmdStorageInfo struct {
global *cmdGlobal
storage *cmdStorage
flagBytes bool
}
func (c *cmdStorageInfo) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("info", i18n.G("[<remote>:]<pool>"))
cmd.Short = i18n.G("Show useful information about storage pools")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Show useful information about storage pools`))
cmd.Flags().BoolVar(&c.flagBytes, "bytes", false, i18n.G("Show the used and free space in bytes"))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageInfo) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 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 fmt.Errorf(i18n.G("Missing pool name"))
}
// Targeting
if c.storage.flagTarget != "" {
if !resource.server.IsClustered() {
return fmt.Errorf(i18n.G("To use --target, the destination remote must be a cluster"))
}
resource.server = resource.server.UseTarget(c.storage.flagTarget)
}
// Get the pool information
pool, _, err := resource.server.GetStoragePool(resource.name)
if err != nil {
return err
}
res, err := resource.server.GetStoragePoolResources(resource.name)
if err != nil {
return err
}
// Declare the poolinfo map of maps in order to build up the yaml
poolinfo := make(map[string]map[string]string)
poolusedby := make(map[string]map[string][]string)
// Translations
usedbystring := i18n.G("used by")
infostring := i18n.G("info")
namestring := i18n.G("name")
driverstring := i18n.G("driver")
descriptionstring := i18n.G("description")
totalspacestring := i18n.G("total space")
spaceusedstring := i18n.G("space used")
// Initialize the usedby map
poolusedby[usedbystring] = map[string][]string{}
/* Build up the usedby map
/1.0/{instances,images,profiles}/storagepoolname and
/1.0/storage-pools/<poolname>/<type>/<volname>
remove the /1.0/ and build the map based on the resources name as key
and resources details as value */
for _, v := range pool.UsedBy {
u, err := url.Parse(v)
if err != nil {
continue
}
fields := strings.Split(u.Path[5:], "/")
bytype := fields[0]
bywhat := fields[1]
if bytype == "storage-pools" {
bytype = "volumes"
bywhat = fields[4]
}
var info string
// Show info regarding the project and target if present.
values := u.Query()
proj := values.Get("project")
target := values.Get("target")
if proj != "" {
info = fmt.Sprintf("project %q", proj)
}
if target != "" {
if info == "" {
info = fmt.Sprintf("target %q", target)
} else {
info = fmt.Sprintf("%s, target %q", info, target)
}
}
if info != "" {
bywhat = fmt.Sprintf("%s (%s)", bywhat, info)
}
poolusedby[usedbystring][bytype] = append(poolusedby[usedbystring][bytype], bywhat)
}
// Initialize the info map
poolinfo[infostring] = map[string]string{}
// Build up the info map
poolinfo[infostring][namestring] = pool.Name
poolinfo[infostring][driverstring] = pool.Driver
poolinfo[infostring][descriptionstring] = pool.Description
if c.flagBytes {
poolinfo[infostring][totalspacestring] = strconv.FormatUint(res.Space.Total, 10)
poolinfo[infostring][spaceusedstring] = strconv.FormatUint(res.Space.Used, 10)
} else {
poolinfo[infostring][totalspacestring] = units.GetByteSizeStringIEC(int64(res.Space.Total), 2)
poolinfo[infostring][spaceusedstring] = units.GetByteSizeStringIEC(int64(res.Space.Used), 2)
}
poolinfodata, err := yaml.Marshal(poolinfo)
if err != nil {
return err
}
poolusedbydata, err := yaml.Marshal(poolusedby)
if err != nil {
return err
}
fmt.Printf("%s", poolinfodata)
fmt.Printf("%s", poolusedbydata)
return nil
}
// List.
type cmdStorageList struct {
global *cmdGlobal
storage *cmdStorage
flagFormat string
}
func (c *cmdStorageList) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("list", i18n.G("[<remote>:]"))
cmd.Aliases = []string{"ls"}
cmd.Short = i18n.G("List available storage pools")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`List available storage pools`))
cmd.Flags().StringVarP(&c.flagFormat, "format", "f", "table", i18n.G("Format (csv|json|table|yaml|compact)")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageList) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 1)
if exit {
return err
}
// Parse remote
remote := ""
if len(args) > 0 {
remote = args[0]
}
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
// Get the storage pools
pools, err := resource.server.GetStoragePools()
if err != nil {
return err
}
data := [][]string{}
for _, pool := range pools {
usedby := strconv.Itoa(len(pool.UsedBy))
details := []string{pool.Name, pool.Driver}
if !resource.server.IsClustered() {
details = append(details, pool.Config["source"])
}
details = append(details, pool.Description)
details = append(details, usedby)
details = append(details, strings.ToUpper(pool.Status))
data = append(data, details)
}
sort.Sort(utils.ByName(data))
header := []string{
i18n.G("NAME"),
i18n.G("DRIVER"),
}
if !resource.server.IsClustered() {
header = append(header, i18n.G("SOURCE"))
}
header = append(header, i18n.G("DESCRIPTION"))
header = append(header, i18n.G("USED BY"))
header = append(header, i18n.G("STATE"))
return utils.RenderTable(c.flagFormat, header, data, pools)
}
// Set.
type cmdStorageSet struct {
global *cmdGlobal
storage *cmdStorage
}
func (c *cmdStorageSet) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("set", i18n.G("[<remote>:]<pool> <key> <value>"))
cmd.Short = i18n.G("Set storage pool configuration keys")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Set storage pool configuration keys
For backward compatibility, a single configuration key may still be set with:
lxc storage set [<remote>:]<pool> <key> <value>`))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageSet) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, -1)
if exit {
return err
}
// Parse remote
remote := args[0]
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return fmt.Errorf(i18n.G("Missing pool name"))
}
client := resource.server
if c.storage.flagTarget != "" {
client = client.UseTarget(c.storage.flagTarget)
}
// Get the pool entry
pool, etag, err := client.GetStoragePool(resource.name)
if err != nil {
return err
}
// Parse key/values
keys, err := getConfig(args[1:]...)
if err != nil {
return err
}
// Update the pool
for k, v := range keys {
pool.Config[k] = v
}
err = client.UpdateStoragePool(resource.name, pool.Writable(), etag)
if err != nil {
return err
}
return nil
}
// Show.
type cmdStorageShow struct {
global *cmdGlobal
storage *cmdStorage
flagResources bool
}
func (c *cmdStorageShow) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("show", i18n.G("[<remote>:]<pool>"))
cmd.Short = i18n.G("Show storage pool configurations and resources")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Show storage pool configurations and resources`))
cmd.Flags().BoolVar(&c.flagResources, "resources", false, i18n.G("Show the resources available to the storage pool"))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageShow) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
remote := ""
if len(args) > 0 {
remote = args[0]
}
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
client := resource.server
if resource.name == "" {
return fmt.Errorf(i18n.G("Missing pool name"))
}
// If a target member was specified, we return also member-specific config values.
if c.storage.flagTarget != "" {
client = client.UseTarget(c.storage.flagTarget)
}
if c.flagResources {
res, err := client.GetStoragePoolResources(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&res)
if err != nil {
return err
}
fmt.Printf("%s", data)
return nil
}
pool, _, err := client.GetStoragePool(resource.name)
if err != nil {
return err
}
sort.Strings(pool.UsedBy)
data, err := yaml.Marshal(&pool)
if err != nil {
return err
}
fmt.Printf("%s", data)
return nil
}
// Unset.
type cmdStorageUnset struct {
global *cmdGlobal
storage *cmdStorage
storageSet *cmdStorageSet
}
func (c *cmdStorageUnset) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("unset", i18n.G("[<remote>:]<pool> <key>"))
cmd.Short = i18n.G("Unset storage pool configuration keys")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Unset storage pool configuration keys`))
cmd.Flags().StringVar(&c.storage.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdStorageUnset) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, 2)
if exit {
return err
}
args = append(args, "")
return c.storageSet.Run(cmd, args)
}