-
Notifications
You must be signed in to change notification settings - Fork 18
/
root.go
388 lines (318 loc) · 9.22 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
package cmd
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"os/user"
"path"
"strings"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var gContext context.Context
var gConfigFolder string
var gConfigFilePath string
//current Account information
var gAccountName string
var gCurrentAccount = &account{
DefaultZone: defaultZone,
DefaultTemplate: defaultTemplate,
Endpoint: defaultEndpoint,
SosEndpoint: defaultSosEndpoint,
}
var gAllAccount *config
//egoscale client
var cs *egoscale.Client
var csDNS *egoscale.Client
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"}
// RootCmd represents the base command when called without any subcommands
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)
},
}
var (
gOutputFormat string
gOutputTemplate string
gQuiet bool
)
// 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)
}
}
func init() {
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(&gOutputFormat, "output-format", "O", "", "Output format (table|json|text)")
RootCmd.PersistentFlags().StringVar(&gOutputTemplate, "output-template", "", "Template to use if output format is \"text\"")
RootCmd.PersistentFlags().BoolVarP(&gQuiet, "quiet", "Q", false, "Quiet mode (disable non-essential command output")
RootCmd.AddCommand(versionCmd)
cobra.OnInitialize(initConfig, buildClient)
}
var ignoreClientBuild = false
// initConfig reads in config file and ENV variables if set.
func initConfig() {
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)
}
}
}
// an attempt to mimic existing behaviours
envEndpoint := readFromEnv(
"EXOSCALE_ENDPOINT",
"EXOSCALE_COMPUTE_ENDPOINT",
"CLOUDSTACK_ENDPOINT")
envKey := readFromEnv(
"EXOSCALE_KEY",
"EXOSCALE_API_KEY",
"CLOUDSTACK_KEY",
"CLOUDSTACK_API_KEY",
)
envSecret := readFromEnv(
"EXOSCALE_SECRET",
"EXOSCALE_API_SECRET",
"EXOSCALE_SECRET_KEY",
"CLOUDSTACK_SECRET",
"CLOUDSTACK_SECRET_KEY",
)
envSosEndpoint := readFromEnv(
"EXOSCALE_SOS_ENDPOINT",
)
if envKey != "" && envSecret != "" {
gCurrentAccount.Name = "environment variables"
gCurrentAccount.Account = "unknown"
gCurrentAccount.Key = envKey
gCurrentAccount.Secret = envSecret
if envEndpoint != "" {
gCurrentAccount.Endpoint = envEndpoint
}
if envSosEndpoint != "" {
gCurrentAccount.SosEndpoint = envSosEndpoint
}
gCurrentAccount.DNSEndpoint = buildDNSAPIEndpoint(gCurrentAccount.Endpoint)
gAllAccount = &config{
DefaultAccount: gCurrentAccount.Name,
Accounts: []account{*gCurrentAccount},
}
buildClient()
return
}
config := &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",
}
}
xdgHome, found := os.LookupEnv("XDG_CONFIG_HOME")
if found {
gConfigFolder = path.Join(xdgHome, "exoscale")
} else {
home, found := os.LookupEnv("HOME")
if found {
gConfigFolder = path.Join(home, ".config", "exoscale")
} else {
// The XDG spec specifies a default XDG_CONFIG_HOME in $HOME/.config
gConfigFolder = path.Join(usr.HomeDir, ".config", "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.
viper.SetConfigFile(gConfigFilePath)
} else {
viper.SetConfigName("exoscale")
viper.AddConfigPath(gConfigFolder)
// Retain backwards compatibility
viper.AddConfigPath(path.Join(usr.HomeDir, ".exoscale"))
viper.AddConfigPath(usr.HomeDir)
viper.AddConfigPath(".")
}
nonCredentialCmds := []string{"config", "version", "status"}
if err := viper.ReadInConfig(); err != nil {
if isNonCredentialCmd(nonCredentialCmds...) {
ignoreClientBuild = true
return
}
log.Fatal(err)
}
// All the stored data (e.g. ssh keys) will be put next to the config file.
gConfigFilePath = viper.ConfigFileUsed()
gConfigFolder = path.Dir(gConfigFilePath)
if err := viper.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", viper.ConfigFileUsed())
return
}
if config.DefaultAccount == "" && gAccountName == "" {
log.Fatalf("default account not defined")
}
if gOutputFormat == "" {
if gOutputFormat = config.DefaultOutputFormat; gOutputFormat == "" {
gOutputFormat = defaultOutputFormat
}
}
if gAccountName == "" {
gAccountName = config.DefaultAccount
}
gAllAccount = config
gAllAccount.DefaultAccount = gAccountName
for i, acc := range config.Accounts {
if acc.Name == gAccountName {
gCurrentAccount = &config.Accounts[i]
break
}
}
if gCurrentAccount == nil {
log.Fatalf("could't find any account with name: %q", gAccountName)
}
if gCurrentAccount.Endpoint == "" {
if gCurrentAccount.ComputeEndpoint != "" {
gCurrentAccount.Endpoint = gCurrentAccount.ComputeEndpoint
} else {
gCurrentAccount.Endpoint = defaultEndpoint
}
}
if gCurrentAccount.DefaultZone == "" {
gCurrentAccount.DefaultZone = defaultZone
}
if gCurrentAccount.DNSEndpoint == "" {
gCurrentAccount.DNSEndpoint = buildDNSAPIEndpoint(gCurrentAccount.Endpoint)
}
if gCurrentAccount.DefaultTemplate == "" {
gCurrentAccount.DefaultTemplate = defaultTemplate
}
if gCurrentAccount.SosEndpoint == "" {
gCurrentAccount.SosEndpoint = defaultSosEndpoint
}
if gCurrentAccount.RunstatusEndpoint == "" {
gCurrentAccount.RunstatusEndpoint = defaultRunstatusEndpoint
}
gCurrentAccount.Endpoint = strings.TrimRight(gCurrentAccount.Endpoint, "/")
gCurrentAccount.DNSEndpoint = strings.TrimRight(gCurrentAccount.DNSEndpoint, "/")
gCurrentAccount.SosEndpoint = strings.TrimRight(gCurrentAccount.SosEndpoint, "/")
gCurrentAccount.RunstatusEndpoint = strings.TrimRight(gCurrentAccount.RunstatusEndpoint, "/")
egoscale.UserAgent = fmt.Sprintf("Exoscale-CLI/%s (%s) %s", gVersion, gCommit, egoscale.UserAgent)
}
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 ""
}