github.com/blixtra/nomad@v0.7.2-0.20171221000451-da9a1d7bb050/command/namespace_apply.go (about) 1 package command 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/hashicorp/nomad/api" 8 flaghelper "github.com/hashicorp/nomad/helper/flag-helpers" 9 "github.com/posener/complete" 10 ) 11 12 type NamespaceApplyCommand struct { 13 Meta 14 } 15 16 func (c *NamespaceApplyCommand) Help() string { 17 helpText := ` 18 Usage: nomad namespace apply [options] <namespace> 19 20 Apply is used to create or update a namespace. It takes the namespace name to 21 create or update as its only argument. 22 23 General Options: 24 25 ` + generalOptionsUsage() + ` 26 27 Apply Options: 28 29 -quota 30 The quota to attach to the namespace. 31 32 -description 33 An optional description for the namespace. 34 ` 35 return strings.TrimSpace(helpText) 36 } 37 38 func (c *NamespaceApplyCommand) AutocompleteFlags() complete.Flags { 39 return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient), 40 complete.Flags{ 41 "-description": complete.PredictAnything, 42 "-quota": QuotaPredictor(c.Meta.Client), 43 }) 44 } 45 46 func (c *NamespaceApplyCommand) AutocompleteArgs() complete.Predictor { 47 return NamespacePredictor(c.Meta.Client, nil) 48 } 49 50 func (c *NamespaceApplyCommand) Synopsis() string { 51 return "Create or update a namespace" 52 } 53 54 func (c *NamespaceApplyCommand) Run(args []string) int { 55 var description, quota *string 56 57 flags := c.Meta.FlagSet("namespace apply", FlagSetClient) 58 flags.Usage = func() { c.Ui.Output(c.Help()) } 59 flags.Var((flaghelper.FuncVar)(func(s string) error { 60 description = &s 61 return nil 62 }), "description", "") 63 flags.Var((flaghelper.FuncVar)(func(s string) error { 64 quota = &s 65 return nil 66 }), "quota", "") 67 68 if err := flags.Parse(args); err != nil { 69 return 1 70 } 71 72 // Check that we get exactly one argument 73 args = flags.Args() 74 if l := len(args); l != 1 { 75 c.Ui.Error(c.Help()) 76 return 1 77 } 78 79 name := args[0] 80 81 // Validate we have at-least a name 82 if name == "" { 83 c.Ui.Error("Namespace name required") 84 return 1 85 } 86 87 // Get the HTTP client 88 client, err := c.Meta.Client() 89 if err != nil { 90 c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err)) 91 return 1 92 } 93 94 // Lookup the given namespace 95 ns, _, err := client.Namespaces().Info(name, nil) 96 if err != nil && !strings.Contains(err.Error(), "404") { 97 c.Ui.Error(fmt.Sprintf("Error looking up namespace: %s", err)) 98 return 1 99 } 100 101 if ns == nil { 102 ns = &api.Namespace{ 103 Name: name, 104 } 105 } 106 107 // Add what is set 108 if description != nil { 109 ns.Description = *description 110 } 111 if quota != nil { 112 ns.Quota = *quota 113 } 114 115 _, err = client.Namespaces().Register(ns, nil) 116 if err != nil { 117 c.Ui.Error(fmt.Sprintf("Error applying namespace: %s", err)) 118 return 1 119 } 120 121 c.Ui.Output(fmt.Sprintf("Successfully applied namespace %q!", name)) 122 return 0 123 }