-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbase.go
More file actions
294 lines (249 loc) · 9.66 KB
/
base.go
File metadata and controls
294 lines (249 loc) · 9.66 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
// Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
//
// 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 component
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/NVIDIA/aicr/pkg/bundler/checksum"
"github.com/NVIDIA/aicr/pkg/bundler/config"
"github.com/NVIDIA/aicr/pkg/bundler/result"
"github.com/NVIDIA/aicr/pkg/bundler/types"
"github.com/NVIDIA/aicr/pkg/errors"
)
// BaseBundler provides common functionality for bundler implementations.
// Bundlers can use this to reuse standard operations and reduce boilerplate.
//
// Thread-safety: BaseBundler is safe for use by a single bundler instance.
// Do not share BaseBundler instances between concurrent bundler executions.
type BaseBundler struct {
Config *config.Config
Result *result.Result
}
// NewBaseBundler creates a new base bundler helper.
func NewBaseBundler(cfg *config.Config, bundlerType types.BundleType) *BaseBundler {
if cfg == nil {
cfg = config.NewConfig()
}
return &BaseBundler{
Config: cfg,
Result: result.New(bundlerType),
}
}
// BundleDirectories holds the standard bundle directory structure.
type BundleDirectories struct {
Root string
Scripts string
Manifests string
}
// CreateBundleDir creates the root bundle directory.
// Subdirectories (scripts, manifests) are created on-demand when files are written.
// Returns the bundle directories for easy access to each subdirectory path.
func (b *BaseBundler) CreateBundleDir(outputDir, bundleName string) (BundleDirectories, error) {
bundleDir := filepath.Join(outputDir, bundleName)
dirs := BundleDirectories{
Root: bundleDir,
Scripts: filepath.Join(bundleDir, "scripts"),
Manifests: filepath.Join(bundleDir, "manifests"),
}
// Only create the root directory. Subdirectories will be created when needed.
if err := os.MkdirAll(dirs.Root, 0755); err != nil {
return dirs, errors.Wrap(errors.ErrCodeInternal, fmt.Sprintf("failed to create directory %s", dirs.Root), err)
}
slog.Debug("bundle directory created",
"bundle", bundleName,
"root", dirs.Root,
)
return dirs, nil
}
// WriteFile writes content to a file and tracks it in the result.
// The file is created with the specified permissions and automatically
// added to the result's file list with its size.
// Parent directories are created automatically if they don't exist.
func (b *BaseBundler) WriteFile(path string, content []byte, perm os.FileMode) error {
// Ensure parent directory exists
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return errors.Wrap(errors.ErrCodeInternal, fmt.Sprintf("failed to create directory %s", dir), err)
}
if err := os.WriteFile(path, content, perm); err != nil {
return errors.Wrap(errors.ErrCodeInternal, fmt.Sprintf("failed to write %s", path), err)
}
b.Result.AddFile(path, int64(len(content)))
slog.Debug("file written",
"path", path,
"size_bytes", len(content),
"permissions", perm,
)
return nil
}
// WriteFileString writes string content to a file.
// This is a convenience wrapper around WriteFile for string content.
func (b *BaseBundler) WriteFileString(path, content string, perm os.FileMode) error {
return b.WriteFile(path, []byte(content), perm)
}
// RenderTemplate renders a template with the given data.
// The template is parsed and executed with the provided data structure.
// Returns the rendered content as a string.
func (b *BaseBundler) RenderTemplate(tmplContent, name string, data any) (string, error) {
tmpl, err := template.New(name).Parse(tmplContent)
if err != nil {
return "", errors.Wrap(errors.ErrCodeInternal, fmt.Sprintf("failed to parse template %s", name), err)
}
var buf strings.Builder
if err := tmpl.Execute(&buf, data); err != nil {
return "", errors.Wrap(errors.ErrCodeInternal, fmt.Sprintf("failed to execute template %s", name), err)
}
return buf.String(), nil
}
// RenderAndWriteTemplate renders a template and writes it to a file.
// This combines RenderTemplate and WriteFile for convenience.
func (b *BaseBundler) RenderAndWriteTemplate(tmplContent, name, outputPath string, data any, perm os.FileMode) error {
content, err := b.RenderTemplate(tmplContent, name, data)
if err != nil {
return errors.Wrap(errors.ErrCodeInternal, "failed to render template for writing", err)
}
return b.WriteFileString(outputPath, content, perm)
}
// GenerateChecksums creates a checksums.txt file for all generated files.
// The checksum file contains SHA256 hashes for verification of bundle integrity.
// Each line follows the format: "<hash> <relative-path>"
func (b *BaseBundler) GenerateChecksums(ctx context.Context, bundleDir string) error {
if err := checksum.GenerateChecksums(ctx, bundleDir, b.Result.Files); err != nil {
return errors.Wrap(errors.ErrCodeInternal, "failed to generate checksums", err)
}
// Add checksums.txt to the result files
checksumPath := checksum.GetChecksumFilePath(bundleDir)
info, err := os.Stat(checksumPath)
if err == nil {
b.Result.AddFile(checksumPath, info.Size())
}
return nil
}
// MakeExecutable changes file permissions to make a file executable.
// This is typically used for shell scripts after writing them.
func (b *BaseBundler) MakeExecutable(path string) error {
if err := os.Chmod(path, 0755); err != nil {
wrappedErr := errors.Wrap(errors.ErrCodeInternal, fmt.Sprintf("failed to make %s executable", filepath.Base(path)), err)
b.Result.AddError(wrappedErr)
return wrappedErr
}
slog.Debug("file made executable", "path", path)
return nil
}
// Finalize marks the bundler as successful and updates metrics.
// This should be called at the end of a successful bundle generation.
// It updates the result duration and marks success.
// Note: Bundlers should record their own Prometheus metrics after calling this.
func (b *BaseBundler) Finalize(start time.Time) {
b.Result.Duration = time.Since(start)
b.Result.MarkSuccess()
slog.Debug("bundle generation finalized",
"type", b.Result.Type,
"files", len(b.Result.Files),
"size_bytes", b.Result.Size,
"duration", b.Result.Duration.Round(time.Millisecond),
)
}
// CheckContext checks if the context has been canceled.
// This should be called periodically during long-running operations
// to allow for graceful cancellation.
func (b *BaseBundler) CheckContext(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return nil
}
}
// AddError adds a non-fatal error to the result.
// These errors are collected but do not stop bundle generation.
func (b *BaseBundler) AddError(err error) {
if err != nil {
b.Result.AddError(err)
slog.Warn("non-fatal error during bundle generation",
"type", b.Result.Type,
"error", err,
)
}
}
const (
//
bundlerVersionKey = "bundler_version"
recipeBundlerVersionKey = "recipe-version"
)
// GetBundlerVersion retrieves the bundler version from the config map.
func GetBundlerVersion(m map[string]string) string {
if v, ok := m[bundlerVersionKey]; ok {
return v
}
return "unknown"
}
// GetRecipeBundlerVersion retrieves the bundler version from the recipe config map.
func GetRecipeBundlerVersion(m map[string]string) string {
if v, ok := m[recipeBundlerVersionKey]; ok {
return v
}
return "unknown"
}
// buildBaseConfigMap creates a configuration map with common bundler settings.
// Returns a map containing bundler version.
// Bundlers can extend this map with their specific values.
func (b *BaseBundler) buildBaseConfigMap() map[string]string {
config := make(map[string]string)
config[bundlerVersionKey] = b.Config.Version()
return config
}
// BuildConfigMapFromInput creates a configuration map from a RecipeInput.
// This includes base config from bundler settings plus recipe version.
// Use this when working with RecipeResult (new format) instead of Recipe.
func (b *BaseBundler) BuildConfigMapFromInput(input interface{ GetVersion() string }) map[string]string {
config := b.buildBaseConfigMap()
// Add recipe version if available
if version := input.GetVersion(); version != "" {
config[recipeBundlerVersionKey] = version
}
return config
}
// TemplateFunc is a function that retrieves templates by name.
// Returns the template content and whether it was found.
type TemplateFunc func(name string) (string, bool)
// GenerateFileFromTemplate is a convenience method that combines template retrieval,
// rendering, and file writing in one call. This reduces boilerplate in bundler
// implementations by handling the common pattern of:
// 1. Get template by name
// 2. Check if template exists
// 3. Render template with data
// 4. Write rendered content to file
//
// Example usage:
//
// err := b.GenerateFileFromTemplate(ctx, GetTemplate, "values.yaml",
// filepath.Join(dir, "values.yaml"), data, 0644)
func (b *BaseBundler) GenerateFileFromTemplate(ctx context.Context, getTemplate TemplateFunc,
templateName, outputPath string, data any, perm os.FileMode) error {
if err := b.CheckContext(ctx); err != nil {
return errors.Wrap(errors.ErrCodeInternal, "context canceled before template generation", err)
}
tmpl, ok := getTemplate(templateName)
if !ok {
return errors.New(errors.ErrCodeNotFound, fmt.Sprintf("%s template not found", templateName))
}
return b.RenderAndWriteTemplate(tmpl, templateName, outputPath, data, perm)
}