From b030c5bd288ecd57bdf828c0792a79605abbae2f Mon Sep 17 00:00:00 2001 From: Sinamcp <50045263+Sinamcp@users.noreply.github.com> Date: Tue, 19 Jul 2022 00:03:31 +0430 Subject: [PATCH] add/grafana-user-controller (#30) * add grafana user controller * fix pipleline error * fix pipleline error1 * fix pipleline error2 * fix logical structure --- Dockerfile | 1 + PROJECT | 10 + .../grafanauser/v1alpha1/grafanauser_types.go | 57 ++++++ .../grafanauser/v1alpha1/groupversion_info.go | 36 ++++ .../v1alpha1/zz_generated.deepcopy.go | 114 ++++++++++++ ...rafanauser.snappcloud.io_grafanausers.yaml | 61 ++++++ config/crd/kustomization.yaml | 21 +++ config/crd/kustomizeconfig.yaml | 19 ++ .../patches/cainjection_in_grafanausers.yaml | 7 + .../crd/patches/webhook_in_grafanausers.yaml | 16 ++ config/rbac/grafanauser_editor_role.yaml | 24 +++ config/rbac/grafanauser_viewer_role.yaml | 20 ++ config/rbac/role.yaml | 62 +++++++ .../grafanauser_v1alpha1_grafanauser.yaml | 12 ++ config/samples/kustomization.yaml | 1 + .../grafanauser/grafanauser_controller.go | 173 ++++++++++++++++++ controllers/grafanauser/suite_test.go | 78 ++++++++ .../{ => namespace}/namespace_controller.go | 0 controllers/{ => namespace}/suite_test.go | 0 go.sum | 5 - main.go | 14 +- 21 files changed, 724 insertions(+), 7 deletions(-) create mode 100644 apis/grafanauser/v1alpha1/grafanauser_types.go create mode 100644 apis/grafanauser/v1alpha1/groupversion_info.go create mode 100644 apis/grafanauser/v1alpha1/zz_generated.deepcopy.go create mode 100644 config/crd/bases/grafanauser.snappcloud.io_grafanausers.yaml create mode 100644 config/crd/kustomization.yaml create mode 100644 config/crd/kustomizeconfig.yaml create mode 100644 config/crd/patches/cainjection_in_grafanausers.yaml create mode 100644 config/crd/patches/webhook_in_grafanausers.yaml create mode 100644 config/rbac/grafanauser_editor_role.yaml create mode 100644 config/rbac/grafanauser_viewer_role.yaml create mode 100644 config/samples/grafanauser_v1alpha1_grafanauser.yaml create mode 100644 controllers/grafanauser/grafanauser_controller.go create mode 100644 controllers/grafanauser/suite_test.go rename controllers/{ => namespace}/namespace_controller.go (100%) rename controllers/{ => namespace}/suite_test.go (100%) diff --git a/Dockerfile b/Dockerfile index 5b6eb09..529aad3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,6 +10,7 @@ COPY go.sum go.sum RUN go mod download # Copy the go source +COPY apis/ apis/ COPY main.go main.go COPY controllers/ controllers/ diff --git a/PROJECT b/PROJECT index 593f1b1..7e733b5 100644 --- a/PROJECT +++ b/PROJECT @@ -1,6 +1,7 @@ domain: snappcloud.io layout: - go.kubebuilder.io/v3 +multigroup: true plugins: manifests.sdk.operatorframework.io/v2: {} scorecard.sdk.operatorframework.io/v2: {} @@ -12,4 +13,13 @@ resources: kind: Namespace path: k8s.io/api/core/v1 version: v1 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: snappcloud.io + group: grafanauser + kind: GrafanaUser + path: github.com/snapp-cab/grafana-complementary-operator/apis/grafanauser/v1alpha1 + version: v1alpha1 version: "3" diff --git a/apis/grafanauser/v1alpha1/grafanauser_types.go b/apis/grafanauser/v1alpha1/grafanauser_types.go new file mode 100644 index 0000000..247ab32 --- /dev/null +++ b/apis/grafanauser/v1alpha1/grafanauser_types.go @@ -0,0 +1,57 @@ +/* +Copyright 2022. + +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" +) + +// 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. + +// GrafanaUserSpec defines the desired state of GrafanaUser +type GrafanaUserSpec struct { + // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster + // Important: Run "make" to regenerate code after modifying this file + + Admin []string `json:"admin,omitempty"` + Edit []string `json:"edit,omitempty"` + View []string `json:"view,omitempty"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status + +// GrafanaUser is the Schema for the grafanausers API +type GrafanaUser struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec GrafanaUserSpec `json:"spec,omitempty"` +} + +//+kubebuilder:object:root=true + +// GrafanaUserList contains a list of GrafanaUser +type GrafanaUserList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []GrafanaUser `json:"items"` +} + +func init() { + SchemeBuilder.Register(&GrafanaUser{}, &GrafanaUserList{}) +} diff --git a/apis/grafanauser/v1alpha1/groupversion_info.go b/apis/grafanauser/v1alpha1/groupversion_info.go new file mode 100644 index 0000000..e9800c2 --- /dev/null +++ b/apis/grafanauser/v1alpha1/groupversion_info.go @@ -0,0 +1,36 @@ +/* +Copyright 2022. + +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 contains API Schema definitions for the grafanauser v1alpha1 API group +//+kubebuilder:object:generate=true +//+groupName=grafanauser.snappcloud.io +package v1alpha1 + +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: "grafanauser.snappcloud.io", Version: "v1alpha1"} + + // 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/apis/grafanauser/v1alpha1/zz_generated.deepcopy.go b/apis/grafanauser/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 0000000..1e7d6a9 --- /dev/null +++ b/apis/grafanauser/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,114 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +/* +Copyright 2022. + +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 v1alpha1 + +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 *GrafanaUser) DeepCopyInto(out *GrafanaUser) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrafanaUser. +func (in *GrafanaUser) DeepCopy() *GrafanaUser { + if in == nil { + return nil + } + out := new(GrafanaUser) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *GrafanaUser) 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 *GrafanaUserList) DeepCopyInto(out *GrafanaUserList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]GrafanaUser, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrafanaUserList. +func (in *GrafanaUserList) DeepCopy() *GrafanaUserList { + if in == nil { + return nil + } + out := new(GrafanaUserList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *GrafanaUserList) 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 *GrafanaUserSpec) DeepCopyInto(out *GrafanaUserSpec) { + *out = *in + if in.Admin != nil { + in, out := &in.Admin, &out.Admin + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Edit != nil { + in, out := &in.Edit, &out.Edit + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.View != nil { + in, out := &in.View, &out.View + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrafanaUserSpec. +func (in *GrafanaUserSpec) DeepCopy() *GrafanaUserSpec { + if in == nil { + return nil + } + out := new(GrafanaUserSpec) + in.DeepCopyInto(out) + return out +} diff --git a/config/crd/bases/grafanauser.snappcloud.io_grafanausers.yaml b/config/crd/bases/grafanauser.snappcloud.io_grafanausers.yaml new file mode 100644 index 0000000..8f81125 --- /dev/null +++ b/config/crd/bases/grafanauser.snappcloud.io_grafanausers.yaml @@ -0,0 +1,61 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.8.0 + creationTimestamp: null + name: grafanausers.grafanauser.snappcloud.io +spec: + group: grafanauser.snappcloud.io + names: + kind: GrafanaUser + listKind: GrafanaUserList + plural: grafanausers + singular: grafanauser + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: GrafanaUser is the Schema for the grafanausers 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: GrafanaUserSpec defines the desired state of GrafanaUser + properties: + admin: + items: + type: string + type: array + edit: + items: + type: string + type: array + view: + items: + type: string + type: array + type: object + type: object + served: true + storage: true + subresources: + status: {} +status: + acceptedNames: + kind: "" + plural: "" + conditions: [] + storedVersions: [] diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml new file mode 100644 index 0000000..f74578e --- /dev/null +++ b/config/crd/kustomization.yaml @@ -0,0 +1,21 @@ +# 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/grafanauser.snappcloud.io_grafanausers.yaml +#+kubebuilder:scaffold:crdkustomizeresource + +patchesStrategicMerge: +# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix. +# patches here are for enabling the conversion webhook for each CRD +#- patches/webhook_in_grafanausers.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 +#- patches/cainjection_in_grafanausers.yaml +#+kubebuilder:scaffold:crdkustomizecainjectionpatch + +# 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/crd/patches/cainjection_in_grafanausers.yaml b/config/crd/patches/cainjection_in_grafanausers.yaml new file mode 100644 index 0000000..ee68ce4 --- /dev/null +++ b/config/crd/patches/cainjection_in_grafanausers.yaml @@ -0,0 +1,7 @@ +# The following patch adds a directive for certmanager to inject CA into the CRD +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) + name: grafanausers.grafanauser.snappcloud.io diff --git a/config/crd/patches/webhook_in_grafanausers.yaml b/config/crd/patches/webhook_in_grafanausers.yaml new file mode 100644 index 0000000..96e6063 --- /dev/null +++ b/config/crd/patches/webhook_in_grafanausers.yaml @@ -0,0 +1,16 @@ +# The following patch enables a conversion webhook for the CRD +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: grafanausers.grafanauser.snappcloud.io +spec: + conversion: + strategy: Webhook + webhook: + clientConfig: + service: + namespace: system + name: webhook-service + path: /convert + conversionReviewVersions: + - v1 diff --git a/config/rbac/grafanauser_editor_role.yaml b/config/rbac/grafanauser_editor_role.yaml new file mode 100644 index 0000000..85f21e4 --- /dev/null +++ b/config/rbac/grafanauser_editor_role.yaml @@ -0,0 +1,24 @@ +# permissions for end users to edit grafanausers. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: grafanauser-editor-role +rules: +- apiGroups: + - grafanauser.snappcloud.io + resources: + - grafanausers + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - grafanauser.snappcloud.io + resources: + - grafanausers/status + verbs: + - get diff --git a/config/rbac/grafanauser_viewer_role.yaml b/config/rbac/grafanauser_viewer_role.yaml new file mode 100644 index 0000000..89af4af --- /dev/null +++ b/config/rbac/grafanauser_viewer_role.yaml @@ -0,0 +1,20 @@ +# permissions for end users to view grafanausers. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: grafanauser-viewer-role +rules: +- apiGroups: + - grafanauser.snappcloud.io + resources: + - grafanausers + verbs: + - get + - list + - watch +- apiGroups: + - grafanauser.snappcloud.io + resources: + - grafanausers/status + verbs: + - get diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index b79c706..17a349c 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -5,6 +5,30 @@ metadata: creationTimestamp: null name: manager-role rules: +- apiGroups: + - "" + resources: + - configmaps + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - "" + resources: + - secrets + verbs: + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - "" resources: @@ -43,6 +67,32 @@ rules: - get - list - watch +- apiGroups: + - grafana.snappcloud.io + resources: + - grafanas + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - grafana.snappcloud.io + resources: + - grafanas/finalizers + verbs: + - update +- apiGroups: + - grafana.snappcloud.io + resources: + - grafanas/status + verbs: + - get + - patch + - update - apiGroups: - integreatly.org resources: @@ -55,3 +105,15 @@ rules: - patch - update - watch +- apiGroups: + - user.openshift.io + resources: + - '*' + verbs: + - create + - delete + - get + - list + - patch + - update + - watch diff --git a/config/samples/grafanauser_v1alpha1_grafanauser.yaml b/config/samples/grafanauser_v1alpha1_grafanauser.yaml new file mode 100644 index 0000000..e49a946 --- /dev/null +++ b/config/samples/grafanauser_v1alpha1_grafanauser.yaml @@ -0,0 +1,12 @@ +apiVersion: grafanauser.snappcloud.io/v1alpha1 +kind: GrafanaUser +metadata: + name: grafanauser-sample + namespace: test +spec: + admin: + - user1 + view: + - user2 + edit: + - user3 diff --git a/config/samples/kustomization.yaml b/config/samples/kustomization.yaml index f57c7cf..ab81745 100644 --- a/config/samples/kustomization.yaml +++ b/config/samples/kustomization.yaml @@ -1,4 +1,5 @@ ## Append samples you want in your CSV to this file as resources ## resources: - core_v1_namespace.yaml +- grafanauser_v1alpha1_grafanauser.yaml #+kubebuilder:scaffold:manifestskustomizesamples diff --git a/controllers/grafanauser/grafanauser_controller.go b/controllers/grafanauser/grafanauser_controller.go new file mode 100644 index 0000000..af0e8cd --- /dev/null +++ b/controllers/grafanauser/grafanauser_controller.go @@ -0,0 +1,173 @@ +/* +Copyright 2022. + +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 grafanauser + +import ( + "context" + "fmt" + "os" + "strings" + + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" + + "github.com/grafana-tools/sdk" + grafanauserv1alpha1 "github.com/snapp-cab/grafana-complementary-operator/apis/grafanauser/v1alpha1" + corev1 "k8s.io/api/core/v1" +) + +const ( + teamLabel = "snappcloud.io/team" +) + +// Get Grafana URL and PassWord as a env. +var grafanaPassword = os.Getenv("GRAFANA_PASSWORD") +var grafanaUsername = os.Getenv("GRAFANA_USERNAME") +var grafanaURL = os.Getenv("GRAFANA_URL") + +// GrafanaReconciler reconciles a Grafana object +type GrafanaUserReconciler struct { + client.Client + Scheme *runtime.Scheme +} + +//+kubebuilder:rbac:groups=grafana.snappcloud.io,resources=grafanas,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=grafana.snappcloud.io,resources=grafanas/status,verbs=get;update;patch +//+kubebuilder:rbac:groups=grafana.snappcloud.io,resources=grafanas/finalizers,verbs=update +//+kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=user.openshift.io,resources=*,verbs=get;list;watch;create;update;patch;delete + +// 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 Grafana 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.9.2/pkg/reconcile +func (r *GrafanaUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := log.FromContext(ctx) + reqLogger := log.WithValues("Request.Namespace", req.Namespace, "Request.Name", req.Name) + // Getting namespace + ns := &corev1.Namespace{} + err := r.Client.Get(context.TODO(), types.NamespacedName{Name: req.Namespace}, ns) + if err != nil { + log.Error(err, "Failed to get namespace") + return ctrl.Result{}, err + } + // Ignore namespaces which does not have team label + org, ok := ns.Labels[teamLabel] + if !ok { + reqLogger.Info("Namespace does not have team label. Ignoring", "namespace", ns.Name, "team name ", org) + return ctrl.Result{}, nil + } + //Connecting to the Grafana API + grafanaclient, err := sdk.NewClient(grafanaURL, fmt.Sprintf("%s:%s", grafanaUsername, grafanaPassword), sdk.DefaultHTTPClient) + if err != nil { + reqLogger.Error(err, "Unable to create Grafana client") + return ctrl.Result{}, err + } + //Retrieving the Organization Info + retrievedOrg, err := grafanaclient.GetOrgByOrgName(ctx, org) + if err != nil { + if strings.Contains(err.Error(), "Organization not found") { + reqLogger.Error(err, "Unable to get organization") + return ctrl.Result{}, err + } + } + reqLogger.Info("Reconciling grafana") + grafana := &grafanauserv1alpha1.GrafanaUser{} + err = r.Client.Get(context.TODO(), req.NamespacedName, grafana) + if err != nil { + if errors.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{}, err + } else { + log.Info("grafana_org is found and orgName is : " + org) + + } + + _, err = r.AddUsersToGrafanaOrgByEmail(ctx, req, org, grafanaclient, retrievedOrg, grafana.Spec.Admin, "admin") + if err != nil { + return ctrl.Result{}, err + } + + _, err = r.AddUsersToGrafanaOrgByEmail(ctx, req, org, grafanaclient, retrievedOrg, grafana.Spec.Edit, "editor") + if err != nil { + return ctrl.Result{}, err + } + _, err = r.AddUsersToGrafanaOrgByEmail(ctx, req, org, grafanaclient, retrievedOrg, grafana.Spec.View, "viewer") + if err != nil { + return ctrl.Result{}, err + } + + return ctrl.Result{}, nil +} +func (r *GrafanaUserReconciler) AddUsersToGrafanaOrgByEmail(ctx context.Context, req ctrl.Request, org string, client *sdk.Client, retrievedOrg sdk.Org, emails []string, role string) (ctrl.Result, error) { + log := log.FromContext(ctx) + reqLogger := log.WithValues("Request.Namespace", req.Namespace, "Request.Name", req.Name) + orgID := retrievedOrg.ID + orgName := retrievedOrg.Name + getallUser, _ := client.GetAllUsers(ctx) + getuserOrg, _ := client.GetOrgUsers(ctx, orgID) + for _, email := range emails { + var orguserfound bool + for _, orguser := range getuserOrg { + UserOrg := orguser.Email + if email == UserOrg { + orguserfound = true + reqLogger.Info(orguser.Email, "is already in", orgName) + break + } + } + if orguserfound { + continue + } + for _, user := range getallUser { + UserEmail := user.Email + if email == UserEmail { + newuser := sdk.UserRole{LoginOrEmail: email, Role: role} + _, err := client.AddOrgUser(ctx, newuser, orgID) + if err != nil { + return ctrl.Result{}, err + } else { + log.Info(UserEmail, "is added to", orgName) + } + break + } + } + } + return ctrl.Result{}, nil +} + +// SetupWithManager sets up the controller with the Manager. +func (r *GrafanaUserReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + For(&grafanauserv1alpha1.GrafanaUser{}). + Complete(r) +} diff --git a/controllers/grafanauser/suite_test.go b/controllers/grafanauser/suite_test.go new file mode 100644 index 0000000..602d0ba --- /dev/null +++ b/controllers/grafanauser/suite_test.go @@ -0,0 +1,78 @@ +/* +Copyright 2022. + +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 grafanauser + +import ( + "path/filepath" + "testing" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + "sigs.k8s.io/controller-runtime/pkg/envtest/printer" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + grafanauserv1alpha1 "github.com/snapp-cab/grafana-complementary-operator/apis/grafanauser/v1alpha1" + //+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 k8sClient client.Client +var testEnv *envtest.Environment + +func TestAPIs(t *testing.T) { + RegisterFailHandler(Fail) + + RunSpecsWithDefaultAndCustomReporters(t, + "Controller Suite", + []Reporter{printer.NewlineReporter{}}) +} + +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, + } + + cfg, err := testEnv.Start() + Expect(err).NotTo(HaveOccurred()) + Expect(cfg).NotTo(BeNil()) + + err = grafanauserv1alpha1.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()) + +}, 60) + +var _ = AfterSuite(func() { + By("tearing down the test environment") + err := testEnv.Stop() + Expect(err).NotTo(HaveOccurred()) +}) diff --git a/controllers/namespace_controller.go b/controllers/namespace/namespace_controller.go similarity index 100% rename from controllers/namespace_controller.go rename to controllers/namespace/namespace_controller.go diff --git a/controllers/suite_test.go b/controllers/namespace/suite_test.go similarity index 100% rename from controllers/suite_test.go rename to controllers/namespace/suite_test.go diff --git a/go.sum b/go.sum index 503e74c..31b79e0 100644 --- a/go.sum +++ b/go.sum @@ -265,7 +265,6 @@ github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTM github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/gobs/pretty v0.0.0-20180724170744-09732c25a95b/go.mod h1:Xo4aNUOrJnVruqWQJBtW6+bTBDTniY8yZum5rF3b5jw= github.com/gobuffalo/flect v0.2.0/go.mod h1:W3K3X9ksuZfir8f/LrfVtWmCDQFfayuylOJ7sz/Fj80= github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= @@ -382,8 +381,6 @@ github.com/grafana-operator/grafana-operator/v4 v4.2.0 h1:zq9mYuklJrSBt8vtA2YtMk github.com/grafana-operator/grafana-operator/v4 v4.2.0/go.mod h1:t6p0gbMXqe2PFK6EK5qQB+qfZwdDcJ2wMi/fGKGA/LU= github.com/grafana-tools/sdk v0.0.0-20220402173226-77f22ba83269 h1:730mFhwDnWHkimN3URriW84LJs8k0PJccN1lDn7cxHA= github.com/grafana-tools/sdk v0.0.0-20220402173226-77f22ba83269/go.mod h1:AHHlOEv1+GGQ3ktHMlhuTUwo3zljV3QJbC0+8o2kn+4= -github.com/grafana/grafana-api-golang-client v0.5.1 h1:PsYNB9mZ2LBC348eciPnU2y5lMqsQg6nANbBEAgG+Po= -github.com/grafana/grafana-api-golang-client v0.5.1/go.mod h1:24W29gPe9yl0/3A9X624TPkAOR8DpHno490cPwnkv8E= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= @@ -396,8 +393,6 @@ github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBt github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= -github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= diff --git a/main.go b/main.go index c0f5a6c..c071f4e 100644 --- a/main.go +++ b/main.go @@ -32,7 +32,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" - "github.com/snapp-cab/grafana-complementary-operator/controllers" + grafanauserv1alpha1 "github.com/snapp-cab/grafana-complementary-operator/apis/grafanauser/v1alpha1" + grafanausercontrollers "github.com/snapp-cab/grafana-complementary-operator/controllers/grafanauser" + namesapcecontrollers "github.com/snapp-cab/grafana-complementary-operator/controllers/namespace" //+kubebuilder:scaffold:imports ) @@ -45,6 +47,7 @@ func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(grafanav1alpha1.AddToScheme(scheme)) + utilruntime.Must(grafanauserv1alpha1.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme } @@ -78,13 +81,20 @@ func main() { os.Exit(1) } - if err = (&controllers.NamespaceReconciler{ + if err = (&namesapcecontrollers.NamespaceReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Namespace") os.Exit(1) } + if err = (&grafanausercontrollers.GrafanaUserReconciler{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "GrafanaUser") + os.Exit(1) + } //+kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {