From 2dade5cd7d501b26d254215ee9ad5d6c91038550 Mon Sep 17 00:00:00 2001 From: Subba Gontla Date: Mon, 15 Dec 2025 23:28:09 +0000 Subject: [PATCH] - New CRD for KVService --- PROJECT | 13 ++ api/v4/kvservice_types.go | 92 +++++++++++++ api/v4/zz_generated.deepcopy.go | 102 ++++++++++++++ cmd/main.go | 17 ++- .../enterprise.splunk.com_kvservices.yaml | 126 ++++++++++++++++++ config/crd/kustomization.yaml | 1 + config/rbac/kustomization.yaml | 9 +- config/rbac/kvservice_admin_role.yaml | 27 ++++ config/rbac/kvservice_editor_role.yaml | 33 +++++ config/rbac/kvservice_viewer_role.yaml | 29 ++++ config/rbac/role.yaml | 26 ++++ config/samples/kustomization.yaml | 1 + config/samples/v4_kvservice.yaml | 9 ++ go.sum | 2 - internal/controller/kvservice_controller.go | 63 +++++++++ .../controller/kvservice_controller_test.go | 84 ++++++++++++ internal/controller/suite_test.go | 5 + 17 files changed, 633 insertions(+), 6 deletions(-) create mode 100644 api/v4/kvservice_types.go create mode 100644 config/crd/bases/enterprise.splunk.com_kvservices.yaml create mode 100644 config/rbac/kvservice_admin_role.yaml create mode 100644 config/rbac/kvservice_editor_role.yaml create mode 100644 config/rbac/kvservice_viewer_role.yaml create mode 100644 config/samples/v4_kvservice.yaml create mode 100644 internal/controller/kvservice_controller.go create mode 100644 internal/controller/kvservice_controller_test.go diff --git a/PROJECT b/PROJECT index 62abf2007..3f2c1204c 100644 --- a/PROJECT +++ b/PROJECT @@ -1,6 +1,11 @@ +# Code generated by tool. DO NOT EDIT. +# This file is used to track the info used to scaffold your project +# and allow the plugins properly work. +# More info: https://book.kubebuilder.io/reference/project-config.html domain: splunk.com layout: - go.kubebuilder.io/v4 +multigroup: true plugins: manifests.sdk.operatorframework.io/v2: {} scorecard.sdk.operatorframework.io/v2: {} @@ -109,4 +114,12 @@ resources: kind: LicenseManager path: github.com/splunk/splunk-operator/api/v4 version: v4 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: splunk.com + kind: KVService + path: github.com/splunk/splunk-operator/api/v4 + version: v4 version: "3" diff --git a/api/v4/kvservice_types.go b/api/v4/kvservice_types.go new file mode 100644 index 000000000..5953910fc --- /dev/null +++ b/api/v4/kvservice_types.go @@ -0,0 +1,92 @@ +/* +Copyright 2021. + +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 v4 + +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. + +// KVServiceSpec defines the desired state of KVService +type KVServiceSpec struct { + // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster + // Important: Run "make" to regenerate code after modifying this file + // The following markers will use OpenAPI v3 schema to validate the value + // More info: https://book.kubebuilder.io/reference/markers/crd-validation.html + + // foo is an example field of KVService. Edit kvservice_types.go to remove/update + // +optional + Foo *string `json:"foo,omitempty"` +} + +// KVServiceStatus defines the observed state of KVService. +type KVServiceStatus struct { + // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster + // Important: Run "make" to regenerate code after modifying this file + + // For Kubernetes API conventions, see: + // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties + + // conditions represent the current state of the KVService resource. + // Each condition has a unique type and reflects the status of a specific aspect of the resource. + // + // Standard condition types include: + // - "Available": the resource is fully functional + // - "Progressing": the resource is being created or updated + // - "Degraded": the resource failed to reach or maintain its desired state + // + // The status of each condition is one of True, False, or Unknown. + // +listType=map + // +listMapKey=type + // +optional + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// KVService is the Schema for the kvservices API +type KVService struct { + metav1.TypeMeta `json:",inline"` + + // metadata is a standard object metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitzero"` + + // spec defines the desired state of KVService + // +required + Spec KVServiceSpec `json:"spec"` + + // status defines the observed state of KVService + // +optional + Status KVServiceStatus `json:"status,omitzero"` +} + +// +kubebuilder:object:root=true + +// KVServiceList contains a list of KVService +type KVServiceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitzero"` + Items []KVService `json:"items"` +} + +func init() { + SchemeBuilder.Register(&KVService{}, &KVServiceList{}) +} diff --git a/api/v4/zz_generated.deepcopy.go b/api/v4/zz_generated.deepcopy.go index 93e988463..a26538439 100644 --- a/api/v4/zz_generated.deepcopy.go +++ b/api/v4/zz_generated.deepcopy.go @@ -22,6 +22,7 @@ package v4 import ( "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) @@ -555,6 +556,107 @@ func (in *IndexerClusterStatus) DeepCopy() *IndexerClusterStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KVService) DeepCopyInto(out *KVService) { + *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 KVService. +func (in *KVService) DeepCopy() *KVService { + if in == nil { + return nil + } + out := new(KVService) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *KVService) 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 *KVServiceList) DeepCopyInto(out *KVServiceList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]KVService, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KVServiceList. +func (in *KVServiceList) DeepCopy() *KVServiceList { + if in == nil { + return nil + } + out := new(KVServiceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *KVServiceList) 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 *KVServiceSpec) DeepCopyInto(out *KVServiceSpec) { + *out = *in + if in.Foo != nil { + in, out := &in.Foo, &out.Foo + *out = new(string) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KVServiceSpec. +func (in *KVServiceSpec) DeepCopy() *KVServiceSpec { + if in == nil { + return nil + } + out := new(KVServiceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KVServiceStatus) DeepCopyInto(out *KVServiceStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KVServiceStatus. +func (in *KVServiceStatus) DeepCopy() *KVServiceStatus { + if in == nil { + return nil + } + out := new(KVServiceStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LicenseManager) DeepCopyInto(out *LicenseManager) { *out = *in diff --git a/cmd/main.go b/cmd/main.go index 6a152ce16..31c89a313 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -23,10 +23,11 @@ import ( "os" "time" + "sigs.k8s.io/controller-runtime/pkg/metrics/filters" + intController "github.com/splunk/splunk-operator/internal/controller" "github.com/splunk/splunk-operator/internal/controller/debug" "github.com/splunk/splunk-operator/pkg/config" - "sigs.k8s.io/controller-runtime/pkg/metrics/filters" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. @@ -47,6 +48,8 @@ import ( enterpriseApiV3 "github.com/splunk/splunk-operator/api/v3" enterpriseApi "github.com/splunk/splunk-operator/api/v4" + splunkcomv4 "github.com/splunk/splunk-operator/api/v4" + "github.com/splunk/splunk-operator/internal/controller" //+kubebuilder:scaffold:imports //extapi "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" ) @@ -60,6 +63,7 @@ func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(enterpriseApi.AddToScheme(scheme)) utilruntime.Must(enterpriseApiV3.AddToScheme(scheme)) + utilruntime.Must(splunkcomv4.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme //utilruntime.Must(extapi.AddToScheme(scheme)) } @@ -107,11 +111,11 @@ func main() { // as certificates issued by a trusted Certificate Authority (CA). The primary risk is potentially allowing // unauthorized access to sensitive metrics data. Consider replacing with CertDir, CertName, and KeyName // to provide certificates, ensuring the server communicates using trusted and secure certificates. - TLSOpts: tlsOpts, + TLSOpts: tlsOpts, FilterProvider: filters.WithAuthenticationAndAuthorization, } - // TODO: enable https for /metrics endpoint by default + // TODO: enable https for /metrics endpoint by default // if secureMetrics { // // FilterProvider is used to protect the metrics endpoint with authn/authz. // // These configurations ensure that only authorized users and service accounts @@ -221,6 +225,13 @@ func main() { setupLog.Error(err, "unable to create controller", "controller", "Standalone") os.Exit(1) } + if err := (&controller.KVServiceReconciler{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "KVService") + os.Exit(1) + } //+kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/config/crd/bases/enterprise.splunk.com_kvservices.yaml b/config/crd/bases/enterprise.splunk.com_kvservices.yaml new file mode 100644 index 000000000..dfebb43e7 --- /dev/null +++ b/config/crd/bases/enterprise.splunk.com_kvservices.yaml @@ -0,0 +1,126 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.16.1 + name: kvservices.enterprise.splunk.com +spec: + group: enterprise.splunk.com + names: + kind: KVService + listKind: KVServiceList + plural: kvservices + singular: kvservice + scope: Namespaced + versions: + - name: v4 + schema: + openAPIV3Schema: + description: KVService is the Schema for the kvservices 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: spec defines the desired state of KVService + properties: + foo: + description: foo is an example field of KVService. Edit kvservice_types.go + to remove/update + type: string + type: object + status: + description: status defines the observed state of KVService + properties: + conditions: + description: |- + conditions represent the current state of the KVService resource. + Each condition has a unique type and reflects the status of a specific aspect of the resource. + + Standard condition types include: + - "Available": the resource is fully functional + - "Progressing": the resource is being created or updated + - "Degraded": the resource failed to reach or maintain its desired state + + The status of each condition is one of True, False, or Unknown. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index dd0d870ec..34d64aeb1 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -10,6 +10,7 @@ resources: - bases/enterprise.splunk.com_monitoringconsoles.yaml - bases/enterprise.splunk.com_searchheadclusters.yaml - bases/enterprise.splunk.com_standalones.yaml +- bases/splunk.com_kvservices.yaml #+kubebuilder:scaffold:crdkustomizeresource diff --git a/config/rbac/kustomization.yaml b/config/rbac/kustomization.yaml index 3577dde2a..3ec5bfc89 100644 --- a/config/rbac/kustomization.yaml +++ b/config/rbac/kustomization.yaml @@ -17,4 +17,11 @@ resources: # More info: https://book.kubebuilder.io/reference/metrics.html - metrics_auth_role.yaml - metrics_auth_role_binding.yaml -- metrics_reader_role.yaml \ No newline at end of file +- metrics_reader_role.yaml# For each CRD, "Admin", "Editor" and "Viewer" roles are scaffolded by +# default, aiding admins in cluster management. Those roles are +# not used by the splunk-operator itself. You can comment the following lines +# if you do not want those helpers be installed with your Project. +- kvservice_admin_role.yaml +- kvservice_editor_role.yaml +- kvservice_viewer_role.yaml + diff --git a/config/rbac/kvservice_admin_role.yaml b/config/rbac/kvservice_admin_role.yaml new file mode 100644 index 000000000..e5a7e6cf3 --- /dev/null +++ b/config/rbac/kvservice_admin_role.yaml @@ -0,0 +1,27 @@ +# This rule is not used by the project splunk-operator itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants full permissions ('*') over splunk.com. +# This role is intended for users authorized to modify roles and bindings within the cluster, +# enabling them to delegate specific permissions to other users or groups as needed. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: splunk-operator + app.kubernetes.io/managed-by: kustomize + name: kvservice-admin-role +rules: +- apiGroups: + - splunk.com + resources: + - kvservices + verbs: + - '*' +- apiGroups: + - splunk.com + resources: + - kvservices/status + verbs: + - get diff --git a/config/rbac/kvservice_editor_role.yaml b/config/rbac/kvservice_editor_role.yaml new file mode 100644 index 000000000..385de7b87 --- /dev/null +++ b/config/rbac/kvservice_editor_role.yaml @@ -0,0 +1,33 @@ +# This rule is not used by the project splunk-operator itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants permissions to create, update, and delete resources within the splunk.com. +# This role is intended for users who need to manage these resources +# but should not control RBAC or manage permissions for others. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: splunk-operator + app.kubernetes.io/managed-by: kustomize + name: kvservice-editor-role +rules: +- apiGroups: + - splunk.com + resources: + - kvservices + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - splunk.com + resources: + - kvservices/status + verbs: + - get diff --git a/config/rbac/kvservice_viewer_role.yaml b/config/rbac/kvservice_viewer_role.yaml new file mode 100644 index 000000000..831537a91 --- /dev/null +++ b/config/rbac/kvservice_viewer_role.yaml @@ -0,0 +1,29 @@ +# This rule is not used by the project splunk-operator itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants read-only access to splunk.com resources. +# This role is intended for users who need visibility into these resources +# without permissions to modify them. It is ideal for monitoring purposes and limited-access viewing. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: splunk-operator + app.kubernetes.io/managed-by: kustomize + name: kvservice-viewer-role +rules: +- apiGroups: + - splunk.com + resources: + - kvservices + verbs: + - get + - list + - watch +- apiGroups: + - splunk.com + resources: + - kvservices/status + verbs: + - get diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 2f9c5122c..07bc72676 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -91,3 +91,29 @@ rules: - get - patch - update +- apiGroups: + - splunk.com + resources: + - kvservices + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - splunk.com + resources: + - kvservices/finalizers + verbs: + - update +- apiGroups: + - splunk.com + resources: + - kvservices/status + verbs: + - get + - patch + - update diff --git a/config/samples/kustomization.yaml b/config/samples/kustomization.yaml index 73c6d3649..cb644b0fe 100644 --- a/config/samples/kustomization.yaml +++ b/config/samples/kustomization.yaml @@ -13,4 +13,5 @@ resources: - enterprise_v4_searchheadcluster.yaml - enterprise_v4_clustermanager.yaml - enterprise_v4_licensemanager.yaml +- v4_kvservice.yaml #+kubebuilder:scaffold:manifestskustomizesamples diff --git a/config/samples/v4_kvservice.yaml b/config/samples/v4_kvservice.yaml new file mode 100644 index 000000000..839e01bcf --- /dev/null +++ b/config/samples/v4_kvservice.yaml @@ -0,0 +1,9 @@ +apiVersion: splunk.com/v4 +kind: KVService +metadata: + labels: + app.kubernetes.io/name: splunk-operator + app.kubernetes.io/managed-by: kustomize + name: kvservice-sample +spec: + # TODO(user): Add fields here diff --git a/go.sum b/go.sum index 107db504c..fb8222b1e 100644 --- a/go.sum +++ b/go.sum @@ -370,8 +370,6 @@ golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs= -golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/oauth2 v0.27.0 h1:da9Vo7/tDv5RH/7nZDz1eMGS/q1Vv1N/7FCrBhI9I3M= golang.org/x/oauth2 v0.27.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/internal/controller/kvservice_controller.go b/internal/controller/kvservice_controller.go new file mode 100644 index 000000000..4cb407b82 --- /dev/null +++ b/internal/controller/kvservice_controller.go @@ -0,0 +1,63 @@ +/* +Copyright 2021. + +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" + logf "sigs.k8s.io/controller-runtime/pkg/log" + + splunkcomv4 "github.com/splunk/splunk-operator/api/v4" +) + +// KVServiceReconciler reconciles a KVService object +type KVServiceReconciler struct { + client.Client + Scheme *runtime.Scheme +} + +// +kubebuilder:rbac:groups=splunk.com,resources=kvservices,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=splunk.com,resources=kvservices/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=splunk.com,resources=kvservices/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 KVService 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.22.4/pkg/reconcile +func (r *KVServiceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + _ = logf.FromContext(ctx) + + // TODO(user): your logic here + + return ctrl.Result{}, nil +} + +// SetupWithManager sets up the controller with the Manager. +func (r *KVServiceReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + For(&splunkcomv4.KVService{}). + Named("kvservice"). + Complete(r) +} diff --git a/internal/controller/kvservice_controller_test.go b/internal/controller/kvservice_controller_test.go new file mode 100644 index 000000000..597990287 --- /dev/null +++ b/internal/controller/kvservice_controller_test.go @@ -0,0 +1,84 @@ +/* +Copyright 2021. + +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" + + splunkcomv4 "github.com/splunk/splunk-operator/api/v4" +) + +var _ = Describe("KVService 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 + } + kvservice := &splunkcomv4.KVService{} + + BeforeEach(func() { + By("creating the custom resource for the Kind KVService") + err := k8sClient.Get(ctx, typeNamespacedName, kvservice) + if err != nil && errors.IsNotFound(err) { + resource := &splunkcomv4.KVService{ + 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 := &splunkcomv4.KVService{} + err := k8sClient.Get(ctx, typeNamespacedName, resource) + Expect(err).NotTo(HaveOccurred()) + + By("Cleanup the specific resource instance KVService") + Expect(k8sClient.Delete(ctx, resource)).To(Succeed()) + }) + It("should successfully reconcile the resource", func() { + By("Reconciling the created resource") + controllerReconciler := &KVServiceReconciler{ + 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 index be2c1a50f..9c7408ee3 100644 --- a/internal/controller/suite_test.go +++ b/internal/controller/suite_test.go @@ -33,11 +33,13 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" + "k8s.io/client-go/kubernetes/scheme" clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" enterpriseApiV3 "github.com/splunk/splunk-operator/api/v3" enterpriseApi "github.com/splunk/splunk-operator/api/v4" + splunkcomv4 "github.com/splunk/splunk-operator/api/v4" //+kubebuilder:scaffold:imports ) @@ -92,6 +94,9 @@ var _ = BeforeSuite(func(ctx context.Context) { err = enterpriseApi.AddToScheme(clientgoscheme.Scheme) Expect(err).NotTo(HaveOccurred()) + err = splunkcomv4.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + //+kubebuilder:scaffold:scheme // Create New Manager for controller