-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathclivalidation.go
638 lines (532 loc) · 21.5 KB
/
clivalidation.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/*
Copyright 2023 The Radius Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cli
import (
"errors"
"fmt"
"path"
"strings"
"github.com/google/uuid"
"github.com/radius-project/radius/pkg/cli/clierrors"
"github.com/radius-project/radius/pkg/cli/cmd/commonflags"
"github.com/radius-project/radius/pkg/cli/config"
"github.com/radius-project/radius/pkg/cli/workspaces"
"github.com/radius-project/radius/pkg/ucp/resources"
resources_radius "github.com/radius-project/radius/pkg/ucp/resources/radius"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type AzureResource struct {
Name string
ResourceType string
ResourceGroup string
SubscriptionID string
}
const (
ResourceTypeFlag = "resource-type"
)
// RequireEnvironmentNameArgs checks if an environment name is provided as an argument or if a default environment is set
// in the workspace, and returns an error if neither is the case. It also handles any errors that may occur while parsing
// the environment resource.
func RequireEnvironmentNameArgs(cmd *cobra.Command, args []string, workspace workspaces.Workspace) (string, error) {
environmentName, err := ReadEnvironmentNameArgs(cmd, args)
if err != nil {
return "", err
}
// We store the environment id in config, but most commands work with the environment name.
if environmentName == "" && workspace.Environment != "" {
id, err := resources.ParseResource(workspace.Environment)
if err != nil {
return "", err
}
environmentName = id.Name()
}
if environmentName == "" {
return "", fmt.Errorf("no environment name provided and no default environment set, " +
"either pass in an environment name or set a default environment by using `rad env switch`")
}
return environmentName, err
}
// RequireEnvironmentName checks if an environment name is provided as a flag or as a default environment in the workspace,
// and returns an error if neither is present. It also handles any errors that occur while parsing the resource.
func RequireEnvironmentName(cmd *cobra.Command, args []string, workspace workspaces.Workspace) (string, error) {
environmentName, err := cmd.Flags().GetString("environment")
if err != nil {
return "", err
}
// We store the environment id in config, but most commands work with the environment name.
if environmentName == "" && workspace.Environment != "" {
id, err := resources.ParseResource(workspace.Environment)
if err != nil {
return "", err
}
environmentName = id.Name()
}
if environmentName == "" && workspace.IsEditableWorkspace() {
// Setting a default environment only applies to editable workspaces
return "", fmt.Errorf("no environment name provided and no default environment set, " +
"either pass in an environment name or set a default environment by using `rad env switch`")
} else if environmentName == "" {
return "", fmt.Errorf("no environment name provided, pass in an environment name")
}
return environmentName, err
}
// RequireEnvironmentNameOrID checks if an environment name or ID is provided as a flag or as a default environment in the workspace,
// and returns an error if neither is present. It also handles any errors that occur while parsing the resource.
func RequireEnvironmentNameOrID(cmd *cobra.Command, args []string, workspace workspaces.Workspace) (string, error) {
environmentNameOrID, err := cmd.Flags().GetString("environment")
if err != nil {
return "", err
}
// We store the environment id in config
if environmentNameOrID == "" && workspace.Environment != "" {
environmentNameOrID = workspace.Environment
}
if environmentNameOrID == "" && workspace.IsEditableWorkspace() {
// Setting a default environment only applies to editable workspaces
return "", fmt.Errorf("no environment name or ID provided and no default environment set, " +
"either pass in an environment name or ID or set a default environment by using `rad env switch`")
} else if environmentNameOrID == "" {
return "", fmt.Errorf("no environment name or ID provided, pass in an environment name or ID")
}
return environmentNameOrID, err
}
// DidSpecifyEnvironmentName checks if an environment name is provided as a flag
func DidSpecifyEnvironmentName(cmd *cobra.Command, args []string) bool {
environmentName, err := cmd.Flags().GetString("environment")
return err == nil && environmentName != "" && !strings.HasPrefix(environmentName, resources.SegmentSeparator)
}
// RequireKubeContext is used by commands that need a kubernetes context name to be specified using -c flag or has a default kubecontext
//
// RequireKubeContext checks if a kubecontext is provided as a flag, and if not, uses the current context. If neither is
// provided, it returns an error.
func RequireKubeContext(cmd *cobra.Command, currentContext string) (string, error) {
kubecontext, err := cmd.Flags().GetString("context")
if err != nil {
return "", err
}
if kubecontext == "" && currentContext == "" {
return "", errors.New("the kubeconfig has no current context")
} else if kubecontext == "" {
kubecontext = currentContext
}
return kubecontext, nil
}
// ReadEnvironmentNameArgs reads the environment name from either the command line arguments or the "-e" flag, and returns
// an error if both are specified.
func ReadEnvironmentNameArgs(cmd *cobra.Command, args []string) (string, error) {
name, err := cmd.Flags().GetString("environment")
if err != nil {
return "", err
}
if len(args) > 0 {
if name != "" {
return "", fmt.Errorf("cannot specify environment name via both arguments and `-e`")
}
name = args[0]
}
return name, err
}
// RequireApplicationArgs reads the application name from the following sources in priority order and returns
// an error if no application name is set.
//
// - '--application' flag
// - first positional arg
// - workspace default application
// - directory config application
//
// RequireApplicationArgs checks if an application name is provided as an argument, and if not, checks if a default
// application is set in the workspace. If no application name is provided, it returns an error.
func RequireApplicationArgs(cmd *cobra.Command, args []string, workspace workspaces.Workspace) (string, error) {
applicationName, err := ReadApplicationNameArgs(cmd, args)
if err != nil {
return "", err
}
if applicationName == "" {
applicationName = workspace.DirectoryConfig.Workspace.Application
}
if applicationName == "" {
return "", fmt.Errorf("no application name provided, " +
"pass in an application name with '-a/--application'")
}
return applicationName, nil
}
// ReadApplicationName reads the application name from the following sources in priority order and returns
// the empty string if no application is set.
//
// - '--application' flag
// - workspace default application
// - directory config application
//
// ReadApplicationName reads the application name from the command line flag and, if not provided, from the workspace
// configuration. It returns an error if the flag is not set correctly.
func ReadApplicationName(cmd *cobra.Command, workspace workspaces.Workspace) (string, error) {
applicationName, err := cmd.Flags().GetString("application")
if err != nil {
return "", err
}
if applicationName == "" {
applicationName = workspace.DirectoryConfig.Workspace.Application
}
return applicationName, nil
}
// ReadApplicationName reads the application name from the following sources in priority order and returns
// the empty string if no application is set.
//
// - '--application' flag
// - first positional arg
//
// ReadApplicationNameArgs reads the application name from either the command line arguments or the "-a" flag, and returns
// an error if both are specified.
func ReadApplicationNameArgs(cmd *cobra.Command, args []string) (string, error) {
name, err := cmd.Flags().GetString("application")
if err != nil {
return "", err
}
if len(args) > 0 {
if name != "" {
return "", fmt.Errorf("cannot specify application name via both arguments and `-a`")
}
name = args[0]
}
return name, err
}
// RequireApplicationArgs reads the application name from the following sources in priority order and returns
// an error if no application name is set.
//
// - '--application' flag
// - workspace default application
// - directory config application
//
// RequireApplication requires the user to provide an application name as an argument and returns it as a string. If the
// user does not provide an application name, an error is returned.
func RequireApplication(cmd *cobra.Command, workspace workspaces.Workspace) (string, error) {
return RequireApplicationArgs(cmd, []string{}, workspace)
}
// RequireResource parses the given command and arguments to extract two required values, a resource type and a resource
// name, and returns them. If either of the values is missing, an error is returned.
func RequireResource(cmd *cobra.Command, args []string) (resourceType string, resourceName string, err error) {
results, err := requiredMultiple(cmd, args, "type", "resource")
if err != nil {
return "", "", err
}
return results[0], results[1], nil
}
// RequireFullyQualifiedResourceTypeAndName checks if the provided arguments contain a resource type and name, and returns them if they
// are present. If either is missing, an error is returned.
func RequireFullyQualifiedResourceTypeAndName(args []string) (string, string, string, error) {
if len(args) < 2 {
return "", "", "", errors.New("no resource type or name provided")
}
resourceProviderName, resourceTypeName, err := RequireFullyQualifiedResourceType(args)
if err != nil {
return "", "", "", err
}
resourceName := args[1]
return resourceProviderName, resourceTypeName, resourceName, nil
}
// RequireResourceType checks if the first argument provided is a valid resource type 'providernamespace/resourcetype' and returns it if it is. If the
// argument is not valid, an error is returned.
//
// Example of resource Type: Applications.Datastores/redisCaches
func RequireResourceType(args []string) (string, error) {
if len(args) < 1 {
return "", errors.New("no resource type provided")
}
resourceTypeName := args[0]
if strings.Contains(resourceTypeName, "/") {
return "", fmt.Errorf("`%s` is not a valid resource type name. Please specify the resource type name. ex: `containers`", resourceTypeName)
}
return resourceTypeName, nil
}
func RequireFullyQualifiedResourceType(args []string) (string, string, error) {
if len(args) < 1 {
return "", "", errors.New("no fully qualified resource type provided")
}
resourceTypeName := args[0]
// Allow only fully-qualified resource type.
if !strings.Contains(resourceTypeName, "/") {
return "", "", fmt.Errorf("`%s` is not a valid resource type. Please specify the fully qualified resource type in format `resource-provider/resource-type` and try again", resourceTypeName)
}
parts := strings.Split(resourceTypeName, "/")
if len(parts) != 2 {
return "", "", fmt.Errorf("'%s' is not a valid resource type. Please specify the fully qualified resource type in format `resource-provider/resource-type` and try again", resourceTypeName)
}
return parts[0], parts[1], nil
}
// "RequireAzureResource" takes in a command and a slice of strings and returns an AzureResource object and an error. It
// uses the "requiredMultiple" function to get the values of the required parameters and then creates an AzureResource
// object with those values. If any of the required parameters are missing, it returns an error.
func RequireAzureResource(cmd *cobra.Command, args []string) (azureResource AzureResource, err error) {
results, err := requiredMultiple(cmd, args, "type", "resource", "resource-group", "resource-subscription-id")
if err != nil {
return AzureResource{}, err
}
return AzureResource{
ResourceType: results[0],
Name: results[1],
ResourceGroup: results[2],
SubscriptionID: results[3],
}, nil
}
// RequireAzureSubscriptionId is used by commands that require specifying an Azure subscriptionId using a flag
func RequireAzureSubscriptionId(cmd *cobra.Command) (string, error) {
subscriptionId, err := cmd.Flags().GetString(commonflags.AzureSubscriptionIdFlag)
if err != nil {
return "", err
}
// Validate that subscriptionId is a valid GUID
if _, err := uuid.Parse(subscriptionId); err != nil {
return "", fmt.Errorf("'%s' is not a valid subscription ID", subscriptionId)
}
return subscriptionId, err
}
func RequireOutput(cmd *cobra.Command) (string, error) {
return cmd.Flags().GetString("output")
}
// RequireWorkspace is used by commands that require an existing workspace either set as the default,
// or specified using the 'workspace' flag.
//
// RequireWorkspace reads the workspace name from the command flags, retrieves the workspace from the configuration, and
// returns it, or a fallback workspace if none is found. It also handles any errors that may occur during the process.
func RequireWorkspace(cmd *cobra.Command, config *viper.Viper, dc *config.DirectoryConfig) (*workspaces.Workspace, error) {
name, err := cmd.Flags().GetString("workspace")
if err != nil {
return nil, err
}
section, err := ReadWorkspaceSection(config)
if err != nil {
return nil, err
}
ws, err := section.GetWorkspace(name)
if err != nil {
return nil, err
}
// If we get here and ws is nil then this means there's no default set (or no config).
// Lets use the fallback configuration.
if ws == nil {
ws = workspaces.MakeFallbackWorkspace()
}
if dc != nil {
ws.DirectoryConfig = *dc
}
return ws, nil
}
// RequireResourceGroupNameArgs is used by commands that require a resource group name to be specified. If no group is passed then the default workspace group is used.
func RequireResourceGroupNameArgs(cmd *cobra.Command, args []string, workspace *workspaces.Workspace) (string, error) {
var resourceGroup string
var err error
if len(args) > 0 {
resourceGroup, err = ReadResourceGroupNameArgs(cmd, args)
if err != nil {
return "", err
}
// If an argument is provided but is empty, we should return an error
if resourceGroup == "" {
return "", fmt.Errorf("resource group name is not provided or is empty ")
}
} else {
id, err := resources.ParseScope(workspace.Scope)
if err != nil {
return "", err
}
resourceGroup = id.FindScope(resources_radius.ScopeResourceGroups)
}
return resourceGroup, nil
}
// RequireUCPResourceGroup is used by commands that require specifying a UCP resource group name using flag or positional args
//
// RequireUCPResourceGroup reads the resource group name from the command line arguments and returns an error if the name
// is not provided or is empty. It also handles any errors that may occur while reading the resource group name.
func RequireUCPResourceGroup(cmd *cobra.Command, args []string) (string, error) {
group, err := ReadResourceGroupNameArgs(cmd, args)
if err != nil {
return "", err
}
if group == "" {
return "", fmt.Errorf("resource group name is not provided or is empty ")
}
return group, nil
}
// ReadResourceGroupNameArgs is used to get the resource group name that is supplied as either the first argument for group commands or using a -g flag
//
// ReadResourceGroupNameArgs reads a resource group name from either a command flag or an argument, and returns an error if
//
// both are specified.
func ReadResourceGroupNameArgs(cmd *cobra.Command, args []string) (string, error) {
name, err := cmd.Flags().GetString("group")
if err != nil {
return "", err
}
if len(args) > 0 {
if name != "" {
return "", fmt.Errorf("cannot specify resource group name via both arguments and `-g`")
}
name = args[0]
}
return name, err
}
// RequireResourceTypeNameArgs is used by commands that require specifying a type name using positional args.
//
// RequireResourceTypeNameArgs reads the resource type name from the command line arguments and returns an error if the name
// is not provided or is empty. It also handles any errors that may occur while reading the resource type name.
func RequireResourceTypeNameArgs(cmd *cobra.Command, args []string) (string, error) {
resourceType, err := ReadResourceTypeNameArgs(cmd, args)
if err != nil {
return "", err
}
if resourceType == "" {
return "", fmt.Errorf("resource type name is not provided or is empty")
}
return resourceType, nil
}
// ReadResourceTypeNameArgs is used to get the resource type name that is supplied as the first argument
func ReadResourceTypeNameArgs(cmd *cobra.Command, args []string) (string, error) {
if len(args) < 1 {
return "", errors.New("resource type name is not provided")
}
return args[0], nil
}
// RequireWorkspaceArgs is used by commands that require an existing workspace either set as the default,
// or specified as a positional arg, or specified using the 'workspace' flag.
//
// RequireWorkspaceArgs reads the workspace name from the command line arguments, retrieves the workspace from the
// configuration, and returns it. If the workspace is not found, it returns a fallback workspace. If any errors occur, it
// returns an error.
func RequireWorkspaceArgs(cmd *cobra.Command, config *viper.Viper, args []string) (*workspaces.Workspace, error) {
name, err := ReadWorkspaceNameArgs(cmd, args)
if err != nil {
return nil, err
}
section, err := ReadWorkspaceSection(config)
if err != nil {
return nil, err
}
ws, err := section.GetWorkspace(name)
if err != nil {
return nil, err
}
// If we get here and ws is nil then this means there's no default set (or no config).
// Lets use the fallback configuration.
if ws == nil {
ws = workspaces.MakeFallbackWorkspace()
}
return ws, nil
}
// ReadWorkspaceNameArgs is used to get the workspace name that is supplied as either the first argument or using a -w flag
//
// ReadWorkspaceNameArgs reads a workspace name from either a command flag or an argument, and returns an error if both are
//
// specified.
func ReadWorkspaceNameArgs(cmd *cobra.Command, args []string) (string, error) {
name, err := cmd.Flags().GetString("workspace")
if err != nil {
return "", err
}
if len(args) > 0 {
if name != "" {
return "", fmt.Errorf("cannot specify workspace name via both arguments and `-w`")
}
name = args[0]
}
return name, err
}
// ReadWorkspaceName is used to get the workspace name that is supplied using a -w flag or as second arg.
//
// ReadWorkspaceNameSecondArg checks if a workspace name is provided via a flag or as the second argument in the command,
// and returns an error if both are specified.
func ReadWorkspaceNameSecondArg(cmd *cobra.Command, args []string) (string, error) {
name, err := cmd.Flags().GetString("workspace")
if err != nil {
return "", err
}
if len(args) > 1 {
if name != "" {
return "", fmt.Errorf("cannot specify workspace name via both arguments and `-w`")
}
name = args[1]
}
return name, err
}
// RequireRadYAML checks if a radfile flag is provided and if not, returns the default rad.yaml file in the current
// directory. If an error occurs, it is returned to the caller.
func RequireRadYAML(cmd *cobra.Command) (string, error) {
radFile, err := cmd.Flags().GetString("radfile")
if err != nil {
return "", err
}
if radFile == "" {
return path.Join(".", "rad.yaml"), nil
}
return radFile, nil
}
func requiredMultiple(cmd *cobra.Command, args []string, names ...string) ([]string, error) {
results := make([]string, len(names))
for i, name := range names {
value, err := cmd.Flags().GetString(name)
if err == nil {
results[i] = value
}
if results[i] != "" {
if len(args) > len(names)-i-1 {
return nil, fmt.Errorf("cannot specify %v name via both arguments and switch", name)
}
continue
}
if len(args) == 0 {
return nil, fmt.Errorf("no %v name provided", name)
}
results[i] = args[0]
args = args[1:]
}
return results, nil
}
// RequireScope returns the scope the command should use to execute or an error if unset.
//
// This function considers the following sources:
//
// - --group flag
// - workspace scope
//
// RequireScope checks if a resource group is passed in as a flag and returns the scope of the resource group if it is,
// otherwise it returns the scope of the workspace if it is set, otherwise it returns an error.
func RequireScope(cmd *cobra.Command, workspace workspaces.Workspace) (string, error) {
resourceGroup, err := cmd.Flags().GetString("group")
if err != nil {
return "", err
}
if resourceGroup != "" {
return fmt.Sprintf("/planes/radius/local/resourceGroups/%s", resourceGroup), nil
} else if workspace.Scope != "" {
return workspace.Scope, nil
} else {
return "", clierrors.Message("No resource group set, use `--group` to pass in a resource group name.")
}
}
// RequireRecipeNameArgs checks if the provided arguments contain at least one string, and if not, returns an error. If the
//
// arguments contain a string, it is returned.
func RequireRecipeNameArgs(cmd *cobra.Command, args []string) (string, error) {
if len(args) < 1 {
return "", errors.New("no recipe name provided")
}
return args[0], nil
}
// GetResourceType retrieves the resource type flag from the given command and returns it, or an error if the flag is not set.
func GetResourceType(cmd *cobra.Command) (string, error) {
resourceType, err := cmd.Flags().GetString(ResourceTypeFlag)
if err != nil {
return "", err
}
return resourceType, nil
}