aboutsummaryrefslogtreecommitdiffstats
path: root/vnfs/DAaaS/microservices/collectd-operator/pkg/controller/collectdplugin/collectdplugin_controller.go
diff options
context:
space:
mode:
Diffstat (limited to 'vnfs/DAaaS/microservices/collectd-operator/pkg/controller/collectdplugin/collectdplugin_controller.go')
-rw-r--r--vnfs/DAaaS/microservices/collectd-operator/pkg/controller/collectdplugin/collectdplugin_controller.go202
1 files changed, 19 insertions, 183 deletions
diff --git a/vnfs/DAaaS/microservices/collectd-operator/pkg/controller/collectdplugin/collectdplugin_controller.go b/vnfs/DAaaS/microservices/collectd-operator/pkg/controller/collectdplugin/collectdplugin_controller.go
index 11cf0bc1..4ce32eb2 100644
--- a/vnfs/DAaaS/microservices/collectd-operator/pkg/controller/collectdplugin/collectdplugin_controller.go
+++ b/vnfs/DAaaS/microservices/collectd-operator/pkg/controller/collectdplugin/collectdplugin_controller.go
@@ -2,15 +2,14 @@ package collectdplugin
import (
"context"
- "crypto/sha256"
"fmt"
- "os"
"reflect"
"strings"
"github.com/go-logr/logr"
onapv1alpha1 "demo/vnfs/DAaaS/microservices/collectd-operator/pkg/apis/onap/v1alpha1"
+ collectdutils "demo/vnfs/DAaaS/microservices/collectd-operator/pkg/controller/utils"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
@@ -29,17 +28,6 @@ import (
var log = logf.Log.WithName("controller_collectdplugin")
-// ResourceMap to hold objects to update/reload
-type ResourceMap struct {
- configMap *corev1.ConfigMap
- daemonSet *extensionsv1beta1.DaemonSet
- collectdPlugins *[]onapv1alpha1.CollectdPlugin
-}
-
-/**
-* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller
-* business logic. Delete these comments after modifying this file.*
- */
// Add creates a new CollectdPlugin Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
@@ -73,7 +61,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error {
&source.Kind{Type: &appsv1.DaemonSet{}},
&handler.EnqueueRequestsFromMapFunc{
ToRequests: handler.ToRequestsFunc(func (a handler.MapObject) []reconcile.Request {
- labelSelector, err := getWatchLabels()
+ labelSelector, err := collectdutils.GetWatchLabels()
labels := strings.Split(labelSelector, "=")
if err != nil {
log.Error(err, "Failed to get watch labels, continuing with default label")
@@ -82,7 +70,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Select the Daemonset with labelSelector (Defautl is app=collectd)
if a.Meta.GetLabels()[labels[0]] == labels[1] {
var requests []reconcile.Request
- cpList, err := rcp.getCollectdPluginList(a.Meta.GetNamespace())
+ cpList, err := collectdutils.GetCollectdPluginList(rcp.client, a.Meta.GetNamespace())
if err != nil {
return nil
}
@@ -114,16 +102,6 @@ type ReconcileCollectdPlugin struct {
scheme *runtime.Scheme
}
-// Define the collectdPlugin finalizer for handling deletion
-const (
- defaultWatchLabel = "app=collectd"
- collectdPluginFinalizer = "finalizer.collectdplugin.onap.org"
-
- // WatchLabelsEnvVar is the constant for env variable WATCH_LABELS
- // which is the labels where the watch activity happens.
- // this value is empty if the operator is running with clusterScope.
- WatchLabelsEnvVar = "WATCH_LABELS"
-)
// Reconcile reads that state of the cluster for a CollectdPlugin object and makes changes based on the state read
// and what is in the CollectdPlugin.Spec
@@ -159,7 +137,7 @@ func (r *ReconcileCollectdPlugin) Reconcile(request reconcile.Request) (reconcil
}
// Add finalizer for this CR
- if !contains(instance.GetFinalizers(), collectdPluginFinalizer) {
+ if !collectdutils.Contains(instance.GetFinalizers(), collectdutils.CollectdFinalizer) {
if err := r.addFinalizer(reqLogger, instance); err != nil {
return reconcile.Result{}, err
}
@@ -174,24 +152,27 @@ func (r *ReconcileCollectdPlugin) Reconcile(request reconcile.Request) (reconcil
// handleCollectdPlugin regenerates the collectd conf on CR Create, Update, Delete events
func (r *ReconcileCollectdPlugin) handleCollectdPlugin(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin, isDelete bool) error {
- rmap, err := r.findResourceMapForCR(reqLogger, cr)
+ rmap, err := collectdutils.FindResourceMapForCR(r.client, reqLogger, cr.Namespace)
if err != nil {
reqLogger.Error(err, "Skip reconcile: Resources not found")
return err
}
- cm := rmap.configMap
- collectPlugins := rmap.collectdPlugins
+ cm := rmap.ConfigMap
reqLogger.V(1).Info("Found ResourceMap")
reqLogger.V(1).Info(":::: ConfigMap Info ::::", "ConfigMap.Namespace", cm.Namespace, "ConfigMap.Name", cm.Name)
- collectdConf, err := rebuildCollectdConf(cr, collectPlugins, isDelete)
+ collectdConf, err := collectdutils.RebuildCollectdConf(r.client, cr.Namespace, isDelete, cr.Spec.PluginName)
+ if err != nil {
+ reqLogger.Error(err, "Skip reconcile: Rebuild conf failed")
+ return err
+ }
cm.SetAnnotations(map[string]string{
- "daaas-random": ComputeSHA256([]byte(collectdConf)),
+ "daaas-random": collectdutils.ComputeSHA256([]byte(collectdConf)),
})
- cm.Data["node-collectd.conf"] = collectdConf
+ cm.Data["collectd.conf"] = collectdConf
// Update the ConfigMap with new Spec and reload DaemonSets
reqLogger.Info("Updating the ConfigMap", "ConfigMap.Namespace", cm.Namespace, "ConfigMap.Name", cm.Name)
@@ -208,7 +189,7 @@ func (r *ReconcileCollectdPlugin) handleCollectdPlugin(reqLogger logr.Logger, cr
// Select DaemonSets with label
dsList := &extensionsv1beta1.DaemonSetList{}
opts := &client.ListOptions{}
- labelSelector, err := getWatchLabels()
+ labelSelector, err := collectdutils.GetWatchLabels()
if err != nil {
reqLogger.Error(err, "Failed to get watch labels, continuing with default label")
}
@@ -227,7 +208,7 @@ func (r *ReconcileCollectdPlugin) handleCollectdPlugin(reqLogger logr.Logger, cr
reqLogger.Info("Reloading the Daemonset", "DaemonSet.Namespace", ds.Namespace, "DaemonSet.Name", ds.Name)
//Restart only if hash of conf has changed.
ds.Spec.Template.SetAnnotations(map[string]string{
- "daaas-random": ComputeSHA256([]byte(collectdConf)),
+ "daaas-random": collectdutils.ComputeSHA256([]byte(collectdConf)),
})
updateErr := r.client.Update(context.TODO(), ds)
return updateErr
@@ -246,89 +227,6 @@ func (r *ReconcileCollectdPlugin) handleCollectdPlugin(reqLogger logr.Logger, cr
return nil
}
-// ComputeSHA256 returns hash of data as string
-func ComputeSHA256(data []byte) string {
- hash := sha256.Sum256(data)
- return fmt.Sprintf("%x", hash)
-}
-
-// findResourceMapForCR returns the configMap, collectd Daemonset and list of Collectd Plugins
-func (r *ReconcileCollectdPlugin) findResourceMapForCR(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin) (ResourceMap, error) {
- cmList := &corev1.ConfigMapList{}
- opts := &client.ListOptions{}
- rmap := ResourceMap{}
-
- // Select ConfigMaps with label
- labelSelector, err := getWatchLabels()
- if err != nil {
- reqLogger.Error(err, "Failed to get watch labels, continuing with default label")
- }
- opts.SetLabelSelector(labelSelector)
- opts.InNamespace(cr.Namespace)
-
- err = r.client.List(context.TODO(), opts, cmList)
- if err != nil {
- return rmap, err
- }
-
- if cmList.Items == nil || len(cmList.Items) == 0 {
- return rmap, errors.NewNotFound(corev1.Resource("configmap"), "ConfigMap")
- }
-
- // Select DaemonSets with label
- dsList := &extensionsv1beta1.DaemonSetList{}
- err = r.client.List(context.TODO(), opts, dsList)
- if err != nil {
- return rmap, err
- }
-
- if dsList.Items == nil || len(dsList.Items) == 0 {
- return rmap, errors.NewNotFound(corev1.Resource("daemonset"), "DaemonSet")
- }
-
- // Get all collectd plugins in the current namespace to rebuild conf.
- cpList, err := r.getCollectdPluginList(cr.Namespace)
- if err != nil {
- return rmap, err
- }
-
- rmap.configMap = &cmList.Items[0]
- rmap.daemonSet = &dsList.Items[0]
- rmap.collectdPlugins = &cpList.Items //will be nil if no plugins exist
- return rmap, err
-}
-
-// Get all collectd plugins and reconstruct, compute Hash and check for changes
-func rebuildCollectdConf(cr *onapv1alpha1.CollectdPlugin, cpList *[]onapv1alpha1.CollectdPlugin, isDelete bool) (string, error) {
- var collectdConf string
- if *cpList == nil || len(*cpList) == 0 {
- return "", errors.NewNotFound(corev1.Resource("collectdplugin"), "CollectdPlugin")
- }
- loadPlugin := make(map[string]string)
- for _, cp := range *cpList {
- if cp.Spec.PluginName == "global" {
- collectdConf += cp.Spec.PluginConf + "\n"
- } else {
- loadPlugin[cp.Spec.PluginName] = cp.Spec.PluginConf
- }
- }
-
- if isDelete {
- delete(loadPlugin, cr.Spec.PluginName)
- }
-
- log.V(1).Info("::::::: Plugins Map ::::::: ", "PluginMap ", loadPlugin)
-
- for cpName, cpConf := range loadPlugin {
- collectdConf += "LoadPlugin" + " " + cpName + "\n"
- collectdConf += cpConf + "\n"
- }
-
- collectdConf += "#Last line (collectd requires ā€˜\\nā€™ at the last line)\n"
-
- return collectdConf, nil
-}
-
// Handle Delete CR event for additional cleanup
func (r *ReconcileCollectdPlugin) handleDelete(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin) (bool, error) {
// Check if the CollectdPlugin instance is marked to be deleted, which is
@@ -340,7 +238,7 @@ func (r *ReconcileCollectdPlugin) handleDelete(reqLogger logr.Logger, cr *onapv1
cr.Status.CollectdAgents = nil
_ = r.client.Status().Update(context.TODO(), cr)
- if contains(cr.GetFinalizers(), collectdPluginFinalizer) {
+ if collectdutils.Contains(cr.GetFinalizers(), collectdutils.CollectdFinalizer) {
// Run finalization logic for collectdPluginFinalizer. If the
// finalization logic fails, don't remove the finalizer so
// that we can retry during the next reconciliation.
@@ -350,7 +248,7 @@ func (r *ReconcileCollectdPlugin) handleDelete(reqLogger logr.Logger, cr *onapv1
// Remove collectdPluginFinalizer. Once all finalizers have been
// removed, the object will be deleted.
- cr.SetFinalizers(remove(cr.GetFinalizers(), collectdPluginFinalizer))
+ cr.SetFinalizers(collectdutils.Remove(cr.GetFinalizers(), collectdutils.CollectdFinalizer))
err := r.client.Update(context.TODO(), cr)
if err != nil {
return isMarkedToBeDeleted, err
@@ -365,7 +263,7 @@ func (r *ReconcileCollectdPlugin) updateStatus(cr *onapv1alpha1.CollectdPlugin)
case onapv1alpha1.Initial:
cr.Status.Status = onapv1alpha1.Created
case onapv1alpha1.Created, onapv1alpha1.Enabled:
- pods, err := r.getPodList(cr.Namespace)
+ pods, err := collectdutils.GetPodList(r.client, cr.Namespace)
if err != nil {
return err
}
@@ -392,7 +290,7 @@ func (r *ReconcileCollectdPlugin) finalizeCollectdPlugin(reqLogger logr.Logger,
func (r *ReconcileCollectdPlugin) addFinalizer(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin) error {
reqLogger.Info("Adding Finalizer for the CollectdPlugin")
- cr.SetFinalizers(append(cr.GetFinalizers(), collectdPluginFinalizer))
+ cr.SetFinalizers(append(cr.GetFinalizers(), collectdutils.CollectdFinalizer))
// Update status from Initial to Created
// Since addFinalizer will be executed only once,
// the status will be changed from Initial state to Created
@@ -408,65 +306,3 @@ func (r *ReconcileCollectdPlugin) addFinalizer(reqLogger logr.Logger, cr *onapv1
}
return nil
}
-
-func contains(list []string, s string) bool {
- for _, v := range list {
- if v == s {
- return true
- }
- }
- return false
-}
-
-func remove(list []string, s string) []string {
- for i, v := range list {
- if v == s {
- list = append(list[:i], list[i+1:]...)
- }
- }
- return list
-}
-
-// getWatchLabels returns the labels the operator should be watching for changes
-func getWatchLabels() (string, error) {
- labelSelector, found := os.LookupEnv(WatchLabelsEnvVar)
- if !found {
- return defaultWatchLabel, fmt.Errorf("%s must be set", WatchLabelsEnvVar)
- }
- return labelSelector, nil
-}
-
-func (r *ReconcileCollectdPlugin) getPodList(ns string) ([]string, error) {
- var pods []string
- podList := &corev1.PodList{}
- opts := &client.ListOptions{}
- // Select ConfigMaps with label
- labelSelector, _ := getWatchLabels()
- opts.SetLabelSelector(labelSelector)
- opts.InNamespace(ns)
- err := r.client.List(context.TODO(), opts, podList)
- if err != nil {
- return nil, err
- }
-
- if podList.Items == nil || len(podList.Items) == 0 {
- return nil, err
- }
-
- for _, pod := range podList.Items {
- pods = append(pods, pod.Name)
- }
- return pods, nil
-}
-
-func (r *ReconcileCollectdPlugin) getCollectdPluginList(ns string) (*onapv1alpha1.CollectdPluginList, error) {
- // Get all collectd plugins in the current namespace to rebuild conf.
- collectdPlugins := &onapv1alpha1.CollectdPluginList{}
- cpOpts := &client.ListOptions{}
- cpOpts.InNamespace(ns)
- err := r.client.List(context.TODO(), cpOpts, collectdPlugins)
- if err != nil {
- return nil, err
- }
- return collectdPlugins, nil
-}