forked from juju/juju
/
configcommand.go
373 lines (328 loc) · 10.3 KB
/
configcommand.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
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package model
import (
"bytes"
"io"
"sort"
"strings"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/utils/keyvalues"
"github.com/juju/juju/api/modelconfig"
"github.com/juju/juju/cmd/juju/block"
"github.com/juju/juju/cmd/modelcmd"
"github.com/juju/juju/cmd/output"
"github.com/juju/juju/environs/config"
)
const (
modelConfigSummary = "Displays or sets configuration values on a model."
modelConfigHelpDoc = `
By default, all configuration (keys, source, and values) for the current model
are displayed.
Supplying one key name returns only the value for the key. Supplying key=value
will set the supplied key to the supplied value, this can be repeated for
multiple keys.
Examples
juju model-config default-series
juju model-config -m mycontroller:mymodel
juju model-config ftp-proxy=10.0.0.1:8000
juju model-config -m othercontroller:mymodel default-series=yakkety test-mode=false
juju model-config --reset default-series test-mode
See also:
models
model-defaults
`
)
// NewConfigCommand wraps configCommand with sane model settings.
func NewConfigCommand() cmd.Command {
return modelcmd.Wrap(&configCommand{})
}
type attributes map[string]interface{}
// configCommand is the simplified command for accessing and setting
// attributes related to model configuration.
type configCommand struct {
api configCommandAPI
modelcmd.ModelCommandBase
out cmd.Output
action func(configCommandAPI, *cmd.Context) error // The action which we want to handle, set in cmd.Init.
keys []string
reset []string // Holds the keys to be reset until parsed.
resetKeys []string // Holds the keys to be reset once parsed.
values attributes
}
// configCommandAPI defines an API interface to be used during testing.
type configCommandAPI interface {
Close() error
ModelGet() (map[string]interface{}, error)
ModelGetWithMetadata() (config.ConfigValues, error)
ModelSet(config map[string]interface{}) error
ModelUnset(keys ...string) error
}
// Info implements part of the cmd.Command interface.
func (c *configCommand) Info() *cmd.Info {
return &cmd.Info{
Args: "[<model-key>[<=value>] ...]",
Doc: modelConfigHelpDoc,
Name: "model-config",
Purpose: modelConfigSummary,
}
}
// SetFlags implements part of the cmd.Command interface.
func (c *configCommand) SetFlags(f *gnuflag.FlagSet) {
c.ModelCommandBase.SetFlags(f)
c.out.AddFlags(f, "tabular", map[string]cmd.Formatter{
"json": cmd.FormatJson,
"tabular": formatConfigTabular,
"yaml": cmd.FormatYaml,
})
f.Var(cmd.NewAppendStringsValue(&c.reset), "reset", "Reset the provided comma delimited keys")
}
// Init implements part of the cmd.Command interface.
func (c *configCommand) Init(args []string) error {
// If there are arguments provided to reset, we turn it into a slice of
// strings and verify them. If there is one or more valid keys to reset and
// no other errors initalizing the command, c.resetDefaults will be called
// in c.Run.
if err := c.parseResetKeys(); err != nil {
return errors.Trace(err)
}
switch len(args) {
case 0:
return c.handleZeroArgs()
case 1:
return c.handleOneArg(args[0])
default:
return c.handleArgs(args)
}
}
// handleZeroArgs handles the case where there are no positional args.
func (c *configCommand) handleZeroArgs() error {
// If reset is empty we're getting configuration
if len(c.reset) == 0 {
c.action = c.getConfig
}
// Otherwise we're going to reset args.
return nil
}
// handleOneArg handles the case where there is one positional arg.
func (c *configCommand) handleOneArg(arg string) error {
if strings.Contains(arg, "=") {
return c.parseSetKeys([]string{arg})
}
// If we are not setting a value, then we are retrieving one so we need to
// make sure that we are not resetting because it is not valid to get and
// reset simultaneously.
if len(c.reset) > 0 {
return errors.New("cannot set and retrieve model values simultaneously")
}
c.keys = []string{arg}
c.action = c.getConfig
return nil
}
// handleArgs handles the case where there's more than one positional arg.
func (c *configCommand) handleArgs(args []string) error {
err := c.parseSetKeys(args)
if err != nil {
if !strings.Contains(strings.Join(args, " "), "=") {
return errors.New("can only retrieve a single value, or all values")
}
return errors.Trace(err)
}
return nil
}
// parseSetKeys iterates over the args and make sure that the key=value pairs
// are valid. It also checks that the same key isn't being reset.
func (c *configCommand) parseSetKeys(args []string) error {
options, err := keyvalues.Parse(args, true)
if err != nil {
return errors.Trace(err)
}
c.values = make(attributes)
for k, v := range options {
if k == config.AgentVersionKey {
return errors.Errorf(`agent-version must be set via "upgrade-juju"`)
}
c.values[k] = v
}
for _, k := range c.resetKeys {
if _, ok := c.values[k]; ok {
return errors.Errorf(
"key %q cannot be both set and reset in the same command", k)
}
}
c.action = c.setConfig
return nil
}
// parseResetKeys splits the keys provided to --reset after trimming any
// leading or trailing comma. It then verifies that we haven't incorrectly
// received any key=value pairs and finally sets the value(s) on c.resetKeys.
func (c *configCommand) parseResetKeys() error {
if len(c.reset) == 0 {
return nil
}
var resetKeys []string
for _, value := range c.reset {
keys := strings.Split(strings.Trim(value, ","), ",")
resetKeys = append(resetKeys, keys...)
}
for _, k := range resetKeys {
if k == config.AgentVersionKey {
return errors.Errorf("%q cannot be reset", config.AgentVersionKey)
}
if strings.Contains(k, "=") {
return errors.Errorf(
`--reset accepts a comma delimited set of keys "a,b,c", received: %q`, k)
}
}
c.resetKeys = resetKeys
return nil
}
// getAPI returns the API. This allows passing in a test configCommandAPI
// implementation.
func (c *configCommand) getAPI() (configCommandAPI, error) {
if c.api != nil {
return c.api, nil
}
api, err := c.NewAPIRoot()
if err != nil {
return nil, errors.Annotate(err, "opening API connection")
}
client := modelconfig.NewClient(api)
return client, nil
}
// Run implements the meaty part of the cmd.Command interface.
func (c *configCommand) Run(ctx *cmd.Context) error {
client, err := c.getAPI()
if err != nil {
return err
}
defer client.Close()
if len(c.resetKeys) > 0 {
err := c.resetConfig(client, ctx)
if err != nil {
// We return this error naked as it is almost certainly going to be
// cmd.ErrSilent and the cmd.Command framework expects that back
// from cmd.Run if the process is blocked.
return err
}
}
if c.action == nil {
// If we are reset only we end up here, only we've already done that.
return nil
}
return c.action(client, ctx)
}
// reset unsets the keys provided to the command.
func (c *configCommand) resetConfig(client configCommandAPI, ctx *cmd.Context) error {
// ctx unused in this method
if err := c.verifyKnownKeys(client); err != nil {
return errors.Trace(err)
}
return block.ProcessBlockedError(client.ModelUnset(c.resetKeys...), block.BlockChange)
}
// set sets the provided key/value pairs on the model.
func (c *configCommand) setConfig(client configCommandAPI, ctx *cmd.Context) error {
// ctx unused in this method.
envAttrs, err := client.ModelGet()
if err != nil {
return err
}
for key := range c.values {
if _, exists := envAttrs[key]; !exists {
logger.Warningf("key %q is not defined in the current model configuration: possible misspelling", key)
}
}
return block.ProcessBlockedError(client.ModelSet(c.values), block.BlockChange)
}
// get writes the value of a single key or the full output for the model to the cmd.Context.
func (c *configCommand) getConfig(client configCommandAPI, ctx *cmd.Context) error {
attrs, err := client.ModelGetWithMetadata()
if err != nil {
return err
}
for attrName := range attrs {
// We don't want model attributes included, these are available
// via show-model.
if c.isModelAttrbute(attrName) {
delete(attrs, attrName)
}
}
if len(c.keys) == 1 {
key := c.keys[0]
if value, found := attrs[key]; found {
if c.out.Name() == "tabular" {
return cmd.FormatYaml(ctx.Stdout, value.Value)
}
attrs = config.ConfigValues{
key: config.ConfigValue{
Source: value.Source,
Value: value.Value,
},
}
} else {
return errors.Errorf("key %q not found in %q model.", key, attrs["name"])
}
}
return c.out.Write(ctx, attrs)
}
// verifyKnownKeys is a helper to validate the keys we are operating with
// against the set of known attributes from the model.
func (c *configCommand) verifyKnownKeys(client configCommandAPI) error {
known, err := client.ModelGet()
if err != nil {
return errors.Trace(err)
}
allKeys := c.resetKeys[:]
for k := range c.values {
allKeys = append(allKeys, k)
}
for _, key := range allKeys {
// check if the key exists in the known config
// and warn the user if the key is not defined
if _, exists := known[key]; !exists {
logger.Warningf(
"key %q is not defined in the current model configuration: possible misspelling", key)
}
}
return nil
}
// isModelAttribute returns if the supplied attribute is a valid model
// attribute.
func (c *configCommand) isModelAttrbute(attr string) bool {
switch attr {
case config.NameKey, config.TypeKey, config.UUIDKey:
return true
}
return false
}
// formatConfigTabular writes a tabular summary of config information.
func formatConfigTabular(writer io.Writer, value interface{}) error {
configValues, ok := value.(config.ConfigValues)
if !ok {
return errors.Errorf("expected value of type %T, got %T", configValues, value)
}
tw := output.TabWriter(writer)
w := output.Wrapper{tw}
var valueNames []string
for name := range configValues {
valueNames = append(valueNames, name)
}
sort.Strings(valueNames)
w.Println("Attribute", "From", "Value")
for _, name := range valueNames {
info := configValues[name]
out := &bytes.Buffer{}
err := cmd.FormatYaml(out, info.Value)
if err != nil {
return errors.Annotatef(err, "formatting value for %q", name)
}
// Some attribute values have a newline appended
// which makes the output messy.
valString := strings.TrimSuffix(out.String(), "\n")
w.Println(name, info.Source, valString)
}
tw.Flush()
return nil
}