|
| 1 | +package workload |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "sync" |
| 9 | + |
| 10 | + "github.com/devantler-tech/ksail/v7/pkg/client/helm" |
| 11 | + "github.com/devantler-tech/ksail/v7/pkg/client/kustomize" |
| 12 | + "github.com/devantler-tech/ksail/v7/pkg/notify" |
| 13 | + "github.com/devantler-tech/ksail/v7/pkg/svc/fluxsubst" |
| 14 | + "github.com/devantler-tech/ksail/v7/pkg/svc/gitops/render" |
| 15 | + "github.com/spf13/cobra" |
| 16 | +) |
| 17 | + |
| 18 | +// renderedManifestPerm is the permission for the rendered manifests file written |
| 19 | +// to the scan temp directory. |
| 20 | +const renderedManifestPerm = 0o600 |
| 21 | + |
| 22 | +// gitopsRenderer expands a kustomization directory into the manifests Flux |
| 23 | +// actually applies: Kustomize build, Flux variable substitution, then in-process |
| 24 | +// Helm rendering of HelmReleases. It is shared by the validate and scan commands. |
| 25 | +type gitopsRenderer struct { |
| 26 | + kustomize *kustomize.Client |
| 27 | +} |
| 28 | + |
| 29 | +// newGitOpsRenderer constructs a renderer. The kustomize client is stateless and |
| 30 | +// safe to share across goroutines; the Helm template client is created per |
| 31 | +// kustomization in expand (see below). |
| 32 | +func newGitOpsRenderer() *gitopsRenderer { |
| 33 | + return &gitopsRenderer{kustomize: kustomize.NewClient()} |
| 34 | +} |
| 35 | + |
| 36 | +// expand builds, substitutes, and Helm-renders one kustomization directory. The |
| 37 | +// kustomize build error is returned unwrapped so the caller's simplifyBuildError |
| 38 | +// can strip the verbose "kustomize build <path>:" prefix. |
| 39 | +// |
| 40 | +// A fresh Helm template client is created per call: helm's action.Configuration |
| 41 | +// is not safe for concurrent use, and validate renders kustomizations in |
| 42 | +// parallel, so each render must be isolated. Construction needs no cluster |
| 43 | +// access and is cheap. |
| 44 | +func (g *gitopsRenderer) expand(ctx context.Context, kustDir string) (render.Result, error) { |
| 45 | + output, err := g.kustomize.Build(ctx, kustDir) |
| 46 | + if err != nil { |
| 47 | + return render.Result{}, err //nolint:wrapcheck // caller strips the kustomize prefix |
| 48 | + } |
| 49 | + |
| 50 | + helmClient, err := helm.NewTemplateOnlyClient() |
| 51 | + if err != nil { |
| 52 | + return render.Result{}, fmt.Errorf("create helm template client: %w", err) |
| 53 | + } |
| 54 | + |
| 55 | + expanded := fluxsubst.ExpandFluxSubstitutions(output.Bytes()) |
| 56 | + |
| 57 | + result, err := render.Expand(ctx, expanded, render.Options{ |
| 58 | + Resolver: render.NewHelmChartResolver(helmClient), |
| 59 | + }) |
| 60 | + if err != nil { |
| 61 | + return render.Result{}, fmt.Errorf("expand HelmReleases: %w", err) |
| 62 | + } |
| 63 | + |
| 64 | + return result, nil |
| 65 | +} |
| 66 | + |
| 67 | +// renderToTempDir renders one kustomization directory to a fresh temp directory |
| 68 | +// and returns it together with a cleanup func, so a file-based scanner |
| 69 | +// (kubescape) can read the actually-applied manifests. Non-silent render |
| 70 | +// degradations are warned to the user. The caller must invoke cleanup (e.g. via |
| 71 | +// defer) to remove the temp directory. |
| 72 | +func (g *gitopsRenderer) renderToTempDir( |
| 73 | + ctx context.Context, |
| 74 | + cmd *cobra.Command, |
| 75 | + kustDir string, |
| 76 | +) (string, func(), error) { |
| 77 | + result, err := g.expand(ctx, kustDir) |
| 78 | + if err != nil { |
| 79 | + return "", nil, fmt.Errorf("render %q: %w", kustDir, err) |
| 80 | + } |
| 81 | + |
| 82 | + tmpDir, err := os.MkdirTemp("", "ksail-scan-*") |
| 83 | + if err != nil { |
| 84 | + return "", nil, fmt.Errorf("create scan temp dir: %w", err) |
| 85 | + } |
| 86 | + |
| 87 | + cleanup := func() { _ = os.RemoveAll(tmpDir) } |
| 88 | + |
| 89 | + manifestPath := filepath.Join(tmpDir, "manifests.yaml") |
| 90 | + |
| 91 | + err = os.WriteFile(manifestPath, result.Bytes(), renderedManifestPerm) |
| 92 | + if err != nil { |
| 93 | + cleanup() |
| 94 | + |
| 95 | + return "", nil, fmt.Errorf("write rendered manifests: %w", err) |
| 96 | + } |
| 97 | + |
| 98 | + warnDegradations(cmd, result.Degradations) |
| 99 | + |
| 100 | + return tmpDir, cleanup, nil |
| 101 | +} |
| 102 | + |
| 103 | +// degradationSink collects render degradations across parallel validation tasks |
| 104 | +// so they can be reported once after the progress group completes (emitting |
| 105 | +// mid-group would interleave with the ANSI progress display). |
| 106 | +type degradationSink struct { |
| 107 | + mu sync.Mutex |
| 108 | + list []render.Degradation |
| 109 | +} |
| 110 | + |
| 111 | +// add records degradations from one render result for later reporting. |
| 112 | +func (s *degradationSink) add(degradations []render.Degradation) { |
| 113 | + s.mu.Lock() |
| 114 | + defer s.mu.Unlock() |
| 115 | + |
| 116 | + s.list = append(s.list, degradations...) |
| 117 | +} |
| 118 | + |
| 119 | +// report warns about all collected degradations. |
| 120 | +func (s *degradationSink) report(cmd *cobra.Command) { |
| 121 | + s.mu.Lock() |
| 122 | + defer s.mu.Unlock() |
| 123 | + |
| 124 | + warnDegradations(cmd, s.list) |
| 125 | +} |
| 126 | + |
| 127 | +// warnDegradations emits a warning for each non-silent render degradation. Silent |
| 128 | +// degradations (e.g. a source object owned by a different kustomization) are |
| 129 | +// skipped to avoid noise on large repos. |
| 130 | +func warnDegradations(cmd *cobra.Command, degradations []render.Degradation) { |
| 131 | + for _, degradation := range degradations { |
| 132 | + if degradation.Silent { |
| 133 | + continue |
| 134 | + } |
| 135 | + |
| 136 | + notify.WriteMessage(notify.Message{ |
| 137 | + Type: notify.WarningType, |
| 138 | + Content: "skipped Helm render for HelmRelease %s (validating the resource as-is): %s", |
| 139 | + Args: []any{degradation.HelmRelease, degradation.Reason}, |
| 140 | + Writer: cmd.ErrOrStderr(), |
| 141 | + }) |
| 142 | + } |
| 143 | +} |
0 commit comments