Skip to content

Commit

Permalink
feat: add new manager for every declared namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
hubeadmin committed Jan 31, 2022
1 parent fd9d0e6 commit 2fdcb31
Show file tree
Hide file tree
Showing 17 changed files with 236 additions and 201 deletions.
1 change: 1 addition & 0 deletions api/integreatly/v1alpha1/grafana_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ type GrafanaClient struct {
// +nullable
TimeoutSeconds *int `json:"timeout,omitempty"`
// +nullable
// +kubebuilder:default:=true
PreferService *bool `json:"preferService,omitempty"`
}

Expand Down
1 change: 1 addition & 0 deletions config/crd/bases/integreatly.org_grafanas.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ spec:
description: GrafanaClient contains the Grafana API client settings
properties:
preferService:
default: true
nullable: true
type: boolean
timeout:
Expand Down
13 changes: 3 additions & 10 deletions controllers/common/auto_detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Background struct {
client client.Client
dc discovery.DiscoveryInterface
ticker *time.Ticker
SubscriptionChannel chan schema.GroupVersionKind
SubscriptionChannel schema.GroupVersionKind
}

// New creates a new auto-detect runner
Expand All @@ -35,13 +35,7 @@ func NewAutoDetect(mgr manager.Manager) (*Background, error) {
return nil, err
}

// Create a new channel that GVK type will be sent down
// The subscription channel can be used in the future to
// implement actions that are dependant on certain resources
// being installed on the cluster
subChan := make(chan schema.GroupVersionKind, 1)

return &Background{dc: dc, client: mgr.GetClient(), SubscriptionChannel: subChan}, nil
return &Background{dc: dc, client: mgr.GetClient()}, nil
}

// Start initializes the auto-detection process that runs in the background
Expand All @@ -61,7 +55,6 @@ func (b *Background) Start() {
// Stop causes the background process to stop auto detecting capabilities
func (b *Background) Stop() {
b.ticker.Stop()
close(b.SubscriptionChannel)
}

func (b *Background) autoDetectCapabilities() {
Expand All @@ -75,6 +68,6 @@ func (b *Background) detectRoute() {
config := config2.GetControllerConfig()
config.AddConfigItem(config2.ConfigOpenshift, true)

b.SubscriptionChannel <- routev1.SchemeGroupVersion.WithKind(RouteKind)
b.SubscriptionChannel = routev1.SchemeGroupVersion.WithKind(RouteKind)
}
}
2 changes: 0 additions & 2 deletions controllers/common/controllerState.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package common

import v1 "k8s.io/apimachinery/pkg/apis/meta/v1"

var ControllerEvents = make(chan ControllerState, 1)

type ControllerState struct {
DashboardSelectors []*v1.LabelSelector
DashboardNamespaceSelector *v1.LabelSelector
Expand Down
3 changes: 2 additions & 1 deletion controllers/constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ const (
GrafanaDataVolumeName = "grafana-data"
GrafanaDatasourcesConfigMapName = "grafana-datasources"
GrafanaHealthEndpoint = "/api/health"
GrafanaPodLabel = "grafana"
LastConfigAnnotation = "last-config"
LastConfigEnvVar = "LAST_CONFIG"
LastDatasourcesConfigEnvVar = "LAST_DATASOURCES"
Expand All @@ -32,4 +31,6 @@ const (
GrafanaHttpPortName = "grafana"
GrafanaSuccessMsg = "success"
GrafanaDefaultClientTimeoutSeconds int = 5
GrafanaUnableToAddHealthzErrorMsg = "unable to add new checker because healthz endpoint has already been created"
GrafanaUnableToAddReadyzErrorMsg = "unable to add new checker because readyz endpoint has already been created"
)
92 changes: 1 addition & 91 deletions controllers/grafana/grafana_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,20 @@ import (
"context"
stdErr "errors"
"fmt"
"reflect"

"github.com/go-logr/logr"
grafanav1alpha1 "github.com/grafana-operator/grafana-operator/v4/api/integreatly/v1alpha1"
"github.com/grafana-operator/grafana-operator/v4/controllers/common"
"github.com/grafana-operator/grafana-operator/v4/controllers/config"
"github.com/grafana-operator/grafana-operator/v4/controllers/model"
routev1 "github.com/openshift/api/route/v1"
v12 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
netv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/tools/record"
"reflect"
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"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)

const ControllerName = "grafana-controller"
Expand All @@ -51,12 +42,6 @@ func (r *ReconcileGrafana) SetupWithManager(mgr ctrl.Manager) error {
Complete(r)
}

// Add creates a new Grafana Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager, autodetectChannel chan schema.GroupVersionKind, _ string) error {
return add(mgr, NewReconciler(mgr), autodetectChannel)
}

// NewReconciler returns a new reconcile.Reconciler
func NewReconciler(mgr manager.Manager) reconcile.Reconciler {
ctx := context.Background()
Expand All @@ -73,64 +58,6 @@ func NewReconciler(mgr manager.Manager) reconcile.Reconciler {
}
}

// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler, autodetectChannel chan schema.GroupVersionKind) error {
// Create a new controller
c, err := controller.New("grafana-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}

// Watch for changes to primary resource Grafana
err = c.Watch(&source.Kind{Type: &grafanav1alpha1.Grafana{}}, &handler.EnqueueRequestForObject{})
if err != nil {
return err
}

if err = watchSecondaryResource(c, &v12.Deployment{}); err != nil {
return err
}

if err = watchSecondaryResource(c, &netv1.Ingress{}); err != nil {
return err
}

if err = watchSecondaryResource(c, &v1.ConfigMap{}); err != nil {
return err
}

if err = watchSecondaryResource(c, &v1.Service{}); err != nil {
return err
}

if err = watchSecondaryResource(c, &v1.ServiceAccount{}); err != nil {
return err
}

go func() {
for gvk := range autodetectChannel {
cfg := config.GetControllerConfig()

// Route already watched?
if cfg.GetConfigBool(config.ConfigRouteWatch, false) {
return
}

// Watch routes if they exist on the cluster
if gvk.String() == routev1.SchemeGroupVersion.WithKind(common.RouteKind).String() {
if err = watchSecondaryResource(c, &routev1.Route{}); err != nil {
log.Error(err, fmt.Sprintf("error adding secondary watch for %v", common.RouteKind))
} else {
cfg.AddConfigItem(config.ConfigRouteWatch, true)
log.V(1).Info(fmt.Sprintf("added secondary watch for %v", common.RouteKind))
}
}
}
}()

return nil
}

var _ reconcile.Reconciler = &ReconcileGrafana{}

// ReconcileGrafana reconciles a Grafana object
Expand All @@ -147,13 +74,6 @@ type ReconcileGrafana struct {
Recorder record.EventRecorder
}

func watchSecondaryResource(c controller.Controller, resource client.Object) error {
return c.Watch(&source.Kind{Type: resource}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &grafanav1alpha1.Grafana{},
})
}

// Reconcile reads that state of the cluster for a Grafana object and makes changes based on the state read
// and what is in the Grafana.Spec
func (r *ReconcileGrafana) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
Expand All @@ -165,10 +85,6 @@ func (r *ReconcileGrafana) Reconcile(ctx context.Context, request reconcile.Requ
r.Config.RemoveConfigItem(config.ConfigDashboardLabelSelector)
r.Config.Cleanup(true)

common.ControllerEvents <- common.ControllerState{
GrafanaReady: false,
}

return reconcile.Result{}, nil
}
return reconcile.Result{}, err
Expand Down Expand Up @@ -229,10 +145,6 @@ func (r *ReconcileGrafana) manageError(cr *grafanav1alpha1.Grafana, issue error,

r.Config.InvalidateDashboards()

common.ControllerEvents <- common.ControllerState{
GrafanaReady: false,
}

return reconcile.Result{RequeueAfter: config.RequeueDelay}, nil
}

Expand Down Expand Up @@ -325,8 +237,6 @@ func (r *ReconcileGrafana) manageSuccess(cr *grafanav1alpha1.Grafana, state *com
controllerState.ClientTimeout = seconds
}

common.ControllerEvents <- controllerState

log.V(1).Info("desired cluster state met")

return reconcile.Result{RequeueAfter: config.RequeueDelay}, nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,12 @@ func SetupWithManager(mgr ctrl.Manager, r reconcile.Reconciler, namespace string
}
}()

go func() {
for stateChange := range common.ControllerEvents {
// Controller state updated
ref.state = stateChange
}
}()
// go func() {
// for stateChange := range common.ControllerEvents {
// // Controller state updated
// ref.state = stateChange
// }
// }()

return err
}
Expand Down
8 changes: 4 additions & 4 deletions controllers/model/grafanaDeployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ func getDeploymentLabels(cr *v1alpha1.Grafana) map[string]string {
}

func getRollingUpdateStrategy() *v1.RollingUpdateDeployment {
var maxUnaval intstr.IntOrString = intstr.FromInt(25)
var maxSurge intstr.IntOrString = intstr.FromInt(25)
var maxUnaval = intstr.FromInt(25)
var maxSurge = intstr.FromInt(25)
return &v1.RollingUpdateDeployment{
MaxUnavailable: &maxUnaval,
MaxSurge: &maxSurge,
Expand All @@ -151,7 +151,7 @@ func getPodLabels(cr *v1alpha1.Grafana) map[string]string {
if cr.Spec.Deployment != nil && cr.Spec.Deployment.Labels != nil {
labels = cr.Spec.Deployment.Labels
}
labels["app"] = constants.GrafanaPodLabel
labels["app"] = cr.Name
return labels
}

Expand Down Expand Up @@ -679,7 +679,7 @@ func getDeploymentSpec(cr *v1alpha1.Grafana, annotations map[string]string, conf
Replicas: getReplicas(cr),
Selector: &v12.LabelSelector{
MatchLabels: map[string]string{
"app": constants.GrafanaPodLabel,
"app": cr.Name,
},
},
Template: v13.PodTemplateSpec{
Expand Down
4 changes: 2 additions & 2 deletions controllers/model/grafanaIngress.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func getIngressSpec(cr *v1alpha1.Grafana) netv1.IngressSpec {
func GrafanaIngress(cr *v1alpha1.Grafana) *netv1.Ingress {
return &netv1.Ingress{
ObjectMeta: v1.ObjectMeta{
Name: constants.GrafanaIngressName,
Name: cr.ObjectMeta.Name,
Namespace: cr.Namespace,
Labels: GetIngressLabels(cr),
Annotations: GetIngressAnnotations(cr, nil),
Expand All @@ -136,6 +136,6 @@ func GrafanaIngressReconciled(cr *v1alpha1.Grafana, currentState *netv1.Ingress)
func GrafanaIngressSelector(cr *v1alpha1.Grafana) client.ObjectKey {
return client.ObjectKey{
Namespace: cr.Namespace,
Name: constants.GrafanaIngressName,
Name: cr.ObjectMeta.Name,
}
}
12 changes: 7 additions & 5 deletions controllers/model/grafanaRoute.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@ func GetPath(cr *v1alpha1.Grafana) string {
}

func GetIngressLabels(cr *v1alpha1.Grafana) map[string]string {
if cr.Spec.Ingress == nil {
return nil
var labels = map[string]string{}
if cr.Spec.Ingress != nil && cr.Spec.Ingress.Labels != nil {
labels = cr.Spec.Ingress.Labels
}
return cr.Spec.Ingress.Labels
labels["app"] = cr.Name
return labels
}

func GetIngressAnnotations(cr *v1alpha1.Grafana, existing map[string]string) map[string]string {
Expand Down Expand Up @@ -101,7 +103,7 @@ func getRouteSpec(cr *v1alpha1.Grafana) v1.RouteSpec {
func GrafanaRoute(cr *v1alpha1.Grafana) *v1.Route {
return &v1.Route{
ObjectMeta: v12.ObjectMeta{
Name: constants.GrafanaRouteName,
Name: cr.ObjectMeta.Name,
Namespace: cr.Namespace,
Labels: GetIngressLabels(cr),
Annotations: GetIngressAnnotations(cr, nil),
Expand All @@ -113,7 +115,7 @@ func GrafanaRoute(cr *v1alpha1.Grafana) *v1.Route {
func GrafanaRouteSelector(cr *v1alpha1.Grafana) client.ObjectKey {
return client.ObjectKey{
Namespace: cr.Namespace,
Name: constants.GrafanaRouteName,
Name: cr.ObjectMeta.Name,
}
}

Expand Down
2 changes: 1 addition & 1 deletion controllers/model/grafanaService.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func GrafanaService(cr *v1alpha1.Grafana) *v1.Service {
Spec: v1.ServiceSpec{
Ports: getServicePorts(cr, nil),
Selector: map[string]string{
"app": constants.GrafanaPodLabel,
"app": cr.ObjectMeta.Name,
},
ClusterIP: getClusterIP(cr),
Type: getServiceType(cr),
Expand Down
4 changes: 4 additions & 0 deletions controllers/model/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,7 @@ func MergeAnnotations(requested map[string]string, existing map[string]string) m
}
return existing
}

func ErrorContainsString(err error, str string) bool {
return err.Error() == str
}
2 changes: 1 addition & 1 deletion deploy/examples/dashboards/SimpleDashboard.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ kind: GrafanaDashboard
metadata:
name: simple-dashboard
labels:
app: grafana
app: "my-test-grafana"
spec:
json: >
{
Expand Down
Loading

0 comments on commit 2fdcb31

Please sign in to comment.