Refactored BPA controller code for better testing
[icn.git] / cmd / bpa-operator / pkg / controller / provisioning / provisioning_controller.go
1 package provisioning
2
3 import (
4         "context"
5         "os"
6         "fmt"
7         "time"
8         "bytes"
9         "regexp"
10         "strings"
11         "io/ioutil"
12         "encoding/json"
13
14         bpav1alpha1 "github.com/bpa-operator/pkg/apis/bpa/v1alpha1"
15         metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
16         corev1 "k8s.io/api/core/v1"
17         batchv1 "k8s.io/api/batch/v1"
18         "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
19         "k8s.io/apimachinery/pkg/runtime/schema"
20         "k8s.io/apimachinery/pkg/api/errors"
21         "k8s.io/apimachinery/pkg/runtime"
22         "k8s.io/client-go/dynamic"
23
24         "k8s.io/client-go/kubernetes"
25         "sigs.k8s.io/controller-runtime/pkg/client"
26         "sigs.k8s.io/controller-runtime/pkg/client/config"
27         "sigs.k8s.io/controller-runtime/pkg/controller"
28         "sigs.k8s.io/controller-runtime/pkg/handler"
29         "sigs.k8s.io/controller-runtime/pkg/manager"
30         "sigs.k8s.io/controller-runtime/pkg/reconcile"
31         logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
32         "sigs.k8s.io/controller-runtime/pkg/source"
33         "gopkg.in/ini.v1"
34         "golang.org/x/crypto/ssh"
35 )
36
37 type VirtletVM struct {
38         IPaddress string
39         MACaddress string
40 }
41
42 type NetworksStatus struct {
43         Name string `json:"name,omitempty"`
44         Interface string `json:"interface,omitempty"`
45         Ips []string `json:"ips,omitempty"`
46         Mac string `json:"mac,omitempty"`
47         Default bool `json:"default,omitempty"`
48         Dns interface{} `json:"dns,omitempty"`
49 }
50
51 var log = logf.Log.WithName("controller_provisioning")
52
53 /**
54 * USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller
55 * business logic.  Delete these comments after modifying this file.*
56  */
57
58 // Add creates a new Provisioning Controller and adds it to the Manager. The Manager will set fields on the Controller
59 // and Start it when the Manager is Started.
60 func Add(mgr manager.Manager) error {
61         return add(mgr, newReconciler(mgr))
62 }
63
64 // newReconciler returns a new reconcile.Reconciler
65 func newReconciler(mgr manager.Manager) reconcile.Reconciler {
66
67         config, err :=  config.GetConfig()
68         if err != nil {
69            fmt.Printf("Could not get kube config, Error: %v\n", err)
70         }
71
72        clientSet, err := kubernetes.NewForConfig(config)
73         if err != nil {
74            fmt.Printf("Could not create clientset, Error: %v\n", err)
75         }
76        bmhDynamicClient, err := dynamic.NewForConfig(config)
77
78        if err != nil {
79           fmt.Printf("Could not create dynamic client for bareMetalHosts, Error: %v\n", err)
80        }
81
82        return &ReconcileProvisioning{client: mgr.GetClient(), scheme: mgr.GetScheme(), clientset: clientSet, bmhClient: bmhDynamicClient }
83 }
84
85 // add adds a new Controller to mgr with r as the reconcile.Reconciler
86 func add(mgr manager.Manager, r reconcile.Reconciler) error {
87         // Create a new controller
88         c, err := controller.New("provisioning-controller", mgr, controller.Options{Reconciler: r})
89         if err != nil {
90                 return err
91         }
92
93         // Watch for changes to primary resource Provisioning
94         err = c.Watch(&source.Kind{Type: &bpav1alpha1.Provisioning{}}, &handler.EnqueueRequestForObject{})
95         if err != nil {
96                 return err
97         }
98
99         // Watch for changes to resource configmap created as a consequence of the provisioning CR
100         err = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForOwner{
101                 IsController: true,
102                 OwnerType:   &bpav1alpha1.Provisioning{},
103         })
104
105         if err != nil {
106                 return err
107         }
108
109        //Watch for changes to job resource also created as a consequence of the provisioning CR
110        err = c.Watch(&source.Kind{Type: &batchv1.Job{}}, &handler.EnqueueRequestForOwner{
111                 IsController: true,
112                 OwnerType:   &bpav1alpha1.Provisioning{},
113         })
114
115         if err != nil {
116                 return err
117         }
118
119         // Watch for changes to resource software CR
120         err = c.Watch(&source.Kind{Type: &bpav1alpha1.Software{}}, &handler.EnqueueRequestForObject{})
121         if err != nil {
122                 return err
123         }
124
125
126         return nil
127 }
128
129 // blank assignment to verify that ReconcileProvisioning implements reconcile.Reconciler
130 var _ reconcile.Reconciler = &ReconcileProvisioning{}
131
132 // ReconcileProvisioning reconciles a Provisioning object
133 type ReconcileProvisioning struct {
134         // This client, initialized using mgr.Client() above, is a split client
135         // that reads objects from the cache and writes to the apiserver
136         client client.Client
137         scheme *runtime.Scheme
138         clientset kubernetes.Interface
139         bmhClient dynamic.Interface
140 }
141
142 // Reconcile reads that state of the cluster for a Provisioning object and makes changes based on the state read
143 // and what is in the Provisioning.Spec
144 // TODO(user): Modify this Reconcile function to implement your Controller logic.  This example creates
145 // a Pod as an example
146 // Note:
147 // The Controller will requeue the Request to be processed again if the returned error is non-nil or
148 // Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
149 func (r *ReconcileProvisioning) Reconcile(request reconcile.Request) (reconcile.Result, error) {
150         reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
151         fmt.Printf("\n\n")
152         reqLogger.Info("Reconciling Custom Resource")
153
154
155
156         // Fetch the Provisioning instance
157         provisioningInstance := &bpav1alpha1.Provisioning{}
158         softwareInstance := &bpav1alpha1.Software{}
159         err := r.client.Get(context.TODO(), request.NamespacedName, provisioningInstance)
160         provisioningCreated := true
161         if err != nil {
162
163                          //Check if its a Software Instance
164                          err = r.client.Get(context.TODO(), request.NamespacedName, softwareInstance)
165                          if err != nil {
166                              if errors.IsNotFound(err) {
167                                 // Request object not found, could have been deleted after reconcile request.
168                                 // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
169                                 // Return and don't requeue
170                                 return reconcile.Result{}, nil
171                              }
172
173                          // Error reading the object - requeue the request.
174                          return reconcile.Result{}, err
175                          }
176
177                          //No error occured and so a Software CR was created not a Provisoning CR
178                          provisioningCreated = false
179         }
180
181
182         masterTag := "MASTER_"
183         workerTag := "WORKER_"
184
185         if provisioningCreated {
186
187         ///////////////////////////////////////////////////////////////////////////////////////////////
188         ////////////////         Provisioning CR was created so install KUD          /////////////////
189         //////////////////////////////////////////////////////////////////////////////////////////////
190         clusterName := provisioningInstance.Labels["cluster"]
191         clusterType := provisioningInstance.Labels["cluster-type"]
192         mastersList := provisioningInstance.Spec.Masters
193         workersList := provisioningInstance.Spec.Workers
194         dhcpLeaseFile := provisioningInstance.Spec.DHCPleaseFile
195         kudInstallerScript := provisioningInstance.Spec.KUDInstaller
196         multiClusterDir := provisioningInstance.Spec.MultiClusterPath
197
198
199         bareMetalHostList, _ := listBareMetalHosts(r.bmhClient)
200         virtletVMList, _ := listVirtletVMs(r.clientset)
201
202
203
204
205         var allString string
206         var masterString string
207         var workerString string
208
209         defaultDHCPFile := "/var/lib/dhcp/dhcpd.leases"
210         defaultKUDInstallerPath := "/multicloud-k8s/kud/hosting_providers/vagrant"
211         defaultMultiClusterDir := "/multi-cluster"
212
213         //Give Default values for paths if no path is given in the CR
214         if dhcpLeaseFile == "" {
215            dhcpLeaseFile = defaultDHCPFile
216         }
217
218         if kudInstallerScript == "" {
219            kudInstallerScript = defaultKUDInstallerPath
220         }
221
222         if multiClusterDir == "" {
223            multiClusterDir = defaultMultiClusterDir
224         }
225
226         //Create Directory for the specific cluster
227         clusterDir := multiClusterDir + "/" + clusterName
228         os.MkdirAll(clusterDir, os.ModePerm)
229
230         //Create Maps to be used for cluster ip address to label configmap
231         clusterLabel := make(map[string]string)
232         clusterLabel["cluster"] = clusterName
233         clusterData := make(map[string]string)
234
235
236
237        //Iterate through mastersList and get all the mac addresses and IP addresses
238        for _, masterMap := range mastersList {
239
240                 for masterLabel, master := range masterMap {
241                    masterMAC := master.MACaddress
242                    hostIPaddress := ""
243
244                    if masterMAC == "" {
245                       err = fmt.Errorf("MAC address for masterNode %s not provided\n", masterLabel)
246                       return reconcile.Result{}, err
247                    }
248
249                    containsMac, bmhCR := checkMACaddress(bareMetalHostList, masterMAC)
250
251                    //Check 'cluster-type' label for Virtlet VMs
252                    if clusterType == "virtlet-vm" {
253                        //Get VM IP address of master
254                        hostIPaddress, err = getVMIPaddress(virtletVMList, masterMAC)
255                        if err != nil || hostIPaddress == "" {
256                            err = fmt.Errorf("IP address not found for VM with MAC address %s \n", masterMAC)
257                            return reconcile.Result{}, err
258                        }
259                        containsMac = true
260                    }
261
262                    if containsMac{
263
264                        if clusterType != "virtlet-vm" {
265                            fmt.Printf("BareMetalHost CR %s has NIC with MAC Address %s\n", bmhCR, masterMAC)
266
267                            //Get IP address of master
268                            hostIPaddress, err = getHostIPaddress(masterMAC, dhcpLeaseFile )
269                            if err != nil || hostIPaddress == ""{
270                                err = fmt.Errorf("IP address not found for host with MAC address %s \n", masterMAC)
271                                return reconcile.Result{}, err
272                            }
273                        }
274
275                        allString += masterLabel + "  ansible_ssh_host="  + hostIPaddress + " ansible_ssh_port=22" + "\n"
276                        masterString += masterLabel + "\n"
277                        clusterData[masterTag + masterLabel] = hostIPaddress
278
279                        fmt.Printf("%s : %s \n", hostIPaddress, masterMAC)
280
281                        if len(workersList) != 0 {
282
283                            //Iterate through workersList and get all the mac addresses
284                            for _, workerMap := range workersList {
285
286                                //Get worker labels from the workermap
287                                for workerLabel, worker := range workerMap {
288
289                                    //Check if workerString already contains worker label
290                                    containsWorkerLabel := strings.Contains(workerString, workerLabel)
291                                    workerMAC := worker.MACaddress
292                                    hostIPaddress = ""
293
294                                    //Error occurs if the same label is given to different hosts (assumption,
295                                    //each MAC address represents a unique host
296                                    if workerLabel == masterLabel && workerMAC != masterMAC && workerMAC != "" {
297                                      if containsWorkerLabel {
298                                             strings.ReplaceAll(workerString, workerLabel, "")
299                                          }
300                                       err = fmt.Errorf(`A node with label %s already exists, modify resource and assign a
301                                       different label to node with MACAddress %s`, workerLabel, workerMAC)
302                                       return reconcile.Result{}, err
303
304                                    //same node performs worker and master roles
305                                    } else if workerLabel == masterLabel && !containsWorkerLabel {
306                                         workerString += workerLabel + "\n"
307
308                                         //Add host to ip address config map with worker tag
309                                         hostIPaddress = clusterData[masterTag + masterLabel]
310                                         clusterData[workerTag + masterLabel] = hostIPaddress
311
312                                    //Error occurs if the same node is given different labels
313                                    } else if workerLabel != masterLabel && workerMAC == masterMAC {
314                                          if containsWorkerLabel {
315                                             strings.ReplaceAll(workerString, workerLabel, "")
316                                          }
317                                          err = fmt.Errorf(`A node with label %s already exists, modify resource and assign a
318                                                         different label to node with MACAddress %s`, workerLabel, workerMAC)
319                                          return reconcile.Result{}, err
320
321                                    //worker node is different from any master node and it has not been added to the worker list
322                                    } else if workerLabel != masterLabel && !containsWorkerLabel {
323
324                                         // Error occurs if MAC address not provided for worker node not matching master
325                                         if workerMAC == "" {
326                                           err = fmt.Errorf("MAC address for worker %s not provided", workerLabel)
327                                           return reconcile.Result{}, err
328                                          }
329
330                                         containsMac, bmhCR := checkMACaddress(bareMetalHostList, workerMAC)
331
332                                         if clusterType == "virtlet-vm" {
333                                             //Get VM IP address of master
334                                             hostIPaddress, err = getVMIPaddress(virtletVMList, workerMAC)
335                                             if err != nil || hostIPaddress == "" {
336                                                 err = fmt.Errorf("IP address not found for VM with MAC address %s \n", workerMAC)
337                                                 return reconcile.Result{}, err
338                                             }
339                                             containsMac = true
340                                         }
341
342                                         if containsMac{
343
344                                            if clusterType != "virtlet-vm" {
345                                                fmt.Printf("Host %s matches that macAddress\n", bmhCR)
346
347                                                //Get IP address of worker
348                                                hostIPaddress, err = getHostIPaddress(workerMAC, dhcpLeaseFile )
349                                                if err != nil {
350                                                    fmt.Errorf("IP address not found for host with MAC address %s \n", workerMAC)
351                                                    return reconcile.Result{}, err
352                                                }
353                                            }
354                                            fmt.Printf("%s : %s \n", hostIPaddress, workerMAC)
355
356
357                                            allString += workerLabel + "  ansible_ssh_host="  + hostIPaddress + " ansible_ssh_port=22" + "\n"
358                                            workerString += workerLabel + "\n"
359                                            clusterData[workerTag + workerLabel] = hostIPaddress
360
361                                        //No host found that matches the worker MAC
362                                        } else {
363
364                                             err = fmt.Errorf("Host with MAC Address %s not found\n", workerMAC)
365                                             return reconcile.Result{}, err
366                                           }
367                                    }
368                              }
369                        }
370                    //No worker node specified, add master as worker node
371                    } else if len(workersList) == 0 && !strings.Contains(workerString, masterLabel) {
372                        workerString += masterLabel + "\n"
373
374                        //Add host to ip address config map with worker tag
375                        hostIPaddress = clusterData[masterTag + masterLabel]
376                        clusterData[workerTag + masterLabel] = hostIPaddress
377                    }
378
379                    //No host matching master MAC found
380                    } else {
381                       err = fmt.Errorf("Host with MAC Address %s not found\n", masterMAC)
382                       return reconcile.Result{}, err
383                    }
384              }
385         }
386
387         //Create host.ini file
388         //iniHostFilePath := kudInstallerScript + "/inventory/hosts.ini"
389         iniHostFilePath := clusterDir + "/hosts.ini"
390         newFile, err := os.Create(iniHostFilePath)
391         defer newFile.Close()
392
393
394         if err != nil {
395            fmt.Printf("Error occured while creating file \n %v", err)
396            return reconcile.Result{}, err
397         }
398
399         hostFile, err := ini.Load(iniHostFilePath)
400         if err != nil {
401            fmt.Printf("Error occured while Loading file \n %v", err)
402            return reconcile.Result{}, err
403         }
404
405         _, err = hostFile.NewRawSection("all", allString)
406         if err != nil {
407            fmt.Printf("Error occured while creating section \n %v", err)
408            return reconcile.Result{}, err
409         }
410         _, err = hostFile.NewRawSection("kube-master", masterString)
411         if err != nil {
412            fmt.Printf("Error occured while creating section \n %v", err)
413            return reconcile.Result{}, err
414         }
415
416         _, err = hostFile.NewRawSection("kube-node", workerString)
417         if err != nil {
418            fmt.Printf("Error occured while creating section \n %v", err)
419            return reconcile.Result{}, err
420         }
421
422         _, err = hostFile.NewRawSection("etcd", masterString)
423         if err != nil {
424            fmt.Printf("Error occured while creating section \n %v", err)
425            return reconcile.Result{}, err
426         }
427
428         if clusterType == "virtlet-vm" {
429                 _, err = hostFile.NewRawSection("ovn-central", masterString)
430                 if err != nil {
431                         fmt.Printf("Error occured while creating section \n %v", err)
432                         return reconcile.Result{}, err
433                 }
434                 _, err = hostFile.NewRawSection("ovn-controller", masterString)
435                 if err != nil {
436                         fmt.Printf("Error occured while creating section \n %v", err)
437                         return reconcile.Result{}, err
438                 }
439         }
440
441         _, err = hostFile.NewRawSection("k8s-cluster:children", "kube-node\n" + "kube-master")
442         if err != nil {
443            fmt.Printf("Error occured while creating section \n %v", err)
444            return reconcile.Result{}, err
445         }
446
447
448         //Create host.ini file for KUD
449         hostFile.SaveTo(iniHostFilePath)
450
451         //Install KUD
452         err = createKUDinstallerJob(clusterName, request.Namespace, clusterLabel, r.clientset)
453         if err != nil {
454            fmt.Printf("Error occured while creating KUD Installer job for cluster %v\n ERROR: %v", clusterName, err)
455            return reconcile.Result{}, err
456         }
457
458         //Start separate thread to keep checking job status, Create an IP address configmap
459         //for cluster if KUD is successfully installed
460         go checkJob(clusterName, request.Namespace, clusterData, clusterLabel, r.clientset)
461
462         return reconcile.Result{}, nil
463
464        }
465
466
467
468         ///////////////////////////////////////////////////////////////////////////////////////////////
469         ////////////////         Software CR was created so install software         /////////////////
470         //////////////////////////////////////////////////////////////////////////////////////////////
471         softwareClusterName, masterSoftwareList, workerSoftwareList := getSoftwareList(softwareInstance)
472         defaultSSHPrivateKey := "/root/.ssh/id_rsa"
473
474         //Get IP address configmap for the cluster
475         clusterConfigMapData, err := getConfigMapData(request.Namespace, softwareClusterName, r.clientset)
476         if err != nil {
477            fmt.Printf("Error occured while retrieving IP address Data for cluster %s, ERROR: %v\n", softwareClusterName, err)
478            return reconcile.Result{}, err
479         }
480
481         for hostLabel, ipAddress := range clusterConfigMapData {
482
483             if strings.Contains(hostLabel, masterTag) {
484                // Its a master node, install master software
485                err = softwareInstaller(ipAddress, defaultSSHPrivateKey, masterSoftwareList)
486                if err != nil {
487                   fmt.Printf("Error occured while installing master software in host %s, ERROR: %v\n", hostLabel, err)
488                }
489             } else if strings.Contains(hostLabel, workerTag) {
490               // Its a worker node, install worker software
491               err = softwareInstaller(ipAddress, defaultSSHPrivateKey, workerSoftwareList)
492               if err != nil {
493                   fmt.Printf("Error occured while installing worker software in host %s, ERROR: %v\n", hostLabel, err)
494                }
495
496             }
497
498         }
499
500         return reconcile.Result{}, nil
501 }
502
503 //Function to Get List containing baremetal hosts
504 func listBareMetalHosts(bmhDynamicClient dynamic.Interface) (*unstructured.UnstructuredList, error) {
505
506     //Create GVR representing a BareMetalHost CR
507     bmhGVR := schema.GroupVersionResource{
508       Group:    "metal3.io",
509       Version:  "v1alpha1",
510       Resource: "baremetalhosts",
511     }
512
513     //Get List containing all BareMetalHosts CRs
514     bareMetalHosts, err := bmhDynamicClient.Resource(bmhGVR).List(metav1.ListOptions{})
515     if err != nil {
516        fmt.Printf("Error occured, cannot get BareMetalHosts list, Error: %v\n", err)
517        return &unstructured.UnstructuredList{}, err
518     }
519
520     return bareMetalHosts, nil
521 }
522
523
524 //Function to check if BareMetalHost containing MAC address exist
525 func checkMACaddress(bareMetalHostList *unstructured.UnstructuredList, macAddress string) (bool, string) {
526
527      //Convert macAddress to byte array for comparison
528      macAddressByte :=  []byte(macAddress)
529      macBool := false
530
531      for _, bareMetalHost := range bareMetalHostList.Items {
532          bmhJson, _ := bareMetalHost.MarshalJSON()
533
534          macBool = bytes.Contains(bmhJson, macAddressByte)
535          if macBool{
536              return macBool, bareMetalHost.GetName()
537          }
538
539       }
540
541          return macBool, ""
542
543 }
544
545
546 //Function to get the IP address of a host from the DHCP file
547 func getHostIPaddress(macAddress string, dhcpLeaseFilePath string ) (string, error) {
548
549      //Read the dhcp lease file
550      dhcpFile, err := ioutil.ReadFile(dhcpLeaseFilePath)
551      if err != nil {
552         fmt.Printf("Failed to read lease file\n")
553         return "", err
554      }
555
556      dhcpLeases := string(dhcpFile)
557
558      //Regex to use to search dhcpLeases
559      reg := "lease.*{|ethernet.*|\n. binding state.*"
560      re, err := regexp.Compile(reg)
561      if err != nil {
562         fmt.Printf("Could not create Regexp object, Error %v occured\n", err)
563         return "", err
564      }
565
566      //Get String containing leased Ip addresses and Corressponding MAC addresses
567      out := re.FindAllString(dhcpLeases, -1)
568      outString := strings.Join(out, " ")
569      stringReplacer := strings.NewReplacer("lease", "", "ethernet ", "", ";", "",
570      " binding state", "", "{", "")
571      replaced := stringReplacer.Replace(outString)
572      ipMacList := strings.Fields(replaced)
573
574
575      //Get IP addresses corresponding to Input MAC Address
576      for idx := len(ipMacList)-1 ; idx >= 0; idx -- {
577          item := ipMacList[idx]
578          if item == macAddress  {
579
580             leaseState := ipMacList[idx -1]
581             if leaseState != "active" {
582                err := fmt.Errorf("No active ip address lease found for MAC address %s \n", macAddress)
583                fmt.Printf("%v\n", err)
584                return "", err
585             }
586             ipAdd := ipMacList[idx - 2]
587             return ipAdd, nil
588     }
589
590  }
591      return "", nil
592 }
593
594 //Function to create configmap 
595 func createConfigMap(data, labels map[string]string, namespace string, clientset kubernetes.Interface) error{
596
597      configmapClient := clientset.CoreV1().ConfigMaps(namespace)
598
599      configmap := &corev1.ConfigMap{
600
601         ObjectMeta: metav1.ObjectMeta{
602                         Name: labels["cluster"] + "-configmap",
603                         Labels: labels,
604                 },
605         Data: data,
606      }
607
608
609       _, err := configmapClient.Create(configmap)
610       if err != nil {
611          return err
612
613       }
614       return nil
615
616 }
617
618 //Function to get configmap Data
619 func getConfigMapData(namespace, clusterName string, clientset kubernetes.Interface) (map[string]string, error) {
620
621      configmapClient := clientset.CoreV1().ConfigMaps(namespace)
622      configmapName := clusterName + "-configmap"
623      clusterConfigmap, err := configmapClient.Get(configmapName, metav1.GetOptions{})
624      if err != nil {
625         return nil, err
626      }
627
628      configmapData := clusterConfigmap.Data
629      return configmapData, nil
630 }
631
632 //Function to create job for KUD installation
633 func createKUDinstallerJob(clusterName, namespace string, labels map[string]string, clientset kubernetes.Interface) error{
634
635     var backOffLimit int32 = 0
636     var privi bool = true
637
638
639     jobClient := clientset.BatchV1().Jobs("default")
640
641         job := &batchv1.Job{
642
643         ObjectMeta: metav1.ObjectMeta{
644                         Name: "kud-" + clusterName,
645                        Labels: labels,
646                 },
647                 Spec: batchv1.JobSpec{
648                       Template: corev1.PodTemplateSpec{
649                                 ObjectMeta: metav1.ObjectMeta{
650                                         Labels: labels,
651                                 },
652
653
654                         Spec: corev1.PodSpec{
655                               HostNetwork: true,
656                               Containers: []corev1.Container{{
657                                           Name: "kud",
658                                           Image: "github.com/onap/multicloud-k8s:latest",
659                                           ImagePullPolicy: "IfNotPresent",
660                                           VolumeMounts: []corev1.VolumeMount{{
661                                                         Name: "multi-cluster",
662                                                         MountPath: "/opt/kud/multi-cluster",
663                                                         },
664                                                         {
665                                                         Name: "secret-volume",
666                                                         MountPath: "/.ssh",
667                                                         },
668
669                                            },
670                                            Command: []string{"/bin/sh","-c"},
671                                            Args: []string{"cp -r /.ssh /root/; chmod -R 600 /root/.ssh; ./installer --cluster " +  clusterName},
672                                            SecurityContext: &corev1.SecurityContext{
673                                                             Privileged : &privi,
674
675                                            },
676                                           },
677                                  },
678                                  Volumes: []corev1.Volume{{
679                                           Name: "multi-cluster",
680                                           VolumeSource: corev1.VolumeSource{
681                                                        HostPath: &corev1.HostPathVolumeSource{
682                                                               Path : "/opt/kud/multi-cluster",
683                                                      }}},
684                                           {
685                                           Name: "secret-volume",
686                                           VolumeSource: corev1.VolumeSource{
687                                                         Secret: &corev1.SecretVolumeSource{
688                                                               SecretName: "ssh-key-secret",
689                                                         },
690
691                                           }}},
692                                  RestartPolicy: "Never",
693                               },
694
695                              },
696                              BackoffLimit : &backOffLimit,
697                              },
698
699                          }
700                     _, err := jobClient.Create(job)
701                     if err != nil {
702                        fmt.Printf("ERROR occured while creating job to install KUD\n ERROR:%v", err)
703                        return err
704                     }
705                     return nil
706
707 }
708
709 //Function to Check if job succeeded
710 func checkJob(clusterName, namespace string, data, labels map[string]string, clientset kubernetes.Interface) {
711
712      fmt.Printf("\nChecking job status for cluster %s\n", clusterName)
713      jobName := "kud-" + clusterName
714      jobClient := clientset.BatchV1().Jobs(namespace)
715
716      for {
717          time.Sleep(2 * time.Second)
718
719          job, err := jobClient.Get(jobName, metav1.GetOptions{})
720          if err != nil {
721             fmt.Printf("ERROR: %v occured while retrieving job: %s", err, jobName)
722             return
723          }
724          jobSucceeded := job.Status.Succeeded
725          jobFailed := job.Status.Failed
726
727          if jobSucceeded == 1 {
728             fmt.Printf("\n Job succeeded, KUD successfully installed in Cluster %s\n", clusterName)
729
730             //KUD was installed successfully create configmap to store IP address info for the cluster
731             err = createConfigMap(data, labels, namespace, clientset)
732             if err != nil {
733                fmt.Printf("Error occured while creating Ip address configmap for cluster %v\n ERROR: %v", clusterName, err)
734                return
735             }
736             return
737          }
738
739         if jobFailed == 1 {
740            fmt.Printf("\n Job Failed, KUD not installed in Cluster %s, check pod logs\n", clusterName)
741            return
742         }
743
744      }
745     return
746
747 }
748
749 //Function to get software list from software CR
750 func getSoftwareList(softwareCR *bpav1alpha1.Software) (string, []interface{}, []interface{}) {
751
752      CRclusterName := softwareCR.GetLabels()["cluster"]
753
754      masterSofwareList := softwareCR.Spec.MasterSoftware
755      workerSoftwareList := softwareCR.Spec.WorkerSoftware
756
757      return CRclusterName, masterSofwareList, workerSoftwareList
758 }
759
760 //Function to install software in clusterHosts
761 func softwareInstaller(ipAddress, sshPrivateKey string, softwareList []interface{}) error {
762
763      var installString string
764      for _, software := range softwareList {
765
766         switch t := software.(type){
767         case string:
768              installString += software.(string) + " "
769         case interface{}:
770              softwareMap, errBool := software.(map[string]interface{})
771              if !errBool {
772                 fmt.Printf("Error occured, cannot install software %v\n", software)
773              }
774              for softwareName, versionMap := range softwareMap {
775
776                  versionMAP, _ := versionMap.(map[string]interface{})
777                  version := versionMAP["version"].(string)
778                  installString += softwareName + "=" + version + " "
779              }
780         default:
781             fmt.Printf("invalid format %v\n", t)
782         }
783
784      }
785
786      err := sshInstaller(installString, sshPrivateKey, ipAddress)
787      if err != nil {
788         return err
789      }
790      return nil
791
792 }
793
794 //Function to Run Installation commands via ssh
795 func sshInstaller(softwareString, sshPrivateKey, ipAddress string) error {
796
797      buffer, err := ioutil.ReadFile(sshPrivateKey)
798      if err != nil {
799         return err
800      }
801
802      key, err := ssh.ParsePrivateKey(buffer)
803      if err != nil {
804         return err
805      }
806
807      sshConfig := &ssh.ClientConfig{
808         User: "root",
809         Auth: []ssh.AuthMethod{
810               ssh.PublicKeys(key),
811      },
812
813      HostKeyCallback: ssh.InsecureIgnoreHostKey(),
814      }
815
816     client, err := ssh.Dial("tcp", ipAddress + ":22", sshConfig)
817     if err != nil {
818        return err
819     }
820
821     session, err := client.NewSession()
822     if err != nil {
823        return err
824     }
825
826     defer session.Close()
827     defer client.Close()
828
829     cmd := "sudo apt-get update && apt-get install " + softwareString + "-y"
830     err = session.Start(cmd)
831
832     if err != nil {
833        return err
834     }
835
836     return nil
837
838 }
839
840 func listVirtletVMs(clientset kubernetes.Interface) ([]VirtletVM, error) {
841
842         var vmPodList []VirtletVM
843
844         pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
845         if err != nil {
846                 fmt.Printf("Could not get pod info, Error: %v\n", err)
847                 return []VirtletVM{}, err
848         }
849
850         for _, pod := range pods.Items {
851                 var podAnnotation map[string]interface{}
852                 var podStatus corev1.PodStatus
853                 var podDefaultNetStatus []NetworksStatus
854
855                 annotation, err := json.Marshal(pod.ObjectMeta.GetAnnotations())
856                 if err != nil {
857                         fmt.Printf("Could not get pod annotations, Error: %v\n", err)
858                         return []VirtletVM{}, err
859                 }
860
861                 json.Unmarshal([]byte(annotation), &podAnnotation)
862                 if podAnnotation != nil && podAnnotation["kubernetes.io/target-runtime"] != nil {
863                         runtime := podAnnotation["kubernetes.io/target-runtime"].(string)
864
865                         podStatusJson, _ := json.Marshal(pod.Status)
866                         json.Unmarshal([]byte(podStatusJson), &podStatus)
867
868                         if runtime  == "virtlet.cloud" && podStatus.Phase == "Running" && podAnnotation["v1.multus-cni.io/default-network"] != nil {
869                                 ns := podAnnotation["v1.multus-cni.io/default-network"].(string)
870                                 json.Unmarshal([]byte(ns), &podDefaultNetStatus)
871
872                                 vmPodList = append(vmPodList, VirtletVM{podStatus.PodIP, podDefaultNetStatus[0].Mac})
873                         }
874                 }
875         }
876
877         return vmPodList, nil
878 }
879
880 func getVMIPaddress(vmList []VirtletVM, macAddress string) (string, error) {
881
882         for i := 0; i < len(vmList); i++ {
883                 if vmList[i].MACaddress == macAddress {
884                         return vmList[i].IPaddress, nil
885                 }
886         }
887         return "", nil
888 }
889