diff --git a/PROJECT b/PROJECT index ed17e0fdb..63ee7fe95 100644 --- a/PROJECT +++ b/PROJECT @@ -13,4 +13,13 @@ resources: kind: ClusterExtension path: github.com/operator-framework/operator-controller/api/v1alpha1 version: v1alpha1 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: operatorframework.io + group: olm + kind: Extension + path: github.com/operator-framework/operator-controller/api/v1alpha1 + version: v1alpha1 version: "3" diff --git a/api/v1alpha1/clusterextension_types.go b/api/v1alpha1/clusterextension_types.go index b763cb60a..bb49e5f0d 100644 --- a/api/v1alpha1/clusterextension_types.go +++ b/api/v1alpha1/clusterextension_types.go @@ -18,6 +18,7 @@ package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "github.com/operator-framework/operator-controller/internal/conditionsets" ) @@ -158,3 +159,17 @@ type ClusterExtensionList struct { func init() { SchemeBuilder.Register(&ClusterExtension{}, &ClusterExtensionList{}) } + +func (r *ClusterExtension) GetPackageSpec() *ExtensionSourcePackage { + p := &ExtensionSourcePackage{} + + p.Channel = r.Spec.Channel + p.Name = r.Spec.PackageName + p.Version = r.Spec.Version + + return p +} + +func (r *ClusterExtension) GetUID() types.UID { + return r.ObjectMeta.GetUID() +} diff --git a/api/v1alpha1/extension_types.go b/api/v1alpha1/extension_types.go new file mode 100644 index 000000000..9be080a39 --- /dev/null +++ b/api/v1alpha1/extension_types.go @@ -0,0 +1,134 @@ +/* +Copyright 2024. + +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" + "k8s.io/apimachinery/pkg/types" +) + +type ExtensionManagedState string + +const ( + // Peform reconcilliation of this Extension + ManagedStateActive ExtensionManagedState = "Active" + // Pause reconcilliation of this Extension + ManagedStatePaused ExtensionManagedState = "Paused" +) + +type ExtensionSourcePackage struct { + //+kubebuilder:validation:MaxLength:=48 + //+kubebuilder:validation:Pattern:=^[a-z0-9]+(-[a-z0-9]+)*$ + // name specifies the name of the name of the package + Name string `json:"name"` + + //+kubebuilder:validation:MaxLength:=64 + //+kubebuilder:validation:Pattern=`^(\s*(=||!=|>|<|>=|=>|<=|=<|~|~>|\^)\s*(v?(0|[1-9]\d*|[x|X|\*])(\.(0|[1-9]\d*|x|X|\*]))?(\.(0|[1-9]\d*|x|X|\*))?(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?)\s*)((?:\s+|,\s*|\s*\|\|\s*)(=||!=|>|<|>=|=>|<=|=<|~|~>|\^)\s*(v?(0|[1-9]\d*|x|X|\*])(\.(0|[1-9]\d*|x|X|\*))?(\.(0|[1-9]\d*|x|X|\*]))?(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?)\s*)*$` + //+kubebuilder:Optional + // Version is an optional semver constraint on the package version. If not specified, the latest version available of the package will be installed. + // If specified, the specific version of the package will be installed so long as it is available in any of the content sources available. + // Examples: 1.2.3, 1.0.0-alpha, 1.0.0-rc.1 + // + // For more information on semver, please see https://semver.org/ + // version constraint definition + Version string `json:"version,omitempty"` + + //+kubebuilder:validation:MaxLength:=48 + //+kubebuilder:validation:Pattern:=^[a-z0-9]+([\.-][a-z0-9]+)*$ + // channel constraint definition + Channel string `json:"channel,omitempty"` + + //+kubebuilder:validation:Enum:=Enforce;Ignore + //+kubebuilder:default:=Enforce + //+kubebuilder:Optional + // + // upgradeConstraintPolicy Defines the policy for how to handle upgrade constraints + UpgradeConstraintPolicy UpgradeConstraintPolicy `json:"upgradeConstraintPolicy,omitempty"` +} + +// ExtensionSource defines the source for this Extension, right now, only a package is supported. +type ExtensionSource struct { + // A source package defined by a name, version and/or channel + Package *ExtensionSourcePackage `json:"package,omitempty"` +} + +// ExtensionSpec defines the desired state of Extension +type ExtensionSpec struct { + //+kubebuilder:validation:Enum:=Active;Paused + //+kubebuilder:default:=Active + //+kubebuilder:Optional + // + // managed controls the management state of the extension. "Active" means this extension will be reconciled and "Paused" means this extension will be ignored. + Managed ExtensionManagedState `json:"managed,omitempty"` + + //+kubebuilder:validation:MaxLength:=253 + //+kubebuilder:validation:Pattern:=^[a-z0-9]+([\.-][a-z0-9]+)*$ + // + // serviceAccountName is the name of a service account in the Extension's namespace that will be used to manage the installation and lifecycle of the extension. + ServiceAccountName string `json:"serviceAccountName"` + + // source of Extension to be installed + Source ExtensionSource `json:"source"` +} + +// ExtensionStatus defines the observed state of Extension +type ExtensionStatus struct { + // +optional + InstalledBundleResource string `json:"installedBundleResource,omitempty"` + // +optional + ResolvedBundleResource string `json:"resolvedBundleResource,omitempty"` + + // +patchMergeKey=type + // +patchStrategy=merge + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type" protobuf:"bytes,1,rep,name=conditions"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status +//+kubebuilder:printcolumn:name="Managed",type=string,JSONPath=`.spec.managed`,description="The current reconciliation state of this extension" + +// Extension is the Schema for the extensions API +type Extension struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ExtensionSpec `json:"spec,omitempty"` + Status ExtensionStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// ExtensionList contains a list of Extension +type ExtensionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Extension `json:"items"` +} + +func init() { + SchemeBuilder.Register(&Extension{}, &ExtensionList{}) +} + +func (r *Extension) GetPackageSpec() *ExtensionSourcePackage { + return r.Spec.Source.Package.DeepCopy() +} + +func (r *Extension) GetUID() types.UID { + return r.ObjectMeta.GetUID() +} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index d0f54acb6..fbebacf2d 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -126,3 +126,135 @@ func (in *ClusterExtensionStatus) DeepCopy() *ClusterExtensionStatus { in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Extension) DeepCopyInto(out *Extension) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Extension. +func (in *Extension) DeepCopy() *Extension { + if in == nil { + return nil + } + out := new(Extension) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Extension) 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 *ExtensionList) DeepCopyInto(out *ExtensionList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Extension, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtensionList. +func (in *ExtensionList) DeepCopy() *ExtensionList { + if in == nil { + return nil + } + out := new(ExtensionList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ExtensionList) 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 *ExtensionSource) DeepCopyInto(out *ExtensionSource) { + *out = *in + if in.Package != nil { + in, out := &in.Package, &out.Package + *out = new(ExtensionSourcePackage) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtensionSource. +func (in *ExtensionSource) DeepCopy() *ExtensionSource { + if in == nil { + return nil + } + out := new(ExtensionSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExtensionSourcePackage) DeepCopyInto(out *ExtensionSourcePackage) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtensionSourcePackage. +func (in *ExtensionSourcePackage) DeepCopy() *ExtensionSourcePackage { + if in == nil { + return nil + } + out := new(ExtensionSourcePackage) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExtensionSpec) DeepCopyInto(out *ExtensionSpec) { + *out = *in + in.Source.DeepCopyInto(&out.Source) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtensionSpec. +func (in *ExtensionSpec) DeepCopy() *ExtensionSpec { + if in == nil { + return nil + } + out := new(ExtensionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExtensionStatus) DeepCopyInto(out *ExtensionStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtensionStatus. +func (in *ExtensionStatus) DeepCopy() *ExtensionStatus { + if in == nil { + return nil + } + out := new(ExtensionStatus) + in.DeepCopyInto(out) + return out +} diff --git a/cmd/manager/main.go b/cmd/manager/main.go index 3e872f5f6..c929b53ee 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -123,6 +123,16 @@ func main() { setupLog.Error(err, "unable to create controller", "controller", "ClusterExtension") os.Exit(1) } + + if err = (&controllers.ExtensionReconciler{ + Client: cl, + BundleProvider: catalogClient, + Scheme: mgr.GetScheme(), + Resolver: resolver, + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "Extension") + os.Exit(1) + } //+kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/config/crd/bases/olm.operatorframework.io_extensions.yaml b/config/crd/bases/olm.operatorframework.io_extensions.yaml new file mode 100644 index 000000000..d6afc1e5f --- /dev/null +++ b/config/crd/bases/olm.operatorframework.io_extensions.yaml @@ -0,0 +1,186 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.12.0 + name: extensions.olm.operatorframework.io +spec: + group: olm.operatorframework.io + names: + kind: Extension + listKind: ExtensionList + plural: extensions + singular: extension + scope: Namespaced + versions: + - additionalPrinterColumns: + - description: The current reconciliation state of this extension + jsonPath: .spec.managed + name: Managed + type: string + name: v1alpha1 + schema: + openAPIV3Schema: + description: Extension is the Schema for the extensions API + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation + of an object. Servers should convert recognized schemas to the latest + internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this + object represents. Servers may infer this from the endpoint the client + submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + description: ExtensionSpec defines the desired state of Extension + properties: + managed: + default: Active + description: managed controls the management state of the extension. + "Active" means this extension will be reconciled and "Paused" means + this extension will be ignored. + enum: + - Active + - Paused + type: string + serviceAccountName: + description: serviceAccountName is the name of a service account in + the Extension's namespace that will be used to manage the installation + and lifecycle of the extension. + maxLength: 253 + pattern: ^[a-z0-9]+([\.-][a-z0-9]+)*$ + type: string + source: + description: source of Extension to be installed + properties: + package: + description: A source package defined by a name, version and/or + channel + properties: + channel: + description: channel constraint definition + maxLength: 48 + pattern: ^[a-z0-9]+([\.-][a-z0-9]+)*$ + type: string + name: + description: name specifies the name of the name of the package + maxLength: 48 + pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ + type: string + upgradeConstraintPolicy: + default: Enforce + description: upgradeConstraintPolicy Defines the policy for + how to handle upgrade constraints + enum: + - Enforce + - Ignore + type: string + version: + description: "Version is an optional semver constraint on + the package version. If not specified, the latest version + available of the package will be installed. If specified, + the specific version of the package will be installed so + long as it is available in any of the content sources available. + Examples: 1.2.3, 1.0.0-alpha, 1.0.0-rc.1 \n For more information + on semver, please see https://semver.org/ version constraint + definition" + maxLength: 64 + pattern: ^(\s*(=||!=|>|<|>=|=>|<=|=<|~|~>|\^)\s*(v?(0|[1-9]\d*|[x|X|\*])(\.(0|[1-9]\d*|x|X|\*]))?(\.(0|[1-9]\d*|x|X|\*))?(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?)\s*)((?:\s+|,\s*|\s*\|\|\s*)(=||!=|>|<|>=|=>|<=|=<|~|~>|\^)\s*(v?(0|[1-9]\d*|x|X|\*])(\.(0|[1-9]\d*|x|X|\*))?(\.(0|[1-9]\d*|x|X|\*]))?(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?)\s*)*$ + type: string + required: + - name + type: object + type: object + required: + - serviceAccountName + - source + type: object + status: + description: ExtensionStatus defines the observed state of Extension + properties: + conditions: + items: + description: "Condition contains details for one aspect of the current + state of this API Resource. --- This struct is intended for direct + use as an array at the field path .status.conditions. For example, + \n type FooStatus struct{ // Represents the observations of a + foo's current state. // Known .status.conditions.type are: \"Available\", + \"Progressing\", and \"Degraded\" // +patchMergeKey=type // +patchStrategy=merge + // +listType=map // +listMapKey=type Conditions []metav1.Condition + `json:\"conditions,omitempty\" patchStrategy:\"merge\" patchMergeKey:\"type\" + protobuf:\"bytes,1,rep,name=conditions\"` \n // other fields }" + properties: + lastTransitionTime: + description: lastTransitionTime is the last time the condition + transitioned from one status to another. This should be when + the underlying condition changed. If that is not known, then + using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: message is a human readable message indicating + details about the transition. This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: observedGeneration represents the .metadata.generation + that the condition was set based upon. For instance, if .metadata.generation + is currently 12, but the .status.conditions[x].observedGeneration + is 9, the condition is out of date with respect to the current + state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: reason contains a programmatic identifier indicating + the reason for the condition's last transition. Producers + of specific condition types may define expected values and + meanings for this field, and whether the values are considered + a guaranteed API. The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + --- Many .condition.type values are consistent across resources + like Available, but because arbitrary conditions can be useful + (see .node.status.conditions), the ability to deconflict is + important. The regex it matches is (dns1123SubdomainFmt/)?(qualifiedNameFmt) + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + installedBundleResource: + type: string + resolvedBundleResource: + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index ec864639d..2e88d28bc 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -3,6 +3,7 @@ # It should be run by config/default resources: - bases/olm.operatorframework.io_clusterextensions.yaml +- bases/olm.operatorframework.io_extensions.yaml # the following config is for teaching kustomize how to do kustomization for CRDs. configurations: diff --git a/config/rbac/extension_editor_role.yaml b/config/rbac/extension_editor_role.yaml new file mode 100644 index 000000000..caa26cfd2 --- /dev/null +++ b/config/rbac/extension_editor_role.yaml @@ -0,0 +1,18 @@ +# permissions for end users to edit extensions. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: extension-editor-role +rules: +- apiGroups: + - olm.operatorframework.io + resources: + - extensions + verbs: + - create + - delete + - get + - list + - patch + - update + - watch diff --git a/config/rbac/extension_viewer_role.yaml b/config/rbac/extension_viewer_role.yaml new file mode 100644 index 000000000..980be2d77 --- /dev/null +++ b/config/rbac/extension_viewer_role.yaml @@ -0,0 +1,14 @@ +# permissions for end users to view extensions. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: extension-viewer-role +rules: +- apiGroups: + - olm.operatorframework.io + resources: + - extensions + verbs: + - get + - list + - watch diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 5c7c712d9..d75683ff4 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -51,3 +51,29 @@ rules: - get - patch - update +- apiGroups: + - olm.operatorframework.io + resources: + - extensions + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - olm.operatorframework.io + resources: + - extensions/finalizers + verbs: + - update +- apiGroups: + - olm.operatorframework.io + resources: + - extensions/status + verbs: + - get + - patch + - update diff --git a/config/samples/kustomization.yaml b/config/samples/kustomization.yaml index 09aabdc54..bd1783176 100644 --- a/config/samples/kustomization.yaml +++ b/config/samples/kustomization.yaml @@ -1,4 +1,5 @@ ## Append samples of your project ## resources: - olm_v1alpha1_clusterextension.yaml +- olm_v1alpha1_extension.yaml #+kubebuilder:scaffold:manifestskustomizesamples diff --git a/config/samples/olm_v1alpha1_extension.yaml b/config/samples/olm_v1alpha1_extension.yaml new file mode 100644 index 000000000..72450583c --- /dev/null +++ b/config/samples/olm_v1alpha1_extension.yaml @@ -0,0 +1,12 @@ +apiVersion: olm.operatorframework.io/v1alpha1 +kind: Extension +metadata: + name: extension-sample + namespace: extension-namespace +spec: + paused: false + serviceAccountName: extension-sa + defaultNamespace: extension-sample + package: + name: argocd-operator + version: 0.6.0 diff --git a/internal/controllers/clusterextension_controller.go b/internal/controllers/clusterextension_controller.go index 126b673f4..ffd02a2ee 100644 --- a/internal/controllers/clusterextension_controller.go +++ b/internal/controllers/clusterextension_controller.go @@ -47,12 +47,6 @@ import ( olmvariables "github.com/operator-framework/operator-controller/internal/resolution/variables" ) -// BundleProvider provides the way to retrieve a list of Bundles from a source, -// generally from a catalog client of some kind. -type BundleProvider interface { - Bundles(ctx context.Context) ([]*catalogmetadata.Bundle, error) -} - // ClusterExtensionReconciler reconciles a ClusterExtension object type ClusterExtensionReconciler struct { client.Client @@ -492,91 +486,6 @@ func mapBundleMediaTypeToBundleProvisioner(mediaType string) (string, error) { } } -// setResolvedStatusConditionSuccess sets the resolved status condition to success. -func setResolvedStatusConditionSuccess(conditions *[]metav1.Condition, message string, generation int64) { - apimeta.SetStatusCondition(conditions, metav1.Condition{ - Type: ocv1alpha1.TypeResolved, - Status: metav1.ConditionTrue, - Reason: ocv1alpha1.ReasonSuccess, - Message: message, - ObservedGeneration: generation, - }) -} - -// setResolvedStatusConditionFailed sets the resolved status condition to failed. -func setResolvedStatusConditionFailed(conditions *[]metav1.Condition, message string, generation int64) { - apimeta.SetStatusCondition(conditions, metav1.Condition{ - Type: ocv1alpha1.TypeResolved, - Status: metav1.ConditionFalse, - Reason: ocv1alpha1.ReasonResolutionFailed, - Message: message, - ObservedGeneration: generation, - }) -} - -// setResolvedStatusConditionUnknown sets the resolved status condition to unknown. -func setResolvedStatusConditionUnknown(conditions *[]metav1.Condition, message string, generation int64) { - apimeta.SetStatusCondition(conditions, metav1.Condition{ - Type: ocv1alpha1.TypeResolved, - Status: metav1.ConditionUnknown, - Reason: ocv1alpha1.ReasonResolutionUnknown, - Message: message, - ObservedGeneration: generation, - }) -} - -// setInstalledStatusConditionSuccess sets the installed status condition to success. -func setInstalledStatusConditionSuccess(conditions *[]metav1.Condition, message string, generation int64) { - apimeta.SetStatusCondition(conditions, metav1.Condition{ - Type: ocv1alpha1.TypeInstalled, - Status: metav1.ConditionTrue, - Reason: ocv1alpha1.ReasonSuccess, - Message: message, - ObservedGeneration: generation, - }) -} - -// setInstalledStatusConditionFailed sets the installed status condition to failed. -func setInstalledStatusConditionFailed(conditions *[]metav1.Condition, message string, generation int64) { - apimeta.SetStatusCondition(conditions, metav1.Condition{ - Type: ocv1alpha1.TypeInstalled, - Status: metav1.ConditionFalse, - Reason: ocv1alpha1.ReasonInstallationFailed, - Message: message, - ObservedGeneration: generation, - }) -} - -// setInstalledStatusConditionUnknown sets the installed status condition to unknown. -func setInstalledStatusConditionUnknown(conditions *[]metav1.Condition, message string, generation int64) { - apimeta.SetStatusCondition(conditions, metav1.Condition{ - Type: ocv1alpha1.TypeInstalled, - Status: metav1.ConditionUnknown, - Reason: ocv1alpha1.ReasonInstallationStatusUnknown, - Message: message, - ObservedGeneration: generation, - }) -} - -func setDeprecationStatusesUnknown(conditions *[]metav1.Condition, message string, generation int64) { - conditionTypes := []string{ - ocv1alpha1.TypeDeprecated, - ocv1alpha1.TypePackageDeprecated, - ocv1alpha1.TypeChannelDeprecated, - ocv1alpha1.TypeBundleDeprecated, - } - - for _, conditionType := range conditionTypes { - apimeta.SetStatusCondition(conditions, metav1.Condition{ - Type: conditionType, - Reason: ocv1alpha1.ReasonDeprecated, - Status: metav1.ConditionUnknown, - Message: message, - ObservedGeneration: generation, - }) - } -} - // Generate reconcile requests for all cluster extensions affected by a catalog change func clusterExtensionRequestsForCatalog(c client.Reader, logger logr.Logger) handler.MapFunc { return func(ctx context.Context, _ client.Object) []reconcile.Request { diff --git a/internal/controllers/common_controller.go b/internal/controllers/common_controller.go new file mode 100644 index 000000000..98067824d --- /dev/null +++ b/internal/controllers/common_controller.go @@ -0,0 +1,120 @@ +/* +Copyright 2023. + +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 controllers + +import ( + "context" + + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/operator-framework/operator-controller/internal/catalogmetadata" + + ocv1alpha1 "github.com/operator-framework/operator-controller/api/v1alpha1" +) + +// BundleProvider provides the way to retrieve a list of Bundles from a source, +// generally from a catalog client of some kind. +type BundleProvider interface { + Bundles(ctx context.Context) ([]*catalogmetadata.Bundle, error) +} + +// setResolvedStatusConditionSuccess sets the resolved status condition to success. +func setResolvedStatusConditionSuccess(conditions *[]metav1.Condition, message string, generation int64) { + apimeta.SetStatusCondition(conditions, metav1.Condition{ + Type: ocv1alpha1.TypeResolved, + Status: metav1.ConditionTrue, + Reason: ocv1alpha1.ReasonSuccess, + Message: message, + ObservedGeneration: generation, + }) +} + +// setInstalledStatusConditionUnknown sets the installed status condition to unknown. +func setInstalledStatusConditionUnknown(conditions *[]metav1.Condition, message string, generation int64) { + apimeta.SetStatusCondition(conditions, metav1.Condition{ + Type: ocv1alpha1.TypeInstalled, + Status: metav1.ConditionUnknown, + Reason: ocv1alpha1.ReasonInstallationStatusUnknown, + Message: message, + ObservedGeneration: generation, + }) +} + +// setResolvedStatusConditionFailed sets the resolved status condition to failed. +func setResolvedStatusConditionFailed(conditions *[]metav1.Condition, message string, generation int64) { + apimeta.SetStatusCondition(conditions, metav1.Condition{ + Type: ocv1alpha1.TypeResolved, + Status: metav1.ConditionFalse, + Reason: ocv1alpha1.ReasonResolutionFailed, + Message: message, + ObservedGeneration: generation, + }) +} + +// setResolvedStatusConditionUnknown sets the resolved status condition to unknown. +func setResolvedStatusConditionUnknown(conditions *[]metav1.Condition, message string, generation int64) { + apimeta.SetStatusCondition(conditions, metav1.Condition{ + Type: ocv1alpha1.TypeResolved, + Status: metav1.ConditionUnknown, + Reason: ocv1alpha1.ReasonResolutionUnknown, + Message: message, + ObservedGeneration: generation, + }) +} + +// setInstalledStatusConditionSuccess sets the installed status condition to success. +func setInstalledStatusConditionSuccess(conditions *[]metav1.Condition, message string, generation int64) { + apimeta.SetStatusCondition(conditions, metav1.Condition{ + Type: ocv1alpha1.TypeInstalled, + Status: metav1.ConditionTrue, + Reason: ocv1alpha1.ReasonSuccess, + Message: message, + ObservedGeneration: generation, + }) +} + +// setInstalledStatusConditionFailed sets the installed status condition to failed. +func setInstalledStatusConditionFailed(conditions *[]metav1.Condition, message string, generation int64) { + apimeta.SetStatusCondition(conditions, metav1.Condition{ + Type: ocv1alpha1.TypeInstalled, + Status: metav1.ConditionFalse, + Reason: ocv1alpha1.ReasonInstallationFailed, + Message: message, + ObservedGeneration: generation, + }) +} + +// setDEprecationStatusesUnknown sets the deprecation status conditions to unknown. +func setDeprecationStatusesUnknown(conditions *[]metav1.Condition, message string, generation int64) { + conditionTypes := []string{ + ocv1alpha1.TypeDeprecated, + ocv1alpha1.TypePackageDeprecated, + ocv1alpha1.TypeChannelDeprecated, + ocv1alpha1.TypeBundleDeprecated, + } + + for _, conditionType := range conditionTypes { + apimeta.SetStatusCondition(conditions, metav1.Condition{ + Type: conditionType, + Reason: ocv1alpha1.ReasonDeprecated, + Status: metav1.ConditionUnknown, + Message: message, + ObservedGeneration: generation, + }) + } +} diff --git a/internal/controllers/extension_controller.go b/internal/controllers/extension_controller.go new file mode 100644 index 000000000..03a7b341f --- /dev/null +++ b/internal/controllers/extension_controller.go @@ -0,0 +1,179 @@ +/* +Copyright 2024. + +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 controllers + +import ( + "context" + + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/runtime" + utilerrors "k8s.io/apimachinery/pkg/util/errors" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/log" + + catalogd "github.com/operator-framework/catalogd/api/core/v1alpha1" + "github.com/operator-framework/deppy/pkg/deppy/solver" + + ocv1alpha1 "github.com/operator-framework/operator-controller/api/v1alpha1" + "github.com/operator-framework/operator-controller/internal/controllers/validators" + "github.com/operator-framework/operator-controller/pkg/features" +) + +// ExtensionReconciler reconciles a Extension object +type ExtensionReconciler struct { + client.Client + BundleProvider BundleProvider + Scheme *runtime.Scheme + Resolver *solver.Solver +} + +//+kubebuilder:rbac:groups=olm.operatorframework.io,resources=extensions,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=olm.operatorframework.io,resources=extensions/status,verbs=get;update;patch +//+kubebuilder:rbac:groups=olm.operatorframework.io,resources=extensions/finalizers,verbs=update + +// Reconcile is part of the main kubernetes reconciliation loop which aims to +// move the current state of the cluster closer to the desired state. +func (r *ExtensionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + l := log.FromContext(ctx).WithName("extension-controller") + l.V(1).Info("starting") + defer l.V(1).Info("ending") + + var existingExt = &ocv1alpha1.Extension{} + if err := r.Client.Get(ctx, req.NamespacedName, existingExt); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + + reconciledExt := existingExt.DeepCopy() + res, reconcileErr := r.reconcile(ctx, reconciledExt) + + // Do checks before any Update()s, as Update() may modify the resource structure! + updateStatus := !equality.Semantic.DeepEqual(existingExt.Status, reconciledExt.Status) + updateFinalizers := !equality.Semantic.DeepEqual(existingExt.Finalizers, reconciledExt.Finalizers) + unexpectedFieldsChanged := r.checkForUnexpectedFieldChange(*existingExt, *reconciledExt) + + if updateStatus { + if updateErr := r.Client.Status().Update(ctx, reconciledExt); updateErr != nil { + return res, utilerrors.NewAggregate([]error{reconcileErr, updateErr}) + } + } + + if unexpectedFieldsChanged { + panic("spec or metadata changed by reconciler") + } + + if updateFinalizers { + if updateErr := r.Client.Update(ctx, reconciledExt); updateErr != nil { + return res, utilerrors.NewAggregate([]error{reconcileErr, updateErr}) + } + } + + return res, reconcileErr +} + +// Compare resources - ignoring status & metadata.finalizers +func (*ExtensionReconciler) checkForUnexpectedFieldChange(a, b ocv1alpha1.Extension) bool { + a.Status, b.Status = ocv1alpha1.ExtensionStatus{}, ocv1alpha1.ExtensionStatus{} + a.Finalizers, b.Finalizers = []string{}, []string{} + return !equality.Semantic.DeepEqual(a, b) +} + +// Helper function to do the actual reconcile +// +// Today we always return ctrl.Result{} and an error. +// But in the future we might update this function +// to return different results (e.g. requeue). +// +//nolint:unparam +func (r *ExtensionReconciler) reconcile(ctx context.Context, ext *ocv1alpha1.Extension) (ctrl.Result, error) { + l := log.FromContext(ctx).WithName("extension-controller") + + // Don't do anything if feature gated + if !features.OperatorControllerFeatureGate.Enabled(features.EnableExtensionAPI) { + l.Info("extension feature is gated", "name", ext.GetName(), "namespace", ext.GetNamespace()) + + // Set the TypeInstalled condition to Unknown to indicate that the resolution + // hasn't been attempted yet, due to the spec being invalid. + ext.Status.InstalledBundleResource = "" + setInstalledStatusConditionUnknown(&ext.Status.Conditions, "extension feature is disabled", ext.GetGeneration()) + // Set the TypeResolved condition to Unknown to indicate that the resolution + // hasn't been attempted yet, due to the spec being invalid. + ext.Status.ResolvedBundleResource = "" + setResolvedStatusConditionUnknown(&ext.Status.Conditions, "extension feature is disabled", ext.GetGeneration()) + + setDeprecationStatusesUnknown(&ext.Status.Conditions, "extension feature is disabled", ext.GetGeneration()) + return ctrl.Result{}, nil + } + + // Don't do anything if Paused + if ext.Spec.Managed == ocv1alpha1.ManagedStatePaused { + l.Info("resource is paused", "name", ext.GetName(), "namespace", ext.GetNamespace()) + return ctrl.Result{}, nil + } + + // validate spec + if err := validators.ValidateExtensionSpec(ext); err != nil { + // Set the TypeInstalled condition to Unknown to indicate that the resolution + // hasn't been attempted yet, due to the spec being invalid. + ext.Status.InstalledBundleResource = "" + setInstalledStatusConditionUnknown(&ext.Status.Conditions, "installation has not been attempted as spec is invalid", ext.GetGeneration()) + // Set the TypeResolved condition to Unknown to indicate that the resolution + // hasn't been attempted yet, due to the spec being invalid. + ext.Status.ResolvedBundleResource = "" + setResolvedStatusConditionUnknown(&ext.Status.Conditions, "validation has not been attempted as spec is invalid", ext.GetGeneration()) + + setDeprecationStatusesUnknown(&ext.Status.Conditions, "deprecation checks have not been attempted as spec is invalid", ext.GetGeneration()) + return ctrl.Result{}, nil + } + + // TODO: kapp-controller integration + // * gather variables for resolution + // * perform resolution + // * lookup the bundle in the solution/selection that corresponds to the Extension's desired Source + // * set the status of the Extension based on the respective deployed application status conditions. + + // Set the TypeInstalled condition to Unknown to indicate that the resolution + // hasn't been attempted yet, due to the spec being invalid. + ext.Status.InstalledBundleResource = "" + setInstalledStatusConditionUnknown(&ext.Status.Conditions, "the Extension interface is not fully implemented", ext.GetGeneration()) + // Set the TypeResolved condition to Unknown to indicate that the resolution + // hasn't been attempted yet, due to the spec being invalid. + ext.Status.ResolvedBundleResource = "" + setResolvedStatusConditionUnknown(&ext.Status.Conditions, "the Extension interface is not fully implemented", ext.GetGeneration()) + + setDeprecationStatusesUnknown(&ext.Status.Conditions, "the Extension interface is not fully implemented", ext.GetGeneration()) + + return ctrl.Result{}, nil +} + +// SetupWithManager sets up the controller with the Manager. +func (r *ExtensionReconciler) SetupWithManager(mgr ctrl.Manager) error { + // TODO: Add watch for kapp-controller resources + + // When feature-gated, don't watch catalogs. + if !features.OperatorControllerFeatureGate.Enabled(features.EnableExtensionAPI) { + return ctrl.NewControllerManagedBy(mgr). + For(&ocv1alpha1.Extension{}). + Complete(r) + } + + return ctrl.NewControllerManagedBy(mgr). + For(&ocv1alpha1.Extension{}). + Watches(&catalogd.Catalog{}, &handler.EnqueueRequestForObject{}). + Complete(r) +} diff --git a/internal/controllers/extension_controller_test.go b/internal/controllers/extension_controller_test.go new file mode 100644 index 000000000..786a24509 --- /dev/null +++ b/internal/controllers/extension_controller_test.go @@ -0,0 +1,235 @@ +package controllers_test + +import ( + "context" + "fmt" + "testing" + + rukpakv1alpha2 "github.com/operator-framework/rukpak/api/v1alpha2" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/rand" + featuregatetesting "k8s.io/component-base/featuregate/testing" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + ocv1alpha1 "github.com/operator-framework/operator-controller/api/v1alpha1" + "github.com/operator-framework/operator-controller/internal/conditionsets" + "github.com/operator-framework/operator-controller/pkg/features" +) + +// Describe: Extension Controller Test +func TestExtensionDoesNotExist(t *testing.T) { + _, reconciler := newClientAndExtensionReconciler(t) + + t.Log("When the extension does not exist") + t.Log("It returns no error") + res, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Name: "non-existent", Namespace: "non-existent"}}) + require.Equal(t, ctrl.Result{}, res) + require.NoError(t, err) +} + +func TestExtensionBadResources(t *testing.T) { + cl, _ := newClientAndExtensionReconciler(t) + ctx := context.Background() + extKey := types.NamespacedName{ + Name: fmt.Sprintf("extension-test-%s", rand.String(8)), + Namespace: fmt.Sprintf("namespace-%s", rand.String(8)), + } + namespace := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: extKey.Namespace, + }, + } + require.NoError(t, cl.Create(ctx, namespace)) + + badExtensions := []ocv1alpha1.Extension{ + { + ObjectMeta: metav1.ObjectMeta{Name: "no-package-name", Namespace: extKey.Namespace}, + Spec: ocv1alpha1.ExtensionSpec{ + Source: ocv1alpha1.ExtensionSource{ + Package: &ocv1alpha1.ExtensionSourcePackage{ + Name: "", + }, + }, + ServiceAccountName: "default", + }, + }, { + ObjectMeta: metav1.ObjectMeta{Name: "no-namespace"}, + Spec: ocv1alpha1.ExtensionSpec{ + Source: ocv1alpha1.ExtensionSource{ + Package: &ocv1alpha1.ExtensionSourcePackage{ + Name: fmt.Sprintf("non-existent-%s", rand.String(6)), + }, + }, + ServiceAccountName: "default", + }, + }, { + ObjectMeta: metav1.ObjectMeta{Name: "no-service-account", Namespace: extKey.Namespace}, + Spec: ocv1alpha1.ExtensionSpec{ + Source: ocv1alpha1.ExtensionSource{ + Package: &ocv1alpha1.ExtensionSourcePackage{ + Name: fmt.Sprintf("non-existent-%s", rand.String(6)), + }, + }, + }, + }, + } + + for _, e := range badExtensions { + ext := e.DeepCopy() + require.Error(t, cl.Create(ctx, ext), fmt.Sprintf("Failed on %q", e.ObjectMeta.GetName())) + } + + invalidExtensions := []ocv1alpha1.Extension{ + { + ObjectMeta: metav1.ObjectMeta{Name: "no-source", Namespace: extKey.Namespace}, + Spec: ocv1alpha1.ExtensionSpec{ + ServiceAccountName: "default", + }, + }, { + ObjectMeta: metav1.ObjectMeta{Name: "no-package", Namespace: extKey.Namespace}, + Spec: ocv1alpha1.ExtensionSpec{ + Source: ocv1alpha1.ExtensionSource{}, + ServiceAccountName: "default", + }, + }, + } + + for _, e := range invalidExtensions { + ext := e.DeepCopy() + require.NoError(t, cl.Create(ctx, ext), fmt.Sprintf("Create failed on %q", e.GetObjectMeta().GetName())) + name := types.NamespacedName{Name: e.GetObjectMeta().GetName(), Namespace: e.GetObjectMeta().GetNamespace()} + + cl, reconciler := newClientAndExtensionReconciler(t) + res, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: name}) + require.Equal(t, ctrl.Result{}, res) + require.NoError(t, err) + + require.NoError(t, cl.Get(ctx, name, ext), fmt.Sprintf("Get failed on %q", e.ObjectMeta.GetName())) + cond := apimeta.FindStatusCondition(ext.Status.Conditions, ocv1alpha1.TypeResolved) + require.NotNil(t, cond, fmt.Sprintf("Get condition failed on %q", ext.ObjectMeta.GetName())) + require.Equal(t, metav1.ConditionUnknown, cond.Status, fmt.Sprintf("Get status check failed on %q", ext.ObjectMeta.GetName())) + require.Equal(t, ocv1alpha1.ReasonResolutionUnknown, cond.Reason, fmt.Sprintf("Get status reason failed on %q", ext.ObjectMeta.GetName())) + require.Equal(t, "extension feature is disabled", cond.Message) + require.NoError(t, client.IgnoreNotFound(cl.Delete(ctx, ext))) + } + + for _, e := range invalidExtensions { + resetFeatureGate := featuregatetesting.SetFeatureGateDuringTest(t, features.OperatorControllerFeatureGate, features.EnableExtensionAPI, true) + ext := e.DeepCopy() + require.NoError(t, cl.Create(ctx, ext), fmt.Sprintf("Create failed on %q", e.GetObjectMeta().GetName())) + name := types.NamespacedName{Name: e.GetObjectMeta().GetName(), Namespace: e.GetObjectMeta().GetNamespace()} + + cl, reconciler := newClientAndExtensionReconciler(t) + res, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: name}) + require.Equal(t, ctrl.Result{}, res) + require.NoError(t, err) + + require.NoError(t, cl.Get(ctx, name, ext), fmt.Sprintf("Get failed on %q", e.ObjectMeta.GetName())) + cond := apimeta.FindStatusCondition(ext.Status.Conditions, ocv1alpha1.TypeResolved) + require.NotNil(t, cond, fmt.Sprintf("Get condition failed on %q", ext.ObjectMeta.GetName())) + require.Equal(t, metav1.ConditionUnknown, cond.Status, fmt.Sprintf("Get status check failed on %q", ext.ObjectMeta.GetName())) + require.Equal(t, ocv1alpha1.ReasonResolutionUnknown, cond.Reason, fmt.Sprintf("Get status reason failed on %q", ext.ObjectMeta.GetName())) + require.Equal(t, "validation has not been attempted as spec is invalid", cond.Message) + + resetFeatureGate() + } + + require.NoError(t, cl.DeleteAllOf(ctx, &ocv1alpha1.Extension{}, client.InNamespace(extKey.Namespace))) + require.NoError(t, cl.Delete(ctx, namespace)) +} + +func TestExtensionInvalidSemverPastRegex(t *testing.T) { + defer featuregatetesting.SetFeatureGateDuringTest(t, features.OperatorControllerFeatureGate, features.EnableExtensionAPI, true)() + cl, reconciler := newClientAndExtensionReconciler(t) + ctx := context.Background() + t.Log("When an invalid semver is provided that bypasses the regex validation") + extKey := types.NamespacedName{ + Name: fmt.Sprintf("extension-test-%s", rand.String(8)), + Namespace: fmt.Sprintf("namespace-%s", rand.String(8)), + } + namespace := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: extKey.Namespace, + }, + } + require.NoError(t, cl.Create(ctx, namespace)) + + t.Log("By injecting creating a client with the bad extension CR") + pkgName := fmt.Sprintf("exists-%s", rand.String(6)) + extension := &ocv1alpha1.Extension{ + ObjectMeta: metav1.ObjectMeta{Name: extKey.Name, Namespace: extKey.Namespace}, + Spec: ocv1alpha1.ExtensionSpec{ + Source: ocv1alpha1.ExtensionSource{ + Package: &ocv1alpha1.ExtensionSourcePackage{ + Name: pkgName, + Version: "1.2.3-123abc_def", // bad semver that matches the regex on the CR validation + }, + }, + ServiceAccountName: "default", + }, + } + + // this bypasses client/server-side CR validation and allows us to test the reconciler's validation + fakeClient := fake.NewClientBuilder().WithScheme(sch).WithObjects(extension).WithStatusSubresource(extension).Build() + + t.Log("By changing the reconciler client to the fake client") + reconciler.Client = fakeClient + + t.Log("It should add an invalid spec condition and *not* re-enqueue for reconciliation") + t.Log("By running reconcile") + res, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: extKey}) + require.Equal(t, ctrl.Result{}, res) + require.NoError(t, err) + + t.Log("By fetching updated extension after reconcile") + require.NoError(t, fakeClient.Get(ctx, extKey, extension)) + + t.Log("By checking the status fields") + require.Empty(t, extension.Status.ResolvedBundleResource) + require.Empty(t, extension.Status.InstalledBundleResource) + + t.Log("By checking the expected conditions") + cond := apimeta.FindStatusCondition(extension.Status.Conditions, ocv1alpha1.TypeResolved) + require.NotNil(t, cond) + require.Equal(t, metav1.ConditionUnknown, cond.Status) + require.Equal(t, ocv1alpha1.ReasonResolutionUnknown, cond.Reason) + require.Equal(t, "validation has not been attempted as spec is invalid", cond.Message) + cond = apimeta.FindStatusCondition(extension.Status.Conditions, ocv1alpha1.TypeInstalled) + require.NotNil(t, cond) + require.Equal(t, metav1.ConditionUnknown, cond.Status) + require.Equal(t, ocv1alpha1.ReasonInstallationStatusUnknown, cond.Reason) + require.Equal(t, "installation has not been attempted as spec is invalid", cond.Message) + + verifyExtensionInvariants(ctx, t, reconciler.Client, extension) + require.NoError(t, cl.DeleteAllOf(ctx, &ocv1alpha1.Extension{}, client.InNamespace(extKey.Namespace))) + require.NoError(t, cl.DeleteAllOf(ctx, &rukpakv1alpha2.BundleDeployment{})) + require.NoError(t, cl.Delete(ctx, namespace)) +} + +func verifyExtensionInvariants(ctx context.Context, t *testing.T, c client.Client, ext *ocv1alpha1.Extension) { + key := client.ObjectKeyFromObject(ext) + require.NoError(t, c.Get(ctx, key, ext)) + + verifyExtensionConditionsInvariants(t, ext) +} + +func verifyExtensionConditionsInvariants(t *testing.T, ext *ocv1alpha1.Extension) { + // Expect that the extension's set of conditions contains all defined + // condition types for the Extension API. Every reconcile should always + // ensure every condition type's status/reason/message reflects the state + // read during _this_ reconcile call. + require.Len(t, ext.Status.Conditions, len(conditionsets.ConditionTypes)) + for _, tt := range conditionsets.ConditionTypes { + cond := apimeta.FindStatusCondition(ext.Status.Conditions, tt) + require.NotNil(t, cond) + require.NotEmpty(t, cond.Status) + require.Contains(t, conditionsets.ConditionReasons, cond.Reason) + require.Equal(t, ext.GetGeneration(), cond.ObservedGeneration) + } +} diff --git a/internal/controllers/suite_test.go b/internal/controllers/suite_test.go index 8ee4abcd3..ba9518cb6 100644 --- a/internal/controllers/suite_test.go +++ b/internal/controllers/suite_test.go @@ -22,6 +22,7 @@ import ( "path/filepath" "testing" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/rest" @@ -59,6 +60,21 @@ func newClientAndReconciler(t *testing.T) (client.Client, *controllers.ClusterEx return cl, reconciler } +func newClientAndExtensionReconciler(t *testing.T) (client.Client, *controllers.ExtensionReconciler) { + resolver, err := solver.New() + require.NoError(t, err) + + cl := newClient(t) + fakeCatalogClient := testutil.NewFakeCatalogClient(testBundleList) + reconciler := &controllers.ExtensionReconciler{ + Client: cl, + BundleProvider: &fakeCatalogClient, + Scheme: sch, + Resolver: resolver, + } + return cl, reconciler +} + var ( sch *runtime.Scheme cfg *rest.Config @@ -82,6 +98,7 @@ func TestMain(m *testing.M) { sch = runtime.NewScheme() utilruntime.Must(ocv1alpha1.AddToScheme(sch)) utilruntime.Must(rukpakv1alpha2.AddToScheme(sch)) + utilruntime.Must(corev1.AddToScheme(sch)) code := m.Run() utilruntime.Must(testEnv.Stop()) diff --git a/internal/controllers/validators/validators.go b/internal/controllers/validators/clusterextension_validators.go similarity index 100% rename from internal/controllers/validators/validators.go rename to internal/controllers/validators/clusterextension_validators.go diff --git a/internal/controllers/validators/extension_validators.go b/internal/controllers/validators/extension_validators.go new file mode 100644 index 000000000..61467690b --- /dev/null +++ b/internal/controllers/validators/extension_validators.go @@ -0,0 +1,58 @@ +package validators + +import ( + "fmt" + + mmsemver "github.com/Masterminds/semver/v3" + + ocv1alpha1 "github.com/operator-framework/operator-controller/api/v1alpha1" +) + +type extensionCRValidatorFunc func(e *ocv1alpha1.Extension) error + +// validatePackageSemver validates that the clusterExtension's version is a valid SemVer. +// this validation should already be happening at the CRD level. But, it depends +// on a regex that could possibly fail to validate a valid SemVer. This is added as an +// extra measure to ensure a valid spec before the CR is processed for resolution +func validatePackageSemver(e *ocv1alpha1.Extension) error { + pkg := e.GetPackageSpec() + if pkg == nil { + return nil + } + if pkg.Version == "" { + return nil + } + if _, err := mmsemver.NewConstraint(pkg.Version); err != nil { + return fmt.Errorf("invalid package version spec: %w", err) + } + return nil +} + +// validatePackageOrDirect validates that one or the other exists +// For now, this just makes sure there's a Package, as no other Source type has been defined +func validatePackage(e *ocv1alpha1.Extension) error { + pkg := e.GetPackageSpec() + if pkg == nil { + return fmt.Errorf("package not found") + } + return nil +} + +// ValidateSpec validates the (cluster)Extension spec, e.g. ensuring that .spec.source.package.version, if provided, is a valid SemVer +func ValidateExtensionSpec(e *ocv1alpha1.Extension) error { + validators := []extensionCRValidatorFunc{ + validatePackageSemver, + validatePackage, + } + + // Currently we only have a two validators, but more will likely be added in the future + // we need to make a decision on whether we want to run all validators or stop at the first error. If the the former, + // we should consider how to present this to the user in a way that is easy to understand and fix. + // this issue is tracked here: https://github.com/operator-framework/operator-controller/issues/167 + for _, validator := range validators { + if err := validator(e); err != nil { + return err + } + } + return nil +} diff --git a/internal/internal.go b/internal/internal.go new file mode 100644 index 000000000..d8475ec30 --- /dev/null +++ b/internal/internal.go @@ -0,0 +1,44 @@ +/* +Copyright 2024. + +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 internal + +import ( + "k8s.io/apimachinery/pkg/types" + + ocv1alpha1 "github.com/operator-framework/operator-controller/api/v1alpha1" +) + +type ExtensionInterface interface { + GetPackageSpec() *ocv1alpha1.ExtensionSourcePackage + GetUID() types.UID +} + +func ExtensionArrayToInterface(in []ocv1alpha1.Extension) []ExtensionInterface { + ei := make([]ExtensionInterface, len(in)) + for i := range in { + ei[i] = &in[i] + } + return ei +} + +func ClusterExtensionArrayToInterface(in []ocv1alpha1.ClusterExtension) []ExtensionInterface { + ei := make([]ExtensionInterface, len(in)) + for i := range in { + ei[i] = &in[i] + } + return ei +} diff --git a/pkg/features/features.go b/pkg/features/features.go index 329737a96..e930fbbaa 100644 --- a/pkg/features/features.go +++ b/pkg/features/features.go @@ -10,6 +10,7 @@ const ( // Ex: SomeFeature featuregate.Feature = "SomeFeature" ForceSemverUpgradeConstraints featuregate.Feature = "ForceSemverUpgradeConstraints" + EnableExtensionAPI featuregate.Feature = "EnableExtensionApi" ) var operatorControllerFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{ @@ -17,6 +18,7 @@ var operatorControllerFeatureGates = map[featuregate.Feature]featuregate.Feature // Ex: SomeFeature: {...} ForceSemverUpgradeConstraints: {Default: false, PreRelease: featuregate.Alpha}, + EnableExtensionAPI: {Default: false, PreRelease: featuregate.Alpha}, } var OperatorControllerFeatureGate featuregate.MutableFeatureGate = featuregate.NewFeatureGate() diff --git a/test/e2e/install_test.go b/test/e2e/cluster_extension_install_test.go similarity index 100% rename from test/e2e/install_test.go rename to test/e2e/cluster_extension_install_test.go