11cf0bc12091903db8f65f42e62f12850d4e1c3f
[demo.git] / vnfs / DAaaS / microservices / collectd-operator / pkg / controller / collectdplugin / collectdplugin_controller.go
1 package collectdplugin
2
3 import (
4         "context"
5         "crypto/sha256"
6         "fmt"
7         "os"
8         "reflect"
9         "strings"
10
11         "github.com/go-logr/logr"
12
13         onapv1alpha1 "demo/vnfs/DAaaS/microservices/collectd-operator/pkg/apis/onap/v1alpha1"
14
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"
28 )
29
30 var log = logf.Log.WithName("controller_collectdplugin")
31
32 // ResourceMap to hold objects to update/reload
33 type ResourceMap struct {
34         configMap       *corev1.ConfigMap
35         daemonSet       *extensionsv1beta1.DaemonSet
36         collectdPlugins *[]onapv1alpha1.CollectdPlugin
37 }
38
39 /**
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.*
42  */
43
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))
48 }
49
50 // newReconciler returns a new reconcile.Reconciler
51 func newReconciler(mgr manager.Manager) reconcile.Reconciler {
52         return &ReconcileCollectdPlugin{client: mgr.GetClient(), scheme: mgr.GetScheme()}
53 }
54
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})
60         if err != nil {
61                 return err
62         }
63
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{})
67         if err != nil {
68                 return err
69         }
70
71         log.V(1).Info("Add watcher for secondary resource Collectd Daemonset")
72         err = c.Watch(
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, "=")
78                                 if err != nil {
79                                         log.Error(err, "Failed to get watch labels, continuing with default label")
80                                 }
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())
86                                         if err != nil {
87                                                 return nil
88                                         }
89                                         for _, cp := range cpList.Items {
90                                                 requests = append(requests, reconcile.Request{
91                                                         NamespacedName: client.ObjectKey{Namespace: cp.Namespace, Name: cp.Name}})
92                                         }
93                                         return requests
94                                 }
95                                 return nil
96                         }),
97                 })
98         if err != nil {
99                 return err
100         }
101
102         return nil
103 }
104
105
106 // blank assignment to verify that ReconcileCollectdPlugin implements reconcile.Reconciler
107 var _ reconcile.Reconciler = &ReconcileCollectdPlugin{}
108
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
113         client client.Client
114         scheme *runtime.Scheme
115 }
116
117 // Define the collectdPlugin finalizer for handling deletion
118 const (
119         defaultWatchLabel       = "app=collectd"
120         collectdPluginFinalizer = "finalizer.collectdplugin.onap.org"
121
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"
126 )
127
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
132 // Note:
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")
138
139         // Fetch the CollectdPlugin instance
140         instance := &onapv1alpha1.CollectdPlugin{}
141         err := r.client.Get(context.TODO(), request.NamespacedName, instance)
142         if err != nil {
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
149                 }
150                 // Error reading the object - requeue the request.
151                 reqLogger.V(1).Info("Error reading the CollectdPlugin object, Requeuing")
152                 return reconcile.Result{}, err
153         }
154
155         // Handle Delete CR for additional cleanup
156         isDelete, err := r.handleDelete(reqLogger, instance)
157         if isDelete {
158                 return reconcile.Result{}, err
159         }
160
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
165                 }
166                 return reconcile.Result{}, nil
167         }
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
172 }
173
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 {
176
177         rmap, err := r.findResourceMapForCR(reqLogger, cr)
178         if err != nil {
179                 reqLogger.Error(err, "Skip reconcile: Resources not found")
180                 return err
181         }
182
183         cm := rmap.configMap
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)
187
188         collectdConf, err := rebuildCollectdConf(cr, collectPlugins, isDelete)
189
190         cm.SetAnnotations(map[string]string{
191                 "daaas-random": ComputeSHA256([]byte(collectdConf)),
192         })
193
194         cm.Data["node-collectd.conf"] = collectdConf
195
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)
200         if err != nil {
201                 reqLogger.Error(err, "Update the ConfigMap failed", "ConfigMap.Namespace", cm.Namespace, "ConfigMap.Name", cm.Name)
202                 return err
203         }
204
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()
212                 if err != nil {
213                         reqLogger.Error(err, "Failed to get watch labels, continuing with default label")
214                 }
215                 opts.SetLabelSelector(labelSelector)
216                 opts.InNamespace(cr.Namespace)
217                 err = r.client.List(context.TODO(), opts, dsList)
218                 if err != nil {
219                         panic(fmt.Errorf("Failed to get latest version of DaemonSet: %v", err))
220                 }
221
222                 if dsList.Items == nil || len(dsList.Items) == 0 {
223                         return errors.NewNotFound(corev1.Resource("daemonset"), "DaemonSet")
224                 }
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)),
231                 })
232                 updateErr := r.client.Update(context.TODO(), ds)
233                 return updateErr
234         })
235         if retryErr != nil {
236                 panic(fmt.Errorf("Update failed: %v", retryErr))
237         }
238
239         err = r.updateStatus(cr)
240         if err != nil {
241                 reqLogger.Error(err, "Unable to update status")
242                 return err
243         }
244         // Reconcile success
245         reqLogger.Info("Reconcile success!!")
246         return nil
247 }
248
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)
253 }
254
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{}
260
261         // Select ConfigMaps with label
262         labelSelector, err := getWatchLabels()
263         if err != nil {
264                 reqLogger.Error(err, "Failed to get watch labels, continuing with default label")
265         }
266         opts.SetLabelSelector(labelSelector)
267         opts.InNamespace(cr.Namespace)
268
269         err = r.client.List(context.TODO(), opts, cmList)
270         if err != nil {
271                 return rmap, err
272         }
273
274         if cmList.Items == nil || len(cmList.Items) == 0 {
275                 return rmap, errors.NewNotFound(corev1.Resource("configmap"), "ConfigMap")
276         }
277
278         // Select DaemonSets with label
279         dsList := &extensionsv1beta1.DaemonSetList{}
280         err = r.client.List(context.TODO(), opts, dsList)
281         if err != nil {
282                 return rmap, err
283         }
284
285         if dsList.Items == nil || len(dsList.Items) == 0 {
286                 return rmap, errors.NewNotFound(corev1.Resource("daemonset"), "DaemonSet")
287         }
288
289         // Get all collectd plugins in the current namespace to rebuild conf.
290         cpList, err := r.getCollectdPluginList(cr.Namespace)
291         if err != nil {
292                 return rmap, err
293         }
294
295         rmap.configMap = &cmList.Items[0]
296         rmap.daemonSet = &dsList.Items[0]
297         rmap.collectdPlugins = &cpList.Items //will be nil if no plugins exist
298         return rmap, err
299 }
300
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")
306         }
307         loadPlugin := make(map[string]string)
308         for _, cp := range *cpList {
309                 if cp.Spec.PluginName == "global" {
310                         collectdConf += cp.Spec.PluginConf + "\n"
311                 } else {
312                         loadPlugin[cp.Spec.PluginName] = cp.Spec.PluginConf
313                 }
314         }
315
316         if isDelete {
317                 delete(loadPlugin, cr.Spec.PluginName)
318         }
319
320         log.V(1).Info("::::::: Plugins Map ::::::: ", "PluginMap ", loadPlugin)
321
322         for cpName, cpConf := range loadPlugin {
323                 collectdConf += "LoadPlugin" + " " + cpName + "\n"
324                 collectdConf += cpConf + "\n"
325         }
326
327         collectdConf += "#Last line (collectd requires ā€˜\\nā€™ at the last line)\n"
328
329         return collectdConf, nil
330 }
331
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)
342
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
349                         }
350
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)
355                         if err != nil {
356                                 return isMarkedToBeDeleted, err
357                         }
358                 }
359         }
360         return isMarkedToBeDeleted, nil
361 }
362
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)
369                 if err != nil {
370                         return err
371                 }
372                 if !reflect.DeepEqual(pods, cr.Status.CollectdAgents) {
373                         cr.Status.CollectdAgents = pods
374                         cr.Status.Status = onapv1alpha1.Enabled
375                 }
376         case onapv1alpha1.Deleting, onapv1alpha1.Deprecated:
377                 return nil
378         }
379         err := r.client.Status().Update(context.TODO(), cr)
380         return err
381 }
382
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!!")
387                 return err
388         }
389         reqLogger.Info("Successfully finalized CollectdPlugin!!")
390         return nil
391 }
392
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")
402         }
403         // Update CR
404         err := r.client.Update(context.TODO(), cr)
405         if err != nil {
406                 reqLogger.Error(err, "Failed to update CollectdPlugin with finalizer")
407                 return err
408         }
409         return nil
410 }
411
412 func contains(list []string, s string) bool {
413         for _, v := range list {
414                 if v == s {
415                         return true
416                 }
417         }
418         return false
419 }
420
421 func remove(list []string, s string) []string {
422         for i, v := range list {
423                 if v == s {
424                         list = append(list[:i], list[i+1:]...)
425                 }
426         }
427         return list
428 }
429
430 // getWatchLabels returns the labels the operator should be watching for changes
431 func getWatchLabels() (string, error) {
432         labelSelector, found := os.LookupEnv(WatchLabelsEnvVar)
433         if !found {
434                 return defaultWatchLabel, fmt.Errorf("%s must be set", WatchLabelsEnvVar)
435         }
436         return labelSelector, nil
437 }
438
439 func (r *ReconcileCollectdPlugin) getPodList(ns string) ([]string, error) {
440         var pods []string
441         podList := &corev1.PodList{}
442         opts := &client.ListOptions{}
443         // Select ConfigMaps with label
444         labelSelector, _ := getWatchLabels()
445         opts.SetLabelSelector(labelSelector)
446         opts.InNamespace(ns)
447         err := r.client.List(context.TODO(), opts, podList)
448         if err != nil {
449                 return nil, err
450         }
451
452         if podList.Items == nil || len(podList.Items) == 0 {
453                 return nil, err
454         }
455
456         for _, pod := range podList.Items {
457                 pods = append(pods, pod.Name)
458         }
459         return pods, nil
460 }
461
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)
468         if err != nil {
469                 return nil, err
470         }
471         return collectdPlugins, nil
472 }