From 4c6bbd02dfec61356a9d20a1ec2bfe8fe0eb90b3 Mon Sep 17 00:00:00 2001 From: Naomi Gelman Date: Sun, 14 Jun 2026 19:37:36 +0300 Subject: [PATCH] remove TektonHub component support --- Makefile | 1 - .../tekton-operator/templates/deployment.yaml | 2 +- .../templates/kubernetes-crds.yaml | 259 ----- .../templates/openshift-crds.yaml | 259 ----- charts/tekton-operator/values.yaml | 2 +- .../static/tekton-hub/postgresql-cm/cm.yaml | 58 - components.yaml | 3 - .../operator.tekton.dev_tektonhubs.yaml | 256 ---- config/base/kustomization.yaml | 1 - .../hub/operator_v1alpha1_hub_cr.yaml | 22 - config/crs/kubernetes/kustomization.yaml | 1 - .../hub/operator_v1alpha1_hub_cr.yaml | 22 - config/crs/openshift/kustomization.yaml | 1 - config/kubernetes/base/operator.yaml | 2 +- config/openshift/base/operator.yaml | 4 +- docs/AirGapImageConfiguration.md | 6 +- docs/TektonConfig.md | 24 - docs/TektonHub.md | 184 --- go.mod | 2 +- hack/fetch-releases.sh | 54 - hack/sync-helm-crds.sh | 3 - ...erator.clusterserviceversion.template.yaml | 8 - .../operator.tekton.dev_tektonhubs.yaml | 49 - ...ktoncd-operator.clusterserviceversion.yaml | 21 +- operatorhub/openshift/config.yaml | 22 - ...tor-rh.clusterserviceversion.template.yaml | 23 +- ...nes-operator-rh.clusterserviceversion.yaml | 42 +- .../operator.tekton.dev_tektonhubs.yaml | 49 - pkg/apis/operator/v1alpha1/const.go | 10 - pkg/apis/operator/v1alpha1/register.go | 5 - .../operator/v1alpha1/tektonconfig_types.go | 3 - .../v1alpha1/tektonconfig_validation.go | 5 - .../v1alpha1/tektonhub_default_test.go | 43 - .../operator/v1alpha1/tektonhub_defaults.go | 37 - .../operator/v1alpha1/tektonhub_lifecycle.go | 252 ---- .../v1alpha1/tektonhub_lifecycle_test.go | 168 --- pkg/apis/operator/v1alpha1/tektonhub_types.go | 184 --- .../operator/v1alpha1/tektonhub_validation.go | 70 -- .../v1alpha1/tektonhub_validation_test.go | 173 --- .../v1alpha1/zz_generated.deepcopy.go | 274 ----- .../v1alpha1/fake/fake_operator_client.go | 4 - .../operator/v1alpha1/fake/fake_tektonhub.go | 50 - .../operator/v1alpha1/generated_expansion.go | 2 - .../operator/v1alpha1/operator_client.go | 5 - .../typed/operator/v1alpha1/tektonhub.go | 70 -- .../informers/externalversions/generic.go | 2 - .../operator/v1alpha1/interface.go | 7 - .../operator/v1alpha1/tektonhub.go | 101 -- .../operator/v1alpha1/tektonhub/fake/fake.go | 40 - .../v1alpha1/tektonhub/filtered/fake/fake.go | 52 - .../v1alpha1/tektonhub/filtered/tektonhub.go | 65 -- .../operator/v1alpha1/tektonhub/tektonhub.go | 52 - .../operator/v1alpha1/tektonhub/controller.go | 178 --- .../operator/v1alpha1/tektonhub/reconciler.go | 551 --------- .../operator/v1alpha1/tektonhub/state.go | 97 -- .../operator/v1alpha1/expansion_generated.go | 4 - .../listers/operator/v1alpha1/tektonhub.go | 48 - pkg/reconciler/common/releases.go | 2 - pkg/reconciler/common/targetnamespace_test.go | 16 - pkg/reconciler/common/transformers.go | 1 - .../kubernetes/kubernetesplatform/config.go | 4 - .../kubernetes/tektonhub/controller.go | 91 -- .../kubernetes/tektonhub/installerset.go | 117 -- .../kubernetes/tektonhub/tektonhub.go | 1035 ----------------- .../kubernetes/tektonhub/transform.go | 72 -- .../openshift/openshiftplatform/config.go | 5 - .../openshift/tektonhub/controller.go | 31 - .../openshift/tektonhub/extension.go | 567 --------- .../openshift/tektonhub/extension_test.go | 106 -- .../testdata/update-db-deployment.yaml | 75 -- pkg/reconciler/platform/const.go | 1 - pkg/reconciler/proxy/controller.go | 1 - pkg/webhook/webhook.go | 1 - .../e2e/common/05_tektonhubdeployment_test.go | 413 ------- test/e2e/common/testdata/hub_externaldb.yaml | 153 --- .../testdata/hub_externaldb_secret.yaml | 26 - test/resources/debug_commands.go | 2 - test/resources/tektonconfigs.go | 4 - test/resources/tektonhub.go | 133 --- test/utils/clients.go | 9 - test/utils/e2e_flags.go | 1 - test/utils/names.go | 2 - 82 files changed, 10 insertions(+), 6790 deletions(-) delete mode 100644 cmd/openshift/operator/kodata/static/tekton-hub/postgresql-cm/cm.yaml delete mode 100644 config/base/generated-crds/operator.tekton.dev_tektonhubs.yaml delete mode 100644 config/crs/kubernetes/hub/operator_v1alpha1_hub_cr.yaml delete mode 100644 config/crs/openshift/hub/operator_v1alpha1_hub_cr.yaml delete mode 100644 docs/TektonHub.md delete mode 100644 operatorhub/kubernetes/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml delete mode 100644 operatorhub/openshift/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml delete mode 100644 pkg/apis/operator/v1alpha1/tektonhub_default_test.go delete mode 100644 pkg/apis/operator/v1alpha1/tektonhub_defaults.go delete mode 100644 pkg/apis/operator/v1alpha1/tektonhub_lifecycle.go delete mode 100644 pkg/apis/operator/v1alpha1/tektonhub_lifecycle_test.go delete mode 100644 pkg/apis/operator/v1alpha1/tektonhub_types.go delete mode 100644 pkg/apis/operator/v1alpha1/tektonhub_validation.go delete mode 100644 pkg/apis/operator/v1alpha1/tektonhub_validation_test.go delete mode 100644 pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_tektonhub.go delete mode 100644 pkg/client/clientset/versioned/typed/operator/v1alpha1/tektonhub.go delete mode 100644 pkg/client/informers/externalversions/operator/v1alpha1/tektonhub.go delete mode 100644 pkg/client/injection/informers/operator/v1alpha1/tektonhub/fake/fake.go delete mode 100644 pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/fake/fake.go delete mode 100644 pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/tektonhub.go delete mode 100644 pkg/client/injection/informers/operator/v1alpha1/tektonhub/tektonhub.go delete mode 100644 pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/controller.go delete mode 100644 pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/reconciler.go delete mode 100644 pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/state.go delete mode 100644 pkg/client/listers/operator/v1alpha1/tektonhub.go delete mode 100644 pkg/reconciler/kubernetes/tektonhub/controller.go delete mode 100644 pkg/reconciler/kubernetes/tektonhub/installerset.go delete mode 100644 pkg/reconciler/kubernetes/tektonhub/tektonhub.go delete mode 100644 pkg/reconciler/kubernetes/tektonhub/transform.go delete mode 100644 pkg/reconciler/openshift/tektonhub/controller.go delete mode 100644 pkg/reconciler/openshift/tektonhub/extension.go delete mode 100644 pkg/reconciler/openshift/tektonhub/extension_test.go delete mode 100644 pkg/reconciler/openshift/tektonhub/testdata/update-db-deployment.yaml delete mode 100644 test/e2e/common/05_tektonhubdeployment_test.go delete mode 100644 test/e2e/common/testdata/hub_externaldb.yaml delete mode 100644 test/e2e/common/testdata/hub_externaldb_secret.yaml delete mode 100644 test/resources/tektonhub.go diff --git a/Makefile b/Makefile index 733ff0b05d..6865d120a2 100644 --- a/Makefile +++ b/Makefile @@ -72,7 +72,6 @@ ifeq ($(TARGET), openshift) rm -rf ./cmd/$(TARGET)/operator/kodata/tekton-pipeline rm -rf ./cmd/$(TARGET)/operator/kodata/tekton-trigger rm -rf ./cmd/$(TARGET)/operator/kodata/tekton-chains - rm -rf ./cmd/$(TARGET)/operator/kodata/tekton-hub rm -rf ./cmd/$(TARGET)/operator/kodata/tekton-results rm -rf ./cmd/$(TARGET)/operator/kodata/manual-approval-gate rm -rf ./cmd/$(TARGET)/operator/kodata/tekton-pruner diff --git a/charts/tekton-operator/templates/deployment.yaml b/charts/tekton-operator/templates/deployment.yaml index 5d75261225..f194ed8b9d 100644 --- a/charts/tekton-operator/templates/deployment.yaml +++ b/charts/tekton-operator/templates/deployment.yaml @@ -77,7 +77,7 @@ spec: {{- end }} args: - "-controllers" - - {{ .Values.controllers | default "tektonconfig,tektonpipeline,tektontrigger,tektonhub,tektonchain,tektonresult,tektondashboard,manualapprovalgate,tektonpruner,openshiftpipelinesascode" | quote }} + - {{ .Values.controllers | default "tektonconfig,tektonpipeline,tektontrigger,tektonchain,tektonresult,tektondashboard,manualapprovalgate,tektonpruner,openshiftpipelinesascode" | quote }} - "-unique-process-name" - "tekton-operator-lifecycle" image: {{ include "tekton-operator.operator-image" . }} diff --git a/charts/tekton-operator/templates/kubernetes-crds.yaml b/charts/tekton-operator/templates/kubernetes-crds.yaml index 9b29362e87..6f182bfdd9 100644 --- a/charts/tekton-operator/templates/kubernetes-crds.yaml +++ b/charts/tekton-operator/templates/kubernetes-crds.yaml @@ -2515,265 +2515,6 @@ spec: --- apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.18.0 - name: tektonhubs.operator.tekton.dev - labels: - version: "devel" - operator.tekton.dev/release: "devel" -spec: - group: operator.tekton.dev - names: - kind: TektonHub - listKind: TektonHubList - plural: tektonhubs - singular: tektonhub - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.version - name: Version - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Reason - type: string - - jsonPath: .status.apiUrl - name: ApiUrl - type: string - - jsonPath: .status.uiUrl - name: UiUrl - type: string - name: v1alpha1 - schema: - openAPIV3Schema: - description: TektonHub is the Schema for the tektonhub 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: - properties: - api: - properties: - catalogRefreshInterval: - type: string - hubConfigUrl: - description: Deprecated, will be removed in further release - type: string - routeHostUrl: - type: string - secret: - type: string - type: object - catalogs: - items: - properties: - contextDir: - type: string - name: - type: string - org: - type: string - provider: - type: string - revision: - type: string - sshUrl: - type: string - type: - type: string - url: - type: string - type: object - type: array - categories: - items: - type: string - type: array - customLogo: - description: The Base64 Encode data and mediaType of the Custom Logo - properties: - base64Data: - type: string - mediaType: - type: string - type: object - db: - properties: - secret: - type: string - type: object - default: - properties: - scopes: - items: - type: string - type: array - type: object - options: - description: options holds additions fields and these fields will - be updated on the manifests - properties: - configMaps: - x-kubernetes-preserve-unknown-fields: true - deployments: - x-kubernetes-preserve-unknown-fields: true - disabled: - type: boolean - horizontalPodAutoscalers: - x-kubernetes-preserve-unknown-fields: true - statefulSets: - x-kubernetes-preserve-unknown-fields: true - webhookConfigurationOptions: - additionalProperties: - description: WebhookOptions defines options for webhooks - properties: - failurePolicy: - description: FailurePolicyType specifies a failure policy - that defines how unrecognized errors from the admission - endpoint are handled. - type: string - sideEffects: - description: SideEffectClass specifies the types of side - effects a webhook may have. - type: string - timeoutSeconds: - type: integer - type: object - type: object - type: object - params: - description: Params is the list of params passed for Hub customization - items: - description: Param declares an string value to use for the parameter - called name. - properties: - name: - type: string - value: - type: string - type: object - type: array - scopes: - items: - properties: - name: - type: string - users: - items: - type: string - type: array - type: object - type: array - targetNamespace: - description: TargetNamespace is where resources will be installed - type: string - required: - - options - type: object - status: - description: TektonHubStatus defines the observed state of TektonHub - properties: - annotations: - additionalProperties: - type: string - description: |- - Annotations is additional Status fields for the Resource to save some - additional State as well as convey more information to the user. This is - roughly akin to Annotations on any k8s resource, just the reconciler conveying - richer information outwards. - type: object - apiUrl: - description: The URL route for API which needs to be exposed - type: string - authUrl: - description: The URL route for Auth server - type: string - conditions: - description: Conditions the latest available observations of a resource's - current state. - items: - description: |- - Condition defines a readiness condition for a Knative resource. - See: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties - properties: - lastTransitionTime: - description: |- - LastTransitionTime is the last time the condition transitioned from one status to another. - We use VolatileTime in place of metav1.Time to exclude this from creating equality.Semantic - differences (all other things held constant). - type: string - message: - description: A human readable message indicating details about - the transition. - type: string - reason: - description: The reason for the condition's last transition. - type: string - severity: - description: |- - Severity with which to treat failures of this type of condition. - When this is not specified, it defaults to Error. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: Type of condition. - type: string - required: - - status - - type - type: object - type: array - hubInstallerSets: - additionalProperties: - type: string - description: The current installer set name - type: object - manifests: - description: The url links of the manifests, separated by comma - items: - type: string - type: array - observedGeneration: - description: |- - ObservedGeneration is the 'Generation' of the Service that - was last processed by the controller. - type: integer - uiUrl: - description: The URL route for UI which needs to be exposed - type: string - version: - description: The version of the installed release - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.18.0 diff --git a/charts/tekton-operator/templates/openshift-crds.yaml b/charts/tekton-operator/templates/openshift-crds.yaml index 9aa4b5bf5d..63ceec7a98 100644 --- a/charts/tekton-operator/templates/openshift-crds.yaml +++ b/charts/tekton-operator/templates/openshift-crds.yaml @@ -2493,265 +2493,6 @@ spec: --- apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.18.0 - name: tektonhubs.operator.tekton.dev - labels: - version: "devel" - operator.tekton.dev/release: "devel" -spec: - group: operator.tekton.dev - names: - kind: TektonHub - listKind: TektonHubList - plural: tektonhubs - singular: tektonhub - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.version - name: Version - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Reason - type: string - - jsonPath: .status.apiUrl - name: ApiUrl - type: string - - jsonPath: .status.uiUrl - name: UiUrl - type: string - name: v1alpha1 - schema: - openAPIV3Schema: - description: TektonHub is the Schema for the tektonhub 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: - properties: - api: - properties: - catalogRefreshInterval: - type: string - hubConfigUrl: - description: Deprecated, will be removed in further release - type: string - routeHostUrl: - type: string - secret: - type: string - type: object - catalogs: - items: - properties: - contextDir: - type: string - name: - type: string - org: - type: string - provider: - type: string - revision: - type: string - sshUrl: - type: string - type: - type: string - url: - type: string - type: object - type: array - categories: - items: - type: string - type: array - customLogo: - description: The Base64 Encode data and mediaType of the Custom Logo - properties: - base64Data: - type: string - mediaType: - type: string - type: object - db: - properties: - secret: - type: string - type: object - default: - properties: - scopes: - items: - type: string - type: array - type: object - options: - description: options holds additions fields and these fields will - be updated on the manifests - properties: - configMaps: - x-kubernetes-preserve-unknown-fields: true - deployments: - x-kubernetes-preserve-unknown-fields: true - disabled: - type: boolean - horizontalPodAutoscalers: - x-kubernetes-preserve-unknown-fields: true - statefulSets: - x-kubernetes-preserve-unknown-fields: true - webhookConfigurationOptions: - additionalProperties: - description: WebhookOptions defines options for webhooks - properties: - failurePolicy: - description: FailurePolicyType specifies a failure policy - that defines how unrecognized errors from the admission - endpoint are handled. - type: string - sideEffects: - description: SideEffectClass specifies the types of side - effects a webhook may have. - type: string - timeoutSeconds: - type: integer - type: object - type: object - type: object - params: - description: Params is the list of params passed for Hub customization - items: - description: Param declares an string value to use for the parameter - called name. - properties: - name: - type: string - value: - type: string - type: object - type: array - scopes: - items: - properties: - name: - type: string - users: - items: - type: string - type: array - type: object - type: array - targetNamespace: - description: TargetNamespace is where resources will be installed - type: string - required: - - options - type: object - status: - description: TektonHubStatus defines the observed state of TektonHub - properties: - annotations: - additionalProperties: - type: string - description: |- - Annotations is additional Status fields for the Resource to save some - additional State as well as convey more information to the user. This is - roughly akin to Annotations on any k8s resource, just the reconciler conveying - richer information outwards. - type: object - apiUrl: - description: The URL route for API which needs to be exposed - type: string - authUrl: - description: The URL route for Auth server - type: string - conditions: - description: Conditions the latest available observations of a resource's - current state. - items: - description: |- - Condition defines a readiness condition for a Knative resource. - See: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties - properties: - lastTransitionTime: - description: |- - LastTransitionTime is the last time the condition transitioned from one status to another. - We use VolatileTime in place of metav1.Time to exclude this from creating equality.Semantic - differences (all other things held constant). - type: string - message: - description: A human readable message indicating details about - the transition. - type: string - reason: - description: The reason for the condition's last transition. - type: string - severity: - description: |- - Severity with which to treat failures of this type of condition. - When this is not specified, it defaults to Error. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: Type of condition. - type: string - required: - - status - - type - type: object - type: array - hubInstallerSets: - additionalProperties: - type: string - description: The current installer set name - type: object - manifests: - description: The url links of the manifests, separated by comma - items: - type: string - type: array - observedGeneration: - description: |- - ObservedGeneration is the 'Generation' of the Service that - was last processed by the controller. - type: integer - uiUrl: - description: The URL route for UI which needs to be exposed - type: string - version: - description: The version of the installed release - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.18.0 diff --git a/charts/tekton-operator/values.yaml b/charts/tekton-operator/values.yaml index 043d76dcb8..49ce72db62 100644 --- a/charts/tekton-operator/values.yaml +++ b/charts/tekton-operator/values.yaml @@ -20,7 +20,7 @@ openshift: installCRDs: false ## Controllers to install -controllers: "tektonconfig,tektonpipeline,tektontrigger,tektonhub,tektonchain,tektonresult,tektondashboard,manualapprovalgate,tektonpruner,openshiftpipelinesascode" +controllers: "tektonconfig,tektonpipeline,tektontrigger,tektonchain,tektonresult,tektondashboard,manualapprovalgate,tektonpruner,openshiftpipelinesascode" ## Control the creation of RBAC resources (Serviceaccount, Role, ClusterRole, ClusterRoleBinding) rbac: diff --git a/cmd/openshift/operator/kodata/static/tekton-hub/postgresql-cm/cm.yaml b/cmd/openshift/operator/kodata/static/tekton-hub/postgresql-cm/cm.yaml deleted file mode 100644 index f9dbcae9ed..0000000000 --- a/cmd/openshift/operator/kodata/static/tekton-hub/postgresql-cm/cm.yaml +++ /dev/null @@ -1,58 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - labels: - app.kubernetes.io/name: tekton-hub-postgres - app.kubernetes.io/part-of: tekton-hub - name: tekton-hub-postgres-upgrade-scripts -data: - postgres-wrapper.sh: | - #!/bin/bash - set -eu - PGDATA="${PGDATA:-/var/lib/pgsql/data}" - CURRENT_VERSION="15" - UPGRADE_FROM_VERSION="13" - echo "=== PostgreSQL Container Starting ===" - - # The sclorg PostgreSQL containers use a subdirectory for data - # Check both $PGDATA and $PGDATA/userdata for existing data - PG_VERSION_FILE="" - if [ -f "$PGDATA/PG_VERSION" ]; then - PG_VERSION_FILE="$PGDATA/PG_VERSION" - elif [ -f "$PGDATA/userdata/PG_VERSION" ]; then - PG_VERSION_FILE="$PGDATA/userdata/PG_VERSION" - echo "Found existing data in userdata subdirectory" - fi - - # Check if data directory exists and has version file - if [ -n "$PG_VERSION_FILE" ]; then - DATA_VERSION=$(cat "$PG_VERSION_FILE") - echo "Data directory PostgreSQL version: $DATA_VERSION" - # Check if upgrade is needed from version 13 to 15 - if [ "$DATA_VERSION" = "$UPGRADE_FROM_VERSION" ]; then - echo "=========================================" - echo "PostgreSQL Upgrade Mode Activated" - echo "Upgrading from PostgreSQL $UPGRADE_FROM_VERSION to PostgreSQL $CURRENT_VERSION" - echo "This is a ONE-TIME operation" - echo "=========================================" - # Set the POSTGRESQL_UPGRADE environment variable - # The sclorg PostgreSQL container will detect this and run pg_upgrade - export POSTGRESQL_UPGRADE="copy" - echo "Starting PostgreSQL with POSTGRESQL_UPGRADE=copy" - echo "Please monitor logs for upgrade progress..." - elif [ "$DATA_VERSION" = "$CURRENT_VERSION" ]; then - echo "PostgreSQL data is already version $CURRENT_VERSION" - echo "Starting normally" - else - echo "WARNING: Unexpected PostgreSQL data version: $DATA_VERSION" - echo "Expected either $CURRENT_VERSION or $UPGRADE_FROM_VERSION" - echo "Starting PostgreSQL and letting it handle the situation" - fi - else - echo "No PG_VERSION file found - fresh installation" - echo "PostgreSQL will initialize a new database" - fi - # Execute the standard PostgreSQL container entrypoint - # This is the default command from the sclorg postgresql container - exec run-postgresql -immutable: true diff --git a/components.yaml b/components.yaml index b58b74c9ac..d0de677380 100644 --- a/components.yaml +++ b/components.yaml @@ -4,9 +4,6 @@ chains: dashboard: github: tektoncd/dashboard version: v0.69.0 -hub: - github: openshift-pipelines/hub - version: v1.24.1 manual-approval-gate: github: openshift-pipelines/manual-approval-gate version: v0.9.0 diff --git a/config/base/generated-crds/operator.tekton.dev_tektonhubs.yaml b/config/base/generated-crds/operator.tekton.dev_tektonhubs.yaml deleted file mode 100644 index 90959ef3a7..0000000000 --- a/config/base/generated-crds/operator.tekton.dev_tektonhubs.yaml +++ /dev/null @@ -1,256 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.18.0 - name: tektonhubs.operator.tekton.dev -spec: - group: operator.tekton.dev - names: - kind: TektonHub - listKind: TektonHubList - plural: tektonhubs - singular: tektonhub - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.version - name: Version - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Reason - type: string - - jsonPath: .status.apiUrl - name: ApiUrl - type: string - - jsonPath: .status.uiUrl - name: UiUrl - type: string - name: v1alpha1 - schema: - openAPIV3Schema: - description: TektonHub is the Schema for the tektonhub 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: - properties: - api: - properties: - catalogRefreshInterval: - type: string - hubConfigUrl: - description: Deprecated, will be removed in further release - type: string - routeHostUrl: - type: string - secret: - type: string - type: object - catalogs: - items: - properties: - contextDir: - type: string - name: - type: string - org: - type: string - provider: - type: string - revision: - type: string - sshUrl: - type: string - type: - type: string - url: - type: string - type: object - type: array - categories: - items: - type: string - type: array - customLogo: - description: The Base64 Encode data and mediaType of the Custom Logo - properties: - base64Data: - type: string - mediaType: - type: string - type: object - db: - properties: - secret: - type: string - type: object - default: - properties: - scopes: - items: - type: string - type: array - type: object - options: - description: options holds additions fields and these fields will - be updated on the manifests - properties: - configMaps: - x-kubernetes-preserve-unknown-fields: true - deployments: - x-kubernetes-preserve-unknown-fields: true - disabled: - type: boolean - horizontalPodAutoscalers: - x-kubernetes-preserve-unknown-fields: true - statefulSets: - x-kubernetes-preserve-unknown-fields: true - webhookConfigurationOptions: - additionalProperties: - description: WebhookOptions defines options for webhooks - properties: - failurePolicy: - description: FailurePolicyType specifies a failure policy - that defines how unrecognized errors from the admission - endpoint are handled. - type: string - sideEffects: - description: SideEffectClass specifies the types of side - effects a webhook may have. - type: string - timeoutSeconds: - format: int32 - type: integer - type: object - type: object - type: object - params: - description: Params is the list of params passed for Hub customization - items: - description: Param declares an string value to use for the parameter - called name. - properties: - name: - type: string - value: - type: string - type: object - type: array - scopes: - items: - properties: - name: - type: string - users: - items: - type: string - type: array - type: object - type: array - targetNamespace: - description: TargetNamespace is where resources will be installed - type: string - type: object - status: - description: TektonHubStatus defines the observed state of TektonHub - properties: - annotations: - additionalProperties: - type: string - description: |- - Annotations is additional Status fields for the Resource to save some - additional State as well as convey more information to the user. This is - roughly akin to Annotations on any k8s resource, just the reconciler conveying - richer information outwards. - type: object - apiUrl: - description: The URL route for API which needs to be exposed - type: string - authUrl: - description: The URL route for Auth server - type: string - conditions: - description: Conditions the latest available observations of a resource's - current state. - items: - description: |- - Condition defines a readiness condition for a Knative resource. - See: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties - properties: - lastTransitionTime: - description: |- - LastTransitionTime is the last time the condition transitioned from one status to another. - We use VolatileTime in place of metav1.Time to exclude this from creating equality.Semantic - differences (all other things held constant). - type: string - message: - description: A human readable message indicating details about - the transition. - type: string - reason: - description: The reason for the condition's last transition. - type: string - severity: - description: |- - Severity with which to treat failures of this type of condition. - When this is not specified, it defaults to Error. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: Type of condition. - type: string - required: - - status - - type - type: object - type: array - hubInstallerSets: - additionalProperties: - type: string - description: The current installer set name - type: object - manifests: - description: The url links of the manifests, separated by comma - items: - type: string - type: array - observedGeneration: - description: |- - ObservedGeneration is the 'Generation' of the Service that - was last processed by the controller. - format: int64 - type: integer - uiUrl: - description: The URL route for UI which needs to be exposed - type: string - version: - description: The version of the installed release - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/config/base/kustomization.yaml b/config/base/kustomization.yaml index c812637d85..bc478bd846 100644 --- a/config/base/kustomization.yaml +++ b/config/base/kustomization.yaml @@ -38,7 +38,6 @@ resources: - generated-crds/operator.tekton.dev_syncerservices.yaml - generated-crds/operator.tekton.dev_tektonchains.yaml - generated-crds/operator.tekton.dev_tektonconfigs.yaml -- generated-crds/operator.tekton.dev_tektonhubs.yaml - generated-crds/operator.tekton.dev_tektoninstallersets.yaml - generated-crds/operator.tekton.dev_tektonmulticlusterproxyaaes.yaml - generated-crds/operator.tekton.dev_tektonpipelines.yaml diff --git a/config/crs/kubernetes/hub/operator_v1alpha1_hub_cr.yaml b/config/crs/kubernetes/hub/operator_v1alpha1_hub_cr.yaml deleted file mode 100644 index f28855410c..0000000000 --- a/config/crs/kubernetes/hub/operator_v1alpha1_hub_cr.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2022 The Tekton 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. - -apiVersion: operator.tekton.dev/v1alpha1 -kind: TektonHub -metadata: - name: hub -spec: - api: - catalogRefreshInterval: 30m - targetNamespace: tekton-pipelines diff --git a/config/crs/kubernetes/kustomization.yaml b/config/crs/kubernetes/kustomization.yaml index d3e28ceebe..2c170d9577 100644 --- a/config/crs/kubernetes/kustomization.yaml +++ b/config/crs/kubernetes/kustomization.yaml @@ -8,7 +8,6 @@ resources: - config/all/operator_v1alpha1_config_cr.yaml - installerset/operator_v1alpha1_installerset_cr.yaml - chain/operator_v1alpha1_chain_cr.yaml -- hub/operator_v1alpha1_hub_cr.yaml - manualapprovalgate/operator_v1alpha1_manualapprovalgate_cr.yaml - pruner/operator_v1alpha1_pruner_cr.yaml - scheduler/operator_v1alpha1_scheduler_cr.yaml diff --git a/config/crs/openshift/hub/operator_v1alpha1_hub_cr.yaml b/config/crs/openshift/hub/operator_v1alpha1_hub_cr.yaml deleted file mode 100644 index 95b16ccb51..0000000000 --- a/config/crs/openshift/hub/operator_v1alpha1_hub_cr.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2022 The Tekton 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. - -apiVersion: operator.tekton.dev/v1alpha1 -kind: TektonHub -metadata: - name: hub -spec: - api: - catalogRefreshInterval: 30m - targetNamespace: openshift-pipelines diff --git a/config/crs/openshift/kustomization.yaml b/config/crs/openshift/kustomization.yaml index 9e6dbed45c..d995f9b552 100644 --- a/config/crs/openshift/kustomization.yaml +++ b/config/crs/openshift/kustomization.yaml @@ -5,7 +5,6 @@ resources: - trigger/operator_v1alpha1_trigger_cr.yaml - installerset/operator_v1alpha1_installerset_cr.yaml - chain/operator_v1alpha1_chain_cr.yaml -- hub/operator_v1alpha1_hub_cr.yaml - pipelinesascode/operator_v1alpha1_openshiftpipelinesascode_cr.yaml - result/operator_v1alpha1_result_cr.yaml - manualapprovalgate/operator_v1alpha1_manualapprovalgate_cr.yaml diff --git a/config/kubernetes/base/operator.yaml b/config/kubernetes/base/operator.yaml index 1668219f4f..14cf1cbc3e 100644 --- a/config/kubernetes/base/operator.yaml +++ b/config/kubernetes/base/operator.yaml @@ -33,7 +33,7 @@ spec: image: ko://github.com/tektoncd/operator/cmd/kubernetes/operator args: - "-controllers" - - "tektonconfig,tektonpipeline,tektontrigger,tektonhub,tektonchain,tektonresult,tektondashboard,manualapprovalgate,tektonpruner,tektonscheduler,tektonmulticlusterproxyaae,openshiftpipelinesascode" + - "tektonconfig,tektonpipeline,tektontrigger,tektonchain,tektonresult,tektondashboard,manualapprovalgate,tektonpruner,tektonscheduler,tektonmulticlusterproxyaae,openshiftpipelinesascode" - "-unique-process-name" - "tekton-operator-lifecycle" imagePullPolicy: IfNotPresent diff --git a/config/openshift/base/operator.yaml b/config/openshift/base/operator.yaml index 6b8eb976bd..e570a64a5a 100644 --- a/config/openshift/base/operator.yaml +++ b/config/openshift/base/operator.yaml @@ -38,7 +38,7 @@ spec: image: ko://github.com/tektoncd/operator/cmd/openshift/operator args: - "-controllers" - - "tektonconfig,tektonpipeline,tektontrigger,tektonhub,tektonchain,tektonaddon,tektonresult,openshiftpipelinesascode,manualapprovalgate,tektonpruner,tektonscheduler,tektonmulticlusterproxyaae,syncerservice" + - "tektonconfig,tektonpipeline,tektontrigger,tektonchain,tektonaddon,tektonresult,openshiftpipelinesascode,manualapprovalgate,tektonpruner,tektonscheduler,tektonmulticlusterproxyaae,syncerservice" - "-unique-process-name" - "tekton-operator-lifecycle" imagePullPolicy: Always @@ -87,8 +87,6 @@ spec: value: tekton-config-observability - name: CONFIG_LEADERELECTION_NAME value: tekton-operator-controller-config-leader-election - - name: IMAGE_HUB_TEKTON_HUB_DB - value: registry.redhat.io/rhel9/postgresql-15@sha256:327d89e4b62d990dbf55d3c78f271373747816c2e0ab3c943fb016cdcf12f9b5 - name: IMAGE_ADDONS_PARAM_BUILDER_IMAGE value: registry.redhat.io/rhel9/buildah@sha256:f0432e506a8aea892078322518aedeb12e0f17504dbc29fd293cd8cda06e7f73 - name: IMAGE_ADDONS_PARAM_KN_IMAGE diff --git a/docs/AirGapImageConfiguration.md b/docs/AirGapImageConfiguration.md index 5f7c04f66f..9f2d9e3a4f 100644 --- a/docs/AirGapImageConfiguration.md +++ b/docs/AirGapImageConfiguration.md @@ -69,11 +69,7 @@ kubectl delete tektoninstallerset | Component | Container/Args name | Environment Variable | |------------------------|------------------------------------|----------------------------------------------------| | Chains | tekton-chains-controller | `IMAGE_CHAINS_TEKTON_CHAINS_CONTROLLER` | -| Dashboard | tekton-dashboard | `IMAGE_DASHBOARD_TEKTON_DASHBOARD` | -| Hub | tekton-hub-api | `IMAGE_HUB_TEKTON_HUB_API` | -| Hub | tekton-hub-db | `IMAGE_HUB_TEKTON_HUB_DB` | -| Hub | tekton-hub-db-migration | `IMAGE_HUB_TEKTON_HUB_DB_MIGRATION` | -| Hub | tekton-hub-ui | `IMAGE_HUB_TEKTON_HUB_UI` | +| Dashboard | tekton-dashboard | `IMAGE_DASHBOARD_TEKTON_DASHBOARD` | | | Manual Approval Gate | manual-approval | `IMAGE_MAG_MANUAL_APPROVAL` | | Manual Approval Gate | tekton-taskgroup-controller | `IMAGE_MAG_TEKTON_TASKGROUP_CONTROLLER` | | Pipeline | arg:entrypoint-image | `IMAGE_PIPELINES_ARG__ENTRYPOINT_IMAGE` | diff --git a/docs/TektonConfig.md b/docs/TektonConfig.md index 6b191ff93e..cb19ad4dd8 100644 --- a/docs/TektonConfig.md +++ b/docs/TektonConfig.md @@ -104,15 +104,6 @@ spec: # keep-since: 1440 # NOTE: you can use either "keep" or "keep-since", not both prune-per-resource: true - hub: - params: - - name: enable-devconsole-integration - value: "true" - options: - disabled: false - configMaps: {} - deployments: {} - webhookConfigurationOptions: {} dashboard: readonly: true options: @@ -496,21 +487,6 @@ addon: **NOTE**: TektonAddon is currently available for OpenShift Platform only. Enabling this for Kubernetes platform is in roadmap of Operator. -### Hub - -This is to enable/disable showing hub resources in pipeline builder of devconsole(OpenShift UI). By default, the field is -not there in the config object. If you want to disable the integration, you can add the param like below in config with value `false`. -The possible values are `true` and `false`. - -Example: - -```yaml -hub: - params: - - name: enable-devconsole-integration - value: "false" -``` - ### Dashboard Dashboard provides configuration options for the Tekton Dashboard if the specified profile value includes the Dashboard component. (E.g. `all` on Kubernetes) diff --git a/docs/TektonHub.md b/docs/TektonHub.md deleted file mode 100644 index 6ccd3f80b3..0000000000 --- a/docs/TektonHub.md +++ /dev/null @@ -1,184 +0,0 @@ -# Tekton Hub - -TektonHub custom resource allows user to install and manage [Tekton Hub][hub]. - -TektonHub is an optional component and currently cannot be installed through TektonConfig. It has to be installed -seperately. It is available for both Kubernetes and OpenShift platform. - -To install Tekton Hub on your cluster follow steps as given below: - - - **Note** : - - Initially user had to enable Tekton Hub Authentication, get the Hub token with required scopes and then hit the catalog refresh api to load the resources in the database. - - Now user doesn't needs to enable login mechanism to get the resources populated in the database as resources will be automatically populated in the database when the api is up and running - - Resources in the hub db will be also automatically refreshed with the updated data with the time which is specified in the Hub CR i.e `catalogRefreshInterval: 30m`. Default time interval is 30m - - If you are using your database instead of default one then - secret name for the database should be `tekton-hub-db` and you need to create the secret in your targetNamespace with the following keys - - **The dependency of config.yaml from git is removed and complete config data is moved into API configMap. Now user can add the config data i.e. - `categories, catalogs, scopes and defaultScopes` in the Hub CR itself. If user does not add any data then default - data provided by Hub in the API configMap will be used** - - ```yaml - apiVersion: v1 - kind: Secret - metadata: - name: tekton-hub-db - labels: - app: tekton-hub-db - type: Opaque - stringData: - POSTGRES_HOST: - POSTGRES_DB: - POSTGRES_USER: - POSTGRES_PASSWORD: - POSTGRES_PORT: - ``` - -### 1. Without login and rating - -- This is how TektonHub CR looks - - ```yaml - apiVersion: operator.tekton.dev/v1alpha1 - kind: TektonHub - metadata: - name: hub - spec: - targetNamespace: - # in which you want to install Tekton Hub. Leave it blank if in case you want to install - # in default installation namespace ie `openshift-pipelines` in case of OpenShift and `tekton-pipelines` in case of Kubernetes - db: # 👈 Optional: If user wants to use his database - secret: tekton-hub-db # 👈 Name of db secret should be `tekton-hub-db` - - categories: # 👈 Optional: If user wants to use his categories - - Automation - - Build Tools - - CLI - - Cloud - - Code Quality - - ... - - catalogs: # 👈 Optional: If user wants to use his catalogs - - name: tekton - org: tektoncd - type: community - provider: github - url: https://github.com/tektoncd/catalog - revision: main - - scopes: # 👈 Optional: User can define his scopes - - name: agent:create - users: [abc, qwe, pqr] - - name: catalog:refresh - users: [abc, qwe, pqr] - - name: config:refresh - users: [abc, qwe, pqr] - - default: # 👈 Optional: User can define his default scopes - scopes: - - rating:read - - rating:write - - api: - catalogRefreshInterval: 30m # After every 30min catalog resources in the hub db would be refreshed to get the updated data from the catalog. Supported time units are As(A seconds), Bm(B minutes) Ch(C hours), Dd(D days) and Ew(E weeks). - ``` - -- You can install Tekton Hub by running the command - - ```sh - kubectl apply -f .yaml - ``` - -- Check the status of installation using following command - - ```sh - $ kubectl get tektonhub.operator.tekton.dev - NAME VERSION READY REASON APIURL UIURL - hub v1.8.0 True https://api.route.url https://ui.route.url - ``` - -### 2. With login and rating -1. Create the secrets for the API before we install Tekton Hub. By default, Tekton Hub expects this secret to have the - following properties: - - - namespace: TargetNamespace defined in TektonHub CR at the time of applying. If nothing is specified then based on - platform create the secrets. `openshift-pipelines` in case of OpenShift, `tekton-pipelines` in case of Kubernetes. - - name: `tekton-hub-api` - - contains the fields: - - - `GH_CLIENT_ID=` - - `GH_CLIENT_SECRET=` - - `GL_CLIENT_ID=` - - `GL_CLIENT_SECRET=` - - `BB_CLIENT_ID=` - - `BB_CLIENT_SECRET=` - - `JWT_SIGNING_KEY=` - - `ACCESS_JWT_EXPIRES_IN=` - - `REFRESH_JWT_EXPIRES_IN=` - - `GHE_URL=` - - `GLE_URL=` - - > _Note 1_: For more details please refer to [here](https://github.com/openshift-pipelines/hub/blob/main/docs/DEPLOYMENT.md#create-git-oauth-applications) - -3. Once the secrets are created now we need to understand how TektonHub CR looks. - - ```yaml - apiVersion: operator.tekton.dev/v1alpha1 - kind: TektonHub - metadata: - name: hub - spec: - targetNamespace: - # in which you want to install Tekton Hub. Leave it blank if in case you want to install - # in default installation namespace ie `openshift-pipelines` in case of OpenShift and `tekton-pipelines` in case of Kubernetes - db: # 👈 Optional: If user wants to use his database - secret: tekton-hub-db # 👈 Name of db secret should be `tekton-hub-db` - - categories: # 👈 Optional: If user wants to use his categories - - Automation - - Build Tools - - CLI - - Cloud - - Code Quality - - ... - - catalogs: # 👈 Optional: If user wants to use his catalogs - - name: tekton - org: tektoncd - type: community - provider: github - url: https://github.com/tektoncd/catalog - revision: main - - scopes: # 👈 Optional: User can define his scopes - - name: agent:create - users: [abc, qwe, pqr] - - name: catalog:refresh - users: [abc, qwe, pqr] - - name: config:refresh - users: [abc, qwe, pqr] - - default: # 👈 Optional: User can define his default scopes - scopes: - - rating:read - - rating:write - - api: - catalogRefreshInterval: 30m # After every 30min catalog resources in the hub db would be refreshed to get the updated data from the catalog. Supported time units are As(A seconds), Bm(B minutes) Ch(C hours), Dd(D days) and Ew(E weeks). - ``` - -4. After configuring the TektonHub spec you can install Tekton Hub by running the command - - ```sh - kubectl apply -f .yaml - ``` - -5. Check the status of installation using following command - - ```sh - $ kubectl get tektonhub.operator.tekton.dev - NAME VERSION READY REASON APIURL UIURL - hub v1.6.0 True https://api.route.url https://ui.route.url - ``` - -[hub]: https://github.com/openshift-pipelines/hub diff --git a/go.mod b/go.mod index 3a9af8d5f7..f9bd8d91af 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,6 @@ require ( github.com/openshift/library-go v0.0.0-20260303171201-5d9eb6295ff6 github.com/sigstore/cosign/v2 v2.6.3 github.com/spf13/cobra v1.10.2 - github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 github.com/tektoncd/pipeline v1.12.0 github.com/tektoncd/plumbing v0.0.0-20250805154627-25448098dea2 @@ -250,6 +249,7 @@ require ( github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect + github.com/spf13/viper v1.21.0 // indirect github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect diff --git a/hack/fetch-releases.sh b/hack/fetch-releases.sh index c2dd4250a2..e3d98c649d 100755 --- a/hack/fetch-releases.sh +++ b/hack/fetch-releases.sh @@ -309,57 +309,6 @@ release_yaml_manualapprovalgate() { } -release_yaml_hub() { - echo fetching '|' component: ${1} '|' version: ${2} - local version=$2 - - ko_data=${SCRIPT_DIR}/cmd/${TARGET}/operator/kodata - if [ ${version} == "latest" ] - then - version=$(curl -sL https://api.github.com/repos/openshift-pipelines/hub/releases | jq -r ".[].tag_name" | sort -Vr | head -n1) - dirPath=${ko_data}/tekton-hub/0.0.0-latest - else - dirPath=${ko_data}/tekton-hub/${version} - fi - mkdir -p ${dirPath} || true - - url="" - components="db db-migration api ui hub-info" - - for component in ${components}; do - echo fetching Hub '|' component: ${component} '|' version: ${2} - - dest=${dirPath}/${component} - fileName=${component}.yaml - destinationFile=${dest}/${fileName} - - if [ -f "$destinationFile" ] && [ $FORCE_FETCH_RELEASE = "false" ]; then - if grep -Eq "$version" $destinationFile; - then - echo "release file already exist with required version, skipping!" - echo "" - continue - fi - fi - - rm -rf ${dest} || true - mkdir -p ${dest} || true - - [[ ${component} == "api" ]] || [[ ${component} == "ui" ]] && fileName=${component}-${TARGET}.yaml - - url="https://github.com/openshift-pipelines/hub/releases/download/${version}/${fileName}" - echo $url - http_response=$(curl -s -L -o ${destinationFile} -w "%{http_code}" ${url}) - echo url: ${url} - if [[ $http_response != "200" ]]; then - echo "Error: failed to get ${component} yaml, status code: $http_response" - exit 1 - fi - echo "Info: Added Hub/$fileName:$version release yaml !!" - echo "" - done -} - fetch_openshift_addon_tasks() { fetch_addon_task_script="${SCRIPT_DIR}/hack/openshift" local dest_dir='cmd/openshift/operator/kodata/tekton-addon/addons/06-ecosystem/tasks' @@ -425,9 +374,6 @@ main() { fetch_openshift_addon_tasks fi - hub_version=$(go run ./cmd/tool component-version ${CONFIG} hub) - release_yaml_hub hub ${hub_version} - mag_version=$(go run ./cmd/tool component-version ${CONFIG} manual-approval-gate) release_yaml_manualapprovalgate ${mag_version} diff --git a/hack/sync-helm-crds.sh b/hack/sync-helm-crds.sh index cada786279..f805881555 100755 --- a/hack/sync-helm-crds.sh +++ b/hack/sync-helm-crds.sh @@ -113,7 +113,6 @@ echo "Step 1: Updating config/ CRD files..." write_config_crd "${GENERATED_DIR}/operator.tekton.dev_manualapprovalgates.yaml" "$BASE_DIR" "300-operator_v1alpha1_manualapprovalgate_crd.yaml" write_config_crd "${GENERATED_DIR}/operator.tekton.dev_tektonchains.yaml" "$BASE_DIR" "300-operator_v1alpha1_chain_crd.yaml" write_config_crd "${GENERATED_DIR}/operator.tekton.dev_tektonconfigs.yaml" "$BASE_DIR" "300-operator_v1alpha1_config_crd.yaml" -write_config_crd "${GENERATED_DIR}/operator.tekton.dev_tektonhubs.yaml" "$BASE_DIR" "300-operator_v1alpha1_hub_crd.yaml" write_config_crd "${GENERATED_DIR}/operator.tekton.dev_tektoninstallersets.yaml" "$BASE_DIR" "300-operator_v1alpha1_installer_set_crd.yaml" write_config_crd "${GENERATED_DIR}/operator.tekton.dev_tektonpipelines.yaml" "$BASE_DIR" "300-operator_v1alpha1_pipeline_crd.yaml" write_config_crd "${GENERATED_DIR}/operator.tekton.dev_tektonresults.yaml" "$BASE_DIR" "300-operator_v1alpha1_result_crd.yaml" @@ -143,7 +142,6 @@ assemble_helm_crds \ "operator.tekton.dev_tektonchains.yaml" \ "operator.tekton.dev_tektonconfigs.yaml" \ "operator.tekton.dev_tektondashboards.yaml" \ - "operator.tekton.dev_tektonhubs.yaml" \ "operator.tekton.dev_tektoninstallersets.yaml" \ "operator.tekton.dev_tektonpipelines.yaml" \ "operator.tekton.dev_tektonresults.yaml" \ @@ -161,7 +159,6 @@ assemble_helm_crds \ "operator.tekton.dev_tektonaddons.yaml" \ "operator.tekton.dev_tektonchains.yaml" \ "operator.tekton.dev_tektonconfigs.yaml" \ - "operator.tekton.dev_tektonhubs.yaml" \ "operator.tekton.dev_tektoninstallersets.yaml" \ "operator.tekton.dev_tektonpipelines.yaml" \ "operator.tekton.dev_tektonresults.yaml" \ diff --git a/operatorhub/kubernetes/manifests/bases/tektoncd-operator.clusterserviceversion.template.yaml b/operatorhub/kubernetes/manifests/bases/tektoncd-operator.clusterserviceversion.template.yaml index 4771db54d3..4228e32dd8 100644 --- a/operatorhub/kubernetes/manifests/bases/tektoncd-operator.clusterserviceversion.template.yaml +++ b/operatorhub/kubernetes/manifests/bases/tektoncd-operator.clusterserviceversion.template.yaml @@ -51,14 +51,6 @@ spec: kind: TektonTrigger name: tektontriggers.operator.tekton.dev version: v1alpha1 - - description: | - TektonHub installs Tekton Hub on a cluster. The operator installs Tekton Hub on a cluster - if an instance of this CRD is created on your cluster with name `hub`. At present, the operator honors only - one CustomResource instance with the name `hub` to ensure only one set of Tekton Hub exists on a cluster. - displayName: TektonHubs - kind: TektonHub - name: tektonhubs.operator.tekton.dev - version: v1alpha1 - description: | TektonInstallerSet internal CRD used by other component reconcilers to create kubernetes resources from their release manifests diff --git a/operatorhub/kubernetes/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml b/operatorhub/kubernetes/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml deleted file mode 100644 index 47c1f549fc..0000000000 --- a/operatorhub/kubernetes/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml +++ /dev/null @@ -1,49 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - operator.tekton.dev/release: v0.75.0 - version: v0.75.0 - name: tektonhubs.operator.tekton.dev -spec: - group: operator.tekton.dev - names: - kind: TektonHub - listKind: TektonHubList - plural: tektonhubs - singular: tektonhub - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.version - name: Version - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Reason - type: string - - jsonPath: .status.apiUrl - name: ApiUrl - type: string - - jsonPath: .status.uiUrl - name: UiUrl - type: string - name: v1alpha1 - schema: - openAPIV3Schema: - description: Schema for the tektonhubs API - type: object - x-kubernetes-preserve-unknown-fields: true - served: true - storage: true - subresources: - status: {} -status: - acceptedNames: - kind: "" - plural: "" - conditions: null - storedVersions: null diff --git a/operatorhub/kubernetes/release-artifacts/bundle/manifests/tektoncd-operator.clusterserviceversion.yaml b/operatorhub/kubernetes/release-artifacts/bundle/manifests/tektoncd-operator.clusterserviceversion.yaml index 2b6be117f8..3f91fc010e 100644 --- a/operatorhub/kubernetes/release-artifacts/bundle/manifests/tektoncd-operator.clusterserviceversion.yaml +++ b/operatorhub/kubernetes/release-artifacts/bundle/manifests/tektoncd-operator.clusterserviceversion.yaml @@ -16,10 +16,7 @@ metadata: \ },\n \"targetNamespace\": \"tekton-pipelines\"\n }\n },\n {\n\ \ \"apiVersion\": \"operator.tekton.dev/v1alpha1\",\n \"kind\": \"TektonDashboard\"\ ,\n \"metadata\": {\n \"name\": \"dashboard\"\n },\n \"spec\"\ - : {\n \"targetNamespace\": \"tekton-pipelines\"\n }\n },\n {\n \ - \ \"apiVersion\": \"operator.tekton.dev/v1alpha1\",\n \"kind\": \"TektonHub\"\ - ,\n \"metadata\": {\n \"name\": \"hub\"\n },\n \"spec\": {\n \ - \ \"targetNamespace\": \"tekton-pipelines\"\n }\n },\n {\n \"apiVersion\"\ + : {\n \"targetNamespace\": \"tekton-pipelines\"\n }\n },\n {\n \"apiVersion\"\ : \"operator.tekton.dev/v1alpha1\",\n \"kind\": \"TektonInstallerSet\",\n\ \ \"metadata\": {\n \"name\": \"foo\"\n },\n \"spec\": {\n \ \ \"manifests\": []\n }\n },\n {\n \"apiVersion\": \"operator.tekton.dev/v1alpha1\"\ @@ -116,20 +113,6 @@ spec: kind: TektonDashboard name: tektondashboards.operator.tekton.dev version: v1alpha1 - - description: 'TektonHub installs Tekton Hub on a cluster. The operator installs - Tekton Hub on a cluster - - if an instance of this CRD is created on your cluster with name `hub`. At - present, the operator honors only - - one CustomResource instance with the name `hub` to ensure only one set of - Tekton Hub exists on a cluster. - - ' - displayName: TektonHubs - kind: TektonHub - name: tektonhubs.operator.tekton.dev - version: v1alpha1 - description: 'TektonInstallerSet internal CRD used by other component reconcilers to create kubernetes resources from their @@ -863,7 +846,7 @@ spec: containers: - args: - -controllers - - tektonconfig,tektonpipeline,tektontrigger,tektonhub,tektonchain,tektonresult,tektondashboard,manualapprovalgate + - tektonconfig,tektonpipeline,tektontrigger,tektonchain,tektonresult,tektondashboard,manualapprovalgate - -unique-process-name - tekton-operator-lifecycle env: diff --git a/operatorhub/openshift/config.yaml b/operatorhub/openshift/config.yaml index 1ce0d156fb..899a6d909c 100644 --- a/operatorhub/openshift/config.yaml +++ b/operatorhub/openshift/config.yaml @@ -216,29 +216,7 @@ image-substitutions: - deploymentName: openshift-pipelines-operator containerName: openshift-pipelines-operator-lifecycle envKeys: - - IMAGE_HUB_TEKTON_HUB_DB - IMAGE_RESULTS_POSTGRES -- image: registry.redhat.io/openshift-pipelines/pipelines-hub-db-migration-rhel9@ - replaceLocations: - envTargets: - - deploymentName: openshift-pipelines-operator - containerName: openshift-pipelines-operator-lifecycle - envKeys: - - IMAGE_HUB_TEKTON_HUB_DB_MIGRATION -- image: registry.redhat.io/openshift-pipelines/pipelines-hub-api-rhel9@ - replaceLocations: - envTargets: - - deploymentName: openshift-pipelines-operator - containerName: openshift-pipelines-operator-lifecycle - envKeys: - - IMAGE_HUB_TEKTON_HUB_API -- image: registry.redhat.io/openshift-pipelines/pipelines-hub-ui-rhel9@ - replaceLocations: - envTargets: - - deploymentName: openshift-pipelines-operator - containerName: openshift-pipelines-operator-lifecycle - envKeys: - - IMAGE_HUB_TEKTON_HUB_UI - image: registry.redhat.io/openshift-pipelines/pipelines-manual-approval-gate-rhel9@ replaceLocations: envTargets: diff --git a/operatorhub/openshift/manifests/bases/openshift-pipelines-operator-rh.clusterserviceversion.template.yaml b/operatorhub/openshift/manifests/bases/openshift-pipelines-operator-rh.clusterserviceversion.template.yaml index 43a9169b70..7ac639ebbd 100644 --- a/operatorhub/openshift/manifests/bases/openshift-pipelines-operator-rh.clusterserviceversion.template.yaml +++ b/operatorhub/openshift/manifests/bases/openshift-pipelines-operator-rh.clusterserviceversion.template.yaml @@ -20,7 +20,7 @@ metadata: features.operators.openshift.io/cnf: "false" features.operators.openshift.io/cni: "false" features.operators.openshift.io/csi: "false" - operators.operatorframework.io/internal-objects: '["tektoninstallersets.operator.tekton.dev", "tektonconfigs.operator.tekton.dev","tektonpipelines.operator.tekton.dev","tektontriggers.operator.tekton.dev","tektonaddons.operator.tekton.dev", "tektonhubs.operator.tekton.dev", "tektonresults.operator.tekton.dev", "tektonchains.operator.tekton.dev", "openshiftpipelinesascodes.operator.tekton.dev", "manualapprovalgates.operator.tekton.dev","tektonpruners.operator.tekton.dev","tektonschedulers.operator.tekton.dev","tektonmulticlusterproxyaaes.operator.tekton.dev","syncerservices.operator.tekton.dev"]' + operators.operatorframework.io/internal-objects: '["tektoninstallersets.operator.tekton.dev", "tektonconfigs.operator.tekton.dev","tektonpipelines.operator.tekton.dev","tektontriggers.operator.tekton.dev","tektonaddons.operator.tekton.dev", "tektonresults.operator.tekton.dev", "tektonchains.operator.tekton.dev", "openshiftpipelinesascodes.operator.tekton.dev", "manualapprovalgates.operator.tekton.dev","tektonpruners.operator.tekton.dev","tektonschedulers.operator.tekton.dev","tektonmulticlusterproxyaaes.operator.tekton.dev","syncerservices.operator.tekton.dev"]' repository: https://github.com/tektoncd/operator support: Red Hat labels: @@ -177,27 +177,6 @@ spec: x-descriptors: - urn:alm:descriptor:com.tectonic.ui:label version: v1alpha1 - - description: Represents an installation of latest version of Hub - displayName: Tekton Hub - kind: TektonHub - name: tektonhubs.operator.tekton.dev - resources: - - kind: tektoninstallersets - name: '' - version: v1alpha1 - specDescriptors: - - description: Namespace where Addons installed - displayName: Target Namespace - path: targetNamespace - x-descriptors: - - urn:alm:descriptor:com.tectonic.ui:label - statusDescriptors: - - description: The version of Addons installed - displayName: Version - path: version - x-descriptors: - - urn:alm:descriptor:com.tectonic.ui:label - version: v1alpha1 - description: Represents an installation of latest version of OpenShift Pipelines As Code displayName: OpenShift Pipelines As Code kind: OpenShiftPipelinesAsCode diff --git a/operatorhub/openshift/release-artifacts/bundle/manifests/openshift-pipelines-operator-rh.clusterserviceversion.yaml b/operatorhub/openshift/release-artifacts/bundle/manifests/openshift-pipelines-operator-rh.clusterserviceversion.yaml index a91dcaa2d0..3cb2839c91 100644 --- a/operatorhub/openshift/release-artifacts/bundle/manifests/openshift-pipelines-operator-rh.clusterserviceversion.yaml +++ b/operatorhub/openshift/release-artifacts/bundle/manifests/openshift-pipelines-operator-rh.clusterserviceversion.yaml @@ -21,9 +21,6 @@ metadata: \ \"resources\": [\n \"pipelinerun\",\n \"taskrun\"\ \n ],\n \"schedule\": \"0 8 * * *\"\n },\n \"targetNamespace\"\ : \"openshift-pipelines\"\n }\n },\n {\n \"apiVersion\": \"operator.tekton.dev/v1alpha1\"\ - ,\n \"kind\": \"TektonHub\",\n \"metadata\": {\n \"name\": \"hub\"\ - \n },\n \"spec\": {\n \"api\": {\n \"hubConfigUrl\": \"https://raw.githubusercontent.com/openshift-pipelines/hub/main/config.yaml\"\ - \n }\n }\n },\n {\n \"apiVersion\": \"operator.tekton.dev/v1alpha1\"\ ,\n \"kind\": \"TektonInstallerSet\",\n \"metadata\": {\n \"name\"\ : \"foo\"\n },\n \"spec\": {\n \"manifests\": []\n }\n },\n \ \ {\n \"apiVersion\": \"operator.tekton.dev/v1alpha1\",\n \"kind\": \"\ @@ -44,7 +41,7 @@ metadata: operators.operatorframework.io/builder: operator-sdk-v1.21.0 operators.operatorframework.io/internal-objects: '["tektoninstallersets.operator.tekton.dev", "tektonconfigs.operator.tekton.dev","tektonpipelines.operator.tekton.dev","tektontriggers.operator.tekton.dev","tektonaddons.operator.tekton.dev", - "tektonhubs.operator.tekton.dev", "tektonchains.operator.tekton.dev"]' + "tektonchains.operator.tekton.dev"]' operators.operatorframework.io/project_layout: unknown repository: https://github.com/openshift/tektoncd-operator support: Red Hat @@ -118,27 +115,6 @@ spec: x-descriptors: - urn:alm:descriptor:com.tectonic.ui:label version: v1alpha1 - - description: Represents an installation of latest version of Hub - displayName: Tekton Hub - kind: TektonHub - name: tektonhubs.operator.tekton.dev - resources: - - kind: tektoninstallersets - name: '' - version: v1alpha1 - specDescriptors: - - description: Namespace where Addons installed - displayName: Target Namespace - path: targetNamespace - x-descriptors: - - urn:alm:descriptor:com.tectonic.ui:label - statusDescriptors: - - description: The version of Addons installed - displayName: Version - path: version - x-descriptors: - - urn:alm:descriptor:com.tectonic.ui:label - version: v1alpha1 - description: This CustomResourceDefinition (CRD) is used internally by the other OpenShift Pipelines CRDs to maintain the lifecycle of OpenShift Pipelines Components @@ -849,8 +825,6 @@ spec: name: tekton-config-defaults - name: CONFIG_OBSERVABILITY_NAME value: tekton-config-observability - - name: IMAGE_HUB_TEKTON_HUB_DB - value: registry.redhat.io/rhel9/postgresql-13@sha256:36647bd6d50d2e0e9c99ecf190bd515577c7ce9476e49d927c4d4065011e3441 - name: IMAGE_ADDONS_PARAM_BUILDER_IMAGE value: registry.redhat.io/rhel9/buildah@sha256:f0432e506a8aea892078322518aedeb12e0f17504dbc29fd293cd8cda06e7f73 - name: IMAGE_ADDONS_PARAM_KN_IMAGE @@ -945,12 +919,6 @@ spec: value: registry.redhat.io/openshift-pipelines/pipelines-results-api-rhel9@ - name: IMAGE_RESULTS_RETENTION_POLICY_AGENT value: registry.redhat.io/openshift-pipelines/pipelines-results-retention-policy-agent-rhel9@ - - name: IMAGE_HUB_TEKTON_HUB_DB_MIGRATION - value: registry.redhat.io/openshift-pipelines/pipelines-hub-db-migration-rhel9@ - - name: IMAGE_HUB_TEKTON_HUB_API - value: registry.redhat.io/openshift-pipelines/pipelines-hub-api-rhel9@ - - name: IMAGE_HUB_TEKTON_HUB_UI - value: registry.redhat.io/openshift-pipelines/pipelines-hub-ui-rhel9@ - name: IMAGE_PAC_TRIGGERTEMPLATE_APPLY_AND_LAUNCH value: registry.redhat.io/openshift-pipelines/pipelines-pipelines-as-code-rhel9@ - name: IMAGE_MAG_TEKTON_TASKGROUP_CONTROLLER @@ -1150,14 +1118,6 @@ spec: name: TEKTON_OPERATOR_WEBHOOK - image: registry.redhat.io/openshift-pipelines/pipelines-chains-controller-rhel9@ name: IMAGE_CHAINS_TEKTON_CHAINS_CONTROLLER - - image: registry.redhat.io/rhel9/postgresql-13@sha256:36647bd6d50d2e0e9c99ecf190bd515577c7ce9476e49d927c4d4065011e3441 - name: IMAGE_HUB_TEKTON_HUB_DB - - image: registry.redhat.io/openshift-pipelines/pipelines-hub-db-migration-rhel9@ - name: IMAGE_HUB_TEKTON_HUB_DB_MIGRATION - - image: registry.redhat.io/openshift-pipelines/pipelines-hub-api-rhel9@ - name: IMAGE_HUB_TEKTON_HUB_API - - image: registry.redhat.io/openshift-pipelines/pipelines-hub-ui-rhel9@ - name: IMAGE_HUB_TEKTON_HUB_UI - image: registry.redhat.io/openshift-pipelines/pipelines-pipelines-as-code-rhel9@ name: IMAGE_PAC_TRIGGERTEMPLATE_APPLY_AND_LAUNCH - image: registry.redhat.io/source-to-image/source-to-image-rhel9@sha256:70293cb8a80aa548933ff5f502bac89945a5cd08801c4ca3aac08a10dd01f62f diff --git a/operatorhub/openshift/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml b/operatorhub/openshift/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml deleted file mode 100644 index 9a16d73834..0000000000 --- a/operatorhub/openshift/release-artifacts/bundle/manifests/operator.tekton.dev_tektonhubs.yaml +++ /dev/null @@ -1,49 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - labels: - operator.tekton.dev/release: devel - version: devel - name: tektonhubs.operator.tekton.dev -spec: - group: operator.tekton.dev - names: - kind: TektonHub - listKind: TektonHubList - plural: tektonhubs - singular: tektonhub - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.version - name: Version - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].reason - name: Reason - type: string - - jsonPath: .status.apiUrl - name: ApiUrl - type: string - - jsonPath: .status.uiUrl - name: UiUrl - type: string - name: v1alpha1 - schema: - openAPIV3Schema: - description: Schema for the tektonhubs API - type: object - x-kubernetes-preserve-unknown-fields: true - served: true - storage: true - subresources: - status: {} -status: - acceptedNames: - kind: "" - plural: "" - conditions: null - storedVersions: null diff --git a/pkg/apis/operator/v1alpha1/const.go b/pkg/apis/operator/v1alpha1/const.go index adfef751eb..9266323011 100644 --- a/pkg/apis/operator/v1alpha1/const.go +++ b/pkg/apis/operator/v1alpha1/const.go @@ -38,9 +38,6 @@ const ( ResolverTasks = "resolverTasks" ResolverStepActions = "resolverStepActions" - // Hub Params - EnableDevconsoleIntegrationParam = "enable-devconsole-integration" - PlatformDataHashKey = "operator.tekton.dev/platform-data-hash" LastAppliedHashKey = "operator.tekton.dev/last-applied-hash" CreatedByKey = "operator.tekton.dev/created-by" @@ -51,7 +48,6 @@ const ( InstallerSetType = "operator.tekton.dev/type" InstallerSetInstallType = "operator.tekton.dev/installType" LabelOperandName = "operator.tekton.dev/operand-name" - DbSecretHash = "operator.tekton.dev/db-secret-hash" DeploymentSpecHashValueLabelKey = "operator.tekton.dev/deployment-spec-applied-hash" // used to recreate pods, if there is a change detected in deployments spec PreUpgradeVersionKey = "operator.tekton.dev/pre-upgrade-version" // used to monitor and execute pre upgrade functions PostUpgradeVersionKey = "operator.tekton.dev/post-upgrade-version" // used to monitor and execute post upgrade functions @@ -120,10 +116,6 @@ var ( ResolverTasks: defaultParamValue, ResolverStepActions: defaultParamValue, } - - HubParams = map[string]ParamValue{ - EnableDevconsoleIntegrationParam: defaultParamValue, - } ) const ( @@ -137,8 +129,6 @@ const ( AddonResourceName = "addon" ResultResourceName = "result" OperandTektoncdResults = "tektoncd-results" - HubResourceName = "hub" - OperandTektoncdHub = "tektoncd-hub" ChainResourceName = "chain" OperandTektoncdChains = "tektoncd-chains" OpenShiftPipelinesAsCodeName = "pipelines-as-code" diff --git a/pkg/apis/operator/v1alpha1/register.go b/pkg/apis/operator/v1alpha1/register.go index 1978804798..a04659ef00 100644 --- a/pkg/apis/operator/v1alpha1/register.go +++ b/pkg/apis/operator/v1alpha1/register.go @@ -50,9 +50,6 @@ const ( // KindTektonInstallerSet is the Kind of TektonInstallerSet in a GVK context. KindTektonInstallerSet = "TektonInstallerSet" - // KindTektonHub is the Kind of TektonHub in a GVK context. - KindTektonHub = "TektonHub" - // KindTektonChain is the Kind of Tekton Chain in a GVK context. KindTektonChain = "TektonChain" @@ -98,8 +95,6 @@ func addKnownTypes(s *runtime.Scheme) error { &TektonResultList{}, &TektonInstallerSet{}, &TektonInstallerSetList{}, - &TektonHub{}, - &TektonHubList{}, &TektonChain{}, &TektonChainList{}, &OpenShiftPipelinesAsCode{}, diff --git a/pkg/apis/operator/v1alpha1/tektonconfig_types.go b/pkg/apis/operator/v1alpha1/tektonconfig_types.go index c8cc186cf5..0b76606f19 100644 --- a/pkg/apis/operator/v1alpha1/tektonconfig_types.go +++ b/pkg/apis/operator/v1alpha1/tektonconfig_types.go @@ -104,9 +104,6 @@ type TektonConfigSpec struct { // Addon holds the addons config // +optional Addon Addon `json:"addon,omitempty"` - // Hub holds the hub config - // +optional - Hub Hub `json:"hub,omitempty"` // Pipeline holds the customizable option for pipeline component // +optional Pipeline Pipeline `json:"pipeline,omitempty"` diff --git a/pkg/apis/operator/v1alpha1/tektonconfig_validation.go b/pkg/apis/operator/v1alpha1/tektonconfig_validation.go index d725ef5bf7..ea4242a731 100644 --- a/pkg/apis/operator/v1alpha1/tektonconfig_validation.go +++ b/pkg/apis/operator/v1alpha1/tektonconfig_validation.go @@ -134,14 +134,9 @@ func (tc *TektonConfig) Validate(ctx context.Context) (errs *apis.FieldError) { errs = errs.Also(validateAddonParams(tc.Spec.Addon.Params, "spec.addon.params")) } - if !tc.Spec.Hub.IsEmpty() { - errs = errs.Also(validateHubParams(tc.Spec.Hub.Params, "spec.hub.params")) - } - errs = errs.Also(tc.Spec.Pipeline.PipelineProperties.validate("spec.pipeline")) errs = errs.Also(tc.Spec.Pipeline.Options.validate("spec.pipeline.options")) - errs = errs.Also(tc.Spec.Hub.Options.validate("spec.hub.options")) errs = errs.Also(tc.Spec.Dashboard.Options.validate("spec.dashboard.options")) errs = errs.Also(tc.Spec.Chain.Options.validate("spec.chain.options")) errs = errs.Also(tc.Spec.Trigger.Options.validate("spec.trigger.options")) diff --git a/pkg/apis/operator/v1alpha1/tektonhub_default_test.go b/pkg/apis/operator/v1alpha1/tektonhub_default_test.go deleted file mode 100644 index 021348fe3c..0000000000 --- a/pkg/apis/operator/v1alpha1/tektonhub_default_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2022 The Tekton 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 v1alpha1 - -import ( - "context" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestSetDefault(t *testing.T) { - - t.Setenv("DEFAULT_TARGET_NAMESPACE", "tekton-pipelines") - th := &TektonHub{ - ObjectMeta: metav1.ObjectMeta{ - Name: "hub", - }, - Spec: TektonHubSpec{ - Api: ApiSpec{ - ApiSecretName: "tetkon-hub-api", - }, - }, - } - th.SetDefaults(context.TODO()) - if th.Spec.TargetNamespace != "tekton-pipelines" { - t.Error("Setting default failed for TektonHub (spec.targetNamespace)") - } -} diff --git a/pkg/apis/operator/v1alpha1/tektonhub_defaults.go b/pkg/apis/operator/v1alpha1/tektonhub_defaults.go deleted file mode 100644 index 6dbe34a437..0000000000 --- a/pkg/apis/operator/v1alpha1/tektonhub_defaults.go +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright 2022 The Tekton 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 v1alpha1 - -import ( - "context" - "os" -) - -func (th *TektonHub) SetDefaults(ctx context.Context) { - - if th.Spec.Api.ApiSecretName == "" { - th.Spec.Api.ApiSecretName = HubApiSecretName - } - - if th.Spec.CommonSpec.TargetNamespace == "" { - th.Spec.CommonSpec.TargetNamespace = os.Getenv("DEFAULT_TARGET_NAMESPACE") - } - - if th.Spec.Api.CatalogRefreshInterval == "" { - th.Spec.Api.CatalogRefreshInterval = "30m" - } -} diff --git a/pkg/apis/operator/v1alpha1/tektonhub_lifecycle.go b/pkg/apis/operator/v1alpha1/tektonhub_lifecycle.go deleted file mode 100644 index 4dda6d1c39..0000000000 --- a/pkg/apis/operator/v1alpha1/tektonhub_lifecycle.go +++ /dev/null @@ -1,252 +0,0 @@ -/* -Copyright 2022 The Tekton 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 v1alpha1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" -) - -const ( - // DB - DbDependenciesInstalled apis.ConditionType = "DbDependenciesInstalled" - DbInstallerSetAvailable apis.ConditionType = "DbInstallSetAvailable" - // DB-migration - // TODO: fix the typo on the value: "DatabasebMigrationDone" - DatabaseMigrationDone apis.ConditionType = "DatabasebMigrationDone" - // API - ApiDependenciesInstalled apis.ConditionType = "ApiDependenciesInstalled" - ApiInstallerSetAvailable apis.ConditionType = "ApiInstallSetAvailable" - // UI - UiInstallerSetAvailable apis.ConditionType = "UiInstallSetAvailable" -) - -var ( - // TODO: Add this back after refactoring all components - // and updating TektonComponentStatus to have updated - // conditions - // _ TektonComponentStatus = (*TektonHubStatus)(nil) - - hubCondSet = apis.NewLivingConditionSet( - DbDependenciesInstalled, - DbInstallerSetAvailable, - DatabaseMigrationDone, - PreReconciler, - ApiDependenciesInstalled, - ApiInstallerSetAvailable, - UiInstallerSetAvailable, - PostReconciler, - ) -) - -// GroupVersionKind returns SchemeGroupVersion of a TektonHub -func (th *TektonHub) GroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind(KindTektonHub) -} - -// required by new type of FilterController -// might have to keep this and remove previous or vice-versa -func (th *TektonHub) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind(KindTektonHub) -} - -// GetCondition returns the current condition of a given condition type -func (ths *TektonHubStatus) GetCondition(t apis.ConditionType) *apis.Condition { - return hubCondSet.Manage(ths).GetCondition(t) -} - -// InitializeConditions initializes conditions of an TektonHubStatus -func (ths *TektonHubStatus) InitializeConditions() { - hubCondSet.Manage(ths).InitializeConditions() -} - -func (ths *TektonHubStatus) MarkNotReady(msg string) { - hubCondSet.Manage(ths).MarkFalse( - apis.ConditionReady, - "Error", - "Ready: %s", msg) -} - -// IsReady looks at the conditions returns true if they are all true. -func (ths *TektonHubStatus) IsReady() bool { - return hubCondSet.Manage(ths).IsHappy() -} - -// Lifecycle for the DB component of Tekton Hub -func (ths *TektonHubStatus) MarkDbDependencyInstalling(msg string) { - ths.MarkNotReady("Dependencies installing for DB") - hubCondSet.Manage(ths).MarkFalse( - DbDependenciesInstalled, - "Error", - "Dependencies are installing for DB: %s", msg) -} - -func (ths *TektonHubStatus) MarkDbDependencyMissing(msg string) { - ths.MarkNotReady("Missing Dependencies for DB") - hubCondSet.Manage(ths).MarkFalse( - DbDependenciesInstalled, - "Error", - "Dependencies are missing for DB: %s", msg) -} - -func (ths *TektonHubStatus) MarkDbDependenciesInstalled() { - hubCondSet.Manage(ths).MarkTrue(DbDependenciesInstalled) -} - -func (ths *TektonHubStatus) MarkDbInstallerSetNotAvailable(msg string) { - ths.MarkNotReady("TektonInstallerSet not ready for DB") - hubCondSet.Manage(ths).MarkFalse( - DbInstallerSetAvailable, - "Error", - "Installer set not ready: %s", msg) -} - -func (ths *TektonHubStatus) MarkDbInstallerSetAvailable() { - hubCondSet.Manage(ths).MarkTrue(DbInstallerSetAvailable) -} - -// Lifecycle for the DB migration component of Tekton Hub -func (ths *TektonHubStatus) MarkDatabaseMigrationFailed(msg string) { - ths.MarkNotReady("Database migration job not ready") - hubCondSet.Manage(ths).MarkFalse( - DatabaseMigrationDone, - "Error", - "Database migration job not ready: %s", msg) -} - -func (ths *TektonHubStatus) MarkDatabaseMigrationDone() { - hubCondSet.Manage(ths).MarkTrue(DatabaseMigrationDone) -} - -// Lifecycle for the API component of Tekton Hub -func (ths *TektonHubStatus) MarkApiDependencyInstalling(msg string) { - ths.MarkNotReady("Dependencies installing for API") - hubCondSet.Manage(ths).MarkFalse( - ApiDependenciesInstalled, - "Error", - "Dependencies are installing for API: %s", msg) -} - -func (ths *TektonHubStatus) MarkApiDependencyMissing(msg string) { - ths.MarkNotReady("Missing Dependencies for API") - hubCondSet.Manage(ths).MarkFalse( - ApiDependenciesInstalled, - "Error", - "Dependencies are missing for API: %s", msg) -} - -func (ths *TektonHubStatus) MarkApiDependenciesInstalled() { - hubCondSet.Manage(ths).MarkTrue(ApiDependenciesInstalled) -} - -func (ths *TektonHubStatus) MarkApiInstallerSetNotAvailable(msg string) { - ths.MarkNotReady("TektonInstallerSet not ready for API") - hubCondSet.Manage(ths).MarkFalse( - ApiInstallerSetAvailable, - "Error", - "Installer set not ready for API: %s", msg) -} - -func (ths *TektonHubStatus) MarkApiInstallerSetAvailable() { - hubCondSet.Manage(ths).MarkTrue(ApiInstallerSetAvailable) -} - -func (ths *TektonHubStatus) MarkUiInstallerSetNotAvailable(msg string) { - ths.MarkNotReady("TektonInstallerSet not ready for UI") - hubCondSet.Manage(ths).MarkFalse( - UiInstallerSetAvailable, - "Error", - "Installer set not ready for UI: %s", msg) -} - -func (ths *TektonHubStatus) MarkUiInstallerSetAvailable() { - hubCondSet.Manage(ths).MarkTrue(UiInstallerSetAvailable) -} - -// GetManifests gets the url links of the manifests. -func (ths *TektonHubStatus) GetUiRoute() string { - return ths.UiRouteUrl -} - -// SetManifests sets the url links of the manifests. -func (ths *TektonHubStatus) SetUiRoute(routeUrl string) { - ths.UiRouteUrl = routeUrl -} - -func (ths *TektonHubStatus) MarkPreReconcilerFailed(msg string) { - ths.MarkNotReady("PreReconciliation failed") - hubCondSet.Manage(ths).MarkFalse( - PreReconciler, - "Error", - "PreReconciliation failed with message: %s", msg) -} - -func (ths *TektonHubStatus) MarkPreReconcilerComplete() { - hubCondSet.Manage(ths).MarkTrue(PreReconciler) -} - -func (ths *TektonHubStatus) MarkPostReconcilerFailed(msg string) { - ths.MarkNotReady("PostReconciliation failed") - hubCondSet.Manage(ths).MarkFalse( - PostReconciler, - "Error", - "PostReconciliation failed with message: %s", msg) -} - -func (ths *TektonHubStatus) MarkPostReconcilerComplete() { - hubCondSet.Manage(ths).MarkTrue(PostReconciler) -} - -// Get the API route URL -func (ths *TektonHubStatus) GetApiRoute() string { - return ths.ApiRouteUrl -} - -// Set the API route URL -func (ths *TektonHubStatus) SetApiRoute(routeUrl string) { - ths.ApiRouteUrl = routeUrl -} - -// Get the Auth route URL -func (ths *TektonHubStatus) GetAuthRoute() string { - return ths.AuthRouteUrl -} - -// Set the Auth route URL -func (ths *TektonHubStatus) SetAuthRoute(routeUrl string) { - ths.AuthRouteUrl = routeUrl -} - -// GetVersion gets the currently installed version of the component. -func (ths *TektonHubStatus) GetVersion() string { - return ths.Version -} - -// SetVersion sets the currently installed version of the component. -func (ths *TektonHubStatus) SetVersion(version string) { - ths.Version = version -} - -// GetManifests gets the url links of the manifests. -func (ths *TektonHubStatus) GetManifests() []string { - return ths.Manifests -} - -// SetManifests sets the url links of the manifests. -func (ths *TektonHubStatus) SetManifests(manifests []string) { - ths.Manifests = manifests -} diff --git a/pkg/apis/operator/v1alpha1/tektonhub_lifecycle_test.go b/pkg/apis/operator/v1alpha1/tektonhub_lifecycle_test.go deleted file mode 100644 index fb26dd9e55..0000000000 --- a/pkg/apis/operator/v1alpha1/tektonhub_lifecycle_test.go +++ /dev/null @@ -1,168 +0,0 @@ -/* -Copyright 2022 The Tekton 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 v1alpha1 - -import ( - "testing" - - "k8s.io/apimachinery/pkg/runtime/schema" - apistest "knative.dev/pkg/apis/testing" -) - -func TestTektonHubGroupVersionKind(t *testing.T) { - r := &TektonHub{} - want := schema.GroupVersionKind{ - Group: GroupName, - Version: SchemaVersion, - Kind: KindTektonHub, - } - if got := r.GetGroupVersionKind(); got != want { - t.Errorf("got: %v, want: %v", got, want) - } -} - -func TestTektonHubHappyPath(t *testing.T) { - th := &TektonHubStatus{} - th.InitializeConditions() - - apistest.CheckConditionOngoing(th, DbDependenciesInstalled, t) - apistest.CheckConditionOngoing(th, DbInstallerSetAvailable, t) - apistest.CheckConditionOngoing(th, DatabaseMigrationDone, t) - apistest.CheckConditionOngoing(th, ApiDependenciesInstalled, t) - apistest.CheckConditionOngoing(th, PreReconciler, t) - apistest.CheckConditionOngoing(th, ApiInstallerSetAvailable, t) - apistest.CheckConditionOngoing(th, PostReconciler, t) - - // DB dependencies are created - th.MarkDbDependenciesInstalled() - apistest.CheckConditionSucceeded(th, DbDependenciesInstalled, t) - - // InstallerSet is not ready when deployment pods are not up - th.MarkDbInstallerSetNotAvailable("waiting for DB deployments") - apistest.CheckConditionFailed(th, DbInstallerSetAvailable, t) - - // Installer set created for DB - th.MarkDbInstallerSetAvailable() - apistest.CheckConditionSucceeded(th, DbInstallerSetAvailable, t) - - // Db-migration - // InstallerSet is not ready when Job pods are not up - th.MarkDatabaseMigrationFailed("waiting for Job to complete") - apistest.CheckConditionFailed(th, DatabaseMigrationDone, t) - - // Installer set created for DB migration - th.MarkDatabaseMigrationDone() - apistest.CheckConditionSucceeded(th, DatabaseMigrationDone, t) - - //API - - th.MarkApiDependenciesInstalled() - apistest.CheckConditionSucceeded(th, ApiDependenciesInstalled, t) - - // InstallerSet is not ready when deployment pods are not up - th.MarkUiInstallerSetNotAvailable("waiting for UI deployments") - apistest.CheckConditionFailed(th, UiInstallerSetAvailable, t) - - // Installer set created for UI - th.MarkUiInstallerSetAvailable() - apistest.CheckConditionSucceeded(th, UiInstallerSetAvailable, t) - - th.MarkPreReconcilerComplete() - apistest.CheckConditionSucceeded(th, PreReconciler, t) - - // InstallerSet is not ready when deployment pods are not up - th.MarkApiInstallerSetNotAvailable("waiting for API deployments") - apistest.CheckConditionFailed(th, ApiInstallerSetAvailable, t) - - // Installer set created for API - th.MarkApiInstallerSetAvailable() - apistest.CheckConditionSucceeded(th, ApiInstallerSetAvailable, t) - - th.MarkPostReconcilerComplete() - apistest.CheckConditionSucceeded(th, PostReconciler, t) - - if ready := th.IsReady(); !ready { - t.Errorf("tp.IsReady() = %v, want true", ready) - } -} - -func TestTektonHubErrorPath(t *testing.T) { - th := &TektonHubStatus{} - th.InitializeConditions() - - apistest.CheckConditionOngoing(th, DbDependenciesInstalled, t) - apistest.CheckConditionOngoing(th, DbInstallerSetAvailable, t) - apistest.CheckConditionOngoing(th, DatabaseMigrationDone, t) - apistest.CheckConditionOngoing(th, ApiDependenciesInstalled, t) - apistest.CheckConditionOngoing(th, PreReconciler, t) - apistest.CheckConditionOngoing(th, ApiInstallerSetAvailable, t) - apistest.CheckConditionOngoing(th, PostReconciler, t) - - // DB dependencies are created - th.MarkDbDependenciesInstalled() - apistest.CheckConditionSucceeded(th, DbDependenciesInstalled, t) - - // InstallerSet is not ready when deployment pods are not up - th.MarkDbInstallerSetNotAvailable("waiting for DB deployments") - apistest.CheckConditionFailed(th, DbInstallerSetAvailable, t) - - // Installer set created for DB - th.MarkDbInstallerSetAvailable() - apistest.CheckConditionSucceeded(th, DbInstallerSetAvailable, t) - - // InstallerSet is not ready when Job pods are not up - th.MarkDatabaseMigrationFailed("waiting for Job to complete") - apistest.CheckConditionFailed(th, DatabaseMigrationDone, t) - - // Installer set created for DB migration - th.MarkDatabaseMigrationDone() - apistest.CheckConditionSucceeded(th, DatabaseMigrationDone, t) - - th.MarkApiDependenciesInstalled() - apistest.CheckConditionSucceeded(th, ApiDependenciesInstalled, t) - - th.MarkPreReconcilerComplete() - apistest.CheckConditionSucceeded(th, PreReconciler, t) - - // InstallerSet is not ready when deployment pods are not up - th.MarkApiInstallerSetNotAvailable("waiting for API deployments") - apistest.CheckConditionFailed(th, ApiInstallerSetAvailable, t) - - // Installer set created for API - th.MarkApiInstallerSetAvailable() - apistest.CheckConditionSucceeded(th, ApiInstallerSetAvailable, t) - - // InstallerSet is not ready when deployment pods are not up - th.MarkUiInstallerSetNotAvailable("waiting for UI deployments") - apistest.CheckConditionFailed(th, UiInstallerSetAvailable, t) - - // Installer set created for UI - th.MarkUiInstallerSetAvailable() - apistest.CheckConditionSucceeded(th, UiInstallerSetAvailable, t) - - th.MarkPostReconcilerComplete() - apistest.CheckConditionSucceeded(th, PostReconciler, t) - - // In further reconciliation deployment might fail and installer - // set will change to not ready - - th.MarkApiInstallerSetNotAvailable("waiting for API deployments") - apistest.CheckConditionFailed(th, ApiInstallerSetAvailable, t) - if ready := th.IsReady(); ready { - t.Errorf("tp.IsReady() = %v, want false", ready) - } -} diff --git a/pkg/apis/operator/v1alpha1/tektonhub_types.go b/pkg/apis/operator/v1alpha1/tektonhub_types.go deleted file mode 100644 index f90e23d6ef..0000000000 --- a/pkg/apis/operator/v1alpha1/tektonhub_types.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2022 The Tekton 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - duckv1 "knative.dev/pkg/apis/duck/v1" -) - -const ( - HubDbSecretName = "tekton-hub-db" - HubApiSecretName = "tekton-hub-api" -) - -var ( - _ TektonComponent = (*TektonHub)(nil) - _ TektonComponentSpec = (*TektonHubSpec)(nil) -) - -// TektonHub is the Schema for the tektonhub API -// +genclient -// +genreconciler:krshapedlogic=false -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +genclient:nonNamespaced -// +kubebuilder:object:root=true -// +kubebuilder:resource:scope=Cluster -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Version",type=string,JSONPath=`.status.version` -// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` -// +kubebuilder:printcolumn:name="Reason",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].message` -// +kubebuilder:printcolumn:name="ApiUrl",type=string,JSONPath=`.status.apiUrl` -// +kubebuilder:printcolumn:name="UiUrl",type=string,JSONPath=`.status.uiUrl` -type TektonHub struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec TektonHubSpec `json:"spec,omitempty"` - Status TektonHubStatus `json:"status,omitempty"` -} - -type TektonHubSpec struct { - CommonSpec `json:",inline"` - Hub `json:",inline"` - Categories []string `json:"categories,omitempty"` - Catalogs []Catalog `json:"catalogs,omitempty"` - Scopes []Scope `json:"scopes,omitempty"` - Default Default `json:"default,omitempty"` - Db DbSpec `json:"db,omitempty"` - Api ApiSpec `json:"api,omitempty"` - CustomLogo CustomLogoSpec `json:"customLogo,omitempty"` -} - -// Hub defines the field to customize Hub component -type Hub struct { - // Params is the list of params passed for Hub customization - // +optional - Params []Param `json:"params,omitempty"` - // options holds additions fields and these fields will be updated on the manifests - // +optional - Options AdditionalOptions `json:"options"` -} - -type DbSpec struct { - DbSecretName string `json:"secret,omitempty"` -} - -type ApiSpec struct { - // Deprecated, will be removed in further release - HubConfigUrl string `json:"hubConfigUrl,omitempty"` - ApiSecretName string `json:"secret,omitempty"` - RouteHostUrl string `json:"routeHostUrl,omitempty"` - CatalogRefreshInterval string `json:"catalogRefreshInterval,omitempty"` -} - -type Category struct { - Name string `json:"name,omitempty"` -} - -type Catalog struct { - Name string `json:"name,omitempty"` - Org string `json:"org,omitempty"` - Type string `json:"type,omitempty"` - URL string `json:"url,omitempty"` - SshUrl string `json:"sshUrl,omitempty"` - ContextDir string `json:"contextDir,omitempty"` - Revision string `json:"revision,omitempty"` - Provider string `json:"provider,omitempty"` -} - -type Scope struct { - Name string `json:"name,omitempty"` - Users []string `json:"users,omitempty"` -} - -type Default struct { - Scopes []string `json:"scopes,omitempty"` -} - -// The Base64 Encode data and mediaType of the Custom Logo -type CustomLogoSpec struct { - Base64Data string `json:"base64Data,omitempty"` - MediaType string `json:"mediaType,omitempty"` -} - -// TektonHubStatus defines the observed state of TektonHub -type TektonHubStatus struct { - duckv1.Status `json:",inline"` - - // The version of the installed release - // +optional - Version string `json:"version,omitempty"` - - // The url links of the manifests, separated by comma - // +optional - Manifests []string `json:"manifests,omitempty"` - - // The URL route for API which needs to be exposed - // +optional - ApiRouteUrl string `json:"apiUrl,omitempty"` - - // The URL route for Auth server - // +optional - AuthRouteUrl string `json:"authUrl,omitempty"` - - // The URL route for UI which needs to be exposed - // +optional - UiRouteUrl string `json:"uiUrl,omitempty"` - - // The current installer set name - // +optional - HubInstallerSet map[string]string `json:"hubInstallerSets,omitempty"` -} - -func (in *TektonHubStatus) MarkInstallerSetReady() { - //TODO implement me - panic("implement me") -} - -func (in *TektonHubStatus) MarkInstallerSetNotReady(s string) { - //TODO implement me - panic("implement me") -} - -func (in *TektonHubStatus) MarkInstallerSetAvailable() { - //TODO implement me - panic("implement me") -} - -// TektonHubList contains a list of TektonHub -// +kubebuilder:object:root=true -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type TektonHubList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []TektonHub `json:"items"` -} - -// GetSpec implements TektonComponent -func (th *TektonHub) GetSpec() TektonComponentSpec { - return &th.Spec -} - -// GetStatus implements TektonComponent -func (th *TektonHub) GetStatus() TektonComponentStatus { - return &th.Status -} - -func (h Hub) IsEmpty() bool { - return len(h.Params) == 0 -} diff --git a/pkg/apis/operator/v1alpha1/tektonhub_validation.go b/pkg/apis/operator/v1alpha1/tektonhub_validation.go deleted file mode 100644 index f13965aa7c..0000000000 --- a/pkg/apis/operator/v1alpha1/tektonhub_validation.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright 2022 The Tekton 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 v1alpha1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -func validateHubParams(params []Param, pathToParams string) *apis.FieldError { - var errs *apis.FieldError - - for i, p := range params { - paramValue, ok := HubParams[p.Name] - if !ok { - errs = errs.Also(apis.ErrInvalidKeyName(p.Name, pathToParams)) - continue - } - if !isValueInArray(paramValue.Possible, p.Value) { - path := pathToParams + "." + p.Name - errs = errs.Also(apis.ErrInvalidArrayValue(p.Value, path, i)) - } - } - - return errs -} - -func (th *TektonHub) Validate(ctx context.Context) (errs *apis.FieldError) { - if apis.IsInDelete(ctx) { - return nil - } - - // disallow to update the targetNamespace - if apis.IsInUpdate(ctx) { - existingTC := apis.GetBaseline(ctx).(*TektonHub) - if existingTC.Spec.GetTargetNamespace() != th.Spec.GetTargetNamespace() { - errs = errs.Also(apis.ErrGeneric("doesn't allow to update targetNamespace, delete existing TektonHub object and create the updated TektonHub object", "spec.targetNamespace")) - } - } - - // execute common spec validations - errs = errs.Also(th.Spec.CommonSpec.validate("spec")) - - // validate database secret name - if th.Spec.Db.DbSecretName != "" && th.Spec.Db.DbSecretName != HubDbSecretName { - errs = errs.Also(apis.ErrInvalidValue(th.Spec.Db.DbSecretName, "spec.db.secret")) - } - - // validate api secret name - if th.Spec.Api.ApiSecretName != "" && th.Spec.Api.ApiSecretName != HubApiSecretName { - errs = errs.Also(apis.ErrInvalidValue(th.Spec.Api.ApiSecretName, "spec.api.secret")) - } - - return errs -} diff --git a/pkg/apis/operator/v1alpha1/tektonhub_validation_test.go b/pkg/apis/operator/v1alpha1/tektonhub_validation_test.go deleted file mode 100644 index 7658d92af7..0000000000 --- a/pkg/apis/operator/v1alpha1/tektonhub_validation_test.go +++ /dev/null @@ -1,173 +0,0 @@ -/* -Copyright 2022 The Tekton 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 v1alpha1 - -import ( - "context" - "testing" - - "gotest.tools/v3/assert" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" -) - -func Test_ValidateTektonConfig_InvalidHubParam(t *testing.T) { - - tc := &TektonConfig{ - ObjectMeta: metav1.ObjectMeta{ - Name: "config", - Namespace: "namespace", - }, - Spec: TektonConfigSpec{ - CommonSpec: CommonSpec{ - TargetNamespace: "namespace", - }, - Profile: "all", - Hub: Hub{ - Params: []Param{ - { - Name: "invalid-param", - Value: "val", - }, - }, - }, - Pruner: Prune{Disabled: true}, - }, - } - - err := tc.Validate(context.TODO()) - assert.Equal(t, "invalid key name \"invalid-param\": spec.hub.params", err.Error()) -} - -func Test_ValidateTektonConfig_InvalidHubParamValue(t *testing.T) { - - tc := &TektonConfig{ - ObjectMeta: metav1.ObjectMeta{ - Name: "config", - Namespace: "namespace", - }, - Spec: TektonConfigSpec{ - CommonSpec: CommonSpec{ - TargetNamespace: "namespace", - }, - Profile: "all", - Hub: Hub{ - Params: []Param{ - { - Name: "enable-devconsole-integration", - Value: "test", - }, - }, - }, - Pruner: Prune{Disabled: true}, - }, - } - - err := tc.Validate(context.TODO()) - assert.Equal(t, "invalid value: test: spec.hub.params.enable-devconsole-integration[0]", err.Error()) -} - -func Test_ValidateTektonHub_InvalidDbSecretName(t *testing.T) { - - th := &TektonHub{ - ObjectMeta: metav1.ObjectMeta{ - Name: "name", - Namespace: "namespace", - }, - Spec: TektonHubSpec{ - CommonSpec: CommonSpec{ - TargetNamespace: "tekton-pipelines", - }, - Db: DbSpec{ - DbSecretName: "invalid-value", - }, - Api: ApiSpec{ - ApiSecretName: "tekton-hub-api", - }, - }, - } - - err := th.Validate(context.TODO()) - assert.Equal(t, "invalid value: invalid-value: spec.db.secret", err.Error()) -} - -func Test_ValidateTektonHub_InvalidApiSecretName(t *testing.T) { - - th := &TektonHub{ - ObjectMeta: metav1.ObjectMeta{ - Name: "name", - Namespace: "namespace", - }, - Spec: TektonHubSpec{ - CommonSpec: CommonSpec{ - TargetNamespace: "tekton-pipelines", - }, - Db: DbSpec{ - DbSecretName: "tekton-hub-db", - }, - Api: ApiSpec{ - ApiSecretName: "invalid-value", - }, - }, - } - - err := th.Validate(context.TODO()) - assert.Equal(t, "invalid value: invalid-value: spec.api.secret", err.Error()) -} - -func Test_ValidateTektonHub_UpdateTargetNamespace(t *testing.T) { - ctx := context.Background() - - th := &TektonHub{ - ObjectMeta: metav1.ObjectMeta{ - Name: "name", - Namespace: "namespace", - }, - Spec: TektonHubSpec{ - CommonSpec: CommonSpec{ - TargetNamespace: "tekton-pipelines", - }, - Db: DbSpec{ - DbSecretName: "tekton-hub-db", - }, - Api: ApiSpec{ - ApiSecretName: "tekton-hub-api", - }, - }, - } - - updatedTH := &TektonHub{ - ObjectMeta: metav1.ObjectMeta{ - Name: "name", - Namespace: "namespace", - }, - Spec: TektonHubSpec{ - CommonSpec: CommonSpec{ - TargetNamespace: "test", - }, - Db: DbSpec{ - DbSecretName: "tekton-hub-db", - }, - Api: ApiSpec{ - ApiSecretName: "tekton-hub-api", - }, - }, - } - ctx = apis.WithinUpdate(ctx, th) - err := updatedTH.Validate(ctx) - assert.Equal(t, `doesn't allow to update targetNamespace, delete existing TektonHub object and create the updated TektonHub object: spec.targetNamespace`, err.Error()) -} diff --git a/pkg/apis/operator/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/operator/v1alpha1/zz_generated.deepcopy.go index 57bf17c3bc..d0d151cb8e 100644 --- a/pkg/apis/operator/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/operator/v1alpha1/zz_generated.deepcopy.go @@ -140,54 +140,6 @@ func (in *Addon) DeepCopy() *Addon { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiSpec) DeepCopyInto(out *ApiSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiSpec. -func (in *ApiSpec) DeepCopy() *ApiSpec { - if in == nil { - return nil - } - out := new(ApiSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Catalog) DeepCopyInto(out *Catalog) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Catalog. -func (in *Catalog) DeepCopy() *Catalog { - if in == nil { - return nil - } - out := new(Catalog) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Category) DeepCopyInto(out *Category) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Category. -func (in *Category) DeepCopy() *Category { - if in == nil { - return nil - } - out := new(Category) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Chain) DeepCopyInto(out *Chain) { *out = *in @@ -301,22 +253,6 @@ func (in *Config) DeepCopy() *Config { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CustomLogoSpec) DeepCopyInto(out *CustomLogoSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomLogoSpec. -func (in *CustomLogoSpec) DeepCopy() *CustomLogoSpec { - if in == nil { - return nil - } - out := new(CustomLogoSpec) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Dashboard) DeepCopyInto(out *Dashboard) { *out = *in @@ -351,43 +287,6 @@ func (in *DashboardProperties) DeepCopy() *DashboardProperties { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DbSpec) DeepCopyInto(out *DbSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DbSpec. -func (in *DbSpec) DeepCopy() *DbSpec { - if in == nil { - return nil - } - out := new(DbSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Default) DeepCopyInto(out *Default) { - *out = *in - if in.Scopes != nil { - in, out := &in.Scopes, &out.Scopes - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Default. -func (in *Default) DeepCopy() *Default { - if in == nil { - return nil - } - out := new(Default) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DeploymentPerformanceArgs) DeepCopyInto(out *DeploymentPerformanceArgs) { *out = *in @@ -419,28 +318,6 @@ func (in *DeploymentPerformanceArgs) DeepCopy() *DeploymentPerformanceArgs { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Hub) DeepCopyInto(out *Hub) { - *out = *in - if in.Params != nil { - in, out := &in.Params, &out.Params - *out = make([]Param, len(*in)) - copy(*out, *in) - } - in.Options.DeepCopyInto(&out.Options) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Hub. -func (in *Hub) DeepCopy() *Hub { - if in == nil { - return nil - } - out := new(Hub) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Kubernetes) DeepCopyInto(out *Kubernetes) { *out = *in @@ -1431,27 +1308,6 @@ func (in *SchedulerConfig) DeepCopy() *SchedulerConfig { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Scope) DeepCopyInto(out *Scope) { - *out = *in - if in.Users != nil { - in, out := &in.Users, &out.Users - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Scope. -func (in *Scope) DeepCopy() *Scope { - if in == nil { - return nil - } - out := new(Scope) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SyncerService) DeepCopyInto(out *SyncerService) { *out = *in @@ -1837,7 +1693,6 @@ func (in *TektonConfigSpec) DeepCopyInto(out *TektonConfigSpec) { in.Scheduler.DeepCopyInto(&out.Scheduler) out.CommonSpec = in.CommonSpec in.Addon.DeepCopyInto(&out.Addon) - in.Hub.DeepCopyInto(&out.Hub) in.Pipeline.DeepCopyInto(&out.Pipeline) in.Trigger.DeepCopyInto(&out.Trigger) in.Chain.DeepCopyInto(&out.Chain) @@ -1989,135 +1844,6 @@ func (in *TektonDashboardStatus) DeepCopy() *TektonDashboardStatus { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TektonHub) DeepCopyInto(out *TektonHub) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TektonHub. -func (in *TektonHub) DeepCopy() *TektonHub { - if in == nil { - return nil - } - out := new(TektonHub) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *TektonHub) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TektonHubList) DeepCopyInto(out *TektonHubList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]TektonHub, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TektonHubList. -func (in *TektonHubList) DeepCopy() *TektonHubList { - if in == nil { - return nil - } - out := new(TektonHubList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *TektonHubList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TektonHubSpec) DeepCopyInto(out *TektonHubSpec) { - *out = *in - out.CommonSpec = in.CommonSpec - in.Hub.DeepCopyInto(&out.Hub) - if in.Categories != nil { - in, out := &in.Categories, &out.Categories - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Catalogs != nil { - in, out := &in.Catalogs, &out.Catalogs - *out = make([]Catalog, len(*in)) - copy(*out, *in) - } - if in.Scopes != nil { - in, out := &in.Scopes, &out.Scopes - *out = make([]Scope, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - in.Default.DeepCopyInto(&out.Default) - out.Db = in.Db - out.Api = in.Api - out.CustomLogo = in.CustomLogo - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TektonHubSpec. -func (in *TektonHubSpec) DeepCopy() *TektonHubSpec { - if in == nil { - return nil - } - out := new(TektonHubSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TektonHubStatus) DeepCopyInto(out *TektonHubStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - if in.Manifests != nil { - in, out := &in.Manifests, &out.Manifests - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.HubInstallerSet != nil { - in, out := &in.HubInstallerSet, &out.HubInstallerSet - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TektonHubStatus. -func (in *TektonHubStatus) DeepCopy() *TektonHubStatus { - if in == nil { - return nil - } - out := new(TektonHubStatus) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TektonInstallerSet) DeepCopyInto(out *TektonInstallerSet) { *out = *in diff --git a/pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_operator_client.go b/pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_operator_client.go index dfed2dbd13..9abb83086d 100644 --- a/pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_operator_client.go +++ b/pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_operator_client.go @@ -56,10 +56,6 @@ func (c *FakeOperatorV1alpha1) TektonDashboards() v1alpha1.TektonDashboardInterf return newFakeTektonDashboards(c) } -func (c *FakeOperatorV1alpha1) TektonHubs() v1alpha1.TektonHubInterface { - return newFakeTektonHubs(c) -} - func (c *FakeOperatorV1alpha1) TektonInstallerSets() v1alpha1.TektonInstallerSetInterface { return newFakeTektonInstallerSets(c) } diff --git a/pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_tektonhub.go b/pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_tektonhub.go deleted file mode 100644 index 9dab1d2d37..0000000000 --- a/pkg/client/clientset/versioned/typed/operator/v1alpha1/fake/fake_tektonhub.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - operatorv1alpha1 "github.com/tektoncd/operator/pkg/client/clientset/versioned/typed/operator/v1alpha1" - gentype "k8s.io/client-go/gentype" -) - -// fakeTektonHubs implements TektonHubInterface -type fakeTektonHubs struct { - *gentype.FakeClientWithList[*v1alpha1.TektonHub, *v1alpha1.TektonHubList] - Fake *FakeOperatorV1alpha1 -} - -func newFakeTektonHubs(fake *FakeOperatorV1alpha1) operatorv1alpha1.TektonHubInterface { - return &fakeTektonHubs{ - gentype.NewFakeClientWithList[*v1alpha1.TektonHub, *v1alpha1.TektonHubList]( - fake.Fake, - "", - v1alpha1.SchemeGroupVersion.WithResource("tektonhubs"), - v1alpha1.SchemeGroupVersion.WithKind("TektonHub"), - func() *v1alpha1.TektonHub { return &v1alpha1.TektonHub{} }, - func() *v1alpha1.TektonHubList { return &v1alpha1.TektonHubList{} }, - func(dst, src *v1alpha1.TektonHubList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha1.TektonHubList) []*v1alpha1.TektonHub { return gentype.ToPointerSlice(list.Items) }, - func(list *v1alpha1.TektonHubList, items []*v1alpha1.TektonHub) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/pkg/client/clientset/versioned/typed/operator/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/operator/v1alpha1/generated_expansion.go index 7c14320fa5..6f2d6cbe1f 100644 --- a/pkg/client/clientset/versioned/typed/operator/v1alpha1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/operator/v1alpha1/generated_expansion.go @@ -32,8 +32,6 @@ type TektonConfigExpansion interface{} type TektonDashboardExpansion interface{} -type TektonHubExpansion interface{} - type TektonInstallerSetExpansion interface{} type TektonMulticlusterProxyAAEExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/operator/v1alpha1/operator_client.go b/pkg/client/clientset/versioned/typed/operator/v1alpha1/operator_client.go index 621b974883..8cb0b4bfbe 100644 --- a/pkg/client/clientset/versioned/typed/operator/v1alpha1/operator_client.go +++ b/pkg/client/clientset/versioned/typed/operator/v1alpha1/operator_client.go @@ -35,7 +35,6 @@ type OperatorV1alpha1Interface interface { TektonChainsGetter TektonConfigsGetter TektonDashboardsGetter - TektonHubsGetter TektonInstallerSetsGetter TektonMulticlusterProxyAAEsGetter TektonPipelinesGetter @@ -78,10 +77,6 @@ func (c *OperatorV1alpha1Client) TektonDashboards() TektonDashboardInterface { return newTektonDashboards(c) } -func (c *OperatorV1alpha1Client) TektonHubs() TektonHubInterface { - return newTektonHubs(c) -} - func (c *OperatorV1alpha1Client) TektonInstallerSets() TektonInstallerSetInterface { return newTektonInstallerSets(c) } diff --git a/pkg/client/clientset/versioned/typed/operator/v1alpha1/tektonhub.go b/pkg/client/clientset/versioned/typed/operator/v1alpha1/tektonhub.go deleted file mode 100644 index 22bd565252..0000000000 --- a/pkg/client/clientset/versioned/typed/operator/v1alpha1/tektonhub.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - - operatorv1alpha1 "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - scheme "github.com/tektoncd/operator/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// TektonHubsGetter has a method to return a TektonHubInterface. -// A group's client should implement this interface. -type TektonHubsGetter interface { - TektonHubs() TektonHubInterface -} - -// TektonHubInterface has methods to work with TektonHub resources. -type TektonHubInterface interface { - Create(ctx context.Context, tektonHub *operatorv1alpha1.TektonHub, opts v1.CreateOptions) (*operatorv1alpha1.TektonHub, error) - Update(ctx context.Context, tektonHub *operatorv1alpha1.TektonHub, opts v1.UpdateOptions) (*operatorv1alpha1.TektonHub, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, tektonHub *operatorv1alpha1.TektonHub, opts v1.UpdateOptions) (*operatorv1alpha1.TektonHub, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*operatorv1alpha1.TektonHub, error) - List(ctx context.Context, opts v1.ListOptions) (*operatorv1alpha1.TektonHubList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *operatorv1alpha1.TektonHub, err error) - TektonHubExpansion -} - -// tektonHubs implements TektonHubInterface -type tektonHubs struct { - *gentype.ClientWithList[*operatorv1alpha1.TektonHub, *operatorv1alpha1.TektonHubList] -} - -// newTektonHubs returns a TektonHubs -func newTektonHubs(c *OperatorV1alpha1Client) *tektonHubs { - return &tektonHubs{ - gentype.NewClientWithList[*operatorv1alpha1.TektonHub, *operatorv1alpha1.TektonHubList]( - "tektonhubs", - c.RESTClient(), - scheme.ParameterCodec, - "", - func() *operatorv1alpha1.TektonHub { return &operatorv1alpha1.TektonHub{} }, - func() *operatorv1alpha1.TektonHubList { return &operatorv1alpha1.TektonHubList{} }, - ), - } -} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index c7f6179678..3ebcf96979 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -67,8 +67,6 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Operator().V1alpha1().TektonConfigs().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("tektondashboards"): return &genericInformer{resource: resource.GroupResource(), informer: f.Operator().V1alpha1().TektonDashboards().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("tektonhubs"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Operator().V1alpha1().TektonHubs().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("tektoninstallersets"): return &genericInformer{resource: resource.GroupResource(), informer: f.Operator().V1alpha1().TektonInstallerSets().Informer()}, nil case v1alpha1.SchemeGroupVersion.WithResource("tektonmulticlusterproxyaaes"): diff --git a/pkg/client/informers/externalversions/operator/v1alpha1/interface.go b/pkg/client/informers/externalversions/operator/v1alpha1/interface.go index 7c58d2382a..a14d9973a1 100644 --- a/pkg/client/informers/externalversions/operator/v1alpha1/interface.go +++ b/pkg/client/informers/externalversions/operator/v1alpha1/interface.go @@ -38,8 +38,6 @@ type Interface interface { TektonConfigs() TektonConfigInformer // TektonDashboards returns a TektonDashboardInformer. TektonDashboards() TektonDashboardInformer - // TektonHubs returns a TektonHubInformer. - TektonHubs() TektonHubInformer // TektonInstallerSets returns a TektonInstallerSetInformer. TektonInstallerSets() TektonInstallerSetInformer // TektonMulticlusterProxyAAEs returns a TektonMulticlusterProxyAAEInformer. @@ -102,11 +100,6 @@ func (v *version) TektonDashboards() TektonDashboardInformer { return &tektonDashboardInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } -// TektonHubs returns a TektonHubInformer. -func (v *version) TektonHubs() TektonHubInformer { - return &tektonHubInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - // TektonInstallerSets returns a TektonInstallerSetInformer. func (v *version) TektonInstallerSets() TektonInstallerSetInformer { return &tektonInstallerSetInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} diff --git a/pkg/client/informers/externalversions/operator/v1alpha1/tektonhub.go b/pkg/client/informers/externalversions/operator/v1alpha1/tektonhub.go deleted file mode 100644 index ee0b5003b7..0000000000 --- a/pkg/client/informers/externalversions/operator/v1alpha1/tektonhub.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - time "time" - - apisoperatorv1alpha1 "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - versioned "github.com/tektoncd/operator/pkg/client/clientset/versioned" - internalinterfaces "github.com/tektoncd/operator/pkg/client/informers/externalversions/internalinterfaces" - operatorv1alpha1 "github.com/tektoncd/operator/pkg/client/listers/operator/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// TektonHubInformer provides access to a shared informer and lister for -// TektonHubs. -type TektonHubInformer interface { - Informer() cache.SharedIndexInformer - Lister() operatorv1alpha1.TektonHubLister -} - -type tektonHubInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewTektonHubInformer constructs a new informer for TektonHub type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewTektonHubInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredTektonHubInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredTektonHubInformer constructs a new informer for TektonHub type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredTektonHubInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.OperatorV1alpha1().TektonHubs().List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.OperatorV1alpha1().TektonHubs().Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.OperatorV1alpha1().TektonHubs().List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.OperatorV1alpha1().TektonHubs().Watch(ctx, options) - }, - }, client), - &apisoperatorv1alpha1.TektonHub{}, - resyncPeriod, - indexers, - ) -} - -func (f *tektonHubInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredTektonHubInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *tektonHubInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apisoperatorv1alpha1.TektonHub{}, f.defaultInformer) -} - -func (f *tektonHubInformer) Lister() operatorv1alpha1.TektonHubLister { - return operatorv1alpha1.NewTektonHubLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/fake/fake.go b/pkg/client/injection/informers/operator/v1alpha1/tektonhub/fake/fake.go deleted file mode 100644 index 16f5d8ba44..0000000000 --- a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/fake/fake.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - fake "github.com/tektoncd/operator/pkg/client/injection/informers/factory/fake" - tektonhub "github.com/tektoncd/operator/pkg/client/injection/informers/operator/v1alpha1/tektonhub" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" -) - -var Get = tektonhub.Get - -func init() { - injection.Fake.RegisterInformer(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := fake.Get(ctx) - inf := f.Operator().V1alpha1().TektonHubs() - return context.WithValue(ctx, tektonhub.Key{}, inf), inf.Informer() -} diff --git a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/fake/fake.go b/pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/fake/fake.go deleted file mode 100644 index cecff0ca7d..0000000000 --- a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/fake/fake.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package fake - -import ( - context "context" - - factoryfiltered "github.com/tektoncd/operator/pkg/client/injection/informers/factory/filtered" - filtered "github.com/tektoncd/operator/pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -var Get = filtered.Get - -func init() { - injection.Fake.RegisterFilteredInformers(withInformer) -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(factoryfiltered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := factoryfiltered.Get(ctx, selector) - inf := f.Operator().V1alpha1().TektonHubs() - ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} diff --git a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/tektonhub.go b/pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/tektonhub.go deleted file mode 100644 index c9667e9327..0000000000 --- a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/filtered/tektonhub.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package filtered - -import ( - context "context" - - v1alpha1 "github.com/tektoncd/operator/pkg/client/informers/externalversions/operator/v1alpha1" - filtered "github.com/tektoncd/operator/pkg/client/injection/informers/factory/filtered" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterFilteredInformers(withInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct { - Selector string -} - -func withInformer(ctx context.Context) (context.Context, []controller.Informer) { - untyped := ctx.Value(filtered.LabelKey{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch labelkey from context.") - } - labelSelectors := untyped.([]string) - infs := []controller.Informer{} - for _, selector := range labelSelectors { - f := filtered.Get(ctx, selector) - inf := f.Operator().V1alpha1().TektonHubs() - ctx = context.WithValue(ctx, Key{Selector: selector}, inf) - infs = append(infs, inf.Informer()) - } - return ctx, infs -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context, selector string) v1alpha1.TektonHubInformer { - untyped := ctx.Value(Key{Selector: selector}) - if untyped == nil { - logging.FromContext(ctx).Panicf( - "Unable to fetch github.com/tektoncd/operator/pkg/client/informers/externalversions/operator/v1alpha1.TektonHubInformer with selector %s from context.", selector) - } - return untyped.(v1alpha1.TektonHubInformer) -} diff --git a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/tektonhub.go b/pkg/client/injection/informers/operator/v1alpha1/tektonhub/tektonhub.go deleted file mode 100644 index b99c855746..0000000000 --- a/pkg/client/injection/informers/operator/v1alpha1/tektonhub/tektonhub.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package tektonhub - -import ( - context "context" - - v1alpha1 "github.com/tektoncd/operator/pkg/client/informers/externalversions/operator/v1alpha1" - factory "github.com/tektoncd/operator/pkg/client/injection/informers/factory" - controller "knative.dev/pkg/controller" - injection "knative.dev/pkg/injection" - logging "knative.dev/pkg/logging" -) - -func init() { - injection.Default.RegisterInformer(withInformer) -} - -// Key is used for associating the Informer inside the context.Context. -type Key struct{} - -func withInformer(ctx context.Context) (context.Context, controller.Informer) { - f := factory.Get(ctx) - inf := f.Operator().V1alpha1().TektonHubs() - return context.WithValue(ctx, Key{}, inf), inf.Informer() -} - -// Get extracts the typed informer from the context. -func Get(ctx context.Context) v1alpha1.TektonHubInformer { - untyped := ctx.Value(Key{}) - if untyped == nil { - logging.FromContext(ctx).Panic( - "Unable to fetch github.com/tektoncd/operator/pkg/client/informers/externalversions/operator/v1alpha1.TektonHubInformer from context.") - } - return untyped.(v1alpha1.TektonHubInformer) -} diff --git a/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/controller.go b/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/controller.go deleted file mode 100644 index 7b6a731e0a..0000000000 --- a/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/controller.go +++ /dev/null @@ -1,178 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package tektonhub - -import ( - context "context" - fmt "fmt" - reflect "reflect" - strings "strings" - - versionedscheme "github.com/tektoncd/operator/pkg/client/clientset/versioned/scheme" - client "github.com/tektoncd/operator/pkg/client/injection/client" - tektonhub "github.com/tektoncd/operator/pkg/client/injection/informers/operator/v1alpha1/tektonhub" - zap "go.uber.org/zap" - corev1 "k8s.io/api/core/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - scheme "k8s.io/client-go/kubernetes/scheme" - v1 "k8s.io/client-go/kubernetes/typed/core/v1" - record "k8s.io/client-go/tools/record" - kubeclient "knative.dev/pkg/client/injection/kube/client" - controller "knative.dev/pkg/controller" - logging "knative.dev/pkg/logging" - logkey "knative.dev/pkg/logging/logkey" - reconciler "knative.dev/pkg/reconciler" -) - -const ( - defaultControllerAgentName = "tektonhub-controller" - defaultFinalizerName = "tektonhubs.operator.tekton.dev" -) - -// NewImpl returns a controller.Impl that handles queuing and feeding work from -// the queue through an implementation of controller.Reconciler, delegating to -// the provided Interface and optional Finalizer methods. OptionsFn is used to return -// controller.ControllerOptions to be used by the internal reconciler. -func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl { - logger := logging.FromContext(ctx) - - // Check the options function input. It should be 0 or 1. - if len(optionsFns) > 1 { - logger.Fatal("Up to one options function is supported, found: ", len(optionsFns)) - } - - tektonhubInformer := tektonhub.Get(ctx) - - lister := tektonhubInformer.Lister() - - var promoteFilterFunc func(obj interface{}) bool - var promoteFunc = func(bkt reconciler.Bucket) {} - - rec := &reconcilerImpl{ - LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ - PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { - - // Signal promotion event - promoteFunc(bkt) - - all, err := lister.List(labels.Everything()) - if err != nil { - return err - } - for _, elt := range all { - if promoteFilterFunc != nil { - if ok := promoteFilterFunc(elt); !ok { - continue - } - } - enq(bkt, types.NamespacedName{ - Namespace: elt.GetNamespace(), - Name: elt.GetName(), - }) - } - return nil - }, - }, - Client: client.Get(ctx), - Lister: lister, - reconciler: r, - finalizerName: defaultFinalizerName, - } - - ctrType := reflect.TypeOf(r).Elem() - ctrTypeName := fmt.Sprintf("%s.%s", ctrType.PkgPath(), ctrType.Name()) - ctrTypeName = strings.ReplaceAll(ctrTypeName, "/", ".") - - logger = logger.With( - zap.String(logkey.ControllerType, ctrTypeName), - zap.String(logkey.Kind, "operator.tekton.dev.TektonHub"), - ) - - impl := controller.NewContext(ctx, rec, controller.ControllerOptions{WorkQueueName: ctrTypeName, Logger: logger}) - agentName := defaultControllerAgentName - - // Pass impl to the options. Save any optional results. - for _, fn := range optionsFns { - opts := fn(impl) - if opts.ConfigStore != nil { - rec.configStore = opts.ConfigStore - } - if opts.FinalizerName != "" { - rec.finalizerName = opts.FinalizerName - } - if opts.AgentName != "" { - agentName = opts.AgentName - } - if opts.SkipStatusUpdates { - rec.skipStatusUpdates = true - } - if opts.DemoteFunc != nil { - rec.DemoteFunc = opts.DemoteFunc - } - if opts.PromoteFilterFunc != nil { - promoteFilterFunc = opts.PromoteFilterFunc - } - if opts.PromoteFunc != nil { - promoteFunc = opts.PromoteFunc - } - if opts.UseServerSideApplyForFinalizers { - if opts.FinalizerFieldManager == "" { - logger.Fatal("FinalizerFieldManager must be provided when UseServerSideApplyForFinalizers is enabled") - } - rec.useServerSideApplyForFinalizers = true - rec.finalizerFieldManager = opts.FinalizerFieldManager - rec.forceApplyFinalizers = opts.ForceApplyFinalizers - } - } - - rec.Recorder = createRecorder(ctx, agentName) - - return impl -} - -func createRecorder(ctx context.Context, agentName string) record.EventRecorder { - logger := logging.FromContext(ctx) - - recorder := controller.GetEventRecorder(ctx) - if recorder == nil { - // Create event broadcaster - logger.Debug("Creating event broadcaster") - eventBroadcaster := record.NewBroadcaster() - watches := []watch.Interface{ - eventBroadcaster.StartLogging(logger.Named("event-broadcaster").Infof), - eventBroadcaster.StartRecordingToSink( - &v1.EventSinkImpl{Interface: kubeclient.Get(ctx).CoreV1().Events("")}), - } - recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName}) - go func() { - <-ctx.Done() - for _, w := range watches { - w.Stop() - } - }() - } - - return recorder -} - -func init() { - versionedscheme.AddToScheme(scheme.Scheme) -} diff --git a/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/reconciler.go b/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/reconciler.go deleted file mode 100644 index dae7e895e9..0000000000 --- a/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/reconciler.go +++ /dev/null @@ -1,551 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package tektonhub - -import ( - context "context" - json "encoding/json" - fmt "fmt" - - v1alpha1 "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - versioned "github.com/tektoncd/operator/pkg/client/clientset/versioned" - operatorv1alpha1 "github.com/tektoncd/operator/pkg/client/listers/operator/v1alpha1" - zap "go.uber.org/zap" - zapcore "go.uber.org/zap/zapcore" - v1 "k8s.io/api/core/v1" - equality "k8s.io/apimachinery/pkg/api/equality" - errors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - types "k8s.io/apimachinery/pkg/types" - sets "k8s.io/apimachinery/pkg/util/sets" - scheme "k8s.io/client-go/kubernetes/scheme" - record "k8s.io/client-go/tools/record" - controller "knative.dev/pkg/controller" - kmp "knative.dev/pkg/kmp" - logging "knative.dev/pkg/logging" - reconciler "knative.dev/pkg/reconciler" -) - -// Interface defines the strongly typed interfaces to be implemented by a -// controller reconciling v1alpha1.TektonHub. -type Interface interface { - // ReconcileKind implements custom logic to reconcile v1alpha1.TektonHub. Any changes - // to the objects .Status or .Finalizers will be propagated to the stored - // object. It is recommended that implementors do not call any update calls - // for the Kind inside of ReconcileKind, it is the responsibility of the calling - // controller to propagate those properties. The resource passed to ReconcileKind - // will always have an empty deletion timestamp. - ReconcileKind(ctx context.Context, o *v1alpha1.TektonHub) reconciler.Event -} - -// Finalizer defines the strongly typed interfaces to be implemented by a -// controller finalizing v1alpha1.TektonHub. -type Finalizer interface { - // FinalizeKind implements custom logic to finalize v1alpha1.TektonHub. Any changes - // to the objects .Status or .Finalizers will be ignored. Returning a nil or - // Normal type reconciler.Event will allow the finalizer to be deleted on - // the resource. The resource passed to FinalizeKind will always have a set - // deletion timestamp. - FinalizeKind(ctx context.Context, o *v1alpha1.TektonHub) reconciler.Event -} - -// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a -// controller reconciling v1alpha1.TektonHub if they want to process resources for which -// they are not the leader. -type ReadOnlyInterface interface { - // ObserveKind implements logic to observe v1alpha1.TektonHub. - // This method should not write to the API. - ObserveKind(ctx context.Context, o *v1alpha1.TektonHub) reconciler.Event -} - -type doReconcile func(ctx context.Context, o *v1alpha1.TektonHub) reconciler.Event - -// reconcilerImpl implements controller.Reconciler for v1alpha1.TektonHub resources. -type reconcilerImpl struct { - // LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware. - reconciler.LeaderAwareFuncs - - // Client is used to write back status updates. - Client versioned.Interface - - // Listers index properties about resources. - Lister operatorv1alpha1.TektonHubLister - - // Recorder is an event recorder for recording Event resources to the - // Kubernetes API. - Recorder record.EventRecorder - - // configStore allows for decorating a context with config maps. - // +optional - configStore reconciler.ConfigStore - - // reconciler is the implementation of the business logic of the resource. - reconciler Interface - - // finalizerName is the name of the finalizer to reconcile. - finalizerName string - - // useServerSideApplyForFinalizers configures whether to use server-side apply for finalizer management - useServerSideApplyForFinalizers bool - - // finalizerFieldManager is the field manager name for server-side apply of finalizers - finalizerFieldManager string - - // forceApplyFinalizers configures whether to force server-side apply for finalizers - forceApplyFinalizers bool - - // skipStatusUpdates configures whether or not this reconciler automatically updates - // the status of the reconciled resource. - skipStatusUpdates bool -} - -// Check that our Reconciler implements controller.Reconciler. -var _ controller.Reconciler = (*reconcilerImpl)(nil) - -// Check that our generated Reconciler is always LeaderAware. -var _ reconciler.LeaderAware = (*reconcilerImpl)(nil) - -func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client versioned.Interface, lister operatorv1alpha1.TektonHubLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { - // Check the options function input. It should be 0 or 1. - if len(options) > 1 { - logger.Fatal("Up to one options struct is supported, found: ", len(options)) - } - - // Fail fast when users inadvertently implement the other LeaderAware interface. - // For the typed reconcilers, Promote shouldn't take any arguments. - if _, ok := r.(reconciler.LeaderAware); ok { - logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) - } - - rec := &reconcilerImpl{ - LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ - PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { - all, err := lister.List(labels.Everything()) - if err != nil { - return err - } - for _, elt := range all { - // TODO: Consider letting users specify a filter in options. - enq(bkt, types.NamespacedName{ - Namespace: elt.GetNamespace(), - Name: elt.GetName(), - }) - } - return nil - }, - }, - Client: client, - Lister: lister, - Recorder: recorder, - reconciler: r, - finalizerName: defaultFinalizerName, - } - - for _, opts := range options { - if opts.ConfigStore != nil { - rec.configStore = opts.ConfigStore - } - if opts.FinalizerName != "" { - rec.finalizerName = opts.FinalizerName - } - if opts.SkipStatusUpdates { - rec.skipStatusUpdates = true - } - if opts.DemoteFunc != nil { - rec.DemoteFunc = opts.DemoteFunc - } - if opts.UseServerSideApplyForFinalizers { - if opts.FinalizerFieldManager == "" { - logger.Fatal("FinalizerFieldManager must be provided when UseServerSideApplyForFinalizers is enabled") - } - rec.useServerSideApplyForFinalizers = true - rec.finalizerFieldManager = opts.FinalizerFieldManager - rec.forceApplyFinalizers = opts.ForceApplyFinalizers - } - } - - return rec -} - -// Reconcile implements controller.Reconciler -func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { - logger := logging.FromContext(ctx) - - // Initialize the reconciler state. This will convert the namespace/name - // string into a distinct namespace and name, determine if this instance of - // the reconciler is the leader, and any additional interfaces implemented - // by the reconciler. Returns an error is the resource key is invalid. - s, err := newState(key, r) - if err != nil { - logger.Error("Invalid resource key: ", key) - return nil - } - - // If we are not the leader, and we don't implement either ReadOnly - // observer interfaces, then take a fast-path out. - if s.isNotLeaderNorObserver() { - return controller.NewSkipKey(key) - } - - // If configStore is set, attach the frozen configuration to the context. - if r.configStore != nil { - ctx = r.configStore.ToContext(ctx) - } - - // Add the recorder to context. - ctx = controller.WithEventRecorder(ctx, r.Recorder) - - // Get the resource with this namespace/name. - - getter := r.Lister - - original, err := getter.Get(s.name) - - if errors.IsNotFound(err) { - // The resource may no longer exist, in which case we stop processing and call - // the ObserveDeletion handler if appropriate. - logger.Debugf("Resource %q no longer exists", key) - if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { - return del.ObserveDeletion(ctx, types.NamespacedName{ - Namespace: s.namespace, - Name: s.name, - }) - } - return nil - } else if err != nil { - return err - } - - // Don't modify the informers copy. - resource := original.DeepCopy() - - var reconcileEvent reconciler.Event - - name, do := s.reconcileMethodFor(resource) - // Append the target method to the logger. - logger = logger.With(zap.String("targetMethod", name)) - switch name { - case reconciler.DoReconcileKind: - // Set and update the finalizer on resource if r.reconciler - // implements Finalizer. - if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { - return fmt.Errorf("failed to set finalizers: %w", err) - } - - // Reconcile this copy of the resource and then write back any status - // updates regardless of whether the reconciliation errored out. - reconcileEvent = do(ctx, resource) - - case reconciler.DoFinalizeKind: - // For finalizing reconcilers, if this resource being marked for deletion - // and reconciled cleanly (nil or normal event), remove the finalizer. - reconcileEvent = do(ctx, resource) - - if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { - return fmt.Errorf("failed to clear finalizers: %w", err) - } - - case reconciler.DoObserveKind: - // Observe any changes to this resource, since we are not the leader. - reconcileEvent = do(ctx, resource) - - } - - // Synchronize the status. - switch { - case r.skipStatusUpdates: - // This reconciler implementation is configured to skip resource updates. - // This may mean this reconciler does not observe spec, but reconciles external changes. - case equality.Semantic.DeepEqual(original.Status, resource.Status): - // If we didn't change anything then don't call updateStatus. - // This is important because the copy we loaded from the injectionInformer's - // cache may be stale and we don't want to overwrite a prior update - // to status with this stale state. - case !s.isLeader: - // High-availability reconcilers may have many replicas watching the resource, but only - // the elected leader is expected to write modifications. - logger.Warn("Saw status changes when we aren't the leader!") - default: - if err = r.updateStatus(ctx, logger, original, resource); err != nil { - logger.Warnw("Failed to update resource status", zap.Error(err)) - r.Recorder.Eventf(resource, v1.EventTypeWarning, "UpdateFailed", - "Failed to update status for %q: %v", resource.Name, err) - return err - } - } - - // Report the reconciler event, if any. - if reconcileEvent != nil { - var event *reconciler.ReconcilerEvent - if reconciler.EventAs(reconcileEvent, &event) { - logger.Infow("Returned an event", zap.Any("event", reconcileEvent)) - r.Recorder.Event(resource, event.EventType, event.Reason, event.Error()) - - // the event was wrapped inside an error, consider the reconciliation as failed - if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { - return reconcileEvent - } - return nil - } - - if controller.IsSkipKey(reconcileEvent) { - // This is a wrapped error, don't emit an event. - } else if ok, _ := controller.IsRequeueKey(reconcileEvent); ok { - // This is a wrapped error, don't emit an event. - } else if errors.IsConflict(reconcileEvent) { - // Conflict errors are expected, don't emit an event. - } else { - logger.Errorw("Returned an error", zap.Error(reconcileEvent)) - r.Recorder.Event(resource, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) - } - return reconcileEvent - } - - return nil -} - -func (r *reconcilerImpl) updateStatus(ctx context.Context, logger *zap.SugaredLogger, existing *v1alpha1.TektonHub, desired *v1alpha1.TektonHub) error { - existing = existing.DeepCopy() - return reconciler.RetryUpdateConflicts(func(attempts int) (err error) { - // The first iteration tries to use the injectionInformer's state, subsequent attempts fetch the latest state via API. - if attempts > 0 { - - getter := r.Client.OperatorV1alpha1().TektonHubs() - - existing, err = getter.Get(ctx, desired.Name, metav1.GetOptions{}) - if err != nil { - return err - } - } - - // If there's nothing to update, just return. - if equality.Semantic.DeepEqual(existing.Status, desired.Status) { - return nil - } - - if logger.Desugar().Core().Enabled(zapcore.DebugLevel) { - if diff, err := kmp.SafeDiff(existing.Status, desired.Status); err == nil && diff != "" { - logger.Debug("Updating status with: ", diff) - } - } - - existing.Status = desired.Status - - updater := r.Client.OperatorV1alpha1().TektonHubs() - - _, err = updater.UpdateStatus(ctx, existing, metav1.UpdateOptions{}) - return err - }) -} - -// updateFinalizersFiltered will update the Finalizers of the resource. -// TODO: this method could be generic and sync all finalizers. For now it only -// updates defaultFinalizerName or its override. -func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.TektonHub, desiredFinalizers sets.Set[string]) (*v1alpha1.TektonHub, error) { - if r.useServerSideApplyForFinalizers { - return r.updateFinalizersFilteredServerSideApply(ctx, resource, desiredFinalizers) - } - return r.updateFinalizersFilteredMergePatch(ctx, resource, desiredFinalizers) -} - -// updateFinalizersFilteredServerSideApply uses server-side apply to manage only this controller's finalizer. -func (r *reconcilerImpl) updateFinalizersFilteredServerSideApply(ctx context.Context, resource *v1alpha1.TektonHub, desiredFinalizers sets.Set[string]) (*v1alpha1.TektonHub, error) { - // Check if we need to do anything - existingFinalizers := sets.New[string](resource.Finalizers...) - - var finalizers []string - if desiredFinalizers.Has(r.finalizerName) { - if existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // Apply configuration with only our finalizer to add it. - finalizers = []string{r.finalizerName} - } else { - if !existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // For removal, we apply an empty configuration for our finalizer field manager. - // This effectively removes our finalizer while preserving others. - finalizers = []string{} // Empty array removes our managed finalizers - } - - // Determine GVK - gvks, _, err := scheme.Scheme.ObjectKinds(resource) - if err != nil || len(gvks) == 0 { - return resource, fmt.Errorf("failed to determine GVK for resource: %w", err) - } - gvk := gvks[0] - - // Create apply configuration - applyConfig := map[string]interface{}{ - "apiVersion": gvk.GroupVersion().String(), - "kind": gvk.Kind, - "metadata": map[string]interface{}{ - "name": resource.Name, - "uid": resource.UID, - "finalizers": finalizers, - }, - } - - patch, err := json.Marshal(applyConfig) - if err != nil { - return resource, err - } - - patcher := r.Client.OperatorV1alpha1().TektonHubs() - - patchOpts := metav1.PatchOptions{ - FieldManager: r.finalizerFieldManager, - Force: &r.forceApplyFinalizers, - } - - updated, err := patcher.Patch(ctx, resource.Name, types.ApplyPatchType, patch, patchOpts) - if err != nil { - if !errors.IsConflict(err) { - r.Recorder.Eventf(resource, v1.EventTypeWarning, "FinalizerUpdateFailed", - "Failed to update finalizers for %q via server-side apply: %v", resource.Name, err) - } - } else { - r.Recorder.Eventf(updated, v1.EventTypeNormal, "FinalizerUpdate", - "Updated finalizers for %q via server-side apply", resource.GetName()) - } - return updated, err -} - -// updateFinalizersFilteredMergePatch uses merge patch to manage finalizers (legacy behavior). -func (r *reconcilerImpl) updateFinalizersFilteredMergePatch(ctx context.Context, resource *v1alpha1.TektonHub, desiredFinalizers sets.Set[string]) (*v1alpha1.TektonHub, error) { - // Don't modify the informers copy. - existing := resource.DeepCopy() - - var finalizers []string - - // If there's nothing to update, just return. - existingFinalizers := sets.New[string](existing.Finalizers...) - - if desiredFinalizers.Has(r.finalizerName) { - if existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // Add the finalizer. - finalizers = append(existing.Finalizers, r.finalizerName) - } else { - if !existingFinalizers.Has(r.finalizerName) { - // Nothing to do. - return resource, nil - } - // Remove the finalizer. - existingFinalizers.Delete(r.finalizerName) - finalizers = sets.List(existingFinalizers) - } - - mergePatch := map[string]interface{}{ - "metadata": map[string]interface{}{ - "finalizers": finalizers, - "resourceVersion": existing.ResourceVersion, - }, - } - - patch, err := json.Marshal(mergePatch) - if err != nil { - return resource, err - } - - patcher := r.Client.OperatorV1alpha1().TektonHubs() - - resourceName := resource.Name - updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) - if err != nil { - if !errors.IsConflict(err) { - r.Recorder.Eventf(existing, v1.EventTypeWarning, "FinalizerUpdateFailed", - "Failed to update finalizers for %q: %v", resourceName, err) - } - } else { - r.Recorder.Eventf(updated, v1.EventTypeNormal, "FinalizerUpdate", - "Updated %q finalizers", resource.GetName()) - } - return updated, err -} - -func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1alpha1.TektonHub) (*v1alpha1.TektonHub, error) { - if _, ok := r.reconciler.(Finalizer); !ok { - return resource, nil - } - - finalizers := sets.New[string](resource.Finalizers...) - - // If this resource is not being deleted, mark the finalizer. - if resource.GetDeletionTimestamp().IsZero() { - finalizers.Insert(r.finalizerName) - } - - // Synchronize the finalizers filtered by r.finalizerName. - return r.updateFinalizersFiltered(ctx, resource, finalizers) -} - -func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1alpha1.TektonHub, reconcileEvent reconciler.Event) (*v1alpha1.TektonHub, error) { - if _, ok := r.reconciler.(Finalizer); !ok { - return resource, nil - } - if resource.GetDeletionTimestamp().IsZero() { - return resource, nil - } - - finalizers := sets.New[string](resource.Finalizers...) - - if reconcileEvent != nil { - var event *reconciler.ReconcilerEvent - if reconciler.EventAs(reconcileEvent, &event) { - if event.EventType == v1.EventTypeNormal { - finalizers.Delete(r.finalizerName) - } - } - } else { - finalizers.Delete(r.finalizerName) - } - - // Synchronize the finalizers filtered by r.finalizerName. - updated, err := r.updateFinalizersFiltered(ctx, resource, finalizers) - if err != nil { - // Check if the resource still exists by querying the API server to avoid logging errors - // when reconciling stale object from cache while the object is actually deleted. - logger := logging.FromContext(ctx) - - getter := r.Client.OperatorV1alpha1().TektonHubs() - - _, getErr := getter.Get(ctx, resource.Name, metav1.GetOptions{}) - if errors.IsNotFound(getErr) { - // Resource no longer exists, which could happen during deletion - logger.Debugw("Resource no longer exists while clearing finalizers", - "resource", resource.GetName(), - "namespace", resource.GetNamespace(), - "originalError", err) - // Return the original resource since the finalizer clearing is effectively complete - return resource, nil - } - - // For other errors, return the original error - return updated, err - } - - return updated, nil -} diff --git a/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/state.go b/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/state.go deleted file mode 100644 index 8c30af7b0c..0000000000 --- a/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub/state.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by injection-gen. DO NOT EDIT. - -package tektonhub - -import ( - fmt "fmt" - - v1alpha1 "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - types "k8s.io/apimachinery/pkg/types" - cache "k8s.io/client-go/tools/cache" - reconciler "knative.dev/pkg/reconciler" -) - -// state is used to track the state of a reconciler in a single run. -type state struct { - // key is the original reconciliation key from the queue. - key string - // namespace is the namespace split from the reconciliation key. - namespace string - // name is the name split from the reconciliation key. - name string - // reconciler is the reconciler. - reconciler Interface - // roi is the read only interface cast of the reconciler. - roi ReadOnlyInterface - // isROI (Read Only Interface) the reconciler only observes reconciliation. - isROI bool - // isLeader the instance of the reconciler is the elected leader. - isLeader bool -} - -func newState(key string, r *reconcilerImpl) (*state, error) { - // Convert the namespace/name string into a distinct namespace and name. - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - return nil, fmt.Errorf("invalid resource key: %s", key) - } - - roi, isROI := r.reconciler.(ReadOnlyInterface) - - isLeader := r.IsLeaderFor(types.NamespacedName{ - Namespace: namespace, - Name: name, - }) - - return &state{ - key: key, - namespace: namespace, - name: name, - reconciler: r.reconciler, - roi: roi, - isROI: isROI, - isLeader: isLeader, - }, nil -} - -// isNotLeaderNorObserver checks to see if this reconciler with the current -// state is enabled to do any work or not. -// isNotLeaderNorObserver returns true when there is no work possible for the -// reconciler. -func (s *state) isNotLeaderNorObserver() bool { - if !s.isLeader && !s.isROI { - // If we are not the leader, and we don't implement the ReadOnly - // interface, then take a fast-path out. - return true - } - return false -} - -func (s *state) reconcileMethodFor(o *v1alpha1.TektonHub) (string, doReconcile) { - if o.GetDeletionTimestamp().IsZero() { - if s.isLeader { - return reconciler.DoReconcileKind, s.reconciler.ReconcileKind - } else if s.isROI { - return reconciler.DoObserveKind, s.roi.ObserveKind - } - } else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok { - return reconciler.DoFinalizeKind, fin.FinalizeKind - } - return "unknown", nil -} diff --git a/pkg/client/listers/operator/v1alpha1/expansion_generated.go b/pkg/client/listers/operator/v1alpha1/expansion_generated.go index ace9551984..bcbe8a4570 100644 --- a/pkg/client/listers/operator/v1alpha1/expansion_generated.go +++ b/pkg/client/listers/operator/v1alpha1/expansion_generated.go @@ -46,10 +46,6 @@ type TektonConfigListerExpansion interface{} // TektonDashboardLister. type TektonDashboardListerExpansion interface{} -// TektonHubListerExpansion allows custom methods to be added to -// TektonHubLister. -type TektonHubListerExpansion interface{} - // TektonInstallerSetListerExpansion allows custom methods to be added to // TektonInstallerSetLister. type TektonInstallerSetListerExpansion interface{} diff --git a/pkg/client/listers/operator/v1alpha1/tektonhub.go b/pkg/client/listers/operator/v1alpha1/tektonhub.go deleted file mode 100644 index 71c36d25fa..0000000000 --- a/pkg/client/listers/operator/v1alpha1/tektonhub.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright 2020 The Tekton 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - operatorv1alpha1 "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// TektonHubLister helps list TektonHubs. -// All objects returned here must be treated as read-only. -type TektonHubLister interface { - // List lists all TektonHubs in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*operatorv1alpha1.TektonHub, err error) - // Get retrieves the TektonHub from the index for a given name. - // Objects returned here must be treated as read-only. - Get(name string) (*operatorv1alpha1.TektonHub, error) - TektonHubListerExpansion -} - -// tektonHubLister implements the TektonHubLister interface. -type tektonHubLister struct { - listers.ResourceIndexer[*operatorv1alpha1.TektonHub] -} - -// NewTektonHubLister returns a new TektonHubLister. -func NewTektonHubLister(indexer cache.Indexer) TektonHubLister { - return &tektonHubLister{listers.New[*operatorv1alpha1.TektonHub](indexer, operatorv1alpha1.Resource("tektonhub"))} -} diff --git a/pkg/reconciler/common/releases.go b/pkg/reconciler/common/releases.go index c7b9748fdc..2dbb44b72b 100644 --- a/pkg/reconciler/common/releases.go +++ b/pkg/reconciler/common/releases.go @@ -94,8 +94,6 @@ func ComponentDir(instance v1alpha1.TektonComponent) string { return filepath.Join(koDataDir, "tekton-config") case *v1alpha1.TektonResult: return filepath.Join(koDataDir, "tekton-results") - case *v1alpha1.TektonHub: - return filepath.Join(koDataDir, "tekton-hub") case *v1alpha1.TektonChain: return filepath.Join(koDataDir, "tekton-chains") case *v1alpha1.ManualApprovalGate: diff --git a/pkg/reconciler/common/targetnamespace_test.go b/pkg/reconciler/common/targetnamespace_test.go index 2dd7af77fc..45ea06ce1e 100644 --- a/pkg/reconciler/common/targetnamespace_test.go +++ b/pkg/reconciler/common/targetnamespace_test.go @@ -51,22 +51,6 @@ func TestReconcileTargetNamespace(t *testing.T) { }, err: nil, }, - { - name: "verify-tekton-hub", - component: &v1alpha1.TektonHub{ - ObjectMeta: metav1.ObjectMeta{Name: "hub"}, - Spec: v1alpha1.TektonHubSpec{CommonSpec: v1alpha1.CommonSpec{TargetNamespace: namespaceTektonPipelines}}, - }, - err: nil, - }, - { - name: "verify-custom-target-namespace-tekton-hub", - component: &v1alpha1.TektonHub{ - ObjectMeta: metav1.ObjectMeta{Name: "hub"}, - Spec: v1alpha1.TektonHubSpec{CommonSpec: v1alpha1.CommonSpec{TargetNamespace: "custom"}}, - }, - err: nil, - }, { name: "verify-custom-target-namespace", component: &v1alpha1.TektonConfig{ diff --git a/pkg/reconciler/common/transformers.go b/pkg/reconciler/common/transformers.go index 8ec7ba745f..2b08aac73d 100644 --- a/pkg/reconciler/common/transformers.go +++ b/pkg/reconciler/common/transformers.go @@ -57,7 +57,6 @@ const ( MulticlusterProxyAAEImagePrefix = "IMAGE_MULTICLUSTERPROXYAAE_" SyncerServiceImagePrefix = "IMAGE_SYNCER_SERVICE_WORKLOAD_" ResultsImagePrefix = "IMAGE_RESULTS_" - HubImagePrefix = "IMAGE_HUB_" DashboardImagePrefix = "IMAGE_DASHBOARD_" DefaultTargetNamespace = "tekton-pipelines" diff --git a/pkg/reconciler/kubernetes/kubernetesplatform/config.go b/pkg/reconciler/kubernetes/kubernetesplatform/config.go index d7fb4b9814..68b2b0a14a 100644 --- a/pkg/reconciler/kubernetes/kubernetesplatform/config.go +++ b/pkg/reconciler/kubernetes/kubernetesplatform/config.go @@ -22,7 +22,6 @@ import ( k8sChain "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektonchain" k8sConfig "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektonconfig" k8sDashboard "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektondashboard" - k8sHub "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektonhub" k8sInstallerSet "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektoninstallerset" k8sMulticlusterProxyAAE "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektonmulticlusterproxyaae" k8sPipeline "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektonpipeline" @@ -56,9 +55,6 @@ var ( Name: string(platform.ControllerTektonTrigger), ControllerConstructor: k8sTrigger.NewController, }, - platform.ControllerTektonHub: injection.NamedControllerConstructor{ - Name: string(platform.ControllerTektonHub), - ControllerConstructor: k8sHub.NewController}, platform.ControllerTektonChain: injection.NamedControllerConstructor{ Name: string(platform.ControllerTektonChain), ControllerConstructor: k8sChain.NewController}, diff --git a/pkg/reconciler/kubernetes/tektonhub/controller.go b/pkg/reconciler/kubernetes/tektonhub/controller.go deleted file mode 100644 index 18e42c7899..0000000000 --- a/pkg/reconciler/kubernetes/tektonhub/controller.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2022 The Tekton 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 tektonhub - -import ( - "context" - - "github.com/go-logr/zapr" - mfc "github.com/manifestival/client-go-client" - mf "github.com/manifestival/manifestival" - "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - operatorclient "github.com/tektoncd/operator/pkg/client/injection/client" - tektonHubinformer "github.com/tektoncd/operator/pkg/client/injection/informers/operator/v1alpha1/tektonhub" - tektonInstallerinformer "github.com/tektoncd/operator/pkg/client/injection/informers/operator/v1alpha1/tektoninstallerset" - tektonHubReconciler "github.com/tektoncd/operator/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub" - "github.com/tektoncd/operator/pkg/reconciler/common" - "go.uber.org/zap" - "k8s.io/client-go/tools/cache" - kubeclient "knative.dev/pkg/client/injection/kube/client" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" - "knative.dev/pkg/injection" - "knative.dev/pkg/logging" -) - -// NewController initializes the controller and is called by the generated code -// Registers eventhandlers to enqueue events -func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - return NewExtendedController(common.NoExtension)(ctx, cmw) -} - -// NewExtendedController returns a controller extended to a specific platform -func NewExtendedController(generator common.ExtensionGenerator) injection.ControllerConstructor { - return func(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - tektonHubInformer := tektonHubinformer.Get(ctx) - kubeClient := kubeclient.Get(ctx) - logger := logging.FromContext(ctx) - - mfclient, err := mfc.NewClient(injection.GetConfig(ctx)) - if err != nil { - logger.Fatalw("Error creating client from injected config", zap.Error(err)) - } - mflogger := zapr.NewLogger(logger.Named("manifestival").Desugar()) - manifest, err := mf.ManifestFrom(mf.Slice{}, mf.UseClient(mfclient), mf.UseLogger(mflogger)) - if err != nil { - logger.Fatalw("Error creating initial manifest", zap.Error(err)) - } - - operatorVer, err := common.OperatorVersion(ctx) - if err != nil { - logger.Fatal(err) - } - - c := &Reconciler{ - kubeClientSet: kubeClient, - operatorClientSet: operatorclient.Get(ctx), - extension: generator(ctx), - manifest: manifest, - operatorVersion: operatorVer, - } - impl := tektonHubReconciler.NewImpl(ctx, c) - - logger.Debug("Setting up event handlers") - - if _, err := tektonHubInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue)); err != nil { - logger.Panicf("Couldn't register TektonHub informer event handler: %w", err) - } - - if _, err := tektonInstallerinformer.Get(ctx).Informer().AddEventHandler(cache.FilteringResourceEventHandler{ - FilterFunc: controller.FilterController(&v1alpha1.TektonHub{}), - Handler: controller.HandleAll(impl.EnqueueControllerOf), - }); err != nil { - logger.Panicf("Couldn't register TektonInstallerSet informer event handler: %w", err) - } - return impl - } -} diff --git a/pkg/reconciler/kubernetes/tektonhub/installerset.go b/pkg/reconciler/kubernetes/tektonhub/installerset.go deleted file mode 100644 index b361f0dfa1..0000000000 --- a/pkg/reconciler/kubernetes/tektonhub/installerset.go +++ /dev/null @@ -1,117 +0,0 @@ -package tektonhub - -import ( - "context" - "fmt" - - mf "github.com/manifestival/manifestival" - "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - clientset "github.com/tektoncd/operator/pkg/client/clientset/versioned" - "github.com/tektoncd/operator/pkg/reconciler/common" - "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektoninstallerset" - "github.com/tektoncd/operator/pkg/reconciler/shared/hash" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// checkIfInstallerSetExist checks if installer set exists for a component and return true/false based on it -// and if installer set which already exist is of older version then it deletes and return false to create a new -// installer set -func (r *Reconciler) checkIfInstallerSetExist(ctx context.Context, oc clientset.Interface, relVersion string, installerSetType string) (bool, error) { - - labels := r.getLabels(installerSetType) - labelSelector, err := common.LabelSelector(labels) - if err != nil { - return false, err - } - - compInstallerSet, err := tektoninstallerset.CurrentInstallerSetName(ctx, r.operatorClientSet, labelSelector) - if err != nil { - return false, err - } - - if compInstallerSet != "" { - // if already created then check which version it is - ctIs, err := oc.OperatorV1alpha1().TektonInstallerSets(). - Get(ctx, compInstallerSet, metav1.GetOptions{}) - if err != nil { - if apierrors.IsNotFound(err) { - return false, nil - } - return false, err - } - - version, ok := ctIs.Annotations[v1alpha1.ReleaseVersionKey] - if ok && version == relVersion { - // if installer set already exist and release version is same - // then ignore and move on - return true, nil - } - - // release version doesn't exist or is different from expected - // deleted existing InstallerSet and create a new one - - err = oc.OperatorV1alpha1().TektonInstallerSets(). - Delete(ctx, compInstallerSet, metav1.DeleteOptions{}) - if err != nil { - return false, err - } - } - - return false, nil -} - -func createInstallerSet(ctx context.Context, oc clientset.Interface, th *v1alpha1.TektonHub, - manifest mf.Manifest, releaseVersion, component, installerSetPrefix, namespace string, labels map[string]string, specHash string) error { - - is := makeInstallerSet(th, manifest, installerSetPrefix, releaseVersion, namespace, labels, specHash) - if is == nil { - return fmt.Errorf("Unable to create installerset") - } - - createdIs, err := oc.OperatorV1alpha1().TektonInstallerSets(). - Create(ctx, is, metav1.CreateOptions{}) - if err != nil { - return err - } - - if len(th.Status.HubInstallerSet) == 0 { - th.Status.HubInstallerSet = map[string]string{} - } - - // Update the status of addon with created installerSet name - th.Status.HubInstallerSet[component] = createdIs.Name - th.Status.SetVersion(releaseVersion) - return nil -} - -func makeInstallerSet(th *v1alpha1.TektonHub, manifest mf.Manifest, prefix, releaseVersion, namespace string, labels map[string]string, specHash string) *v1alpha1.TektonInstallerSet { - ownerRef := *metav1.NewControllerRef(th, th.GetGroupVersionKind()) - - tektonHubCRSpecHash, err := hash.Compute(th.Spec) - if err != nil { - return nil - } - - is := &v1alpha1.TektonInstallerSet{ - ObjectMeta: metav1.ObjectMeta{ - GenerateName: fmt.Sprintf("%s-", prefix), - Labels: labels, - Annotations: map[string]string{ - v1alpha1.ReleaseVersionKey: releaseVersion, - v1alpha1.TargetNamespaceKey: namespace, - v1alpha1.LastAppliedHashKey: tektonHubCRSpecHash, - }, - OwnerReferences: []metav1.OwnerReference{ownerRef}, - }, - Spec: v1alpha1.TektonInstallerSetSpec{ - Manifests: manifest.Resources(), - }, - } - - if specHash != "" { - is.Annotations[v1alpha1.DbSecretHash] = specHash - } - - return is -} diff --git a/pkg/reconciler/kubernetes/tektonhub/tektonhub.go b/pkg/reconciler/kubernetes/tektonhub/tektonhub.go deleted file mode 100644 index 9d1386016b..0000000000 --- a/pkg/reconciler/kubernetes/tektonhub/tektonhub.go +++ /dev/null @@ -1,1035 +0,0 @@ -/* -Copyright 2022 The Tekton 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 tektonhub - -import ( - "bytes" - "context" - "fmt" - "io" - "net/http" - "path/filepath" - "reflect" - "strings" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - - mf "github.com/manifestival/manifestival" - "github.com/spf13/viper" - "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - clientset "github.com/tektoncd/operator/pkg/client/clientset/versioned" - tektonhubconciler "github.com/tektoncd/operator/pkg/client/injection/reconciler/operator/v1alpha1/tektonhub" - "github.com/tektoncd/operator/pkg/reconciler/common" - "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektoninstallerset" - "github.com/tektoncd/operator/pkg/reconciler/shared/hash" - "k8s.io/client-go/kubernetes" - "knative.dev/pkg/apis" - "knative.dev/pkg/logging" - pkgreconciler "knative.dev/pkg/reconciler" -) - -// Reconciler implements controller.Reconciler for TektonHub resources. -type Reconciler struct { - // kubeClientSet allows us to talk to the k8s for core APIs - kubeClientSet kubernetes.Interface - // operatorClientSet allows us to configure operator objects - operatorClientSet clientset.Interface - // manifest is empty, but with a valid client and logger. all - // manifests are immutable, and any created during reconcile are - // expected to be appended to this one, obviating the passing of - // client & logger - manifest mf.Manifest - // Platform-specific behavior to affect the transform - extension common.Extension - operatorVersion string -} - -const ( - // installerSet labels - installerSetLabelCreatedByValue = "TektonHub" - - // installerSet names - installerSetNameDatabase = "DbInstallerSet" - installerSetDatabaseMigration = "DbMigrationInstallerSet" - installerSetNameAPI = "ApiInstallerSet" - installerSetNameUI = "UiInstallerSet" - - // installerSet types - installerSetTypeDatabase = "tekton-hub-db" - installerSetTypeDatabaseMigration = "tekton-hub-db-migration" - installerSetTypeAPI = "tekton-hub-api" - installerSetTypeUI = "tekton-hub-ui" - - // manifests directory names - manifestDirDatabase = "db" - manifestDirDatabaseMigration = "db-migration" - manifestDirAPI = "api" - manifestDirUI = "ui" - manifestDirInfo = "hub-info" - - // resource names - databaseSecretName = "tekton-hub-db" - apiConfigMapName = "tekton-hub-api" - uiConfigMapName = "tekton-hub-ui" - - // database secret keys - secretKeyPostgresHost = "POSTGRES_HOST" - secretKeyPostgresDB = "POSTGRES_DB" - secretKeyPostgresUser = "POSTGRES_USER" - secretKeyPostgresPassword = "POSTGRES_PASSWORD" - secretKeyPostgresPort = "POSTGRES_PORT" - - // default postgres database values - defaultPostgresHost = "tekton-hub-db" - defaultPostgresDB = "hub" - defaultPostgresUser = "hub" - defaultPostgresPassword = "hub" - defaultPostgresPort = "5432" -) - -var ( - errKeyMissing error = fmt.Errorf("secret doesn't contains all the keys") - - // Check that our Reconciler implements controller.Reconciler - _ tektonhubconciler.Interface = (*Reconciler)(nil) - _ tektonhubconciler.Finalizer = (*Reconciler)(nil) - - ls = metav1.LabelSelector{ - MatchLabels: map[string]string{ - v1alpha1.CreatedByKey: installerSetLabelCreatedByValue, - v1alpha1.InstallerSetType: v1alpha1.HubResourceName, - }, - } - - dbKeys = []string{secretKeyPostgresHost, secretKeyPostgresDB, secretKeyPostgresUser, secretKeyPostgresPassword, secretKeyPostgresPort} -) - -type Data struct { - Catalogs []v1alpha1.Catalog - Categories []v1alpha1.Category - Scopes []v1alpha1.Scope - Default v1alpha1.Default -} - -// FinalizeKind removes all resources after deletion of a TektonHub. -func (r *Reconciler) FinalizeKind(ctx context.Context, original *v1alpha1.TektonHub) pkgreconciler.Event { - logger := logging.FromContext(ctx) - - labelSelector, err := common.LabelSelector(ls) - if err != nil { - return err - } - if err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets(). - DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{ - LabelSelector: labelSelector, - }); err != nil { - logger.Error("Failed to delete installer set created by TektonHub", err) - return err - } - - if err := r.extension.Finalize(ctx, original); err != nil { - logger.Error("Failed to finalize platform resources", err) - } - return nil -} - -// ReconcileKind compares the actual state with the desired, and attempts to -// converge the two. -func (r *Reconciler) ReconcileKind(ctx context.Context, th *v1alpha1.TektonHub) pkgreconciler.Event { - logger := logging.FromContext(ctx) - th.Status.InitializeConditions() - th.Status.ObservedGeneration = th.Generation - - logger.Infow("Reconciling TektonHub", "status", th.Status) - - // we have to maintain only one hub across the cluster and the accepted resource name is "hub" - if th.GetName() != v1alpha1.HubResourceName { - msg := fmt.Sprintf("Resource ignored, Expected Name: %s, Got Name: %s", - v1alpha1.HubResourceName, - th.GetName(), - ) - logger.Error(msg) - th.Status.MarkNotReady(msg) - return nil - } - - th.SetDefaults(ctx) - - // reconcile target namespace - if err := common.ReconcileTargetNamespace(ctx, nil, nil, th, r.kubeClientSet); err != nil { - logger.Errorw("error on reconciling targetNamespace", - "targetNamespace", th.Spec.GetTargetNamespace(), - err, - ) - return err - } - - // execute pre-reconcile, used in extension - if err := r.extension.PreReconcile(ctx, th); err != nil { - return r.handleError(err, th) - } - th.Status.MarkPreReconcilerComplete() - - // get TektonHub version and yaml manifests directory - version := common.TargetVersion(th) - hubManifestDir := filepath.Join(common.ComponentDir(th), version) - - // if user has not supplied external database credentials setup a database - if err := r.reconcileDatabaseInstallerSet(ctx, th, hubManifestDir, version); err != nil { - return r.handleError(err, th) - } - - if err := r.setupDatabaseMigrationInstallerSet(ctx, th, hubManifestDir, version); err != nil { - return r.handleError(err, th) - } - th.Status.MarkDatabaseMigrationDone() - - if err := r.reconcileApiInstallerSet(ctx, th, hubManifestDir, version); err != nil { - return r.handleError(err, th) - } - th.Status.MarkApiInstallerSetAvailable() - - if err := r.reconcileUiInstallerSet(ctx, th, hubManifestDir, version); err != nil { - return r.handleError(err, th) - } - th.Status.MarkUiInstallerSetAvailable() - - // execute post-reconcile, used in extension - if err := r.extension.PostReconcile(ctx, th); err != nil { - return r.handleError(err, th) - } - th.Status.MarkPostReconcilerComplete() - - return nil -} - -func (r *Reconciler) handleError(err error, th *v1alpha1.TektonHub) error { - if err == v1alpha1.RECONCILE_AGAIN_ERR { - return v1alpha1.REQUEUE_EVENT_AFTER - } - return err -} - -func (r *Reconciler) reconcileUiInstallerSet(ctx context.Context, th *v1alpha1.TektonHub, hubDir, version string) error { - exist, err := r.checkIfInstallerSetExist(ctx, r.operatorClientSet, version, installerSetTypeUI) - if err != nil { - return err - } - - if !exist { - th.Status.MarkUiInstallerSetNotAvailable("UI installer set not available") - uiLocation := filepath.Join(hubDir, manifestDirUI) - - manifest, err := r.getManifest(ctx, th, uiLocation) - if err != nil { - return err - } - - err = r.setUpAndCreateInstallerSet(ctx, *manifest, th, installerSetNameUI, version, installerSetTypeUI) - if err != nil { - return err - } - - } - - if exist { - // Get the installerset, check for the hash of spec - // if not same delete the installerset. - labels := r.getLabels(installerSetTypeUI) - labelSelector, err := common.LabelSelector(labels) - if err != nil { - return err - } - - compInstallerSet, err := tektoninstallerset.CurrentInstallerSetName(ctx, r.operatorClientSet, labelSelector) - if err != nil { - return err - } - - if compInstallerSet != "" { - ctIs, err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets().Get(ctx, compInstallerSet, metav1.GetOptions{}) - if err != nil { - return err - } - - lastAppliedTektonHubCRSpecHash := ctIs.Annotations[v1alpha1.LastAppliedHashKey] - tektonHubCRSpecHash, err := hash.Compute(th.Spec) - if err != nil { - return err - } - - if tektonHubCRSpecHash != lastAppliedTektonHubCRSpecHash { - if err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets().Delete(ctx, ctIs.Name, metav1.DeleteOptions{}); err != nil { - return err - } - return v1alpha1.RECONCILE_AGAIN_ERR - } - } - } - - err = r.checkComponentStatus(ctx, th, installerSetTypeUI) - if err != nil { - th.Status.MarkUiInstallerSetNotAvailable(err.Error()) - return v1alpha1.RECONCILE_AGAIN_ERR - } - - return nil -} - -func (r *Reconciler) reconcileApiInstallerSet(ctx context.Context, th *v1alpha1.TektonHub, hubDir, version string) error { - - // Validate whether the secrets and configmap are created for API - if err := r.validateApiDependencies(ctx, th, hubDir, manifestDirAPI); err != nil { - th.Status.MarkApiDependencyMissing("api secrets not present") - return v1alpha1.REQUEUE_EVENT_AFTER - } - - th.Status.MarkApiDependenciesInstalled() - - exist, err := r.checkIfInstallerSetExist(ctx, r.operatorClientSet, version, installerSetTypeAPI) - if err != nil { - return err - } - - apiLocation := filepath.Join(hubDir, manifestDirAPI) - apiManifest, err := r.getManifest(ctx, th, apiLocation) - if err != nil { - return err - } - - infoLocation := filepath.Join(hubDir, manifestDirInfo) - infoManifest, err := r.getManifest(ctx, th, infoLocation) - if err != nil { - return err - } - - *apiManifest = apiManifest.Append(*infoManifest) - - if err := applyPVC(ctx, apiManifest, th); err != nil { - return err - } - - if !exist { - th.Status.MarkApiInstallerSetNotAvailable("API installer set not available") - - err = r.setUpAndCreateInstallerSet(ctx, *apiManifest, th, installerSetNameAPI, version, installerSetTypeAPI) - if err != nil { - return err - } - } - - if exist { - // Get the installerset, check for the hash of db secret - // if not same delete the installerset. - labels := r.getLabels(installerSetTypeAPI) - labelSelector, err := common.LabelSelector(labels) - if err != nil { - return err - } - - compInstallerSet, err := tektoninstallerset.CurrentInstallerSetName(ctx, r.operatorClientSet, labelSelector) - if err != nil { - return err - } - - if compInstallerSet != "" { - ctIs, err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets(). - Get(ctx, compInstallerSet, metav1.GetOptions{}) - if err != nil { - return err - } - - lastAppliedDbSecretHash := ctIs.Annotations[v1alpha1.DbSecretHash] - lastAppliedTektonHubCRSpecHash := ctIs.Annotations[v1alpha1.LastAppliedHashKey] - - secret, err := r.getSecret(ctx, databaseSecretName, th.Spec.GetTargetNamespace(), dbKeys) - if err != nil { - return err - } - - expectedDbSecretHash, err := hash.Compute(secret.Data) - if err != nil { - return err - } - tektonHubCRSpecHash, err := hash.Compute(th.Spec) - if err != nil { - return err - } - - if lastAppliedDbSecretHash != expectedDbSecretHash || tektonHubCRSpecHash != lastAppliedTektonHubCRSpecHash { - - if err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets().Delete(ctx, ctIs.Name, metav1.DeleteOptions{}); err != nil { - return err - } - return v1alpha1.RECONCILE_AGAIN_ERR - } - } - } - - err = r.checkComponentStatus(ctx, th, installerSetTypeAPI) - if err != nil { - th.Status.MarkApiInstallerSetNotAvailable(err.Error()) - return v1alpha1.RECONCILE_AGAIN_ERR - } - return nil -} - -func (r *Reconciler) setupDatabaseMigrationInstallerSet(ctx context.Context, th *v1alpha1.TektonHub, hubDir, version string) error { - // Check if the InstallerSet is available for DB-migration - exist, err := r.checkIfInstallerSetExist(ctx, r.operatorClientSet, version, installerSetTypeDatabaseMigration) - if err != nil { - return err - } - - if !exist { - dbMigrationManifestsDir := filepath.Join(hubDir, manifestDirDatabaseMigration) - th.Status.MarkDatabaseMigrationFailed("DB migration installerset not available") - - manifest, err := r.getManifest(ctx, th, dbMigrationManifestsDir) - if err != nil { - return err - } - - err = r.setUpAndCreateInstallerSet(ctx, *manifest, th, installerSetDatabaseMigration, version, installerSetTypeDatabaseMigration) - if err != nil { - return err - } - } - - if exist { - // Get the installerset, check for the hash of db secret - // if not same delete the installerset - - labels := r.getLabels(installerSetTypeDatabaseMigration) - labelSelector, err := common.LabelSelector(labels) - if err != nil { - return err - } - - compInstallerSet, err := tektoninstallerset.CurrentInstallerSetName(ctx, r.operatorClientSet, labelSelector) - if err != nil { - return err - } - - if compInstallerSet != "" { - ctIs, err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets().Get(ctx, compInstallerSet, metav1.GetOptions{}) - if err != nil { - return err - } - - lastAppliedDbSecretHash := ctIs.Annotations[v1alpha1.DbSecretHash] - - secret, err := r.getSecret(ctx, databaseSecretName, th.Spec.GetTargetNamespace(), dbKeys) - if err != nil { - return err - } - - expectedDbSecretHash, err := hash.Compute(secret.Data) - if err != nil { - return err - } - - if lastAppliedDbSecretHash != expectedDbSecretHash { - if err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets().Delete(ctx, ctIs.Name, metav1.DeleteOptions{}); err != nil { - return err - } - } - } - } - - err = r.checkComponentStatus(ctx, th, installerSetTypeDatabaseMigration) - if err != nil { - th.Status.MarkDatabaseMigrationFailed(err.Error()) - return v1alpha1.RECONCILE_AGAIN_ERR - } - return nil -} - -func (r *Reconciler) setupDatabase(ctx context.Context, th *v1alpha1.TektonHub, hubDir, version string) error { - // Check if the DB secrets are created - if err := r.validateOrCreateDBSecrets(ctx, th); err != nil { - th.Status.MarkDbDependencyMissing("db secrets are either invalid or not present") - return err - } - th.Status.MarkDbDependenciesInstalled() - - exist, err := r.checkIfInstallerSetExist(ctx, r.operatorClientSet, version, installerSetTypeDatabase) - if err != nil { - return err - } - - dbLocation := filepath.Join(hubDir, manifestDirDatabase) - dbManifest, err := r.getManifest(ctx, th, dbLocation) - if err != nil { - return err - } - - if err := applyPVC(ctx, dbManifest, th); err != nil { - return err - } - - if !exist { - th.Status.MarkDbInstallerSetNotAvailable("DB installer set not available") - - err = r.setUpAndCreateInstallerSet(ctx, *dbManifest, th, installerSetNameDatabase, version, installerSetTypeDatabase) - if err != nil { - return err - } - } - - err = r.checkComponentStatus(ctx, th, installerSetTypeDatabase) - if err != nil { - th.Status.MarkDbInstallerSetNotAvailable(err.Error()) - return v1alpha1.RECONCILE_AGAIN_ERR - } - - return nil -} - -// Validate DB are present on the cluster. If DB secrets are present and all the keys don't -// have values then update the remaining values with default values. If the DB secret -// is not present then create a new secret with default values. -func (r *Reconciler) validateOrCreateDBSecrets(ctx context.Context, th *v1alpha1.TektonHub) error { - logger := logging.FromContext(ctx) - targetNamespace := th.Spec.GetTargetNamespace() - - // th.Status.MarkDbDependencyInstalling("db secrets are being added into the namespace") - - dbSecret, err := r.getSecret(ctx, databaseSecretName, targetNamespace, dbKeys) - if err != nil { - newDbSecret := createDbSecret(databaseSecretName, targetNamespace, dbSecret, th) - if apierrors.IsNotFound(err) { - _, err = r.kubeClientSet.CoreV1().Secrets(targetNamespace).Create(ctx, newDbSecret, metav1.CreateOptions{}) - if err != nil { - logger.Error(err) - th.Status.MarkDbDependencyMissing(fmt.Sprintf("%s secret is missing", databaseSecretName)) - return err - } - return nil - } - if err == errKeyMissing { - _, err = r.kubeClientSet.CoreV1().Secrets(targetNamespace).Update(ctx, newDbSecret, metav1.UpdateOptions{}) - if err != nil { - logger.Error(err) - th.Status.MarkDbDependencyMissing(fmt.Sprintf("%s secret is missing", databaseSecretName)) - return err - } - } else { - logger.Error(err) - return err - } - } - - return nil -} - -// TektonHub expects API secrets to be created before installing Tekton Hub API -func (r *Reconciler) validateApiDependencies(ctx context.Context, th *v1alpha1.TektonHub, hubDir, comp string) error { - logger := logging.FromContext(ctx) - apiSecretKeys := []string{"GH_CLIENT_ID", "GH_CLIENT_SECRET", "JWT_SIGNING_KEY", "ACCESS_JWT_EXPIRES_IN", "REFRESH_JWT_EXPIRES_IN", "GHE_URL"} - - th.Status.MarkApiDependencyInstalling("checking for api secrets in the namespace and creating the ConfigMap") - - _, err := r.getSecret(ctx, th.Spec.Api.ApiSecretName, th.Spec.GetTargetNamespace(), apiSecretKeys) - if err != nil { - if apierrors.IsNotFound(err) { - if err := r.createApiSecret(ctx, th, hubDir, comp); err != nil { - return err - } - } - if err == errKeyMissing { - th.Status.MarkApiDependencyMissing(fmt.Sprintf("%s secret is missing the keys", th.Spec.Api.ApiSecretName)) - return err - } else { - logger.Error(err) - return err - } - } - return nil -} - -func (r *Reconciler) getManifest(ctx context.Context, th *v1alpha1.TektonHub, manifestLocation string) (*mf.Manifest, error) { - manifest := r.manifest.Append() - - if err := common.AppendManifest(&manifest, manifestLocation); err != nil { - return nil, err - } - - transformer := filterAndTransform(r.extension) - transformedManifest, err := transformer(ctx, &manifest, th) - if err != nil { - return nil, err - } - - return transformedManifest, nil -} - -func (r *Reconciler) getLabels(componentInstallerSetType string) metav1.LabelSelector { - return metav1.LabelSelector{ - MatchLabels: map[string]string{ - v1alpha1.CreatedByKey: installerSetLabelCreatedByValue, - v1alpha1.InstallerSetType: componentInstallerSetType, - }, - } -} - -func applyPVC(ctx context.Context, manifest *mf.Manifest, th *v1alpha1.TektonHub) error { - logger := logging.FromContext(ctx) - - pvc := manifest.Filter(mf.ByKind("PersistentVolumeClaim")) - pvcManifest, err := pvc.Transform( - mf.InjectOwner(th), - mf.InjectNamespace(th.Spec.GetTargetNamespace()), - ) - - if err != nil { - logger.Error("failed to transform manifest") - return err - } - - if err := pvcManifest.Apply(); err != nil { - return err - } - - return nil -} - -func (r *Reconciler) reconcileDatabaseInstallerSet(ctx context.Context, th *v1alpha1.TektonHub, hubDir, version string) error { - // Get the db secret, if not found or if any key is missing, - // then manage the db installerset. If the value of db host - // is different then user already has the db, hence delete - // existing db installerset - secret, err := r.getSecret(ctx, databaseSecretName, th.Spec.GetTargetNamespace(), dbKeys) - if err != nil { - // If not found create db with default db - if apierrors.IsNotFound(err) || err == errKeyMissing { - if err := r.setupDatabase(ctx, th, hubDir, version); err != nil { - return r.handleError(err, th) - } - th.Status.MarkDbInstallerSetAvailable() - return nil - } - return err - } else if string(secret.Data[secretKeyPostgresHost]) != defaultPostgresHost { - // Mark the database as ready state as the - // database is already installed by the user - th.Status.MarkDbDependenciesInstalled() - th.Status.MarkDbInstallerSetAvailable() - - // Get and delete the default db installerset - if err := r.getAndDeleteInstallerSet(ctx, installerSetTypeDatabase); err != nil { - if apierrors.IsNotFound(err) { - return nil - } - return err - } - } else { - // If secret found, with no error, then make sure db is up and running - if err := r.setupDatabase(ctx, th, hubDir, version); err != nil { - return r.handleError(err, th) - } - th.Status.MarkDbInstallerSetAvailable() - } - - return nil -} - -func (r *Reconciler) setUpAndCreateInstallerSet(ctx context.Context, manifest mf.Manifest, th *v1alpha1.TektonHub, installerSetName, version, prefixName string) error { - - manifest = manifest.Filter(mf.Not(mf.Any(mf.ByKind("Secret"), mf.ByKind("PersistentVolumeClaim"), mf.ByKind("Namespace")))) - - specHash := "" - if prefixName == installerSetTypeDatabaseMigration || prefixName == installerSetTypeAPI { - secret, err := r.kubeClientSet.CoreV1().Secrets(th.Spec.GetTargetNamespace()).Get(ctx, databaseSecretName, metav1.GetOptions{}) - if err != nil { - return err - } - - specHash, err = hash.Compute(secret.Data) - if err != nil { - return err - } - } - labels := r.getLabels(prefixName).MatchLabels - if err := createInstallerSet(ctx, r.operatorClientSet, th, manifest, - version, installerSetName, prefixName, th.Spec.GetTargetNamespace(), labels, specHash); err != nil { - return err - } - - return nil -} - -func (r *Reconciler) getAndDeleteInstallerSet(ctx context.Context, installerSetType string) error { - labels := r.getLabels(installerSetType) - labelSelector, err := common.LabelSelector(labels) - if err != nil { - return err - } - - compInstallerSet, err := tektoninstallerset.CurrentInstallerSetName(ctx, r.operatorClientSet, labelSelector) - if err != nil { - return err - } - - if compInstallerSet != "" { - _, err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets(). - Get(ctx, compInstallerSet, metav1.GetOptions{}) - if err != nil { - if apierrors.IsNotFound(err) { - return nil - } - return err - } - - err = r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets(). - Delete(ctx, compInstallerSet, metav1.DeleteOptions{}) - if err != nil { - return err - } - } - - return nil -} - -func (r *Reconciler) checkComponentStatus(ctx context.Context, th *v1alpha1.TektonHub, installerSetType string) error { - - labels := r.getLabels(installerSetType) - labelSelector, err := common.LabelSelector(labels) - if err != nil { - return err - } - - compInstallerSet, err := tektoninstallerset.CurrentInstallerSetName(ctx, r.operatorClientSet, labelSelector) - if err != nil { - return err - } - - if compInstallerSet != "" { - - ctIs, err := r.operatorClientSet.OperatorV1alpha1().TektonInstallerSets(). - Get(ctx, compInstallerSet, metav1.GetOptions{}) - if err != nil { - if apierrors.IsNotFound(err) { - return nil - } - return err - } - - ready := ctIs.Status.GetCondition(apis.ConditionReady) - if ready == nil || ready.Status == corev1.ConditionUnknown { - return fmt.Errorf("InstallerSet %s: waiting for installation", ctIs.Name) - } else if ready.Status == corev1.ConditionFalse { - return fmt.Errorf("InstallerSet %s: ", ready.Message) - } - } - - return nil -} - -func (r *Reconciler) getSecret(ctx context.Context, name, targetNs string, verifyKeys []string) (*corev1.Secret, error) { - secret, err := r.kubeClientSet.CoreV1().Secrets(targetNs).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return nil, err - } - - for _, key := range verifyKeys { - if _, ok := secret.Data[key]; !ok { - return nil, errKeyMissing - } - } - - return secret, nil -} - -func (r *Reconciler) createApiSecret(ctx context.Context, th *v1alpha1.TektonHub, hubDir, comp string) error { - - manifest, err := r.getHubManifest(ctx, th, hubDir, comp) - if err != nil { - return err - } - - secret := manifest.Filter(mf.ByKind("Secret")) - secretManifest, err := secret.Transform( - mf.InjectNamespace(th.Spec.GetTargetNamespace()), - ) - if err != nil { - return err - } - - if err := secretManifest.Apply(); err != nil { - return err - } - - return nil -} - -func (r *Reconciler) getHubManifest(ctx context.Context, th *v1alpha1.TektonHub, hubDir, comp string) (*mf.Manifest, error) { - manifestLocation := filepath.Join(hubDir, comp) - - manifest, err := r.getManifest(ctx, th, manifestLocation) - if err != nil { - return nil, err - } - - return manifest, nil -} - -func createDbSecret(name, namespace string, existingSecret *corev1.Secret, th *v1alpha1.TektonHub) *corev1.Secret { - s := &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - Labels: map[string]string{ - "app": "db", - }, - OwnerReferences: []metav1.OwnerReference{getOwnerRef(th)}, - }, - Type: corev1.SecretTypeOpaque, - } - - if existingSecret != nil && existingSecret.Data != nil { - s.Data = existingSecret.Data - } - - s.StringData = make(map[string]string) - - defaultValues := map[string]string{ - secretKeyPostgresHost: defaultPostgresHost, - secretKeyPostgresDB: defaultPostgresDB, - secretKeyPostgresUser: defaultPostgresUser, - secretKeyPostgresPassword: defaultPostgresPassword, - secretKeyPostgresPort: defaultPostgresPort, - } - - // fill default value for absents - for secretKey, defaultValue := range defaultValues { - if s.Data[secretKey] == nil || len(s.Data[secretKey]) == 0 { - s.StringData[secretKey] = defaultValue - } - } - - return s -} - -// Get an ownerRef of TektonHub -func getOwnerRef(th *v1alpha1.TektonHub) metav1.OwnerReference { - return *metav1.NewControllerRef(th, th.GroupVersionKind()) -} - -// add key value pair to the given configmap name -func addConfigMapKeyValue(configMapName, key, value string) mf.Transformer { - return func(u *unstructured.Unstructured) error { - kind := strings.ToLower(u.GetKind()) - if kind != "configmap" { - return nil - } - if u.GetName() != configMapName { - return nil - } - - cm := &corev1.ConfigMap{} - err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, cm) - if err != nil { - return err - } - - if cm.Data == nil { - cm.Data = map[string]string{} - } - - cm.Data[key] = value - - unstrObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(cm) - if err != nil { - return err - } - u.SetUnstructuredContent(unstrObj) - - return nil - } -} - -func updateApiConfigMap(th *v1alpha1.TektonHub, configMapName string) mf.Transformer { - return func(u *unstructured.Unstructured) error { - - kind := strings.ToLower(u.GetKind()) - if kind != "configmap" { - return nil - } - - if u.GetName() != configMapName { - return nil - } - - cm := &corev1.ConfigMap{} - err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, cm) - if err != nil { - return err - } - - // TODO: Remove this condition in the next release - if th.Spec.Api.HubConfigUrl != "" { - - hubUrlConfigdata, err := getConfigDataFromHubURL(th) - if err != nil { - return err - } - cm = updateConfigMapDataFromHubConfigURL(th, cm, hubUrlConfigdata) - - } else { - - if len(th.Spec.Categories) > 0 { - categories := "" - for _, c := range th.Spec.Categories { - categories += fmt.Sprintf("- %s\n", c) - } - cm.Data["CATEGORIES"] = categories - } - - if len(th.Spec.Catalogs) > 0 { - catalogs := "" - for _, c := range th.Spec.Catalogs { - catalogs = catalogs + getCatalogData(c, th) - } - cm.Data["CATALOGS"] = catalogs - } - - if len(th.Spec.Scopes) > 0 { - userScopes := "" - for _, s := range th.Spec.Scopes { - scope := "" - scope += fmt.Sprintf("- name: %s\n", s.Name) - scope += fmt.Sprintf(" users: [%s]\n", strings.Join(s.Users, ", ")) - userScopes = userScopes + scope - } - cm.Data["SCOPES"] = userScopes - } else { - cm.Data["SCOPES"] = "" - } - - if len(th.Spec.Default.Scopes) > 0 { - defaultScopes := "" - scopes := fmt.Sprintf("%s\n", defaultScopes) - for _, d := range th.Spec.Default.Scopes { - scopes += fmt.Sprintf(" - %s\n", d) - } - defaultScopes = fmt.Sprintf(" scopes: \n%s", scopes) - cm.Data["DEFAULT"] = defaultScopes - } - } - - if th.Spec.Api.CatalogRefreshInterval != "" { - cm.Data["CATALOG_REFRESH_INTERVAL"] = th.Spec.Api.CatalogRefreshInterval - } - - unstrObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(cm) - if err != nil { - return err - } - u.SetUnstructuredContent(unstrObj) - - return nil - } -} - -// TODO: Remove this function in the next release -// Adds Config Data from HubConfigUrl to API Config Map -func updateConfigMapDataFromHubConfigURL(th *v1alpha1.TektonHub, cm *corev1.ConfigMap, hubUrlConfigdata *Data) *corev1.ConfigMap { - categories := "" - for _, c := range hubUrlConfigdata.Categories { - categories += fmt.Sprintf("- %s\n", c.Name) - } - cm.Data["CATEGORIES"] = categories - - catalogs := "" - for _, c := range hubUrlConfigdata.Catalogs { - catalogs = catalogs + getCatalogData(c, th) - } - cm.Data["CATALOGS"] = catalogs - - userScopes := "" - for _, s := range hubUrlConfigdata.Scopes { - scope := "" - scope += fmt.Sprintf("- name: %s\n", s.Name) - scope += fmt.Sprintf(" users: [%s]\n", strings.Join(s.Users, ", ")) - userScopes = userScopes + scope - } - cm.Data["SCOPES"] = userScopes - - defaultScopes := "" - scopes := fmt.Sprintf("%s\n", defaultScopes) - for _, d := range hubUrlConfigdata.Default.Scopes { - scopes += fmt.Sprintf(" - %s\n", d) - } - defaultScopes = fmt.Sprintf(" scopes: \n%s", scopes) - cm.Data["DEFAULT"] = defaultScopes - - return cm -} - -func getCatalogData(c v1alpha1.Catalog, th *v1alpha1.TektonHub) string { - catalogs := "" - v := reflect.ValueOf(c) - - for i := 0; i < v.NumField(); i++ { - cat := "" - key := strings.ToLower(v.Type().Field(i).Name) - - if v.Field(i).Interface() != "" { - if key == "name" { - key = "- " + key - cat += fmt.Sprintf("%s: %s\n", key, v.Field(i).Interface()) - } else { - cat += fmt.Sprintf(" %s: %s\n", key, v.Field(i).Interface()) - } - catalogs = catalogs + cat - } - } - return catalogs -} - -// TODO: Remove this function in the next release -func getConfigDataFromHubURL(th *v1alpha1.TektonHub) (*Data, error) { - var data = &Data{} - if th.Spec.Api.HubConfigUrl != "" { - resp, err := http.Get(th.Spec.Api.HubConfigUrl) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - viper.SetConfigType("yaml") - if err := viper.ReadConfig(bytes.NewBuffer(body)); err != nil { - return nil, err - } - if err := viper.Unmarshal(&data); err != nil { - return nil, err - } - } - - return data, nil -} diff --git a/pkg/reconciler/kubernetes/tektonhub/transform.go b/pkg/reconciler/kubernetes/tektonhub/transform.go deleted file mode 100644 index ad0aa273ee..0000000000 --- a/pkg/reconciler/kubernetes/tektonhub/transform.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright 2023 The Tekton 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 tektonhub - -import ( - "context" - - mf "github.com/manifestival/manifestival" - "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - "github.com/tektoncd/operator/pkg/reconciler/common" - "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektoninstallerset/client" - "knative.dev/pkg/logging" -) - -func filterAndTransform(extension common.Extension) client.FilterAndTransform { - return func(ctx context.Context, manifest *mf.Manifest, comp v1alpha1.TektonComponent) (*mf.Manifest, error) { - logger := logging.FromContext(ctx) - hubCR := comp.(*v1alpha1.TektonHub) - - imagesRaw := common.ToLowerCaseKeys(common.ImagesFromEnv(common.HubImagePrefix)) - images := common.ImageRegistryDomainOverride(imagesRaw) - - trans := extension.Transformers(hubCR) - extra := []mf.Transformer{ - common.InjectOperandNameLabelOverwriteExisting(v1alpha1.OperandTektoncdHub), - mf.InjectOwner(hubCR), - mf.InjectNamespace(hubCR.Spec.GetTargetNamespace()), - common.DeploymentImages(images), - common.DeploymentEnvVarKubernetesMinVersion(), - common.JobImages(images), - updateApiConfigMap(hubCR, apiConfigMapName), - addConfigMapKeyValue(uiConfigMapName, "API_URL", hubCR.Status.ApiRouteUrl), - addConfigMapKeyValue(uiConfigMapName, "AUTH_BASE_URL", hubCR.Status.AuthRouteUrl), - addConfigMapKeyValue(uiConfigMapName, "API_VERSION", "v1"), - addConfigMapKeyValue(uiConfigMapName, "REDIRECT_URI", hubCR.Status.UiRouteUrl), - addConfigMapKeyValue(uiConfigMapName, "CUSTOM_LOGO_BASE64_DATA", hubCR.Spec.CustomLogo.Base64Data), - addConfigMapKeyValue(uiConfigMapName, "CUSTOM_LOGO_MEDIA_TYPE", hubCR.Spec.CustomLogo.MediaType), - common.AddDeploymentRestrictedPSA(), - common.AddJobRestrictedPSA(), - } - - trans = append(trans, extra...) - - err := common.Transform(ctx, manifest, hubCR, trans...) - if err != nil { - logger.Error("failed to transform manifest") - return &mf.Manifest{}, err - } - - // additional options transformer - // always execute as last transformer, so that the values in options will be final update values on the manifests - if err := common.ExecuteAdditionalOptionsTransformer(ctx, manifest, hubCR.Spec.GetTargetNamespace(), hubCR.Spec.Options); err != nil { - return &mf.Manifest{}, err - } - - return manifest, nil - } -} diff --git a/pkg/reconciler/openshift/openshiftplatform/config.go b/pkg/reconciler/openshift/openshiftplatform/config.go index b2c491930a..8a9c558bb0 100644 --- a/pkg/reconciler/openshift/openshiftplatform/config.go +++ b/pkg/reconciler/openshift/openshiftplatform/config.go @@ -24,7 +24,6 @@ import ( openshiftAddon "github.com/tektoncd/operator/pkg/reconciler/openshift/tektonaddon" openshiftChain "github.com/tektoncd/operator/pkg/reconciler/openshift/tektonchain" openshiftConfig "github.com/tektoncd/operator/pkg/reconciler/openshift/tektonconfig" - openshiftHub "github.com/tektoncd/operator/pkg/reconciler/openshift/tektonhub" openshiftMulticlusterProxyAAE "github.com/tektoncd/operator/pkg/reconciler/openshift/tektonmulticlusterproxyaae" openshiftPipeline "github.com/tektoncd/operator/pkg/reconciler/openshift/tektonpipeline" openshiftPruner "github.com/tektoncd/operator/pkg/reconciler/openshift/tektonpruner" @@ -56,10 +55,6 @@ var ( Name: string(platform.ControllerTektonTrigger), ControllerConstructor: openshiftTrigger.NewController, }, - platform.ControllerTektonHub: injection.NamedControllerConstructor{ - Name: string(platform.ControllerTektonHub), - ControllerConstructor: openshiftHub.NewController, - }, platform.ControllerTektonChain: injection.NamedControllerConstructor{ Name: string(platform.ControllerTektonChain), ControllerConstructor: openshiftChain.NewController, diff --git a/pkg/reconciler/openshift/tektonhub/controller.go b/pkg/reconciler/openshift/tektonhub/controller.go deleted file mode 100644 index f0a0a7b42b..0000000000 --- a/pkg/reconciler/openshift/tektonhub/controller.go +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright 2022 The Tekton 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 tektonhub - -import ( - "context" - - k8s_ctrl "github.com/tektoncd/operator/pkg/reconciler/kubernetes/tektonhub" - "knative.dev/pkg/configmap" - "knative.dev/pkg/controller" -) - -// NewController initializes the controller and is called by the generated code -// Registers eventhandlers to enqueue events -func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { - return k8s_ctrl.NewExtendedController(OpenShiftExtension)(ctx, cmw) -} diff --git a/pkg/reconciler/openshift/tektonhub/extension.go b/pkg/reconciler/openshift/tektonhub/extension.go deleted file mode 100644 index 9b3da36f4a..0000000000 --- a/pkg/reconciler/openshift/tektonhub/extension.go +++ /dev/null @@ -1,567 +0,0 @@ -/* -Copyright 2022 The Tekton 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 tektonhub - -import ( - "context" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/go-logr/zapr" - mfc "github.com/manifestival/client-go-client" - mf "github.com/manifestival/manifestival" - console "github.com/openshift/api/console/v1" - routev1 "github.com/openshift/api/route/v1" - "github.com/openshift/client-go/route/clientset/versioned/scheme" - "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - clientset "github.com/tektoncd/operator/pkg/client/clientset/versioned" - operatorclient "github.com/tektoncd/operator/pkg/client/injection/client" - "github.com/tektoncd/operator/pkg/reconciler/common" - openshiftCommon "github.com/tektoncd/operator/pkg/reconciler/openshift/common" - "go.uber.org/zap" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/kubernetes" - kubeclient "knative.dev/pkg/client/injection/kube/client" - "knative.dev/pkg/injection" - "knative.dev/pkg/logging" -) - -const ( - hubprefix string = "tekton-hub" - tektonHubAPIResourceKey string = "api" - tektonHubUiResourceKey string = "ui" - CreatedByValue string = "TektonHub" - ConsoleHubLinkInstallerSet = "ConsoleHubLink" - postgreSQLConfigMapDirectory = "static/tekton-hub/postgresql-cm" -) - -var replaceVal = map[string]string{ - "POSTGRES_DB": "POSTGRESQL_DATABASE", - "POSTGRES_USER": "POSTGRESQL_USER", - "POSTGRES_PASSWORD": "POSTGRESQL_PASSWORD", -} - -var ( - db string = fmt.Sprintf("%s-%s", hubprefix, "db") - api string = fmt.Sprintf("%s-%s", hubprefix, "api") - ui string = fmt.Sprintf("%s-%s", hubprefix, "ui") -) - -func OpenShiftExtension(ctx context.Context) common.Extension { - logger := logging.FromContext(ctx) - mfclient, err := mfc.NewClient(injection.GetConfig(ctx)) - if err != nil { - logger.Fatalw("error creating client from injected config", zap.Error(err)) - } - mflogger := zapr.NewLogger(logger.Named("manifestival").Desugar()) - manifest, err := mf.ManifestFrom(mf.Slice{}, mf.UseClient(mfclient), mf.UseLogger(mflogger)) - if err != nil { - logger.Fatalw("error creating initial manifest", zap.Error(err)) - } - - ext := openshiftExtension{ - operatorClientSet: operatorclient.Get(ctx), - kubeClientSet: kubeclient.Get(ctx), - manifest: manifest, - } - return ext -} - -type openshiftExtension struct { - operatorClientSet clientset.Interface - kubeClientSet kubernetes.Interface - manifest mf.Manifest -} - -func (oe openshiftExtension) Transformers(comp v1alpha1.TektonComponent) []mf.Transformer { - return []mf.Transformer{ - UpdateDbDeployment(), - injectPostgresUpgradeSupport(), - openshiftCommon.RemoveRunAsUser(), - openshiftCommon.RemoveRunAsUserForJob(), - openshiftCommon.RemoveFsGroupForDeployment(), - openshiftCommon.RemoveFsGroupForJob(), - } -} - -func (oe openshiftExtension) PreReconcile(ctx context.Context, tc v1alpha1.TektonComponent) error { - th := tc.(*v1alpha1.TektonHub) - logger := logging.FromContext(ctx) - targetNs := th.Spec.GetTargetNamespace() - hubDir := filepath.Join(common.ComponentDir(th), common.TargetVersion(th), tektonHubAPIResourceKey) - manifest := oe.manifest.Append() - - if err := common.AppendManifest(&manifest, hubDir); err != nil { - return err - } - - // Fetch and append the postgresql config map which has postgresupgrade wrapper script - postgresqlCMDir := filepath.Join(common.ComponentBaseDir(), postgreSQLConfigMapDirectory) - postgresqlManifest := oe.manifest.Append() - if err := common.AppendManifest(&postgresqlManifest, postgresqlCMDir); err != nil { - return err - } - - // Transform and apply the postgresql ConfigMap - postgresqlManifest, err := postgresqlManifest.Transform( - mf.InjectOwner(th), - mf.InjectNamespace(targetNs), - ) - if err != nil { - logger.Error("failed to transform postgresql configmap manifest") - return err - } - if err := postgresqlManifest.Apply(); err != nil { - logger.Error("failed to apply postgresql configmap manifest") - return err - } - - apiRouteManifest := manifest.Filter(mf.ByKind("Route")) - apiRouteManifest, err = apiRouteManifest.Transform( - mf.InjectOwner(th), - mf.InjectNamespace(targetNs), - ) - if err != nil { - logger.Error("failed to transform manifest") - return err - } - if err := apiRouteManifest.Apply(); err != nil { - return err - } - - // Get the host of API route - apiRoute, err := getRouteHost(&apiRouteManifest, api) - if err != nil { - return err - } - th.Status.SetApiRoute(fmt.Sprintf("https://%s", apiRoute)) - - // Set Auth Url in Tekton Hub Status - if err := oe.SetAuthBaseURL(ctx, th, apiRouteManifest); err != nil { - return err - } - - // Create UI route based on the value of ui i.e. false/true - uiHubDir := filepath.Join(common.ComponentDir(th), common.TargetVersion(th), tektonHubUiResourceKey) - uiManifest := oe.manifest.Append() - - if err := common.AppendManifest(&uiManifest, uiHubDir); err != nil { - return err - } - - uiRouteManifest := uiManifest.Filter(mf.ByKind("Route")) - uiRouteManifest, err = uiRouteManifest.Transform( - mf.InjectOwner(th), - mf.InjectNamespace(targetNs), - ) - if err != nil { - logger.Error("failed to transform manifest") - return err - } - if err := uiRouteManifest.Apply(); err != nil { - return err - } - - uiRoute, err := getRouteHost(&uiRouteManifest, ui) - if err != nil { - return err - } - - th.Status.SetUiRoute(fmt.Sprintf("https://%s", uiRoute)) - - return nil -} - -func (oe openshiftExtension) PostReconcile(ctx context.Context, tc v1alpha1.TektonComponent) error { - th := tc.(*v1alpha1.TektonHub) - consoleCLILS := metav1.LabelSelector{ - MatchLabels: map[string]string{ - v1alpha1.InstallerSetType: ConsoleHubLinkInstallerSet, - }, - } - - consoleHubLinkLabelSelector, err := common.LabelSelector(consoleCLILS) - if err != nil { - return err - } - - exist, err := checkIfInstallerSetExist(ctx, oe.operatorClientSet, common.TargetVersion(th), consoleHubLinkLabelSelector) - if err != nil { - return err - } - - if !exist { - hubConsoleLinkManifest := oe.manifest.Append() - if err := applyHubConsoleLinkManifest(&hubConsoleLinkManifest); err != nil { - return err - } - - if err := consoleLinkTransform(ctx, &hubConsoleLinkManifest, th.Status.GetUiRoute()); err != nil { - return err - } - - if err := createInstallerSet(ctx, oe.operatorClientSet, th, hubConsoleLinkManifest, - common.TargetVersion(th), ConsoleHubLinkInstallerSet, "console-link-hub"); err != nil { - return err - } - } - - return nil -} - -func checkIfInstallerSetExist(ctx context.Context, oc clientset.Interface, relVersion string, - labelSelector string) (bool, error) { - - installerSets, err := oc.OperatorV1alpha1().TektonInstallerSets(). - List(ctx, metav1.ListOptions{ - LabelSelector: labelSelector, - }) - if err != nil { - return false, err - } - - if len(installerSets.Items) == 0 { - return false, nil - } - - if len(installerSets.Items) == 1 { - // if already created then check which version it is - version, ok := installerSets.Items[0].Labels[v1alpha1.ReleaseVersionKey] - if ok && version == relVersion { - // if installer set already exist and release version is same - // then ignore and move on - return true, nil - } - } - - // release version doesn't exist or is different from expected - // deleted existing InstallerSet and create a new one - // or there is more than one installerset (unexpected) - if err = oc.OperatorV1alpha1().TektonInstallerSets(). - DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{ - LabelSelector: labelSelector, - }); err != nil { - return false, err - } - - return false, v1alpha1.RECONCILE_AGAIN_ERR -} - -func createInstallerSet(ctx context.Context, oc clientset.Interface, ta *v1alpha1.TektonHub, - manifest mf.Manifest, releaseVersion, component, installerSetPrefix string) error { - - is := makeInstallerSet(ta, manifest, installerSetPrefix, releaseVersion, component) - - if _, err := oc.OperatorV1alpha1().TektonInstallerSets(). - Create(ctx, is, metav1.CreateOptions{}); err != nil { - return err - } - - return nil -} - -func makeInstallerSet(ta *v1alpha1.TektonHub, manifest mf.Manifest, prefix, releaseVersion, component string) *v1alpha1.TektonInstallerSet { - ownerRef := *metav1.NewControllerRef(ta, ta.GetGroupVersionKind()) - labels := map[string]string{ - v1alpha1.CreatedByKey: CreatedByValue, - v1alpha1.InstallerSetType: component, - v1alpha1.ReleaseVersionKey: releaseVersion, - } - namePrefix := fmt.Sprintf("%s-", prefix) - - return &v1alpha1.TektonInstallerSet{ - ObjectMeta: metav1.ObjectMeta{ - GenerateName: namePrefix, - Labels: labels, - Annotations: map[string]string{ - v1alpha1.TargetNamespaceKey: ta.Spec.TargetNamespace, - }, - OwnerReferences: []metav1.OwnerReference{ownerRef}, - }, - Spec: v1alpha1.TektonInstallerSetSpec{ - Manifests: manifest.Resources(), - }, - } -} - -func applyHubConsoleLinkManifest(manifest *mf.Manifest) error { - koDataDir := os.Getenv(common.KoEnvKey) - location := filepath.Join(koDataDir, "openshift", "tekton-hub") - return common.AppendManifest(manifest, location) -} - -func consoleLinkTransform(ctx context.Context, manifest *mf.Manifest, baseURL string) error { - if baseURL == "" { - return fmt.Errorf("route url should not be empty") - } - logger := logging.FromContext(ctx) - logger.Debug("Transforming manifest") - - transformers := []mf.Transformer{ - replaceURLConsoleLink(baseURL), - } - - transformManifest, err := manifest.Transform(transformers...) - if err != nil { - return err - } - - *manifest = transformManifest - return nil -} - -func replaceURLConsoleLink(baseURL string) mf.Transformer { - return func(u *unstructured.Unstructured) error { - if u.GetKind() != "ConsoleLink" { - return nil - } - cl := &console.ConsoleLink{} - err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, cl) - if err != nil { - return err - } - - cl.Spec.Href = baseURL - - unstrObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(cl) - if err != nil { - return err - } - u.SetUnstructuredContent(unstrObj) - return nil - } -} - -func (oe openshiftExtension) Finalize(context.Context, v1alpha1.TektonComponent) error { - return nil -} - -func (oe openshiftExtension) GetPlatformData() string { - return "" -} - -// Get the Host value of the Route created -func getRouteHost(manifest *mf.Manifest, routeName string) (string, error) { - var hostUrl string - for _, r := range manifest.Filter(mf.ByKind("Route")).Resources() { - u, err := manifest.Client.Get(&r) - if err != nil { - return "", err - } - if u.GetName() == routeName { - route := &routev1.Route{} - if err := scheme.Scheme.Convert(u, route, nil); err != nil { - return "", err - } - hostUrl = route.Spec.Host - } - } - return hostUrl, nil -} - -func UpdateDbDeployment() mf.Transformer { - return func(u *unstructured.Unstructured) error { - if u.GetKind() != "Deployment" { - return nil - } - - d := &appsv1.Deployment{} - err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, d) - if err != nil { - return err - } - - if d.Name == db { - env := d.Spec.Template.Spec.Containers[0].Env - - replaceEnv(env) - - d.Spec.Template.Spec.Containers[0].Env = env - - mountPath := "/var/lib/pgsql/data" - d.Spec.Template.Spec.Containers[0].VolumeMounts[0].MountPath = mountPath - - replaceProbeCommand(d.Spec.Template.Spec.Containers[0].ReadinessProbe.Exec.Command) - replaceProbeCommand(d.Spec.Template.Spec.Containers[0].LivenessProbe.Exec.Command) - - unstrObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(d) - if err != nil { - return err - } - u.SetUnstructuredContent(unstrObj) - - return nil - } - - return nil - } -} - -func (oe openshiftExtension) SetAuthBaseURL(ctx context.Context, th *v1alpha1.TektonHub, apiRouteManifest mf.Manifest) error { - // Get the api secret - secret, err := oe.kubeClientSet.CoreV1().Secrets(th.Spec.GetTargetNamespace()).Get(ctx, "tekton-hub-api", metav1.GetOptions{}) - if err != nil { - if apierrors.IsNotFound(err) { - th.Status.SetAuthRoute("") - } else { - return err - } - } - - if len(secret.Data["GH_CLIENT_ID"]) != 0 || len(secret.Data["GL_CLIENT_ID"]) != 0 || len(secret.Data["BB_CLIENT_ID"]) != 0 { - // Get the host of Auth route - authRoute, err := getRouteHost(&apiRouteManifest, "tekton-hub-auth") - if err != nil { - return err - } - th.Status.SetAuthRoute(fmt.Sprintf("https://%s", authRoute)) - - if secret.Data == nil || string(secret.Data["AUTH_BASE_URL"]) != th.Status.AuthRouteUrl { - - if secret.StringData == nil { - secret.StringData = make(map[string]string) - } - - secret.StringData["AUTH_BASE_URL"] = th.Status.AuthRouteUrl - - _, err = oe.kubeClientSet.CoreV1().Secrets(th.Spec.GetTargetNamespace()).Update(ctx, secret, metav1.UpdateOptions{}) - if err != nil { - return err - } - } - } else { - th.Status.SetAuthRoute("") - } - - return nil -} - -func replaceProbeCommand(data []string) { - if strings.Contains(data[2], "POSTGRES_USER") { - data[2] = strings.ReplaceAll(data[2], "POSTGRES_USER", "POSTGRESQL_USER") - } - if strings.Contains(data[2], "POSTGRES_DB") { - data[2] = strings.ReplaceAll(data[2], "POSTGRES_DB", "POSTGRESQL_DATABASE") - } -} - -func replaceEnv(envs []corev1.EnvVar) { - for i, e := range envs { - _, ok := replaceVal[e.Name] - if ok { - envs[i].Name = replaceVal[e.Name] - } - // Update PGDATA value to match the new mount path - if e.Name == "PGDATA" { - envs[i].Value = "/var/lib/pgsql/data" - } - } -} - -// injectPostgresUpgradeSupport modifies the postgres container to support automatic -// upgrade from PostgreSQL 13 to PostgreSQL 15. The wrapper script checks the PG_VERSION -// file in the data directory and sets POSTGRESQL_UPGRADE=copy if an upgrade is needed, -// triggering the sclorg container's built-in upgrade mechanism. -func injectPostgresUpgradeSupport() mf.Transformer { - return func(u *unstructured.Unstructured) error { - // Only apply this transformer to the tekton-hub-db Deployment - if u.GetKind() != "Deployment" || u.GetName() != "tekton-hub-db" { - return nil - } - - d := &appsv1.Deployment{} - err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, d) - if err != nil { - return err - } - - // Modify the main postgres container - for i, container := range d.Spec.Template.Spec.Containers { - if container.Name == "tekton-hub-db" { - // Add volume mount for upgrade scripts - vmFound := false - for _, vm := range container.VolumeMounts { - if vm.Name == "upgrade-scripts" { - vmFound = true - break - } - } - if !vmFound { - d.Spec.Template.Spec.Containers[i].VolumeMounts = append( - container.VolumeMounts, - corev1.VolumeMount{ - Name: "upgrade-scripts", - MountPath: "/upgrade-scripts", - }, - ) - } - - // Change the command to use the wrapper script - d.Spec.Template.Spec.Containers[i].Command = []string{ - "/bin/bash", - "/upgrade-scripts/postgres-wrapper.sh", - } - } - } - - // Add volume for upgrade scripts ConfigMap - scriptsVolume := corev1.Volume{ - Name: "upgrade-scripts", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "tekton-hub-postgres-upgrade-scripts", - }, - DefaultMode: func() *int32 { - mode := int32(0755) - return &mode - }(), - }, - }, - } - - volumeFound := false - for i, vol := range d.Spec.Template.Spec.Volumes { - if vol.Name == "upgrade-scripts" { - d.Spec.Template.Spec.Volumes[i] = scriptsVolume - volumeFound = true - break - } - } - if !volumeFound { - d.Spec.Template.Spec.Volumes = append( - d.Spec.Template.Spec.Volumes, - scriptsVolume, - ) - } - - // Convert back to unstructured - uObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(d) - if err != nil { - return err - } - u.SetUnstructuredContent(uObj) - return nil - } -} diff --git a/pkg/reconciler/openshift/tektonhub/extension_test.go b/pkg/reconciler/openshift/tektonhub/extension_test.go deleted file mode 100644 index 940ebb6d3b..0000000000 --- a/pkg/reconciler/openshift/tektonhub/extension_test.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2022 The Tekton 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 tektonhub - -import ( - "path" - "strings" - "testing" - - mf "github.com/manifestival/manifestival" - "gotest.tools/v3/assert" - appsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -func TestUpdateDbDeployment(t *testing.T) { - testData := path.Join("testdata", "update-db-deployment.yaml") - - manifest, err := mf.ManifestFrom(mf.Recursive(testData)) - assert.NilError(t, err) - - newManifest, err := manifest.Transform(UpdateDbDeployment()) - assert.NilError(t, err) - - d := &appsv1.Deployment{} - err = runtime.DefaultUnstructuredConverter.FromUnstructured(newManifest.Resources()[0].Object, d) - assert.NilError(t, err) - - env := d.Spec.Template.Spec.Containers[0].Env - assert.Equal(t, env[0].Name, "POSTGRESQL_DATABASE") - - // Verify PGDATA environment variable value is updated - var pgdataValue string - for _, e := range env { - if e.Name == "PGDATA" { - pgdataValue = e.Value - break - } - } - assert.Equal(t, pgdataValue, "/var/lib/pgsql/data") - - mountPath := d.Spec.Template.Spec.Containers[0].VolumeMounts[0].MountPath - assert.Equal(t, mountPath, "/var/lib/pgsql/data") - - cmd := d.Spec.Template.Spec.Containers[0].ReadinessProbe.Exec.Command - assert.Equal(t, strings.Contains(cmd[2], "POSTGRESQL_USER"), true) -} - -func TestInjectPostgresUpgradeSupport(t *testing.T) { - testData := path.Join("testdata", "update-db-deployment.yaml") - - manifest, err := mf.ManifestFrom(mf.Recursive(testData)) - assert.NilError(t, err) - - newManifest, err := manifest.Transform(injectPostgresUpgradeSupport()) - assert.NilError(t, err) - - d := &appsv1.Deployment{} - err = runtime.DefaultUnstructuredConverter.FromUnstructured(newManifest.Resources()[0].Object, d) - assert.NilError(t, err) - - // Verify command is set to use the wrapper script - command := d.Spec.Template.Spec.Containers[0].Command - assert.Equal(t, len(command), 2) - assert.Equal(t, command[0], "/bin/bash") - assert.Equal(t, command[1], "/upgrade-scripts/postgres-wrapper.sh") - - // Verify volume mount for upgrade scripts is added - volumeMounts := d.Spec.Template.Spec.Containers[0].VolumeMounts - var upgradeScriptsMountFound bool - for _, vm := range volumeMounts { - if vm.Name == "upgrade-scripts" { - upgradeScriptsMountFound = true - assert.Equal(t, vm.MountPath, "/upgrade-scripts") - break - } - } - assert.Equal(t, upgradeScriptsMountFound, true) - - // Verify volume for upgrade scripts ConfigMap is added - volumes := d.Spec.Template.Spec.Volumes - var upgradeScriptsVolumeFound bool - for _, vol := range volumes { - if vol.Name == "upgrade-scripts" { - upgradeScriptsVolumeFound = true - assert.Equal(t, vol.ConfigMap.Name, "tekton-hub-postgres-upgrade-scripts") - assert.Equal(t, *vol.ConfigMap.DefaultMode, int32(0755)) - break - } - } - assert.Equal(t, upgradeScriptsVolumeFound, true) -} diff --git a/pkg/reconciler/openshift/tektonhub/testdata/update-db-deployment.yaml b/pkg/reconciler/openshift/tektonhub/testdata/update-db-deployment.yaml deleted file mode 100644 index edb5045623..0000000000 --- a/pkg/reconciler/openshift/tektonhub/testdata/update-db-deployment.yaml +++ /dev/null @@ -1,75 +0,0 @@ -# Copyright © 2022 The Tekton 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. - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: tekton-hub-db - labels: - app: tekton-hub-db -spec: - replicas: 1 - selector: - matchLabels: - app: tekton-hub-db - template: - metadata: - labels: - app: tekton-hub-db - spec: - containers: - - name: tekton-hub-db - image: postgres:13@sha256:7cc1c1a6a9df06df9e775eccdd77e45a868cb197e8e0981e23a2a814aaf56906 - imagePullPolicy: IfNotPresent - ports: - - containerPort: 5432 - protocol: TCP - env: - - name: POSTGRES_DB - valueFrom: - secretKeyRef: - name: tekton-hub-db - key: POSTGRES_DB - - name: POSTGRES_USER - valueFrom: - secretKeyRef: - name: tekton-hub-db - key: POSTGRES_USER - - name: POSTGRES_PASSWORD - valueFrom: - secretKeyRef: - name: tekton-hub-db - key: POSTGRES_PASSWORD - - name: PGDATA - value: /var/lib/postgresql/data/pgdata - volumeMounts: - - name: tekton-hub-db - mountPath: /var/lib/postgresql/data - readinessProbe: - exec: - command: [bash, -c, "psql -w -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'SELECT 1'"] - initialDelaySeconds: 15 - timeoutSeconds: 2 - periodSeconds: 15 - livenessProbe: - exec: - command: [bash, -c, "psql -w -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'SELECT 1'"] - initialDelaySeconds: 45 - timeoutSeconds: 2 - periodSeconds: 15 - volumes: - - name: tekton-hub-db - persistentVolumeClaim: - claimName: tekton-hub-db - restartPolicy: Always diff --git a/pkg/reconciler/platform/const.go b/pkg/reconciler/platform/const.go index 4dcaeb625c..30b1d732e5 100644 --- a/pkg/reconciler/platform/const.go +++ b/pkg/reconciler/platform/const.go @@ -22,7 +22,6 @@ const ( ControllerTektonPipeline ControllerName = "tektonpipeline" ControllerTektonTrigger ControllerName = "tektontrigger" ControllerTektonInstallerSet ControllerName = "tektoninstallerset" - ControllerTektonHub ControllerName = "tektonhub" ControllerTektonChain ControllerName = "tektonchain" ControllerTektonResult ControllerName = "tektonresult" ControllerManualApprovalGate ControllerName = "manualapprovalgate" diff --git a/pkg/reconciler/proxy/controller.go b/pkg/reconciler/proxy/controller.go index 78641eff02..3d5f4017be 100644 --- a/pkg/reconciler/proxy/controller.go +++ b/pkg/reconciler/proxy/controller.go @@ -96,7 +96,6 @@ func NewAdmissionController( return c } - func NewProxyDefaultingAdmissionController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { return NewAdmissionController(ctx, diff --git a/pkg/webhook/webhook.go b/pkg/webhook/webhook.go index 818f2c5167..e5944a9a55 100644 --- a/pkg/webhook/webhook.go +++ b/pkg/webhook/webhook.go @@ -34,7 +34,6 @@ var types = map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ v1alpha1.SchemeGroupVersion.WithKind(v1alpha1.KindTektonConfig): &v1alpha1.TektonConfig{}, v1alpha1.SchemeGroupVersion.WithKind(v1alpha1.KindTektonPipeline): &v1alpha1.TektonPipeline{}, v1alpha1.SchemeGroupVersion.WithKind(v1alpha1.KindTektonTrigger): &v1alpha1.TektonTrigger{}, - v1alpha1.SchemeGroupVersion.WithKind(v1alpha1.KindTektonHub): &v1alpha1.TektonHub{}, v1alpha1.SchemeGroupVersion.WithKind(v1alpha1.KindTektonResult): &v1alpha1.TektonResult{}, v1alpha1.SchemeGroupVersion.WithKind(v1alpha1.KindTektonChain): &v1alpha1.TektonChain{}, v1alpha1.SchemeGroupVersion.WithKind(v1alpha1.KindTektonPruner): &v1alpha1.TektonPruner{}, diff --git a/test/e2e/common/05_tektonhubdeployment_test.go b/test/e2e/common/05_tektonhubdeployment_test.go deleted file mode 100644 index f77a209c1b..0000000000 --- a/test/e2e/common/05_tektonhubdeployment_test.go +++ /dev/null @@ -1,413 +0,0 @@ -//go:build e2e -// +build e2e - -/* -Copyright 2022 The Tekton 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 common - -import ( - "context" - "fmt" - "strings" - "testing" - "time" - - mfc "github.com/manifestival/client-go-client" - mf "github.com/manifestival/manifestival" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - "github.com/tektoncd/operator/pkg/reconciler/common" - "github.com/tektoncd/operator/test/client" - "github.com/tektoncd/operator/test/resources" - "github.com/tektoncd/operator/test/utils" - "go.uber.org/zap" - apierrs "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/util/wait" -) - -const ( - hubExternalDatabaseYaml = "testdata/hub_externaldb.yaml" - hubExternalDatabaseSecretYaml = "testdata/hub_externaldb_secret.yaml" - hubDatabaseExternalSecretName = "tekton-hub-db" - hubExternalDatabaseNamespace = "hub-external-db" - hubDatabaseDeploymentName = "tekton-hub-db" -) - -type TektonHubTestSuite struct { - suite.Suite - resourceNames utils.ResourceNames - clients *utils.Clients - deployments []string - pvcs []string - dbMigrationJobName string - interval time.Duration - timeout time.Duration - logger *zap.SugaredLogger -} - -func TestTektonHubTestSuite(t *testing.T) { - hs := NewTektonHubTestSuite(t) - - // actual tests starts here - suite.Run(t, hs) -} - -// if other suites want to execute a method on this suite, -// can create a instance by calling this function -// also used internally -func NewTektonHubTestSuite(t *testing.T) *TektonHubTestSuite { - hs := TektonHubTestSuite{ - resourceNames: utils.GetResourceNames(), - deployments: []string{ - hubDatabaseDeploymentName, - "tekton-hub-api", - "tekton-hub-ui", - }, - pvcs: []string{ - "tekton-hub-api", - "tekton-hub-db", - }, - dbMigrationJobName: "tekton-hub-db-migration", - interval: 5 * time.Second, - timeout: 5 * time.Minute, - logger: utils.Logger(), - } - - // setup clients - hs.clients = client.Setup(t, hs.resourceNames.TargetNamespace) - - return &hs -} - -// before suite -func (s *TektonHubTestSuite) SetupSuite() { - resources.PrintClusterInformation(s.logger, s.resourceNames) - - // reset the tekton config into default state - s.logger.Debug("resetting TektonConfig to it's default state") - tcSuite := NewTestTektonConfigTestSuite(s.T()) - tcSuite.recreateOperatorPod() - tcSuite.resetToDefaults() -} - -// after suite -func (s *TektonHubTestSuite) TearDownSuite() { - // removes tekton hub CR and external database - s.undeploy("") - s.undeployExternalDatabase() -} - -// before each tests -// clean up existing hub cr and external database -func (s *TektonHubTestSuite) SetupTest() { - t := s.T() - s.logger.Debug("removing the tekton hub cr if any") - s.undeploy("") - s.undeployExternalDatabase() - err := resources.CreateNamespace(s.clients.KubeClient, s.resourceNames.TargetNamespace) - require.NoError(t, err, "create namespace: %s", s.resourceNames.TargetNamespace) - s.logger.Debug("test environment ready. starting the actual test") -} - -// after each tests -// if there is a failures, execute debug commands -func (s *TektonHubTestSuite) TearDownTest() { - t := s.T() - if t.Failed() { - s.logger.Infow("test failed, executing debug commands", "testName", t.Name()) - resources.ExecuteDebugCommands(s.logger, s.resourceNames) - - // remove tektonHub and external database, if any - s.undeployExternalDatabase() - s.undeploy("") - } -} - -// actual tests -// TODO: add tests to verify data from UI and API endpoint - -// deploys default TektonHub CR and verify resources -func (s *TektonHubTestSuite) Test01_DeployDefault() { - s.deploy("", s.resourceNames.TektonHub) - s.verifyResources("") -} - -// deploys TektonHub CR external database -func (s *TektonHubTestSuite) Test02_DeployWithExternalDatabase() { - // deploy external database - s.deployExternalDatabase() - - // deploy tektonHub - s.deploy(hubDatabaseExternalSecretName, s.resourceNames.TektonHub) - - // verify resources - s.verifyResources(hubExternalDatabaseNamespace) -} - -// deploys default TektonHub CR and updates the CR to external database -func (s *TektonHubTestSuite) Test03_DeployDefaultThenUpdateToExternalDatabase() { - t := s.T() - pollInterval := s.interval - timeout := s.timeout - - // deploy tektonHub - s.deploy("", s.resourceNames.TektonHub) - s.logger.Debug("deployed hub with self provisioned database") - - // verify resources - s.verifyResources("") - - s.logger.Debug("deploying hub with external database") - // deploy external database - s.deployExternalDatabase() - - // update hub cr - hubCR, err := s.clients.TektonHub().Get(context.TODO(), s.resourceNames.TektonHub, metav1.GetOptions{}) - require.NoError(t, err) - hubCR.Spec.Db.DbSecretName = hubDatabaseExternalSecretName - - // update hub cr - _, err = s.clients.TektonHub().Update(context.Background(), hubCR, metav1.UpdateOptions{}) - require.NoError(t, err) - - // verify internal database removed - err = resources.WaitForDeploymentDeletion(s.clients.KubeClient, hubDatabaseDeploymentName, s.resourceNames.TargetNamespace, pollInterval, timeout) - require.NoError(t, err) - - // verify hub is updated and running - s.verifyResources(hubExternalDatabaseNamespace) -} - -// deploys the hub with invalid name -// operator accepts only TektonHub name with "hub" -func (s *TektonHubTestSuite) Test04_DeployWithInvalidHubName() { - t := s.T() - - // random hub name - hubName := common.SimpleNameGenerator.RestrictLengthWithRandomSuffix("custom-hub") - - // deploy tektonHub - s.deploy("", hubName) - - // remove this hub cr on exit - defer func() { - err := s.clients.TektonHub().Delete(context.TODO(), hubName, metav1.DeleteOptions{}) - if err != nil { - s.logger.Errorw("error on cleaning the hub cr", "name", hubName) - } - }() - - expectedMessage := fmt.Sprintf("Resource ignored, Expected Name: %s, Got Name: %s", s.resourceNames.TektonHub, hubName) - // wait for tektonHub status for 30 seconds - verifyStatus := func() (bool, error) { - th, err := s.clients.TektonHub().Get(context.TODO(), hubName, metav1.GetOptions{}) - if err != nil { - return false, err - } - if th.Status.IsReady() { - return false, fmt.Errorf("TektonHub is in ready status. name:%s", hubName) - } - for _, condition := range th.Status.Conditions { - if condition.Type == "Ready" { - s.logger.Debugw("ready status", "condition", condition) - return strings.Contains(condition.Message, expectedMessage), nil - } - } - return false, nil - } - - err := wait.PollImmediate(s.interval, 30*time.Second, verifyStatus) - require.NoError(t, err) -} - -// helper functions - -func (s *TektonHubTestSuite) deploy(databaseSecretName, hubName string) { - t := s.T() - - if hubName == "" { - hubName = s.resourceNames.TektonHub - } - - hubSpec := &v1alpha1.TektonHub{ - ObjectMeta: metav1.ObjectMeta{ - Name: hubName, - }, - Spec: v1alpha1.TektonHubSpec{ - CommonSpec: v1alpha1.CommonSpec{ - TargetNamespace: s.resourceNames.TargetNamespace, - }, - }, - } - - if databaseSecretName != "" { - hubSpec.Spec.Db.DbSecretName = databaseSecretName - } - - // create a TektonHub CR - _, err := resources.EnsureTektonHubExists(s.clients.TektonHub(), hubSpec) - require.NoError(t, err, "TektonHub %q failed to create: %v", hubSpec.GetName(), err) -} - -func (s *TektonHubTestSuite) verifyResources(databaseNamespace string) { - t := s.T() - interval := s.interval - timeout := s.timeout - - // assert tekton hub ready status - resources.AssertTektonHubCRReadyStatus(t, s.clients, s.resourceNames) - - // verify deployments are ready - for _, deploymentName := range s.deployments { - namespace := s.resourceNames.TargetNamespace - if deploymentName == hubDatabaseDeploymentName && databaseNamespace != "" { - namespace = databaseNamespace - } - err := resources.WaitForDeploymentReady(s.clients.KubeClient, deploymentName, namespace, interval, timeout) - require.NoError(t, err, "wait for a deployment ready status, deployment:%s, namespace:%s", deploymentName, namespace) - } - - // verify migration job has completed successfully - err := resources.WaitForJobCompletion(s.clients.KubeClient, s.dbMigrationJobName, s.resourceNames.TargetNamespace, interval, timeout) - require.NoError(t, err, "wait for database migration job completion") -} - -func (s *TektonHubTestSuite) undeploy(databaseNamespace string) { - t := s.T() - pollInterval := s.interval - timeout := s.timeout - - // delete the hub cr - resources.TektonHubCRDelete(t, s.clients, s.resourceNames) - - // verify deployments are removed - for _, deploymentName := range s.deployments { - namespace := s.resourceNames.TargetNamespace - if deploymentName == hubDatabaseDeploymentName && databaseNamespace != "" { - // no need to verify external database removal - continue - } - err := resources.WaitForDeploymentDeletion(s.clients.KubeClient, deploymentName, namespace, pollInterval, timeout) - require.NoError(t, err) - } - // verify pvcs are removed - for _, pvcName := range s.pvcs { - namespace := s.resourceNames.TargetNamespace - if databaseNamespace != "" { - // no need to verify external database removal - continue - } - err := resources.WaitForPVCDeletion(s.clients.KubeClient, pvcName, namespace, pollInterval, timeout) - require.NoError(t, err) - } - // verify migration job is removed - err := resources.WaitForJobDeletion(s.clients.KubeClient, s.dbMigrationJobName, s.resourceNames.TargetNamespace, pollInterval, timeout) - require.NoError(t, err) -} - -func (s *TektonHubTestSuite) deployExternalDatabase() { - t := s.T() - pollInterval := s.interval - timeout := s.timeout - - // install db in different namespace and wait for deployment ready - mfClient, err := mfc.NewUnsafeDynamicClient(s.clients.Dynamic) - require.NoError(t, err) - - manifest, err := mf.NewManifest(hubExternalDatabaseYaml, mf.UseClient(mfClient)) - require.NoError(t, err) - - // apply transformers - updatedManifest, err := manifest.Transform(s.externalDatabaseTransformer) - require.NoError(t, err) - manifest = updatedManifest - - // apply manifests - err = manifest.Apply() - require.NoError(t, err) - - s.logger.Debugw("wait for external database deployment becomes ready", - "namespace", hubExternalDatabaseNamespace, - "deploymentName", hubDatabaseDeploymentName, - ) - err = resources.WaitForDeploymentReady(s.clients.KubeClient, hubDatabaseDeploymentName, hubExternalDatabaseNamespace, pollInterval, timeout) - require.NoError(t, err, "external database deployment is not ready") - s.logger.Debug("external database deployment is ready") - - // create secret to namespace where hub api will be deployed - // remove the existing secret, if any - err = s.clients.KubeClient.CoreV1().Secrets(s.resourceNames.TargetNamespace).Delete(context.TODO(), hubDatabaseExternalSecretName, metav1.DeleteOptions{}) - if err != nil && !apierrs.IsNotFound(err) { - require.NoError(t, err) - } - // create secret - secManifest, err := mf.NewManifest(hubExternalDatabaseSecretYaml, mf.UseClient(mfClient)) - require.NoError(t, err) - - // apply transformers - updatedManifest, err = secManifest.Transform(s.externalDatabaseTransformer) - require.NoError(t, err) - secManifest = updatedManifest - - // apply manifests - err = secManifest.Apply() - require.NoError(t, err) -} - -func (s *TektonHubTestSuite) undeployExternalDatabase() { - t := s.T() - pollInterval := s.interval - timeout := 3 * time.Minute - - err := resources.DeleteNamespaceAndWait(s.clients.KubeClient, hubExternalDatabaseNamespace, pollInterval, timeout) - require.NoError(t, err) - - // remove secret from pipelines namespace - err = s.clients.KubeClient.CoreV1().Secrets(s.resourceNames.TargetNamespace).Delete(context.TODO(), hubDatabaseExternalSecretName, metav1.DeleteOptions{}) - if err != nil && !apierrs.IsNotFound(err) { - require.NoError(t, err) - } -} - -// in openshift can not run with fsGroup: 65532 and runAsUser: 65532 -// remove those fields from yaml configuration and continue -func (s *TektonHubTestSuite) externalDatabaseTransformer(u *unstructured.Unstructured) error { - if utils.IsOpenShift() { - if u.GetKind() == "Deployment" && u.GetName() == "tekton-hub-db" { - // removes, spec.template.spec.securityContext.fsGroup: 65532 - unstructured.RemoveNestedField(u.Object, "spec", "template", "spec", "securityContext", "fsGroup") - containers, _, err := unstructured.NestedSlice(u.Object, "spec", "template", "spec", "containers") - if err != nil { - return err - } - for _, c := range containers { - // removes, spec.template.spec.containers[*].securityContext.runAsUser: 65532 - unstructured.RemoveNestedField(c.(map[string]interface{}), "securityContext", "runAsUser") - } - // update containers - if err := unstructured.SetNestedField(u.Object, containers, "spec", "template", "spec", "containers"); err != nil { - return err - } - } else if utils.IsOpenShift() && u.GetKind() == "Secret" && u.GetNamespace() == "tekton-pipelines" { - u.SetNamespace(s.resourceNames.TargetNamespace) - } - } - return nil -} diff --git a/test/e2e/common/testdata/hub_externaldb.yaml b/test/e2e/common/testdata/hub_externaldb.yaml deleted file mode 100644 index 6c000113b4..0000000000 --- a/test/e2e/common/testdata/hub_externaldb.yaml +++ /dev/null @@ -1,153 +0,0 @@ -# Copyright © 2022 The Tekton 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. - ---- -apiVersion: v1 -kind: Namespace -metadata: - name: hub-external-db - labels: - pod-security.kubernetes.io/enforce: restricted -spec: {} - ---- -apiVersion: v1 -kind: Secret -metadata: - namespace: hub-external-db - name: tekton-hub-db - labels: - app: tekton-hub-db -type: Opaque -stringData: - POSTGRES_HOST: tekton-hub-db - POSTGRES_DB: hub - POSTGRES_USER: postgres - POSTGRES_PASSWORD: postgres - POSTGRES_PORT: '5432' - ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - namespace: hub-external-db - name: tekton-hub-db - labels: - app: tekton-hub-db -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 1Gi - ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - namespace: hub-external-db - name: tekton-hub-db - labels: - app: tekton-hub-db -spec: - replicas: 1 - selector: - matchLabels: - app: tekton-hub-db - template: - metadata: - labels: - app: tekton-hub-db - spec: - securityContext: - fsGroup: 65532 - runAsNonRoot: true - seccompProfile: - type: RuntimeDefault - containers: - - name: tekton-hub-db - image: postgres:13@sha256:7cc1c1a6a9df06df9e775eccdd77e45a868cb197e8e0981e23a2a814aaf56906 - resources: - requests: - cpu: 100m - memory: 100Mi - limits: - cpu: 500m - memory: 500Mi - imagePullPolicy: IfNotPresent - ports: - - containerPort: 5432 - protocol: TCP - securityContext: - allowPrivilegeEscalation: false - runAsUser: 65532 - capabilities: - drop: - - ALL - env: - - name: POSTGRES_DB - valueFrom: - secretKeyRef: - name: tekton-hub-db - key: POSTGRES_DB - - name: POSTGRES_USER - valueFrom: - secretKeyRef: - name: tekton-hub-db - key: POSTGRES_USER - - name: POSTGRES_PASSWORD - valueFrom: - secretKeyRef: - name: tekton-hub-db - key: POSTGRES_PASSWORD - - name: PGDATA - value: /var/lib/postgresql/data/pgdata - volumeMounts: - - name: tekton-hub-db - mountPath: /var/lib/postgresql/data - readinessProbe: - exec: - command: [bash, -c, "psql -w -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'SELECT 1'"] - initialDelaySeconds: 15 - timeoutSeconds: 2 - periodSeconds: 15 - livenessProbe: - exec: - command: [bash, -c, "psql -w -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'SELECT 1'"] - initialDelaySeconds: 45 - timeoutSeconds: 2 - periodSeconds: 15 - volumes: - - name: tekton-hub-db - persistentVolumeClaim: - claimName: tekton-hub-db - restartPolicy: Always - ---- -apiVersion: v1 -kind: Service -metadata: - namespace: hub-external-db - name: tekton-hub-db - labels: - app: tekton-hub-db -spec: - type: ClusterIP - selector: - app: tekton-hub-db - ports: - - name: postgresql - port: 5432 - protocol: TCP - targetPort: 5432 diff --git a/test/e2e/common/testdata/hub_externaldb_secret.yaml b/test/e2e/common/testdata/hub_externaldb_secret.yaml deleted file mode 100644 index 1ed13c3029..0000000000 --- a/test/e2e/common/testdata/hub_externaldb_secret.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright © 2022 The Tekton 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. - -apiVersion: v1 -kind: Secret -metadata: - namespace: tekton-pipelines - name: tekton-hub-db -type: Opaque -stringData: - POSTGRES_HOST: tekton-hub-db.hub-external-db.svc.cluster.local - POSTGRES_DB: hub - POSTGRES_USER: postgres - POSTGRES_PASSWORD: postgres - POSTGRES_PORT: '5432' diff --git a/test/resources/debug_commands.go b/test/resources/debug_commands.go index 82347751ce..3d587171d6 100644 --- a/test/resources/debug_commands.go +++ b/test/resources/debug_commands.go @@ -45,11 +45,9 @@ func getDebugCommands(resourceNames utils.ResourceNames) []string { "kubectl get tektonpipeline", "kubectl get tektonchain", "kubectl get tektontrigger", - "kubectl get tektonhub", "kubectl get tektondashboard", fmt.Sprintf("kubectl get %s --output=wide --namespace=%s", debugNamespacedResources, pipelinesNamespace), fmt.Sprintf("kubectl get %s --output=wide --namespace=%s", debugNamespacedResources, operatorNamespace), - fmt.Sprintf("kubectl get %s --output=wide --namespace=hub-external-db", debugNamespacedResources), } if utils.IsOpenShift() { openshiftCommands := []string{ diff --git a/test/resources/tektonconfigs.go b/test/resources/tektonconfigs.go index 339b9e31c9..56202fe4e3 100644 --- a/test/resources/tektonconfigs.go +++ b/test/resources/tektonconfigs.go @@ -204,10 +204,6 @@ func WaitForTektonConfigReady(client operatorV1alpha1.TektonConfigInterface, nam // 2. Even if the Pod has started properly, it may not have entered the // Reconcile logic yet, which could also lead to instability. // For example: - // In the testing logic of TektonHub, it immediately deletes the - // CR of TektonHub and then polls whether the CR has been cleaned up. - // At this point, the tekton-operator enters the Reconcile logic and - // automatically creates the CR of TektonHub again, causing the test to fail. return readyCount >= 3, nil } diff --git a/test/resources/tektonhub.go b/test/resources/tektonhub.go deleted file mode 100644 index a0a4c0b58b..0000000000 --- a/test/resources/tektonhub.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2022 The Tekton 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 resources - -import ( - "context" - "errors" - "fmt" - "path/filepath" - "runtime" - "testing" - - mfc "github.com/manifestival/client-go-client" - mf "github.com/manifestival/manifestival" - "github.com/tektoncd/operator/pkg/apis/operator/v1alpha1" - typedv1alpha1 "github.com/tektoncd/operator/pkg/client/clientset/versioned/typed/operator/v1alpha1" - "github.com/tektoncd/operator/test/utils" - apierrs "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "knative.dev/pkg/test/logging" -) - -func EnsureTektonHubExists(clients typedv1alpha1.TektonHubInterface, hub *v1alpha1.TektonHub) (*v1alpha1.TektonHub, error) { - // If this function is called by the upgrade tests, we only create the custom resource, if it does not exist. - ks, err := clients.Get(context.TODO(), hub.GetName(), metav1.GetOptions{}) - if apierrs.IsNotFound(err) { - return clients.Create(context.TODO(), hub, metav1.CreateOptions{}) - } - return ks, err -} - -// WaitForTektonHubState polls the status of the TektonHub called name -// from client every `interval` until `inState` returns `true` indicating it -// is done, returns an error or timeout. -func WaitForTektonHubState(clients typedv1alpha1.TektonHubInterface, name string, - inState func(s *v1alpha1.TektonHub, err error) (bool, error)) (*v1alpha1.TektonHub, error) { - span := logging.GetEmitableSpan(context.Background(), fmt.Sprintf("WaitForTektonHubState/%s/%s", name, "TektonHubIsReady")) - defer span.End() - - var lastState *v1alpha1.TektonHub - waitErr := wait.PollUntilContextTimeout(context.TODO(), utils.Interval, utils.Timeout, true, func(ctx context.Context) (bool, error) { - lastState, err := clients.Get(context.TODO(), name, metav1.GetOptions{}) - return inState(lastState, err) - }) - - if waitErr != nil { - return lastState, fmt.Errorf("tektonhub %s is not in desired state, got: %+v: %w", name, lastState, waitErr) - } - - return lastState, nil -} - -// IsTektonHubReady will check the status conditions of the TektonHub and return true if the TektonHub is ready. -func IsTektonHubReady(s *v1alpha1.TektonHub, err error) (bool, error) { - return s.Status.IsReady(), err -} - -// AssertTektonHubCRReadyStatus verifies if the TektonHub reaches the READY status. -func AssertTektonHubCRReadyStatus(t *testing.T, clients *utils.Clients, names utils.ResourceNames) { - if _, err := WaitForTektonHubState(clients.TektonHub(), names.TektonHub, IsTektonHubReady); err != nil { - t.Fatalf("TektonHubCR %q failed to get to the READY status: %v", names.TektonHub, err) - } -} - -// TektonHubCRDelete deletes tha TektonHub to see if all resources will be deleted -func TektonHubCRDelete(t *testing.T, clients *utils.Clients, crNames utils.ResourceNames) { - if err := clients.TektonHub().Delete(context.TODO(), crNames.TektonHub, metav1.DeleteOptions{}); err != nil { - if apierrs.IsNotFound(err) { - return - } - t.Fatalf("TektonHub %q failed to delete: %v", crNames.TektonHub, err) - } - err := wait.PollUntilContextTimeout(context.TODO(), utils.Interval, utils.Timeout, true, func(ctx context.Context) (bool, error) { - _, err := clients.TektonHub().Get(context.TODO(), crNames.TektonHub, metav1.GetOptions{}) - if apierrs.IsNotFound(err) { - return true, nil - } - return false, err - }) - if err != nil { - t.Fatal("Timed out waiting on TektonHub to delete", err) - } - _, b, _, ok := runtime.Caller(0) - if !ok { - t.Fatal("Failed to get caller information") - } - m, err := mfc.NewManifest(filepath.Join((filepath.Dir(b)+"/.."), "manifests/"), clients.Config) - if err != nil { - t.Fatal("Failed to load manifest", err) - } - if err := verifyNoTektonHubCR(clients); err != nil { - t.Fatal(err) - } - - // verify all but the CRD's and the Namespace are gone - for _, u := range m.Filter(mf.NoCRDs, mf.Not(mf.ByKind("Namespace"))).Resources() { - if _, err := m.Client.Get(&u); !apierrs.IsNotFound(err) { - t.Fatalf("The %s %s failed to be deleted: %v", u.GetKind(), u.GetName(), err) - } - } - // verify all the CRD's remain - for _, u := range m.Filter(mf.CRDs).Resources() { - if _, err := m.Client.Get(&u); apierrs.IsNotFound(err) { - t.Fatalf("The %s CRD was deleted", u.GetName()) - } - } -} - -func verifyNoTektonHubCR(clients *utils.Clients) error { - hub, err := clients.TektonHubAll().List(context.TODO(), metav1.ListOptions{}) - if err != nil { - return err - } - if len(hub.Items) > 0 { - return errors.New("Unable to verify cluster-scoped resources are deleted if any TektonHub exists") - } - return nil -} diff --git a/test/utils/clients.go b/test/utils/clients.go index 05d5bf54bc..3b13f9d79e 100644 --- a/test/utils/clients.go +++ b/test/utils/clients.go @@ -162,15 +162,6 @@ func (c *Clients) TektonChains() operatorv1alpha1.TektonChainInterface { func (c *Clients) TektonChainsAll() operatorv1alpha1.TektonChainInterface { return c.Operator.TektonChains() } - -func (c *Clients) TektonHub() operatorv1alpha1.TektonHubInterface { - return c.Operator.TektonHubs() -} - -func (c *Clients) TektonHubAll() operatorv1alpha1.TektonHubInterface { - return c.Operator.TektonHubs() -} - func (c *Clients) TektonPruner() operatorv1alpha1.TektonPrunerInterface { return c.Operator.TektonPruners() } diff --git a/test/utils/e2e_flags.go b/test/utils/e2e_flags.go index 7b6068b937..8c88afb46c 100644 --- a/test/utils/e2e_flags.go +++ b/test/utils/e2e_flags.go @@ -28,7 +28,6 @@ var ( TektonTriggerDeploymentLabel = labelString(v1alpha1.OperandTektoncdTriggers) TektonDashboardDeploymentLabel = labelString(v1alpha1.OperandTektoncdDashboard) TektonChainDeploymentLabel = labelString(v1alpha1.OperandTektoncdChains) - TektonHubDeploymentLabel = labelString(v1alpha1.OperandTektoncdHub) TektonResultsDeploymentLabel = labelString(v1alpha1.OperandTektoncdResults) ManualApprovalGateDeploymentLabel = labelString(v1alpha1.ManualApprovalGates) TektonPrunerDeploymentLabel = labelString(v1alpha1.TektonPrunerResourceName) diff --git a/test/utils/names.go b/test/utils/names.go index 39f490300d..4a3603228b 100644 --- a/test/utils/names.go +++ b/test/utils/names.go @@ -28,7 +28,6 @@ type ResourceNames struct { TektonPruner string TektonResult string TektonChain string - TektonHub string Namespace string TargetNamespace string OperatorPodSelectorLabel string @@ -46,7 +45,6 @@ func GetResourceNames() ResourceNames { TektonPruner: v1alpha1.TektonPrunerResourceName, TektonResult: v1alpha1.ResultResourceName, TektonChain: v1alpha1.ChainResourceName, - TektonHub: v1alpha1.HubResourceName, ManualApprovalGate: v1alpha1.ManualApprovalGates, OpenShiftPipelinesAsCode: v1alpha1.OpenShiftPipelinesAsCodeName, Namespace: "tekton-operator",