forked from argoproj/argo-cd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplicationset.go
More file actions
506 lines (449 loc) · 16.4 KB
/
applicationset.go
File metadata and controls
506 lines (449 loc) · 16.4 KB
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
package commands
import (
"fmt"
"io"
"os"
"reflect"
"text/tabwriter"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
"google.golang.org/grpc/codes"
"github.com/argoproj/argo-cd/v3/cmd/argocd/commands/admin"
"github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
"github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
"github.com/argoproj/argo-cd/v3/pkg/apiclient/applicationset"
arogappsetv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v3/util/argo"
"github.com/argoproj/argo-cd/v3/util/errors"
"github.com/argoproj/argo-cd/v3/util/grpc"
argoio "github.com/argoproj/argo-cd/v3/util/io"
"github.com/argoproj/argo-cd/v3/util/templates"
)
var appSetExample = templates.Examples(`
# Get an ApplicationSet.
argocd appset get APPSETNAME
# List all the ApplicationSets
argocd appset list
# Create an ApplicationSet from a YAML stored in a file or at given URL
argocd appset create <filename or URL> (<filename or URL>...)
# Delete an ApplicationSet
argocd appset delete APPSETNAME (APPSETNAME...)
`)
// NewAppSetCommand returns a new instance of an `argocd appset` command
func NewAppSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
command := &cobra.Command{
Use: "appset",
Short: "Manage ApplicationSets",
Example: appSetExample,
Run: func(c *cobra.Command, args []string) {
c.HelpFunc()(c, args)
os.Exit(1)
},
}
command.AddCommand(NewApplicationSetGetCommand(clientOpts))
command.AddCommand(NewApplicationSetCreateCommand(clientOpts))
command.AddCommand(NewApplicationSetListCommand(clientOpts))
command.AddCommand(NewApplicationSetDeleteCommand(clientOpts))
command.AddCommand(NewApplicationSetGenerateCommand(clientOpts))
return command
}
// NewApplicationSetGetCommand returns a new instance of an `argocd appset get` command
func NewApplicationSetGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
var (
output string
showParams bool
)
command := &cobra.Command{
Use: "get APPSETNAME",
Short: "Get ApplicationSet details",
Example: templates.Examples(`
# Get ApplicationSets
argocd appset get APPSETNAME
`),
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
if len(args) == 0 {
c.HelpFunc()(c, args)
os.Exit(1)
}
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := acdClient.NewApplicationSetClientOrDie()
defer argoio.Close(conn)
appSetName, appSetNs := argo.ParseFromQualifiedName(args[0], "")
appSet, err := appIf.Get(ctx, &applicationset.ApplicationSetGetQuery{Name: appSetName, AppsetNamespace: appSetNs})
errors.CheckError(err)
switch output {
case "yaml", "json":
err := PrintResource(appSet, output)
errors.CheckError(err)
case "wide", "":
printAppSetSummaryTable(appSet)
if len(appSet.Status.Conditions) > 0 {
fmt.Println()
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
printAppSetConditions(w, appSet)
_ = w.Flush()
fmt.Println()
}
if showParams {
printHelmParams(appSet.Spec.Template.Spec.GetSource().Helm)
}
default:
errors.CheckError(fmt.Errorf("unknown output format: %s", output))
}
},
}
command.Flags().StringVarP(&output, "output", "o", "wide", "Output format. One of: json|yaml|wide")
command.Flags().BoolVar(&showParams, "show-params", false, "Show ApplicationSet parameters and overrides")
return command
}
// NewApplicationSetCreateCommand returns a new instance of an `argocd appset create` command
func NewApplicationSetCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
var output string
var upsert, dryRun bool
command := &cobra.Command{
Use: "create",
Short: "Create one or more ApplicationSets",
Example: templates.Examples(`
# Create ApplicationSets
argocd appset create <filename or URL> (<filename or URL>...)
# Dry-run AppSet creation to see what applications would be managed
argocd appset create --dry-run <filename or URL> -o json | jq -r '.status.resources[].name'
`),
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
if len(args) == 0 {
c.HelpFunc()(c, args)
os.Exit(1)
}
argocdClient := headless.NewClientOrDie(clientOpts, c)
fileURL := args[0]
appsets, err := cmdutil.ConstructApplicationSet(fileURL)
errors.CheckError(err)
if len(appsets) == 0 {
fmt.Printf("No ApplicationSets found while parsing the input file")
os.Exit(1)
}
for _, appset := range appsets {
if appset.Name == "" {
err := fmt.Errorf("Error creating ApplicationSet %s. ApplicationSet does not have Name field set", appset)
errors.CheckError(err)
}
conn, appIf := argocdClient.NewApplicationSetClientOrDie()
defer argoio.Close(conn)
// Get app before creating to see if it is being updated or no change
existing, err := appIf.Get(ctx, &applicationset.ApplicationSetGetQuery{Name: appset.Name, AppsetNamespace: appset.Namespace})
if grpc.UnwrapGRPCStatus(err).Code() != codes.NotFound {
errors.CheckError(err)
}
appSetCreateRequest := applicationset.ApplicationSetCreateRequest{
Applicationset: appset,
Upsert: upsert,
DryRun: dryRun,
}
created, err := appIf.Create(ctx, &appSetCreateRequest)
errors.CheckError(err)
dryRunMsg := ""
if dryRun {
dryRunMsg = " (dry-run)"
}
var action string
switch {
case existing == nil:
action = "created"
case !hasAppSetChanged(existing, created, upsert):
action = "unchanged"
default:
action = "updated"
}
c.PrintErrf("ApplicationSet '%s' %s%s\n", created.ObjectMeta.Name, action, dryRunMsg)
switch output {
case "yaml", "json":
err := PrintResource(created, output)
errors.CheckError(err)
case "wide", "":
printAppSetSummaryTable(created)
if len(created.Status.Conditions) > 0 {
fmt.Println()
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
printAppSetConditions(w, created)
_ = w.Flush()
fmt.Println()
}
default:
errors.CheckError(fmt.Errorf("unknown output format: %s", output))
}
}
},
}
command.Flags().BoolVar(&upsert, "upsert", false, "Allows to override ApplicationSet with the same name even if supplied ApplicationSet spec is different from existing spec")
command.Flags().BoolVar(&dryRun, "dry-run", false, "Allows to evaluate the ApplicationSet template on the server to get a preview of the applications that would be created")
command.Flags().StringVarP(&output, "output", "o", "wide", "Output format. One of: json|yaml|wide")
return command
}
// NewApplicationSetGenerateCommand returns a new instance of an `argocd appset generate` command
func NewApplicationSetGenerateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
var output string
command := &cobra.Command{
Use: "generate",
Short: "Generate apps of ApplicationSet rendered templates",
Example: templates.Examples(`
# Generate apps of ApplicationSet rendered templates
argocd appset generate <filename or URL> (<filename or URL>...)
`),
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
if len(args) == 0 {
c.HelpFunc()(c, args)
os.Exit(1)
}
argocdClient := headless.NewClientOrDie(clientOpts, c)
fileURL := args[0]
appsets, err := cmdutil.ConstructApplicationSet(fileURL)
errors.CheckError(err)
if len(appsets) != 1 {
fmt.Printf("Input file must contain one ApplicationSet")
os.Exit(1)
}
appset := appsets[0]
if appset.Name == "" {
err := fmt.Errorf("Error generating apps for ApplicationSet %s. ApplicationSet does not have Name field set", appset)
errors.CheckError(err)
}
conn, appIf := argocdClient.NewApplicationSetClientOrDie()
defer argoio.Close(conn)
req := applicationset.ApplicationSetGenerateRequest{
ApplicationSet: appset,
}
resp, err := appIf.Generate(ctx, &req)
errors.CheckError(err)
var appsList []arogappsetv1.Application
for i := range resp.Applications {
appsList = append(appsList, *resp.Applications[i])
}
switch output {
case "yaml", "json":
var resources []any
for i := range appsList {
app := appsList[i]
// backfill api version and kind because k8s client always return empty values for these fields
app.APIVersion = arogappsetv1.ApplicationSchemaGroupVersionKind.GroupVersion().String()
app.Kind = arogappsetv1.ApplicationSchemaGroupVersionKind.Kind
resources = append(resources, app)
}
cobra.CheckErr(admin.PrintResources(output, os.Stdout, resources...))
case "wide", "":
printApplicationTable(appsList, &output)
default:
errors.CheckError(fmt.Errorf("unknown output format: %s", output))
}
},
}
command.Flags().StringVarP(&output, "output", "o", "wide", "Output format. One of: json|yaml|wide")
return command
}
// NewApplicationSetListCommand returns a new instance of an `argocd appset list` command
func NewApplicationSetListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
var (
output string
selector string
projects []string
appSetNamespace string
)
command := &cobra.Command{
Use: "list",
Short: "List ApplicationSets",
Example: templates.Examples(`
# List all ApplicationSets
argocd appset list
`),
Run: func(c *cobra.Command, _ []string) {
ctx := c.Context()
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationSetClientOrDie()
defer argoio.Close(conn)
appsets, err := appIf.List(ctx, &applicationset.ApplicationSetListQuery{Selector: selector, Projects: projects, AppsetNamespace: appSetNamespace})
errors.CheckError(err)
appsetList := appsets.Items
switch output {
case "yaml", "json":
err := PrintResourceList(appsetList, output, false)
errors.CheckError(err)
case "name":
printApplicationSetNames(appsetList)
case "wide", "":
printApplicationSetTable(appsetList, &output)
default:
errors.CheckError(fmt.Errorf("unknown output format: %s", output))
}
},
}
command.Flags().StringVarP(&output, "output", "o", "wide", "Output format. One of: wide|name|json|yaml")
command.Flags().StringVarP(&selector, "selector", "l", "", "List applicationsets by label")
command.Flags().StringArrayVarP(&projects, "project", "p", []string{}, "Filter by project name")
command.Flags().StringVarP(&appSetNamespace, "appset-namespace", "N", "", "Only list applicationsets in namespace")
return command
}
// NewApplicationSetDeleteCommand returns a new instance of an `argocd appset delete` command
func NewApplicationSetDeleteCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
var noPrompt bool
command := &cobra.Command{
Use: "delete",
Short: "Delete one or more ApplicationSets",
Example: templates.Examples(`
# Delete an applicationset
argocd appset delete APPSETNAME (APPSETNAME...)
`),
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
if len(args) == 0 {
c.HelpFunc()(c, args)
os.Exit(1)
}
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationSetClientOrDie()
defer argoio.Close(conn)
var isTerminal bool = isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
numOfApps := len(args)
promptFlag := c.Flag("yes")
if promptFlag.Changed && promptFlag.Value.String() == "true" {
noPrompt = true
}
var (
confirmAll = false
confirm = false
)
// This is for backward compatibility,
// before we showed the prompts only when condition isTerminal && !noPrompt is true
promptUtil := utils.NewPrompt(isTerminal && !noPrompt)
for _, appSetQualifiedName := range args {
appSetName, appSetNs := argo.ParseFromQualifiedName(appSetQualifiedName, "")
appsetDeleteReq := applicationset.ApplicationSetDeleteRequest{
Name: appSetName,
AppsetNamespace: appSetNs,
}
messageForSingle := "Are you sure you want to delete '" + appSetQualifiedName + "' and all its Applications? [y/n] "
messageForAll := "Are you sure you want to delete '" + appSetQualifiedName + "' and all its Applications? [y/n/a] where 'a' is to delete all specified ApplicationSets and their Applications without prompting"
if !confirmAll {
confirm, confirmAll = promptUtil.ConfirmBaseOnCount(messageForSingle, messageForAll, numOfApps)
}
if confirm || confirmAll {
_, err := appIf.Delete(ctx, &appsetDeleteReq)
errors.CheckError(err)
fmt.Printf("applicationset '%s' deleted\n", appSetQualifiedName)
} else {
fmt.Println("The command to delete '" + appSetQualifiedName + "' was cancelled.")
}
}
},
}
command.Flags().BoolVarP(&noPrompt, "yes", "y", false, "Turn off prompting to confirm cascaded deletion of Application resources")
return command
}
// Print simple list of application names
func printApplicationSetNames(apps []arogappsetv1.ApplicationSet) {
for _, app := range apps {
fmt.Println(app.QualifiedName())
}
}
// Print table of application data
func printApplicationSetTable(apps []arogappsetv1.ApplicationSet, output *string) {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
var fmtStr string
headers := []any{"NAME", "PROJECT", "SYNCPOLICY", "CONDITIONS"}
if *output == "wide" {
fmtStr = "%s\t%s\t%s\t%s\t%s\t%s\t%s\n"
headers = append(headers, "REPO", "PATH", "TARGET")
} else {
fmtStr = "%s\t%s\t%s\t%s\n"
}
_, _ = fmt.Fprintf(w, fmtStr, headers...)
for _, app := range apps {
conditions := make([]arogappsetv1.ApplicationSetCondition, 0)
for _, condition := range app.Status.Conditions {
if condition.Status == arogappsetv1.ApplicationSetConditionStatusTrue {
conditions = append(conditions, condition)
}
}
vals := []any{
app.QualifiedName(),
app.Spec.Template.Spec.Project,
app.Spec.SyncPolicy,
conditions,
}
if *output == "wide" {
vals = append(vals, app.Spec.Template.Spec.GetSource().RepoURL, app.Spec.Template.Spec.GetSource().Path, app.Spec.Template.Spec.GetSource().TargetRevision)
}
_, _ = fmt.Fprintf(w, fmtStr, vals...)
}
_ = w.Flush()
}
func getServerForAppSet(appSet *arogappsetv1.ApplicationSet) string {
if appSet.Spec.Template.Spec.Destination.Server == "" {
return appSet.Spec.Template.Spec.Destination.Name
}
return appSet.Spec.Template.Spec.Destination.Server
}
func printAppSetSummaryTable(appSet *arogappsetv1.ApplicationSet) {
fmt.Printf(printOpFmtStr, "Name:", appSet.QualifiedName())
fmt.Printf(printOpFmtStr, "Project:", appSet.Spec.Template.Spec.GetProject())
fmt.Printf(printOpFmtStr, "Server:", getServerForAppSet(appSet))
fmt.Printf(printOpFmtStr, "Namespace:", appSet.Spec.Template.Spec.Destination.Namespace)
if !appSet.Spec.Template.Spec.HasMultipleSources() {
fmt.Println("Source:")
} else {
fmt.Println("Sources:")
}
// if no source has been defined, print the default value for a source
if len(appSet.Spec.Template.Spec.GetSources()) == 0 {
src := appSet.Spec.Template.Spec.GetSource()
printAppSourceDetails(&src)
} else {
// otherwise range over the sources and print each source details
for _, source := range appSet.Spec.Template.Spec.GetSources() {
printAppSourceDetails(&source)
}
}
var (
syncPolicyStr string
syncPolicy = appSet.Spec.Template.Spec.SyncPolicy
)
if syncPolicy != nil && syncPolicy.IsAutomatedSyncEnabled() {
syncPolicyStr = "Automated"
if syncPolicy.Automated.Prune {
syncPolicyStr += " (Prune)"
}
} else {
syncPolicyStr = "<none>"
}
fmt.Printf(printOpFmtStr, "SyncPolicy:", syncPolicyStr)
}
func printAppSetConditions(w io.Writer, appSet *arogappsetv1.ApplicationSet) {
_, _ = fmt.Fprintf(w, "CONDITION\tSTATUS\tMESSAGE\tLAST TRANSITION\n")
for _, item := range appSet.Status.Conditions {
_, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", item.Type, item.Status, item.Message, item.LastTransitionTime)
}
}
func hasAppSetChanged(appReq, appRes *arogappsetv1.ApplicationSet, upsert bool) bool {
// upsert==false, no change occurred from create command
if !upsert {
return false
}
// Server will return nils for empty labels, annotations, finalizers
if len(appReq.Labels) == 0 {
appReq.Labels = nil
}
if len(appReq.Annotations) == 0 {
appReq.Annotations = nil
}
if len(appReq.Finalizers) == 0 {
appReq.Finalizers = nil
}
if reflect.DeepEqual(appRes.Spec, appReq.Spec) &&
reflect.DeepEqual(appRes.Labels, appReq.Labels) &&
reflect.DeepEqual(appRes.ObjectMeta.Annotations, appReq.Annotations) &&
reflect.DeepEqual(appRes.Finalizers, appReq.Finalizers) {
return false
}
return true
}