-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathexecutor.go
More file actions
518 lines (464 loc) · 17.2 KB
/
Copy pathexecutor.go
File metadata and controls
518 lines (464 loc) · 17.2 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
507
508
509
510
511
512
513
514
515
516
517
518
package kubernetes
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
errUtils "github.com/cloudposse/atmos/errors"
e "github.com/cloudposse/atmos/internal/exec"
"github.com/cloudposse/atmos/pkg/auth"
"github.com/cloudposse/atmos/pkg/component"
cfg "github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/data"
"github.com/cloudposse/atmos/pkg/dependencies"
"github.com/cloudposse/atmos/pkg/hooks"
log "github.com/cloudposse/atmos/pkg/logger"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/schema"
tfgenerate "github.com/cloudposse/atmos/pkg/terraform/generate"
"github.com/cloudposse/atmos/pkg/ui"
u "github.com/cloudposse/atmos/pkg/utils"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
var (
initCliConfig = cfg.InitCliConfig
setupComponentAuthForCLI = e.SetupComponentAuthForCLI
processStacks = e.ProcessStacks
executeDescribeStacks = e.ExecuteDescribeStacks
executeAffectedWithRepoPath = e.ExecuteDescribeAffectedWithTargetRepoPath
executeAffectedWithRefClone = e.ExecuteDescribeAffectedWithTargetRefClone
executeAffectedWithRefCheckout = e.ExecuteDescribeAffectedWithTargetRefCheckout
executeGraph = component.ExecuteGraph
affectedKubernetesComponentsFunc = affectedKubernetesComponents
provisionAndResolveComponentPath = component.ProvisionAndResolveComponentPath
dependenciesForComponent = dependencies.ForComponent
getHooks = hooks.GetHooks
runAllHooks = func(hookSet *hooks.Hooks, event hooks.HookEvent, atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) error {
return hookSet.RunAll(event, atmosConfig, info, nil, nil)
}
runKubernetesCIHooks = hooks.RunCIHooks
runKubernetesCIHookFunc = runKubernetesCIHook
newKubernetesSDKClient = newSDKClient
)
func Execute(ctx *component.ExecutionContext, operation Operation) error {
defer perf.Track(ctx.AtmosConfig, "kubernetes.ExecuteOperation")()
info := ctx.ConfigAndStacksInfo
command := ctx.SubCommand
if command == "" {
command = string(operation)
}
info.ComponentType = cfg.KubernetesComponentType
info.SubCommand = command
info.CliArgs = []string{cfg.KubernetesComponentType, command}
atmosConfig, err := initCliConfig(info, true)
if err != nil {
return err
}
normalizeGlobalConfig(&atmosConfig)
if info.All || info.Affected || len(info.Tags) > 0 || len(info.Labels) > 0 {
return executeBulk(ctx, &atmosConfig, &info, operation)
}
if err := processStacksWithAuth(&atmosConfig, &info); err != nil {
return err
}
if !info.ComponentIsEnabled {
log.Info("Component is not enabled and skipped", "component", info.ComponentFromArg)
return nil
}
source, err := validateAndResolveComponent(&atmosConfig, &info)
if err != nil {
return err
}
if err := renderManifestInputTemplates(&atmosConfig, info.ComponentSection); err != nil {
return err
}
restoreEnv, err := prepareComponentEnvironment(&atmosConfig, &info)
if err != nil {
return err
}
defer restoreEnv()
return runWithHooks(ctx, &atmosConfig, &info, operation, source)
}
// manifestSource bundles the resolved provider and component path used to load manifests.
type manifestSource struct {
provider string
componentPath string
}
// runWithHooks runs the before/after hooks around loading manifests and executing the operation.
func runWithHooks(
ctx *component.ExecutionContext,
atmosConfig *schema.AtmosConfiguration,
info *schema.ConfigAndStacksInfo,
operation Operation,
source manifestSource,
) error {
hookSet, err := getHooks(atmosConfig, info)
if err != nil {
return err
}
before, after := eventsForCommand(info.SubCommand, operation)
if err := runAllHooks(hookSet, before, atmosConfig, info); err != nil {
runKubernetesCIHookFunc(after, ctx.Flags, atmosConfig, info, nil, err)
return err
}
objects, err := loadManifestObjects(source, info)
if err != nil {
runKubernetesCIHookFunc(after, ctx.Flags, atmosConfig, info, nil, err)
return err
}
result, err := runOperation(ctx, atmosConfig, info, operation, objects)
if err != nil {
runKubernetesCIHookFunc(after, ctx.Flags, atmosConfig, info, result, err)
return err
}
if err := runAllHooks(hookSet, after, atmosConfig, info); err != nil {
runKubernetesCIHookFunc(after, ctx.Flags, atmosConfig, info, result, err)
return err
}
runKubernetesCIHookFunc(after, ctx.Flags, atmosConfig, info, result, nil)
return nil
}
// validateAndResolveComponent validates the component and resolves its on-disk path,
// auto-generating files when configured and confirming a usable input source exists.
func validateAndResolveComponent(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (manifestSource, error) {
if err := (&ComponentProvider{}).ValidateComponent(info.ComponentSection); err != nil {
return manifestSource{}, err
}
provider := resolveProvider(atmosConfig, info.ComponentSection)
if provider != ProviderKubectl && provider != ProviderKustomize {
return manifestSource{}, fmt.Errorf("%w: provider must be %q or %q", errUtils.ErrComponentValidationFailed, ProviderKubectl, ProviderKustomize)
}
componentPath, componentPathExists, err := resolveComponentPath(atmosConfig, info)
if err != nil {
return manifestSource{}, err
}
if err := maybeAutoGenerateFiles(atmosConfig, info, componentPath); err != nil {
return manifestSource{}, err
}
if err := ensureComponentInputExists(atmosConfig, info, componentPath, componentPathExists); err != nil {
return manifestSource{}, err
}
return manifestSource{provider: provider, componentPath: componentPath}, nil
}
// ensureComponentInputExists verifies the component has a usable input source:
// an existing component directory or configured manifests/paths.
func ensureComponentInputExists(
atmosConfig *schema.AtmosConfiguration,
info *schema.ConfigAndStacksInfo,
componentPath string,
componentPathExists bool,
) error {
if !componentPathExists {
if stat, statErr := os.Stat(componentPath); statErr == nil && stat.IsDir() {
componentPathExists = true
}
}
manifestsInput, err := asAnySlice(info.ComponentSection["manifests"])
if err != nil {
return err
}
pathsInput, err := asStringSlice(info.ComponentSection["paths"])
if err != nil {
return err
}
if componentPathExists || len(manifestsInput) > 0 || len(pathsInput) > 0 {
return nil
}
basePath, _ := u.GetComponentBasePath(atmosConfig, cfg.KubernetesComponentType)
return fmt.Errorf(
"%w: '%s' points to the Kubernetes component '%s', but it does not exist in '%s'",
errUtils.ErrInvalidComponent,
info.ComponentFromArg,
info.FinalComponent,
basePath,
)
}
// loadManifestObjects loads the Kubernetes objects for the component from the
// resolved component path and configured manifest sources.
func loadManifestObjects(source manifestSource, info *schema.ConfigAndStacksInfo) ([]*unstructured.Unstructured, error) {
loader := manifestLoader{
componentPath: source.componentPath,
provider: source.provider,
}
objects, err := loader.Load(info.ComponentSection)
if err != nil {
return nil, err
}
if len(objects) == 0 {
return nil, fmt.Errorf("%w: no Kubernetes manifests found for component %q", errUtils.ErrInvalidComponent, info.ComponentFromArg)
}
return objects, nil
}
// runOperation dispatches the rendered objects to the requested Kubernetes operation.
// Apply/deploy resolves the configured provision target (cluster by default, or a
// delivery destination such as git); render/diff/delete remain cluster-local.
func runOperation(ctx *component.ExecutionContext, atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo, operation Operation, objects []*unstructured.Unstructured) (*schema.KubernetesCIResult, error) {
result := newKubernetesCIResult(info, objects)
results, err := executeKubernetesOperation(ctx, atmosConfig, info, operation, objects)
if operation == OperationValidate && err != nil && len(results) == 0 && errors.Is(err, errUtils.ErrKubernetesValidationFailed) {
results = objectsToResults("invalid", objects)
}
result.Actions = objectCIResults(results)
result.ActionCounts = countKubernetesActions(result.Actions)
return result, err
}
func executeKubernetesOperation(ctx *component.ExecutionContext, atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo, operation Operation, objects []*unstructured.Unstructured) ([]objectResult, error) {
switch operation {
case OperationRender:
options := resolveRenderOptions(ctx.Flags, info.ComponentSection)
options.AtmosConfig = atmosConfig
err := renderObjects(objects, options)
if err == nil {
return objectsToResults("rendered", objects), nil
}
return nil, err
case OperationDiff:
return runDiff(objects)
case OperationApply:
// Auto-gate apply/deploy: fail fast on structurally invalid manifests
// before contacting the cluster or delivering to a provision target.
// Component-level `validate: false` opts out explicitly.
if resolveComponentValidateEnabled(info.ComponentSection) {
if err := validateObjectsStructural(objects); err != nil {
return nil, err
}
}
return deliverApply(atmosConfig, info, ctx.Flags, objects)
case OperationDelete:
return runDelete(objects)
case OperationValidate:
if !resolveComponentValidateEnabled(info.ComponentSection) {
ui.Warningf("structural validation skipped: 'validate: false' is set for this component")
return objectsToResults("skipped", objects), nil
}
return runValidate(objects, resolveValidateOptions(ctx.Flags))
default:
return nil, fmt.Errorf("%w: %q", errUtils.ErrKubernetesUnsupportedOperation, operation)
}
}
func normalizeGlobalConfig(atmosConfig *schema.AtmosConfiguration) {
if atmosConfig.Components.Kubernetes.BasePath == "" {
atmosConfig.Components.Kubernetes.BasePath = DefaultConfig().BasePath
}
if atmosConfig.Components.Kubernetes.Provider == "" {
atmosConfig.Components.Kubernetes.Provider = DefaultConfig().Provider
}
}
func processStacksWithAuth(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) error {
var authManager auth.AuthManager
if info.Identity != "" {
var err error
authManager, err = setupComponentAuthForCLI(atmosConfig, info)
if err != nil {
return err
}
}
processedInfo, err := processStacks(atmosConfig, *info, true, true, true, nil, authManager)
if err != nil {
return err
}
*info = processedInfo
return nil
}
func resolveProvider(atmosConfig *schema.AtmosConfiguration, componentSection map[string]any) string {
if provider, ok := componentSection["provider"].(string); ok && provider != "" {
return provider
}
if atmosConfig.Components.Kubernetes.Provider != "" {
return atmosConfig.Components.Kubernetes.Provider
}
return DefaultConfig().Provider
}
func resolveComponentPath(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (string, bool, error) {
initialPath, err := u.GetComponentPath(atmosConfig, cfg.KubernetesComponentType, info.ComponentFolderPrefix, info.FinalComponent)
if err != nil {
return "", false, errors.Join(errUtils.ErrPathResolution, fmt.Errorf("component path: %w", err))
}
provisionCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
return provisionAndResolveComponentPath(provisionCtx, atmosConfig, info, cfg.KubernetesComponentType, initialPath)
}
func maybeAutoGenerateFiles(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo, componentPath string) error {
if !atmosConfig.Components.Kubernetes.AutoGenerateFiles {
return nil
}
generateSection := tfgenerate.GetGenerateSectionFromComponent(info.ComponentSection)
if generateSection == nil {
return nil
}
if err := os.MkdirAll(componentPath, dirPerm); err != nil {
return fmt.Errorf("%w: %q: %w", errUtils.ErrKubernetesComponentDir, componentPath, err)
}
templateContext := tfgenerate.BuildTemplateContext(info)
_, err := tfgenerate.GenerateFiles(generateSection, componentPath, templateContext, tfgenerate.GenerateConfig{})
return err
}
func runApply(objects []*unstructured.Unstructured) ([]objectResult, error) {
client, err := newKubernetesSDKClient()
if err != nil {
return nil, err
}
results, err := client.Apply(context.Background(), objects)
if err != nil {
return nil, err
}
printResults(results)
return results, nil
}
func runDelete(objects []*unstructured.Unstructured) ([]objectResult, error) {
client, err := newKubernetesSDKClient()
if err != nil {
return nil, err
}
results, err := client.Delete(context.Background(), objects)
if err != nil {
return nil, err
}
printResults(results)
return results, nil
}
func runDiff(objects []*unstructured.Unstructured) ([]objectResult, error) {
client, err := newKubernetesSDKClient()
if err != nil {
return nil, err
}
results, err := client.Diff(context.Background(), objects)
if err != nil {
return nil, err
}
printResults(results)
return results, nil
}
func printResults(results []objectResult) {
for _, result := range results {
line := fmt.Sprintf("%s %s", result.Action, objectResultRef(&result))
// For plan/diff, print the unified diff body beneath the action line.
// Empty for apply/delete/no-change/Secret objects. Lines with diffs
// remain data output so the diff body stays pipeable.
if result.Diff != "" {
_ = data.Writef("%s\n", line)
_ = data.Writef("%s\n", result.Diff)
continue
}
ui.Success(line)
}
}
func objectResultRef(result *objectResult) string {
if result.Namespace == "" {
return fmt.Sprintf("%s %s", result.Resource, result.Name)
}
return fmt.Sprintf("%s %s/%s", result.Resource, result.Namespace, result.Name)
}
func eventsFor(operation Operation) (hooks.HookEvent, hooks.HookEvent) {
return eventsForCommand(string(operation), operation)
}
func eventsForCommand(command string, operation Operation) (hooks.HookEvent, hooks.HookEvent) {
switch command {
case "plan":
return hooks.BeforeKubernetesPlan, hooks.AfterKubernetesPlan
case "deploy":
return hooks.BeforeKubernetesDeploy, hooks.AfterKubernetesDeploy
}
switch operation {
case OperationRender:
return hooks.BeforeKubernetesRender, hooks.AfterKubernetesRender
case OperationDiff:
return hooks.BeforeKubernetesDiff, hooks.AfterKubernetesDiff
case OperationApply:
return hooks.BeforeKubernetesApply, hooks.AfterKubernetesApply
case OperationDelete:
return hooks.BeforeKubernetesDelete, hooks.AfterKubernetesDelete
case OperationValidate:
return hooks.BeforeKubernetesValidate, hooks.AfterKubernetesValidate
default:
return hooks.HookEvent(""), hooks.HookEvent("")
}
}
func newKubernetesCIResult(info *schema.ConfigAndStacksInfo, objects []*unstructured.Unstructured) *schema.KubernetesCIResult {
result := &schema.KubernetesCIResult{
ObjectsTotal: len(objects),
ActionCounts: map[string]int{},
}
if info != nil {
result.Stack = info.Stack
result.Component = info.ComponentFromArg
result.Command = info.SubCommand
}
return result
}
func objectCIResults(results []objectResult) []schema.KubernetesObjectCIResult {
out := make([]schema.KubernetesObjectCIResult, 0, len(results))
for _, result := range results {
out = append(out, schema.KubernetesObjectCIResult{
Action: result.Action,
Resource: result.Resource,
Namespace: result.Namespace,
Name: result.Name,
Diff: result.Diff,
})
}
return out
}
func countKubernetesActions(results []schema.KubernetesObjectCIResult) map[string]int {
counts := make(map[string]int)
for _, result := range results {
counts[result.Action]++
}
return counts
}
func objectsToResults(action string, objects []*unstructured.Unstructured) []objectResult {
results := make([]objectResult, 0, len(objects))
for _, obj := range objects {
results = append(results, objectResult{
Action: action,
Resource: resourceID(obj),
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
})
}
return results
}
func runKubernetesCIHook(
event hooks.HookEvent,
flags map[string]any,
atmosConfig *schema.AtmosConfiguration,
info *schema.ConfigAndStacksInfo,
result *schema.KubernetesCIResult,
commandErr error,
) {
if result == nil {
result = newKubernetesCIResult(info, nil)
}
result.ExitCode = errUtils.GetExitCode(commandErr)
if commandErr != nil {
result.Error = commandErr.Error()
}
if err := runKubernetesCIHooks(&hooks.RunCIHooksOptions{
Event: event,
AtmosConfig: atmosConfig,
Info: info,
ForceCIMode: kubernetesCIModeEnabled(flags),
CommandError: commandErr,
ExitCode: result.ExitCode,
Aggregate: result,
}); err != nil {
log.Warn("Kubernetes CI summary skipped", "event", event, "error", err)
}
}
// kubernetesCIModeEnabled reports whether CI mode is forced for the operation:
// either via the --ci flag (threaded through ExecutionContext.Flags) or the
// standard CI environment variables. Mirrors helmCIModeEnabled.
func kubernetesCIModeEnabled(flags map[string]any) bool {
if value, ok := flags["ci"].(bool); ok && value {
return true
}
return ciEnvEnabled("ATMOS_CI") || ciEnvEnabled("CI")
}
// ciEnvEnabled reports whether a CI environment variable is set to a truthy value.
func ciEnvEnabled(key string) bool {
//nolint:forbidigo // Standard CI env vars (ATMOS_CI/CI), read directly for CI auto-detection.
value := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
return value != "" && value != "false" && value != "0" && value != "no"
}