forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject.go
817 lines (647 loc) · 17.6 KB
/
project.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
package main
import (
"fmt"
"io/ioutil"
"os"
"sort"
"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 cmdProject struct {
global *cmdGlobal
}
func (c *cmdProject) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("project")
cmd.Short = i18n.G("Manage projects")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage projects`))
// Create
projectCreateCmd := cmdProjectCreate{global: c.global, project: c}
cmd.AddCommand(projectCreateCmd.Command())
// Delete
projectDeleteCmd := cmdProjectDelete{global: c.global, project: c}
cmd.AddCommand(projectDeleteCmd.Command())
// Edit
projectEditCmd := cmdProjectEdit{global: c.global, project: c}
cmd.AddCommand(projectEditCmd.Command())
// Get
projectGetCmd := cmdProjectGet{global: c.global, project: c}
cmd.AddCommand(projectGetCmd.Command())
// List
projectListCmd := cmdProjectList{global: c.global, project: c}
cmd.AddCommand(projectListCmd.Command())
// Rename
projectRenameCmd := cmdProjectRename{global: c.global, project: c}
cmd.AddCommand(projectRenameCmd.Command())
// Set
projectSetCmd := cmdProjectSet{global: c.global, project: c}
cmd.AddCommand(projectSetCmd.Command())
// Unset
projectUnsetCmd := cmdProjectUnset{global: c.global, project: c, projectSet: &projectSetCmd}
cmd.AddCommand(projectUnsetCmd.Command())
// Show
projectShowCmd := cmdProjectShow{global: c.global, project: c}
cmd.AddCommand(projectShowCmd.Command())
// Info
projectGetInfo := cmdProjectInfo{global: c.global, project: c}
cmd.AddCommand(projectGetInfo.Command())
// Set default
projectSwitchCmd := cmdProjectSwitch{global: c.global, project: c}
cmd.AddCommand(projectSwitchCmd.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 cmdProjectCreate struct {
global *cmdGlobal
project *cmdProject
flagConfig []string
}
func (c *cmdProjectCreate) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("create", i18n.G("[<remote>:]<project>"))
cmd.Short = i18n.G("Create projects")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Create projects`))
cmd.Flags().StringArrayVarP(&c.flagConfig, "config", "c", nil, i18n.G("Config key/value to apply to the new project")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectCreate) 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 project name"))
}
// Create the project
project := api.ProjectsPost{}
project.Name = resource.name
project.Config = map[string]string{}
for _, entry := range c.flagConfig {
if !strings.Contains(entry, "=") {
return fmt.Errorf(i18n.G("Bad key=value pair: %s"), entry)
}
fields := strings.SplitN(entry, "=", 2)
project.Config[fields[0]] = fields[1]
}
err = resource.server.CreateProject(project)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Project %s created")+"\n", resource.name)
}
return nil
}
// Delete.
type cmdProjectDelete struct {
global *cmdGlobal
project *cmdProject
}
func (c *cmdProjectDelete) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("delete", i18n.G("[<remote>:]<project>"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Delete projects")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Delete projects`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectDelete) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
remoteName, _, err := c.global.conf.ParseRemote(args[0])
if err != nil {
return err
}
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return fmt.Errorf(i18n.G("Missing project name"))
}
// Delete the project
err = resource.server.DeleteProject(resource.name)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Project %s deleted")+"\n", resource.name)
}
// Switch back to default project
if resource.name == c.global.conf.Remotes[remoteName].Project {
rc := c.global.conf.Remotes[remoteName]
rc.Project = ""
c.global.conf.Remotes[remoteName] = rc
return c.global.conf.SaveConfig(c.global.confPath)
}
return nil
}
// Edit.
type cmdProjectEdit struct {
global *cmdGlobal
project *cmdProject
}
func (c *cmdProjectEdit) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("edit", i18n.G("[<remote>:]<project>"))
cmd.Short = i18n.G("Edit project configurations as YAML")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Edit project configurations as YAML`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc project edit <project> < project.yaml
Update a project using the content of project.yaml`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectEdit) helpTemplate() string {
return i18n.G(
`### This is a YAML representation of the project.
### Any line starting with a '# will be ignored.
###
### A project consists of a set of features and a description.
###
### An example would look like:
### name: my-project
### features:
### images: True
### profiles: True
### description: My own project
###
### Note that the name is shown but cannot be changed`)
}
func (c *cmdProjectEdit) 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 project 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.ProjectPut{}
err = yaml.Unmarshal(contents, &newdata)
if err != nil {
return err
}
return resource.server.UpdateProject(resource.name, newdata, "")
}
// Extract the current value
project, etag, err := resource.server.GetProject(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&project)
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.ProjectPut{}
err = yaml.Unmarshal(content, &newdata)
if err == nil {
err = resource.server.UpdateProject(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 cmdProjectGet struct {
global *cmdGlobal
project *cmdProject
}
func (c *cmdProjectGet) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("get", i18n.G("[<remote>:]<project> <key>"))
cmd.Short = i18n.G("Get values for project configuration keys")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Get values for project configuration keys`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectGet) 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 project name"))
}
// Get the configuration key
project, _, err := resource.server.GetProject(resource.name)
if err != nil {
return err
}
fmt.Printf("%s\n", project.Config[args[1]])
return nil
}
// List.
type cmdProjectList struct {
global *cmdGlobal
project *cmdProject
flagFormat string
}
func (c *cmdProjectList) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("list", i18n.G("[<remote>:]"))
cmd.Aliases = []string{"ls"}
cmd.Short = i18n.G("List projects")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`List projects`))
cmd.Flags().StringVarP(&c.flagFormat, "format", "f", "table", i18n.G("Format (csv|json|table|yaml|compact)")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectList) Run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 1)
if exit {
return err
}
// Parse remote
remote := conf.DefaultRemote
if len(args) > 0 {
remote = args[0]
}
remoteName := strings.TrimSuffix(remote, ":")
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
// List projects
projects, err := resource.server.GetProjects()
if err != nil {
return err
}
currentProject := conf.Remotes[remoteName].Project
if currentProject == "" {
currentProject = "default"
}
data := [][]string{}
for _, project := range projects {
images := i18n.G("NO")
if shared.IsTrue(project.Config["features.images"]) {
images = i18n.G("YES")
}
profiles := i18n.G("NO")
if shared.IsTrue(project.Config["features.profiles"]) {
profiles = i18n.G("YES")
}
storageVolumes := i18n.G("NO")
if shared.IsTrue(project.Config["features.storage.volumes"]) {
storageVolumes = i18n.G("YES")
}
networks := i18n.G("NO")
if shared.IsTrue(project.Config["features.networks"]) {
networks = i18n.G("YES")
}
name := project.Name
if name == currentProject {
name = fmt.Sprintf("%s (%s)", name, i18n.G("current"))
}
strUsedBy := fmt.Sprintf("%d", len(project.UsedBy))
data = append(data, []string{name, images, profiles, storageVolumes, networks, project.Description, strUsedBy})
}
sort.Sort(utils.ByName(data))
header := []string{
i18n.G("NAME"),
i18n.G("IMAGES"),
i18n.G("PROFILES"),
i18n.G("STORAGE VOLUMES"),
i18n.G("NETWORKS"),
i18n.G("DESCRIPTION"),
i18n.G("USED BY"),
}
return utils.RenderTable(c.flagFormat, header, data, projects)
}
// Rename.
type cmdProjectRename struct {
global *cmdGlobal
project *cmdProject
}
func (c *cmdProjectRename) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("rename", i18n.G("[<remote>:]<project> <new-name>"))
cmd.Aliases = []string{"mv"}
cmd.Short = i18n.G("Rename projects")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Rename projects`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectRename) 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 project name"))
}
// Rename the project
op, err := resource.server.RenameProject(resource.name, api.ProjectPost{Name: args[1]})
if err != nil {
return err
}
err = op.Wait()
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Project %s renamed to %s")+"\n", resource.name, args[1])
}
return nil
}
// Set.
type cmdProjectSet struct {
global *cmdGlobal
project *cmdProject
}
func (c *cmdProjectSet) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("set", i18n.G("[<remote>:]<project> <key>=<value>..."))
cmd.Short = i18n.G("Set project configuration keys")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Set project configuration keys
For backward compatibility, a single configuration key may still be set with:
lxc project set [<remote>:]<project> <key> <value>`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectSet) 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 fmt.Errorf(i18n.G("Missing project name"))
}
// Get the project
project, etag, err := resource.server.GetProject(resource.name)
if err != nil {
return err
}
// Set the configuration key
keys, err := getConfig(args[1:]...)
if err != nil {
return err
}
for k, v := range keys {
project.Config[k] = v
}
return resource.server.UpdateProject(resource.name, project.Writable(), etag)
}
// Unset.
type cmdProjectUnset struct {
global *cmdGlobal
project *cmdProject
projectSet *cmdProjectSet
}
func (c *cmdProjectUnset) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("unset", i18n.G("[<remote>:]<project> <key>"))
cmd.Short = i18n.G("Unset project configuration keys")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Unset project configuration keys`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectUnset) 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.projectSet.Run(cmd, args)
}
// Show.
type cmdProjectShow struct {
global *cmdGlobal
project *cmdProject
}
func (c *cmdProjectShow) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("show", i18n.G("[<remote>:]<project>"))
cmd.Short = i18n.G("Show project options")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Show project options`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectShow) 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 project name"))
}
// Show the project
project, _, err := resource.server.GetProject(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&project)
if err != nil {
return err
}
fmt.Printf("%s", data)
return nil
}
// Switch project.
type cmdProjectSwitch struct {
global *cmdGlobal
project *cmdProject
}
func (c *cmdProjectSwitch) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("switch", i18n.G("[<remote>:]<project>"))
cmd.Short = i18n.G("Switch the current project")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Switch the current project`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectSwitch) Run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse the remote
remote, project, err := conf.ParseRemote(args[0])
if err != nil {
return err
}
// Make sure the remote exists
rc, ok := conf.Remotes[remote]
if !ok {
return fmt.Errorf(i18n.G("Remote %s doesn't exist"), remote)
}
// Make sure the project exists
d, err := conf.GetInstanceServer(remote)
if err != nil {
return err
}
_, _, err = d.GetProject(project)
if err != nil {
return err
}
rc.Project = project
conf.Remotes[remote] = rc
return conf.SaveConfig(c.global.confPath)
}
// Info.
type cmdProjectInfo struct {
global *cmdGlobal
project *cmdProject
flagFormat string
}
func (c *cmdProjectInfo) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("info", i18n.G("[<remote>:]<project> <key>"))
cmd.Short = i18n.G("Get a summary of resource allocations")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Get a summary of resource allocations`))
cmd.Flags().StringVarP(&c.flagFormat, "format", "f", "table", i18n.G("Format (csv|json|table|yaml|compact)")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdProjectInfo) 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 project name"))
}
// Get the current allocations
projectState, err := resource.server.GetProjectState(resource.name)
if err != nil {
return err
}
// Render the output
byteLimits := []string{"disk", "memory"}
data := [][]string{}
for k, v := range projectState.Resources {
limit := i18n.G("UNLIMITED")
if v.Limit >= 0 {
if shared.StringInSlice(k, byteLimits) {
limit = units.GetByteSizeStringIEC(v.Limit, 2)
} else {
limit = fmt.Sprintf("%d", v.Limit)
}
}
usage := ""
if shared.StringInSlice(k, byteLimits) {
usage = units.GetByteSizeStringIEC(v.Usage, 2)
} else {
usage = fmt.Sprintf("%d", v.Usage)
}
data = append(data, []string{strings.ToUpper(k), limit, usage})
}
sort.Sort(utils.ByName(data))
header := []string{
i18n.G("RESOURCE"),
i18n.G("LIMIT"),
i18n.G("USAGE"),
}
return utils.RenderTable(c.flagFormat, header, data, projectState)
}