|
| 1 | +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// Package chainsaw executes Chainsaw-style assertions against a live Kubernetes cluster. |
| 16 | +package chainsaw |
| 17 | + |
| 18 | +import ( |
| 19 | + "bytes" |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "log/slog" |
| 23 | + "os" |
| 24 | + "os/exec" |
| 25 | + "path/filepath" |
| 26 | + "sync" |
| 27 | + "text/template" |
| 28 | + "time" |
| 29 | + |
| 30 | + "github.com/NVIDIA/aicr/pkg/errors" |
| 31 | +) |
| 32 | + |
| 33 | +// ComponentAssert holds the data needed to run Chainsaw for one component. |
| 34 | +type ComponentAssert struct { |
| 35 | + // Name is the component name (e.g., "gpu-operator"). |
| 36 | + Name string |
| 37 | + |
| 38 | + // AssertYAML is the raw Chainsaw assert file content. |
| 39 | + AssertYAML string |
| 40 | +} |
| 41 | + |
| 42 | +// Result holds the outcome of a Chainsaw assertion run for one component. |
| 43 | +type Result struct { |
| 44 | + // Component is the component name. |
| 45 | + Component string |
| 46 | + |
| 47 | + // Passed indicates whether the assertion passed. |
| 48 | + Passed bool |
| 49 | + |
| 50 | + // Output contains Chainsaw stdout/stderr for diagnostics. |
| 51 | + Output string |
| 52 | + |
| 53 | + // Error contains any error from executing Chainsaw. |
| 54 | + Error error |
| 55 | +} |
| 56 | + |
| 57 | +// chainsawTestTemplate is the Chainsaw test manifest template. |
| 58 | +var chainsawTestTemplate = template.Must(template.New("chainsaw-test").Parse(`apiVersion: chainsaw.kyverno.io/v1alpha1 |
| 59 | +kind: Test |
| 60 | +metadata: |
| 61 | + name: {{ .Name }} |
| 62 | +spec: |
| 63 | + timeouts: |
| 64 | + assert: {{ .Timeout }} |
| 65 | + steps: |
| 66 | + - try: |
| 67 | + - assert: |
| 68 | + file: assert.yaml |
| 69 | +`)) |
| 70 | + |
| 71 | +// chainsawTestData holds template parameters for generating chainsaw-test.yaml. |
| 72 | +type chainsawTestData struct { |
| 73 | + Name string |
| 74 | + Timeout string |
| 75 | +} |
| 76 | + |
| 77 | +// Run executes Chainsaw assertions for a set of components. |
| 78 | +// Creates a temp directory structure and runs `chainsaw test` per component. |
| 79 | +// Components are run concurrently with bounded parallelism. |
| 80 | +func Run(ctx context.Context, asserts []ComponentAssert, timeout time.Duration) []Result { |
| 81 | + if len(asserts) == 0 { |
| 82 | + return nil |
| 83 | + } |
| 84 | + |
| 85 | + results := make([]Result, len(asserts)) |
| 86 | + |
| 87 | + var wg sync.WaitGroup |
| 88 | + // Limit concurrency to 4 parallel Chainsaw runs. |
| 89 | + sem := make(chan struct{}, 4) |
| 90 | + |
| 91 | + for i, ca := range asserts { |
| 92 | + wg.Add(1) |
| 93 | + go func() { |
| 94 | + defer wg.Done() |
| 95 | + sem <- struct{}{} |
| 96 | + defer func() { <-sem }() |
| 97 | + |
| 98 | + results[i] = runSingle(ctx, ca, timeout) |
| 99 | + }() |
| 100 | + } |
| 101 | + |
| 102 | + wg.Wait() |
| 103 | + return results |
| 104 | +} |
| 105 | + |
| 106 | +// runSingle executes Chainsaw for a single component. |
| 107 | +func runSingle(ctx context.Context, ca ComponentAssert, timeout time.Duration) Result { |
| 108 | + result := Result{Component: ca.Name} |
| 109 | + |
| 110 | + // Create temp directory for this component's test files. |
| 111 | + baseDir, err := os.MkdirTemp("", "chainsaw-run-*") |
| 112 | + if err != nil { |
| 113 | + result.Error = errors.Wrap(errors.ErrCodeInternal, "failed to create temp directory", err) |
| 114 | + return result |
| 115 | + } |
| 116 | + defer os.RemoveAll(baseDir) |
| 117 | + |
| 118 | + testDir := filepath.Join(baseDir, ca.Name) |
| 119 | + if err := os.MkdirAll(testDir, 0o750); err != nil { |
| 120 | + result.Error = errors.Wrap(errors.ErrCodeInternal, "failed to create test directory", err) |
| 121 | + return result |
| 122 | + } |
| 123 | + |
| 124 | + // Write assert.yaml. |
| 125 | + assertPath := filepath.Join(testDir, "assert.yaml") |
| 126 | + if err := os.WriteFile(assertPath, []byte(ca.AssertYAML), 0o600); err != nil { |
| 127 | + result.Error = errors.Wrap(errors.ErrCodeInternal, "failed to write assert.yaml", err) |
| 128 | + return result |
| 129 | + } |
| 130 | + |
| 131 | + // Generate chainsaw-test.yaml. |
| 132 | + testYAMLPath := filepath.Join(testDir, "chainsaw-test.yaml") |
| 133 | + if err := generateTestManifest(testYAMLPath, ca.Name, timeout); err != nil { |
| 134 | + result.Error = err |
| 135 | + return result |
| 136 | + } |
| 137 | + |
| 138 | + // Execute chainsaw test. |
| 139 | + output, execErr := execChainsaw(ctx, testDir) |
| 140 | + result.Output = output |
| 141 | + |
| 142 | + if execErr != nil { |
| 143 | + result.Passed = false |
| 144 | + result.Error = execErr |
| 145 | + slog.Warn("chainsaw health check failed", |
| 146 | + "component", ca.Name, |
| 147 | + "error", execErr) |
| 148 | + } else { |
| 149 | + result.Passed = true |
| 150 | + slog.Info("chainsaw health check passed", "component", ca.Name) |
| 151 | + } |
| 152 | + |
| 153 | + return result |
| 154 | +} |
| 155 | + |
| 156 | +// generateTestManifest writes a chainsaw-test.yaml file for the given component. |
| 157 | +func generateTestManifest(path, componentName string, timeout time.Duration) error { |
| 158 | + data := chainsawTestData{ |
| 159 | + Name: componentName, |
| 160 | + Timeout: fmt.Sprintf("%ds", int(timeout.Seconds())), |
| 161 | + } |
| 162 | + |
| 163 | + var buf bytes.Buffer |
| 164 | + if err := chainsawTestTemplate.Execute(&buf, data); err != nil { |
| 165 | + return errors.Wrap(errors.ErrCodeInternal, "failed to render chainsaw test template", err) |
| 166 | + } |
| 167 | + |
| 168 | + if err := os.WriteFile(path, buf.Bytes(), 0o600); err != nil { |
| 169 | + return errors.Wrap(errors.ErrCodeInternal, "failed to write chainsaw-test.yaml", err) |
| 170 | + } |
| 171 | + |
| 172 | + return nil |
| 173 | +} |
| 174 | + |
| 175 | +// execChainsaw runs `chainsaw test --test-dir <dir> --no-color` and returns |
| 176 | +// combined stdout+stderr output. Returns nil error on exit code 0, otherwise |
| 177 | +// wraps the exec error. |
| 178 | +func execChainsaw(ctx context.Context, testDir string) (string, error) { |
| 179 | + cmd := exec.CommandContext(ctx, "chainsaw", "test", "--test-dir", testDir, "--no-color") |
| 180 | + |
| 181 | + var combined bytes.Buffer |
| 182 | + cmd.Stdout = &combined |
| 183 | + cmd.Stderr = &combined |
| 184 | + |
| 185 | + slog.Debug("executing chainsaw", "dir", testDir, "cmd", cmd.String()) |
| 186 | + |
| 187 | + err := cmd.Run() |
| 188 | + output := combined.String() |
| 189 | + |
| 190 | + if err != nil { |
| 191 | + return output, errors.Wrap(errors.ErrCodeInternal, |
| 192 | + fmt.Sprintf("chainsaw test failed (exit code: %v)", cmd.ProcessState.ExitCode()), err) |
| 193 | + } |
| 194 | + |
| 195 | + return output, nil |
| 196 | +} |
0 commit comments