-
Notifications
You must be signed in to change notification settings - Fork 211
/
base.go
268 lines (224 loc) · 6.78 KB
/
base.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
// Package cmd is the base package for various sets of builds and executables created from go-spacemesh
package cmd
import (
"context"
"fmt"
"math/big"
"os"
"os/signal"
"reflect"
"sync"
"github.com/mitchellh/mapstructure"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/spacemeshos/go-spacemesh/cmd/mapstructureutil"
"github.com/spacemeshos/go-spacemesh/common/types"
bc "github.com/spacemeshos/go-spacemesh/config"
"github.com/spacemeshos/go-spacemesh/filesystem"
"github.com/spacemeshos/go-spacemesh/log"
)
var (
// Version is the app's semantic version. Designed to be overwritten by make.
Version string
// Branch is the git branch used to build the App. Designed to be overwritten by make.
Branch string
// Commit is the git commit used to build the app. Designed to be overwritten by make.
Commit string
)
var (
mu sync.RWMutex
globalCtx, globalCancel = context.WithCancel(context.Background())
)
// Ctx returns global context.
func Ctx() context.Context {
mu.RLock()
defer mu.RUnlock()
return globalCtx
}
// SetCtx sets global context.
func SetCtx(ctx context.Context) {
mu.Lock()
defer mu.Unlock()
globalCtx = ctx
}
// Cancel returns global cancellation function.
func Cancel() func() {
mu.RLock()
defer mu.RUnlock()
return globalCancel
}
// SetCancel sets global cancellation function.
func SetCancel(cancelFunc func()) {
mu.Lock()
defer mu.Unlock()
globalCancel = cancelFunc
}
// BaseApp is the base application command, provides basic init and flags for all executables and applications.
type BaseApp struct {
Config *bc.Config
}
// NewBaseApp returns new basic application.
func NewBaseApp() *BaseApp {
dc := bc.DefaultConfig()
return &BaseApp{Config: &dc}
}
// Initialize loads config, sets logger and listens to Ctrl ^C.
func (app *BaseApp) Initialize(cmd *cobra.Command) {
// exit gracefully - e.g. with app Cleanup on sig abort (ctrl-c)
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
// Goroutine that listens for Ctrl ^ C command
// and triggers the quit app
go func() {
for range signalChan {
log.Info("Received an interrupt, stopping services...\n")
Cancel()()
}
}()
// parse the config file based on flags et al
conf, err := parseConfig()
if err != nil {
log.Panic("Panic: ", err.Error())
}
app.Config = conf
if err := EnsureCLIFlags(cmd, app.Config); err != nil {
log.Panic(err.Error())
}
setupLogging(app.Config)
}
func setupLogging(config *bc.Config) {
if config.TestMode {
log.JSONLog(true)
}
// setup logging early
err := filesystem.ExistOrCreate(config.DataDir())
if err != nil {
log.Panic("Failed to setup spacemesh data dir", err)
}
}
func parseConfig() (*bc.Config, error) {
fileLocation := viper.GetString("config")
vip := viper.New()
// read in default config if passed as param using viper
if err := bc.LoadConfig(fileLocation, vip); err != nil {
log.Error(fmt.Sprintf("couldn't load config file at location: %s switching to defaults \n error: %v.",
fileLocation, err))
// return err
}
conf := bc.DefaultConfig()
// load config if it was loaded to our viper
hook := mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
mapstructureutil.BigRatDecodeFunc(),
)
// load config if it was loaded to our viper
err := vip.Unmarshal(&conf, viper.DecodeHook(hook))
if err != nil {
log.Error("Failed to parse config\n")
return nil, fmt.Errorf("parse config: %w", err)
}
return &conf, nil
}
// EnsureCLIFlags checks flag types and converts them.
func EnsureCLIFlags(cmd *cobra.Command, appCFG *bc.Config) error {
assignFields := func(p reflect.Type, elem reflect.Value, name string) {
for i := 0; i < p.NumField(); i++ {
if p.Field(i).Tag.Get("mapstructure") == name {
var val interface{}
switch p.Field(i).Type.String() {
case "bool":
val = viper.GetBool(name)
case "string":
val = viper.GetString(name)
case "int":
val = viper.GetInt(name)
case "int8":
val = int8(viper.GetInt(name))
case "int16":
val = int16(viper.GetInt(name))
case "int32":
val = viper.GetInt32(name)
case "int64":
val = viper.GetInt64(name)
case "uint":
val = viper.GetUint(name)
case "uint8":
val = uint8(viper.GetUint(name))
case "uint16":
val = uint16(viper.GetUint(name))
case "uint32":
val = viper.GetUint32(name)
case "uint64":
val = viper.GetUint64(name)
case "float64":
val = viper.GetFloat64(name)
case "[]string":
val = viper.GetStringSlice(name)
case "time.Duration":
val = viper.GetDuration(name)
case "*big.Rat":
v, ok := new(big.Rat).SetString(viper.GetString(name))
if !ok {
panic("bad string for *big.Rat provided")
}
val = v
case "types.RoundID":
val = types.RoundID(viper.GetUint64(name))
default:
val = viper.Get(name)
}
elem.Field(i).Set(reflect.ValueOf(val))
return
}
}
}
// this is ugly but we have to do this because viper can't handle nested structs when deserialize
cmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {
if f.Changed {
name := f.Name
ff := reflect.TypeOf(appCFG.BaseConfig)
elem := reflect.ValueOf(&appCFG.BaseConfig).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(*appCFG)
elem = reflect.ValueOf(&appCFG).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.API)
elem = reflect.ValueOf(&appCFG.API).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.P2P)
elem = reflect.ValueOf(&appCFG.P2P).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.TIME)
elem = reflect.ValueOf(&appCFG.TIME).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.HARE)
elem = reflect.ValueOf(&appCFG.HARE).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.HareEligibility)
elem = reflect.ValueOf(&appCFG.HareEligibility).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.TortoiseBeacon)
elem = reflect.ValueOf(&appCFG.TortoiseBeacon).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.POST)
elem = reflect.ValueOf(&appCFG.POST).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.SMESHING)
elem = reflect.ValueOf(&appCFG.SMESHING).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.SMESHING.Opts)
elem = reflect.ValueOf(&appCFG.SMESHING.Opts).Elem()
assignFields(ff, elem, name)
ff = reflect.TypeOf(appCFG.LOGGING)
elem = reflect.ValueOf(&appCFG.LOGGING).Elem()
assignFields(ff, elem, name)
}
})
// check list of requested GRPC services (if any)
if err := appCFG.API.ParseServicesList(); err != nil {
return fmt.Errorf("parse services list: %w", err)
}
return nil
}