From 668ddc552ece9bf2406a30be323c1047d4667b85 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 17:23:37 +0300 Subject: [PATCH 01/11] refactor(installer): remove CRDs from Helm chart, rely on operator --install-crds Remove the crds/ directory from the cozy-installer Helm chart. The operator already installs embedded CRDs via server-side apply on every startup with the --install-crds=true flag, making the Helm crds/ directory redundant. Convert templates/packagesource.yaml to a Helm post-install/post-upgrade hook so it is applied after the operator has started and installed CRDs. Update codegen to write CRDs only to internal/crdinstall/manifests/ (single source of truth) and update the Makefile to source build assets from there. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- Makefile | 22 +- hack/update-codegen.sh | 6 +- packages/core/installer/crds/.gitattributes | 1 - .../installer/crds/cozystack.io_packages.yaml | 171 ------------ .../crds/cozystack.io_packagesources.yaml | 250 ------------------ .../templates/cozystack-operator.yaml | 7 +- .../installer/templates/packagesource.yaml | 2 + 7 files changed, 15 insertions(+), 444 deletions(-) delete mode 100644 packages/core/installer/crds/.gitattributes delete mode 100644 packages/core/installer/crds/cozystack.io_packages.yaml delete mode 100644 packages/core/installer/crds/cozystack.io_packagesources.yaml diff --git a/Makefile b/Makefile index 73bd0bea5..226ee9d0d 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: manifests assets unit-tests helm-unit-tests verify-crds +.PHONY: manifests assets unit-tests helm-unit-tests include hack/common-envs.mk @@ -38,24 +38,24 @@ build: build-deps manifests: mkdir -p _out/assets - cat packages/core/installer/crds/*.yaml > _out/assets/cozystack-crds.yaml + cat internal/crdinstall/manifests/*.yaml > _out/assets/cozystack-crds.yaml # Talos variant (default) helm template installer packages/core/installer -n cozy-system \ - -s templates/cozystack-operator.yaml \ - -s templates/packagesource.yaml \ + --show-only templates/cozystack-operator.yaml \ + --show-only templates/packagesource.yaml \ > _out/assets/cozystack-operator-talos.yaml # Generic Kubernetes variant (k3s, kubeadm, RKE2) helm template installer packages/core/installer -n cozy-system \ --set cozystackOperator.variant=generic \ --set cozystack.apiServerHost=REPLACE_ME \ - -s templates/cozystack-operator.yaml \ - -s templates/packagesource.yaml \ + --show-only templates/cozystack-operator.yaml \ + --show-only templates/packagesource.yaml \ > _out/assets/cozystack-operator-generic.yaml # Hosted variant (managed Kubernetes) helm template installer packages/core/installer -n cozy-system \ --set cozystackOperator.variant=hosted \ - -s templates/cozystack-operator.yaml \ - -s templates/packagesource.yaml \ + --show-only templates/cozystack-operator.yaml \ + --show-only templates/packagesource.yaml \ > _out/assets/cozystack-operator-hosted.yaml cozypkg: @@ -80,11 +80,7 @@ test: make -C packages/core/testing apply make -C packages/core/testing test -verify-crds: - @diff --recursive packages/core/installer/crds/ internal/crdinstall/manifests/ --exclude='.*' \ - || (echo "ERROR: CRD manifests out of sync. Run 'make generate' to fix." && exit 1) - -unit-tests: helm-unit-tests verify-crds +unit-tests: helm-unit-tests helm-unit-tests: hack/helm-unit-tests.sh diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index b7f96691a..6a6fc3be2 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -24,8 +24,7 @@ API_KNOWN_VIOLATIONS_DIR="${API_KNOWN_VIOLATIONS_DIR:-"${SCRIPT_ROOT}/api/api-ru UPDATE_API_KNOWN_VIOLATIONS="${UPDATE_API_KNOWN_VIOLATIONS:-true}" CONTROLLER_GEN="go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.16.4" TMPDIR=$(mktemp -d) -OPERATOR_CRDDIR=packages/core/installer/crds -OPERATOR_EMBEDDIR=internal/crdinstall/manifests +OPERATOR_CRDDIR=internal/crdinstall/manifests COZY_CONTROLLER_CRDDIR=packages/system/cozystack-controller/definitions COZY_RD_CRDDIR=packages/system/application-definition-crd/definition BACKUPS_CORE_CRDDIR=packages/system/backup-controller/definitions @@ -74,9 +73,6 @@ $CONTROLLER_GEN rbac:roleName=manager-role crd paths="./api/..." output:crd:arti mv ${TMPDIR}/cozystack.io_packages.yaml ${OPERATOR_CRDDIR}/cozystack.io_packages.yaml mv ${TMPDIR}/cozystack.io_packagesources.yaml ${OPERATOR_CRDDIR}/cozystack.io_packagesources.yaml -cp ${OPERATOR_CRDDIR}/cozystack.io_packages.yaml ${OPERATOR_EMBEDDIR}/cozystack.io_packages.yaml -cp ${OPERATOR_CRDDIR}/cozystack.io_packagesources.yaml ${OPERATOR_EMBEDDIR}/cozystack.io_packagesources.yaml - mv ${TMPDIR}/cozystack.io_applicationdefinitions.yaml \ ${COZY_RD_CRDDIR}/cozystack.io_applicationdefinitions.yaml diff --git a/packages/core/installer/crds/.gitattributes b/packages/core/installer/crds/.gitattributes deleted file mode 100644 index f581feca0..000000000 --- a/packages/core/installer/crds/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.yaml linguist-generated diff --git a/packages/core/installer/crds/cozystack.io_packages.yaml b/packages/core/installer/crds/cozystack.io_packages.yaml deleted file mode 100644 index cb7e27631..000000000 --- a/packages/core/installer/crds/cozystack.io_packages.yaml +++ /dev/null @@ -1,171 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.16.4 - name: packages.cozystack.io -spec: - group: cozystack.io - names: - kind: Package - listKind: PackageList - plural: packages - shortNames: - - pkg - - pkgs - singular: package - scope: Cluster - versions: - - additionalPrinterColumns: - - description: Selected variant - jsonPath: .spec.variant - name: Variant - type: string - - description: Ready status - jsonPath: .status.conditions[?(@.type=='Ready')].status - name: Ready - type: string - - description: Ready message - jsonPath: .status.conditions[?(@.type=='Ready')].message - name: Status - type: string - name: v1alpha1 - schema: - openAPIV3Schema: - description: Package is the Schema for the packages 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 - 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 - type: string - metadata: - type: object - spec: - description: PackageSpec defines the desired state of Package - properties: - components: - additionalProperties: - description: PackageComponent defines overrides for a specific component - properties: - enabled: - description: |- - Enabled indicates whether this component should be installed - If false, the component will be disabled even if it's defined in the PackageSource - type: boolean - values: - description: |- - Values contains Helm chart values as a JSON object - These values will be merged with the default values from the PackageSource - x-kubernetes-preserve-unknown-fields: true - type: object - description: |- - Components is a map of release name to component overrides - Allows overriding values and enabling/disabling specific components from the PackageSource - type: object - ignoreDependencies: - description: |- - IgnoreDependencies is a list of package source dependencies to ignore - Dependencies listed here will not be installed even if they are specified in the PackageSource - items: - type: string - type: array - variant: - description: |- - Variant is the name of the variant to use from the PackageSource - If not specified, defaults to "default" - type: string - type: object - status: - description: PackageStatus defines the observed state of Package - properties: - conditions: - description: Conditions represents the latest available observations - of a Package's state - items: - description: Condition contains details for one aspect of the current - state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - type: array - dependencies: - additionalProperties: - description: DependencyStatus represents the readiness status of - a dependency - properties: - ready: - description: Ready indicates whether the dependency is ready - type: boolean - required: - - ready - type: object - description: |- - Dependencies tracks the readiness status of each dependency - Key is the dependency package name, value indicates if the dependency is ready - type: object - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/packages/core/installer/crds/cozystack.io_packagesources.yaml b/packages/core/installer/crds/cozystack.io_packagesources.yaml deleted file mode 100644 index 0acfcdd22..000000000 --- a/packages/core/installer/crds/cozystack.io_packagesources.yaml +++ /dev/null @@ -1,250 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.16.4 - name: packagesources.cozystack.io -spec: - group: cozystack.io - names: - kind: PackageSource - listKind: PackageSourceList - plural: packagesources - shortNames: - - pks - singular: packagesource - scope: Cluster - versions: - - additionalPrinterColumns: - - description: Package variants (comma-separated) - jsonPath: .status.variants - name: Variants - type: string - - description: Ready status - jsonPath: .status.conditions[?(@.type=='Ready')].status - name: Ready - type: string - - description: Ready message - jsonPath: .status.conditions[?(@.type=='Ready')].message - name: Status - type: string - name: v1alpha1 - schema: - openAPIV3Schema: - description: PackageSource is the Schema for the packagesources 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 - 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 - type: string - metadata: - type: object - spec: - description: PackageSourceSpec defines the desired state of PackageSource - properties: - sourceRef: - description: SourceRef is the source reference for the package source - charts - properties: - kind: - description: Kind of the source reference - enum: - - GitRepository - - OCIRepository - type: string - name: - description: Name of the source reference - type: string - namespace: - description: Namespace of the source reference - type: string - path: - description: |- - Path is the base path where packages are located in the source. - For GitRepository, defaults to "packages" if not specified. - For OCIRepository, defaults to empty string (root) if not specified. - type: string - required: - - kind - - name - - namespace - type: object - variants: - description: |- - Variants is a list of package source variants - Each variant defines components, applications, dependencies, and libraries for a specific configuration - items: - description: Variant defines a single variant configuration - properties: - components: - description: Components is a list of Helm releases to be installed - as part of this variant - items: - description: Component defines a single Helm release component - within a package source - properties: - install: - description: Install defines installation parameters for - this component - properties: - dependsOn: - description: DependsOn is a list of component names - that must be installed before this component - items: - type: string - type: array - namespace: - description: Namespace is the Kubernetes namespace - where the release will be installed - type: string - privileged: - description: Privileged indicates whether this release - requires privileged access - type: boolean - releaseName: - description: |- - ReleaseName is the name of the HelmRelease resource that will be created - If not specified, defaults to the component Name field - type: string - type: object - libraries: - description: |- - Libraries is a list of library names that this component depends on - These libraries must be defined at the variant level - items: - type: string - type: array - name: - description: Name is the unique identifier for this component - within the package source - type: string - path: - description: Path is the path to the Helm chart directory - type: string - valuesFiles: - description: ValuesFiles is a list of values file names - to use - items: - type: string - type: array - required: - - name - - path - type: object - type: array - dependsOn: - description: |- - DependsOn is a list of package source dependencies - For example: "cozystack.networking" - items: - type: string - type: array - libraries: - description: Libraries is a list of Helm library charts used - by components in this variant - items: - description: Library defines a Helm library chart - properties: - name: - description: Name is the optional name for library placed - in charts - type: string - path: - description: Path is the path to the library chart directory - type: string - required: - - path - type: object - type: array - name: - description: Name is the unique identifier for this variant - type: string - required: - - name - type: object - type: array - type: object - status: - description: PackageSourceStatus defines the observed state of PackageSource - properties: - conditions: - description: Conditions represents the latest available observations - of a PackageSource's state - items: - description: Condition contains details for one aspect of the current - state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - type: array - variants: - description: |- - Variants is a comma-separated list of package variant names - This field is populated by the controller based on spec.variants keys - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/packages/core/installer/templates/cozystack-operator.yaml b/packages/core/installer/templates/cozystack-operator.yaml index 5cd471cff..b33d186a0 100644 --- a/packages/core/installer/templates/cozystack-operator.yaml +++ b/packages/core/installer/templates/cozystack-operator.yaml @@ -53,10 +53,9 @@ spec: args: - --leader-elect=true - --install-flux=true - # CRDs are also in crds/ for initial helm install, but Helm never updates - # them on upgrade and never deletes them on uninstall. The operator applies - # embedded CRDs via server-side apply on every startup, ensuring they stay - # up to date. To fully remove CRDs, delete them manually after helm uninstall. + # The operator applies embedded CRDs via server-side apply on every + # startup, ensuring they stay up to date. + # To fully remove CRDs, delete them manually after helm uninstall. - --install-crds=true - --metrics-bind-address=0 - --health-probe-bind-address=0 diff --git a/packages/core/installer/templates/packagesource.yaml b/packages/core/installer/templates/packagesource.yaml index 65b1e4bfd..daaf7eb82 100644 --- a/packages/core/installer/templates/packagesource.yaml +++ b/packages/core/installer/templates/packagesource.yaml @@ -8,6 +8,8 @@ kind: PackageSource metadata: name: cozystack.cozystack-platform annotations: + "helm.sh/hook": post-install,post-upgrade + "helm.sh/hook-delete-policy": before-hook-creation operator.cozystack.io/skip-cozystack-values: "true" spec: sourceRef: From 655133b81cf8a66fd3519704fdac129d52d9fce2 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 17:38:23 +0300 Subject: [PATCH 02/11] fix(installer): move PackageSource creation from Helm template to operator Replace the Helm hook approach with programmatic PackageSource creation in the operator startup sequence. Helm hooks are unsuitable for persistent resources like PackageSource because before-hook-creation policy causes cascade deletion of owned ArtifactGenerators during upgrades. The operator now creates the platform PackageSource after installing CRDs and the Flux source resource, using the same create-or-update pattern as installPlatformSourceResource(). The sourceRef.kind is derived from the platform source URL (OCIRepository for oci://, GitRepository for git). Also fix stale comment in e2e test referencing deleted crds/ directory. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- Makefile | 3 - cmd/cozystack-operator/main.go | 126 ++++++++++++++++++ hack/e2e-install-cozystack.bats | 2 +- .../installer/templates/packagesource.yaml | 59 -------- 4 files changed, 127 insertions(+), 63 deletions(-) delete mode 100644 packages/core/installer/templates/packagesource.yaml diff --git a/Makefile b/Makefile index 226ee9d0d..ca48197c3 100644 --- a/Makefile +++ b/Makefile @@ -42,20 +42,17 @@ manifests: # Talos variant (default) helm template installer packages/core/installer -n cozy-system \ --show-only templates/cozystack-operator.yaml \ - --show-only templates/packagesource.yaml \ > _out/assets/cozystack-operator-talos.yaml # Generic Kubernetes variant (k3s, kubeadm, RKE2) helm template installer packages/core/installer -n cozy-system \ --set cozystackOperator.variant=generic \ --set cozystack.apiServerHost=REPLACE_ME \ --show-only templates/cozystack-operator.yaml \ - --show-only templates/packagesource.yaml \ > _out/assets/cozystack-operator-generic.yaml # Hosted variant (managed Kubernetes) helm template installer packages/core/installer -n cozy-system \ --set cozystackOperator.variant=hosted \ --show-only templates/cozystack-operator.yaml \ - --show-only templates/packagesource.yaml \ > _out/assets/cozystack-operator-hosted.yaml cozypkg: diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index d3c40f7ef..ba5730e20 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -222,6 +222,20 @@ func main() { } else { setupLog.Info("Platform source resource installation completed successfully") } + + // Create platform PackageSource that references the source resource + setupLog.Info("Creating platform PackageSource", "platformSourceName", platformSourceName) + sourceType, _, _ := parsePlatformSourceURL(platformSourceURL) + sourceRefKind := "OCIRepository" + if sourceType == "git" { + sourceRefKind = "GitRepository" + } + if err := installPlatformPackageSource(installCtx, directClient, platformSourceName, sourceRefKind); err != nil { + setupLog.Error(err, "failed to create platform PackageSource") + os.Exit(1) + } else { + setupLog.Info("Platform PackageSource creation completed successfully") + } } // Setup PackageSource reconciler @@ -552,3 +566,115 @@ func generateGitRepository(name, repoURL string, refMap map[string]string) (*sou return obj, nil } + +// installPlatformPackageSource creates the platform PackageSource resource +// that references the Flux source resource (OCIRepository or GitRepository). +func installPlatformPackageSource(ctx context.Context, k8sClient client.Client, platformSourceName, sourceRefKind string) error { + logger := log.FromContext(ctx) + + packageSourceName := "cozystack." + platformSourceName + + ps := &cozyv1alpha1.PackageSource{ + TypeMeta: metav1.TypeMeta{ + APIVersion: cozyv1alpha1.GroupVersion.String(), + Kind: "PackageSource", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: packageSourceName, + Annotations: map[string]string{ + "operator.cozystack.io/skip-cozystack-values": "true", + }, + }, + Spec: cozyv1alpha1.PackageSourceSpec{ + SourceRef: &cozyv1alpha1.PackageSourceRef{ + Kind: sourceRefKind, + Name: platformSourceName, + Namespace: "cozy-system", + Path: "/", + }, + Variants: []cozyv1alpha1.Variant{ + { + Name: "default", + Components: []cozyv1alpha1.Component{ + { + Name: "platform", + Path: "core/platform", + Install: &cozyv1alpha1.ComponentInstall{ + Namespace: "cozy-system", + ReleaseName: "cozystack-platform", + }, + ValuesFiles: []string{"values.yaml"}, + }, + }, + }, + { + Name: "isp-full", + Components: []cozyv1alpha1.Component{ + { + Name: "platform", + Path: "core/platform", + Install: &cozyv1alpha1.ComponentInstall{ + Namespace: "cozy-system", + ReleaseName: "cozystack-platform", + }, + ValuesFiles: []string{"values.yaml", "values-isp-full.yaml"}, + }, + }, + }, + { + Name: "isp-hosted", + Components: []cozyv1alpha1.Component{ + { + Name: "platform", + Path: "core/platform", + Install: &cozyv1alpha1.ComponentInstall{ + Namespace: "cozy-system", + ReleaseName: "cozystack-platform", + }, + ValuesFiles: []string{"values.yaml", "values-isp-hosted.yaml"}, + }, + }, + }, + { + Name: "isp-full-generic", + Components: []cozyv1alpha1.Component{ + { + Name: "platform", + Path: "core/platform", + Install: &cozyv1alpha1.ComponentInstall{ + Namespace: "cozy-system", + ReleaseName: "cozystack-platform", + }, + ValuesFiles: []string{"values.yaml", "values-isp-full-generic.yaml"}, + }, + }, + }, + }, + }, + } + + logger.Info("Applying platform PackageSource", "name", packageSourceName) + + existing := &cozyv1alpha1.PackageSource{} + key := client.ObjectKeyFromObject(ps) + + err := k8sClient.Get(ctx, key, existing) + if err != nil { + if client.IgnoreNotFound(err) == nil { + if err := k8sClient.Create(ctx, ps); err != nil { + return fmt.Errorf("failed to create PackageSource %s: %w", packageSourceName, err) + } + logger.Info("Created platform PackageSource", "name", packageSourceName) + } else { + return fmt.Errorf("failed to check if PackageSource exists: %w", err) + } + } else { + ps.SetResourceVersion(existing.GetResourceVersion()) + if err := k8sClient.Update(ctx, ps); err != nil { + return fmt.Errorf("failed to update PackageSource %s: %w", packageSourceName, err) + } + logger.Info("Updated platform PackageSource", "name", packageSourceName) + } + + return nil +} diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index 5e518cad3..5a705906c 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -8,7 +8,7 @@ } @test "Install Cozystack" { - # Install cozy-installer chart (CRDs from crds/ are applied automatically) + # Install cozy-installer chart (operator installs CRDs on startup via --install-crds) helm upgrade installer packages/core/installer \ --install \ --namespace cozy-system \ diff --git a/packages/core/installer/templates/packagesource.yaml b/packages/core/installer/templates/packagesource.yaml deleted file mode 100644 index daaf7eb82..000000000 --- a/packages/core/installer/templates/packagesource.yaml +++ /dev/null @@ -1,59 +0,0 @@ -{{- $validVariants := list "talos" "generic" "hosted" -}} -{{- if not (has .Values.cozystackOperator.variant $validVariants) -}} -{{- fail (printf "Invalid cozystackOperator.variant %q: must be one of talos, generic, hosted" .Values.cozystackOperator.variant) -}} -{{- end -}} ---- -apiVersion: cozystack.io/v1alpha1 -kind: PackageSource -metadata: - name: cozystack.cozystack-platform - annotations: - "helm.sh/hook": post-install,post-upgrade - "helm.sh/hook-delete-policy": before-hook-creation - operator.cozystack.io/skip-cozystack-values: "true" -spec: - sourceRef: - kind: OCIRepository - name: cozystack-platform - namespace: cozy-system - path: / - variants: - - name: default - components: - - install: - namespace: cozy-system - releaseName: cozystack-platform - name: platform - path: core/platform - valuesFiles: - - values.yaml - - name: isp-full - components: - - install: - namespace: cozy-system - releaseName: cozystack-platform - name: platform - path: core/platform - valuesFiles: - - values.yaml - - values-isp-full.yaml - - name: isp-hosted - components: - - install: - namespace: cozy-system - releaseName: cozystack-platform - name: platform - path: core/platform - valuesFiles: - - values.yaml - - values-isp-hosted.yaml - - name: isp-full-generic - components: - - install: - namespace: cozy-system - releaseName: cozystack-platform - name: platform - path: core/platform - valuesFiles: - - values.yaml - - values-isp-full-generic.yaml From 0e8b6515afaa0131fbbd9665ebfa5111d602b60c Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 17:42:31 +0300 Subject: [PATCH 03/11] fix(installer): handle parsePlatformSourceURL error, restore variant validation Check error from parsePlatformSourceURL instead of discarding it, preventing silent fallback to OCIRepository on invalid URLs. Move variant validation from deleted packagesource.yaml to cozystack-operator.yaml template so invalid cozystackOperator.variant values still fail at helm template/install time. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main.go | 6 +++++- packages/core/installer/templates/cozystack-operator.yaml | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index ba5730e20..cb19a3d30 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -225,7 +225,11 @@ func main() { // Create platform PackageSource that references the source resource setupLog.Info("Creating platform PackageSource", "platformSourceName", platformSourceName) - sourceType, _, _ := parsePlatformSourceURL(platformSourceURL) + sourceType, _, err := parsePlatformSourceURL(platformSourceURL) + if err != nil { + setupLog.Error(err, "failed to parse platform source URL for PackageSource creation") + os.Exit(1) + } sourceRefKind := "OCIRepository" if sourceType == "git" { sourceRefKind = "GitRepository" diff --git a/packages/core/installer/templates/cozystack-operator.yaml b/packages/core/installer/templates/cozystack-operator.yaml index b33d186a0..fcd499a80 100644 --- a/packages/core/installer/templates/cozystack-operator.yaml +++ b/packages/core/installer/templates/cozystack-operator.yaml @@ -1,3 +1,7 @@ +{{- $validVariants := list "talos" "generic" "hosted" -}} +{{- if not (has .Values.cozystackOperator.variant $validVariants) -}} +{{- fail (printf "Invalid cozystackOperator.variant %q: must be one of talos, generic, hosted" .Values.cozystackOperator.variant) -}} +{{- end -}} --- apiVersion: v1 kind: Namespace From 8450830f06d6c3cd0325c21966a028acd0642334 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 17:50:09 +0300 Subject: [PATCH 04/11] fix(installer): add CRD wait in E2E, unit tests for PackageSource creation Add explicit CRD wait (kubectl wait crd --for=condition=Established) in E2E test before creating Package resources, preventing race condition between operator CRD installation and resource creation. Add unit tests for installPlatformPackageSource covering create, update, and GitRepository sourceRef kind scenarios. Document that hardcoded variant list is an intentional design choice matching the previous Helm template behavior. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main.go | 4 + cmd/cozystack-operator/main_test.go | 152 ++++++++++++++++++++++++++++ hack/e2e-install-cozystack.bats | 4 + 3 files changed, 160 insertions(+) create mode 100644 cmd/cozystack-operator/main_test.go diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index cb19a3d30..fb45b96c5 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -573,6 +573,10 @@ func generateGitRepository(name, repoURL string, refMap map[string]string) (*sou // installPlatformPackageSource creates the platform PackageSource resource // that references the Flux source resource (OCIRepository or GitRepository). +// +// The variant list is intentionally hardcoded here. These are platform-defined +// deployment profiles (not user-extensible), matching what was previously in +// the Helm template. Changes require a new operator build and release. func installPlatformPackageSource(ctx context.Context, k8sClient client.Client, platformSourceName, sourceRefKind string) error { logger := log.FromContext(ctx) diff --git a/cmd/cozystack-operator/main_test.go b/cmd/cozystack-operator/main_test.go new file mode 100644 index 000000000..da1769f21 --- /dev/null +++ b/cmd/cozystack-operator/main_test.go @@ -0,0 +1,152 @@ +/* +Copyright 2025 The Cozystack 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 main + +import ( + "context" + "testing" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func newTestScheme() *runtime.Scheme { + s := runtime.NewScheme() + _ = cozyv1alpha1.AddToScheme(s) + return s +} + +func TestInstallPlatformPackageSource_Creates(t *testing.T) { + s := newTestScheme() + k8sClient := fake.NewClientBuilder().WithScheme(s).Build() + + err := installPlatformPackageSource(context.Background(), k8sClient, "cozystack-platform", "OCIRepository") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + ps := &cozyv1alpha1.PackageSource{} + if err := k8sClient.Get(context.Background(), client.ObjectKey{Name: "cozystack.cozystack-platform"}, ps); err != nil { + t.Fatalf("PackageSource not found: %v", err) + } + + // Verify name + if ps.Name != "cozystack.cozystack-platform" { + t.Errorf("expected name %q, got %q", "cozystack.cozystack-platform", ps.Name) + } + + // Verify annotation + if ps.Annotations["operator.cozystack.io/skip-cozystack-values"] != "true" { + t.Errorf("expected skip-cozystack-values annotation to be 'true', got %q", ps.Annotations["operator.cozystack.io/skip-cozystack-values"]) + } + + // Verify sourceRef + if ps.Spec.SourceRef == nil { + t.Fatal("expected SourceRef to be set") + } + if ps.Spec.SourceRef.Kind != "OCIRepository" { + t.Errorf("expected sourceRef.kind %q, got %q", "OCIRepository", ps.Spec.SourceRef.Kind) + } + if ps.Spec.SourceRef.Name != "cozystack-platform" { + t.Errorf("expected sourceRef.name %q, got %q", "cozystack-platform", ps.Spec.SourceRef.Name) + } + if ps.Spec.SourceRef.Namespace != "cozy-system" { + t.Errorf("expected sourceRef.namespace %q, got %q", "cozy-system", ps.Spec.SourceRef.Namespace) + } + if ps.Spec.SourceRef.Path != "/" { + t.Errorf("expected sourceRef.path %q, got %q", "/", ps.Spec.SourceRef.Path) + } + + // Verify variants + expectedVariants := []string{"default", "isp-full", "isp-hosted", "isp-full-generic"} + if len(ps.Spec.Variants) != len(expectedVariants) { + t.Fatalf("expected %d variants, got %d", len(expectedVariants), len(ps.Spec.Variants)) + } + for i, name := range expectedVariants { + if ps.Spec.Variants[i].Name != name { + t.Errorf("expected variant[%d].name %q, got %q", i, name, ps.Spec.Variants[i].Name) + } + if len(ps.Spec.Variants[i].Components) != 1 { + t.Errorf("expected variant[%d] to have 1 component, got %d", i, len(ps.Spec.Variants[i].Components)) + } + } +} + +func TestInstallPlatformPackageSource_Updates(t *testing.T) { + s := newTestScheme() + + existing := &cozyv1alpha1.PackageSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "cozystack.cozystack-platform", + ResourceVersion: "1", + }, + Spec: cozyv1alpha1.PackageSourceSpec{ + SourceRef: &cozyv1alpha1.PackageSourceRef{ + Kind: "OCIRepository", + Name: "old-name", + Namespace: "cozy-system", + }, + }, + } + + k8sClient := fake.NewClientBuilder().WithScheme(s).WithObjects(existing).Build() + + err := installPlatformPackageSource(context.Background(), k8sClient, "cozystack-platform", "OCIRepository") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + ps := &cozyv1alpha1.PackageSource{} + if err := k8sClient.Get(context.Background(), client.ObjectKey{Name: "cozystack.cozystack-platform"}, ps); err != nil { + t.Fatalf("PackageSource not found: %v", err) + } + + // Verify sourceRef was updated + if ps.Spec.SourceRef.Name != "cozystack-platform" { + t.Errorf("expected updated sourceRef.name %q, got %q", "cozystack-platform", ps.Spec.SourceRef.Name) + } + + // Verify all 4 variants are present after update + if len(ps.Spec.Variants) != 4 { + t.Errorf("expected 4 variants after update, got %d", len(ps.Spec.Variants)) + } +} + +func TestInstallPlatformPackageSource_GitRepository(t *testing.T) { + s := newTestScheme() + k8sClient := fake.NewClientBuilder().WithScheme(s).Build() + + err := installPlatformPackageSource(context.Background(), k8sClient, "my-source", "GitRepository") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + ps := &cozyv1alpha1.PackageSource{} + if err := k8sClient.Get(context.Background(), client.ObjectKey{Name: "cozystack.my-source"}, ps); err != nil { + t.Fatalf("PackageSource not found: %v", err) + } + + if ps.Spec.SourceRef.Kind != "GitRepository" { + t.Errorf("expected sourceRef.kind %q, got %q", "GitRepository", ps.Spec.SourceRef.Kind) + } + if ps.Spec.SourceRef.Name != "my-source" { + t.Errorf("expected sourceRef.name %q, got %q", "my-source", ps.Spec.SourceRef.Name) + } +} diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index 5a705906c..815622bc4 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -19,6 +19,10 @@ # Verify the operator deployment is available kubectl wait deployment/cozystack-operator -n cozy-system --timeout=1m --for=condition=Available + # Wait for operator to install CRDs (happens at startup before reconcile loop) + kubectl wait crd/packages.cozystack.io --for=condition=Established --timeout=2m + kubectl wait crd/packagesources.cozystack.io --for=condition=Established --timeout=2m + # Create platform Package with isp-full variant kubectl apply -f - < Date: Thu, 19 Feb 2026 17:54:33 +0300 Subject: [PATCH 05/11] fix(operator): use SSA for PackageSource, separate context, unconditional creation Switch installPlatformPackageSource to server-side apply (SSA) with field manager, matching the pattern used in crdinstall. SSA is idempotent and preserves metadata fields managed by other controllers. Create PackageSource unconditionally (not only when platformSourceURL is set), matching the previous Helm template behavior where PackageSource was always created regardless of source URL configuration. Use a dedicated context with its own 2-minute timeout for PackageSource creation, separate from the platform source resource installation. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main.go | 55 +++++++++++++---------------- cmd/cozystack-operator/main_test.go | 8 +++++ 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index fb45b96c5..10102bc0e 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -222,24 +222,28 @@ func main() { } else { setupLog.Info("Platform source resource installation completed successfully") } + } - // Create platform PackageSource that references the source resource - setupLog.Info("Creating platform PackageSource", "platformSourceName", platformSourceName) - sourceType, _, err := parsePlatformSourceURL(platformSourceURL) - if err != nil { - setupLog.Error(err, "failed to parse platform source URL for PackageSource creation") - os.Exit(1) - } + // Create platform PackageSource unconditionally (it was previously created + // by a Helm template regardless of platformSourceURL). Derive sourceRefKind + // from URL when available, default to OCIRepository otherwise. + { sourceRefKind := "OCIRepository" - if sourceType == "git" { - sourceRefKind = "GitRepository" + if platformSourceURL != "" { + sourceType, _, _ := parsePlatformSourceURL(platformSourceURL) + // Error already checked by installPlatformSourceResource above + if sourceType == "git" { + sourceRefKind = "GitRepository" + } } - if err := installPlatformPackageSource(installCtx, directClient, platformSourceName, sourceRefKind); err != nil { + setupLog.Info("Creating platform PackageSource", "platformSourceName", platformSourceName) + psCtx, psCancel := context.WithTimeout(mgrCtx, 2*time.Minute) + defer psCancel() + if err := installPlatformPackageSource(psCtx, directClient, platformSourceName, sourceRefKind); err != nil { setupLog.Error(err, "failed to create platform PackageSource") os.Exit(1) - } else { - setupLog.Info("Platform PackageSource creation completed successfully") } + setupLog.Info("Platform PackageSource creation completed successfully") } // Setup PackageSource reconciler @@ -663,26 +667,15 @@ func installPlatformPackageSource(ctx context.Context, k8sClient client.Client, logger.Info("Applying platform PackageSource", "name", packageSourceName) - existing := &cozyv1alpha1.PackageSource{} - key := client.ObjectKeyFromObject(ps) - - err := k8sClient.Get(ctx, key, existing) - if err != nil { - if client.IgnoreNotFound(err) == nil { - if err := k8sClient.Create(ctx, ps); err != nil { - return fmt.Errorf("failed to create PackageSource %s: %w", packageSourceName, err) - } - logger.Info("Created platform PackageSource", "name", packageSourceName) - } else { - return fmt.Errorf("failed to check if PackageSource exists: %w", err) - } - } else { - ps.SetResourceVersion(existing.GetResourceVersion()) - if err := k8sClient.Update(ctx, ps); err != nil { - return fmt.Errorf("failed to update PackageSource %s: %w", packageSourceName, err) - } - logger.Info("Updated platform PackageSource", "name", packageSourceName) + patchOptions := &client.PatchOptions{ + FieldManager: "cozystack-operator", + Force: func() *bool { b := true; return &b }(), } + if err := k8sClient.Patch(ctx, ps, client.Apply, patchOptions); err != nil { + return fmt.Errorf("failed to apply PackageSource %s: %w", packageSourceName, err) + } + + logger.Info("Applied platform PackageSource", "name", packageSourceName) return nil } diff --git a/cmd/cozystack-operator/main_test.go b/cmd/cozystack-operator/main_test.go index da1769f21..41b0655f8 100644 --- a/cmd/cozystack-operator/main_test.go +++ b/cmd/cozystack-operator/main_test.go @@ -96,6 +96,9 @@ func TestInstallPlatformPackageSource_Updates(t *testing.T) { ObjectMeta: metav1.ObjectMeta{ Name: "cozystack.cozystack-platform", ResourceVersion: "1", + Labels: map[string]string{ + "custom-label": "should-be-preserved", + }, }, Spec: cozyv1alpha1.PackageSourceSpec{ SourceRef: &cozyv1alpha1.PackageSourceRef{ @@ -127,6 +130,11 @@ func TestInstallPlatformPackageSource_Updates(t *testing.T) { if len(ps.Spec.Variants) != 4 { t.Errorf("expected 4 variants after update, got %d", len(ps.Spec.Variants)) } + + // Verify that labels set by other controllers are preserved (SSA does not overwrite unmanaged fields) + if ps.Labels["custom-label"] != "should-be-preserved" { + t.Errorf("expected custom-label to be preserved, got %q", ps.Labels["custom-label"]) + } } func TestInstallPlatformPackageSource_GitRepository(t *testing.T) { From dbfdbc8298bdbeedf3e24a7c6a843275ec356468 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 17:57:45 +0300 Subject: [PATCH 06/11] fix(installer): check parsePlatformSourceURL error, wait for PackageSource in E2E Explicitly check error from parsePlatformSourceURL instead of relying on the implicit guarantee that installPlatformSourceResource already checked it. This prevents latent bugs if startup order is ever restructured. Add wait for platform PackageSource existence in E2E test before creating Package resource, preventing flaky failures when operator startup is slow. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main.go | 7 +++++-- hack/e2e-install-cozystack.bats | 3 +++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index 10102bc0e..34172d95c 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -230,8 +230,11 @@ func main() { { sourceRefKind := "OCIRepository" if platformSourceURL != "" { - sourceType, _, _ := parsePlatformSourceURL(platformSourceURL) - // Error already checked by installPlatformSourceResource above + sourceType, _, err := parsePlatformSourceURL(platformSourceURL) + if err != nil { + setupLog.Error(err, "failed to parse platform source URL for PackageSource") + os.Exit(1) + } if sourceType == "git" { sourceRefKind = "GitRepository" } diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index 815622bc4..2cfebfbff 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -23,6 +23,9 @@ kubectl wait crd/packages.cozystack.io --for=condition=Established --timeout=2m kubectl wait crd/packagesources.cozystack.io --for=condition=Established --timeout=2m + # Wait for operator to create the platform PackageSource + timeout 120 sh -ec 'until kubectl get packagesource cozystack.cozystack-platform >/dev/null 2>&1; do sleep 2; done' + # Create platform Package with isp-full variant kubectl apply -f - < Date: Thu, 19 Feb 2026 18:04:50 +0300 Subject: [PATCH 07/11] fix(operator): correct default platformSourceName, gate PackageSource on installCRDs Change default --platform-source-name from "cozystack-packages" to "cozystack-platform" to match the value passed by the Helm template. Gate PackageSource creation on --install-crds flag: when the operator does not manage CRDs, the PackageSource CRD may not exist yet, so skip creation and let an external process handle it. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index 34172d95c..ad4a27782 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -108,7 +108,7 @@ func main() { flag.StringVar(&telemetryInterval, "telemetry-interval", "15m", "Interval between telemetry data collection (e.g. 15m, 1h)") flag.StringVar(&platformSourceURL, "platform-source-url", "", "Platform source URL (oci:// or https://). If specified, generates OCIRepository or GitRepository resource.") - flag.StringVar(&platformSourceName, "platform-source-name", "cozystack-packages", "Name for the generated platform source resource (default: cozystack-packages)") + flag.StringVar(&platformSourceName, "platform-source-name", "cozystack-platform", "Name for the generated platform source resource and PackageSource") flag.StringVar(&platformSourceRef, "platform-source-ref", "", "Reference specification as key=value pairs (e.g., 'branch=main' or 'digest=sha256:...,tag=v1.0'). For OCI: digest, semver, semverFilter, tag. For Git: branch, tag, semver, name, commit.") flag.StringVar(&cozyValuesSecretName, "cozy-values-secret-name", "cozystack-values", "The name of the secret containing cluster-wide configuration values.") flag.StringVar(&cozyValuesSecretNamespace, "cozy-values-secret-namespace", "cozy-system", "The namespace of the secret containing cluster-wide configuration values.") @@ -224,10 +224,10 @@ func main() { } } - // Create platform PackageSource unconditionally (it was previously created - // by a Helm template regardless of platformSourceURL). Derive sourceRefKind - // from URL when available, default to OCIRepository otherwise. - { + // Create platform PackageSource when CRDs are managed by the operator. + // When --install-crds=false the PackageSource CRD may not exist yet, + // so we skip creation and let an external process handle it. + if installCRDs { sourceRefKind := "OCIRepository" if platformSourceURL != "" { sourceType, _, err := parsePlatformSourceURL(platformSourceURL) From d0a6ddd7822ef41a9db7260c8d4c79079318ca70 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 18:25:14 +0300 Subject: [PATCH 08/11] refactor(operator): reduce variant duplication in installPlatformPackageSource Replace repetitive Variant struct literals with a loop over variant data, making it easier to add new variants and reducing copy-paste errors. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main.go | 87 ++++++++++++---------------------- 1 file changed, 29 insertions(+), 58 deletions(-) diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index ad4a27782..03855e7eb 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -607,67 +607,38 @@ func installPlatformPackageSource(ctx context.Context, k8sClient client.Client, Namespace: "cozy-system", Path: "/", }, - Variants: []cozyv1alpha1.Variant{ - { - Name: "default", - Components: []cozyv1alpha1.Component{ - { - Name: "platform", - Path: "core/platform", - Install: &cozyv1alpha1.ComponentInstall{ - Namespace: "cozy-system", - ReleaseName: "cozystack-platform", - }, - ValuesFiles: []string{"values.yaml"}, - }, - }, - }, - { - Name: "isp-full", - Components: []cozyv1alpha1.Component{ - { - Name: "platform", - Path: "core/platform", - Install: &cozyv1alpha1.ComponentInstall{ - Namespace: "cozy-system", - ReleaseName: "cozystack-platform", - }, - ValuesFiles: []string{"values.yaml", "values-isp-full.yaml"}, - }, - }, - }, - { - Name: "isp-hosted", - Components: []cozyv1alpha1.Component{ - { - Name: "platform", - Path: "core/platform", - Install: &cozyv1alpha1.ComponentInstall{ - Namespace: "cozy-system", - ReleaseName: "cozystack-platform", - }, - ValuesFiles: []string{"values.yaml", "values-isp-hosted.yaml"}, - }, - }, - }, - { - Name: "isp-full-generic", - Components: []cozyv1alpha1.Component{ - { - Name: "platform", - Path: "core/platform", - Install: &cozyv1alpha1.ComponentInstall{ - Namespace: "cozy-system", - ReleaseName: "cozystack-platform", - }, - ValuesFiles: []string{"values.yaml", "values-isp-full-generic.yaml"}, - }, - }, - }, - }, }, } + variantData := []struct { + name string + valuesFiles []string + }{ + {"default", []string{"values.yaml"}}, + {"isp-full", []string{"values.yaml", "values-isp-full.yaml"}}, + {"isp-hosted", []string{"values.yaml", "values-isp-hosted.yaml"}}, + {"isp-full-generic", []string{"values.yaml", "values-isp-full-generic.yaml"}}, + } + + variants := make([]cozyv1alpha1.Variant, len(variantData)) + for i, v := range variantData { + variants[i] = cozyv1alpha1.Variant{ + Name: v.name, + Components: []cozyv1alpha1.Component{ + { + Name: "platform", + Path: "core/platform", + Install: &cozyv1alpha1.ComponentInstall{ + Namespace: "cozy-system", + ReleaseName: "cozystack-platform", + }, + ValuesFiles: v.valuesFiles, + }, + }, + } + } + ps.Spec.Variants = variants + logger.Info("Applying platform PackageSource", "name", packageSourceName) patchOptions := &client.PatchOptions{ From 8b9a11360e4d1bb38aa4e38b0dce2e39f85e762d Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 18:29:55 +0300 Subject: [PATCH 09/11] fix(operator): skip PackageSource creation when platform source URL is empty When platformSourceURL is empty no Flux source resource is created, so creating a PackageSource that references it would leave a dangling SourceRef in a permanent error state. Guard the creation block on platformSourceURL != "". Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main.go | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/cmd/cozystack-operator/main.go b/cmd/cozystack-operator/main.go index 03855e7eb..e215b7792 100644 --- a/cmd/cozystack-operator/main.go +++ b/cmd/cozystack-operator/main.go @@ -224,20 +224,18 @@ func main() { } } - // Create platform PackageSource when CRDs are managed by the operator. - // When --install-crds=false the PackageSource CRD may not exist yet, - // so we skip creation and let an external process handle it. - if installCRDs { + // Create platform PackageSource when CRDs are managed by the operator and + // a platform source URL is configured. Without a URL there is no Flux source + // resource to reference, so creating a PackageSource would leave a dangling SourceRef. + if installCRDs && platformSourceURL != "" { sourceRefKind := "OCIRepository" - if platformSourceURL != "" { - sourceType, _, err := parsePlatformSourceURL(platformSourceURL) - if err != nil { - setupLog.Error(err, "failed to parse platform source URL for PackageSource") - os.Exit(1) - } - if sourceType == "git" { - sourceRefKind = "GitRepository" - } + sourceType, _, err := parsePlatformSourceURL(platformSourceURL) + if err != nil { + setupLog.Error(err, "failed to parse platform source URL for PackageSource") + os.Exit(1) + } + if sourceType == "git" { + sourceRefKind = "GitRepository" } setupLog.Info("Creating platform PackageSource", "platformSourceName", platformSourceName) psCtx, psCancel := context.WithTimeout(mgrCtx, 2*time.Minute) From 4843a617bc0905f9e1ba8ee997547b852fac7f8e Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 18:31:49 +0300 Subject: [PATCH 10/11] fix(operator): skip PackageSource on empty URL, add comprehensive tests Guard PackageSource creation on platformSourceURL != "" to avoid dangling SourceRef when no Flux source resource exists. Add tests covering all new and modified functions: - parsePlatformSourceURL (OCI, HTTPS, SSH, empty, unsupported scheme) - parseRefSpec (single/multi values, whitespace, equals in value, missing equals, empty key/value, trailing comma) - validateOCIRef / validateGitRef (valid keys, invalid keys, format) - generateOCIRepository / generateGitRepository (with ref, no ref, invalid ref) - installPlatformPackageSource variant valuesFiles validation - installPlatformPackageSource custom name Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- cmd/cozystack-operator/main_test.go | 414 ++++++++++++++++++++++++++++ 1 file changed, 414 insertions(+) diff --git a/cmd/cozystack-operator/main_test.go b/cmd/cozystack-operator/main_test.go index 41b0655f8..a69bc9b57 100644 --- a/cmd/cozystack-operator/main_test.go +++ b/cmd/cozystack-operator/main_test.go @@ -137,6 +137,151 @@ func TestInstallPlatformPackageSource_Updates(t *testing.T) { } } +func TestParsePlatformSourceURL(t *testing.T) { + tests := []struct { + name string + url string + wantType string + wantURL string + wantErr bool + }{ + { + name: "OCI URL", + url: "oci://ghcr.io/cozystack/cozystack/cozystack-packages", + wantType: "oci", + wantURL: "oci://ghcr.io/cozystack/cozystack/cozystack-packages", + }, + { + name: "HTTPS URL", + url: "https://github.com/cozystack/cozystack", + wantType: "git", + wantURL: "https://github.com/cozystack/cozystack", + }, + { + name: "SSH URL", + url: "ssh://git@github.com/cozystack/cozystack", + wantType: "git", + wantURL: "ssh://git@github.com/cozystack/cozystack", + }, + { + name: "empty URL", + url: "", + wantErr: true, + }, + { + name: "unsupported scheme", + url: "ftp://example.com/repo", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sourceType, repoURL, err := parsePlatformSourceURL(tt.url) + if tt.wantErr { + if err == nil { + t.Fatalf("expected error for URL %q, got nil", tt.url) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if sourceType != tt.wantType { + t.Errorf("expected type %q, got %q", tt.wantType, sourceType) + } + if repoURL != tt.wantURL { + t.Errorf("expected URL %q, got %q", tt.wantURL, repoURL) + } + }) + } +} + +func TestInstallPlatformPackageSource_VariantValuesFiles(t *testing.T) { + s := newTestScheme() + k8sClient := fake.NewClientBuilder().WithScheme(s).Build() + + err := installPlatformPackageSource(context.Background(), k8sClient, "cozystack-platform", "OCIRepository") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + ps := &cozyv1alpha1.PackageSource{} + if err := k8sClient.Get(context.Background(), client.ObjectKey{Name: "cozystack.cozystack-platform"}, ps); err != nil { + t.Fatalf("PackageSource not found: %v", err) + } + + expectedValuesFiles := map[string][]string{ + "default": {"values.yaml"}, + "isp-full": {"values.yaml", "values-isp-full.yaml"}, + "isp-hosted": {"values.yaml", "values-isp-hosted.yaml"}, + "isp-full-generic": {"values.yaml", "values-isp-full-generic.yaml"}, + } + + for _, v := range ps.Spec.Variants { + expected, ok := expectedValuesFiles[v.Name] + if !ok { + t.Errorf("unexpected variant %q", v.Name) + continue + } + + if len(v.Components) != 1 { + t.Errorf("variant %q: expected 1 component, got %d", v.Name, len(v.Components)) + continue + } + + comp := v.Components[0] + if comp.Name != "platform" { + t.Errorf("variant %q: expected component name %q, got %q", v.Name, "platform", comp.Name) + } + if comp.Path != "core/platform" { + t.Errorf("variant %q: expected component path %q, got %q", v.Name, "core/platform", comp.Path) + } + if comp.Install == nil { + t.Errorf("variant %q: expected Install to be set", v.Name) + } else { + if comp.Install.Namespace != "cozy-system" { + t.Errorf("variant %q: expected install namespace %q, got %q", v.Name, "cozy-system", comp.Install.Namespace) + } + if comp.Install.ReleaseName != "cozystack-platform" { + t.Errorf("variant %q: expected install releaseName %q, got %q", v.Name, "cozystack-platform", comp.Install.ReleaseName) + } + } + + if len(comp.ValuesFiles) != len(expected) { + t.Errorf("variant %q: expected %d valuesFiles, got %d", v.Name, len(expected), len(comp.ValuesFiles)) + continue + } + for i, f := range expected { + if comp.ValuesFiles[i] != f { + t.Errorf("variant %q: expected valuesFiles[%d] %q, got %q", v.Name, i, f, comp.ValuesFiles[i]) + } + } + } +} + +func TestInstallPlatformPackageSource_CustomName(t *testing.T) { + s := newTestScheme() + k8sClient := fake.NewClientBuilder().WithScheme(s).Build() + + err := installPlatformPackageSource(context.Background(), k8sClient, "custom-source", "OCIRepository") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + ps := &cozyv1alpha1.PackageSource{} + if err := k8sClient.Get(context.Background(), client.ObjectKey{Name: "cozystack.custom-source"}, ps); err != nil { + t.Fatalf("PackageSource not found: %v", err) + } + + if ps.Name != "cozystack.custom-source" { + t.Errorf("expected name %q, got %q", "cozystack.custom-source", ps.Name) + } + if ps.Spec.SourceRef.Name != "custom-source" { + t.Errorf("expected sourceRef.name %q, got %q", "custom-source", ps.Spec.SourceRef.Name) + } +} + func TestInstallPlatformPackageSource_GitRepository(t *testing.T) { s := newTestScheme() k8sClient := fake.NewClientBuilder().WithScheme(s).Build() @@ -158,3 +303,272 @@ func TestInstallPlatformPackageSource_GitRepository(t *testing.T) { t.Errorf("expected sourceRef.name %q, got %q", "my-source", ps.Spec.SourceRef.Name) } } + +func TestParseRefSpec(t *testing.T) { + tests := []struct { + name string + input string + want map[string]string + wantErr bool + }{ + { + name: "empty string", + input: "", + want: map[string]string{}, + }, + { + name: "single key-value", + input: "tag=v1.0", + want: map[string]string{"tag": "v1.0"}, + }, + { + name: "multiple key-values", + input: "digest=sha256:abc123,tag=v1.0", + want: map[string]string{"digest": "sha256:abc123", "tag": "v1.0"}, + }, + { + name: "whitespace around pairs", + input: " tag=v1.0 , branch=main ", + want: map[string]string{"tag": "v1.0", "branch": "main"}, + }, + { + name: "equals sign in value", + input: "digest=sha256:abc=123", + want: map[string]string{"digest": "sha256:abc=123"}, + }, + { + name: "missing equals sign", + input: "tag", + wantErr: true, + }, + { + name: "empty key", + input: "=value", + wantErr: true, + }, + { + name: "empty value", + input: "tag=", + wantErr: true, + }, + { + name: "trailing comma", + input: "tag=v1.0,", + want: map[string]string{"tag": "v1.0"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := parseRefSpec(tt.input) + if tt.wantErr { + if err == nil { + t.Fatalf("expected error for input %q, got nil", tt.input) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(got) != len(tt.want) { + t.Fatalf("expected %d entries, got %d: %v", len(tt.want), len(got), got) + } + for k, v := range tt.want { + if got[k] != v { + t.Errorf("expected %q=%q, got %q=%q", k, v, k, got[k]) + } + } + }) + } +} + +func TestValidateOCIRef(t *testing.T) { + tests := []struct { + name string + refMap map[string]string + wantErr bool + }{ + { + name: "valid tag", + refMap: map[string]string{"tag": "v1.0"}, + }, + { + name: "valid digest", + refMap: map[string]string{"digest": "sha256:abc123def456"}, + }, + { + name: "valid semver", + refMap: map[string]string{"semver": ">=1.0.0"}, + }, + { + name: "multiple valid keys", + refMap: map[string]string{"tag": "v1.0", "digest": "sha256:abc"}, + }, + { + name: "empty map", + refMap: map[string]string{}, + }, + { + name: "invalid key", + refMap: map[string]string{"branch": "main"}, + wantErr: true, + }, + { + name: "invalid digest format", + refMap: map[string]string{"digest": "md5:abc"}, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateOCIRef(tt.refMap) + if tt.wantErr && err == nil { + t.Fatal("expected error, got nil") + } + if !tt.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +func TestValidateGitRef(t *testing.T) { + tests := []struct { + name string + refMap map[string]string + wantErr bool + }{ + { + name: "valid branch", + refMap: map[string]string{"branch": "main"}, + }, + { + name: "valid commit", + refMap: map[string]string{"commit": "abc1234"}, + }, + { + name: "valid tag and branch", + refMap: map[string]string{"tag": "v1.0", "branch": "release"}, + }, + { + name: "empty map", + refMap: map[string]string{}, + }, + { + name: "invalid key", + refMap: map[string]string{"digest": "sha256:abc"}, + wantErr: true, + }, + { + name: "commit too short", + refMap: map[string]string{"commit": "abc"}, + wantErr: true, + }, + { + name: "commit not hex", + refMap: map[string]string{"commit": "zzzzzzz"}, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateGitRef(tt.refMap) + if tt.wantErr && err == nil { + t.Fatal("expected error, got nil") + } + if !tt.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +func TestGenerateOCIRepository(t *testing.T) { + refMap := map[string]string{"tag": "v1.0", "digest": "sha256:abc123"} + obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", refMap) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if obj.Name != "my-repo" { + t.Errorf("expected name %q, got %q", "my-repo", obj.Name) + } + if obj.Namespace != "cozy-system" { + t.Errorf("expected namespace %q, got %q", "cozy-system", obj.Namespace) + } + if obj.Spec.URL != "oci://registry.example.com/repo" { + t.Errorf("expected URL %q, got %q", "oci://registry.example.com/repo", obj.Spec.URL) + } + if obj.Spec.Reference == nil { + t.Fatal("expected Reference to be set") + } + if obj.Spec.Reference.Tag != "v1.0" { + t.Errorf("expected tag %q, got %q", "v1.0", obj.Spec.Reference.Tag) + } + if obj.Spec.Reference.Digest != "sha256:abc123" { + t.Errorf("expected digest %q, got %q", "sha256:abc123", obj.Spec.Reference.Digest) + } +} + +func TestGenerateOCIRepository_NoRef(t *testing.T) { + obj, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if obj.Spec.Reference != nil { + t.Error("expected Reference to be nil for empty refMap") + } +} + +func TestGenerateOCIRepository_InvalidRef(t *testing.T) { + _, err := generateOCIRepository("my-repo", "oci://registry.example.com/repo", map[string]string{"branch": "main"}) + if err == nil { + t.Fatal("expected error for invalid OCI ref key, got nil") + } +} + +func TestGenerateGitRepository(t *testing.T) { + refMap := map[string]string{"branch": "main", "commit": "abc1234def5678"} + obj, err := generateGitRepository("my-repo", "https://github.com/user/repo", refMap) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if obj.Name != "my-repo" { + t.Errorf("expected name %q, got %q", "my-repo", obj.Name) + } + if obj.Namespace != "cozy-system" { + t.Errorf("expected namespace %q, got %q", "cozy-system", obj.Namespace) + } + if obj.Spec.URL != "https://github.com/user/repo" { + t.Errorf("expected URL %q, got %q", "https://github.com/user/repo", obj.Spec.URL) + } + if obj.Spec.Reference == nil { + t.Fatal("expected Reference to be set") + } + if obj.Spec.Reference.Branch != "main" { + t.Errorf("expected branch %q, got %q", "main", obj.Spec.Reference.Branch) + } + if obj.Spec.Reference.Commit != "abc1234def5678" { + t.Errorf("expected commit %q, got %q", "abc1234def5678", obj.Spec.Reference.Commit) + } +} + +func TestGenerateGitRepository_NoRef(t *testing.T) { + obj, err := generateGitRepository("my-repo", "https://github.com/user/repo", map[string]string{}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if obj.Spec.Reference != nil { + t.Error("expected Reference to be nil for empty refMap") + } +} + +func TestGenerateGitRepository_InvalidRef(t *testing.T) { + _, err := generateGitRepository("my-repo", "https://github.com/user/repo", map[string]string{"digest": "sha256:abc"}) + if err == nil { + t.Fatal("expected error for invalid Git ref key, got nil") + } +} From 4e5455c72cc9922fcbe750989fddeb3be7268741 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Thu, 19 Feb 2026 19:24:19 +0300 Subject: [PATCH 11/11] fix(e2e): poll for CRD existence before waiting for Established condition kubectl wait fails immediately with NotFound if the CRD does not exist yet. The operator creates CRDs asynchronously on startup, so wrap the wait in a retry loop that tolerates the initial absence. Co-Authored-By: Claude Signed-off-by: Aleksei Sviridkin --- hack/e2e-install-cozystack.bats | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/hack/e2e-install-cozystack.bats b/hack/e2e-install-cozystack.bats index 2cfebfbff..43b8ab8f4 100644 --- a/hack/e2e-install-cozystack.bats +++ b/hack/e2e-install-cozystack.bats @@ -19,9 +19,10 @@ # Verify the operator deployment is available kubectl wait deployment/cozystack-operator -n cozy-system --timeout=1m --for=condition=Available - # Wait for operator to install CRDs (happens at startup before reconcile loop) - kubectl wait crd/packages.cozystack.io --for=condition=Established --timeout=2m - kubectl wait crd/packagesources.cozystack.io --for=condition=Established --timeout=2m + # Wait for operator to install CRDs (happens at startup before reconcile loop). + # kubectl wait fails immediately if the CRD does not exist yet, so poll until it appears first. + timeout 120 sh -ec 'until kubectl wait crd/packages.cozystack.io --for=condition=Established --timeout=10s 2>/dev/null; do sleep 2; done' + timeout 120 sh -ec 'until kubectl wait crd/packagesources.cozystack.io --for=condition=Established --timeout=10s 2>/dev/null; do sleep 2; done' # Wait for operator to create the platform PackageSource timeout 120 sh -ec 'until kubectl get packagesource cozystack.cozystack-platform >/dev/null 2>&1; do sleep 2; done'