11 "github.com/go-logr/logr"
13 onapv1alpha1 "demo/vnfs/DAaaS/microservices/collectd-operator/pkg/apis/onap/v1alpha1"
15 appsv1 "k8s.io/api/apps/v1"
16 corev1 "k8s.io/api/core/v1"
17 extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
18 "k8s.io/apimachinery/pkg/api/errors"
19 "k8s.io/apimachinery/pkg/runtime"
20 "k8s.io/client-go/util/retry"
21 "sigs.k8s.io/controller-runtime/pkg/client"
22 "sigs.k8s.io/controller-runtime/pkg/controller"
23 "sigs.k8s.io/controller-runtime/pkg/handler"
24 "sigs.k8s.io/controller-runtime/pkg/manager"
25 "sigs.k8s.io/controller-runtime/pkg/reconcile"
26 logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
27 "sigs.k8s.io/controller-runtime/pkg/source"
30 var log = logf.Log.WithName("controller_collectdplugin")
32 // ResourceMap to hold objects to update/reload
33 type ResourceMap struct {
34 configMap *corev1.ConfigMap
35 daemonSet *extensionsv1beta1.DaemonSet
36 collectdPlugins *[]onapv1alpha1.CollectdPlugin
40 * USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller
41 * business logic. Delete these comments after modifying this file.*
44 // Add creates a new CollectdPlugin Controller and adds it to the Manager. The Manager will set fields on the Controller
45 // and Start it when the Manager is Started.
46 func Add(mgr manager.Manager) error {
47 return add(mgr, newReconciler(mgr))
50 // newReconciler returns a new reconcile.Reconciler
51 func newReconciler(mgr manager.Manager) reconcile.Reconciler {
52 return &ReconcileCollectdPlugin{client: mgr.GetClient(), scheme: mgr.GetScheme()}
55 // add adds a new Controller to mgr with r as the reconcile.Reconciler
56 func add(mgr manager.Manager, r reconcile.Reconciler) error {
57 // Create a new controller
58 log.V(1).Info("Creating a new controller for CollectdPlugin")
59 c, err := controller.New("collectdplugin-controller", mgr, controller.Options{Reconciler: r})
64 // Watch for changes to primary resource CollectdPlugin
65 log.V(1).Info("Add watcher for primary resource CollectdPlugin")
66 err = c.Watch(&source.Kind{Type: &onapv1alpha1.CollectdPlugin{}}, &handler.EnqueueRequestForObject{})
71 log.V(1).Info("Add watcher for secondary resource Collectd Daemonset")
73 &source.Kind{Type: &appsv1.DaemonSet{}},
74 &handler.EnqueueRequestsFromMapFunc{
75 ToRequests: handler.ToRequestsFunc(func (a handler.MapObject) []reconcile.Request {
76 labelSelector, err := getWatchLabels()
77 labels := strings.Split(labelSelector, "=")
79 log.Error(err, "Failed to get watch labels, continuing with default label")
81 rcp := r.(*ReconcileCollectdPlugin)
82 // Select the Daemonset with labelSelector (Defautl is app=collectd)
83 if a.Meta.GetLabels()[labels[0]] == labels[1] {
84 var requests []reconcile.Request
85 cpList, err := rcp.getCollectdPluginList(a.Meta.GetNamespace())
89 for _, cp := range cpList.Items {
90 requests = append(requests, reconcile.Request{
91 NamespacedName: client.ObjectKey{Namespace: cp.Namespace, Name: cp.Name}})
106 // blank assignment to verify that ReconcileCollectdPlugin implements reconcile.Reconciler
107 var _ reconcile.Reconciler = &ReconcileCollectdPlugin{}
109 // ReconcileCollectdPlugin reconciles a CollectdPlugin object
110 type ReconcileCollectdPlugin struct {
111 // This client, initialized using mgr.Client() above, is a split client
112 // that reads objects from the cache and writes to the apiserver
114 scheme *runtime.Scheme
117 // Define the collectdPlugin finalizer for handling deletion
119 defaultWatchLabel = "app=collectd"
120 collectdPluginFinalizer = "finalizer.collectdplugin.onap.org"
122 // WatchLabelsEnvVar is the constant for env variable WATCH_LABELS
123 // which is the labels where the watch activity happens.
124 // this value is empty if the operator is running with clusterScope.
125 WatchLabelsEnvVar = "WATCH_LABELS"
128 // Reconcile reads that state of the cluster for a CollectdPlugin object and makes changes based on the state read
129 // and what is in the CollectdPlugin.Spec
130 // TODO(user): Modify this Reconcile function to implement your Controller logic. This example creates
131 // a Pod as an example
133 // The Controller will requeue the Request to be processed again if the returned error is non-nil or
134 // Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
135 func (r *ReconcileCollectdPlugin) Reconcile(request reconcile.Request) (reconcile.Result, error) {
136 reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
137 reqLogger.Info("Reconciling CollectdPlugin")
139 // Fetch the CollectdPlugin instance
140 instance := &onapv1alpha1.CollectdPlugin{}
141 err := r.client.Get(context.TODO(), request.NamespacedName, instance)
143 if errors.IsNotFound(err) {
144 // Request object not found, could have been deleted after reconcile request.
145 // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
146 // Return and don't requeue
147 reqLogger.V(1).Info("CollectdPlugin object Not found")
148 return reconcile.Result{}, nil
150 // Error reading the object - requeue the request.
151 reqLogger.V(1).Info("Error reading the CollectdPlugin object, Requeuing")
152 return reconcile.Result{}, err
155 // Handle Delete CR for additional cleanup
156 isDelete, err := r.handleDelete(reqLogger, instance)
158 return reconcile.Result{}, err
161 // Add finalizer for this CR
162 if !contains(instance.GetFinalizers(), collectdPluginFinalizer) {
163 if err := r.addFinalizer(reqLogger, instance); err != nil {
164 return reconcile.Result{}, err
166 return reconcile.Result{}, nil
168 // Handle the reconciliation for CollectdPlugin.
169 // At this stage the Status of the CollectdPlugin should NOT be ""
170 err = r.handleCollectdPlugin(reqLogger, instance, false)
171 return reconcile.Result{}, err
174 // handleCollectdPlugin regenerates the collectd conf on CR Create, Update, Delete events
175 func (r *ReconcileCollectdPlugin) handleCollectdPlugin(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin, isDelete bool) error {
177 rmap, err := r.findResourceMapForCR(reqLogger, cr)
179 reqLogger.Error(err, "Skip reconcile: Resources not found")
184 collectPlugins := rmap.collectdPlugins
185 reqLogger.V(1).Info("Found ResourceMap")
186 reqLogger.V(1).Info(":::: ConfigMap Info ::::", "ConfigMap.Namespace", cm.Namespace, "ConfigMap.Name", cm.Name)
188 collectdConf, err := rebuildCollectdConf(cr, collectPlugins, isDelete)
190 cm.SetAnnotations(map[string]string{
191 "daaas-random": ComputeSHA256([]byte(collectdConf)),
194 cm.Data["node-collectd.conf"] = collectdConf
196 // Update the ConfigMap with new Spec and reload DaemonSets
197 reqLogger.Info("Updating the ConfigMap", "ConfigMap.Namespace", cm.Namespace, "ConfigMap.Name", cm.Name)
198 log.V(1).Info("ConfigMap Data", "Map: ", cm.Data)
199 err = r.client.Update(context.TODO(), cm)
201 reqLogger.Error(err, "Update the ConfigMap failed", "ConfigMap.Namespace", cm.Namespace, "ConfigMap.Name", cm.Name)
205 retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
206 // Retrieve the latest version of Daemonset before attempting update
207 // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver
208 // Select DaemonSets with label
209 dsList := &extensionsv1beta1.DaemonSetList{}
210 opts := &client.ListOptions{}
211 labelSelector, err := getWatchLabels()
213 reqLogger.Error(err, "Failed to get watch labels, continuing with default label")
215 opts.SetLabelSelector(labelSelector)
216 opts.InNamespace(cr.Namespace)
217 err = r.client.List(context.TODO(), opts, dsList)
219 panic(fmt.Errorf("Failed to get latest version of DaemonSet: %v", err))
222 if dsList.Items == nil || len(dsList.Items) == 0 {
223 return errors.NewNotFound(corev1.Resource("daemonset"), "DaemonSet")
225 ds := &dsList.Items[0]
226 //Restart Collectd Pods
227 reqLogger.Info("Reloading the Daemonset", "DaemonSet.Namespace", ds.Namespace, "DaemonSet.Name", ds.Name)
228 //Restart only if hash of conf has changed.
229 ds.Spec.Template.SetAnnotations(map[string]string{
230 "daaas-random": ComputeSHA256([]byte(collectdConf)),
232 updateErr := r.client.Update(context.TODO(), ds)
236 panic(fmt.Errorf("Update failed: %v", retryErr))
239 err = r.updateStatus(cr)
241 reqLogger.Error(err, "Unable to update status")
245 reqLogger.Info("Reconcile success!!")
249 // ComputeSHA256 returns hash of data as string
250 func ComputeSHA256(data []byte) string {
251 hash := sha256.Sum256(data)
252 return fmt.Sprintf("%x", hash)
255 // findResourceMapForCR returns the configMap, collectd Daemonset and list of Collectd Plugins
256 func (r *ReconcileCollectdPlugin) findResourceMapForCR(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin) (ResourceMap, error) {
257 cmList := &corev1.ConfigMapList{}
258 opts := &client.ListOptions{}
259 rmap := ResourceMap{}
261 // Select ConfigMaps with label
262 labelSelector, err := getWatchLabels()
264 reqLogger.Error(err, "Failed to get watch labels, continuing with default label")
266 opts.SetLabelSelector(labelSelector)
267 opts.InNamespace(cr.Namespace)
269 err = r.client.List(context.TODO(), opts, cmList)
274 if cmList.Items == nil || len(cmList.Items) == 0 {
275 return rmap, errors.NewNotFound(corev1.Resource("configmap"), "ConfigMap")
278 // Select DaemonSets with label
279 dsList := &extensionsv1beta1.DaemonSetList{}
280 err = r.client.List(context.TODO(), opts, dsList)
285 if dsList.Items == nil || len(dsList.Items) == 0 {
286 return rmap, errors.NewNotFound(corev1.Resource("daemonset"), "DaemonSet")
289 // Get all collectd plugins in the current namespace to rebuild conf.
290 cpList, err := r.getCollectdPluginList(cr.Namespace)
295 rmap.configMap = &cmList.Items[0]
296 rmap.daemonSet = &dsList.Items[0]
297 rmap.collectdPlugins = &cpList.Items //will be nil if no plugins exist
301 // Get all collectd plugins and reconstruct, compute Hash and check for changes
302 func rebuildCollectdConf(cr *onapv1alpha1.CollectdPlugin, cpList *[]onapv1alpha1.CollectdPlugin, isDelete bool) (string, error) {
303 var collectdConf string
304 if *cpList == nil || len(*cpList) == 0 {
305 return "", errors.NewNotFound(corev1.Resource("collectdplugin"), "CollectdPlugin")
307 loadPlugin := make(map[string]string)
308 for _, cp := range *cpList {
309 if cp.Spec.PluginName == "global" {
310 collectdConf += cp.Spec.PluginConf + "\n"
312 loadPlugin[cp.Spec.PluginName] = cp.Spec.PluginConf
317 delete(loadPlugin, cr.Spec.PluginName)
320 log.V(1).Info("::::::: Plugins Map ::::::: ", "PluginMap ", loadPlugin)
322 for cpName, cpConf := range loadPlugin {
323 collectdConf += "LoadPlugin" + " " + cpName + "\n"
324 collectdConf += cpConf + "\n"
327 collectdConf += "#Last line (collectd requires ā\\nā at the last line)\n"
329 return collectdConf, nil
332 // Handle Delete CR event for additional cleanup
333 func (r *ReconcileCollectdPlugin) handleDelete(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin) (bool, error) {
334 // Check if the CollectdPlugin instance is marked to be deleted, which is
335 // indicated by the deletion timestamp being set.
336 isMarkedToBeDeleted := cr.GetDeletionTimestamp() != nil
337 if isMarkedToBeDeleted {
338 // Update status to Deleting state
339 cr.Status.Status = onapv1alpha1.Deleting
340 cr.Status.CollectdAgents = nil
341 _ = r.client.Status().Update(context.TODO(), cr)
343 if contains(cr.GetFinalizers(), collectdPluginFinalizer) {
344 // Run finalization logic for collectdPluginFinalizer. If the
345 // finalization logic fails, don't remove the finalizer so
346 // that we can retry during the next reconciliation.
347 if err := r.finalizeCollectdPlugin(reqLogger, cr); err != nil {
348 return isMarkedToBeDeleted, err
351 // Remove collectdPluginFinalizer. Once all finalizers have been
352 // removed, the object will be deleted.
353 cr.SetFinalizers(remove(cr.GetFinalizers(), collectdPluginFinalizer))
354 err := r.client.Update(context.TODO(), cr)
356 return isMarkedToBeDeleted, err
360 return isMarkedToBeDeleted, nil
363 func (r *ReconcileCollectdPlugin) updateStatus(cr *onapv1alpha1.CollectdPlugin) error {
364 switch cr.Status.Status {
365 case onapv1alpha1.Initial:
366 cr.Status.Status = onapv1alpha1.Created
367 case onapv1alpha1.Created, onapv1alpha1.Enabled:
368 pods, err := r.getPodList(cr.Namespace)
372 if !reflect.DeepEqual(pods, cr.Status.CollectdAgents) {
373 cr.Status.CollectdAgents = pods
374 cr.Status.Status = onapv1alpha1.Enabled
376 case onapv1alpha1.Deleting, onapv1alpha1.Deprecated:
379 err := r.client.Status().Update(context.TODO(), cr)
383 func (r *ReconcileCollectdPlugin) finalizeCollectdPlugin(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin) error {
384 // Cleanup by regenerating new collectd conf and rolling update of DaemonSet
385 if err := r.handleCollectdPlugin(reqLogger, cr, true); err != nil {
386 reqLogger.Error(err, "Finalize CollectdPlugin failed!!")
389 reqLogger.Info("Successfully finalized CollectdPlugin!!")
393 func (r *ReconcileCollectdPlugin) addFinalizer(reqLogger logr.Logger, cr *onapv1alpha1.CollectdPlugin) error {
394 reqLogger.Info("Adding Finalizer for the CollectdPlugin")
395 cr.SetFinalizers(append(cr.GetFinalizers(), collectdPluginFinalizer))
396 // Update status from Initial to Created
397 // Since addFinalizer will be executed only once,
398 // the status will be changed from Initial state to Created
399 updateErr := r.updateStatus(cr)
400 if updateErr != nil {
401 reqLogger.Error(updateErr, "Failed to update status from Initial state")
404 err := r.client.Update(context.TODO(), cr)
406 reqLogger.Error(err, "Failed to update CollectdPlugin with finalizer")
412 func contains(list []string, s string) bool {
413 for _, v := range list {
421 func remove(list []string, s string) []string {
422 for i, v := range list {
424 list = append(list[:i], list[i+1:]...)
430 // getWatchLabels returns the labels the operator should be watching for changes
431 func getWatchLabels() (string, error) {
432 labelSelector, found := os.LookupEnv(WatchLabelsEnvVar)
434 return defaultWatchLabel, fmt.Errorf("%s must be set", WatchLabelsEnvVar)
436 return labelSelector, nil
439 func (r *ReconcileCollectdPlugin) getPodList(ns string) ([]string, error) {
441 podList := &corev1.PodList{}
442 opts := &client.ListOptions{}
443 // Select ConfigMaps with label
444 labelSelector, _ := getWatchLabels()
445 opts.SetLabelSelector(labelSelector)
447 err := r.client.List(context.TODO(), opts, podList)
452 if podList.Items == nil || len(podList.Items) == 0 {
456 for _, pod := range podList.Items {
457 pods = append(pods, pod.Name)
462 func (r *ReconcileCollectdPlugin) getCollectdPluginList(ns string) (*onapv1alpha1.CollectdPluginList, error) {
463 // Get all collectd plugins in the current namespace to rebuild conf.
464 collectdPlugins := &onapv1alpha1.CollectdPluginList{}
465 cpOpts := &client.ListOptions{}
466 cpOpts.InNamespace(ns)
467 err := r.client.List(context.TODO(), cpOpts, collectdPlugins)
471 return collectdPlugins, nil