-
Notifications
You must be signed in to change notification settings - Fork 151
/
init.go
351 lines (312 loc) · 10.3 KB
/
init.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
package init
import (
"context"
"errors"
"fmt"
"net/http"
"reflect"
"strings"
"github.com/fatih/color"
"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-cli/v2/internal/namespaces/autocomplete"
iamcommands "github.com/scaleway/scaleway-cli/v2/internal/namespaces/iam/v1alpha1"
"github.com/scaleway/scaleway-cli/v2/internal/terminal"
iam "github.com/scaleway/scaleway-sdk-go/api/iam/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/scw"
)
/*
See below the schema `scw init` follows to ask for default config:
yes +----------+
+-------+Config ok?|
| +----------+
+---+ no +----v----+ |no
|out+<----+Override?| v
+---+ +----+----+ +----+-----+
| |Read +-----------+
+------>+ token | token |
yes +----------+ |
|
v
+------+---+
|Read access|
| key |
+------+---+
|
|
|
|
|
|
|
|
|
|
|
|
+-------+----------+ |
|ask default config+<-----+
+------------------+
*/
func GetCommands() *core.Commands {
return core.NewCommands(initCommand())
}
type initArgs struct {
AccessKey string
SecretKey string
ProjectID string
OrganizationID string
Region scw.Region
Zone scw.Zone
SendTelemetry *bool
WithSSHKey *bool
InstallAutocomplete *bool
}
func initCommand() *core.Command {
return &core.Command{
Groups: []string{"config"},
Short: `Initialize the config`,
Long: `Initialize the active profile of the config.
Default path for configuration file is based on the following priority order:
- $SCW_CONFIG_PATH
- $XDG_CONFIG_HOME/scw/config.yaml
- $HOME/.config/scw/config.yaml
- $USERPROFILE/.config/scw/config.yaml`,
Namespace: "init",
AllowAnonymousClient: true,
ArgsType: reflect.TypeOf(initArgs{}),
ArgSpecs: core.ArgSpecs{
{
Name: "secret-key",
Short: "Scaleway secret-key",
ValidateFunc: core.ValidateSecretKey(),
},
{
Name: "access-key",
Short: "Scaleway access-key",
ValidateFunc: core.ValidateAccessKey(),
},
{
Name: "organization-id",
Short: "Scaleway organization ID",
ValidateFunc: core.ValidateOrganizationID(),
},
{
Name: "project-id",
Short: "Scaleway project ID",
ValidateFunc: core.ValidateProjectID(),
},
{
Name: "send-telemetry",
Short: "Send usage statistics and diagnostics",
},
{
Name: "with-ssh-key",
Short: "Whether the SSH key for managing instances should be uploaded automatically",
Default: core.DefaultValueSetter("true"),
},
{
Name: "install-autocomplete",
Short: "Whether the autocomplete script should be installed during initialisation",
},
core.RegionArgSpec(scw.AllRegions...),
core.ZoneArgSpec(scw.AllZones...),
},
SeeAlsos: []*core.SeeAlso{
{
Short: "Config management help",
Command: "scw config",
},
},
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
args := argsI.(*initArgs)
profileName := core.ExtractProfileName(ctx)
configPath := core.ExtractConfigPath(ctx)
// Show logo banner, or simple welcome message
printScalewayBanner()
config, err := loadConfigOrEmpty(configPath)
if err != nil {
return nil, err
}
err = promptProfileOverride(ctx, config, configPath, profileName)
if err != nil {
return nil, err
}
// Credentials
if args.SecretKey == "" {
args.SecretKey, err = promptSecretKey(ctx)
if err != nil {
return nil, err
}
}
if args.AccessKey == "" {
args.AccessKey, err = promptAccessKey(ctx)
if err != nil {
return nil, err
}
}
if args.OrganizationID == "" {
args.OrganizationID, err = promptOrganizationID(ctx)
if err != nil {
return nil, err
}
}
if args.ProjectID == "" {
args.ProjectID = getAPIKeyDefaultProjectID(ctx, args.AccessKey, args.SecretKey, args.OrganizationID)
args.ProjectID, err = promptProjectID(ctx, args.AccessKey, args.SecretKey, args.OrganizationID, args.ProjectID)
if err != nil {
return nil, err
}
}
// Ask for default zone, currently not used as CLI will default to fr-par-1
if args.Zone == "" {
args.Zone, err = promptDefaultZone(ctx)
if err != nil {
return nil, err
}
}
// Deduce Region from Zone
if args.Region == "" {
args.Region, err = args.Zone.Region()
if err != nil {
return nil, err
}
}
// Ask for send usage permission
if args.SendTelemetry == nil {
args.SendTelemetry, err = promptTelemetry(ctx)
if err != nil {
return nil, err
}
}
// Ask whether we should install autocomplete
if args.InstallAutocomplete == nil {
args.InstallAutocomplete, err = promptAutocomplete(ctx)
if err != nil {
return nil, err
}
}
profile := &scw.Profile{
AccessKey: &args.AccessKey,
SecretKey: &args.SecretKey,
DefaultZone: scw.StringPtr(args.Zone.String()),
DefaultRegion: scw.StringPtr(args.Region.String()),
DefaultOrganizationID: &args.OrganizationID,
DefaultProjectID: &args.ProjectID, // An API key is always bound to a project.
}
// Save the profile as default or as a named profile
if profileName == scw.DefaultProfileName {
// Default configuration
config.Profile = *profile
} else {
if config.Profiles == nil {
config.Profiles = make(map[string]*scw.Profile)
}
config.Profiles[profileName] = profile
}
// Persist configuration on disk
interactive.Printf("Config saved at %s:\n%s\n", configPath, terminal.Style(fmt.Sprint(config), color.Faint))
err = config.SaveTo(configPath)
if err != nil {
return nil, err
}
// Now that the config has been recorded we reload the client with the new config
err = core.ReloadClient(ctx)
if err != nil {
return nil, err
}
successDetails := []string(nil)
// Install autocomplete
if *args.InstallAutocomplete {
_, _ = interactive.Println()
_, err := autocomplete.InstallCommandRun(ctx, &autocomplete.InstallArgs{})
if err != nil {
successDetails = append(successDetails, "Except for autocomplete: "+err.Error())
}
}
// Init SSH Key
if *args.WithSSHKey {
_, _ = interactive.Println()
_, err := iamcommands.InitWithSSHKeyRun(ctx, nil)
if err != nil {
successDetails = append(successDetails, "Except for SSH key: "+err.Error())
}
}
_, _ = interactive.Println()
return &core.SuccessResult{
Message: "Initialization completed with success",
Details: strings.Join(successDetails, "\n"),
}, nil
},
}
}
func printScalewayBanner() {
if terminal.GetWidth() >= 80 {
interactive.Printf("%s\n%s\n\n", interactive.Center(logo), interactive.Line("-"))
} else {
interactive.Printf("Welcome to the Scaleway Cli\n\n")
}
}
// loadConfigOrEmpty checks if a config exists
// Creates a new one if it does not
func loadConfigOrEmpty(configPath string) (*scw.Config, error) {
config, err := scw.LoadConfigFromPath(configPath)
if err != nil {
_, ok := err.(*scw.ConfigFileNotFoundError)
if ok {
config = &scw.Config{}
interactive.Printf("Creating new config\n")
} else {
return nil, err
}
}
return config, nil
}
// getAPIKeyDefaultProjectID tries to find the api-key default project ID
// return default project ID (organization ID) if it cannot find it
func getAPIKeyDefaultProjectID(ctx context.Context, accessKey string, secretKey string, organizationID string) string {
client := core.ExtractClient(ctx)
api := iam.NewAPI(client)
apiKey, err := api.GetAPIKey(&iam.GetAPIKeyRequest{AccessKey: accessKey}, scw.WithAuthRequest(accessKey, secretKey))
if err != nil && !is403Error(err) {
// If 403 Unauthorized, API Key does not have permissions to get himself
// It requires IAM permission to fetch an API Key
return organizationID
}
if apiKey == nil {
return organizationID
}
return apiKey.DefaultProjectID
}
// isHTTPCodeError returns true if err is an http error with code statusCode
func isHTTPCodeError(err error, statusCode int) bool {
if err == nil {
return false
}
responseError := &scw.ResponseError{}
if errors.As(err, &responseError) && responseError.StatusCode == statusCode {
return true
}
return false
}
// is403Error returns true if err is an HTTP 403 error
func is403Error(err error) bool {
permissionsDeniedError := &scw.PermissionsDeniedError{}
return isHTTPCodeError(err, http.StatusForbidden) || errors.As(err, &permissionsDeniedError)
}
const logo = `
@@@@@@@@@@@@@@@.
@@@@@@@@@@@@@@@@@@@@ __ __ _
@@@ @@@@ \ \ / / | |
@@@ @@@@@@@ .@@@ \ \ /\ / /__| | ___ ___ _ __ ___ ___
@@@ @@@@@@@@ @@@ \ \/ \/ / _ \ |/ __/ _ \| '_ ` + "`" + ` _ \ / _ \
@@@ @@@ @@@ \ /\ / __/ | (_| (_) | | | | | | __/
@@@ @@@ @@@ @@@ \/ \/ \___|_|\___\___/|_| |_| |_|\___|
@@@ @@@ @@@ @@@ _ _
@@@ @@@ @@@ | |(_)
@@@ .@@@@@@@ @@@ ___ ___ __ __ ___ | | _
@@@ @@@@@@@ @@@ / __| / __|\ \ /\ / / / __|| || |
@@@. @@@ \__ \| (__ \ V V / | (__ | || |
@@@@@@. .@@@@ |___/ \___| \_/\_/ \___||_||_|
@@@@@@@@@@@@@@@@.
`