From ab365d176cef02a939603fec73a6711d28b1742d Mon Sep 17 00:00:00 2001 From: Satoshi Konno Date: Thu, 28 Mar 2024 23:55:34 +0900 Subject: [PATCH] Add controller --- PROJECT | 10 ++ api/v1/groupversion_info.go | 36 ++++++ api/v1/puzzledb_types.go | 64 ++++++++++ api/v1/zz_generated.deepcopy.go | 114 ++++++++++++++++++ cmd/main.go | 11 ++ ...ions.k8s.io.cybergarage.org_puzzledbs.yaml | 54 +++++++++ config/crd/kustomization.yaml | 23 ++++ config/crd/kustomizeconfig.yaml | 19 +++ config/default/kustomization.yaml | 2 +- config/rbac/puzzledb_editor_role.yaml | 31 +++++ config/rbac/puzzledb_viewer_role.yaml | 27 +++++ config/rbac/role.yaml | 37 ++++-- .../apiextensions.k8s.io_v1_puzzledb.yaml | 12 ++ config/samples/kustomization.yaml | 4 + internal/controller/puzzledb_controller.go | 62 ++++++++++ .../controller/puzzledb_controller_test.go | 84 +++++++++++++ internal/controller/suite_test.go | 90 ++++++++++++++ 17 files changed, 669 insertions(+), 11 deletions(-) create mode 100644 api/v1/groupversion_info.go create mode 100644 api/v1/puzzledb_types.go create mode 100644 api/v1/zz_generated.deepcopy.go create mode 100644 config/crd/bases/apiextensions.k8s.io.cybergarage.org_puzzledbs.yaml create mode 100644 config/crd/kustomization.yaml create mode 100644 config/crd/kustomizeconfig.yaml create mode 100644 config/rbac/puzzledb_editor_role.yaml create mode 100644 config/rbac/puzzledb_viewer_role.yaml create mode 100644 config/samples/apiextensions.k8s.io_v1_puzzledb.yaml create mode 100644 config/samples/kustomization.yaml create mode 100644 internal/controller/puzzledb_controller.go create mode 100644 internal/controller/puzzledb_controller_test.go create mode 100644 internal/controller/suite_test.go diff --git a/PROJECT b/PROJECT index 6011e03..9f26cb7 100644 --- a/PROJECT +++ b/PROJECT @@ -10,4 +10,14 @@ plugins: scorecard.sdk.operatorframework.io/v2: {} projectName: puzzledb-operator repo: github.com/cybergarage/puzzledb-operator +resources: +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: cybergarage.org + group: apiextensions.k8s.io + kind: PuzzleDB + path: github.com/cybergarage/puzzledb-operator/api/v1 + version: v1 version: "3" diff --git a/api/v1/groupversion_info.go b/api/v1/groupversion_info.go new file mode 100644 index 0000000..1b99bb6 --- /dev/null +++ b/api/v1/groupversion_info.go @@ -0,0 +1,36 @@ +/* +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 v1 contains API Schema definitions for the apiextensions.k8s.io v1 API group +// +kubebuilder:object:generate=true +// +groupName=apiextensions.k8s.io.cybergarage.org +package v1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +var ( + // GroupVersion is group version used to register these objects + GroupVersion = schema.GroupVersion{Group: "apiextensions.k8s.io.cybergarage.org", Version: "v1"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme + SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} + + // AddToScheme adds the types in this group-version to the given scheme. + AddToScheme = SchemeBuilder.AddToScheme +) diff --git a/api/v1/puzzledb_types.go b/api/v1/puzzledb_types.go new file mode 100644 index 0000000..963f996 --- /dev/null +++ b/api/v1/puzzledb_types.go @@ -0,0 +1,64 @@ +/* +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 v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// PuzzleDBSpec defines the desired state of PuzzleDB +type PuzzleDBSpec struct { + // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster + // Important: Run "make" to regenerate code after modifying this file + + // Foo is an example field of PuzzleDB. Edit puzzledb_types.go to remove/update + Foo string `json:"foo,omitempty"` +} + +// PuzzleDBStatus defines the observed state of PuzzleDB +type PuzzleDBStatus struct { + // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster + // Important: Run "make" to regenerate code after modifying this file +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status + +// PuzzleDB is the Schema for the puzzledbs API +type PuzzleDB struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec PuzzleDBSpec `json:"spec,omitempty"` + Status PuzzleDBStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// PuzzleDBList contains a list of PuzzleDB +type PuzzleDBList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []PuzzleDB `json:"items"` +} + +func init() { + SchemeBuilder.Register(&PuzzleDB{}, &PuzzleDBList{}) +} diff --git a/api/v1/zz_generated.deepcopy.go b/api/v1/zz_generated.deepcopy.go new file mode 100644 index 0000000..9933462 --- /dev/null +++ b/api/v1/zz_generated.deepcopy.go @@ -0,0 +1,114 @@ +//go:build !ignore_autogenerated + +/* +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. +*/ + +// Code generated by controller-gen. DO NOT EDIT. + +package v1 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PuzzleDB) DeepCopyInto(out *PuzzleDB) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + out.Status = in.Status +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PuzzleDB. +func (in *PuzzleDB) DeepCopy() *PuzzleDB { + if in == nil { + return nil + } + out := new(PuzzleDB) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PuzzleDB) 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 *PuzzleDBList) DeepCopyInto(out *PuzzleDBList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PuzzleDB, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PuzzleDBList. +func (in *PuzzleDBList) DeepCopy() *PuzzleDBList { + if in == nil { + return nil + } + out := new(PuzzleDBList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PuzzleDBList) 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 *PuzzleDBSpec) DeepCopyInto(out *PuzzleDBSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PuzzleDBSpec. +func (in *PuzzleDBSpec) DeepCopy() *PuzzleDBSpec { + if in == nil { + return nil + } + out := new(PuzzleDBSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PuzzleDBStatus) DeepCopyInto(out *PuzzleDBStatus) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PuzzleDBStatus. +func (in *PuzzleDBStatus) DeepCopy() *PuzzleDBStatus { + if in == nil { + return nil + } + out := new(PuzzleDBStatus) + in.DeepCopyInto(out) + return out +} diff --git a/cmd/main.go b/cmd/main.go index 88ae894..9bf6f48 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -33,6 +33,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" + + apiextensionsk8siov1 "github.com/cybergarage/puzzledb-operator/api/v1" + "github.com/cybergarage/puzzledb-operator/internal/controller" //+kubebuilder:scaffold:imports ) @@ -44,6 +47,7 @@ var ( func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) + utilruntime.Must(apiextensionsk8siov1.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme } @@ -118,6 +122,13 @@ func main() { os.Exit(1) } + if err = (&controller.PuzzleDBReconciler{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "PuzzleDB") + os.Exit(1) + } //+kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/config/crd/bases/apiextensions.k8s.io.cybergarage.org_puzzledbs.yaml b/config/crd/bases/apiextensions.k8s.io.cybergarage.org_puzzledbs.yaml new file mode 100644 index 0000000..be9955b --- /dev/null +++ b/config/crd/bases/apiextensions.k8s.io.cybergarage.org_puzzledbs.yaml @@ -0,0 +1,54 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.14.0 + name: puzzledbs.apiextensions.k8s.io.cybergarage.org +spec: + group: apiextensions.k8s.io.cybergarage.org + names: + kind: PuzzleDB + listKind: PuzzleDBList + plural: puzzledbs + singular: puzzledb + scope: Namespaced + versions: + - name: v1 + schema: + openAPIV3Schema: + description: PuzzleDB is the Schema for the puzzledbs 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: PuzzleDBSpec defines the desired state of PuzzleDB + properties: + foo: + description: Foo is an example field of PuzzleDB. Edit puzzledb_types.go + to remove/update + type: string + type: object + status: + description: PuzzleDBStatus defines the observed state of PuzzleDB + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml new file mode 100644 index 0000000..2a1a305 --- /dev/null +++ b/config/crd/kustomization.yaml @@ -0,0 +1,23 @@ +# This kustomization.yaml is not intended to be run by itself, +# since it depends on service name and namespace that are out of this kustomize package. +# It should be run by config/default +resources: +- bases/apiextensions.k8s.io.cybergarage.org_puzzledbs.yaml +#+kubebuilder:scaffold:crdkustomizeresource + +patches: +# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix. +# patches here are for enabling the conversion webhook for each CRD +#- path: patches/webhook_in_puzzledbs.yaml +#+kubebuilder:scaffold:crdkustomizewebhookpatch + +# [CERTMANAGER] To enable cert-manager, uncomment all the sections with [CERTMANAGER] prefix. +# patches here are for enabling the CA injection for each CRD +#- path: patches/cainjection_in_puzzledbs.yaml +#+kubebuilder:scaffold:crdkustomizecainjectionpatch + +# [WEBHOOK] To enable webhook, uncomment the following section +# the following config is for teaching kustomize how to do kustomization for CRDs. + +#configurations: +#- kustomizeconfig.yaml diff --git a/config/crd/kustomizeconfig.yaml b/config/crd/kustomizeconfig.yaml new file mode 100644 index 0000000..ec5c150 --- /dev/null +++ b/config/crd/kustomizeconfig.yaml @@ -0,0 +1,19 @@ +# This file is for teaching kustomize how to substitute name and namespace reference in CRD +nameReference: +- kind: Service + version: v1 + fieldSpecs: + - kind: CustomResourceDefinition + version: v1 + group: apiextensions.k8s.io + path: spec/conversion/webhook/clientConfig/service/name + +namespace: +- kind: CustomResourceDefinition + version: v1 + group: apiextensions.k8s.io + path: spec/conversion/webhook/clientConfig/service/namespace + create: false + +varReference: +- path: metadata/annotations diff --git a/config/default/kustomization.yaml b/config/default/kustomization.yaml index 6ee17d5..b4a4109 100644 --- a/config/default/kustomization.yaml +++ b/config/default/kustomization.yaml @@ -15,7 +15,7 @@ namePrefix: puzzledb-operator- # someName: someValue resources: -#- ../crd +- ../crd - ../rbac - ../manager # [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in diff --git a/config/rbac/puzzledb_editor_role.yaml b/config/rbac/puzzledb_editor_role.yaml new file mode 100644 index 0000000..27c0f83 --- /dev/null +++ b/config/rbac/puzzledb_editor_role.yaml @@ -0,0 +1,31 @@ +# permissions for end users to edit puzzledbs. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clusterrole + app.kubernetes.io/instance: puzzledb-editor-role + app.kubernetes.io/component: rbac + app.kubernetes.io/created-by: puzzledb-operator + app.kubernetes.io/part-of: puzzledb-operator + app.kubernetes.io/managed-by: kustomize + name: puzzledb-editor-role +rules: +- apiGroups: + - apiextensions.k8s.io.cybergarage.org + resources: + - puzzledbs + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - apiextensions.k8s.io.cybergarage.org + resources: + - puzzledbs/status + verbs: + - get diff --git a/config/rbac/puzzledb_viewer_role.yaml b/config/rbac/puzzledb_viewer_role.yaml new file mode 100644 index 0000000..bfd7ac4 --- /dev/null +++ b/config/rbac/puzzledb_viewer_role.yaml @@ -0,0 +1,27 @@ +# permissions for end users to view puzzledbs. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clusterrole + app.kubernetes.io/instance: puzzledb-viewer-role + app.kubernetes.io/component: rbac + app.kubernetes.io/created-by: puzzledb-operator + app.kubernetes.io/part-of: puzzledb-operator + app.kubernetes.io/managed-by: kustomize + name: puzzledb-viewer-role +rules: +- apiGroups: + - apiextensions.k8s.io.cybergarage.org + resources: + - puzzledbs + verbs: + - get + - list + - watch +- apiGroups: + - apiextensions.k8s.io.cybergarage.org + resources: + - puzzledbs/status + verbs: + - get diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 10fef44..fe51833 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -1,15 +1,32 @@ +--- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: - labels: - app.kubernetes.io/name: clusterrole - app.kubernetes.io/instance: manager-role - app.kubernetes.io/component: rbac - app.kubernetes.io/created-by: puzzledb-operator - app.kubernetes.io/part-of: puzzledb-operator - app.kubernetes.io/managed-by: kustomize name: manager-role rules: -- apiGroups: [""] - resources: ["pods"] - verbs: ["get", "list", "watch"] +- apiGroups: + - apiextensions.k8s.io.cybergarage.org + resources: + - puzzledbs + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - apiextensions.k8s.io.cybergarage.org + resources: + - puzzledbs/finalizers + verbs: + - update +- apiGroups: + - apiextensions.k8s.io.cybergarage.org + resources: + - puzzledbs/status + verbs: + - get + - patch + - update diff --git a/config/samples/apiextensions.k8s.io_v1_puzzledb.yaml b/config/samples/apiextensions.k8s.io_v1_puzzledb.yaml new file mode 100644 index 0000000..1f05c7e --- /dev/null +++ b/config/samples/apiextensions.k8s.io_v1_puzzledb.yaml @@ -0,0 +1,12 @@ +apiVersion: apiextensions.k8s.io.cybergarage.org/v1 +kind: PuzzleDB +metadata: + labels: + app.kubernetes.io/name: puzzledb + app.kubernetes.io/instance: puzzledb-sample + app.kubernetes.io/part-of: puzzledb-operator + app.kubernetes.io/managed-by: kustomize + app.kubernetes.io/created-by: puzzledb-operator + name: puzzledb-sample +spec: + # TODO(user): Add fields here diff --git a/config/samples/kustomization.yaml b/config/samples/kustomization.yaml new file mode 100644 index 0000000..b7ebed8 --- /dev/null +++ b/config/samples/kustomization.yaml @@ -0,0 +1,4 @@ +## Append samples of your project ## +resources: +- apiextensions.k8s.io_v1_puzzledb.yaml +#+kubebuilder:scaffold:manifestskustomizesamples diff --git a/internal/controller/puzzledb_controller.go b/internal/controller/puzzledb_controller.go new file mode 100644 index 0000000..1a29a36 --- /dev/null +++ b/internal/controller/puzzledb_controller.go @@ -0,0 +1,62 @@ +/* +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 controller + +import ( + "context" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" + + apiextensionsk8siov1 "github.com/cybergarage/puzzledb-operator/api/v1" +) + +// PuzzleDBReconciler reconciles a PuzzleDB object +type PuzzleDBReconciler struct { + client.Client + Scheme *runtime.Scheme +} + +//+kubebuilder:rbac:groups=apiextensions.k8s.io.cybergarage.org,resources=puzzledbs,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=apiextensions.k8s.io.cybergarage.org,resources=puzzledbs/status,verbs=get;update;patch +//+kubebuilder:rbac:groups=apiextensions.k8s.io.cybergarage.org,resources=puzzledbs/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. +// TODO(user): Modify the Reconcile function to compare the state specified by +// the PuzzleDB object against the actual cluster state, and then +// perform operations to make the cluster state reflect the state specified by +// the user. +// +// For more details, check Reconcile and its Result here: +// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.16.3/pkg/reconcile +func (r *PuzzleDBReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + _ = log.FromContext(ctx) + + // TODO(user): your logic here + + return ctrl.Result{}, nil +} + +// SetupWithManager sets up the controller with the Manager. +func (r *PuzzleDBReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + For(&apiextensionsk8siov1.PuzzleDB{}). + Complete(r) +} diff --git a/internal/controller/puzzledb_controller_test.go b/internal/controller/puzzledb_controller_test.go new file mode 100644 index 0000000..a0427e8 --- /dev/null +++ b/internal/controller/puzzledb_controller_test.go @@ -0,0 +1,84 @@ +/* +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 controller + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + apiextensionsk8siov1 "github.com/cybergarage/puzzledb-operator/api/v1" +) + +var _ = Describe("PuzzleDB Controller", func() { + Context("When reconciling a resource", func() { + const resourceName = "test-resource" + + ctx := context.Background() + + typeNamespacedName := types.NamespacedName{ + Name: resourceName, + Namespace: "default", // TODO(user):Modify as needed + } + puzzledb := &apiextensionsk8siov1.PuzzleDB{} + + BeforeEach(func() { + By("creating the custom resource for the Kind PuzzleDB") + err := k8sClient.Get(ctx, typeNamespacedName, puzzledb) + if err != nil && errors.IsNotFound(err) { + resource := &apiextensionsk8siov1.PuzzleDB{ + ObjectMeta: metav1.ObjectMeta{ + Name: resourceName, + Namespace: "default", + }, + // TODO(user): Specify other spec details if needed. + } + Expect(k8sClient.Create(ctx, resource)).To(Succeed()) + } + }) + + AfterEach(func() { + // TODO(user): Cleanup logic after each test, like removing the resource instance. + resource := &apiextensionsk8siov1.PuzzleDB{} + err := k8sClient.Get(ctx, typeNamespacedName, resource) + Expect(err).NotTo(HaveOccurred()) + + By("Cleanup the specific resource instance PuzzleDB") + Expect(k8sClient.Delete(ctx, resource)).To(Succeed()) + }) + It("should successfully reconcile the resource", func() { + By("Reconciling the created resource") + controllerReconciler := &PuzzleDBReconciler{ + Client: k8sClient, + Scheme: k8sClient.Scheme(), + } + + _, err := controllerReconciler.Reconcile(ctx, reconcile.Request{ + NamespacedName: typeNamespacedName, + }) + Expect(err).NotTo(HaveOccurred()) + // TODO(user): Add more specific assertions depending on your controller's reconciliation logic. + // Example: If you expect a certain status condition after reconciliation, verify it here. + }) + }) +}) diff --git a/internal/controller/suite_test.go b/internal/controller/suite_test.go new file mode 100644 index 0000000..81d2ffc --- /dev/null +++ b/internal/controller/suite_test.go @@ -0,0 +1,90 @@ +/* +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 controller + +import ( + "fmt" + "path/filepath" + "runtime" + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + apiextensionsk8siov1 "github.com/cybergarage/puzzledb-operator/api/v1" + //+kubebuilder:scaffold:imports +) + +// These tests use Ginkgo (BDD-style Go testing framework). Refer to +// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. + +var cfg *rest.Config +var k8sClient client.Client +var testEnv *envtest.Environment + +func TestControllers(t *testing.T) { + RegisterFailHandler(Fail) + + RunSpecs(t, "Controller Suite") +} + +var _ = BeforeSuite(func() { + logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) + + By("bootstrapping test environment") + testEnv = &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")}, + ErrorIfCRDPathMissing: true, + + // The BinaryAssetsDirectory is only required if you want to run the tests directly + // without call the makefile target test. If not informed it will look for the + // default path defined in controller-runtime which is /usr/local/kubebuilder/. + // Note that you must have the required binaries setup under the bin directory to perform + // the tests directly. When we run make test it will be setup and used automatically. + BinaryAssetsDirectory: filepath.Join("..", "..", "bin", "k8s", + fmt.Sprintf("1.28.3-%s-%s", runtime.GOOS, runtime.GOARCH)), + } + + var err error + // cfg is defined in this file globally. + cfg, err = testEnv.Start() + Expect(err).NotTo(HaveOccurred()) + Expect(cfg).NotTo(BeNil()) + + err = apiextensionsk8siov1.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + + //+kubebuilder:scaffold:scheme + + k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) + Expect(err).NotTo(HaveOccurred()) + Expect(k8sClient).NotTo(BeNil()) + +}) + +var _ = AfterSuite(func() { + By("tearing down the test environment") + err := testEnv.Stop() + Expect(err).NotTo(HaveOccurred()) +})