mirror of
https://github.com/kubevela/kubevela.git
synced 2026-08-27 16:17:34 +00:00
* Docs(KEP): Go SDK for X-Definition Authoring (defkit) Introduces KEP proposal for defkit, a Go SDK that enables platform engineers to author X-Definitions using native Go code instead of CUE. Key proposed features: - Fluent builder API for Component, Trait, Policy, and WorkflowStep definitions - Transparent Go-to-CUE compilation - IDE support with autocomplete and type checking - Schema-agnostic resource construction - Collection operations (map, filter, dedupe) - Composable health and status expressions - Addon integration with godef/ folder support - Module dependencies for definition sharing via go get Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(KEP): Examples and minor api changes given in the document Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(KEP): align defkit examples - Fix golang version in CI - Fix variable declaration in example for testing - Add Is() comparison method to status check Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Docs(KEP): add security considerations section - Add goal #7 for secure code execution model - Add Security Considerations section covering: - Code execution model (compile-time only, not runtime) - Security benefits over CUE (static analysis, dependency scanning) - Threat model with mitigations Addresses PR feedback about code execution safety. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Docs(KEP): add module versioning and definition placement sections - Add Module Versioning section explaining git-based version derivation - Add Definition Placement section covering: - Motivation for placement constraints in multi-cluster environments - Fluent API for placement (RunOn, NotRunOn, label conditions) - Logical combinators (And, Or, Not) - Module-level placement defaults - Placement evaluation logic - CLI experience for managing cluster labels - Add Module Hooks section for lifecycle callbacks - Minor fixes and clarifications throughout Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Docs(KEP): add module hooks and update addon integration sections - Add Module Hooks section covering: - Use cases (CRD installation, setup scripts, post-install samples) - Hook configuration in module.yaml (pre-apply, post-apply) - Hook types (path for manifests, script for shell scripts) - waitFor field with condition names and CUE expressions - CLI usage (--skip-hooks, --dry-run) - Update Addon Integration section with implementation details: - godef/ folder structure with module.yaml - CLI flags (--godef, --components, --traits, --policies, --workflowsteps) - Conflict detection and --override-definitions flag - Development workflow Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Docs(KEP): address PR review comments and clarify placement labels - Fix misleading "Sandboxed Compilation" claim (cubic-ai feedback) - renamed to "Isolated Compilation" and clarified that security relies on trust model, not technical sandboxing - Fix inconsistent apiVersion in module hooks example (defkit.oam.dev/v1 → core.oam.dev/v1beta1) - Clarify that placement uses vela-cluster-identity ConfigMap directly, not the vela cluster labels command (which is planned for future) - Add --stats flag to apply-module CLI documentation Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Docs(KEP): fix API documentation Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add core fluent API types for Go-based definitions Introduce the defkit package providing a fluent Go API for defining KubeVela X-Definitions (components, traits, policies, workflow steps). Core types added: - types.go: Value, Condition, Param interfaces - base.go: Base definition types and interfaces - param.go: Parameter builders (String, Int, Bool, Array, Map, Struct, Enum) - expr.go: Expression builders for conditions and comparisons - resource.go: Resource operations (Set, SetIf, Spread) - context.go: KubeVela context references (appName, namespace, etc.) - test_context.go: Test utilities for definition validation This enables writing type-safe Go definitions that compile to CUE. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add collection operations and helper builders Add fluent API for array/collection transformations: - CollectionOp with Filter, Map, Pick, Wrap, Dedupe operations - From() and Each() entry points for collection pipelines - FieldRef, FieldEquals, FieldMap for field-level operations - MultiSource for complex multi-array comprehensions - Add helper builders for template variables - Add value transformation utilities Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add CUE code generator Implement CUEGenerator that transforms Go definitions into CUE code Added helper methods and writers for conversion Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add status and health policy builders Add fluent builders for customStatus and healthPolicy CUE generation Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add definition type builders Add fluent builders for all four KubeVela X-Definition types: - ComponentDefinition - TraitDefinition - PolicyDefinition - WorkflowStepDefinition Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(goloader): add Go module loader for definitions - Definition interface and registry for runtime discovery - Discover and parse Go-based definition files - Compile Go definitions to CUE at runtime - Module environment for batch processing - Parallel generation for better performance Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(cli): add vela def commands for Go-based definitions - init-module: scaffold a new Go definition module - apply-module: compile and apply definitions to cluster - list-module: show definitions in a module - validate-module: validate definitions without applying - Also support the cue commands for xdefintions for go code Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add testing utilities and matchers - CUE comparison matchers for Ginkgo/Gomega tests - Test helpers for definition validation Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add patch container helpers for container mod operations Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(cli): update the go module to 1.23.8 for defkit init-module command Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Refactor: Add grouped help output for vela def command Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add definition placement for cluster-aware deployments Enable definitions to specify which clusters they should run on based on cluster identity labels stored in a well-known ConfigMap. Also derives module version from git tags and improves init-module to create directories from --name flag. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add RunOn/NotRunOn fluent API for placement constraints Add placement methods to all definition builders allowing definitions to specify cluster eligibility using the placement package's fluent API. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Docs(defkit): add commented placement example to module.yaml template Show users the placement syntax in generated module.yaml without setting actual values. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add module-level placement support Add placement constraints at the module level in module.yaml that apply to all definitions unless overridden at definition level. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add CLI placement enforcement in apply-module Add placement constraint checking to `vela def apply-module` command. Definitions are skipped if cluster labels don't match module placement. - Add --ignore-placement flag to bypass placement checks - Display placement status during apply with clear skip reasons - Track placement-skipped count in summary output Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(defkit): show all flags in subcommand help output Fix custom help function to properly display flags for def subcommands like init-module and apply-module instead of only showing parent flags. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(defkit): apply name prefix to definitions in apply-module The --prefix flag was not being applied to definition names. The prefix was set in module loader metadata but not used when creating Kubernetes objects from parsed CUE. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Chore(defkit): align module command help with standard vela pattern Remove argument placeholders from command Use field to align with other vela commands (addon, cluster, workflow). Arguments are shown in examples and individual --help output instead of the listing. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(goloader): use json.Unmarshal for go mod download output The downloadGoModule function parses JSON output from 'go mod download -json' but was incorrectly using yaml.Unmarshal with json struct tags. The yaml.v3 library ignores json tags, resulting in empty field values. This would cause remote Go module loading (e.g., github.com/foo/bar@v1.0.0) to fail with "go mod download did not return a directory" because result.Dir would be empty. Fix: Use json.Unmarshal instead since the data is JSON from the Go toolchain. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(goloader): use semver for MinVelaVersion comparison String comparison of version numbers is incorrect for cases like "v1.10.0" > "v1.9.0" which returns false due to lexicographic ordering. Use the Masterminds/semver library (already a dependency) for proper semantic version comparison in ValidateModule(). Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(placement): validate operator in module placement conditions Add validation to catch invalid placement operators at module load time instead of silently failing at runtime evaluation. - Add Operator.IsValid() method to check for valid operators - Add ValidOperators() helper function - Add validatePlacementConditions() in ValidateModule() - Provides clear error message with valid operator list Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(cli): validate conflict strategy in apply-module Invalid --conflict values like "invalid" were silently accepted and would fall through the switch statement, behaving like "overwrite". Add ConflictStrategy.IsValid() method and validation at flag parsing to provide clear error message for invalid values. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(placement): support definition-level placement constraints Previously only module-level placement was enforced. Now individual definitions can specify their own placement constraints that override module defaults. Changes: - Add Placement field to DefinitionInfo and DefinitionPlacement types - Add GetPlacement/HasPlacement to Definition interface - Update registry ToJSON to include placement in output - Update goloader to capture definition placement from registry - Update CLI apply-module to use GetEffectivePlacement() for combining module-level and definition-level placement - Add comprehensive tests for definition placement Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Chore(defkit): remove dead PatchTemplate code PatchTemplate, PatchOp, SetPatchOp, and SetIfPatchOp were defined but never used anywhere in the codebase. The PatchResource type already provides the same functionality and is the one actually being used through Template.Patch(). Removed: - PatchTemplate struct and its methods (ToCue, SetIf, Set) - PatchOp interface - SetPatchOp struct and its ToCue method - SetIfPatchOp struct and its ToCue method - NewPatchTemplate constructor This cleanup reduces maintenance burden without affecting any functionality. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(cli): pass actual VelaVersion to validate-module command The help text for `vela def validate-module` promised to check minVelaVersion requirements but ValidateModule() was called with an empty string, causing the check to be silently skipped. Now passes velaversion.VelaVersion so modules specifying a minimum KubeVela version will be properly validated against the current CLI version. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): implement WithDetails() and FromTyped() APIs WithDetails(): - Adds WithDetails(message, details...) method to StatusBuilder - Allows adding structured key-value details alongside status messages - Uses existing StatusDetail and statusWithDetailsExpr infrastructure - Example: s.WithDetails(s.Format("Ready: %v", ...), s.Detail("endpoint", ...)) FromTyped(): - Converts typed Kubernetes objects (runtime.Object) to Resource - Provides compile-time type safety for building resources - Requires TypeMeta to be set on the object - Includes MustFromTyped() variant that panics on error - Example: defkit.FromTyped(&appsv1.Deployment{...}) Both APIs were documented in the KEP but not implemented. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Style(defkit): apply gofmt formatting Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(defkit): fix remote module download with @latest version When downloading a Go module without an explicit version, always append @latest to ensure go mod download fetches from the remote repository instead of skipping the download. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(defkit): support running def commands from any directory Previously, module commands like `vela def list-module` only worked when run from within the kubevela repository. Now they work from any directory by honoring replace directives in the source module's go.mod. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): generate doc.go files in init-module Create doc.go files with package documentation in each definition directory (components, traits, policies, workflowsteps). This ensures go mod tidy works correctly by making each directory a valid Go package, and provides helpful examples for users creating new definitions. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(defkit): deduplicate definitions from overlapping directory scans The module loader scans both conventional directories (components/, traits/, etc.) and the root directory. Since DiscoverDefinitions uses recursive filepath.Walk, files in subdirectories were found twice. Added file tracking to skip already-processed files. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(defkit): validate placement constraints and fix GOWORK interference Add validation for conflicting placement constraints at registration time. Definitions with logically impossible placement (e.g., same condition in both RunOn and NotRunOn) now fail fast with a clear error message. Also fix placement loading when parent directories contain go.work files by setting GOWORK=off when running the registry generator. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add parameter schema constraints and runtime condition methods Extend the parameter fluent API with comprehensive validation and conditional logic support: - Schema constraints for input validation (Min/Max, Pattern, MinLen/MaxLen, MinItems/MaxItems) - Runtime conditions for template logic (In, Contains, Matches, StartsWith/EndsWith, Len*, IsEmpty/IsNotEmpty, HasKey, IsFalse) Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(defkit): add waitFor support with CUE expressions for module hooks Add the ability to specify custom readiness conditions for module hooks using the new `waitFor` field. This allows users to define precise conditions for when resources should be considered ready. The waitFor field supports two formats: - Simple condition name (e.g., "Ready", "Established") - checks status.conditions for the named condition with status "True" - CUE expression (e.g., "status.replicas == status.readyReplicas") - evaluated against the full resource for flexible readiness checks Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Feat(addon): add godef support for Go-based definitions in addons Add support for a godef/ folder in addons that allows writing definitions in Go instead of CUE. When an addon is enabled, Go definitions are automatically compiled to CUE and deployed alongside traditional CUE definitions. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: lint issues and make reviewable Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: lint and build failure Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: lint and ci errors Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: golangci-lint errors for defkit package - Use standard library errors (errors.Is/As) instead of pkg/errors - Fix ineffassign issues by scoping variables correctly - Add nolint comments for intentional nilerr, makezero patterns - Combine chained appends in addon init.go - Add gosec nolint for CLI file operations and permissions - Increase gocyclo threshold to 35, nolint complex CLI commands Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: kubectl installation with retry and fallback version in github actions Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix(ci): hardcode kubectl version to avoid flaky CDN endpoint Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Chore: improve test coverage for codecov Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Chore: add more tests for codecov and CI to pass Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: ci failure on style Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: OperatorNotEquals to fail closed with empty values Change NotEquals operator to return false when Values slice is empty, matching the fail-closed behavior of Equals operator. This prevents silent widening of placement eligibility when a malformed constraint is created. Following Kubernetes label selector semantics where In/NotIn operators require non-empty values, we apply a fail-closed approach for safety in placement decisions. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: OpenArrayParam field shadowing and remove redundant GetName() Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: path traversal vulnerability in Go definition scaffolding Validate Go definition names before using them in file paths to prevent creation of files outside the addon directory. Unsanitized names could contain path traversal segments (e.g., "../../../etc/passwd") allowing arbitrary file writes. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: unescaped string interpolation in health_expr CUE generation Use %q format verb in formatValue() to properly escape quotes and special characters when generating CUE strings. Update fieldContainsExpr to use formatValue() instead of raw string interpolation. This prevents invalid CUE when substring values contain quotes or backslashes. Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: Guard against typed nil in Gomega matchers to prevent panic Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: Guard against malformed bracket path in parseBracketAccess Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: incomplete AppRevision test to actually verify resolution Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Fix: apply fail-closed behavior to NotIn with empty values Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> * Doc: Added note about RawCUE and some alignment style Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in> --------- Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>
547 lines
17 KiB
Go
547 lines
17 KiB
Go
/*
|
|
Copyright 2025 The KubeVela Authors.
|
|
|
|
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 goloader
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"cuelang.org/go/cue"
|
|
"cuelang.org/go/cue/cuecontext"
|
|
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/util/wait"
|
|
"k8s.io/apimachinery/pkg/util/yaml"
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
|
|
"github.com/oam-dev/kubevela/pkg/utils/util"
|
|
)
|
|
|
|
const (
|
|
// DefaultScriptTimeout is the default timeout for script execution
|
|
DefaultScriptTimeout = 30 * time.Second
|
|
// DefaultWaitTimeout is the default timeout for waiting on resources
|
|
DefaultWaitTimeout = 5 * time.Minute
|
|
// DefaultPollInterval is the polling interval when waiting for resources
|
|
DefaultPollInterval = 2 * time.Second
|
|
)
|
|
|
|
// HookExecutor handles the execution of module hooks
|
|
type HookExecutor struct {
|
|
// Client is the Kubernetes client for applying manifests
|
|
Client client.Client
|
|
// ModulePath is the base path of the module
|
|
ModulePath string
|
|
// Namespace is the target namespace for resources
|
|
Namespace string
|
|
// DryRun indicates whether to perform a dry run
|
|
DryRun bool
|
|
// Streams provides output streams for logging
|
|
Streams util.IOStreams
|
|
}
|
|
|
|
// HookExecutionStats contains statistics from hook execution
|
|
type HookExecutionStats struct {
|
|
// TotalDuration is the total time spent executing hooks
|
|
TotalDuration time.Duration
|
|
// HookDetails contains per-hook timing information
|
|
HookDetails []HookDetail
|
|
// ResourcesCreated is the number of resources created by path hooks
|
|
ResourcesCreated int
|
|
// ResourcesUpdated is the number of resources updated by path hooks
|
|
ResourcesUpdated int
|
|
// OptionalFailed is the number of optional hooks that failed
|
|
OptionalFailed int
|
|
}
|
|
|
|
// HookDetail contains information about a single hook execution
|
|
type HookDetail struct {
|
|
// Name is the hook name (path or script)
|
|
Name string
|
|
// Duration is how long the hook took to execute
|
|
Duration time.Duration
|
|
// Wait indicates if this hook waited for resources
|
|
Wait bool
|
|
// ResourcesCreated is resources created by this hook
|
|
ResourcesCreated int
|
|
// ResourcesUpdated is resources updated by this hook
|
|
ResourcesUpdated int
|
|
}
|
|
|
|
// NewHookExecutor creates a new HookExecutor
|
|
func NewHookExecutor(c client.Client, modulePath, namespace string, dryRun bool, streams util.IOStreams) *HookExecutor {
|
|
return &HookExecutor{
|
|
Client: c,
|
|
ModulePath: modulePath,
|
|
Namespace: namespace,
|
|
DryRun: dryRun,
|
|
Streams: streams,
|
|
}
|
|
}
|
|
|
|
// ExecuteHooks runs a list of hooks in order and returns execution statistics
|
|
func (e *HookExecutor) ExecuteHooks(ctx context.Context, phase string, hooks []Hook) (*HookExecutionStats, error) {
|
|
stats := &HookExecutionStats{}
|
|
|
|
if len(hooks) == 0 {
|
|
return stats, nil
|
|
}
|
|
|
|
totalStart := time.Now()
|
|
e.Streams.Infof("\nExecuting %s hooks...\n", phase)
|
|
|
|
for i, hook := range hooks {
|
|
hookName := fmt.Sprintf("%s[%d]", phase, i)
|
|
displayName := hook.Path
|
|
if hook.Path != "" {
|
|
hookName = fmt.Sprintf("%s: %s", hookName, hook.Path)
|
|
} else if hook.Script != "" {
|
|
hookName = fmt.Sprintf("%s: %s", hookName, hook.Script)
|
|
displayName = hook.Script
|
|
}
|
|
|
|
e.Streams.Infof(" Running %s...\n", hookName)
|
|
|
|
hookStart := time.Now()
|
|
var err error
|
|
var created, updated int
|
|
|
|
if hook.Path != "" {
|
|
created, updated, err = e.executePathHook(ctx, hook)
|
|
} else if hook.Script != "" {
|
|
err = e.executeScriptHook(ctx, hook)
|
|
}
|
|
|
|
hookDuration := time.Since(hookStart)
|
|
|
|
// Record hook detail
|
|
detail := HookDetail{
|
|
Name: displayName,
|
|
Duration: hookDuration,
|
|
Wait: hook.Wait,
|
|
ResourcesCreated: created,
|
|
ResourcesUpdated: updated,
|
|
}
|
|
stats.HookDetails = append(stats.HookDetails, detail)
|
|
stats.ResourcesCreated += created
|
|
stats.ResourcesUpdated += updated
|
|
|
|
if err != nil {
|
|
if hook.Optional {
|
|
e.Streams.Infof(" Warning: %s failed (optional): %v\n", hookName, err)
|
|
stats.OptionalFailed++
|
|
continue
|
|
}
|
|
stats.TotalDuration = time.Since(totalStart)
|
|
return stats, fmt.Errorf("hook %s failed: %w", hookName, err)
|
|
}
|
|
|
|
e.Streams.Infof(" %s completed successfully\n", hookName)
|
|
}
|
|
|
|
stats.TotalDuration = time.Since(totalStart)
|
|
e.Streams.Infof("%s hooks completed\n", phase)
|
|
return stats, nil
|
|
}
|
|
|
|
// executePathHook applies YAML manifests from a directory
|
|
// Returns the number of resources created, updated, and any error
|
|
func (e *HookExecutor) executePathHook(ctx context.Context, hook Hook) (created, updated int, err error) {
|
|
fullPath := filepath.Join(e.ModulePath, hook.Path)
|
|
|
|
// Get list of YAML files, sorted alphabetically
|
|
files, err := getYAMLFiles(fullPath)
|
|
if err != nil {
|
|
return 0, 0, fmt.Errorf("failed to list files in %s: %w", hook.Path, err)
|
|
}
|
|
|
|
if len(files) == 0 {
|
|
e.Streams.Infof(" No YAML files found in %s\n", hook.Path)
|
|
return 0, 0, nil
|
|
}
|
|
|
|
// Apply each file
|
|
var appliedObjects []*unstructured.Unstructured
|
|
for _, file := range files {
|
|
objs, fileCreated, fileUpdated, applyErr := e.applyManifestFile(ctx, file)
|
|
if applyErr != nil {
|
|
return created, updated, fmt.Errorf("failed to apply %s: %w", filepath.Base(file), applyErr)
|
|
}
|
|
appliedObjects = append(appliedObjects, objs...)
|
|
created += fileCreated
|
|
updated += fileUpdated
|
|
}
|
|
|
|
// Wait for resources if requested
|
|
if hook.Wait && !e.DryRun && len(appliedObjects) > 0 {
|
|
timeout := parseTimeout(hook.Timeout, DefaultWaitTimeout)
|
|
if waitErr := e.waitForResources(ctx, appliedObjects, timeout, hook.WaitFor); waitErr != nil {
|
|
return created, updated, fmt.Errorf("timed out waiting for resources: %w", waitErr)
|
|
}
|
|
}
|
|
|
|
return created, updated, nil
|
|
}
|
|
|
|
// executeScriptHook runs a shell script
|
|
func (e *HookExecutor) executeScriptHook(ctx context.Context, hook Hook) error {
|
|
fullPath := filepath.Join(e.ModulePath, hook.Script)
|
|
|
|
// Parse timeout
|
|
timeout := parseTimeout(hook.Timeout, DefaultScriptTimeout)
|
|
|
|
// Create context with timeout
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
|
|
if e.DryRun {
|
|
e.Streams.Infof(" [dry-run] Would execute: %s\n", hook.Script)
|
|
return nil
|
|
}
|
|
|
|
// Make script executable
|
|
if err := os.Chmod(fullPath, 0755); err != nil { //nolint:gosec // G302: 0755 required for script execution
|
|
return fmt.Errorf("failed to make script executable: %w", err)
|
|
}
|
|
|
|
// Execute the script
|
|
cmd := exec.CommandContext(ctx, fullPath) //nolint:gosec // G204: Script path is from trusted module.yaml hooks config
|
|
cmd.Dir = e.ModulePath
|
|
cmd.Env = append(os.Environ(),
|
|
fmt.Sprintf("MODULE_PATH=%s", e.ModulePath),
|
|
fmt.Sprintf("NAMESPACE=%s", e.Namespace),
|
|
)
|
|
|
|
// Capture output
|
|
var stdout, stderr bytes.Buffer
|
|
cmd.Stdout = &stdout
|
|
cmd.Stderr = &stderr
|
|
|
|
err := cmd.Run()
|
|
if err != nil {
|
|
// Include output in error message
|
|
errMsg := fmt.Sprintf("script failed: %v", err)
|
|
if stderr.Len() > 0 {
|
|
errMsg += fmt.Sprintf("\nstderr: %s", stderr.String())
|
|
}
|
|
if stdout.Len() > 0 {
|
|
errMsg += fmt.Sprintf("\nstdout: %s", stdout.String())
|
|
}
|
|
return errors.New(errMsg)
|
|
}
|
|
|
|
// Print script output
|
|
if stdout.Len() > 0 {
|
|
e.Streams.Infof(" Output: %s\n", strings.TrimSpace(stdout.String()))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// applyManifestFile reads and applies all resources from a YAML file
|
|
// Returns the applied objects, count of created resources, count of updated resources, and any error
|
|
func (e *HookExecutor) applyManifestFile(ctx context.Context, filePath string) ([]*unstructured.Unstructured, int, int, error) {
|
|
content, err := os.ReadFile(filePath) //nolint:gosec // G304: File path is from trusted module hook directory
|
|
if err != nil {
|
|
return nil, 0, 0, fmt.Errorf("failed to read file: %w", err)
|
|
}
|
|
|
|
// Parse YAML documents
|
|
reader := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(content), 4096)
|
|
var objects []*unstructured.Unstructured
|
|
var created, updated int
|
|
|
|
for {
|
|
obj := &unstructured.Unstructured{}
|
|
if err := reader.Decode(obj); err != nil {
|
|
if errors.Is(err, io.EOF) {
|
|
break
|
|
}
|
|
return nil, created, updated, fmt.Errorf("failed to decode YAML: %w", err)
|
|
}
|
|
|
|
// Skip empty documents
|
|
if len(obj.Object) == 0 {
|
|
continue
|
|
}
|
|
|
|
// Set namespace if not specified and resource is namespaced
|
|
if obj.GetNamespace() == "" && e.Namespace != "" {
|
|
// Note: We don't know if it's cluster-scoped, so we set namespace
|
|
// and let the API server reject if inappropriate
|
|
obj.SetNamespace(e.Namespace)
|
|
}
|
|
|
|
if e.DryRun {
|
|
e.Streams.Infof(" [dry-run] Would apply: %s %s/%s\n",
|
|
obj.GetKind(), obj.GetNamespace(), obj.GetName())
|
|
objects = append(objects, obj)
|
|
created++ // Count as created for dry-run purposes
|
|
continue
|
|
}
|
|
|
|
// Try to create, update if already exists
|
|
err = e.Client.Create(ctx, obj)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "already exists") {
|
|
// Get existing object and update
|
|
existing := &unstructured.Unstructured{}
|
|
existing.SetGroupVersionKind(obj.GroupVersionKind())
|
|
if getErr := e.Client.Get(ctx, client.ObjectKeyFromObject(obj), existing); getErr != nil {
|
|
return nil, created, updated, fmt.Errorf("failed to get existing %s %s: %w", obj.GetKind(), obj.GetName(), getErr)
|
|
}
|
|
obj.SetResourceVersion(existing.GetResourceVersion())
|
|
if updateErr := e.Client.Update(ctx, obj); updateErr != nil {
|
|
return nil, created, updated, fmt.Errorf("failed to update %s %s: %w", obj.GetKind(), obj.GetName(), updateErr)
|
|
}
|
|
e.Streams.Infof(" Updated %s %s/%s\n", obj.GetKind(), obj.GetNamespace(), obj.GetName())
|
|
updated++
|
|
} else {
|
|
return nil, created, updated, fmt.Errorf("failed to create %s %s: %w", obj.GetKind(), obj.GetName(), err)
|
|
}
|
|
} else {
|
|
e.Streams.Infof(" Created %s %s/%s\n", obj.GetKind(), obj.GetNamespace(), obj.GetName())
|
|
created++
|
|
}
|
|
|
|
objects = append(objects, obj)
|
|
}
|
|
|
|
return objects, created, updated, nil
|
|
}
|
|
|
|
// waitForResources waits for all applied resources to be ready
|
|
func (e *HookExecutor) waitForResources(ctx context.Context, objects []*unstructured.Unstructured, timeout time.Duration, waitFor string) error {
|
|
if waitFor != "" {
|
|
e.Streams.Infof(" Waiting for resources (condition: %s, timeout: %s)...\n", waitFor, timeout)
|
|
} else {
|
|
e.Streams.Infof(" Waiting for resources to be ready (timeout: %s)...\n", timeout)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
|
|
for _, obj := range objects {
|
|
if err := e.waitForResource(ctx, obj, waitFor); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// waitForResource waits for a single resource to be ready
|
|
func (e *HookExecutor) waitForResource(ctx context.Context, obj *unstructured.Unstructured, waitFor string) error {
|
|
key := client.ObjectKeyFromObject(obj)
|
|
gvk := obj.GroupVersionKind()
|
|
|
|
return wait.PollUntilContextCancel(ctx, DefaultPollInterval, true, func(ctx context.Context) (bool, error) {
|
|
current := &unstructured.Unstructured{}
|
|
current.SetGroupVersionKind(gvk)
|
|
if err := e.Client.Get(ctx, key, current); err != nil {
|
|
if apierrors.IsNotFound(err) {
|
|
return false, nil // Resource doesn't exist yet, keep waiting
|
|
}
|
|
return false, err // Propagate other errors
|
|
}
|
|
|
|
// If a custom waitFor expression is provided, evaluate it
|
|
if waitFor != "" {
|
|
return evaluateWaitFor(current, waitFor)
|
|
}
|
|
|
|
// Otherwise, check for common readiness conditions
|
|
ready, found := isResourceReady(current)
|
|
if found {
|
|
return ready, nil
|
|
}
|
|
|
|
// If no status, assume ready (for CRDs and similar)
|
|
return true, nil
|
|
})
|
|
}
|
|
|
|
// isResourceReady checks if a resource is ready based on its status
|
|
func isResourceReady(obj *unstructured.Unstructured) (ready bool, found bool) {
|
|
status, exists, _ := unstructured.NestedMap(obj.Object, "status")
|
|
if !exists {
|
|
return false, false
|
|
}
|
|
|
|
// Check for conditions array (common pattern)
|
|
conditions, exists, _ := unstructured.NestedSlice(status, "conditions")
|
|
if exists {
|
|
for _, c := range conditions {
|
|
cond, ok := c.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
condType, _, _ := unstructured.NestedString(cond, "type")
|
|
condStatus, _, _ := unstructured.NestedString(cond, "status")
|
|
|
|
// Check for Ready or Available conditions
|
|
if (condType == "Ready" || condType == "Available" || condType == "Established") && condStatus == "True" {
|
|
return true, true
|
|
}
|
|
}
|
|
// Found conditions but none are ready
|
|
return false, true
|
|
}
|
|
|
|
// Check for phase field (Pods, PVs, etc.)
|
|
phase, exists, _ := unstructured.NestedString(status, "phase")
|
|
if exists {
|
|
return phase == "Running" || phase == "Bound" || phase == "Active", true
|
|
}
|
|
|
|
return false, false
|
|
}
|
|
|
|
// simpleConditionPattern matches simple condition names like "Ready", "Available", "Established"
|
|
var simpleConditionPattern = regexp.MustCompile(`^[A-Z][a-zA-Z]*$`)
|
|
|
|
// evaluateWaitFor evaluates a waitFor expression against a resource.
|
|
// It supports two formats:
|
|
// 1. Simple condition name (e.g., "Ready", "Established") - checks status.conditions
|
|
// 2. CUE expression (e.g., "status.replicas == status.readyReplicas") - evaluated against the resource
|
|
func evaluateWaitFor(obj *unstructured.Unstructured, waitFor string) (bool, error) {
|
|
// Check if it's a simple condition name
|
|
if isSimpleConditionName(waitFor) {
|
|
return checkCondition(obj, waitFor)
|
|
}
|
|
|
|
// Otherwise, treat it as a CUE expression
|
|
return evaluateCUEExpression(obj, waitFor)
|
|
}
|
|
|
|
// isSimpleConditionName checks if the waitFor string is a simple condition name
|
|
func isSimpleConditionName(waitFor string) bool {
|
|
return simpleConditionPattern.MatchString(waitFor)
|
|
}
|
|
|
|
// checkCondition checks if a specific condition is True in the resource's status
|
|
func checkCondition(obj *unstructured.Unstructured, conditionName string) (bool, error) {
|
|
status, exists, _ := unstructured.NestedMap(obj.Object, "status")
|
|
if !exists {
|
|
return false, nil // Keep waiting, status not yet present
|
|
}
|
|
|
|
conditions, exists, _ := unstructured.NestedSlice(status, "conditions")
|
|
if !exists {
|
|
return false, nil // Keep waiting, conditions not yet present
|
|
}
|
|
|
|
for _, c := range conditions {
|
|
cond, ok := c.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
condType, _, _ := unstructured.NestedString(cond, "type")
|
|
condStatus, _, _ := unstructured.NestedString(cond, "status")
|
|
|
|
if condType == conditionName && condStatus == "True" {
|
|
return true, nil
|
|
}
|
|
}
|
|
|
|
return false, nil // Condition not found or not True
|
|
}
|
|
|
|
// evaluateCUEExpression evaluates a CUE expression against a resource
|
|
// The resource is available as the root context, so expressions like
|
|
// "status.replicas == status.readyReplicas" or "status.phase == \"Running\""
|
|
// can be used.
|
|
func evaluateCUEExpression(obj *unstructured.Unstructured, expr string) (bool, error) {
|
|
// Convert the unstructured object to JSON
|
|
jsonBytes, err := json.Marshal(obj.Object)
|
|
if err != nil {
|
|
return false, fmt.Errorf("failed to marshal resource to JSON: %w", err)
|
|
}
|
|
|
|
// Create CUE context and compile the resource
|
|
ctx := cuecontext.New()
|
|
resourceValue := ctx.CompileBytes(jsonBytes)
|
|
if resourceValue.Err() != nil {
|
|
return false, fmt.Errorf("failed to compile resource as CUE: %w", resourceValue.Err())
|
|
}
|
|
|
|
// Compile and evaluate the expression against the resource
|
|
// We create a CUE expression that references fields from the resource
|
|
exprValue := ctx.CompileString(expr, cue.Scope(resourceValue))
|
|
if exprValue.Err() != nil {
|
|
return false, fmt.Errorf("failed to compile waitFor expression %s: %w", expr, exprValue.Err())
|
|
}
|
|
|
|
// The expression should evaluate to a boolean
|
|
result, err := exprValue.Bool()
|
|
if err != nil {
|
|
// If it's not a boolean, check if the expression is incomplete (waiting for more data)
|
|
if exprValue.Exists() && !exprValue.IsConcrete() {
|
|
return false, nil // Keep waiting
|
|
}
|
|
return false, fmt.Errorf("waitFor expression must evaluate to boolean %s: %w", expr, err)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// getYAMLFiles returns a sorted list of YAML files in a directory
|
|
func getYAMLFiles(dir string) ([]string, error) {
|
|
entries, err := os.ReadDir(dir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var files []string
|
|
for _, entry := range entries {
|
|
if entry.IsDir() {
|
|
continue
|
|
}
|
|
name := entry.Name()
|
|
if strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml") {
|
|
files = append(files, filepath.Join(dir, name))
|
|
}
|
|
}
|
|
|
|
// Sort alphabetically for deterministic ordering
|
|
sort.Strings(files)
|
|
return files, nil
|
|
}
|
|
|
|
// parseTimeout parses a timeout string (e.g., "30s", "5m") or returns the default
|
|
func parseTimeout(timeout string, defaultTimeout time.Duration) time.Duration {
|
|
if timeout == "" {
|
|
return defaultTimeout
|
|
}
|
|
d, err := time.ParseDuration(timeout)
|
|
if err != nil {
|
|
return defaultTimeout
|
|
}
|
|
return d
|
|
}
|