Compare commits

..

70 Commits

Author SHA1 Message Date
lif
e65938087d Feat: Validate undeclared parameters in application definitions (#7075)
* Feat: Validate undeclared parameters in application definitions (#6862)

Add a new feature gate ValidateUndeclaredParameters that rejects
parameters not declared in the CUE definition schema at admission time.
When enabled, any parameter field not present in the template's parameter
stanza will cause a validation error.

Signed-off-by: majiayu000 <1835304752@qq.com>

* Fix: Handle CUE pattern constraints and improve undeclared param validation

- Detect pattern constraints ([string]: T) using LookupPath to avoid
  false positives on webservice labels/annotations fields
- Use GetSelectorLabel() for safe selector extraction
- Add klog debug logging when schema compilation fails
- Sort undeclared field names for deterministic error messages
- Add test cases for pattern constraints and sorted output

Signed-off-by: majiayu000 <1835304752@qq.com>

* Fix: go fmt alignment in validate_test.go

Signed-off-by: majiayu000 <1835304752@qq.com>

* fix: address review feedback on PR #7075

- Handle conditional parameter declarations via two-pass schema
  compilation: first without params for base fields, then with
  declared params to resolve CUE conditionals
- Return nil from findUndeclaredFields when schema.Fields() errors
  to prevent false positives from empty declared map
- Recurse into list elements containing structs using cue.AnyIndex
  so undeclared fields inside arrays are detected
- Save/restore previous feature gate state in tests instead of
  resetting to fixed values

Signed-off-by: majiayu000 <1835304752@qq.com>

---------

Signed-off-by: majiayu000 <1835304752@qq.com>
2026-03-22 12:45:02 -07:00
Jerrin Francis
124cd105d6 Chore: Updating pkg and workflow versions (#7077)
* Updating pkg and workflow version

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* Running reviewable

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* Removing accidental commit of .claude

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* Updating testdata to use new config provider

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* Updating testdata to use new config provider

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

---------

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>
2026-03-22 12:42:42 -07:00
Brian Kane
38dea0b56c feat: application-scoped policies (#7067)
Introduces application-scoped policies and global auto-applied policies
for KubeVela.

Key changes:
- PolicyDefinition gains `scope`, `global`, and `priority` fields
- Global policies (global=true, scope=Application) are auto-applied to
  every Application in their namespace (and vela-system globals apply
  cluster-wide) without being listed in spec.policies
- PolicyScopeIndex: in-memory singleton index of PolicyDefinition
  metadata, bootstrapped at startup and kept live via watch events.
  Follows KubeVela's 2-step lookup (local namespace → vela-system)
- ApplicationPolicyCache: per-app cache of rendered policy results,
  invalidated by spec hash, revision hash, or TTL; cleared on deletion
- Policy rendering pipeline extended to inject global policies before
  user-specified ones, respecting priority ordering
- Appfile.Context carries context.Context from controller into rendering
- Feature gates: EnableApplicationScopedPolicies and EnableGlobalPolicies
  (both Alpha, default false); admission webhook warns when a
  PolicyDefinition targets a disabled gate

Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-03-19 07:58:15 -07:00
Brian Kane
61e06c0bbb Feat: Immutable Parameters (#7059)
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-03-18 21:11:22 -07:00
Brian Kane
e5779ec9ec Feat: Cue 0.14.1 Preupgrade CLI Check (#6983)
* Feat: Cue 0.14.1 Preupgrade CLI Check

Signed-off-by: Brian Kane <briankane1@gmail.com>

* Feat: Add Support for Repeat Operations

Signed-off-by: Brian Kane <briankane1@gmail.com>

---------

Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-03-18 21:05:24 -07:00
Ayush Kumar
21640b55cd Refactor: sort map keys before rendering in CUE generation functions (#7073)
* Refactor: sort map keys before rendering in CUE generation functions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: add tests for alphabetical ordering of labels and outputs in CUE generation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: add tests for alphabetical ordering of computed fields and output groups in CUE generation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2026-03-18 16:00:37 +00:00
Ayush Kumar
401ad98a37 Feat: add ClosedUnion and ClosedStruct support in defkit (#7069)
* feat: add ClosedUnion and ClosedStruct support in defkit

- Introduced ClosedUnionParam and ClosedStructOption to handle closed struct disjunctions in parameters.
- Implemented methods for creating closed structs and adding fields.
- Enhanced CUE generation to support closed unions, allowing for more complex parameter definitions.
- Added tests for ClosedUnion and ClosedStruct to ensure correct functionality and integration.
- Updated existing tests to cover new features and ensure backward compatibility.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: enhance CUE generation with deduplication and inner braces for array elements

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: enhance WorkflowStep parameter handling in CUE generation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: add WithDirectFields method to BuiltinActionBuilder for direct field rendering

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: streamline string formatting in CUE generation for improved readability

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: enhance CUE generation with deduplication support and improve test assertions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: add support for ClosedUnion and condition rendering in CUE generation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* ci: retrigger checks

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: refactor value rendering in CUE generation to improve builder support

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: add GuardedBlockAction and corresponding CUE generation support

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: update writeOneOfParam and writeStructField to use marker instead of optional

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: add ClosedUnionParam support and update related tests for optionality

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: update parameter definitions to remove required constraints in example code

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: enhance CUE generation with multiline value indentation and improved block handling

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: add baseContainer definition to CUE generation for container patterns

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* fix: update test to expect _baseContainer singular field in PatchContainer output

The _baseContainer: *_|_ | {...} field was intentionally added to CUE
generation but the test was still asserting it should not exist.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* ci: retrigger checks

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2026-03-17 09:20:48 -07:00
Jerrin Francis
c6ee19ee45 Fix: remove Mandatory() API and make non-optional the default field state in defkit (#7070)
Replace the three-state field marker system (Optional/Mandatory/Required)
  with a simpler two-state system where the default behavior produces
  `field: type` (no marker), `.Required()` produces `field!: type`, and
  `.Optional()` produces `field?: type`.

  - Remove Mandatory(), IsMandatory(), ForceOptional(), IsForceOptional()
    from all param types, StructField, Param interface, and CUE generator
  - Replace `mandatory` and `forceOptional` fields with `optional` field
    in baseParam and StructField
  - Simplify CUE marker resolution to: default=none, Required="!",
    Optional="?"
  - Remove BeMandatory() matcher and mandatoryParam interface
  - Migrate all test usages: .Mandatory() removed (now default behavior),
    .ForceOptional() replaced with .Optional()

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>
2026-03-16 06:38:06 -07:00
Jerrin Francis
cf66f20cd9 Feat: introduce Mandatory() API and three-state CUE field markers in defkit (#7068)
* feat(defkit): introduce Mandatory() API and three-state CUE field markers

 Add a new .Mandatory() fluent method to all defkit param types and StructField,
 giving callers explicit control over all three CUE field presence semantics:

   field?: type   — optional, emitted by default (no method call)
   field: type    — non-optional; must have a value, defaults/merging can satisfy (.Mandatory())
   field!: type   — required in input; user must explicitly provide it (.Required())

 Previously, Required() emitted no marker (identical to a mandatory field), making
 it impossible to generate the CUE ! marker at all. Now Required() emits ! and
 Mandatory() emits no marker, matching their intuitive meanings.

 - Add `mandatory bool` field to baseParam and StructField
 - Add IsMandatory() accessor to baseParam, StructField, and Param interface
 - Add .Mandatory() builder method to all 10 concrete param types and StructField
 - Replace the `optional string` variable in cuegen.go with a typed `marker` variable
   backed by named constants (fieldMarkerOptional, fieldMarkerNone, fieldMarkerRequired)
 - Update IsOptional() to return !required && !mandatory
 - Update Optional() to clear mandatory instead of required
 - Update all tests to use .Mandatory() for non-optional fields

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* fix(defkit): correct doc comments after Required/Mandatory semantic swap

  Fix misleading comments that still described the pre-swap behaviour.
  Mandatory() comments incorrectly referenced the "!" marker, and
  Required()/IsRequired() accessors had stale descriptions. Aligned
  all doc comments and field annotations with the actual semantics:
  Required → "!" marker, Mandatory → non-optional (no ? marker).

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* feat(defkit): add BeMandatory matcher and fix BeOptional for three-state semantics

  BeOptional incorrectly returned true for mandatory params by checking
  !IsRequired(). Now uses IsOptional() which correctly excludes both
  required and mandatory params. Adds BeMandatory() matcher and updates
  paramAccessor interface with IsOptional/IsMandatory methods.

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* fix(defkit): clear required flag in Optional() for all param types

  The previous commit only fixed StringParam.Optional(). Apply the same
  fix to Int, Bool, Float, Array, Map, Struct, StructField, Enum, OneOf,
  and StringKeyMap so that Optional() consistently resets both mandatory
  and required flags across all parameter types.

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* fix(defkit): make Required() and Mandatory() mutually exclusive and fix missing optional markers in CUE generation

  Required() and Mandatory() only set their own flag without clearing
  the other, allowing both to be true simultaneously via chaining.
  Each method now clears the opposite flag so the last call wins,
  matching the reset semantics that Optional() already followed.

  Also fix CUE generation for int, bool, float, and enum params where
  the optional marker was dropped from format strings when a default
  value was present, causing those fields to always render without
  the field marker regardless of their optional/mandatory/required state.

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

* Empty commit to re-trigger e2e

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

---------

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>
2026-03-12 16:39:34 +00:00
Kelly Navarro
79d1ee7029 Fix: StateKeep: add nil-guard in dispatch path and clean up stale ResourceTracker entries for deleted apply-once resources (#7065)
* fix: address issue #7055

Signed-off-by: Kelly Navarro <gabrnavarro@users.noreply.github.com>

* chore: remove bot artifact (pr_body.md)

Signed-off-by: Kelly Navarro <gabrnavarro@users.noreply.github.com>

* fix: address review feedback (attempt 2)

Addresses review comments on #7055.

Signed-off-by: Kelly Navarro <gabrnavarro@users.noreply.github.com>

---------

Signed-off-by: Kelly Navarro <gabrnavarro@users.noreply.github.com>
Co-authored-by: gabrnavarro <gabrnavarro@users.noreply.github.com>
2026-03-10 12:51:20 -07:00
Vishal Kumar
732b49d236 Feat: defkit api completeness (#7064)
* docs: map existing codebase

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs: initialize project

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Fix: add Short() and Ignore() methods to FloatParam for API completeness

FloatParam was the only param type missing Short(string) and Ignore()
fluent methods; the underlying baseParam fields already existed. Adds
matching test cases following the existing BoolParam/IntParam pattern.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(defkit): add StatusDetails() to all 4 definition types via baseDefinition

Adds statusDetails string field to baseDefinition with setStatusDetails()
setter and GetStatusDetails() getter. Exposes StatusDetails(string) fluent
method on ComponentDefinition, TraitDefinition, WorkflowStepDefinition, and
PolicyDefinition. Updates writeStatus in cuegen.go and the inline status
render block in trait.go to render statusDetails as a #"""..."""# CUE block
alongside customStatus and healthPolicy when set.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(01-02): add ForceOptional() to IntParam, FloatParam, EnumParam

- IntParam.ForceOptional() *IntParam
- FloatParam.ForceOptional() *FloatParam
- EnumParam.ForceOptional() *EnumParam
- Test cases for all three types following BoolParam/StringParam patterns

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-01): add Labels()/GetLabels() to PolicyDefinition and fix hardcoded labels CUE

- Add labels map[string]string field to PolicyDefinition struct
- Add Labels() fluent setter and GetLabels() getter
- Replace hardcoded labels: {} in PolicyCUEGenerator with nil-conditional sorted output
- Add sort import to policy.go

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(02-01): add Ginkgo tests for PolicyDefinition.Labels

- Test store/return labels
- Test sorted key output in CUE
- Test labels block omitted when Labels() never called
- Test empty labels block when Labels called with empty map

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(02-01): complete Labels on PolicyDefinition plan

- SUMMARY.md: plan 02-01 execution results
- STATE.md: phase 2 in progress, B1 satisfied, key decisions recorded
- ROADMAP.md: phase 2 progress updated (1/3 plans)
- REQUIREMENTS.md: B1 marked complete

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): add annotations field to baseDefinition with getter/setter

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-03): wire status block rendering into WorkflowStep and Policy CUE generators

- Add status: { customStatus, healthPolicy, statusDetails } rendering to WorkflowStepCUEGenerator.GenerateTemplate
- Add same status block rendering to PolicyCUEGenerator.GenerateTemplate
- Block only emitted when at least one status field is non-empty, matching trait.go pattern

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): add Annotations() fluent method to all 4 definition types

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): conditional sorted annotations CUE block for component, trait, policy

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(02-03): add Ginkgo status block CUE render tests for WorkflowStep and Policy

- 5 new tests in WorkflowStepDefinition/Status Block CUE Render context
- 5 new tests in PolicyDefinition/Status Block CUE Render context
- Rule 3 fix: restore sort import in trait.go (used by annotations render, spuriously flagged)

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): merge user annotations before category in workflow step CUE block

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): add sorted annotations CUE block to WorkflowStepCUEGenerator

- Wire sorted user annotations rendering into WorkflowStep.GenerateFullDefinition
- Matches pattern already added to Component, Trait, and Policy generators

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): merge user annotations into metadata.annotations in ToYAML for all 4 types

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(02-03): complete Wire Status Block Rendering plan

- Add 02-03-SUMMARY.md with full execution record
- Update STATE.md: phase 2 complete, new decision recorded
- Update ROADMAP.md progress for phase 2
- Mark B4 complete in REQUIREMENTS.md

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(02-02): add Annotations Ginkgo tests for all 4 definition types

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(02-02): complete Annotations plan - SUMMARY, STATE, ROADMAP updated

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03): create phase 3 plans for missing CRD spec fields

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-01): add Version() fluent method and GetVersion() to all 4 definition types

- version string field added to baseDefinition struct
- setVersion/GetVersion methods on baseDefinition following existing pattern
- Version(string) fluent setter on TraitDefinition, ComponentDefinition, PolicyDefinition, WorkflowStepDefinition
- TDD RED+GREEN: tests for round-trip pass; CUE/YAML render tests added (fail, to be fixed in next task)

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-02): add ManageWorkload/ControlPlaneOnly/RevisionEnabled to TraitDefinition

- Add manageWorkload, controlPlaneOnly, revisionEnabled bool fields to TraitDefinition struct
- Add ManageWorkload(), ControlPlaneOnly(), RevisionEnabled() fluent setters
- Add IsManageWorkload(), IsControlPlaneOnly(), IsRevisionEnabled() getters
- Emit conditionally in ToYAML only when true; ToCue() unaffected
- Add 11 round-trip tests covering defaults, setters, and YAML emission

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(03-03): add Ginkgo tests for ChildResourceKind accumulator on ComponentDefinition

- 7 specs covering nil default, single entry, multi-entry accumulation,
  selector preservation, ToYAML emit/omit, and chaining

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-02): add ManageHealthCheck to PolicyDefinition

- Add manageHealthCheck bool field to PolicyDefinition struct
- Add ManageHealthCheck() fluent setter and IsManageHealthCheck() getter
- Emit conditionally in ToYAML only when true; ToCue() unaffected
- Add 5 round-trip tests covering default, setter, YAML emission, and chaining

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(03-03): add Ginkgo tests for PodSpecPath on ComponentDefinition

- 5 specs covering empty default, set/get round-trip, ToYAML emit/omit,
  and chaining; both fields satisfy C5 (childResourceKinds) and C6 (podSpecPath)

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-01): render version in CUE output and spec.version in ToYAML for all 4 definition types

- cuegen.go: conditional version emit in ComponentDefinition GenerateFullDefinition (after description)
- trait.go: conditional version emit in TraitCUEGenerator.GenerateFullDefinition; spec.version in ToYAML
- policy.go: conditional version emit in PolicyCUEGenerator.GenerateFullDefinition; spec.version in ToYAML
- workflow_step.go: conditional version emit in WorkflowStepCUEGenerator.GenerateFullDefinition; spec.version in ToYAML
- version omitted entirely when not set; TDD GREEN phase complete

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03-03): complete ChildResourceKind+PodSpecPath plan - SUMMARY, STATE, ROADMAP updated

- C5 (childResourceKinds accumulator) and C6 (podSpecPath) requirements satisfied
- 12 Ginkgo specs added covering both fields

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03-02): complete boolean CRD spec fields plan — manageWorkload/controlPlaneOnly/revisionEnabled/manageHealthCheck

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03-01): complete Version() plan — SUMMARY, STATE, ROADMAP updated

- 03-01-SUMMARY.md created documenting Version() on all 4 definition types
- STATE.md: 03-01 session log entry added; phase 3 marked complete; decision recorded
- ROADMAP.md: phase 3 updated to 3/3 plans executed; status Complete
- REQUIREMENTS.md: C1 marked complete

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(04): add gap closure plan 04-03 for vela-go-definitions call sites

Closes 17 ArrayOf→Of and 1 FilterPred→Filter call sites broken by the phase 04 renames.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(phase-4): low-risk renames — SetField→Set, ArrayOf→Of, FilterPred→Filter

A1: PolicyTemplate.SetField() renamed to Set()
A3: StructField.ArrayOf() renamed to Of()
A5: HelperBuilder.FilterPred(Predicate) renamed to Filter(Predicate);
    HelperBuilder.Filter(Condition) renamed to FilterCond(Condition)

All callers within defkit updated. Verification: 894 Ginkgo specs pass,
go build exits 0, zero occurrences of old names in pkg/definition/defkit/.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(05-high-impact-renames): create phase plan

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(phase-5): high-impact renames — Values→Enum, Fields→WithFields

A4: EnumParam.Values() renamed to Enum() — aligns with StringParam.Enum()
    and StructField.Enum(); 10 call sites updated in defkit tests

A2: StructParam.Fields() and OneOfVariant.Fields() renamed to WithFields()
    — aligns with ArrayParam and MapParam; ~50 call sites updated in defkit tests

Both repos build clean. go test ./pkg/definition/defkit/... passes.
Non-target .Fields() methods (InCondition, StructBuilder, ArrayElement etc.)
correctly preserved.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* chore: exclude .planning/ and .claude/ from version control

Local development artifacts only — not for upstream.

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* refactor: adjust formatting for consistency in component and policy definitions

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: add FilterCond method for filtering items by Condition expression

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: enhance filter condition handling with AND-composition for multiple filters

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: rename Enum method to Values for consistency in parameter definitions

Signed-off-by: Jerrin Francis <jfo@>

* feat: simplify labels handling in policy and trait definitions

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

---------

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>
Signed-off-by: Jerrin Francis <jfo@>
Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-10 11:28:23 +00:00
Brian Kane
9a83c932a4 Fix: update debug-webhook-setup.sh for k3d on macOS with Docker Desktop (#7060)
- Use host.docker.internal instead of bridge gateway IP on macOS, which
  is unreachable from the host when using Docker Desktop
- Make webhook port configurable via first argument (default 9445) to
  avoid conflicts with other processes

Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-03-05 15:45:08 -08:00
Ayush Kumar
6a0ac8d910 Fix: add enum generation for struct fields in CUEGenerator (#7058)
* Fix: add enum generation for struct fields in CUEGenerator

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* ci: retrigger checks

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2026-03-04 09:57:00 +00:00
Brian Kane
3c74ac68bf Fix: Allow status.details field to support dynamic keys and option to disable validation (#7056)
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-03-03 07:39:06 -08:00
Vishal Kumar
356ecffe74 Fix: Update duration format handling and enhance StringParam with enum string support (#7053)
* Fix: update duration format handling and enhance StringParam with enum string support

Signed-off-by: Anaswara Suresh M K <anaswarasuresh2212@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* date build-push-image workflow and improve image handlinggp

Signed-off-by: Anaswara Suresh M K <anaswarasuresh2212@gmail.com>

* chore: commit to re run pipeline

Signed-off-by: Anaswara Suresh M K <anaswarasuresh2212@gmail.com>

* Feat: add deduplication and field order tracking in collections and array elements

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>

* Fix: update test expectation for parameter data count in workflow step

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>

* Feat: add tests for label handling and template body in workflow steps

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>

* Feat: add tests for label handling and template body in workflow steps

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>

* Refactor: rename AllowString to OpenEnum for clarity in enum handling

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>

* Chore: format StringParam struct for improved readability

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>

---------

Signed-off-by: Anaswara Suresh M K <anaswarasuresh2212@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
2026-03-03 11:15:58 +00:00
Oana Schipor
b9a44ebfaa Fix: do not recreate externally deleted apply-once resources on reconciliation (#7051)
* skip ext deleted resources from state keep

Signed-off-by: Oana Schipor <oana.schipor@vortexa.com>

* state keep test

Signed-off-by: Oana Schipor <oana.schipor@vortexa.com>

* re-trigger CI

Signed-off-by: Oana Schipor <oana.schipor@vortexa.com>

---------

Signed-off-by: Oana Schipor <oana.schipor@vortexa.com>
2026-03-02 09:49:00 +00:00
Ayush Kumar
3f7ad2ba95 Feat: defkit comp def discrepancies (#7048)
* Feat: add MapVariant operation and support for OneOf parameters with default variant

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: enhance string parameter output to include optional prefix in CUE generation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: add ConditionalOrFieldRef for fallback handling and support inline array values

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: update CUE generation to support inline arrays with conditional wrapping

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: update CUE generation to support inline arrays with conditional wrapping

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: add support for compound optional fields and enhance array builder with guarded filtering

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: add comprehensive tests for ArrayBuilder functionality

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: implement field grouping in StatusBuilder for consolidated CUE output

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: enhance CUE decomposition to support condValues and improve filtering logic

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: add metadata labels to ComponentDefinition and update CUE generation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: clean up comments and formatting in cuegen and param files

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: enhance CUE generation, trait definitions, and PatchContainer logic

CUE Generation:
- Simplify condition decomposition logic and rename GetDirective method
- Add condition decomposition and lifting logic to improve generated CUE output
- Refactor cueTypeForParamType to use a standalone cueTypeStr function for reusability

Collections:
- Enhance MapVariant operation to merge variant mappings and preserve non-matching items

Trait Definitions:
- Enhance TraitDefinition and PatchContainerConfig with new attributes (MultiContainerCheckField, MultiContainerErrMsg)
- Update emission logic in TraitCUEGenerator for multi-container support

PatchContainer:
- Update error messages to use camelCase for consistency with KubeVela conventions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: enhance test descriptions for clarity and accuracy in array_builder, collections, and status tests

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: enhance handling of optional fields in collections and improve test descriptions for clarity

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: improve ConditionalOrFieldRef tests for clarity and accuracy in handling primary and fallback fields

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: enhance test descriptions for clarity and accuracy in array_builder and expr tests

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: improve formatting of test data in collections tests for better readability

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2026-03-01 21:29:18 -08:00
Vishal Kumar
5369aa666a Fix: reorder cue buffer construction and add test for status with import statement (#7047)
Signed-off-by: vishal210893 <vishal210893@gmail.com>
2026-02-23 08:17:14 -08:00
Ayush Kumar
4010da6765 Chore: fix trait definition translation discrepancies (#7044)
* Fix: Enhance CUE generation for optional fields in collection operations

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Feat: Add tests for optional fields and conditional logic in trait definitions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add namespace field to podAffinityTerm in affinity trait definition

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add support for ForEachMap operation in CUE generation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add tests for ForEachMap let bindings and custom rendering in trait definitions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add optional description fields for PatchContainer and enhance parameter generation logic

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Update parameter access to bracket notation in CUE generation and tests

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Implement PatchStrategyAnnotation for CUE generation and enhance condition hoisting logic

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add SpreadAll operation for array patches and enhance IntParam constraints handling

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Refactor writeSpreadAllOp to improve condition handling and element processing

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Correct nodeSelector spelling and references in affinity trait definition

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add optional namespace field to podAffinityTerm in affinity trait definition

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* test: re-trigger test pipelines

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>

* ci: retrigger checks

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>

* Fix: Update workflow API import paths to use the correct package location

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Update dependency versions in go.mod for improved compatibility

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>

* ci: retrigger checks

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add tests for SpreadAll operation and conditional handling in trait definitions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Enhance optional field handling for non-string conditions in PatchContainer

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Implement ForceOptional parameter handling to retain optionality with defaults

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Add PatchStrategy field to PatchContainerConfig and update related logic in trait definitions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Implement PatchFieldBuilder for fluent API construction of PatchContainerField

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Update test descriptions and enhance CUE generation for PatchFields with NotEmpty and IsSet conditions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
2026-02-20 14:09:11 -08:00
Vishal Kumar
3cd345c243 Fix: defkit CUE generation for task health, nested array schemas, and patch traits (#7041)
* Fix: Update JobHealth logic to reflect correct health status based on parallelism

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix: Correct formatting in status output for better readability

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix: Enhance CUE generation for nested array structs and lift shared conditions to parent nodes

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix: Improve handling of array values in CUE generation for patchKey operations

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Feat: Defkit Refactor and Clean-Up (#7042)

* feat: Enhance status and health policy CUE generation with field grouping, column alignment, `_isHealth` pattern, and annotation-based health disable.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: introduce defkit package for a structured Go API to define KubeVela component and trait templates with outputs, patches, and helpers.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Consolidate two `append` calls into one for health expression parts.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

update status.go

Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix: Correct formatting in status output for better readability

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>

# Conflicts:
#	pkg/definition/defkit/status.go
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* removed unitended commited file

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix: Preserve explicit action variable names in BuiltinAction and update CUE generation

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix: Update default WebhookConfig settings for improved configuration

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix: Enhance CUE generation with ForEachMapOp support and add alias handling in workflow steps

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>

---------

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
Co-authored-by: Ayush Kumar <65535504+roguepikachu@users.noreply.github.com>
2026-02-18 06:24:57 -08:00
Ayush Kumar
413e881e04 Feat: Defkit Refactor and Clean-Up (#7042)
* feat: Enhance status and health policy CUE generation with field grouping, column alignment, `_isHealth` pattern, and annotation-based health disable.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: introduce defkit package for a structured Go API to define KubeVela component and trait templates with outputs, patches, and helpers.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Consolidate two `append` calls into one for health expression parts.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2026-02-16 09:50:02 +00:00
Ayush Kumar
1396884a44 Feat: Implement array builder and enhance CUE generation for X-Definitions (#7039)
* feat: implement array builder and enhance CUE generation with conditional outputs

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Co-authored-by: Amit Singh <singhamitch@outlook.com>
Co-authored-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Amit Singh <singhamitch@outlook.com>

* feat: enhance CUE generation for struct fields and add support for array element types

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Amit Singh <singhamitch@outlook.com>

* feat: refactor CUE generation logic for struct fields and streamline resource output handling

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Amit Singh <singhamitch@outlook.com>
2026-02-12 14:27:56 +00:00
Anoop Gopalakrishnan
29a26d5650 Feat: Defkit implementation (#7037)
* 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>
2026-02-10 15:00:44 +00:00
Vishal Kumar
ff5f3a8fbb Feat: eager status for post dispatch (#7030)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 2m56s
* Fix: 7032 Adds component type to structured log output (#7033)

Signed-off-by: Brian Kane <briankane1@gmail.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: add pending status for traits during post dispatch processing

Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: enhance health status evaluation for workloads and traits

Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: update application health status evaluation and add workload health indicator

Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: remove required healthy field from application revisions and applications, update status structure

Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Fix: Support multiple traits of same type and improve PostDispatch handling

                                                                                               * fix: support multiple traits of the same type and improve PostDispatch handling

                                                                                               - Refactored trait status tracking in  to use a composite key (Type + Index), enabling support for multiple traits of the same type on a single component.
                                                                                               - Updated health evaluation logic in  and  to ignore traits marked as  when determining overall health.
                                                                                               - Enhanced  to refresh component status after dispatching traits, ensuring the application status reflects the latest state.
                                                                                               - Adjusted logic to correctly mark PostDispatch traits as  when the workload is not yet healthy.

Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Fix: Support multiple traits of same type and improve PostDispatch handling

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* refactor: minor reviewable changes

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* test: verifying kubebbuilder annotation

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: optimize trait status handling by removing unnecessary order tracking

Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: remove unnecessary trait dispatch stage checks to streamline status processing

Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* refactor: removes redundant changes

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: ensure health status is collected for PostDispatch traits during workflow execution

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: ensure health status is collected for PostDispatch traits during workflow execution

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>

# Conflicts:
#	pkg/controller/core.oam.dev/v1beta1/application/apply.go
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: add health status checks for PostDispatch traits in application tests

Co-authored-by: vaibhav0096 <vaibhav.agrawal0096@gmail.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: make workloadHealthy field optional in application revisions and applications

Signed-off-by: vishal210893 <vishal210893@gmail.com>

---------

Signed-off-by: Brian Kane <briankane1@gmail.com>
Signed-off-by: vaagrawal_gwre <vaagrawal@Guidewire.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
Co-authored-by: Brian Kane <briankane1@gmail.com>
Co-authored-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
2026-02-04 09:41:38 +00:00
Brian Kane
995a09d3c7 Fix: 7032 Adds component type to structured log output (#7033)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 11m56s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-01-27 09:30:58 +00:00
Brian Kane
7c06ee2060 Fix: Prevent app validation errors when traits are used alongside workflow data passing (#7031)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 51m50s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-01-23 18:03:09 +00:00
Brian Kane
37fb2a6f49 Feat: 7024 Enable custom errors in components similar to traits (#7028)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 12m42s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-01-21 10:37:07 +00:00
Brian Kane
555e4416f4 Fix: 7018 Ensure Component removals are correctly persisted and reflected in status (#7027)
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-01-21 09:26:17 +00:00
Amit Singh
5ead6db8d7 Chore: bumps up pkg and workflow dependency versions (#7026)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 1m29s
* chore: bumps up workflow and pkg versions and updates import statements

Signed-off-by: Amit Singh <singhamitch@outlook.com>

* chore: minor linter fixes

Signed-off-by: Amit Singh <singhamitch@outlook.com>

---------

Signed-off-by: Amit Singh <singhamitch@outlook.com>
2026-01-20 15:32:03 +00:00
Brian Kane
2a75dbdc35 Add a minimal, interface based provider registry to break complex import cycle (#7021)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 1m45s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-01-19 11:22:28 +00:00
Brian Kane
568b1c578b Feat: 7019 Support re-running workflows and ensure passed data is updated during dispatch (#7025)
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-01-19 11:18:10 +00:00
GoGstickGo
8c85dcdbbc Fix: Support cuex package imports in vela show/def show commands (#7017)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 2m0s
- Added GetCUExParameterValue()
 function that uses cuex.DefaultCompiler instead
    of standard CUE compiler

 - Added GetParametersWithCuex() function with cuex support
- Updated GetBaseResourceKinds() to use cuex compiler
- Updated all callers to use cuex-aware functions

 Fixes #7012

Signed-off-by: GoGstickGo <janilution@gmail.com>
2026-01-16 09:56:10 +00:00
Amit Singh
0b85d55e68 Feat: post dispatch output context (#7008)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 1m46s
* exploring context data passing

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* adds output status fetch logic

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix: standardize  import in dispatcher.

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: Allow  traits to access workload output status in CUE context

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: Implement PostDispatch traits that apply after component health is confirmed.

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: Refactor  trait handling and status propagation in application dispatch.

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix: run make reviewable

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: Implement and document PostDispatch traits, applying them after component health is confirmed and guarded by a feature flag, along with new example applications.

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: Add comments

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Fix: Restore the status field in ctx.

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Fix: Error for evaluating the status of the trait

Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* refactor: removes minor unnecessary changes

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* refactor: minor linter changes

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test: Add comprehensive tests for PostDispatch traits and their status handling

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Fix: Increase multi-cluster test time

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Chore: Add focus and print the application status

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Chore: print deployment status in the multicluster test

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Chore: add labels for the deployment

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* debugging test failure

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* debugging test failure by updating multi cluster ctx

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* undoes multi cluster ctx change

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Feat: enable MultiStageComponentApply feature by default

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Feat: implement post-dispatch traits application in workflow states

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Chore: remove unnecessary blank lines in application_controller.go

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Feat: enhance output readiness handling in health checks

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Feat: add logic to determine need for post-dispatch outputs in workload processing

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Feat: enhance output extraction and dependency checking for post-dispatch traits

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix code to exclude validation of post dispatch trait in webhook

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix code to exclude validation of post dispatch trait in webhook

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* commit for running the test again

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* commit for running the test again

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* commit for running the test again

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* triggering checks

Signed-off-by: Amit Singh <singhamitch@outlook.com>

* chore: adds explanation comments

Signed-off-by: Amit Singh <singhamitch@outlook.com>

* chore: adds errors to context

Signed-off-by: Amit Singh <singhamitch@outlook.com>

* chore: minor improvements

Signed-off-by: Amit Singh <singhamitch@outlook.com>

* fix: update output handling for pending PostDispatch traits

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix: improve output handling for PostDispatch traits in deploy process

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix: streamline output handling in PostDispatch process

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* chore: commit to re run the pipeline

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* chore: commit to re run the pipeline

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* chore: commit to re run the pipeline

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix: enhance output status handling in PostDispatch context for multi-stage support

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* chore: commit to re run the pipeline

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix: increase timeout for PostDispatch trait verification in tests

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* fix: enhance output status handling in PostDispatch context for multi-stage support

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* chore: commit to re run the pipeline

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

---------

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Chitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Vishal Kumar <vishal210893@gmail.com>
2026-01-14 10:28:13 +00:00
Brian Kane
432ffd3ddd Feat: Improve Cue Error Reporting (#6984)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 11m49s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2026-01-07 14:37:06 +00:00
Ricardo Noriega
3cc668289e Fix typos in documentation (#7015)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 2m58s
Signed-off-by: Ricardo Noriega De Soto <rnoriega@redhat.com>
2026-01-06 11:29:14 +00:00
Anoop Gopalakrishnan
e2935da549 Docs(KEP): Go SDK for X-Definition Authoring (defkit) (#7009)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 16m11s
* 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>

* Docs(KEP): add forward-reference for RawCUE() escape hatch

Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>

---------

Signed-off-by: Anoop Gopalakrishnan <anoop2811@aol.in>
2025-12-30 16:11:46 -08:00
Bryan Leong
358e46e628 Style: clean up dry-run (#7007)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 13m45s
- Remove trailing whitespace on dryrun outputs
- Fixed the relevant plugin-test outputs
- Refactor to avoid partial lines that codecov flags out

Signed-off-by: Bryan Leong <leong.bryan@gmail.com>
2025-12-16 11:18:14 +00:00
Brian Kane
bf2340bb35 Feat(KEP): Declarative Addon Support (#6996)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 17m36s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2025-11-28 16:43:06 +00:00
rahulkhinchi-wq
a459bba20e fix: dangerous-exec-command-87 (#6999)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 17m1s
Co-authored-by: root <root@ai-guardian-remediation-54f45fdc58-g5zpm>
2025-11-26 06:52:34 -08:00
Ayush Kumar
552764d48f Fix: Enhance shared resource handling to avoid last-applied-configuration pollution (#6998)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 19m3s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2025-11-26 11:08:22 +00:00
Brian Kane
9b558e38cd Feat(KEP): #6973 - Native Helm Rendering (#6974)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 16m47s
* KEP #6973 - Native Helm Rendering

Signed-off-by: Brian Kane <briankane1@gmail.com>

* KEP: #6973 - Native Helm Rendering - Minor format and spelling corrections

Signed-off-by: Brian Kane <briankane1@gmail.com>

---------

Signed-off-by: Brian Kane <briankane1@gmail.com>
2025-11-25 11:36:27 +00:00
Brian Kane
9889a0cb31 Feat(KEP): Nested Definition Rendering (Compositions) (#6993)
* Feat(KEP): Nested Definition Rendering (Compositions)

Signed-off-by: Brian Kane <briankane1@gmail.com>

* Feat(KEP) #6990 - Nested Definition Rendering (Compositions) - Minor Updates

Signed-off-by: Brian Kane <briankane1@gmail.com>

---------

Signed-off-by: Brian Kane <briankane1@gmail.com>
2025-11-25 11:35:08 +00:00
Chaitanyareddy0702
90ed704cff Refactor: update workflow-related types to use v1alpha1 API (#6975)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 17m1s
* refactor: update workflow-related types to use v1alpha1 API

- Changed the workflow mode in ApplicationBuilder from v1beta1 to v1alpha1.
- Updated WorkflowStep and WorkflowSubStep constructors to use the new v1alpha1 types.
- Modified the TypedApplication interface to reflect the new workflow mode.
- Adjusted WorkflowStepBase and WorkflowSubStepBase to utilize v1alpha1 inputs and outputs.
- Commented out unused WorkflowSubStep registration for future consideration.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: update Inputs and Outputs types to use v1alpha1 API in GoDefModifier

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: remove commented-out code for AddInput and AddOutput in genBaseSetterFunc

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: update ApplicationBuilder to use apis package for components, steps, and policies

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: remove unused WorkflowSubStep related code and update WorkflowStep reference to use v1alpha1 API

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* feat: add support for WorkflowSubStep registration and handling in GoDefModifier

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: update import path for WorkflowStepBase in GoDefModifier

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: update import path for WorkflowStep in DefinitionKindToStatement

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: update WorkflowSubStep references to use WorkflowStepBase from v1alpha1 API

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: simplify subSteps generation in GoDefModifier by directly appending WorkflowStepBase

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: nest properties under WorkflowStepBase in GoDefModifier for WorkflowStep definitions

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: remove toolchain version from go.mod

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Run: make reviewable

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* fix: enhance application auto-update test to wait for application revisions

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Signed-off-by: semmet95 <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: Amit Singh <singhamitch@outlook.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
2025-11-18 08:47:44 +00:00
Ayush Kumar
0a599ad177 Refactor: Pre-Validation Hooks to be More Extensible and Testable (#6978)
* refactor: pre-start hook implementation

- Introduced a new `hook.go` file defining the `PreStartHook` interface for pre-start validation hooks.
- Removed the old `pre_start_hook.go` file which contained the `SystemCRDValidationHook` implementation.
- Updated the server initialization code to use the new hook structure, specifically integrating the `crdvalidation` package for pre-start validation.
- Enhanced logging for pre-start hook execution to improve clarity on hook names and execution results.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: move color writer implementation to logging package and update usage in server setup

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: rename Hook to CRDValidation for clarity and consistency

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: reorder import statements for consistency

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: replace hardcoded namespace with variable in cleanup function

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: rename CRDValidation type to Hook for consistency

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: enhance CRD validation hook with custom client support and improved error handling

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: extend timeout for CRD validation hook and improve error handling for slow API servers

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: remove redundant comments from PreStartHook definition

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2025-11-17 18:14:40 -08:00
Chaitanyareddy0702
d064d3dbd2 Feat: Add configurable timeout for admission webhooks (#6977)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 23s
* Feat: Add configurable timeout for admission webhooks

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: Update admission webhook timeout configuration to use admissionWebhookTimeout variable

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* Feat: Add admission webhook timeout parameter to README

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

* removed period in readme to run pipelines

Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>

---------

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Chaitanyareddy0702 <chaitanyareddy0702@gmail.com>
Signed-off-by: Vaibhav Agrawal <vaibhav.agrawal0096@gmail.com>
2025-11-13 11:43:35 +08:00
Ayush Kumar
89ff116f8e Fix: E2E Application Test (live-diff application version) (#6976)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 27s
* refactor: Simplify application auto-update test by removing unnecessary reconciliation waits

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>

* feat: Add e2e application tests with k3d and webhook validation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* fix: Remove unnecessary blank line in application auto-update test

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: Add k3d cleanup step after running application tests

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
2025-11-11 14:24:30 +00:00
Ayush Kumar
0485704cd7 Fix: Prevent namespace admins from accessing vela-system definitions without explicit permissions (#6972)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 34s
* fix: add admission rules for applications and improve permission checks

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* test: enhance application auto-update tests with reconciliation checks

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* fix: enhance application auto-update test to verify application revision creation

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2025-11-10 08:14:41 +00:00
Amit Singh
2a31930c4b Chore: imports workflow crd from pkg repo (#6954)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 38s
* chore: adds logic to pull workflow crd from pkg repo

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: introduce GetIteratorLabel utility function and refactor label retrieval in CUE processing

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>
Co-authored-by: Vishal Kumar <vishal210893@gmail.com>

* feat: refactor FromCUE method to use GetIteratorLabel utility for improved label retrieval

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: remove unused imports and optimize list concatenation in template files

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>
Co-authored-by: Vishal Kumar <vishal210893@gmail.com>

* refactor: standardize import formatting across multiple YAML and Go files

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>
Co-authored-by: Vishal Kumar <vishal210893@gmail.com>
Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>

* refactor: import statements in multiple YAML templates for consistency

- Removed unnecessary parentheses around import statements in various CUE templates.
- Ensured a consistent import style across all templates in the vela-core chart.

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>

* feat: add disk space cleanup steps before and after cross-build in Go workflow

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>

* refactor: update check-diff target to depend on build for improved consistency

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>

* refactor: update reviewable target to include build for improved consistency in check-diff

Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Ayush <ayushshyamkumar888@gmail.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Vishal Kumar <vishal210893@gmail.com>
2025-11-06 18:56:04 -08:00
Brian Kane
8e3749f970 Fix: Fix issue with imports/packages in status validations (#6963)
Signed-off-by: Brian Kane <briankane1@gmail.com>
2025-11-06 15:23:08 -08:00
Anirudh Edpuganti
089f657b0c fix: update YAML import path to use go.yaml.in/yaml/v3 and adjust dependencies in go.mod and go.sum (#6944)
Signed-off-by: ANIRUDH-333 <aniedpuganti@gmail.com>
2025-11-06 10:37:19 +00:00
Ayush Kumar
ea409c7437 Refactor: controller setup and improve server tests (#6958)
* Feat: Add integration test setup and cleanup scripts, enhance server testing capabilities

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Refactor: Rename variables for clarity and consistency in core command handling

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Remove redundant server test targets and enhance logging in core command execution

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Refactor server tests and enhance E2E testing setup

- Updated server_test.go to improve test organization and clarity, including the addition of BeforeSuite and AfterSuite for environment setup and teardown.
- Enhanced the waitWebhookSecretVolume tests to cover various scenarios including empty directories and files.
- Added new tests for syncConfigurations and logging setup functions to ensure proper configuration handling.
- Introduced a new E2E test for the main function in main_e2e_test.go to validate the core functionality of the application.
- Improved the e2e.mk file to set up a k3d cluster for running main_e2e_test with embedded test binaries and added cleanup steps.
- Removed the setup-integration-tests.sh script as its functionality is now integrated into the Makefile.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Refactor:  improve multicluster test timeouts

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2025-11-05 10:23:24 +00:00
Vishal Kumar
5b24e8b410 Chore: Graceful skip and robust processing for missing definition directories in install script (#6964)
* Feat(script): Update installation definition script for improved error handling and namespace management

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>

* added line to rerun the github action

Signed-off-by: vishal210893 <vishal210893@gmail.com>

* minor change to rerun the github action

Signed-off-by: vishal210893 <vishal210893@gmail.com>

* Fix(script): Enhance installation script to restore original files on failure

Signed-off-by: vishal210893 <vishal210893@gmail.com>

---------

Signed-off-by: Reetika Malhotra <malhotra.reetika25@gmail.com>
Signed-off-by: vishal210893 <vishal210893@gmail.com>
2025-11-05 09:12:56 +00:00
AshvinBambhaniya2003
305a90f428 Feat(addon): Store addon registry tokens in Secrets (#6935)
* feat(addon): Store addon registry tokens in Secrets

Previously, addon registry tokens were stored in plaintext within the 'vela-addon-registry' ConfigMap. This is not a secure practice for sensitive data.

This commit refactors the addon registry functionality to store tokens in Kubernetes Secrets. The ConfigMap now only contains a reference to the secret name, while the token itself is stored securely.

This change includes:
- Creating/updating secrets when a registry is added/updated.
- Loading tokens from secrets when a registry is listed/retrieved.
- Deleting secrets when a registry is deleted.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* test(addon): Add tests for registry token secret storage

This commit introduces a comprehensive test suite for the addon registry feature.

It includes:
- Isolated unit tests for each CRUD operation (Add, Update, List, Get, Delete) to ensure each function works correctly in isolation.
- A stateful integration test to validate the complete lifecycle of an addon registry from creation to deletion.

The tests verify that tokens are handled correctly via Kubernetes Secrets, confirming the implementation of the secure token storage feature.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(addon): improve addon registry robustness and fix bugs

This commit introduces several improvements to the addon registry to make it more robust and fixes several bugs.

- When updating a secret, the existing secret is now fetched and updated to avoid potential conflicts.
- Deleting a non-existent registry now returns no error, making the operation idempotent.
- Getting a non-existent registry now returns a structured not-found error.
- Loading a token from a non-existent secret is now handled gracefully.
- When setting a token directly on a git-based addon source, the token secret reference is now cleared.
- The token secret reference is now correctly copied in `SafeCopy`.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* Refactor(addon): Fix secret deletion and improve registry logic

This commit refactors the addon registry data store to fix a critical bug where deleting an addon registry would not delete its associated token secret.

The root cause was that the `GetRegistry` function, which was used by `DeleteRegistry`, would load the token from the secret and then clear the `TokenSecretRef` field on the in-memory object. This meant that when `DeleteRegistry` tried to find the secret to delete, the reference was already gone.

This has been fixed by:
1. Introducing a central `getRegistries` helper function to read the raw registry data from the ConfigMap.
2. Refactoring all data store methods (`List`, `Get`, `Add`, `Update`, `Delete`) to use this central helper, removing duplicate code.
3. Ensuring `DeleteRegistry` uses the raw, unmodified registry data so that the `TokenSecretRef` is always available for deletion.

Additionally, comprehensive unit tests for the new helper functions (`getRegistries`, `loadTokenFromSecret`, `createOrUpdateTokenSecret`) have been added to verify the fix and improve overall code quality and stability.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(addon): improve addon registry token security and logging

This commit enhances the security and observability of addon registry token handling.

- Adds a warning message to users when an insecure inline token is detected in an addon registry configuration, prompting them to migrate to a more secure secret-based storage.
- Implements info-level logging to create an audit trail for token migrations, providing administrators with visibility into security-related events.
- Refactors the token migration logic into a new `migrateInlineTokenToSecret` function, improving code clarity and maintainability.
- Introduces unit tests for the `TokenSource` interface methods and the `GetTokenSource` function to ensure correctness and prevent regressions.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* Chore: remove comments to triger ci

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-31 13:52:30 +00:00
AshvinBambhaniya2003
d1f077ee0d Fix(addon): show correct owner in definition conflict error (#6903)
* fix(addon): show correct owner in definition conflict error

When enabling an addon, if a definition conflicted with one from another existing addon, the error message would misleadingly cite the addon being installed as the owner, rather than the actual owner of the definition. This made it difficult for users to diagnose the conflict.

This commit corrects the error message generation in `checkConflictDefs` to use the name of the actual owner application. A comprehensive unit test for this function has also been added to verify the corrected behavior and prevent regressions.

Fixes #6898

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* fix(addon): show correct owner name in conflict message

When a definition conflict occurs, the error message attempts to show the addon that owns the existing definition.

However, if the owner is not a KubeVela addon application (i.e., its name doesn't have the 'addon-' prefix), the `AppName2Addon` function returns an empty string. This resulted in a confusing conflict message with a blank owner name, like "already exist in  \n".

This patch fixes the issue by checking if the result of `AppName2Addon` is empty. If it is, it falls back to using the full application name of the owner,
ensuring the conflict message is always clear and actionable.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* chore(addon): update comment for addon name

- Add this comment to trigger ci

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* fix(addon): improve conflict message for addon definitions

adjust comment placement and logic to ensure correct addon name display in conflict messages

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-31 13:52:00 +00:00
AshvinBambhaniya2003
260fc1a294 Feat: Enhance unit test coverage for references/appfile package (#6913)
* feat(appfile): Enhance unit test coverage and migrate to standard Go testing

This commit significantly enhances the unit test coverage for the `references/appfile` package by introducing a comprehensive suite of new test cases and migrating existing tests to the standard Go `testing` framework with `testify/assert`.

Key additions and improvements include:
- **New Test Cases for `references/appfile/api/appfile.go`**: Added tests for `NewAppFile`, `JSONToYaml`, and `LoadFromBytes` to ensure correct application file initialization, parsing, and loading.
- **New Test Cases for `references/appfile/api/service.go`**: Introduced tests for `GetUserConfigName`, `GetApplicationConfig`, and `ToStringSlice` to validate service configuration extraction and type conversions.
- **Expanded Test Coverage for `references/appfile/app.go`**: Added new tests for `NewApplication`, `Validate`, `GetComponents`, `GetServiceConfig`, `GetApplicationSettings`, `GetWorkload`, and `GetTraits`, ensuring the robustness of application-level operations.
- **Dedicated Test Files for `modify.go` and `run.go`**: Created `modify_test.go` and `run_test.go` to provide specific unit tests for `SetWorkload`, `CreateOrUpdateApplication`, `CreateOrUpdateObjects`, and `Run` functions.
- **Test Framework Migration**: Refactored `addon_suit_test.go` to `main_test.go` and `addon_test.go` to use standard Go `testing` and `testify/assert`, improving consistency and maintainability.

These changes collectively improve the robustness, reliability, and maintainability of the `appfile` package by providing a more comprehensive and standardized testing approach.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* chore(references/appfile): improve test suite robustness and style

This commit introduces two improvements to the test suite in the `references/appfile` package.

First, the `TestMain` function in `main_test.go` is refactored to ensure the `envtest` control-plane is always stopped, even if test setup fails. This is achieved by creating a single exit path that handles cleanup, preventing resource leaks.

Second, a minor linting issue (S1005) in `modify_test.go` is fixed by removing an unnecessary assignment to the blank identifier.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* Chore: remove comment to trigger ci

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-31 13:51:09 +00:00
AshvinBambhaniya2003
24f6718619 Feat(testing): Enhance Unit Test Coverage for Core Utility Packages (#6929)
* test(cli): enhance unit test coverage for theme and color config

This commit introduces a comprehensive suite of unit tests for the theme and color configuration functions in `references/cli/top/config`.

Key changes include:
- Refactored existing tests in `color_test.go` to use table-driven sub-tests for improved clarity and maintainability.
- Added new test functions to validate color parsing, hex color detection, and default theme creation.
- Implemented tests for theme file lifecycle management, including creation and loading logic.

These additions significantly increase the test coverage and ensure the robustness and correctness of the CLI's theme and color functionality.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* test(cli): refactor and enhance tests for top view models and utils

This commit improves the unit test suite for the CLI's top view functionality by refactoring existing tests and adding new ones to increase coverage.

Key changes include:
- In `application_test.go`, `TestApplicationList_ToTableBody` is refactored to be a table-driven test, and new tests are added for `serviceNum`, `workflowMode`, and `workflowStepNum` helpers.
- In `time_test.go`, `TestTimeFormat` is refactored into a table-driven test for better structure and readability.

These changes align the tests with best practices and improve the overall robustness of the CLI top view's data presentation logic.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* test(cuegen): enhance unit test coverage for CUE generation packages

This commit introduces a comprehensive suite of unit tests and refactors existing tests for the CUE generation packages located in `references/cuegen`.

Key changes include:
- Refactored existing tests in `generator_test.go` and `provider_test.go` to use table-driven sub-tests, improving clarity, maintainability, and coverage of error conditions.
- Added new test functions to `convert_test.go` to validate helper functions for comment generation, type support, and enum field handling.
- Added new tests in `provider_test.go` to cover provider extraction, declaration modification, and panic recovery logic.

These changes significantly increase the test coverage for the `cuegen` libraries, ensuring the correctness and robustness of the CUE code generation functionality.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* test(docgen): add comprehensive unit tests for doc generation

This commit introduces a comprehensive suite of unit tests for the documentation generation package located in `references/docgen`.

Key changes include:
- Added new test files (`console_test.go`, `convert_test.go`, `openapi_test.go`) to cover the core functions for parsing and generating documentation for CUE, Terraform, and OpenAPI schemas.
- Refactored and enhanced `i18n_test.go` to use sub-tests, resolve race conditions, and improve coverage for fallback logic and error handling.
- Ensured all new and existing tests follow best practices, using table-driven tests for clarity and maintainability.

This effort significantly increases the test coverage for the `docgen` package, improving the reliability and robustness of the documentation generation features.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* test: improve test reliability and conventions

This commit introduces several improvements to the test suite to enhance reliability and adhere to best practices.

- **Fix flaky test in `docgen/openapi_test.go`**:
  The test for `GenerateConsoleDocument` was flaky because it performed an exact string match on table output generated from a map. Since map iteration order is not guaranteed, this could cause spurious failures. The test is now order-insensitive, comparing sorted sets of lines instead.

- **Improve assertions in `docgen/console_test.go`**:
  - Removes an unnecessary `test.EquateErrors()` option, which is not needed for simple string comparisons.
  - Corrects the `cmp.Diff` argument order to the standard `(want, got)` convention for clearer failure messages.
  - Fixes a typo in an error message.

- **Standardize assertions in `cli/top/config/color_test.go`**:
  Swaps `assert.Equal` arguments to the standard `(expected, actual)` convention.

- **Clean up `cuegen/generators/provider/provider_test.go`**:
  Removes a redundant error check.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-31 13:50:30 +00:00
AshvinBambhaniya2003
44ac92d1ba Feat(test): Enhance unit test coverage for webhook, workflow, VELAQL, and monitor packages (#6895)
* feat(monitor): Add unit tests for application metrics watcher

This commit introduces a new test file with comprehensive unit tests for the application metrics watcher functionality in pkg/monitor/watcher.

Key additions include:
  - Test cases for the application metrics watcher's inc() method covering add, delete, and update operations
  - Test cases for report() method that verifies dirty flags are cleared
  - Test cases for helper functions getPhase() and getApp()

These additions improve the overall test coverage and ensure the correctness of the application metrics monitoring functionality.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(velaql): Add comprehensive unit tests for ParseVelaQLFromPath

This commit introduces new unit tests for the ParseVelaQLFromPath function in pkg/velaql, along with test data files to improve test coverage and ensure correctness.

Key additions include:
  - `pkg/velaql/parse_test.go`: Adds TestParseVelaQLFromPath function with comprehensive test cases covering:
    * Valid CUE files with and without export fields
    * Nonexistent and empty file paths
    * Invalid CUE content
    * Files with invalid export types
  - Test data files in pkg/velaql/testdata/:
    * simple-valid.cue: Valid CUE file with export field
    * simple-no-export.cue: Valid CUE file without export field
    * empty.cue: Empty CUE file
    * invalid-cue-content.cue: CUE file with invalid syntax
    * invalid-export.cue: CUE file with invalid export type

These additions improve the overall test coverage and ensure the robustness of the VELAQL parsing functionality.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(webhook): Add unit tests for ValidateDefinitionRevision function

This commit introduces new unit tests for the ValidateDefinitionRevision function in pkg/webhook/utils to improve test coverage and ensure correctness of definition revision validation.

Key additions include:
  - `pkg/webhook/utils/utils_test.go`: Adds TestValidateDefinitionRevision function with comprehensive test cases covering:
    * Success scenarios with matching definition revisions
    * Success scenarios when definition revision does not exist
    * Failure scenarios with revision hash mismatches
    * Failure scenarios with spec mismatches
    * Failure scenarios with invalid definition revision names

These additions improve the overall test coverage and ensure the robustness of the webhook utility functions for validating definition revisions.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(workflow): Add unit tests for OAM apply and query utilities

This commit introduces new unit tests for workflow provider functions in pkg/workflow/providers to improve test coverage and ensure correctness.

Key additions include:
  - `pkg/workflow/providers/oam/apply_test.go`: Adds TestRenderComponent function with comprehensive test cases for component rendering
  - `pkg/workflow/providers/query/utils_test.go`: Adds:
    * TestBuildResourceArray function with comprehensive test cases covering simple, nested, and complex resource tree scenarios
    * TestBuildResourceItem function with test cases for resources with and without annotations

These additions improve the overall test coverage and ensure the robustness of the workflow provider functions for OAM applications.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* fix(velaql): Improve error handling in ParseVelaQLFromPath test

This commit addresses an issue in the TestParseVelaQLFromPath function where file read errors were being silently ignored. The changes include:

- Removing the unused expectedView field from test cases
- Replacing conditional error checking with require.NoError to ensure file read operations are properly validated
- Ensuring that test failures are properly reported when file reading fails

This fix improves the reliability of the test suite by making sure that any file I/O errors are properly caught and reported rather than silently ignored.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat: Apply cross-cutting test improvements

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat: Enhance test coverage with file-specific suggestions

This commit applies file-specific suggestions to enhance the test suite's
coverage and robustness.

Key changes include:

- **`pkg/monitor/watcher/application_test.go`**:
  - Added a test case for a multi-step workflow with mixed phases to
    validate `stepPhaseCounter` aggregation.
  - Added a test for idempotence by calling `inc` twice.
  - Added test cases for an empty workflow and an unknown application phase.
  - Strengthened the `report` test to assert that counters are not cleared.

- **`pkg/velaql/parse_test.go`**:
  - Added a test case for `ParseVelaQLFromPath` to handle files with
    leading/trailing whitespace.
  - Added a test case to ensure consistent error messages for relative paths.

- **`pkg/webhook/utils/utils_test.go`**:
  - Added a test case to `TestValidateCueTemplate` for a malformed CUE
    template.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-31 13:49:15 +00:00
Chaitanyareddy0702
d627ecea2a Chore: Upgrade cuelang version to v0.14.1 (#6877)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 24s
* chore: updates culenag version and syntax across all files

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* debuggin: reverts tf provider changes

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Refactor: Simplify provider configuration by removing 'providerBasic' and directly defining access keys and region for providers

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Refactor: Consolidate provider configuration by introducing 'providerBasic' for access keys and region

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: reorganize import statements in deepcopy files for consistency

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: reorder import statements for consistency across deepcopy files

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Refactor: Safely handle pattern parameter selectors to avoid panics in GetParameters and getStatusMap

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: add comment to clarify test context in definition_revision_test.go

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: remove redundant comment from test context initialization in definition_revision_test.go

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Refactor: Introduce GetSelectorLabel function to safely extract labels from CUE selectors

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: add newline at end of file in utils.go

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: increase timeout for multi-cluster e2e

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Amit Singh <singhamitch@outlook.com>
Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
Co-authored-by: Amit Singh <singhamitch@outlook.com>
Co-authored-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2025-10-23 10:56:37 +01:00
Ayush Kumar
d8a17740dc Refactor: controller flags registration and cobra options (#6949)
* feat: Introduce comprehensive configuration management for KubeVela

- Added multiple configuration files under `cmd/core/app/config` to encapsulate various aspects of KubeVela's functionality, including:
  - Feature gates
  - Logging (KLog)
  - Kubernetes API client settings
  - Multi-cluster management
  - OAM-specific configurations
  - Observability settings (metrics and logging)
  - Performance optimizations
  - Profiling settings
  - Reconciliation settings
  - Resource management
  - Server-level configurations
  - Sharding configurations
  - Webhook settings
  - Workflow engine configurations

- Refactored `CoreOptions` to utilize the new configuration modules, ensuring a clean delegation pattern for flag registration.
- Updated tests to validate the new configuration structure and ensure backward compatibility with legacy fields.

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: Sync config module values to legacy fields and add debug logging for webhook configuration

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: Remove debug logging for webhook configuration in server command

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* chore: Add missing newlines at the end of multiple configuration files

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Clean up legacy field synchronization and improve configuration handling in CoreOptions

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: Introduce ControllerConfig for improved controller configuration management

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: Implement sync methods for configuration values across various modules

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Update ControllerConfig to embed Args struct and simplify flag registration

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Remove ConfigureKLog method and apply klog settings directly in server run function

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Remove unnecessary line in ControllerConfig and update test assertions for CUE options

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: Enhance CUE configuration flags with detailed descriptions and add comprehensive tests for core options

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* feat: Add backward compatibility notes to sync methods and enhance CLI override tests for configuration values

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* refactor: Standardize flag formatting in TestCoreOptions_AllConfigModulesHaveFlags

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2025-10-23 10:54:45 +01:00
jguionnet
05b0ec89a5 Refactor: Update documentation generation to retain .md extensions and fixed Components header (#6957)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 25s
- Modified the documentation generation logic to keep .md file extensions, enhancing IDE support and compatibility with Docusaurus.
- Updated various documentation headers to include the correct .md references in auto-generated messages, ensuring consistency across multiple components (component, policy, trait, workflow).

Signed-off-by: jguionnet jguionnet@guidewire.com

Signed-off-by: jguionnet jguionnet@guidewire.com
Signed-off-by: Jerome Guionnet <jguionnet@guidewire.com>
2025-10-22 18:17:46 -07:00
Ayush Kumar
f196d66b5e Fix: Prevent index out-of-bounds in definitions (#6948)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 24s
* Fix: Update ingress messages to handle host retrieval more robustly across multiple templates

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Enhance output handling in k8s-objects template to check for empty objects

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

* Fix: Ensure policy selection from envBindingPolicies only occurs if the list is not empty

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>

---------

Signed-off-by: Ayush Kumar <ayushshyamkumar888@gmail.com>
2025-10-17 14:34:43 +01:00
AshvinBambhaniya2003
21d9d24b07 Feat(addon): Enhance unit test coverage for pkg/addon (#6901)
* feat(addon): add comprehensive unit tests for addon readers

This commit enhances the test coverage and code quality for the addon reader implementations in the pkg/addon package.

- Refactors all existing addon reader tests (gitee, github, gitlab, local) to use consistent, modern testing patterns like sub-tests.
- Replaces the old memory_reader_test.go with a completely refactored implementation.
- Adds new unit tests for previously untested functions, including various getters, client constructors, and RelativePath helpers.
- Improves http-based tests (gitlab, github, gitee) to use robust mock handlers that correctly simulate API behavior, including pagination and error states.

These changes improve the overall quality and reliability of the addon system and uncovered two minor bugs during the process.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(addon): add more unit tests for addon helpers

This commit continues to improve the test coverage for the pkg/addon package by adding unit tests for several helper and factory functions.

- Adds a test for WrapErrRateLimit to ensure GitHub API rate limit errors are handled correctly.
- Adds a test for ClassifyItemByPattern to verify addon file classification logic.
- Adds a test for the NewAsyncReader factory function to ensure correct reader instantiation.
- Adds tests for various utility functions in utils.go, including IsRegistryFuncs, InstallOptions, ProduceDefConflictError, and GenerateChartMetadata.

These tests increase the reliability of the addon installation and handling logic.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* feat(addon): add unit tests for versioned addon registry

This commit improves test coverage for the versioned addon registry logic in the pkg/addon package.

- Adds a unit test for resolveAddonListFromIndex to verify the logic for parsing Helm index files.
- Introduces a new table-driven test for the internal loadAddon function, covering success and multiple failure scenarios (e.g., version not found, download failure, corrupt data).
- Adds a new test helper, setupAddonTestServer, to create isolated mock HTTP servers for testing addon loading, improving test reliability and clarity.

These tests ensure the core logic for discovering and fetching versioned addons is robust and functions as expected.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* chore(addon): remove unused gitlab testdata path constant

- remove unused gitlab testdata path constant name `gitlabTestdataPath`

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* refactor(addon): improve unit tests based on review feedback

This commit addresses several code review comments to improve the quality, correctness, and robustness of the unit tests in the pkg/addon package.
- Refactors map key assertions in the memory reader test to use the correct "comma ok" idiom instead of assert.NotNil.
- Updates the GitHub reader test to use a compliant addon mock that includes the required template.cue file.
- Modifies the chart metadata test in utils_test.go to use t.TempDir() for better test isolation and automatic cleanup.
- Switches from assert.NotNil to require.NotNil in the versioned registry test to prevent panics on nil pointers.
These changes make the test suite more robust, reliable, and easier to maintain.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-17 10:47:43 +01:00
AshvinBambhaniya2003
3f5b698dac Feat(appfile): Add comprehensive unit tests for appfile and component package (#6908)
* feat(appfile): Add comprehensive unit tests for appfile package

This commit significantly enhances the test coverage for the `pkg/appfile` package by adding a comprehensive suite of new unit tests. These tests improve the reliability of core application parsing, generation, and validation logic.

Key additions include:
- **Parsing:** New tests for policy parsing, legacy application revision handling, and dynamic component loading.
- **Manifest Generation:** Added coverage for `GenerateComponentManifests` and `GeneratePolicyManifests` to ensure correctness of generated resources.
- **OAM Contracts:** New tests for `SetOAMContract` and `setWorkloadRefToTrait` to verify OAM label and reference injection.
- **Template & Context:** Added tests for loading templates from revisions (`LoadTemplateFromRevision`) and preparing the process context (`PrepareProcessContext`).
- **Validation:** Enhanced validation tests for component parameters and uniqueness of output names.

As part of this effort, the existing tests were also migrated from Ginkgo to the standard `testing` package with `testify/assert` to maintain consistency across the codebase.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* refactor(pkg/component): Migrate ref-objects tests to standard Go testing and add new test cases

This commit refactors the unit tests for `pkg/component/ref-objects` from a Ginkgo-based suite to the standard Go `testing` package. Additionally, new unit test cases have been added to further enhance test coverage and ensure the robustness of the `ref-objects` functionality.

Key changes include:
- Deletion of `pkg/component/ref_objects_suite_test.go`.
- Introduction of `pkg/component/main_test.go` to manage test environment setup and teardown using `TestMain`.
- Creation of `pkg/component/ref_objects_test.go` containing all the ref-objects related unit tests, now using standard Go testing functions, along with newly added test cases for improved coverage.

This migration improves consistency with other unit tests in the codebase and leverages the native Go testing framework.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* chore(pkg/component): Reorder imports in ref_objects_test.go

This commit reorders the import statements in `pkg/component/ref_objects_test.go` to adhere to standard Go formatting and import grouping conventions. This change improves code readability and consistency.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-17 10:45:45 +01:00
AshvinBambhaniya2003
4b1d1601c8 fix(addon): correct path calculation in gitlab reader (#6902)
The GetPath method for GitLabItem produced an incorrect path when an addon's base path in the repository was empty. This was caused by an off-by-one error in the string slicing logic that always assumed a base path separator existed, incorrectly truncating the first character of the file path.

This commit corrects the logic by adding a check for an empty base path, ensuring the full path is returned in that case.

Fixes #6899

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-17 10:43:08 +01:00
Brian Kane
ebf73d03c2 Chore: Add codeowners (#6946)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 20s
Signed-off-by: Brian Kane <briankane1@gmail.com>
2025-10-16 08:33:49 -07:00
AshvinBambhaniya2003
1d7b186664 Feat: Enhance unit test coverage for references/common package (#6918)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 26s
* feat(common): Enhance unit test coverage for common utilities

This commit significantly enhances the unit test coverage for the `references/common` package, covering a wide range of utilities related to application management, metrics, registry operations, traits, and workloads. Existing tests have also been refactored to improve readability and maintainability.

Key additions and improvements include:
- **Application Utilities**: New tests for `ExportFromAppFile`, `ApplyApp`, `IsAppfile`, `Info`, `SonLeafResource`, `LoadAppFile`, and `ApplyApplication` in `application_test.go`.
- **Metrics Utilities**: Expanded tests for `ToPercentage`, `GetPodStorage`, and `GetPodOfManagedResource` in `metrics_test.go`, with existing tests refactored to use `testify/assert` and table-driven formats.
- **Registry Operations**: New tests for `InstallComponentDefinition` and `InstallTraitDefinition` in `registry_test.go`.
- **Trait Definitions**: New `trait_test.go` file with tests for `ListRawWorkloadDefinitions`.
- **Workload Initialization**: New `workload_test.go` file with tests for `InitApplication` and `BaseComplete`.

These changes collectively improve the robustness, reliability, and maintainability of the `references/common` package by providing a more comprehensive and standardized testing approach.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* test(common): Improve test assertions and error handling

This commit improves the quality and reliability of unit tests in the `references/common` package by addressing several inconsistencies and potential issues.

Key changes include:

- Asserts the error returned by `v1beta1.AddToScheme` across multiple test files (`application_test.go`, `registry_test.go`, `workload_test.go`) to prevent masking scheme registration failures.
- Replaces `strings.Contains` with the more idiomatic `assert.Contains` in `application_test.go`.
- Adds an assertion to check the error returned by `tmpFile.Close()` in `application_test.go`.
- Uses `assert.EqualError` instead of `assert.Equal` for comparing error messages in `registry_test.go` for more precise error checking.
- Removes an unused `strings` import from `application_test.go`.

These changes lead to more robust, readable, and consistent tests.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* fix(common): Fix flaky test in TestExportFromAppFile

The `TestExportFromAppFile` test was passing locally but failing in CI with a "no matches for kind" error.

This was caused by passing an uninitialized `common.Args` object to the `ExportFromAppFile` function. The function was using the client from this object, which was not the correctly configured fake client.

This commit fixes the issue by explicitly setting the fake client on the `common.Args` object before it is used, making the test hermetic and reliable.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-14 11:33:21 -07:00
James Dobson
d46ad7e06e Chore: Remove unused parameter 'addonName' from 'vela-cli' workflow step. (#6930)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 20s
Signed-off-by: James Dobson <jdobson@guidewire.com>
2025-10-09 13:34:26 -07:00
Ayush Kumar
743fcc6efc Chore: update homebrew bump action (#6939)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 23s
* Fix: update Homebrew formula action to latest version

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>

* Fix: update Homebrew formula action reference to correct version

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>

* fix: remove redundant Homebrew bump action

- Fixes: https://github.com/kubevela/kubevela/actions/runs/18149681613/job/51659048948
- The kubevela formula in homebrew/core is already configured for automatic updates via BrewTestBot.
- BrewTestBot runs every ~3 hours after a new release to automatically open version bump PRs.
- The manual bump step (dawidd6/action-homebrew-bump-formula) was redundant and caused workflow failures:
  'Error: Whoops, the kubevela formula has its version update pull requests automatically opened by BrewTestBot every ~3 hours!'
- Removed the manual bump action to prevent conflicts and rely solely on BrewTestBot for formula updates https://github.com/Homebrew/homebrew-core/blob/master/Formula/k/kubevela.rb.

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>

---------

Signed-off-by: Chaitanya Reddy Onteddu <chaitanyareddy0702@gmail.com>
2025-10-06 11:59:00 -07:00
AshvinBambhaniya2003
10b45d3a8f Fix(references/appfile): Fix namespace check and Terraform output parsing (#6915)
* fix(references/appfile): correct namespace existence check in addon

The `generateSecretFromTerraformOutput` function was using an incorrect logic to check for namespace existence. It was trying to create the namespace and if it succeeded, it would return an error.

This commit corrects the logic to use `k8sClient.Get` and checks for a `NotFound` error to accurately determine if the namespace exists.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* fix(references/appfile): make terraform output parsing robust

The previous implementation for parsing `terraform output` was fragile and could lead to data corruption or errors. It would incorrectly remove all spaces from values and would fail to parse values that contained an equals sign.

This commit refactors the parsing logic to be more robust:
- It no longer removes spaces from output values, preserving them correctly.
- It correctly parses `key=value` pairs by splitting only on the first equals sign in a line.
- It properly handles quoted string values from Terraform.

The corresponding tests in `addon_test.go` have been updated to align with the refactored function signature and verify the new, robust behavior.

Fixes #6916

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-06 11:57:37 -07:00
Vishal Kumar
7f81d6f2d6 Feat: add KinD setup step to sync-sdk workflow (#6937)
Some checks failed
Webhook Upgrade Validation / webhook-upgrade-check (push) Failing after 34s
Signed-off-by: vishal210893 <vishal210893@gmail.com>
2025-10-02 15:01:20 -07:00
430 changed files with 85706 additions and 5571 deletions

30
.github/CODEOWNERS vendored
View File

@@ -1,35 +1,35 @@
# This file is a github code protect rule follow the codeowners https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-code-owners#example-of-a-codeowners-file
* @barnettZQG @wonderflow @leejanee @Somefive @jefree-cat @FogDong @wangyikewxgm @chivalryq @anoop2811
design/ @barnettZQG @leejanee @wonderflow @Somefive @jefree-cat @FogDong @anoop2811
* @barnettZQG @wonderflow @leejanee @Somefive @jefree-cat @FogDong @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
design/ @barnettZQG @leejanee @wonderflow @Somefive @jefree-cat @FogDong @anoop2811 @briankane @jguionnet
# Owner of Core Controllers
pkg/controller/core.oam.dev @Somefive @FogDong @barnettZQG @wonderflow @wangyikewxgm @chivalryq @anoop2811
pkg/controller/core.oam.dev @Somefive @FogDong @barnettZQG @wonderflow @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
# Owner of Standard Controllers
pkg/controller/standard.oam.dev @wangyikewxgm @barnettZQG @wonderflow @Somefive @anoop2811 @FogDong
pkg/controller/standard.oam.dev @wangyikewxgm @barnettZQG @wonderflow @Somefive @anoop2811 @FogDong @briankane @jguionnet
# Owner of CUE
pkg/cue @leejanee @FogDong @Somefive @anoop2811
pkg/stdlib @leejanee @FogDong @Somefive @anoop2811
pkg/cue @leejanee @FogDong @Somefive @anoop2811 @briankane @jguionnet
pkg/stdlib @leejanee @FogDong @Somefive @anoop2811 @briankane @jguionnet
# Owner of Workflow
pkg/workflow @leejanee @FogDong @Somefive @wangyikewxgm @chivalryq @anoop2811
pkg/workflow @leejanee @FogDong @Somefive @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
# Owner of vela templates
vela-templates/ @Somefive @barnettZQG @wonderflow @FogDong @wangyikewxgm @chivalryq @anoop2811
vela-templates/ @Somefive @barnettZQG @wonderflow @FogDong @wangyikewxgm @chivalryq @anoop2811 @briankane @jguionnet
# Owner of vela CLI
references/cli/ @Somefive @StevenLeiZhang @charlie0129 @wangyikewxgm @chivalryq @anoop2811 @FogDong
references/cli/ @Somefive @StevenLeiZhang @charlie0129 @wangyikewxgm @chivalryq @anoop2811 @FogDong @briankane @jguionnet
# Owner of vela addon framework
pkg/addon/ @wangyikewxgm @wonderflow @charlie0129 @anoop2811 @FogDong
pkg/addon/ @wangyikewxgm @wonderflow @charlie0129 @anoop2811 @FogDong @briankane @jguionnet
# Owner of resource keeper and tracker
pkg/resourcekeeper @Somefive @FogDong @chivalryq @anoop2811
pkg/resourcetracker @Somefive @FogDong @chivalryq @anoop2811
pkg/resourcekeeper @Somefive @FogDong @chivalryq @anoop2811 @briankane @jguionnet
pkg/resourcetracker @Somefive @FogDong @chivalryq @anoop2811 @briankane @jguionnet
.github/ @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811
makefiles @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811
go.* @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811
.github/ @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811 @briankane @jguionnet
makefiles @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811 @briankane @jguionnet
go.* @chivalryq @wonderflow @Somefive @FogDong @wangyikewxgm @anoop2811 @briankane @jguionnet

View File

@@ -19,6 +19,10 @@ runs:
# ========================================================================
- name: Configure environment setup
uses: ./.github/actions/env-setup
with:
install-ginkgo: 'true'
install-setup-envtest: 'false'
install-kustomize: 'false'
- name: Build project
shell: bash

View File

@@ -1,11 +1,27 @@
name: 'Kubevela Test Environment Setup'
description: 'Sets up complete testing environment for Kubevela with Go, Kubernetes tools, and Ginkgo framework for E2E testing.'
description: 'Sets up complete testing environment for Kubevela with Go, Kubernetes tools, and testing frameworks.'
inputs:
go-version:
description: 'Go version to use for testing'
required: false
default: '1.23.8'
install-ginkgo:
description: 'Install Ginkgo testing framework'
required: false
default: 'true'
install-setup-envtest:
description: 'Install setup-envtest for integration testing'
required: false
default: 'false'
install-kustomize:
description: 'Install kustomize for manifest management'
required: false
default: 'false'
kustomize-version:
description: 'Kustomize version to install'
required: false
default: '4.5.4'
runs:
@@ -32,20 +48,22 @@ runs:
run: |
# Detect architecture
ARCH=$(uname -m | sed 's/x86_64/amd64/' | sed 's/aarch64/arm64/')
# Install kubectl
echo "Installing kubectl for architecture: $ARCH"
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/${ARCH}/kubectl"
# Install kubectl using a known stable version to avoid network issues
# The dl.k8s.io/release/stable.txt endpoint can return garbage due to CDN issues
KUBECTL_VERSION="v1.31.0"
echo "Installing kubectl version: $KUBECTL_VERSION for architecture: $ARCH"
curl -LO --retry 3 --fail "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/${ARCH}/kubectl"
chmod +x kubectl
sudo mv kubectl /usr/local/bin/
# Install helm using the official script (more reliable)
# Install helm using the official script
echo "Installing Helm using official script..."
curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
curl -fsSL --retry 3 -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
chmod 700 get_helm.sh
./get_helm.sh
rm get_helm.sh
# Verify installations
echo "Verifying installations..."
kubectl version --client
@@ -66,7 +84,37 @@ runs:
go mod verify
- name: Install Ginkgo testing framework
if: ${{ inputs.install-ginkgo == 'true' }}
shell: bash
run: |
echo "Installing Ginkgo testing framework..."
go install github.com/onsi/ginkgo/v2/ginkgo@v2.14.0
echo "Ginkgo installed successfully"
- name: Install setup-envtest
if: ${{ inputs.install-setup-envtest == 'true' }}
shell: bash
run: |
echo "Installing setup-envtest for integration testing..."
mkdir -p ./bin
GOBIN=$(pwd)/bin go install sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.0.0-20240522175850-2e9781e9fc60
echo "setup-envtest installed successfully at ./bin/setup-envtest"
ls -la ./bin/setup-envtest
# Download and cache the Kubernetes binaries for envtest
echo "Downloading Kubernetes binaries for envtest..."
KUBEBUILDER_ASSETS=$(./bin/setup-envtest use 1.31.0 --bin-dir ./bin -p path)
echo "Kubernetes binaries downloaded successfully"
echo "KUBEBUILDER_ASSETS=${KUBEBUILDER_ASSETS}"
# Export for subsequent steps
echo "KUBEBUILDER_ASSETS=${KUBEBUILDER_ASSETS}" >> $GITHUB_ENV
- name: Install kustomize
if: ${{ inputs.install-kustomize == 'true' }}
shell: bash
run: |
echo "Installing kustomize version ${{ inputs.kustomize-version }}..."
mkdir -p ./bin
curl -sS https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh | bash -s ${{ inputs.kustomize-version }} $(pwd)/bin
echo "kustomize installed successfully at ./bin/kustomize"
./bin/kustomize version

View File

@@ -20,6 +20,10 @@ runs:
# ========================================================================
- name: Configure environment setup
uses: ./.github/actions/env-setup
with:
install-ginkgo: 'true'
install-setup-envtest: 'false'
install-kustomize: 'false'
# ========================================================================
# E2E Test Execution

View File

@@ -19,6 +19,10 @@ runs:
# ========================================================================
- name: Configure environment setup
uses: ./.github/actions/env-setup
with:
install-ginkgo: 'true'
install-setup-envtest: 'true'
install-kustomize: 'true'
# ========================================================================
# Unit Test Execution

View File

@@ -11,4 +11,7 @@ wangyuan249
chivalryq
FogDong
leejanee
barnettZQG
barnettZQG
anoop2811
briankane
jguionnet

View File

@@ -97,6 +97,21 @@ jobs:
with:
submodules: true
- name: Free Disk Space
run: |
echo "Disk space before cleanup:"
df -h
# Remove unnecessary software to free up disk space
sudo rm -rf /usr/share/dotnet
sudo rm -rf /usr/local/lib/android
sudo rm -rf /opt/ghc
sudo rm -rf /opt/hostedtoolcache/CodeQL
sudo docker image prune --all --force
echo "Disk space after cleanup:"
df -h
- name: Setup Env
uses: ./.github/actions/env-setup
@@ -111,6 +126,24 @@ jobs:
- name: Run cross-build
run: make cross-build
- name: Free Disk Space After Cross-Build
run: |
echo "Disk space before cleanup:"
df -h
# Remove cross-build artifacts to free up space
# (make build will rebuild binaries for current platform)
rm -rf _bin
# Clean Go build cache and test cache
go clean -cache -testcache
# Remove Docker build cache
sudo docker builder prune --all --force || true
echo "Disk space after cleanup:"
df -h
- name: Check Diff
run: |
export PATH=$(pwd)/bin/:$PATH

View File

@@ -111,16 +111,9 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
- name: Update kubectl plugin version in krew-index
uses: rajatjindal/krew-release-bot@df3eb197549e3568be8b4767eec31c5e8e8e6ad8 # v0.0.46
- name: Update Homebrew formula
uses: dawidd6/action-homebrew-bump-formula@d3667e5ae14df19579e4414897498e3e88f2f458 # v3.10.0
with:
token: ${{ secrets.HOMEBREW_TOKEN }}
formula: kubevela
tag: ${{ github.ref }}
revision: ${{ github.sha }}
force: false
provenance-vela-bins:
name: generate provenance for binaries

View File

@@ -28,10 +28,15 @@ jobs:
- name: Install Go tools
run: |
make goimports
- name: Build CLI
run: make vela-cli
- name: Setup KinD
uses: ./.github/actions/setup-kind-cluster
with:
name: sync-sdk
- name: Get the version
id: get_version
run: echo "VERSION=${GITHUB_REF}" >> $GITHUB_OUTPUT

2
.gitignore vendored
View File

@@ -62,3 +62,5 @@ git-page/
vela.json
dist/
.planning/
.claude/

View File

@@ -29,7 +29,7 @@ linters-settings:
gocyclo:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 30
min-complexity: 35
dupl:
@@ -144,6 +144,14 @@ issues:
linters:
- gocritic
# The preferFprint suggestion (sb.WriteString(fmt.Sprintf(...)) -> fmt.Fprintf(sb, ...))
# is a micro-optimization. The defkit package generates CUE code infrequently,
# so the performance difference is negligible and the current style is more readable.
- path: pkg/definition/defkit/
text: "preferFprint"
linters:
- gocritic
# Gosmopolitan complains of internationalization issues on the file that actually defines
# the translation.
- path: i18n\.go

View File

@@ -230,7 +230,7 @@ spec:
1. Workflow support specify Order Steps by Field Tag (#2022)
2. support application policy (#2011)
3. add OCM multi cluster demo (#1992)
4. Fix(volume): seperate volume to trait (#2027)
4. Fix(volume): separate volume to trait (#2027)
5. allow application skip gc resource and leave workload ownerReference controlled by rollout(#2024)
6. Store component parameters in context (#2030)
7. Allow specify chart values for helm trait(#2033)

View File

@@ -64,8 +64,8 @@ lint: golangci
@GOLANGCILINT=$(GOLANGCILINT) ./hack/utils/golangci-lint-wrapper.sh
## reviewable: Run the reviewable
reviewable: manifests fmt vet lint staticcheck helm-doc-gen sdk_fmt
go mod tidy
## Run make build to compile vela binary before running this target to ensure all generated definitions are up to date.
reviewable: build manifests fmt vet lint staticcheck helm-doc-gen sdk_fmt
# check-diff: Execute auto-gen code commands and ensure branch is clean.
check-diff: reviewable
@@ -103,7 +103,7 @@ manager:
$(GOBUILD_ENV) go build -o bin/manager -a -ldflags $(LDFLAGS) ./cmd/core/main.go
## manifests: Generate manifests e.g. CRD, RBAC etc.
manifests: installcue kustomize
manifests: tidy installcue kustomize sync-crds
go generate $(foreach t,pkg apis,./$(t)/...)
# TODO(yangsoon): kustomize will merge all CRD into a whole file, it may not work if we want patch more than one CRD in this way
$(KUSTOMIZE) build config/crd -o config/crd/base/core.oam.dev_applications.yaml

View File

@@ -107,7 +107,7 @@ Check out [KubeVela videos](https://kubevela.io/videos/talks/en/oam-dapr) for th
## Contributing
Check out [CONTRIBUTING](https://kubevela.io/docs/contributor/overview) to see how to develop with KubeVela.
Check out [CONTRIBUTING](https://kubevela.io/docs/contributor/overview) to see how to develop with KubeVela
## Report Vulnerability

View File

@@ -26,6 +26,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
wfTypesv1alpha1 "github.com/kubevela/pkg/apis/oam/v1alpha1"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/condition"
@@ -173,12 +174,15 @@ type ApplicationComponentStatus struct {
Cluster string `json:"cluster,omitempty"`
Env string `json:"env,omitempty"`
// WorkloadDefinition is the definition of a WorkloadDefinition, such as deployments/apps.v1
WorkloadDefinition WorkloadGVK `json:"workloadDefinition,omitempty"`
Healthy bool `json:"healthy"`
Details map[string]string `json:"details,omitempty"`
Message string `json:"message,omitempty"`
Traits []ApplicationTraitStatus `json:"traits,omitempty"`
Scopes []corev1.ObjectReference `json:"scopes,omitempty"`
WorkloadDefinition WorkloadGVK `json:"workloadDefinition,omitempty"`
Healthy bool `json:"healthy"`
// WorkloadHealthy indicates the workload health without considering trait health.
// +optional
WorkloadHealthy bool `json:"workloadHealthy,omitempty"`
Details map[string]string `json:"details,omitempty"`
Message string `json:"message,omitempty"`
Traits []ApplicationTraitStatus `json:"traits,omitempty"`
Scopes []corev1.ObjectReference `json:"scopes,omitempty"`
}
// Equal check if two ApplicationComponentStatus are equal
@@ -191,6 +195,7 @@ func (in ApplicationComponentStatus) Equal(r ApplicationComponentStatus) bool {
type ApplicationTraitStatus struct {
Type string `json:"type"`
Healthy bool `json:"healthy"`
Pending bool `json:"pending,omitempty"`
Details map[string]string `json:"details,omitempty"`
Message string `json:"message,omitempty"`
}
@@ -204,6 +209,40 @@ type Revision struct {
RevisionHash string `json:"revisionHash,omitempty"`
}
// AppliedApplicationPolicy records minimal status information about an Application-scoped policy.
// This covers both global (auto-discovered) and explicit (spec-referenced) policies.
// Full details (transforms, labels, annotations, etc.) are stored in the ConfigMap referenced
// by ApplicationPoliciesConfigMap for persistent storage and observability.
type AppliedApplicationPolicy struct {
Name string `json:"name"`
Type string `json:"type,omitempty"`
Namespace string `json:"namespace"`
Applied bool `json:"applied"`
Error bool `json:"error,omitempty"`
Message string `json:"message,omitempty"`
Source string `json:"source,omitempty"` // "global" or "explicit" - how the policy was applied
SpecModified bool `json:"specModified,omitempty"`
LabelsCount int `json:"labelsCount,omitempty"`
AnnotationsCount int `json:"annotationsCount,omitempty"`
HasContext bool `json:"hasContext,omitempty"`
// Version tracking
// DefinitionRevisionName is the DefinitionRevision resource name if a versioned policy was used (e.g., "my-policy-v3")
// Empty if the policy wasn't versioned (used latest PolicyDefinition)
// +optional
DefinitionRevisionName string `json:"definitionRevisionName,omitempty"`
// Revision is the revision number from the DefinitionRevision (e.g. 3)
// +optional
Revision int64 `json:"revision,omitempty"`
// RevisionHash is the hash of the PolicyDefinition template from the DefinitionRevision
// This is the definitive proof of exactly what template was used
// +optional
RevisionHash string `json:"revisionHash,omitempty"`
}
// AppStatus defines the observed state of Application
type AppStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
@@ -225,6 +264,12 @@ type AppStatus struct {
// Workflow record the status of workflow
Workflow *WorkflowStatus `json:"workflow,omitempty"`
// WorkflowRestartScheduledAt schedules a workflow restart at the specified time.
// This field is automatically set when the app.oam.dev/restart-workflow annotation is present,
// and is cleared after the restart is triggered. Use RFC3339 format or set to current time for immediate restart.
// +optional
WorkflowRestartScheduledAt *metav1.Time `json:"workflowRestartScheduledAt,omitempty"`
// LatestRevision of the application configuration it generates
// +optional
LatestRevision *Revision `json:"latestRevision,omitempty"`
@@ -232,6 +277,16 @@ type AppStatus struct {
// AppliedResources record the resources that the workflow step apply.
AppliedResources []ClusterObjectReference `json:"appliedResources,omitempty"`
// AppliedApplicationPolicies lists Application-scoped policies (both global and explicit)
// that were discovered and applied (or skipped) during reconciliation.
// +optional
AppliedApplicationPolicies []AppliedApplicationPolicy `json:"appliedApplicationPolicies,omitempty"`
// ApplicationPoliciesConfigMap references the ConfigMap containing rendered policy outputs
// Format: "application-policies-{namespace}-{name}"
// +optional
ApplicationPoliciesConfigMap string `json:"applicationPoliciesConfigMap,omitempty"`
// PolicyStatus records the status of policy
// Deprecated This field is only used by EnvBinding Policy which is deprecated.
PolicyStatus []PolicyStatus `json:"policy,omitempty"`
@@ -301,9 +356,9 @@ type ApplicationComponent struct {
// +kubebuilder:pruning:PreserveUnknownFields
Properties *runtime.RawExtension `json:"properties,omitempty"`
DependsOn []string `json:"dependsOn,omitempty"`
Inputs workflowv1alpha1.StepInputs `json:"inputs,omitempty"`
Outputs workflowv1alpha1.StepOutputs `json:"outputs,omitempty"`
DependsOn []string `json:"dependsOn,omitempty"`
Inputs wfTypesv1alpha1.StepInputs `json:"inputs,omitempty"`
Outputs wfTypesv1alpha1.StepOutputs `json:"outputs,omitempty"`
// Traits define the trait of one component, the type must be array to keep the order.
Traits []ApplicationTrait `json:"traits,omitempty"`

View File

@@ -21,6 +21,7 @@ limitations under the License.
package common
import (
oamv1alpha1 "github.com/kubevela/pkg/apis/oam/v1alpha1"
"github.com/kubevela/workflow/api/v1alpha1"
crossplane_runtime "github.com/oam-dev/terraform-controller/api/types/crossplane-runtime"
v1 "k8s.io/api/core/v1"
@@ -48,6 +49,10 @@ func (in *AppStatus) DeepCopyInto(out *AppStatus) {
*out = new(WorkflowStatus)
(*in).DeepCopyInto(*out)
}
if in.WorkflowRestartScheduledAt != nil {
in, out := &in.WorkflowRestartScheduledAt, &out.WorkflowRestartScheduledAt
*out = (*in).DeepCopy()
}
if in.LatestRevision != nil {
in, out := &in.LatestRevision, &out.LatestRevision
*out = new(Revision)
@@ -58,6 +63,11 @@ func (in *AppStatus) DeepCopyInto(out *AppStatus) {
*out = make([]ClusterObjectReference, len(*in))
copy(*out, *in)
}
if in.AppliedApplicationPolicies != nil {
in, out := &in.AppliedApplicationPolicies, &out.AppliedApplicationPolicies
*out = make([]AppliedApplicationPolicy, len(*in))
copy(*out, *in)
}
if in.PolicyStatus != nil {
in, out := &in.PolicyStatus, &out.PolicyStatus
*out = make([]PolicyStatus, len(*in))
@@ -92,12 +102,12 @@ func (in *ApplicationComponent) DeepCopyInto(out *ApplicationComponent) {
}
if in.Inputs != nil {
in, out := &in.Inputs, &out.Inputs
*out = make(v1alpha1.StepInputs, len(*in))
*out = make(oamv1alpha1.StepInputs, len(*in))
copy(*out, *in)
}
if in.Outputs != nil {
in, out := &in.Outputs, &out.Outputs
*out = make(v1alpha1.StepOutputs, len(*in))
*out = make(oamv1alpha1.StepOutputs, len(*in))
copy(*out, *in)
}
if in.Traits != nil {
@@ -203,6 +213,21 @@ func (in *ApplicationTraitStatus) DeepCopy() *ApplicationTraitStatus {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AppliedApplicationPolicy) DeepCopyInto(out *AppliedApplicationPolicy) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AppliedApplicationPolicy.
func (in *AppliedApplicationPolicy) DeepCopy() *AppliedApplicationPolicy {
if in == nil {
return nil
}
out := new(AppliedApplicationPolicy)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *CUE) DeepCopyInto(out *CUE) {
*out = *in

View File

@@ -21,7 +21,7 @@ import (
k8sscheme "k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/scheme"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
wfTypesv1alpha1 "github.com/kubevela/pkg/apis/oam/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
)
@@ -57,7 +57,7 @@ var (
func init() {
SchemeBuilder.Register(&Policy{}, &PolicyList{})
SchemeBuilder.Register(&workflowv1alpha1.Workflow{}, &workflowv1alpha1.WorkflowList{})
SchemeBuilder.Register(&wfTypesv1alpha1.Workflow{}, &wfTypesv1alpha1.WorkflowList{})
_ = SchemeBuilder.AddToScheme(k8sscheme.Scheme)
}

View File

@@ -23,7 +23,7 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
wfTypesv1alpha1 "github.com/kubevela/pkg/apis/oam/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/condition"
@@ -42,9 +42,9 @@ type AppPolicy struct {
// Workflow defines workflow steps and other attributes
type Workflow struct {
Ref string `json:"ref,omitempty"`
Mode *workflowv1alpha1.WorkflowExecuteMode `json:"mode,omitempty"`
Steps []workflowv1alpha1.WorkflowStep `json:"steps,omitempty"`
Ref string `json:"ref,omitempty"`
Mode *wfTypesv1alpha1.WorkflowExecuteMode `json:"mode,omitempty"`
Steps []wfTypesv1alpha1.WorkflowStep `json:"steps,omitempty"`
}
// ApplicationSpec is the spec of Application

View File

@@ -19,8 +19,8 @@ package v1beta1
import (
"encoding/json"
wfTypesv1alpha1 "github.com/kubevela/pkg/apis/oam/v1alpha1"
"github.com/kubevela/pkg/util/compression"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
@@ -56,6 +56,11 @@ type ApplicationRevisionCompressibleFields struct {
// PolicyDefinitions records the snapshot of the PolicyDefinitions related with the created/modified Application
PolicyDefinitions map[string]PolicyDefinition `json:"policyDefinitions,omitempty"`
// PolicyVersions records version metadata for each policy (which DefinitionRevision was used)
// Key is the policy name (same as PolicyDefinitions keys)
// +optional
PolicyVersions map[string]PolicyVersionMetadata `json:"policyVersions,omitempty"`
// WorkflowStepDefinitions records the snapshot of the WorkflowStepDefinitions related with the created/modified Application
WorkflowStepDefinitions map[string]*WorkflowStepDefinition `json:"workflowStepDefinitions,omitempty"`
@@ -63,7 +68,7 @@ type ApplicationRevisionCompressibleFields struct {
Policies map[string]v1alpha1.Policy `json:"policies,omitempty"`
// Workflow records the external workflow
Workflow *workflowv1alpha1.Workflow `json:"workflow,omitempty"`
Workflow *wfTypesv1alpha1.Workflow `json:"workflow,omitempty"`
// ReferredObjects records the referred objects used in the ref-object typed components
// +kubebuilder:pruning:PreserveUnknownFields
@@ -161,3 +166,21 @@ type ApplicationRevisionList struct {
metav1.ListMeta `json:"metadata,omitempty"`
Items []ApplicationRevision `json:"items"`
}
// PolicyVersionMetadata records version information for a PolicyDefinition used in an ApplicationRevision
// This helps users identify which DefinitionRevision was selected when the ApplicationRevision was created
type PolicyVersionMetadata struct {
// DefinitionRevisionName is the DefinitionRevision resource name if versioned (e.g. "my-policy-v3")
// Empty if the policy used latest PolicyDefinition (no @version specified)
// +optional
DefinitionRevisionName string `json:"definitionRevisionName,omitempty"`
// Revision is the revision number from the DefinitionRevision (e.g. 3)
// +optional
Revision int64 `json:"revision,omitempty"`
// RevisionHash is the hash of the PolicyDefinition template
// This is the definitive proof of exactly what template was used
// +optional
RevisionHash string `json:"revisionHash,omitempty"`
}

View File

@@ -24,6 +24,19 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
)
// PolicyScope defines the scope at which a policy operates
type PolicyScope string
const (
// DefaultScope (empty string) means standard output / builtin policy
DefaultScope PolicyScope = ""
// ApplicationScope means the policy transforms the Application CR before parsing
// These policies use the Application transforms pattern
// (via output.{labels|annotations|ctx|components|traits|workflow|policies}) and don't generate resources
ApplicationScope PolicyScope = "Application"
)
// PolicyDefinitionSpec defines the desired state of PolicyDefinition
type PolicyDefinitionSpec struct {
// Reference to the CustomResourceDefinition that defines this trait kind.
@@ -40,6 +53,30 @@ type PolicyDefinitionSpec struct {
//+optional
Version string `json:"version,omitempty"`
// Scope defines the scope at which this policy operates.
// - DefaultScope (empty/omitted): Standard output-based or builtin policies (topology, override, etc.)
// These can generate Kubernetes resources from CUE templates with an 'output' field or apply Go-logic in the controller
// - ApplicationScope: Transform-based policies that modify the Application CR before parsing.
// Requires EnableApplicationScopedPolicies feature gate.
// +optional
Scope PolicyScope `json:"scope,omitempty"`
// Global indicates this policy should automatically apply to all Applications
// in this namespace (or all namespaces if in vela-system).
// Global policies cannot be explicitly referenced in Application specs.
// Requires EnableGlobalPolicies feature gate for discovery and
// EnableApplicationScopedPolicies feature gate for execution.
// +optional
Global bool `json:"global,omitempty"`
// Priority defines the order in which global policies are applied.
// Lower values run first (e.g. 0 runs before 100), following the same
// convention as Kubernetes admission webhooks. Policies with the same
// priority are applied in alphabetical order by name.
// If not specified, defaults to 0.
// +optional
Priority int32 `json:"priority,omitempty"`
}
// PolicyDefinitionStatus is the status of PolicyDefinition

View File

@@ -21,7 +21,7 @@ limitations under the License.
package v1beta1
import (
"github.com/kubevela/workflow/api/v1alpha1"
"github.com/kubevela/pkg/apis/oam/v1alpha1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
@@ -184,6 +184,13 @@ func (in *ApplicationRevisionCompressibleFields) DeepCopyInto(out *ApplicationRe
(*out)[key] = *val.DeepCopy()
}
}
if in.PolicyVersions != nil {
in, out := &in.PolicyVersions, &out.PolicyVersions
*out = make(map[string]PolicyVersionMetadata, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.WorkflowStepDefinitions != nil {
in, out := &in.WorkflowStepDefinitions, &out.WorkflowStepDefinitions
*out = make(map[string]*WorkflowStepDefinition, len(*in))
@@ -691,6 +698,21 @@ func (in *PolicyDefinitionStatus) DeepCopy() *PolicyDefinitionStatus {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PolicyVersionMetadata) DeepCopyInto(out *PolicyVersionMetadata) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PolicyVersionMetadata.
func (in *PolicyVersionMetadata) DeepCopy() *PolicyVersionMetadata {
if in == nil {
return nil
}
out := new(PolicyVersionMetadata)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceTracker) DeepCopyInto(out *ResourceTracker) {
*out = *in

View File

@@ -148,6 +148,15 @@ const (
// TypeLegacy defines legacy commands
TypeLegacy = "Legacy Commands"
// TypeDefManagement defines definition management commands
TypeDefManagement = "Definition Management"
// TypeDefGeneration defines definition generation commands
TypeDefGeneration = "Code Generation"
// TypeDefModule defines Go definition module commands
TypeDefModule = "Go Definition Modules"
)
// LabelArg is the argument `label` of a definition

View File

@@ -101,6 +101,8 @@ helm install --create-namespace -n vela-system kubevela kubevela/vela-core --wai
| `featureGates.enableCueValidation` | enable the strict cue validation for cue required parameter fields | `false` |
| `featureGates.enableApplicationStatusMetrics` | enable application status metrics and structured logging | `false` |
| `featureGates.validateResourcesExist` | enable webhook validation to check if resource types referenced in definition templates exist in the cluster | `false` |
| `featureGates.enableApplicationScopedPolicies` | enable Application-scoped PolicyDefinitions that transform Application CR before rendering (Alpha) | `false` |
| `featureGates.enableGlobalPolicies` | enable automatic discovery and application of global PolicyDefinitions to all Applications (Alpha) | `false` |
### MultiCluster parameters
@@ -151,6 +153,7 @@ helm install --create-namespace -n vela-system kubevela kubevela/vela-core --wai
| `devLogs` | Enable formatted logging support for development purpose | `false` |
| `logFilePath` | If non-empty, write log files in this path | `""` |
| `logFileMaxSize` | Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0, the maximum file size is unlimited. | `1024` |
| `admissionWebhookTimeout` | Timeout seconds for admission webhooks | `10` |
| `kubeClient.qps` | The qps for reconcile clients | `400` |
| `kubeClient.burst` | The burst for reconcile clients | `600` |
| `authentication.enabled` | Enable authentication framework for applications | `false` |

View File

@@ -372,6 +372,66 @@ spec:
status:
description: AppStatus defines the observed state of Application
properties:
applicationPoliciesConfigMap:
description: |-
ApplicationPoliciesConfigMap references the ConfigMap containing rendered policy outputs
Format: "application-policies-{namespace}-{name}"
type: string
appliedApplicationPolicies:
description: |-
AppliedApplicationPolicies lists Application-scoped policies (both global and explicit)
that were discovered and applied (or skipped) during reconciliation.
items:
description: |-
AppliedApplicationPolicy records minimal status information about an Application-scoped policy.
This covers both global (auto-discovered) and explicit (spec-referenced) policies.
Full details (transforms, labels, annotations, etc.) are stored in the ConfigMap referenced
by ApplicationPoliciesConfigMap for persistent storage and observability.
properties:
annotationsCount:
type: integer
applied:
type: boolean
definitionRevisionName:
description: |-
Version tracking
DefinitionRevisionName is the DefinitionRevision resource name if a versioned policy was used (e.g., "my-policy-v3")
Empty if the policy wasn't versioned (used latest PolicyDefinition)
type: string
error:
type: boolean
hasContext:
type: boolean
labelsCount:
type: integer
message:
type: string
name:
type: string
namespace:
type: string
revision:
description: Revision is the revision number from the
DefinitionRevision (e.g. 3)
format: int64
type: integer
revisionHash:
description: |-
RevisionHash is the hash of the PolicyDefinition template from the DefinitionRevision
This is the definitive proof of exactly what template was used
type: string
source:
type: string
specModified:
type: boolean
type:
type: string
required:
- applied
- name
- namespace
type: object
type: array
appliedResources:
description: AppliedResources record the resources that the workflow
step apply.
@@ -632,6 +692,8 @@ spec:
type: boolean
message:
type: string
pending:
type: boolean
type:
type: string
required:
@@ -651,6 +713,10 @@ spec:
- apiVersion
- kind
type: object
workloadHealthy:
description: WorkloadHealthy indicates the workload
health without considering trait health.
type: boolean
required:
- healthy
- name
@@ -817,6 +883,13 @@ spec:
- suspend
- terminated
type: object
workflowRestartScheduledAt:
description: |-
WorkflowRestartScheduledAt schedules a workflow restart at the specified time.
This field is automatically set when the app.oam.dev/restart-workflow annotation is present,
and is cleared after the restart is triggered. Use RFC3339 format or set to current time for immediate restart.
format: date-time
type: string
type: object
type: object
componentDefinitions:
@@ -1218,11 +1291,28 @@ spec:
required:
- name
type: object
global:
description: |-
Global indicates this policy should automatically apply to all Applications
in this namespace (or all namespaces if in vela-system).
Global policies cannot be explicitly referenced in Application specs.
Requires EnableGlobalPolicies feature gate for discovery and
EnableApplicationScopedPolicies feature gate for execution.
type: boolean
manageHealthCheck:
description: |-
ManageHealthCheck means the policy will handle health checking and skip application controller
built-in health checking.
type: boolean
priority:
description: |-
Priority defines the order in which global policies are applied.
Lower values run first (e.g. 0 runs before 100), following the same
convention as Kubernetes admission webhooks. Policies with the same
priority are applied in alphabetical order by name.
If not specified, defaults to 0.
format: int32
type: integer
schematic:
description: |-
Schematic defines the data format and template of the encapsulation of the policy definition.
@@ -1319,6 +1409,14 @@ spec:
- configuration
type: object
type: object
scope:
description: |-
Scope defines the scope at which this policy operates.
- DefaultScope (empty/omitted): Standard output-based or builtin policies (topology, override, etc.)
These can generate Kubernetes resources from CUE templates with an 'output' field or apply Go-logic in the controller
- ApplicationScope: Transform-based policies that modify the Application CR before parsing.
Requires EnableApplicationScopedPolicies feature gate.
type: string
version:
type: string
type: object
@@ -1386,6 +1484,32 @@ spec:
description: PolicyDefinitions records the snapshot of the PolicyDefinitions
related with the created/modified Application
type: object
policyVersions:
additionalProperties:
description: |-
PolicyVersionMetadata records version information for a PolicyDefinition used in an ApplicationRevision
This helps users identify which DefinitionRevision was selected when the ApplicationRevision was created
properties:
definitionRevisionName:
description: |-
DefinitionRevisionName is the DefinitionRevision resource name if versioned (e.g. "my-policy-v3")
Empty if the policy used latest PolicyDefinition (no @version specified)
type: string
revision:
description: Revision is the revision number from the DefinitionRevision
(e.g. 3)
format: int64
type: integer
revisionHash:
description: |-
RevisionHash is the hash of the PolicyDefinition template
This is the definitive proof of exactly what template was used
type: string
type: object
description: |-
PolicyVersions records version metadata for each policy (which DefinitionRevision was used)
Key is the policy name (same as PolicyDefinitions keys)
type: object
referredObjects:
description: ReferredObjects records the referred objects used in
the ref-object typed components

View File

@@ -322,6 +322,66 @@ spec:
status:
description: AppStatus defines the observed state of Application
properties:
applicationPoliciesConfigMap:
description: |-
ApplicationPoliciesConfigMap references the ConfigMap containing rendered policy outputs
Format: "application-policies-{namespace}-{name}"
type: string
appliedApplicationPolicies:
description: |-
AppliedApplicationPolicies lists Application-scoped policies (both global and explicit)
that were discovered and applied (or skipped) during reconciliation.
items:
description: |-
AppliedApplicationPolicy records minimal status information about an Application-scoped policy.
This covers both global (auto-discovered) and explicit (spec-referenced) policies.
Full details (transforms, labels, annotations, etc.) are stored in the ConfigMap referenced
by ApplicationPoliciesConfigMap for persistent storage and observability.
properties:
annotationsCount:
type: integer
applied:
type: boolean
definitionRevisionName:
description: |-
Version tracking
DefinitionRevisionName is the DefinitionRevision resource name if a versioned policy was used (e.g., "my-policy-v3")
Empty if the policy wasn't versioned (used latest PolicyDefinition)
type: string
error:
type: boolean
hasContext:
type: boolean
labelsCount:
type: integer
message:
type: string
name:
type: string
namespace:
type: string
revision:
description: Revision is the revision number from the DefinitionRevision
(e.g. 3)
format: int64
type: integer
revisionHash:
description: |-
RevisionHash is the hash of the PolicyDefinition template from the DefinitionRevision
This is the definitive proof of exactly what template was used
type: string
source:
type: string
specModified:
type: boolean
type:
type: string
required:
- applied
- name
- namespace
type: object
type: array
appliedResources:
description: AppliedResources record the resources that the workflow
step apply.
@@ -580,6 +640,8 @@ spec:
type: boolean
message:
type: string
pending:
type: boolean
type:
type: string
required:
@@ -599,6 +661,10 @@ spec:
- apiVersion
- kind
type: object
workloadHealthy:
description: WorkloadHealthy indicates the workload health without
considering trait health.
type: boolean
required:
- healthy
- name
@@ -760,6 +826,13 @@ spec:
- suspend
- terminated
type: object
workflowRestartScheduledAt:
description: |-
WorkflowRestartScheduledAt schedules a workflow restart at the specified time.
This field is automatically set when the app.oam.dev/restart-workflow annotation is present,
and is cleared after the restart is triggered. Use RFC3339 format or set to current time for immediate restart.
format: date-time
type: string
type: object
type: object
served: true

View File

@@ -395,11 +395,28 @@ spec:
required:
- name
type: object
global:
description: |-
Global indicates this policy should automatically apply to all Applications
in this namespace (or all namespaces if in vela-system).
Global policies cannot be explicitly referenced in Application specs.
Requires EnableGlobalPolicies feature gate for discovery and
EnableApplicationScopedPolicies feature gate for execution.
type: boolean
manageHealthCheck:
description: |-
ManageHealthCheck means the policy will handle health checking and skip application controller
built-in health checking.
type: boolean
priority:
description: |-
Priority defines the order in which global policies are applied.
Lower values run first (e.g. 0 runs before 100), following the same
convention as Kubernetes admission webhooks. Policies with the same
priority are applied in alphabetical order by name.
If not specified, defaults to 0.
format: int32
type: integer
schematic:
description: |-
Schematic defines the data format and template of the encapsulation of the policy definition.
@@ -495,6 +512,14 @@ spec:
- configuration
type: object
type: object
scope:
description: |-
Scope defines the scope at which this policy operates.
- DefaultScope (empty/omitted): Standard output-based or builtin policies (topology, override, etc.)
These can generate Kubernetes resources from CUE templates with an 'output' field or apply Go-logic in the controller
- ApplicationScope: Transform-based policies that modify the Application CR before parsing.
Requires EnableApplicationScopedPolicies feature gate.
type: string
version:
type: string
type: object

View File

@@ -58,11 +58,28 @@ spec:
required:
- name
type: object
global:
description: |-
Global indicates this policy should automatically apply to all Applications
in this namespace (or all namespaces if in vela-system).
Global policies cannot be explicitly referenced in Application specs.
Requires EnableGlobalPolicies feature gate for discovery and
EnableApplicationScopedPolicies feature gate for execution.
type: boolean
manageHealthCheck:
description: |-
ManageHealthCheck means the policy will handle health checking and skip application controller
built-in health checking.
type: boolean
priority:
description: |-
Priority defines the order in which global policies are applied.
Lower values run first (e.g. 0 runs before 100), following the same
convention as Kubernetes admission webhooks. Policies with the same
priority are applied in alphabetical order by name.
If not specified, defaults to 0.
format: int32
type: integer
schematic:
description: |-
Schematic defines the data format and template of the encapsulation of the policy definition.
@@ -156,6 +173,14 @@ spec:
- configuration
type: object
type: object
scope:
description: |-
Scope defines the scope at which this policy operates.
- DefaultScope (empty/omitted): Standard output-based or builtin policies (topology, override, etc.)
These can generate Kubernetes resources from CUE templates with an 'output' field or apply Go-logic in the controller
- ApplicationScope: Transform-based policies that modify the Application CR before parsing.
Requires EnableApplicationScopedPolicies feature gate.
type: string
version:
type: string
type: object

View File

@@ -3,8 +3,7 @@ apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
controller-gen.kubebuilder.io/version: v0.9.0
creationTimestamp: null
controller-gen.kubebuilder.io/version: v0.16.5
name: workflows.core.oam.dev
spec:
group: core.oam.dev
@@ -23,14 +22,19 @@ spec:
description: Workflow is the Schema for the workflow API
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to the latest
internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
description: |-
APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
description: |-
Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated.
In CamelCase.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
type: string
metadata:
type: object
@@ -59,6 +63,7 @@ spec:
inputs:
description: Inputs is the inputs of the step
items:
description: InputItem defines an input variable of WorkflowStep
properties:
from:
type: string
@@ -66,7 +71,6 @@ spec:
type: string
required:
- from
- parameterKey
type: object
type: array
meta:
@@ -75,12 +79,18 @@ spec:
alias:
type: string
type: object
mode:
description: Mode is only valid for sub steps, it defines the mode
of the sub steps
nullable: true
type: string
name:
description: Name is the unique name of the workflow step.
type: string
outputs:
description: Outputs is the outputs of the step
items:
description: OutputItem defines an output variable of WorkflowStep
properties:
name:
type: string
@@ -110,6 +120,7 @@ spec:
inputs:
description: Inputs is the inputs of the step
items:
description: InputItem defines an input variable of WorkflowStep
properties:
from:
type: string
@@ -117,7 +128,6 @@ spec:
type: string
required:
- from
- parameterKey
type: object
type: array
meta:
@@ -132,6 +142,7 @@ spec:
outputs:
description: Outputs is the outputs of the step
items:
description: OutputItem defines an output variable of WorkflowStep
properties:
name:
type: string
@@ -153,7 +164,6 @@ spec:
description: Type is the type of the workflow step.
type: string
required:
- name
- type
type: object
type: array
@@ -164,7 +174,6 @@ spec:
description: Type is the type of the workflow step.
type: string
required:
- name
- type
type: object
type: array

View File

@@ -45,6 +45,7 @@ webhooks:
- UPDATE
resources:
- applications
timeoutSeconds: {{ .Values.admissionWebhookTimeout }}
- clientConfig:
caBundle: {{ default "Cg==" (get $vals "comps") }}
service:
@@ -71,5 +72,6 @@ webhooks:
- UPDATE
resources:
- componentdefinitions
timeoutSeconds: {{ .Values.admissionWebhookTimeout }}
{{- end -}}

View File

@@ -47,7 +47,7 @@ webhooks:
- UPDATE
resources:
- traitdefinitions
timeoutSeconds: 5
timeoutSeconds: {{ .Values.admissionWebhookTimeout }}
- clientConfig:
caBundle: {{ default "Cg==" (get $vals "apps") }}
service:
@@ -74,6 +74,7 @@ webhooks:
- UPDATE
resources:
- applications
timeoutSeconds: {{ .Values.admissionWebhookTimeout }}
- clientConfig:
caBundle: {{ default "Cg==" (get $vals "comps") }}
service:
@@ -100,6 +101,7 @@ webhooks:
- UPDATE
resources:
- componentdefinitions
timeoutSeconds: {{ .Values.admissionWebhookTimeout }}
- clientConfig:
caBundle: {{ default "Cg==" (get $vals "policies") }}
service:
@@ -126,6 +128,7 @@ webhooks:
- UPDATE
resources:
- policydefinitions
timeoutSeconds: {{ .Values.admissionWebhookTimeout }}
- clientConfig:
caBundle: Cg==
service:
@@ -152,4 +155,5 @@ webhooks:
- UPDATE
resources:
- workflowstepdefinitions
timeoutSeconds: {{ .Values.admissionWebhookTimeout }}
{{- end -}}

View File

@@ -131,20 +131,21 @@ spec:
#podAffinityTerm: {
labelSelector?: #labelSelector
namespace?: string
namespaces?: [...string]
topologyKey: string
namespaceSelector?: #labelSelector
}
#nodeSelecor: {
#nodeSelector: {
key: string
operator: *"In" | "NotIn" | "Exists" | "DoesNotExist" | "Gt" | "Lt"
values?: [...string]
}
#nodeSelectorTerm: {
matchExpressions?: [...#nodeSelecor]
matchFields?: [...#nodeSelecor]
matchExpressions?: [...#nodeSelector]
matchFields?: [...#nodeSelector]
}
parameter: {

View File

@@ -15,9 +15,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
)
import "vela/op"
output: op.#ApplyApplicationInParallel & {}

View File

@@ -16,9 +16,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
)
import "vela/op"
// apply application
output: op.#ApplyApplication & {}

View File

@@ -13,12 +13,8 @@ spec:
schematic:
cue:
template: |
import (
"strconv"
"strings"
"vela/kube"
"vela/builtin"
)
import "vela/kube"
import "vela/builtin"
output: kube.#Apply & {
$params: {

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
)
import "vela/kube"
apply: kube.#Apply & {
$params: parameter

View File

@@ -16,9 +16,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
)
import "vela/op"
// apply remaining components and traits
apply: op.#ApplyRemaining & {

View File

@@ -13,10 +13,8 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
"vela/builtin"
)
import "vela/kube"
import "vela/builtin"
apply: kube.#Apply & {
$params: value: {

View File

@@ -13,12 +13,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/config"
"vela/kube"
"vela/builtin"
"strings"
)
import "vela/config"
import "vela/kube"
import "vela/builtin"
cfg: config.#CreateConfig & {
$params: {
@@ -87,9 +84,9 @@ spec:
}
}
providerBasic: {
accessKey: string
secretKey: string
region: string
accessKey!: string
secretKey!: string
region!: string
}
#AlibabaProvider: {
providerBasic
@@ -141,5 +138,5 @@ spec:
type: "ucloud"
name: *"ucloud-provider" | string
}
parameter: *#AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider
parameter: #AlibabaProvider | #AWSProvider | #AzureProvider | #BaiduProvider | #ECProvider | #GCPProvider | #TencentProvider | #UCloudProvider

View File

@@ -13,13 +13,10 @@ spec:
schematic:
cue:
template: |
import (
"vela/builtin"
"vela/kube"
"vela/util"
"encoding/json"
"strings"
)
import "vela/builtin"
import "vela/kube"
import "vela/util"
import "strings"
url: {
if parameter.context.git != _|_ {

View File

@@ -14,17 +14,14 @@ spec:
schematic:
cue:
template: |
import (
"vela/metrics"
"vela/builtin"
)
import "vela/metrics"
import "vela/builtin"
check: metrics.#PromCheck & {
$params: {
query: parameter.query
metricEndpoint: parameter.metricEndpoint
condition: parameter.condition
stepID: context.stepSessionID
duration: parameter.duration
failDuration: parameter.failDuration
}

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
)
import "vela/kube"
parameter: {
labelselector?: {...}

View File

@@ -12,11 +12,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/builtin"
"vela/query"
"strconv"
)
import "vela/builtin"
import "vela/query"
import "strconv"
collect: query.#CollectServiceEndpoints & {
$params: app: {

View File

@@ -16,6 +16,8 @@ spec:
schematic:
cue:
template: |
import "list"
#PatchParams: {
// +usage=Specify the name of the target container, if not set, use the component name
containerName: *"" | string
@@ -73,7 +75,7 @@ spec:
}
// +patchStrategy=replace
args: [for a in _args if _delArgs[a] == _|_ {a}] + [for a in _addArgs if _delArgs[a] == _|_ && _argsMap[a] == _|_ {a}]
args: list.Concat([[for a in _args if _delArgs[a] == _|_ {a}], [for a in _addArgs if _delArgs[a] == _|_ && _argsMap[a] == _|_ {a}]])
}
}
// +patchStrategy=open

View File

@@ -17,10 +17,9 @@ spec:
schematic:
cue:
template: |
import (
"strconv"
"strings"
)
import "strconv"
import "strings"
import "list"
#PatchParams: {
// +usage=Specify the name of the target container, if not set, use the component name
@@ -67,7 +66,7 @@ spec:
_basePortsMap: {for _basePort in _basePorts {(strings.ToLower(_basePort.protocol) + strconv.FormatInt(_basePort.containerPort, 10)): _basePort}}
_portsMap: {for port in _params.ports {(strings.ToLower(port.protocol) + strconv.FormatInt(port.containerPort, 10)): port}}
// +patchStrategy=replace
ports: [for portVar in _basePorts {
ports: list.Concat([[for portVar in _basePorts {
containerPort: portVar.containerPort
protocol: portVar.protocol
name: portVar.name
@@ -80,7 +79,7 @@ spec:
hostIP: _portsMap[_uniqueKey].hostIP
}
}
}] + [for port in _params.ports if _basePortsMap[strings.ToLower(port.protocol)+strconv.FormatInt(port.containerPort, 10)] == _|_ {
}], [for port in _params.ports if _basePortsMap[strings.ToLower(port.protocol)+strconv.FormatInt(port.containerPort, 10)] == _|_ {
if port.containerPort != _|_ {
containerPort: port.containerPort
}
@@ -93,7 +92,7 @@ spec:
if port.hostIP != _|_ {
hostIP: port.hostIP
}
}]
}]])
}
}
}

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/config"
)
import "vela/config"
deploy: config.#CreateConfig & {
$params: parameter

View File

@@ -11,6 +11,8 @@ spec:
schematic:
cue:
template: |
import "list"
mountsArray: {
pvc: *[
for v in parameter.volumeMounts.pvc {
@@ -130,7 +132,7 @@ spec:
},
] | []
}
volumesList: volumesArray.pvc + volumesArray.configMap + volumesArray.secret + volumesArray.emptyDir + volumesArray.hostPath
volumesList: list.Concat([volumesArray.pvc, volumesArray.configMap, volumesArray.secret, volumesArray.emptyDir, volumesArray.hostPath])
deDupVolumesArray: [
for val in [
for i, vi in volumesList {

View File

@@ -11,9 +11,7 @@ spec:
schematic:
cue:
template: |
import (
"strconv"
)
import "strconv"
mountsArray: [
if parameter.volumeMounts != _|_ && parameter.volumeMounts.pvc != _|_ for v in parameter.volumeMounts.pvc {

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/config"
)
import "vela/config"
deploy: config.#DeleteConfig & {
$params: parameter

View File

@@ -12,11 +12,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
"vela/builtin"
"encoding/yaml"
)
import "vela/kube"
import "vela/builtin"
import "encoding/yaml"
dependsOn: kube.#Read & {
$params: value: {

View File

@@ -14,9 +14,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
)
import "vela/op"
app: op.#DeployCloudResource & {
env: parameter.env

View File

@@ -14,10 +14,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/multicluster"
"vela/builtin"
)
import "vela/multicluster"
import "vela/builtin"
if parameter.auto == false {
suspend: builtin.#Suspend & {$params: message: "Waiting approval to the deploy step \"\(context.stepName)\""}

View File

@@ -15,9 +15,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
)
import "vela/op"
app: op.#ApplyEnvBindApp & {
env: parameter.env

View File

@@ -15,9 +15,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
)
import "vela/op"
app: op.#Steps & {
load: op.#Load

View File

@@ -16,6 +16,8 @@ spec:
schematic:
cue:
template: |
import "list"
#PatchParams: {
// +usage=Specify the name of the target container, if not set, use the component name
containerName: *"" | string
@@ -49,7 +51,7 @@ spec:
if _baseEnv != _|_ {
_baseEnvMap: {for envVar in _baseEnv {(envVar.name): envVar}}
// +patchStrategy=replace
env: [for envVar in _baseEnv if _delKeys[envVar.name] == _|_ && !_params.replace {
env: list.Concat([[for envVar in _baseEnv if _delKeys[envVar.name] == _|_ && !_params.replace {
name: envVar.name
if _params.env[envVar.name] != _|_ {
value: _params.env[envVar.name]
@@ -62,10 +64,10 @@ spec:
valueFrom: envVar.valueFrom
}
}
}] + [for k, v in _params.env if _delKeys[k] == _|_ && (_params.replace || _baseEnvMap[k] == _|_) {
}], [for k, v in _params.env if _delKeys[k] == _|_ && (_params.replace || _baseEnvMap[k] == _|_) {
name: k
value: v
}]
}]])
}
}
}

View File

@@ -14,10 +14,8 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
"vela/kube"
)
import "vela/op"
import "vela/kube"
object: {
apiVersion: "v1"

View File

@@ -14,10 +14,8 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
"vela/kube"
)
import "vela/op"
import "vela/kube"
meta: {
name: *context.name | string

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
)
import "vela/kube"
apply: kube.#Apply & {
$params: {

View File

@@ -12,11 +12,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
"encoding/base64"
"encoding/json"
)
import "vela/kube"
import "encoding/base64"
import "encoding/json"
secret: {
data: *parameter.data | {}

View File

@@ -15,10 +15,8 @@ spec:
schematic:
cue:
template: |
import (
"strconv"
"strings"
)
import "strconv"
import "strings"
outputs: service: {
apiVersion: "v1"
@@ -96,21 +94,17 @@ spec:
stage: PostDispatch
status:
customStatus: |-
message: *"" | string
service: context.outputs.service
message: *"" | string
if service.spec.type == "ClusterIP" {
message: "ClusterIP: \(service.spec.clusterIP)"
}
if service.spec.type == "LoadBalancer" {
status: service.status
isHealth: *false | bool
message: *"ExternalIP: Pending" | string
if status != _|_ if status.loadBalancer != _|_ if status.loadBalancer.ingress != _|_ if len(status.loadBalancer.ingress) > 0 if status.loadBalancer.ingress[0].ip != _|_ {
isHealth: true
}
if !isHealth {
message: "ExternalIP: Pending"
}
if isHealth {
message: "ExternalIP: \(status.loadBalancer.ingress[0].ip)"
}
}

View File

@@ -17,6 +17,7 @@ spec:
template: |
import "strconv"
let nameSuffix = {
if parameter.name != _|_ {"-" + parameter.name}
if parameter.name == _|_ {""}
@@ -160,13 +161,17 @@ spec:
if parameter.name == _|_ { "" }
}
let ingressMetaName = context.name + nameSuffix
let ig = [for i in context.outputs if (i.kind == "Ingress") && (i.metadata.name == ingressMetaName) {i}][0]
let igList = [for i in context.outputs if (i.kind == "Ingress") && (i.metadata.name == ingressMetaName) {i}]
ig: *_|_ | _
if len(igList) > 0 {
ig: igList[0]
}
igs: *{} | {}
if ig != _|_ if ig.status != _|_ if ig.status.loadbalancer != _|_ {
if ig != _|_ if ig.status != _|_ if ig.status.loadbalancer != _|_ if len(ig.status.loadbalancer.ingress) > 0 {
igs: ig.status.loadbalancer.ingress[0]
}
igr: *{} | {}
if ig != _|_ if ig.spec != _|_ {
if ig != _|_ if ig.spec != _|_ if len(ig.spec.rules) > 0 {
igr: ig.spec.rules[0]
}
if igs == _|_ {

View File

@@ -12,11 +12,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
"vela/util"
"encoding/base64"
)
import "vela/kube"
import "vela/util"
import "encoding/base64"
output: kube.#Read & {
$params: value: {

View File

@@ -69,11 +69,16 @@ spec:
message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + "'\n"
}
if len(igs) > 0 {
let rules = context.outputs.ingress.spec.rules
host: *"" | string
if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
host: rules[0].host
}
if igs[0].ip != _|_ {
message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
message: "Visiting URL: " + host + ", IP: " + igs[0].ip
}
if igs[0].ip == _|_ {
message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
message: "Visiting URL: " + host
}
}
healthPolicy: 'isHealth: len(context.outputs.service.spec.clusterIP) > 0'

View File

@@ -62,11 +62,16 @@ spec:
message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + "'\n"
}
if len(igs) > 0 {
let rules = context.outputs.ingress.spec.rules
host: *"" | string
if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
host: rules[0].host
}
if igs[0].ip != _|_ {
message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
message: "Visiting URL: " + host + ", IP: " + igs[0].ip
}
if igs[0].ip == _|_ {
message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
message: "Visiting URL: " + host
}
}
healthPolicy: 'isHealth: len(context.outputs.service.spec.clusterIP) > 0'

View File

@@ -17,6 +17,8 @@ spec:
schematic:
cue:
template: |
import "list"
patch: spec: template: spec: {
// +patchKey=name
containers: [{
@@ -43,10 +45,10 @@ spec:
}
// +patchKey=name
volumeMounts: [{
volumeMounts: list.Concat([[{
name: parameter.mountName
mountPath: parameter.initMountPath
}] + parameter.extraVolumeMounts
}], parameter.extraVolumeMounts])
}]
// +patchKey=name
volumes: [{

View File

@@ -11,7 +11,12 @@ spec:
schematic:
cue:
template: |
output: parameter.objects[0]
output: {
if len(parameter.objects) > 0 {
parameter.objects[0]
}
...
}
outputs: {
for i, v in parameter.objects {

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/config"
)
import "vela/config"
output: config.#ListConfig & {
$params: parameter

View File

@@ -19,9 +19,7 @@ spec:
schematic:
cue:
template: |
import (
"encoding/json"
)
import "encoding/json"
outputs: nocalhostService: {
apiVersion: "v1"

View File

@@ -12,14 +12,12 @@ spec:
schematic:
cue:
template: |
import (
"vela/http"
"vela/email"
"vela/kube"
"vela/util"
"encoding/base64"
"encoding/json"
)
import "vela/http"
import "vela/email"
import "vela/kube"
import "vela/util"
import "encoding/base64"
import "encoding/json"
parameter: {
// +usage=Please fulfill its url and message if you want to send Lark messages
@@ -216,7 +214,7 @@ spec:
ding: {
if parameter.dingding != _|_ {
if parameter.dingding.url.value != _|_ {
ding1: http.#Do & {
ding1: http.#HTTPDo & {
$params: {
method: "POST"
url: parameter.dingding.url.value
@@ -240,7 +238,7 @@ spec:
}
stringValue: util.#ConvertString & {$params: bt: base64.Decode(null, read.$returns.value.data[parameter.dingding.url.secretRef.key])}
ding2: http.#Do & {
ding2: http.#HTTPDo & {
$params: {
method: "POST"
url: stringValue.$returns.str
@@ -257,10 +255,10 @@ spec:
lark: {
if parameter.lark != _|_ {
if parameter.lark.url.value != _|_ {
lark1: http.#Do & {
lark1: http.#HTTPDo & {
$params: {
method: "POST"
url: parameter.lark.message
url: parameter.lark.url.value
request: {
body: json.Marshal(parameter.lark.message)
header: "Content-Type": "application/json"
@@ -281,7 +279,7 @@ spec:
}
stringValue: util.#ConvertString & {$params: bt: base64.Decode(null, read.$returns.value.data[parameter.lark.url.secretRef.key])}
lark2: http.#Do & {
lark2: http.#HTTPDo & {
$params: {
method: "POST"
url: stringValue.$returns.str
@@ -299,7 +297,7 @@ spec:
slack: {
if parameter.slack != _|_ {
if parameter.slack.url.value != _|_ {
slack1: http.#Do & {
slack1: http.#HTTPDo & {
$params: {
method: "POST"
url: parameter.slack.url.value
@@ -323,7 +321,7 @@ spec:
}
stringValue: util.#ConvertString & {$params: bt: base64.Decode(null, read.$returns.value.data[parameter.slack.url.secretRef.key])}
slack2: http.#Do & {
slack2: http.#HTTPDo & {
$params: {
method: "POST"
url: stringValue.$returns.str

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/builtin"
)
import "vela/builtin"
parameter: message: string

View File

@@ -49,11 +49,16 @@ spec:
message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + " --route'\n"
}
if len(igs) > 0 {
let rules = context.outputs.ingress.spec.rules
host: *"" | string
if rules != _|_ if len(rules) > 0 if rules[0].host != _|_ {
host: rules[0].host
}
if igs[0].ip != _|_ {
message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + igs[0].ip
message: "Visiting URL: " + host + ", IP: " + igs[0].ip
}
if igs[0].ip == _|_ {
message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host
message: "Visiting URL: " + host
}
}
workloadRefPath: ""

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/config"
)
import "vela/config"
output: config.#ReadConfig & {
$params: parameter

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
)
import "vela/kube"
output: kube.#Read & {
$params: {

View File

@@ -13,11 +13,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
"vela/http"
"encoding/json"
)
import "vela/op"
import "vela/http"
import "encoding/json"
req: http.#HTTPDo & {
$params: {

View File

@@ -0,0 +1,117 @@
# Code generated by KubeVela templates. DO NOT EDIT. Please edit the original cue file.
# Definition source cue file: vela-templates/definitions/internal/restart-workflow.cue
apiVersion: core.oam.dev/v1beta1
kind: WorkflowStepDefinition
metadata:
annotations:
custom.definition.oam.dev/category: Workflow Control
definition.oam.dev/description: Schedule the current Application's workflow to restart at a specific time, after a duration, or at recurring intervals
labels:
custom.definition.oam.dev/scope: Application
name: restart-workflow
namespace: {{ include "systemDefinitionNamespace" . }}
spec:
schematic:
cue:
template: |
import "vela/kube"
import "vela/builtin"
// Count how many parameters are provided
_paramCount: len([
if parameter.at != _|_ {1},
if parameter.after != _|_ {1},
if parameter.every != _|_ {1},
])
// Fail if not exactly one parameter is provided
if _paramCount != 1 {
validateParams: builtin.#Fail & {
$params: message: "Exactly one of 'at', 'after', or 'every' parameters must be specified (found \(_paramCount))"
}
}
// Build the bash script to calculate annotation value
_script: string
if parameter.at != _|_ {
// Fixed timestamp mode - use as-is
_script: """
VALUE="\(parameter.at)"
kubectl annotate application \(context.name) -n \(context.namespace) app.oam.dev/restart-workflow="$VALUE" --overwrite
"""
}
if parameter.after != _|_ {
// Relative time mode - calculate timestamp using date
// Convert duration format (5m, 1h, 2d) to seconds, then calculate
_script: """
DURATION="\(parameter.after)"
# Convert duration to seconds
SECONDS=0
if [[ "$DURATION" =~ ^([0-9]+)s$ ]]; then
SECONDS=${BASH_REMATCH[1]}
elif [[ "$DURATION" =~ ^([0-9]+)m$ ]]; then
SECONDS=$((${BASH_REMATCH[1]} * 60))
elif [[ "$DURATION" =~ ^([0-9]+)h$ ]]; then
SECONDS=$((${BASH_REMATCH[1]} * 3600))
elif [[ "$DURATION" =~ ^([0-9]+)d$ ]]; then
SECONDS=$((${BASH_REMATCH[1]} * 86400))
else
echo "ERROR: Invalid duration format: $DURATION (expected format: 30s, 5m, 1h, or 2d)"
exit 1
fi
# Calculate future timestamp using seconds offset
VALUE=$(date -u -d "@$(($(date +%s) + SECONDS))" +%Y-%m-%dT%H:%M:%SZ)
echo "Calculated timestamp for after '$DURATION' ($SECONDS seconds): $VALUE"
kubectl annotate application \(context.name) -n \(context.namespace) app.oam.dev/restart-workflow="$VALUE" --overwrite
"""
}
if parameter.every != _|_ {
// Recurring interval mode - pass duration directly
_script: """
VALUE="\(parameter.every)"
kubectl annotate application \(context.name) -n \(context.namespace) app.oam.dev/restart-workflow="$VALUE" --overwrite
"""
}
// Run kubectl to annotate the Application
job: kube.#Apply & {
$params: value: {
apiVersion: "batch/v1"
kind: "Job"
metadata: {
name: "\(context.name)-restart-workflow-\(context.stepSessionID)"
namespace: "vela-system"
}
spec: {
backoffLimit: 3
template: spec: {
containers: [{
name: "kubectl-annotate"
image: "bitnami/kubectl:latest"
command: ["/bin/sh", "-c"]
args: [_script]
}]
restartPolicy: "Never"
serviceAccountName: "kubevela-vela-core"
}
}
}
}
wait: builtin.#ConditionalWait & {
if job.$returns.value.status != _|_ if job.$returns.value.status.succeeded != _|_ {
$params: continue: job.$returns.value.status.succeeded > 0
}
}
parameter: {
// +usage=Schedule restart at a specific RFC3339 timestamp (e.g., "2025-01-15T14:30:00Z")
at?: string & =~"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$"
// +usage=Schedule restart after a relative duration from now (e.g., "5m", "1h", "2d")
after?: string & =~"^[0-9]+(s|m|h|d)$"
// +usage=Schedule recurring restarts every specified duration (e.g., "5m", "1h", "24h")
every?: string & =~"^[0-9]+(s|m|h|d)$"
}

View File

@@ -14,9 +14,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/op"
)
import "vela/op"
app: op.#ShareCloudResource & {
env: parameter.env

View File

@@ -11,10 +11,8 @@ spec:
schematic:
cue:
template: |
import (
"strconv"
"strings"
)
import "strconv"
import "strings"
mountsArray: [
if parameter.volumeMounts != _|_ if parameter.volumeMounts.pvc != _|_ for v in parameter.volumeMounts.pvc {

View File

@@ -12,9 +12,7 @@ spec:
schematic:
cue:
template: |
import (
"vela/builtin"
)
import "vela/builtin"
suspend: builtin.#Suspend & {
$params: parameter

View File

@@ -12,11 +12,9 @@ spec:
schematic:
cue:
template: |
import (
"vela/kube"
"vela/builtin"
"vela/util"
)
import "vela/kube"
import "vela/builtin"
import "vela/util"
mountsArray: [
if parameter.storage != _|_ && parameter.storage.secret != _|_ for v in parameter.storage.secret {
@@ -126,8 +124,6 @@ spec:
}
parameter: {
// +usage=Specify the name of the addon.
addonName: string
// +usage=Specify the vela command
command: [...string]
// +usage=Specify the image

View File

@@ -12,13 +12,11 @@ spec:
schematic:
cue:
template: |
import (
"vela/http"
"vela/kube"
"vela/util"
"encoding/json"
"encoding/base64"
)
import "vela/http"
import "vela/kube"
import "vela/util"
import "encoding/json"
import "encoding/base64"
data: {
if parameter.data == _|_ {
@@ -40,9 +38,10 @@ spec:
}
webhook: {
if parameter.url.value != _|_ {
req: http.#HTTPPost & {
req: http.#HTTPDo & {
$params: {
url: parameter.url.value
method: "POST"
url: parameter.url.value
request: {
body: data.value
header: "Content-Type": "application/json"
@@ -63,9 +62,10 @@ spec:
}
stringValue: util.#ConvertString & {$params: bt: base64.Decode(null, read.$returns.value.data[parameter.url.secretRef.key])}
req: http.#HTTPPost & {
req: http.#HTTPDo & {
$params: {
url: stringValue.$returns.str
method: "POST"
url: stringValue.$returns.str
request: {
body: data.value
header: "Content-Type": "application/json"

View File

@@ -11,10 +11,8 @@ spec:
schematic:
cue:
template: |
import (
"strconv"
"strings"
)
import "strconv"
import "strings"
mountsArray: [
if parameter.volumeMounts != _|_ && parameter.volumeMounts.pvc != _|_ for v in parameter.volumeMounts.pvc {

View File

@@ -314,6 +314,8 @@ spec:
- "--feature-gates=EnableCueValidation={{- .Values.featureGates.enableCueValidation | toString -}}"
- "--feature-gates=EnableApplicationStatusMetrics={{- .Values.featureGates.enableApplicationStatusMetrics | toString -}}"
- "--feature-gates=ValidateResourcesExist={{- .Values.featureGates.validateResourcesExist | toString -}}"
- "--feature-gates=EnableApplicationScopedPolicies={{- .Values.featureGates.enableApplicationScopedPolicies | toString -}}"
- "--feature-gates=EnableGlobalPolicies={{- .Values.featureGates.enableGlobalPolicies | toString -}}"
- "--feature-gates=ValidateDefinitionPermissions={{ .Values.authorization.definitionValidationEnabled | toString -}}"
{{ if .Values.authentication.enabled }}
{{ if .Values.authentication.withUser }}

View File

@@ -126,6 +126,8 @@ optimize:
##@param featureGates.enableCueValidation enable the strict cue validation for cue required parameter fields
##@param featureGates.enableApplicationStatusMetrics enable application status metrics and structured logging
##@param featureGates.validateResourcesExist enable webhook validation to check if resource types referenced in definition templates exist in the cluster
##@param featureGates.enableApplicationScopedPolicies enable Application-scoped PolicyDefinitions that transform Application CR before rendering (Alpha)
##@param featureGates.enableGlobalPolicies enable automatic discovery and application of global PolicyDefinitions to all Applications (Alpha)
##@param
featureGates:
gzipResourceTracker: false
@@ -144,6 +146,8 @@ featureGates:
enableCueValidation: false
enableApplicationStatusMetrics: false
validateResourcesExist: false
enableApplicationScopedPolicies: false
enableGlobalPolicies: false
## @section MultiCluster parameters
@@ -267,6 +271,9 @@ logFilePath: ""
## @param logFileMaxSize Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0, the maximum file size is unlimited.
logFileMaxSize: 1024
## @param admissionWebhookTimeout Timeout seconds for admission webhooks
admissionWebhookTimeout: 10
## @skip admissionWebhooks
admissionWebhooks:
enabled: true

51
cmd/core/app/bootstrap.go Normal file
View File

@@ -0,0 +1,51 @@
/*
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 app
import (
"k8s.io/klog/v2"
)
// bootstrapProviderRegistry registers framework-level providers that need
// to be available globally. This is called early in prepareRun before
// controllers are initialized.
//
// The provider registry is a fallback mechanism for breaking import cycles
// that block development. Providers registered here enable immediate feature
// work while longer-term refactoring efforts can be planned.
//
// Best practices when adding a provider:
// 1. Document which packages have the cycle (in comments below)
// 2. Define narrow, focused interfaces (< 5 methods)
// 3. Consider opportunities for future refactoring to eliminate the cycle
// 4. Prefer constructor injection for new code without cycles
//
// See pkg/registry/README.md for feature overview and pkg/registry package docs for guidelines.
func bootstrapProviderRegistry() {
klog.V(2).InfoS("Bootstrapping provider registry")
// ────────────────────────────────────────────────────────────────────
// Add providers below following this pattern:
// ────────────────────────────────────────────────────────────────────
//
// ProviderInterface - Brief description
// Cycle: pkg/foo ↔ pkg/bar (explain the circular dependency)
// Note: Consider refactoring to extract shared interfaces
// registry.RegisterAs[ProviderInterface](implementation)
klog.V(2).InfoS("Provider registry bootstrap complete")
}

View File

@@ -0,0 +1,38 @@
/*
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 config
import (
"github.com/spf13/pflag"
standardcontroller "github.com/oam-dev/kubevela/pkg/controller"
)
// AdmissionConfig contains admission control configuration.
type AdmissionConfig struct {
// Fields will be populated based on what standardcontroller.AddAdmissionFlags sets
}
// NewAdmissionConfig creates a new AdmissionConfig with defaults.
func NewAdmissionConfig() *AdmissionConfig {
return &AdmissionConfig{}
}
// AddFlags registers admission configuration flags.
func (c *AdmissionConfig) AddFlags(fs *pflag.FlagSet) {
standardcontroller.AddAdmissionFlags(fs)
}

View File

@@ -0,0 +1,56 @@
/*
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 config
import (
"time"
"github.com/spf13/pflag"
commonconfig "github.com/oam-dev/kubevela/pkg/controller/common"
)
// ApplicationConfig contains application-specific configuration.
type ApplicationConfig struct {
ReSyncPeriod time.Duration
}
// NewApplicationConfig creates a new ApplicationConfig with defaults.
func NewApplicationConfig() *ApplicationConfig {
return &ApplicationConfig{
ReSyncPeriod: commonconfig.ApplicationReSyncPeriod,
}
}
// AddFlags registers application configuration flags.
func (c *ApplicationConfig) AddFlags(fs *pflag.FlagSet) {
fs.DurationVar(&c.ReSyncPeriod,
"application-re-sync-period",
c.ReSyncPeriod,
"Re-sync period for application to re-sync, also known as the state-keep interval.")
}
// SyncToApplicationGlobals syncs the parsed configuration values to application package global variables.
// This should be called after flag parsing to ensure the application controller uses the configured values.
//
// NOTE: This method exists for backward compatibility with legacy code that depends on global
// variables in the commonconfig package. Ideally, configuration should be injected rather than using globals.
//
// The flow is: CLI flags -> ApplicationConfig struct fields -> commonconfig globals (via this method)
func (c *ApplicationConfig) SyncToApplicationGlobals() {
commonconfig.ApplicationReSyncPeriod = c.ReSyncPeriod
}

View File

@@ -0,0 +1,40 @@
/*
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 config
import (
pkgclient "github.com/kubevela/pkg/controller/client"
"github.com/spf13/pflag"
)
// ClientConfig contains controller client configuration.
// This wraps the external package's client configuration flags.
type ClientConfig struct {
// Note: The actual configuration is managed by the pkgclient package
// This is a wrapper to maintain consistency with our config pattern
}
// NewClientConfig creates a new ClientConfig with defaults.
func NewClientConfig() *ClientConfig {
return &ClientConfig{}
}
// AddFlags registers client configuration flags.
// Delegates to the external package's flag registration.
func (c *ClientConfig) AddFlags(fs *pflag.FlagSet) {
pkgclient.AddTimeoutControllerClientFlags(fs)
}

View File

@@ -0,0 +1,67 @@
/*
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 config
import (
"github.com/spf13/pflag"
oamcontroller "github.com/oam-dev/kubevela/pkg/controller/core.oam.dev"
)
// ControllerConfig wraps the oamcontroller.Args configuration.
// While this appears to duplicate the Args struct, it serves as the new home for
// controller flag registration after the AddFlags method was moved here from
// the oamcontroller package during refactoring.
type ControllerConfig struct {
// Embed the existing Args struct to reuse its fields
oamcontroller.Args
}
// NewControllerConfig creates a new ControllerConfig with defaults.
func NewControllerConfig() *ControllerConfig {
return &ControllerConfig{
Args: oamcontroller.Args{
RevisionLimit: 50,
AppRevisionLimit: 10,
DefRevisionLimit: 20,
AutoGenWorkloadDefinition: true,
ConcurrentReconciles: 4,
IgnoreAppWithoutControllerRequirement: false,
IgnoreDefinitionWithoutControllerRequirement: false,
},
}
}
// AddFlags registers controller configuration flags.
// This method was moved here from oamcontroller.Args during refactoring
// to centralize configuration management.
func (c *ControllerConfig) AddFlags(fs *pflag.FlagSet) {
fs.IntVar(&c.RevisionLimit, "revision-limit", c.RevisionLimit,
"RevisionLimit is the maximum number of revisions that will be maintained. The default value is 50.")
fs.IntVar(&c.AppRevisionLimit, "application-revision-limit", c.AppRevisionLimit,
"application-revision-limit is the maximum number of application useless revisions that will be maintained, if the useless revisions exceed this number, older ones will be GCed first.The default value is 10.")
fs.IntVar(&c.DefRevisionLimit, "definition-revision-limit", c.DefRevisionLimit,
"definition-revision-limit is the maximum number of component/trait definition useless revisions that will be maintained, if the useless revisions exceed this number, older ones will be GCed first.The default value is 20.")
fs.BoolVar(&c.AutoGenWorkloadDefinition, "autogen-workload-definition", c.AutoGenWorkloadDefinition,
"Automatic generated workloadDefinition which componentDefinition refers to.")
fs.IntVar(&c.ConcurrentReconciles, "concurrent-reconciles", c.ConcurrentReconciles,
"concurrent-reconciles is the concurrent reconcile number of the controller. The default value is 4")
fs.BoolVar(&c.IgnoreAppWithoutControllerRequirement, "ignore-app-without-controller-version", c.IgnoreAppWithoutControllerRequirement,
"If true, application controller will not process the app without 'app.oam.dev/controller-version-require' annotation")
fs.BoolVar(&c.IgnoreDefinitionWithoutControllerRequirement, "ignore-definition-without-controller-version", c.IgnoreDefinitionWithoutControllerRequirement,
"If true, trait/component/workflowstep definition controller will not process the definition without 'definition.oam.dev/controller-version-require' annotation")
}

View File

@@ -0,0 +1,61 @@
/*
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 config
import (
"github.com/kubevela/pkg/cue/cuex"
"github.com/spf13/pflag"
)
// CUEConfig contains CUE language configuration.
type CUEConfig struct {
EnableExternalPackage bool
EnableExternalPackageWatch bool
}
// NewCUEConfig creates a new CUEConfig with defaults.
func NewCUEConfig() *CUEConfig {
return &CUEConfig{
EnableExternalPackage: cuex.EnableExternalPackageForDefaultCompiler,
EnableExternalPackageWatch: cuex.EnableExternalPackageWatchForDefaultCompiler,
}
}
// AddFlags registers CUE configuration flags.
func (c *CUEConfig) AddFlags(fs *pflag.FlagSet) {
fs.BoolVar(&c.EnableExternalPackage,
"enable-external-package-for-default-compiler",
c.EnableExternalPackage,
"Enable loading third-party CUE packages into the default CUE compiler. When enabled, external CUE packages can be imported and used in CUE templates.")
fs.BoolVar(&c.EnableExternalPackageWatch,
"enable-external-package-watch-for-default-compiler",
c.EnableExternalPackageWatch,
"Enable watching for changes in external CUE packages and automatically reload them when modified. Requires enable-external-package-for-default-compiler to be enabled.")
}
// SyncToCUEGlobals syncs the parsed configuration values to CUE package global variables.
// This should be called after flag parsing to ensure the CUE compiler uses the configured values.
//
// NOTE: This method exists for backward compatibility with legacy code that depends on global
// variables in the cuex package. Ideally, the CUE compiler configuration should be injected
// rather than relying on globals.
//
// The flow is: CLI flags -> CUEConfig struct fields -> cuex globals (via this method)
func (c *CUEConfig) SyncToCUEGlobals() {
cuex.EnableExternalPackageForDefaultCompiler = c.EnableExternalPackage
cuex.EnableExternalPackageWatchForDefaultCompiler = c.EnableExternalPackageWatch
}

View File

@@ -0,0 +1,40 @@
/*
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 config
import (
"github.com/spf13/pflag"
utilfeature "k8s.io/apiserver/pkg/util/feature"
)
// FeatureConfig contains feature gate configuration.
// This wraps the Kubernetes feature gate system.
type FeatureConfig struct {
// Note: The actual configuration is managed by the utilfeature package
// This is a wrapper to maintain consistency with our config pattern
}
// NewFeatureConfig creates a new FeatureConfig with defaults.
func NewFeatureConfig() *FeatureConfig {
return &FeatureConfig{}
}
// AddFlags registers feature gate configuration flags.
// Delegates to the Kubernetes feature gate system.
func (c *FeatureConfig) AddFlags(fs *pflag.FlagSet) {
utilfeature.DefaultMutableFeatureGate.AddFlag(fs)
}

View File

@@ -0,0 +1,42 @@
/*
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 config
import (
utillog "github.com/kubevela/pkg/util/log"
"github.com/spf13/pflag"
)
// KLogConfig contains klog configuration.
// This wraps the Kubernetes logging configuration.
type KLogConfig struct {
// Reference to observability config for log settings
observability *ObservabilityConfig
}
// NewKLogConfig creates a new KLogConfig.
func NewKLogConfig(observability *ObservabilityConfig) *KLogConfig {
return &KLogConfig{
observability: observability,
}
}
// AddFlags registers klog configuration flags.
func (c *KLogConfig) AddFlags(fs *pflag.FlagSet) {
// Add base klog flags
utillog.AddFlags(fs)
}

View File

@@ -0,0 +1,49 @@
/*
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 config
import (
"time"
"github.com/spf13/pflag"
)
// KubernetesConfig contains Kubernetes API client configuration.
type KubernetesConfig struct {
QPS float64
Burst int
InformerSyncPeriod time.Duration
}
// NewKubernetesConfig creates a new KubernetesConfig with defaults.
func NewKubernetesConfig() *KubernetesConfig {
return &KubernetesConfig{
QPS: 50,
Burst: 100,
InformerSyncPeriod: 10 * time.Hour,
}
}
// AddFlags registers Kubernetes configuration flags.
func (c *KubernetesConfig) AddFlags(fs *pflag.FlagSet) {
fs.Float64Var(&c.QPS, "kube-api-qps", c.QPS,
"the qps for reconcile clients. Low qps may lead to low throughput. High qps may give stress to api-server. Raise this value if concurrent-reconciles is set to be high.")
fs.IntVar(&c.Burst, "kube-api-burst", c.Burst,
"the burst for reconcile clients. Recommend setting it qps*2.")
fs.DurationVar(&c.InformerSyncPeriod, "informer-sync-period", c.InformerSyncPeriod,
"The re-sync period for informer in controller-runtime. This is a system-level configuration.")
}

View File

@@ -0,0 +1,53 @@
/*
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 config
import (
"time"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
"github.com/spf13/pflag"
)
// MultiClusterConfig contains multi-cluster configuration.
type MultiClusterConfig struct {
EnableClusterGateway bool
EnableClusterMetrics bool
ClusterMetricsInterval time.Duration
}
// NewMultiClusterConfig creates a new MultiClusterConfig with defaults.
func NewMultiClusterConfig() *MultiClusterConfig {
return &MultiClusterConfig{
EnableClusterGateway: false,
EnableClusterMetrics: false,
ClusterMetricsInterval: 15 * time.Second,
}
}
// AddFlags registers multi-cluster configuration flags.
func (c *MultiClusterConfig) AddFlags(fs *pflag.FlagSet) {
fs.BoolVar(&c.EnableClusterGateway, "enable-cluster-gateway", c.EnableClusterGateway,
"Enable cluster-gateway to use multicluster, disabled by default.")
fs.BoolVar(&c.EnableClusterMetrics, "enable-cluster-metrics", c.EnableClusterMetrics,
"Enable cluster-metrics-management to collect metrics from clusters with cluster-gateway, disabled by default. When this param is enabled, enable-cluster-gateway should be enabled")
fs.DurationVar(&c.ClusterMetricsInterval, "cluster-metrics-interval", c.ClusterMetricsInterval,
"The interval that ClusterMetricsMgr will collect metrics from clusters, default value is 15 seconds.")
// Also register additional multicluster flags from external package
pkgmulticluster.AddFlags(fs)
}

View File

@@ -0,0 +1,54 @@
/*
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 config
import (
"github.com/spf13/pflag"
"github.com/oam-dev/kubevela/pkg/oam"
)
// OAMConfig contains OAM-specific configuration.
type OAMConfig struct {
SystemDefinitionNamespace string
}
// NewOAMConfig creates a new OAMConfig with defaults.
func NewOAMConfig() *OAMConfig {
return &OAMConfig{
SystemDefinitionNamespace: "vela-system",
}
}
// AddFlags registers OAM configuration flags.
func (c *OAMConfig) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&c.SystemDefinitionNamespace,
"system-definition-namespace",
c.SystemDefinitionNamespace,
"Define the namespace of the system-level definition")
}
// SyncToOAMGlobals syncs the parsed configuration values to OAM package global variables.
// This should be called after flag parsing to ensure the OAM runtime uses the configured values.
//
// NOTE: This method exists for backward compatibility with legacy code that depends on global
// variables in the oam package. Ideally, configuration should be injected rather than using globals.
//
// The flow is: CLI flags -> OAMConfig struct fields -> oam globals (via this method)
func (c *OAMConfig) SyncToOAMGlobals() {
oam.SystemDefinitionNamespace = c.SystemDefinitionNamespace
}

View File

@@ -0,0 +1,55 @@
/*
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 config
import (
"github.com/spf13/pflag"
)
// ObservabilityConfig contains metrics and logging configuration.
type ObservabilityConfig struct {
MetricsAddr string
LogFilePath string
LogFileMaxSize uint64
LogDebug bool
DevLogs bool
}
// NewObservabilityConfig creates a new ObservabilityConfig with defaults.
func NewObservabilityConfig() *ObservabilityConfig {
return &ObservabilityConfig{
MetricsAddr: ":8080",
LogFilePath: "",
LogFileMaxSize: 1024,
LogDebug: false,
DevLogs: false,
}
}
// AddFlags registers observability configuration flags.
func (c *ObservabilityConfig) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&c.MetricsAddr, "metrics-addr", c.MetricsAddr,
"The address the metric endpoint binds to.")
fs.StringVar(&c.LogFilePath, "log-file-path", c.LogFilePath,
"The file to write logs to.")
fs.Uint64Var(&c.LogFileMaxSize, "log-file-max-size", c.LogFileMaxSize,
"Defines the maximum size a log file can grow to, Unit is megabytes.")
fs.BoolVar(&c.LogDebug, "log-debug", c.LogDebug,
"Enable debug logs for development purpose")
fs.BoolVar(&c.DevLogs, "dev-logs", c.DevLogs,
"Enable ANSI color formatting for console logs (ignored when log-file-path is set)")
}

View File

@@ -0,0 +1,58 @@
/*
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 config
import (
"github.com/spf13/pflag"
standardcontroller "github.com/oam-dev/kubevela/pkg/controller"
commonconfig "github.com/oam-dev/kubevela/pkg/controller/common"
)
// PerformanceConfig contains performance and optimization configuration.
type PerformanceConfig struct {
PerfEnabled bool
}
// NewPerformanceConfig creates a new PerformanceConfig with defaults.
func NewPerformanceConfig() *PerformanceConfig {
return &PerformanceConfig{
PerfEnabled: commonconfig.PerfEnabled,
}
}
// AddFlags registers performance configuration flags.
func (c *PerformanceConfig) AddFlags(fs *pflag.FlagSet) {
fs.BoolVar(&c.PerfEnabled,
"perf-enabled",
c.PerfEnabled,
"Enable performance logging for controllers, disabled by default.")
// Add optimization flags from the standard controller
standardcontroller.AddOptimizeFlags(fs)
}
// SyncToPerformanceGlobals syncs the parsed configuration values to performance package global variables.
// This should be called after flag parsing to ensure the performance monitoring uses the configured values.
//
// NOTE: This method exists for backward compatibility with legacy code that depends on global
// variables in the commonconfig package. Ideally, configuration should be injected rather than using globals.
//
// The flow is: CLI flags -> PerformanceConfig struct fields -> commonconfig globals (via this method)
func (c *PerformanceConfig) SyncToPerformanceGlobals() {
commonconfig.PerfEnabled = c.PerfEnabled
}

View File

@@ -0,0 +1,40 @@
/*
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 config
import (
"github.com/kubevela/pkg/util/profiling"
"github.com/spf13/pflag"
)
// ProfilingConfig contains profiling configuration.
// This wraps the external package's profiling configuration flags.
type ProfilingConfig struct {
// Note: The actual configuration is managed by the profiling package
// This is a wrapper to maintain consistency with our config pattern
}
// NewProfilingConfig creates a new ProfilingConfig with defaults.
func NewProfilingConfig() *ProfilingConfig {
return &ProfilingConfig{}
}
// AddFlags registers profiling configuration flags.
// Delegates to the external package's flag registration.
func (c *ProfilingConfig) AddFlags(fs *pflag.FlagSet) {
profiling.AddFlags(fs)
}

View File

@@ -0,0 +1,40 @@
/*
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 config
import (
ctrlrec "github.com/kubevela/pkg/controller/reconciler"
"github.com/spf13/pflag"
)
// ReconcileConfig contains controller reconciliation configuration.
// This wraps the external package's reconciler configuration flags.
type ReconcileConfig struct {
// Note: The actual configuration is managed by the ctrlrec package
// This is a wrapper to maintain consistency with our config pattern
}
// NewReconcileConfig creates a new ReconcileConfig with defaults.
func NewReconcileConfig() *ReconcileConfig {
return &ReconcileConfig{}
}
// AddFlags registers reconcile configuration flags.
// Delegates to the external package's flag registration.
func (c *ReconcileConfig) AddFlags(fs *pflag.FlagSet) {
ctrlrec.AddFlags(fs)
}

View File

@@ -0,0 +1,55 @@
/*
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 config
import (
"github.com/spf13/pflag"
"github.com/oam-dev/kubevela/pkg/resourcekeeper"
)
// ResourceConfig contains resource management configuration.
type ResourceConfig struct {
MaxDispatchConcurrent int
}
// NewResourceConfig creates a new ResourceConfig with defaults.
func NewResourceConfig() *ResourceConfig {
return &ResourceConfig{
MaxDispatchConcurrent: 10,
}
}
// AddFlags registers resource configuration flags.
func (c *ResourceConfig) AddFlags(fs *pflag.FlagSet) {
fs.IntVar(&c.MaxDispatchConcurrent,
"max-dispatch-concurrent",
c.MaxDispatchConcurrent,
"Set the max dispatch concurrent number, default is 10")
}
// SyncToResourceGlobals syncs the parsed configuration values to resource package global variables.
// This should be called after flag parsing to ensure the resource keeper uses the configured values.
//
// NOTE: This method exists for backward compatibility with legacy code that depends on global
// variables in the resourcekeeper package. The long-term goal should be to refactor to use
// dependency injection rather than globals.
//
// The flow is: CLI flags -> ResourceConfig struct fields -> resourcekeeper globals (via this method)
func (c *ResourceConfig) SyncToResourceGlobals() {
resourcekeeper.MaxDispatchConcurrent = c.MaxDispatchConcurrent
}

View File

@@ -0,0 +1,65 @@
/*
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 config
import (
"time"
"github.com/spf13/pflag"
)
// ServerConfig contains server-level configuration.
type ServerConfig struct {
HealthAddr string
StorageDriver string
EnableLeaderElection bool
LeaderElectionNamespace string
LeaseDuration time.Duration
RenewDeadline time.Duration
RetryPeriod time.Duration
}
// NewServerConfig creates a new ServerConfig with defaults.
func NewServerConfig() *ServerConfig {
return &ServerConfig{
HealthAddr: ":9440",
StorageDriver: "Local",
EnableLeaderElection: false,
LeaderElectionNamespace: "",
LeaseDuration: 15 * time.Second,
RenewDeadline: 10 * time.Second,
RetryPeriod: 2 * time.Second,
}
}
// AddFlags registers server configuration flags.
func (c *ServerConfig) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&c.HealthAddr, "health-addr", c.HealthAddr,
"The address the health endpoint binds to.")
fs.StringVar(&c.StorageDriver, "storage-driver", c.StorageDriver,
"Application storage driver.")
fs.BoolVar(&c.EnableLeaderElection, "enable-leader-election", c.EnableLeaderElection,
"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
fs.StringVar(&c.LeaderElectionNamespace, "leader-election-namespace", c.LeaderElectionNamespace,
"Determines the namespace in which the leader election configmap will be created.")
fs.DurationVar(&c.LeaseDuration, "leader-election-lease-duration", c.LeaseDuration,
"The duration that non-leader candidates will wait to force acquire leadership")
fs.DurationVar(&c.RenewDeadline, "leader-election-renew-deadline", c.RenewDeadline,
"The duration that the acting controlplane will retry refreshing leadership before giving up")
fs.DurationVar(&c.RetryPeriod, "leader-election-retry-period", c.RetryPeriod,
"The duration the LeaderElector clients should wait between tries of actions")
}

View File

@@ -0,0 +1,40 @@
/*
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 config
import (
"github.com/kubevela/pkg/controller/sharding"
"github.com/spf13/pflag"
)
// ShardingConfig contains controller sharding configuration.
// This wraps the external package's sharding configuration flags.
type ShardingConfig struct {
// Note: The actual configuration is managed by the sharding package
// This is a wrapper to maintain consistency with our config pattern
}
// NewShardingConfig creates a new ShardingConfig with defaults.
func NewShardingConfig() *ShardingConfig {
return &ShardingConfig{}
}
// AddFlags registers sharding configuration flags.
// Delegates to the external package's flag registration.
func (c *ShardingConfig) AddFlags(fs *pflag.FlagSet) {
sharding.AddFlags(fs)
}

Some files were not shown because too many files have changed in this diff Show More