-
Notifications
You must be signed in to change notification settings - Fork 20
/
root.go
415 lines (341 loc) · 10.8 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
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
package cmd
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"os/user"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/exoscale/cli/pkg/account"
"github.com/exoscale/cli/pkg/globalstate"
"github.com/exoscale/cli/pkg/output"
"github.com/exoscale/egoscale"
)
var gContext context.Context
var gConfig *viper.Viper
var gConfigFolder string
var gConfigFilePath string
// current Account information
var gAccountName string
var csRunstatus *egoscale.Client
// Aliases
var gListAlias = []string{"ls"}
var gRemoveAlias = []string{"rm"}
var gDeleteAlias = []string{"del"}
var gRevokeAlias = []string{"rvk"}
var gShowAlias = []string{"get"}
var gCreateAlias = []string{"add"}
var gUploadAlias = []string{"up"}
var gDissociateAlias = []string{"disassociate", "dissoc"}
var gAssociateAlias = []string{"assoc"}
var RootCmd = &cobra.Command{
Use: "exo",
Short: "Manage your Exoscale infrastructure easily",
SilenceUsage: true,
SilenceErrors: true,
}
var gVersion string
var gCommit string
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version of exo",
Run: func(cmd *cobra.Command, _ []string) {
fmt.Printf("%s %s %s (egoscale %s)\n", cmd.Parent().Name(), gVersion, gCommit, egoscale.Version)
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the RootCmd.
func Execute(version, commit string) {
gVersion = version
gCommit = commit
// trap Ctrl+C and call cancel on the context
ctx, cancel := context.WithCancel(context.Background())
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
defer func() {
signal.Stop(c)
cancel()
}()
go func() {
select {
case <-c:
cancel()
case <-ctx.Done():
}
}()
gContext = ctx
if err := RootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1) //nolint:gocritic
}
}
func init() {
account.CurrentAccount = &account.Account{
DefaultZone: defaultZone,
DefaultTemplate: defaultTemplate,
Endpoint: defaultEndpoint,
Environment: defaultEnvironment,
SosEndpoint: defaultSosEndpoint,
}
gConfig = viper.New()
RootCmd.PersistentFlags().StringVarP(&gConfigFilePath, "config", "C", "", "Specify an alternate config file [env EXOSCALE_CONFIG]")
RootCmd.PersistentFlags().StringVarP(&gAccountName, "use-account", "A", "", "Account to use in config file [env EXOSCALE_ACCOUNT]")
RootCmd.PersistentFlags().StringVarP(&globalstate.OutputFormat, "output-format", "O", "", "Output format (table|json|text), see \"exo output --help\" for more information")
RootCmd.PersistentFlags().StringVar(&output.GOutputTemplate, "output-template", "", "Template to use if output format is \"text\"")
RootCmd.PersistentFlags().BoolVarP(&globalstate.Quiet, "quiet", "Q", false, "Quiet mode (disable non-essential command output)")
RootCmd.AddCommand(versionCmd)
// Don't attempt to load client configuration in testing mode.
// FIXME: stop using global configurations, see if this can be replaced
// with rootCmd.PersistentPreRun or something.
if !strings.HasSuffix(os.Args[0], ".test") {
cobra.OnInitialize(initConfig, buildClient)
}
}
var ignoreClientBuild = false
// initConfig reads in config file and ENV variables if set.
func initConfig() { //nolint:gocyclo
envs := map[string]string{
"EXOSCALE_CONFIG": "config",
"EXOSCALE_ACCOUNT": "use-account",
}
for env, flag := range envs {
pflag := RootCmd.Flags().Lookup(flag)
if pflag == nil {
panic(fmt.Sprintf("unknown flag '%s'", flag))
}
if value, ok := os.LookupEnv(env); ok {
if err := pflag.Value.Set(value); err != nil {
log.Fatal(err)
}
}
}
endpointFromEnv := readFromEnv(
"EXOSCALE_API_ENDPOINT",
"EXOSCALE_COMPUTE_API_ENDPOINT",
"EXOSCALE_ENDPOINT",
"EXOSCALE_COMPUTE_ENDPOINT",
"CLOUDSTACK_ENDPOINT")
sosEndpointFromEnv := readFromEnv(
"EXOSCALE_STORAGE_API_ENDPOINT",
"EXOSCALE_SOS_ENDPOINT",
)
apiKeyFromEnv := readFromEnv(
"EXOSCALE_API_KEY",
"EXOSCALE_KEY",
"CLOUDSTACK_KEY",
"CLOUDSTACK_API_KEY",
)
apiSecretFromEnv := readFromEnv(
"EXOSCALE_API_SECRET",
"EXOSCALE_SECRET",
"EXOSCALE_SECRET_KEY",
"CLOUDSTACK_SECRET",
"CLOUDSTACK_SECRET_KEY",
)
apiEnvironmentFromEnv := readFromEnv("EXOSCALE_API_ENVIRONMENT")
if apiKeyFromEnv != "" && apiSecretFromEnv != "" {
account.CurrentAccount.Name = "<environment variables>"
gConfigFilePath = "<environment variables>"
account.CurrentAccount.Account = "unknown"
account.CurrentAccount.Key = apiKeyFromEnv
account.CurrentAccount.Secret = apiSecretFromEnv
if apiEnvironmentFromEnv != "" {
account.CurrentAccount.Environment = apiEnvironmentFromEnv
}
if endpointFromEnv != "" {
account.CurrentAccount.Endpoint = endpointFromEnv
}
if sosEndpointFromEnv != "" {
account.CurrentAccount.SosEndpoint = sosEndpointFromEnv
}
account.CurrentAccount.DNSEndpoint = buildDNSAPIEndpoint(account.CurrentAccount.Endpoint)
if account.CurrentAccount.ClientTimeout == 0 {
account.CurrentAccount.ClientTimeout = defaultClientTimeout
}
account.GAllAccount = &account.Config{
DefaultAccount: account.CurrentAccount.Name,
Accounts: []account.Account{*account.CurrentAccount},
}
buildClient()
return
}
config := &account.Config{}
usr, err := user.Current()
if err != nil {
log.Println(`current user cannot be read, using "root"`)
usr = &user.User{
Uid: "0",
Gid: "0",
Username: "root",
Name: "root",
HomeDir: "/root",
}
}
cfgdir, err := os.UserConfigDir()
if err != nil {
log.Fatalf("could not find configuration directory: %s", err)
}
gConfigFolder = path.Join(cfgdir, "exoscale")
// Snap packages use $HOME/.exoscale (as negotiated with the snap store)
if _, snap := os.LookupEnv("SNAP_USER_COMMON"); snap {
gConfigFolder = path.Join(usr.HomeDir, ".exoscale")
}
if gConfigFilePath != "" {
// Use config file from the flag.
gConfig.SetConfigFile(gConfigFilePath)
} else {
gConfig.SetConfigName("exoscale")
gConfig.AddConfigPath(gConfigFolder)
// Retain backwards compatibility
gConfig.AddConfigPath(path.Join(usr.HomeDir, ".exoscale"))
gConfig.AddConfigPath(usr.HomeDir)
gConfig.AddConfigPath(".")
}
nonCredentialCmds := []string{"config", "version", "status"}
if err := gConfig.ReadInConfig(); err != nil {
if isNonCredentialCmd(nonCredentialCmds...) {
ignoreClientBuild = true
return
}
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Fatal(`error: the exo CLI must be configured before usage, please run "exo config"`)
}
log.Fatal(err)
}
// All the stored data (e.g. ssh keys) will be put next to the config file.
gConfigFilePath = gConfig.ConfigFileUsed()
gConfigFolder = filepath.Dir(gConfigFilePath)
if err := gConfig.Unmarshal(config); err != nil {
log.Fatal(fmt.Errorf("couldn't read config: %s", err))
}
if len(config.Accounts) == 0 {
if isNonCredentialCmd(nonCredentialCmds...) {
ignoreClientBuild = true
return
}
log.Fatalf("no accounts were found into %q", gConfig.ConfigFileUsed())
return
}
if config.DefaultAccount == "" && gAccountName == "" {
log.Fatalf("default account not defined")
}
if gAccountName == "" {
gAccountName = config.DefaultAccount
}
account.GAllAccount = config
account.GAllAccount.DefaultAccount = gAccountName
for i, acc := range config.Accounts {
if acc.Name == gAccountName {
account.CurrentAccount = &config.Accounts[i]
break
}
}
if account.CurrentAccount.Name == "" {
log.Fatalf("error: could't find any configured account named %q", gAccountName)
}
if account.CurrentAccount.Endpoint == "" {
if account.CurrentAccount.ComputeEndpoint != "" {
account.CurrentAccount.Endpoint = account.CurrentAccount.ComputeEndpoint
} else {
account.CurrentAccount.Endpoint = defaultEndpoint
}
}
if account.CurrentAccount.Environment == "" {
account.CurrentAccount.Environment = defaultEnvironment
}
if account.CurrentAccount.DefaultZone == "" {
account.CurrentAccount.DefaultZone = defaultZone
}
// if an output format isn't specified via cli argument, use
// the current account default format
if globalstate.OutputFormat == "" {
if account.CurrentAccount.DefaultOutputFormat != "" {
globalstate.OutputFormat = account.CurrentAccount.DefaultOutputFormat
} else {
globalstate.OutputFormat = defaultOutputFormat
}
}
if account.CurrentAccount.DNSEndpoint == "" {
account.CurrentAccount.DNSEndpoint = buildDNSAPIEndpoint(account.CurrentAccount.Endpoint)
}
if account.CurrentAccount.DefaultTemplate == "" {
account.CurrentAccount.DefaultTemplate = defaultTemplate
}
if account.CurrentAccount.SosEndpoint == "" {
account.CurrentAccount.SosEndpoint = defaultSosEndpoint
}
if account.CurrentAccount.RunstatusEndpoint == "" {
account.CurrentAccount.RunstatusEndpoint = defaultRunstatusEndpoint
}
if account.CurrentAccount.ClientTimeout == 0 {
account.CurrentAccount.ClientTimeout = defaultClientTimeout
}
clientTimeoutFromEnv := readFromEnv("EXOSCALE_API_TIMEOUT")
if clientTimeoutFromEnv != "" {
if t, err := strconv.Atoi(clientTimeoutFromEnv); err == nil {
account.CurrentAccount.ClientTimeout = t
}
}
account.CurrentAccount.Endpoint = strings.TrimRight(account.CurrentAccount.Endpoint, "/")
account.CurrentAccount.DNSEndpoint = strings.TrimRight(account.CurrentAccount.DNSEndpoint, "/")
account.CurrentAccount.SosEndpoint = strings.TrimRight(account.CurrentAccount.SosEndpoint, "/")
account.CurrentAccount.RunstatusEndpoint = strings.TrimRight(account.CurrentAccount.RunstatusEndpoint, "/")
}
func isNonCredentialCmd(cmds ...string) bool {
for _, cmd := range cmds {
if getCmdPosition(cmd) == 1 {
return true
}
}
return false
}
func buildDNSAPIEndpoint(defaultEndpoint string) string {
dnsEndpoint := strings.Replace(defaultEndpoint, "/"+apiVersion, "/dns", 1)
if strings.Contains(dnsEndpoint, "/"+legacyAPIVersion) {
dnsEndpoint = strings.Replace(defaultEndpoint, "/"+legacyAPIVersion, "/dns", 1)
}
return dnsEndpoint
}
// getCmdPosition returns a command position by fetching os.args and ignoring flags
//
// example: "$ exo -r preprod vm create" vm position is 1 and create is 2
func getCmdPosition(cmd string) int {
count := 1
isFlagParam := false
for _, arg := range os.Args[1:] {
if strings.HasPrefix(arg, "-") {
flag := RootCmd.Flags().Lookup(strings.Trim(arg, "-"))
if flag == nil {
flag = RootCmd.Flags().ShorthandLookup(strings.Trim(arg, "-"))
}
if flag != nil && (flag.Value.Type() != "bool") {
isFlagParam = true
}
continue
}
if isFlagParam {
isFlagParam = false
continue
}
if arg == cmd {
break
}
count++
}
return count
}
// readFromEnv is a os.Getenv on steroids
func readFromEnv(keys ...string) string {
for _, key := range keys {
if value, ok := os.LookupEnv(key); ok {
return value
}
}
return ""
}