-
Notifications
You must be signed in to change notification settings - Fork 67
/
config.go
379 lines (334 loc) 路 10.8 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
package cmd
import (
"context"
"fmt"
"net/http"
"os"
"time"
"github.com/Jeffail/gabs/v2"
"github.com/kubeshop/tracetest/cli/actions"
"github.com/kubeshop/tracetest/cli/analytics"
"github.com/kubeshop/tracetest/cli/config"
"github.com/kubeshop/tracetest/cli/formatters"
"github.com/kubeshop/tracetest/cli/parameters"
"github.com/kubeshop/tracetest/cli/pkg/resourcemanager"
"github.com/kubeshop/tracetest/cli/utils"
"github.com/spf13/cobra"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var (
cliConfig config.Config
cliLogger *zap.Logger
versionText string
isVersionMatch bool
resourceRegistry = actions.NewResourceRegistry()
resourceParams = ¶meters.ResourceParams{}
)
type setupConfig struct {
shouldValidateConfig bool
shouldValidateVersionMismatch bool
}
type setupOption func(*setupConfig)
func SkipConfigValidation() setupOption {
return func(sc *setupConfig) {
sc.shouldValidateConfig = false
}
}
func SkipVersionMismatchCheck() setupOption {
return func(sc *setupConfig) {
sc.shouldValidateVersionMismatch = false
}
}
var resources = resourcemanager.NewRegistry()
func setupCommand(options ...setupOption) func(cmd *cobra.Command, args []string) {
config := setupConfig{
shouldValidateConfig: true,
shouldValidateVersionMismatch: true,
}
for _, option := range options {
option(&config)
}
return func(cmd *cobra.Command, args []string) {
setupOutputFormat(cmd)
setupLogger(cmd, args)
loadConfig(cmd, args)
overrideConfig()
setupVersion()
extraHeaders := http.Header{}
extraHeaders.Set("x-client-id", analytics.ClientID())
extraHeaders.Set("x-source", "cli")
httpClient := resourcemanager.NewHTTPClient(cliConfig.URL(), extraHeaders)
resources.Register(
resourcemanager.NewClient(
httpClient,
"config", "configs",
resourcemanager.TableConfig{
Cells: []resourcemanager.TableCellConfig{
{Header: "ID", Path: "spec.id"},
{Header: "NAME", Path: "spec.name"},
{Header: "ANALYTICS ENABLED", Path: "spec.analyticsEnabled"},
},
},
),
)
resources.Register(
resourcemanager.NewClient(
httpClient,
"analyzer", "analyzers",
resourcemanager.TableConfig{
Cells: []resourcemanager.TableCellConfig{
{Header: "ID", Path: "spec.id"},
{Header: "NAME", Path: "spec.name"},
{Header: "ENABLED", Path: "spec.enabled"},
{Header: "MINIMUM SCORE", Path: "spec.minimumScore"},
},
},
),
)
resources.Register(
resourcemanager.NewClient(
httpClient,
"pollingprofile", "pollingprofiles",
resourcemanager.TableConfig{
Cells: []resourcemanager.TableCellConfig{
{Header: "ID", Path: "spec.id"},
{Header: "NAME", Path: "spec.name"},
{Header: "STRATEGY", Path: "spec.strategy"},
},
},
),
)
resources.Register(
resourcemanager.NewClient(
httpClient,
"demo", "demos",
resourcemanager.TableConfig{
Cells: []resourcemanager.TableCellConfig{
{Header: "ID", Path: "spec.id"},
{Header: "NAME", Path: "spec.name"},
{Header: "TYPE", Path: "spec.type"},
{Header: "ENABLED", Path: "spec.enabled"},
},
},
),
)
resources.Register(
resourcemanager.NewClient(
httpClient,
"datastore", "datastores",
resourcemanager.TableConfig{
Cells: []resourcemanager.TableCellConfig{
{Header: "ID", Path: "spec.id"},
{Header: "NAME", Path: "spec.name"},
{Header: "DEFAULT", Path: "spec.default"},
},
ItemModifier: func(item *gabs.Container) error {
isDefault := item.Path("spec.default").Data().(bool)
if !isDefault {
item.SetP("", "spec.default")
} else {
item.SetP("*", "spec.default")
}
return nil
},
},
),
)
resources.Register(
resourcemanager.NewClient(
httpClient,
"environment", "environments",
resourcemanager.TableConfig{
Cells: []resourcemanager.TableCellConfig{
{Header: "ID", Path: "spec.id"},
{Header: "NAME", Path: "spec.name"},
{Header: "DESCRIPTION", Path: "spec.description"},
},
},
),
)
resources.Register(
resourcemanager.NewClient(
httpClient,
"transaction", "transactions",
resourcemanager.TableConfig{
Cells: []resourcemanager.TableCellConfig{
{Header: "ID", Path: "spec.id"},
{Header: "NAME", Path: "spec.name"},
{Header: "VERSION", Path: "spec.version"},
{Header: "STEPS", Path: "spec.summary.steps"},
{Header: "RUNS", Path: "spec.summary.runs"},
{Header: "LAST RUN TIME", Path: "spec.summary.lastRun.time"},
{Header: "LAST RUN SUCCESSES", Path: "spec.summary.lastRun.passes"},
{Header: "LAST RUN FAILURES", Path: "spec.summary.lastRun.fails"},
},
ItemModifier: func(item *gabs.Container) error {
// set spec.summary.steps to the number of steps in the transaction
item.SetP(len(item.Path("spec.steps").Children()), "spec.summary.steps")
// if lastRun.time is not empty, show it in a nicer format
lastRunTime := item.Path("spec.summary.lastRun.time").Data().(string)
if lastRunTime != "" {
date, err := time.Parse(time.RFC3339, lastRunTime)
if err != nil {
return fmt.Errorf("failed to parse last run time: %s", err)
}
if date.IsZero() {
item.SetP("", "spec.summary.lastRun.time")
} else {
item.SetP(date.Format(time.DateTime), "spec.summary.lastRun.time")
}
}
return nil
},
},
),
)
baseOptions := []actions.ResourceArgsOption{actions.WithLogger(cliLogger), actions.WithConfig(cliConfig)}
configOptions := append(
baseOptions,
actions.WithClient(utils.GetResourceAPIClient("configs", cliConfig)),
actions.WithFormatter(formatters.NewConfigFormatter()),
)
configActions := actions.NewConfigActions(configOptions...)
resourceRegistry.Register(configActions)
analyzerOptions := append(
baseOptions,
actions.WithClient(utils.GetResourceAPIClient("analyzers", cliConfig)),
actions.WithFormatter(formatters.NewAnalyzerFormatter()),
)
analyzerActions := actions.NewAnalyzerActions(analyzerOptions...)
resourceRegistry.Register(analyzerActions)
pollingOptions := append(
baseOptions,
actions.WithClient(utils.GetResourceAPIClient("pollingprofiles", cliConfig)),
actions.WithFormatter(formatters.NewPollingFormatter()),
)
pollingActions := actions.NewPollingActions(pollingOptions...)
resourceRegistry.Register(pollingActions)
demoOptions := append(
baseOptions,
actions.WithClient(utils.GetResourceAPIClient("demos", cliConfig)),
actions.WithFormatter(formatters.NewDemoFormatter()),
)
demoActions := actions.NewDemoActions(demoOptions...)
resourceRegistry.Register(demoActions)
dataStoreOptions := append(
baseOptions,
actions.WithClient(utils.GetResourceAPIClient("datastores", cliConfig)),
actions.WithFormatter(formatters.NewDatastoreFormatter()),
)
dataStoreActions := actions.NewDataStoreActions(dataStoreOptions...)
resourceRegistry.Register(dataStoreActions)
environmentOptions := append(
baseOptions,
actions.WithClient(utils.GetResourceAPIClient("environments", cliConfig)),
actions.WithFormatter(formatters.NewEnvironmentsFormatter()),
)
environmentActions := actions.NewEnvironmentsActions(environmentOptions...)
resourceRegistry.Register(environmentActions)
openapiClient := utils.GetAPIClient(cliConfig)
transactionOptions := append(
baseOptions,
actions.WithClient(utils.GetResourceAPIClient("transactions", cliConfig)),
actions.WithFormatter(formatters.NewTransactionsFormatter()),
)
transactionActions := actions.NewTransactionsActions(openapiClient, transactionOptions...)
resourceRegistry.Register(transactionActions)
if config.shouldValidateConfig {
validateConfig(cmd, args)
}
if config.shouldValidateVersionMismatch {
validateVersionMismatch()
}
analytics.Init()
}
}
func overrideConfig() {
if overrideEndpoint != "" {
scheme, endpoint, err := config.ParseServerURL(overrideEndpoint)
if err != nil {
msg := fmt.Sprintf("cannot parse endpoint %s", overrideEndpoint)
cliLogger.Error(msg, zap.Error(err))
ExitCLI(1)
}
cliConfig.Scheme = scheme
cliConfig.Endpoint = endpoint
}
}
func setupOutputFormat(cmd *cobra.Command) {
if cmd.GroupID != "resources" && output == string(formatters.Empty) {
output = string(formatters.DefaultOutput)
}
o := formatters.Output(output)
if !formatters.ValidOutput(o) {
fmt.Fprintf(os.Stderr, "Invalid output format %s. Available formats are [%s]\n", output, outputFormatsString)
ExitCLI(1)
}
formatters.SetOutput(o)
}
func loadConfig(cmd *cobra.Command, args []string) {
config, err := config.LoadConfig(configFile)
if err != nil {
cliLogger.Fatal("could not load config", zap.Error(err))
}
cliConfig = config
}
func validateConfig(cmd *cobra.Command, args []string) {
if cliConfig.IsEmpty() {
cliLogger.Warn("You haven't configured your CLI, some commands might fail!")
cliLogger.Warn("Run 'tracetest configure' to configure your CLI")
}
}
func setupLogger(cmd *cobra.Command, args []string) {
atom := zap.NewAtomicLevel()
if verbose {
atom.SetLevel(zap.DebugLevel)
} else {
atom.SetLevel(zap.WarnLevel)
}
encoderCfg := zapcore.EncoderConfig{
TimeKey: zapcore.OmitKey,
LevelKey: "level",
NameKey: zapcore.OmitKey,
CallerKey: zapcore.OmitKey,
FunctionKey: zapcore.OmitKey,
MessageKey: "message",
StacktraceKey: zapcore.OmitKey,
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.CapitalColorLevelEncoder,
EncodeTime: zapcore.EpochTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
logger := zap.New(zapcore.NewCore(
zapcore.NewConsoleEncoder(encoderCfg),
zapcore.Lock(os.Stdout),
atom,
))
cliLogger = logger
}
func teardownCommand(cmd *cobra.Command, args []string) {
cliLogger.Sync()
}
func setupVersion() {
ctx := context.Background()
options := []actions.ActionArgsOption{
actions.ActionWithClient(utils.GetAPIClient(cliConfig)),
actions.ActionWithConfig(cliConfig),
actions.ActionWithLogger(cliLogger),
}
action := actions.NewGetServerVersionAction(options...)
versionText, isVersionMatch = action.GetVersion(ctx)
}
func validateVersionMismatch() {
if !isVersionMatch && os.Getenv("TRACETEST_DEV") == "" {
fmt.Fprintf(os.Stderr, versionText+`
鉁栵笍 Error: Version Mismatch
The CLI version and the server version are not compatible. To fix this, you'll need to make sure that both your CLI and server are using compatible versions.
We recommend upgrading both of them to the latest available version. Check out our documentation https://docs.tracetest.io/configuration/upgrade for simple instructions on how to upgrade.
Thank you for using Tracetest! We apologize for any inconvenience caused.
`)
ExitCLI(1)
}
}