/
root.go
142 lines (118 loc) · 3.7 KB
/
root.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
package cmd
import (
"bytes"
"encoding/json"
"io/ioutil"
"reflect"
"strings"
"github.com/brocaar/chirpstack-fuota-server/internal/config"
"github.com/mitchellh/mapstructure"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
cfgFile string
version string
)
var rootCmd = &cobra.Command{
Use: "chirpstack-fuota-server",
Short: "ChirpStack FUOTA Server",
RunE: run,
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "path to configuration file (optional)")
rootCmd.PersistentFlags().Int("log-level", 4, "debug=5, info=4, error=2, fatal=1, panic=0")
viper.BindPFlag("general.log_level", rootCmd.PersistentFlags().Lookup("log-level"))
// default values
viper.SetDefault("postgresql.dsn", "postgres://localhost/chirpstack_fuota?sslmode=disable")
viper.SetDefault("postgresql.automigrate", true)
viper.SetDefault("postgresql.max_idle_connections", 2)
viper.SetDefault("application_server.event_handler.marshaler", "protobuf")
viper.SetDefault("application_server.event_handler.http.bind", "0.0.0.0:8090")
viper.SetDefault("application_server.api.server", "localhost:8080")
viper.SetDefault("fuota_server.api.bind", "0.0.0.0:8070")
rootCmd.AddCommand(configCmd)
rootCmd.AddCommand(versionCmd)
}
// Execute executes the root command.
func Execute(v string) {
version = v
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
func initConfig() {
config.Version = version
if cfgFile != "" {
b, err := ioutil.ReadFile(cfgFile)
if err != nil {
log.WithError(err).WithField("config", cfgFile).Fatal("error loading config file")
}
viper.SetConfigType("toml")
if err := viper.ReadConfig(bytes.NewBuffer(b)); err != nil {
log.WithError(err).WithField("config", cfgFile).Fatal("error loading config file")
}
} else {
viper.SetConfigName("chirpstack-fuota-server")
viper.AddConfigPath(".")
viper.AddConfigPath("$HOME/.config/chirpstack-fuota-server")
viper.AddConfigPath("/etc/chirpstack-fuota-server")
if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
default:
log.WithError(err).Fatal("read configuration file error")
}
}
}
viperBindEnvs(config.C)
viperHooks := mapstructure.ComposeDecodeHookFunc(
viperDecodeJSONSlice,
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
)
if err := viper.Unmarshal(&config.C, viper.DecodeHook(viperHooks)); err != nil {
log.WithError(err).Fatal("unmarshal config error")
}
}
func viperBindEnvs(iface interface{}, parts ...string) {
ifv := reflect.ValueOf(iface)
ift := reflect.TypeOf(iface)
for i := 0; i < ift.NumField(); i++ {
v := ifv.Field(i)
t := ift.Field(i)
tv, ok := t.Tag.Lookup("mapstructure")
if !ok {
tv = strings.ToLower(t.Name)
}
if tv == "-" {
continue
}
switch v.Kind() {
case reflect.Struct:
viperBindEnvs(v.Interface(), append(parts, tv)...)
default:
// Bash doesn't allow env variable names with a dot so
// bind the double underscore version.
keyDot := strings.Join(append(parts, tv), ".")
keyUnderscore := strings.Join(append(parts, tv), "__")
viper.BindEnv(keyDot, strings.ToUpper(keyUnderscore))
}
}
}
func viperDecodeJSONSlice(rf reflect.Kind, rt reflect.Kind, data interface{}) (interface{}, error) {
// input must be a string and destination must be a slice
if rf != reflect.String || rt != reflect.Slice {
return data, nil
}
raw := data.(string)
// this decoder expects a JSON list
if !strings.HasPrefix(raw, "[") || !strings.HasSuffix(raw, "]") {
return data, nil
}
var out []map[string]interface{}
err := json.Unmarshal([]byte(raw), &out)
return out, err
}