-
Notifications
You must be signed in to change notification settings - Fork 20
/
root.go
304 lines (246 loc) · 6.67 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
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
var gAllAccount *config
//egoscale client
var cs *egoscale.Client
var csDNS *egoscale.Client
//Aliases
var gListAlias = []string{"ls"}
var gRemoveAlias = []string{"rm"}
var gDeleteAlias = []string{"del"}
var gShowAlias = []string{"get"}
var gCreateAlias = []string{"add"}
var gUploadAlias = []string{"up"}
var gDissociateAlias = []string{"disassociate", "dissoc"}
var gAssociateAlias = []string{"assoc"}
type account struct {
Name string
Account string
Endpoint string
ComputeEndpoint string // legacy config.
DNSEndpoint string
SosEndpoint string
Key string
Secret string
DefaultZone string
DefaultSSHKey string
DefaultTemplate string
}
type config struct {
DefaultAccount string
Accounts []account
}
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "exo",
Short: "Manage easily your Exoscale infrastructure",
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, args []string) {
fmt.Printf("exo %s %s (egoscale %s)\n", 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.Println(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.AddCommand(versionCmd)
cobra.OnInitialize(initConfig, buildClient)
}
var ignoreClientBuild = false
func buildClient() {
if ignoreClientBuild {
return
}
if cs != nil {
return
}
csDNS = egoscale.NewClient(gCurrentAccount.DNSEndpoint, gCurrentAccount.Key, gCurrentAccount.Secret)
cs = egoscale.NewClient(gCurrentAccount.Endpoint, gCurrentAccount.Key, gCurrentAccount.Secret)
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
envs := map[string]string{
"EXOSCALE_CONFIG": "config",
"EXOSCALE_ACCOUNT": "account",
}
for env, flag := range envs {
flag := RootCmd.Flags().Lookup(flag)
if value, ok := os.LookupEnv(env); ok {
if err := flag.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",
"CLOUSTACK_API_KEY",
)
envSecret := readFromEnv(
"EXOSCALE_SECRET",
"EXOSCALE_API_SECRET",
"EXOSCALE_SECRET_KEY",
"CLOUDSTACK_SECRET",
"CLOUDSTACK_SECRET_KEY",
)
if envEndpoint != "" && envKey != "" && envSecret != "" {
cs = egoscale.NewClient(envEndpoint, envKey, envSecret)
return
}
config := &config{}
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
gConfigFolder = path.Join(usr.HomeDir, ".exoscale")
if gConfigFilePath != "" {
// Use config file from the flag.
viper.SetConfigFile(gConfigFilePath)
} else {
// Search config in home directory with name ".cobra_test" (without extension).
viper.SetConfigName("exoscale")
viper.AddConfigPath(path.Join(usr.HomeDir, ".exoscale"))
viper.AddConfigPath(usr.HomeDir)
viper.AddConfigPath(".")
}
if err := viper.ReadInConfig(); err != nil && (getCmdPosition("config") == 1 || getCmdPosition("version") == 1) {
ignoreClientBuild = true
return
}
if err := viper.ReadInConfig(); err != nil {
log.Fatal(err)
}
if err := viper.Unmarshal(config); err != nil {
log.Fatal(fmt.Errorf("couldn't read config: %s", err))
}
if config.DefaultAccount == "" && gAccountName == "" {
log.Fatalf("default account not defined")
}
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.DNSEndpoint == "" {
gCurrentAccount.DNSEndpoint = strings.Replace(gCurrentAccount.Endpoint, "/compute", "/dns", 1)
}
if gCurrentAccount.DefaultTemplate == "" {
gCurrentAccount.DefaultTemplate = defaultTemplate
}
if gCurrentAccount.SosEndpoint == "" {
gCurrentAccount.SosEndpoint = defaultSosEndpoint
}
gCurrentAccount.Endpoint = strings.TrimRight(gCurrentAccount.Endpoint, "/")
gCurrentAccount.DNSEndpoint = strings.TrimRight(gCurrentAccount.DNSEndpoint, "/")
gCurrentAccount.SosEndpoint = strings.TrimRight(gCurrentAccount.SosEndpoint, "/")
}
// 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 ""
}