forked from mattermost/mattermost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
431 lines (350 loc) · 10.5 KB
/
config.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
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package commands
import (
"bytes"
"encoding/json"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
"github.com/mattermost/mattermost-server/utils/fileutils"
)
var ConfigCmd = &cobra.Command{
Use: "config",
Short: "Configuration",
}
var ValidateConfigCmd = &cobra.Command{
Use: "validate",
Short: "Validate config file",
Long: "If the config file is valid, this command will output a success message and have a zero exit code. If it is invalid, this command will output an error and have a non-zero exit code.",
RunE: configValidateCmdF,
}
var ConfigSubpathCmd = &cobra.Command{
Use: "subpath",
Short: "Update client asset loading to use the configured subpath",
Long: "Update the hard-coded production client asset paths to take into account Mattermost running on a subpath.",
Example: ` config subpath
config subpath --path /mattermost
config subpath --path /`,
RunE: configSubpathCmdF,
}
var ConfigGetCmd = &cobra.Command{
Use: "get",
Short: "Get config setting",
Long: "Gets the value of a config setting by its name in dot notation.",
Example: `config get SqlSettings.DriverName`,
Args: cobra.ExactArgs(1),
RunE: configGetCmdF,
}
var ConfigShowCmd = &cobra.Command{
Use: "show",
Short: "Writes the server configuration to STDOUT",
Long: "Pretty-prints the server configuration and writes to STDOUT",
Example: "config show",
RunE: configShowCmdF,
}
var ConfigSetCmd = &cobra.Command{
Use: "set",
Short: "Set config setting",
Long: "Sets the value of a config setting by its name in dot notation. Accepts multiple values for array settings",
Example: "config set SqlSettings.DriverName mysql",
Args: cobra.MinimumNArgs(2),
RunE: configSetCmdF,
}
func init() {
ConfigSubpathCmd.Flags().String("path", "", "Optional subpath; defaults to value in SiteURL")
ConfigCmd.AddCommand(
ValidateConfigCmd,
ConfigSubpathCmd,
ConfigGetCmd,
ConfigShowCmd,
ConfigSetCmd,
)
RootCmd.AddCommand(ConfigCmd)
}
func configValidateCmdF(command *cobra.Command, args []string) error {
utils.TranslationsPreInit()
model.AppErrorInit(utils.T)
filePath, err := command.Flags().GetString("config")
if err != nil {
return err
}
filePath = fileutils.FindConfigFile(filePath)
file, err := os.Open(filePath)
if err != nil {
return err
}
decoder := json.NewDecoder(file)
config := model.Config{}
err = decoder.Decode(&config)
if err != nil {
return err
}
if _, err := file.Stat(); err != nil {
return err
}
if err := config.IsValid(); err != nil {
return errors.New(utils.T(err.Id))
}
CommandPrettyPrintln("The document is valid")
return nil
}
func configSubpathCmdF(command *cobra.Command, args []string) error {
a, err := InitDBCommandContextCobra(command)
if err != nil {
return err
}
defer a.Shutdown()
path, err := command.Flags().GetString("path")
if err != nil {
return errors.Wrap(err, "failed reading path")
}
if path == "" {
return utils.UpdateAssetsSubpathFromConfig(a.Config())
}
if err := utils.UpdateAssetsSubpath(path); err != nil {
return errors.Wrap(err, "failed to update assets subpath")
}
return nil
}
func configGetCmdF(command *cobra.Command, args []string) error {
app, err := InitDBCommandContextCobra(command)
if err != nil {
return err
}
defer app.Shutdown()
// create the model for config
// Note: app.Config() returns a pointer, make appropriate changes
config := app.Config()
// get the print config setting and any error if there is
out, err := printConfigValues(configToMap(*config), strings.Split(args[0], "."), args[0])
if err != nil {
return err
}
fmt.Printf("%s", out)
return nil
}
func configShowCmdF(command *cobra.Command, args []string) error {
app, err := InitDBCommandContextCobra(command)
if err != nil {
return err
}
defer app.Shutdown()
// check that no arguments are given
err = cobra.NoArgs(command, args)
if err != nil {
return err
}
// set up the config object
config := app.Config()
// pretty print
fmt.Printf("%s", prettyPrint(configToMap(*config)))
return nil
}
// printConfigValues function prints out the value of the configSettings working recursively or
// gives an error if config setting is not in the file.
func printConfigValues(configMap map[string]interface{}, configSetting []string, name string) (string, error) {
res, ok := configMap[configSetting[0]]
if !ok {
return "", fmt.Errorf("%s configuration setting is not in the file", name)
}
value := reflect.ValueOf(res)
switch value.Kind() {
case reflect.Map:
if len(configSetting) == 1 {
return printMap(value, 0), nil
}
return printConfigValues(res.(map[string]interface{}), configSetting[1:], name)
default:
if len(configSetting) == 1 {
return fmt.Sprintf("%s: \"%v\"\n", name, res), nil
}
return "", fmt.Errorf("%s configuration setting is not in the file", name)
}
}
// prettyPrint the map
func prettyPrint(configMap map[string]interface{}) string {
value := reflect.ValueOf(configMap)
return printMap(value, 0)
}
// printMap takes a reflect.Value and print it out, recursively if its a map with the given tab settings.
func printMap(value reflect.Value, tabVal int) string {
out := &bytes.Buffer{}
for _, key := range value.MapKeys() {
val := value.MapIndex(key)
if newVal, ok := val.Interface().(map[string]interface{}); !ok {
fmt.Fprintf(out, "%s", strings.Repeat("\t", tabVal))
fmt.Fprintf(out, "%v: \"%v\"\n", key.Interface(), val.Interface())
} else {
fmt.Fprintf(out, "%s", strings.Repeat("\t", tabVal))
fmt.Fprintf(out, "%v:\n", key.Interface())
// going one level in, increase the tab
tabVal++
fmt.Fprintf(out, "%s", printMap(reflect.ValueOf(newVal), tabVal))
// coming back one level, decrease the tab
tabVal--
}
}
return out.String()
}
func configSetCmdF(command *cobra.Command, args []string) error {
app, err := InitDBCommandContextCobra(command)
if err != nil {
return err
}
defer app.Shutdown()
// args[0] -> holds the config setting that we want to change
// args[1:] -> the new value of the config setting
configSetting := args[0]
newVal := args[1:]
// Update the config
// first disable the watchers
app.DisableConfigWatch()
// create the function to update config
oldConfig := app.Config()
newConfig := app.Config()
f := updateConfigValue(configSetting, newVal, oldConfig, newConfig)
// update the config
app.UpdateConfig(f)
// Verify new config
if err := newConfig.IsValid(); err != nil {
return err
}
if err := utils.ValidateLocales(app.Config()); err != nil {
return errors.New("Invalid locale configuration")
}
// make the changes persist
app.PersistConfig()
// reload config
app.ReloadConfig()
// Enable config watchers
app.EnableConfigWatch()
return nil
}
func updateConfigValue(configSetting string, newVal []string, oldConfig, newConfig *model.Config) func(*model.Config) {
return func(update *model.Config) {
// convert config to map[string]interface
configMap := configToMap(*oldConfig)
// iterate through the map and update the value or print an error and exit
err := UpdateMap(configMap, strings.Split(configSetting, "."), newVal)
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}
// convert map to json
bs, err := json.Marshal(configMap)
if err != nil {
fmt.Printf("Error while marshalling map to json %s\n", err)
os.Exit(1)
}
// convert json to struct
err = json.Unmarshal(bs, newConfig)
if err != nil {
fmt.Printf("Error while unmarshalling json to struct %s\n", err)
os.Exit(1)
}
*update = *newConfig
}
}
func UpdateMap(configMap map[string]interface{}, configSettings []string, newVal []string) error {
res, ok := configMap[configSettings[0]]
if !ok {
return fmt.Errorf("unable to find a setting with that name %s", configSettings[0])
}
value := reflect.ValueOf(res)
switch value.Kind() {
case reflect.Map:
// we can only change the value of a particular setting, not the whole map, return error
if len(configSettings) == 1 {
return errors.New("unable to set multiple settings at once")
}
return UpdateMap(res.(map[string]interface{}), configSettings[1:], newVal)
case reflect.Int:
if len(configSettings) == 1 {
val, err := strconv.Atoi(newVal[0])
if err != nil {
return err
}
configMap[configSettings[0]] = val
return nil
}
return fmt.Errorf("unable to find a setting with that name %s", configSettings[0])
case reflect.Int64:
if len(configSettings) == 1 {
val, err := strconv.Atoi(newVal[0])
if err != nil {
return err
}
configMap[configSettings[0]] = int64(val)
return nil
}
return fmt.Errorf("unable to find a setting with that name %s", configSettings[0])
case reflect.Bool:
if len(configSettings) == 1 {
val, err := strconv.ParseBool(newVal[0])
if err != nil {
return err
}
configMap[configSettings[0]] = val
return nil
}
return fmt.Errorf("unable to find a setting with that name %s", configSettings[0])
case reflect.String:
if len(configSettings) == 1 {
configMap[configSettings[0]] = newVal[0]
return nil
}
return fmt.Errorf("unable to find a setting with that name %s", configSettings[0])
case reflect.Slice:
if len(configSettings) == 1 {
configMap[configSettings[0]] = newVal
return nil
}
return fmt.Errorf("unable to find a setting with that name %s", configSettings[0])
default:
return errors.New("type not supported yet")
}
}
// configToMap converts our config into a map
func configToMap(s interface{}) map[string]interface{} {
return structToMap(s)
}
// structToMap converts a struct into a map
func structToMap(t interface{}) map[string]interface{} {
defer func() {
if r := recover(); r != nil {
mlog.Error(fmt.Sprintf("Panicked in structToMap. This should never happen. %v", r))
}
}()
val := reflect.ValueOf(t)
if val.Kind() != reflect.Struct {
return nil
}
out := map[string]interface{}{}
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
var value interface{}
switch field.Kind() {
case reflect.Struct:
value = structToMap(field.Interface())
case reflect.Ptr:
indirectType := field.Elem()
if indirectType.Kind() == reflect.Struct {
value = structToMap(indirectType.Interface())
} else {
value = indirectType.Interface()
}
default:
value = field.Interface()
}
out[val.Type().Field(i).Name] = value
}
return out
}