diff --git a/PROJECT b/PROJECT index 62abf2007..da48e2f34 100644 --- a/PROJECT +++ b/PROJECT @@ -1,3 +1,7 @@ +# 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 @@ -109,4 +113,13 @@ resources: kind: LicenseManager path: github.com/splunk/splunk-operator/api/v4 version: v4 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: splunk.com + group: enterprise + 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..30318baee --- /dev/null +++ b/api/v4/kvservice_types.go @@ -0,0 +1,70 @@ +/* +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. + +const ( + // KVServicePausedAnnotation is the annotation that pauses the reconciliation (triggers + // an immediate requeue) + KVServicePausedAnnotation = "kvservice.enterprise.splunk.com/paused" +) + +// 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 + + // Foo is an example field of KVService. Edit kvservice_types.go to remove/update + 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 +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// KVService is the Schema for the kvservices API +type KVService struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec KVServiceSpec `json:"spec,omitempty"` + Status KVServiceStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// KVServiceList contains a list of KVService +type KVServiceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + 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..498a2c2ec 100644 --- a/api/v4/zz_generated.deepcopy.go +++ b/api/v4/zz_generated.deepcopy.go @@ -555,6 +555,95 @@ 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) + out.Spec = in.Spec + out.Status = in.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 +} + +// 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 +} + +// 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 f8aba0ae1..59a9e1ae7 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" + enterprisev4 "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(enterprisev4.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme //utilruntime.Must(extapi.AddToScheme(scheme)) } @@ -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..635df3459 --- /dev/null +++ b/config/crd/bases/enterprise.splunk.com_kvservices.yaml @@ -0,0 +1,54 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.18.0 + 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: KVServiceSpec 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: KVServiceStatus defines the observed state of KVService + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index dd0d870ec..1b6f7d070 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/enterprise.splunk.com_kvservices.yaml #+kubebuilder:scaffold:crdkustomizeresource @@ -37,6 +38,7 @@ patchesStrategicMerge: #- patches/cainjection_in_monitoringconsoles.yaml #- patches/cainjection_in_searchheadclusters.yaml #- patches/cainjection_in_standalones.yaml +#- path: patches/cainjection_in_kvservices.yaml #+kubebuilder:scaffold:crdkustomizecainjectionpatch # the following config is for teaching kustomize how to do kustomization for CRDs. diff --git a/config/rbac/kustomization.yaml b/config/rbac/kustomization.yaml index 3577dde2a..e1be2f4c7 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, "Editor" and "Viewer" roles are scaffolded by +# default, aiding admins in cluster management. Those roles are +# not used by the Project itself. You can comment the following lines +# if you do not want those helpers be installed with your Project. +- kvservice_editor_role.yaml +- kvservice_viewer_role.yaml + diff --git a/config/rbac/kvservice_editor_role.yaml b/config/rbac/kvservice_editor_role.yaml new file mode 100644 index 000000000..45fb94780 --- /dev/null +++ b/config/rbac/kvservice_editor_role.yaml @@ -0,0 +1,27 @@ +# permissions for end users to edit kvservices. +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: + - enterprise.splunk.com + resources: + - kvservices + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - enterprise.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..c3f9ccdad --- /dev/null +++ b/config/rbac/kvservice_viewer_role.yaml @@ -0,0 +1,23 @@ +# permissions for end users to view kvservices. +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: + - enterprise.splunk.com + resources: + - kvservices + verbs: + - get + - list + - watch +- apiGroups: + - enterprise.splunk.com + resources: + - kvservices/status + verbs: + - get diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 1bbc2427e..1943def1d 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -50,6 +50,7 @@ rules: - clustermanagers - clustermasters - indexerclusters + - kvservices - licensemanagers - licensemasters - monitoringconsoles @@ -69,6 +70,7 @@ rules: - clustermanagers/finalizers - clustermasters/finalizers - indexerclusters/finalizers + - kvservices/finalizers - licensemanagers/finalizers - licensemasters/finalizers - monitoringconsoles/finalizers @@ -82,6 +84,7 @@ rules: - clustermanagers/status - clustermasters/status - indexerclusters/status + - kvservices/status - licensemanagers/status - licensemasters/status - monitoringconsoles/status diff --git a/config/samples/enterprise_v4_kvservice.yaml b/config/samples/enterprise_v4_kvservice.yaml new file mode 100644 index 000000000..3b8c1bbd0 --- /dev/null +++ b/config/samples/enterprise_v4_kvservice.yaml @@ -0,0 +1,9 @@ +apiVersion: enterprise.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/config/samples/kustomization.yaml b/config/samples/kustomization.yaml index 73c6d3649..08e3fdb6e 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 +- enterprise_v4_kvservice.yaml #+kubebuilder:scaffold:manifestskustomizesamples diff --git a/helm-chart/splunk-operator/templates/rbac/kvservice_editor_role.yaml b/helm-chart/splunk-operator/templates/rbac/kvservice_editor_role.yaml new file mode 100644 index 000000000..45fb94780 --- /dev/null +++ b/helm-chart/splunk-operator/templates/rbac/kvservice_editor_role.yaml @@ -0,0 +1,27 @@ +# permissions for end users to edit kvservices. +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: + - enterprise.splunk.com + resources: + - kvservices + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - enterprise.splunk.com + resources: + - kvservices/status + verbs: + - get diff --git a/helm-chart/splunk-operator/templates/rbac/kvservice_viewer_role.yaml b/helm-chart/splunk-operator/templates/rbac/kvservice_viewer_role.yaml new file mode 100644 index 000000000..c3f9ccdad --- /dev/null +++ b/helm-chart/splunk-operator/templates/rbac/kvservice_viewer_role.yaml @@ -0,0 +1,23 @@ +# permissions for end users to view kvservices. +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: + - enterprise.splunk.com + resources: + - kvservices + verbs: + - get + - list + - watch +- apiGroups: + - enterprise.splunk.com + resources: + - kvservices/status + verbs: + - get diff --git a/helm-chart/splunk-operator/templates/rbac/role.yaml b/helm-chart/splunk-operator/templates/rbac/role.yaml index 2a2869654..893922e5b 100644 --- a/helm-chart/splunk-operator/templates/rbac/role.yaml +++ b/helm-chart/splunk-operator/templates/rbac/role.yaml @@ -1,3 +1,4 @@ +--- {{- if not .Values.splunkOperator.clusterWideAccess }} apiVersion: rbac.authorization.k8s.io/v1 kind: Role @@ -5,136 +6,18 @@ metadata: creationTimestamp: null name: {{ include "splunk-operator.operator.fullname" . }}-manager-role rules: -- apiGroups: - - apiextensions.k8s.io - resources: - - customresourcedefinitions - verbs: - - get - - list -- apiGroups: - - apps - resources: - - statefulsets - verbs: - - create - - delete - - get - - list - - patch - - update - - watch - apiGroups: - "" resources: - configmaps - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - endpoints - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - events - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - persistentvolumeclaims - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - pods - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - pods/exec - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - secrets - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - serviceaccounts - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - services - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - services/finalizers verbs: - create @@ -145,61 +28,16 @@ rules: - update - watch - apiGroups: - - enterprise.splunk.com + - apiextensions.k8s.io resources: - - clustermasters + - customresourcedefinitions verbs: - - create - - delete - get - list - - patch - - update - - watch -- apiGroups: - - enterprise.splunk.com - resources: - - clustermasters/finalizers - verbs: - - update -- apiGroups: - - enterprise.splunk.com - resources: - - clustermasters/status - verbs: - - get - - patch - - update - apiGroups: - - enterprise.splunk.com - resources: - - clustermanagers - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - enterprise.splunk.com - resources: - - clustermanagers/finalizers - verbs: - - update -- apiGroups: - - enterprise.splunk.com - resources: - - clustermanagers/status - verbs: - - get - - patch - - update -- apiGroups: - - enterprise.splunk.com + - apps resources: - - indexerclusters + - statefulsets verbs: - create - delete @@ -211,124 +49,14 @@ rules: - apiGroups: - enterprise.splunk.com resources: - - indexerclusters/finalizers - verbs: - - update -- apiGroups: - - enterprise.splunk.com - resources: - - indexerclusters/status - verbs: - - get - - patch - - update -- apiGroups: - - enterprise.splunk.com - resources: + - clustermanagers + - clustermasters + - indexerclusters + - kvservices + - licensemanagers - licensemasters - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - enterprise.splunk.com - resources: - - licensemasters/finalizers - verbs: - - update -- apiGroups: - - enterprise.splunk.com - resources: - - licensemasters/status - verbs: - - get - - patch - - update -- apiGroups: - - enterprise.splunk.com - resources: - - licensemanagers - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - enterprise.splunk.com - resources: - - licensemanagers/finalizers - verbs: - - update -- apiGroups: - - enterprise.splunk.com - resources: - - licensemanagers/status - verbs: - - get - - patch - - update -- apiGroups: - - enterprise.splunk.com - resources: - monitoringconsoles - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - enterprise.splunk.com - resources: - - monitoringconsoles/finalizers - verbs: - - update -- apiGroups: - - enterprise.splunk.com - resources: - - monitoringconsoles/status - verbs: - - get - - patch - - update -- apiGroups: - - enterprise.splunk.com - resources: - searchheadclusters - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - enterprise.splunk.com - resources: - - searchheadclusters/finalizers - verbs: - - update -- apiGroups: - - enterprise.splunk.com - resources: - - searchheadclusters/status - verbs: - - get - - patch - - update -- apiGroups: - - enterprise.splunk.com - resources: - standalones verbs: - create @@ -341,12 +69,28 @@ rules: - apiGroups: - enterprise.splunk.com resources: + - clustermanagers/finalizers + - clustermasters/finalizers + - indexerclusters/finalizers + - kvservices/finalizers + - licensemanagers/finalizers + - licensemasters/finalizers + - monitoringconsoles/finalizers + - searchheadclusters/finalizers - standalones/finalizers verbs: - update - apiGroups: - enterprise.splunk.com resources: + - clustermanagers/status + - clustermasters/status + - indexerclusters/status + - kvservices/status + - licensemanagers/status + - licensemasters/status + - monitoringconsoles/status + - searchheadclusters/status - standalones/status verbs: - get diff --git a/internal/controller/kvservice_controller.go b/internal/controller/kvservice_controller.go new file mode 100644 index 000000000..99cd5e1aa --- /dev/null +++ b/internal/controller/kvservice_controller.go @@ -0,0 +1,148 @@ +/* +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" + "time" + + "github.com/pkg/errors" + enterprisev4 "github.com/splunk/splunk-operator/api/v4" + "github.com/splunk/splunk-operator/internal/controller/common" + metrics "github.com/splunk/splunk-operator/pkg/splunk/client/metrics" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/predicate" +) + +// KVServiceReconciler reconciles a KVService object +type KVServiceReconciler struct { + client.Client + Scheme *runtime.Scheme +} + +//+kubebuilder:rbac:groups=apiextensions.k8s.io,resources=customresourcedefinitions,verbs=get;list +//+kubebuilder:rbac:groups=core,resources=services,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=services/finalizers,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=serviceaccounts,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=endpoints,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=pods/exec,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=events,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=get;list;watch;create;update;patch;delete + +// +kubebuilder:rbac:groups=enterprise.splunk.com,resources=kvservices,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=enterprise.splunk.com,resources=kvservices/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=enterprise.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.19.0/pkg/reconcile +func (r *KVServiceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + metrics.ReconcileCounters.With(metrics.GetPrometheusLabels(req, "KVService")).Inc() + defer recordInstrumentionData(time.Now(), req, "controller", "KVService") + + reqLogger := log.FromContext(ctx) + reqLogger = reqLogger.WithValues("kvservice", req.NamespacedName) + + // Fetch the KVService + instance := &enterprisev4.KVService{} + err := r.Get(ctx, req.NamespacedName, instance) + if err != nil { + if k8serrors.IsNotFound(err) { + // Request object not found, could have been deleted after + // reconcile request. Owned objects are automatically + // garbage collected. For additional cleanup logic use + // finalizers. Return and don't requeue + return ctrl.Result{}, nil + } + // Error reading the object - requeue the request. + return ctrl.Result{}, errors.Wrap(err, "could not load kvservice data") + } + + // If the reconciliation is paused, requeue + annotations := instance.GetAnnotations() + if annotations != nil { + if _, ok := annotations[enterprisev4.KVServicePausedAnnotation]; ok { + return ctrl.Result{Requeue: true, RequeueAfter: pauseRetryDelay}, nil + } + } + + reqLogger.Info("start", "CR version", instance.GetResourceVersion()) + + // ToDo: Commenting for now, will be implementing in follow-up stories + // result, err := ApplyKVService(ctx, r.Client, instance) + // if result.Requeue && result.RequeueAfter != 0 { + // reqLogger.Info("Requeued", "period(seconds)", int(result.RequeueAfter/time.Second)) + // } + + // return result, err + + return ctrl.Result{}, nil +} + +func (r *KVServiceReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + For(&enterprisev4.KVService{}). + WithEventFilter(predicate.Or( + common.GenerationChangedPredicate(), + common.AnnotationChangedPredicate(), + common.LabelChangedPredicate(), + common.SecretChangedPredicate(), + common.StatefulsetChangedPredicate(), + common.PodChangedPredicate(), + common.ConfigMapChangedPredicate(), + common.CrdChangedPredicate(), + )). + Watches(&corev1.Secret{}, + handler.EnqueueRequestForOwner( + mgr.GetScheme(), + mgr.GetRESTMapper(), + &enterprisev4.KVService{}, + )). + Watches(&corev1.Pod{}, + handler.EnqueueRequestForOwner( + mgr.GetScheme(), + mgr.GetRESTMapper(), + &enterprisev4.KVService{}, + )). + Watches(&corev1.ConfigMap{}, + handler.EnqueueRequestForOwner( + mgr.GetScheme(), + mgr.GetRESTMapper(), + &enterprisev4.KVService{}, + )). + WithOptions(controller.Options{ + MaxConcurrentReconciles: enterprisev4.TotalWorker, + }). + Complete(r) +} diff --git a/internal/controller/kvservice_controller_test.go b/internal/controller/kvservice_controller_test.go new file mode 100644 index 000000000..0dd3b5cfa --- /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" + + enterprisev4 "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 := &enterprisev4.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 := &enterprisev4.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 := &enterprisev4.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..a3ad3170b 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" + enterprisev4 "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 = enterprisev4.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + //+kubebuilder:scaffold:scheme // Create New Manager for controller