Add e2e script for Virtlet VM provisioning
[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         kudPlugins := provisioningInstance.Spec.KUDPlugins
195
196
197         bareMetalHostList, _ := listBareMetalHosts(r.bmhClient)
198         virtletVMList, _ := listVirtletVMs(r.clientset)
199
200
201
202
203         var allString string
204         var masterString string
205         var workerString string
206
207         dhcpLeaseFile := "/var/lib/dhcp/dhcpd.leases"
208         multiClusterDir := "/multi-cluster"
209
210         //Create Directory for the specific cluster
211         clusterDir := multiClusterDir + "/" + clusterName
212         os.MkdirAll(clusterDir, os.ModePerm)
213
214         //Create Maps to be used for cluster ip address to label configmap
215         clusterLabel := make(map[string]string)
216         clusterLabel["cluster"] = clusterName
217         clusterData := make(map[string]string)
218
219
220
221        //Iterate through mastersList and get all the mac addresses and IP addresses
222        for _, masterMap := range mastersList {
223
224                 for masterLabel, master := range masterMap {
225                    masterMAC := master.MACaddress
226                    hostIPaddress := ""
227
228                    if masterMAC == "" {
229                       err = fmt.Errorf("MAC address for masterNode %s not provided\n", masterLabel)
230                       return reconcile.Result{}, err
231                    }
232
233                    containsMac, bmhCR := checkMACaddress(bareMetalHostList, masterMAC)
234
235                    //Check 'cluster-type' label for Virtlet VMs
236                    if clusterType == "virtlet-vm" {
237                        //Get VM IP address of master
238                        hostIPaddress, err = getVMIPaddress(virtletVMList, masterMAC)
239                        if err != nil || hostIPaddress == "" {
240                            err = fmt.Errorf("IP address not found for VM with MAC address %s \n", masterMAC)
241                            return reconcile.Result{}, err
242                        }
243                        containsMac = true
244                    }
245
246                    if containsMac{
247
248                        if clusterType != "virtlet-vm" {
249                            fmt.Printf("BareMetalHost CR %s has NIC with MAC Address %s\n", bmhCR, masterMAC)
250
251                            //Get IP address of master
252                            hostIPaddress, err = getHostIPaddress(masterMAC, dhcpLeaseFile )
253                            if err != nil || hostIPaddress == ""{
254                                err = fmt.Errorf("IP address not found for host with MAC address %s \n", masterMAC)
255                                return reconcile.Result{}, err
256                            }
257                        }
258
259                        allString += masterLabel + "  ansible_ssh_host="  + hostIPaddress + " ansible_ssh_port=22" + "\n"
260                        if clusterType == "virtlet-vm" {
261                            allString = masterLabel + "  ansible_ssh_host="  + hostIPaddress + " ansible_ssh_port=22" + " ansible_ssh_user=root" + " ansible_ssh_pass=root" + "\n"
262                        }
263                        masterString += masterLabel + "\n"
264                        clusterData[masterTag + masterLabel] = hostIPaddress
265
266                        fmt.Printf("%s : %s \n", hostIPaddress, masterMAC)
267
268                        if len(workersList) != 0 {
269
270                            //Iterate through workersList and get all the mac addresses
271                            for _, workerMap := range workersList {
272
273                                //Get worker labels from the workermap
274                                for workerLabel, worker := range workerMap {
275
276                                    //Check if workerString already contains worker label
277                                    containsWorkerLabel := strings.Contains(workerString, workerLabel)
278                                    workerMAC := worker.MACaddress
279                                    hostIPaddress = ""
280
281                                    //Error occurs if the same label is given to different hosts (assumption,
282                                    //each MAC address represents a unique host
283                                    if workerLabel == masterLabel && workerMAC != masterMAC && workerMAC != "" {
284                                      if containsWorkerLabel {
285                                             strings.ReplaceAll(workerString, workerLabel, "")
286                                          }
287                                       err = fmt.Errorf(`A node with label %s already exists, modify resource and assign a
288                                       different label to node with MACAddress %s`, workerLabel, workerMAC)
289                                       return reconcile.Result{}, err
290
291                                    //same node performs worker and master roles
292                                    } else if workerLabel == masterLabel && !containsWorkerLabel {
293                                         workerString += workerLabel + "\n"
294
295                                         //Add host to ip address config map with worker tag
296                                         hostIPaddress = clusterData[masterTag + masterLabel]
297                                         clusterData[workerTag + masterLabel] = hostIPaddress
298
299                                    //Error occurs if the same node is given different labels
300                                    } else if workerLabel != masterLabel && workerMAC == masterMAC {
301                                          if containsWorkerLabel {
302                                             strings.ReplaceAll(workerString, workerLabel, "")
303                                          }
304                                          err = fmt.Errorf(`A node with label %s already exists, modify resource and assign a
305                                                         different label to node with MACAddress %s`, workerLabel, workerMAC)
306                                          return reconcile.Result{}, err
307
308                                    //worker node is different from any master node and it has not been added to the worker list
309                                    } else if workerLabel != masterLabel && !containsWorkerLabel {
310
311                                         // Error occurs if MAC address not provided for worker node not matching master
312                                         if workerMAC == "" {
313                                           err = fmt.Errorf("MAC address for worker %s not provided", workerLabel)
314                                           return reconcile.Result{}, err
315                                          }
316
317                                         containsMac, bmhCR := checkMACaddress(bareMetalHostList, workerMAC)
318
319                                         if clusterType == "virtlet-vm" {
320                                             //Get VM IP address of master
321                                             hostIPaddress, err = getVMIPaddress(virtletVMList, workerMAC)
322                                             if err != nil || hostIPaddress == "" {
323                                                 err = fmt.Errorf("IP address not found for VM with MAC address %s \n", workerMAC)
324                                                 return reconcile.Result{}, err
325                                             }
326                                             containsMac = true
327                                         }
328
329                                         if containsMac{
330
331                                            if clusterType != "virtlet-vm" {
332                                                fmt.Printf("Host %s matches that macAddress\n", bmhCR)
333
334                                                //Get IP address of worker
335                                                hostIPaddress, err = getHostIPaddress(workerMAC, dhcpLeaseFile )
336                                                if err != nil {
337                                                    fmt.Errorf("IP address not found for host with MAC address %s \n", workerMAC)
338                                                    return reconcile.Result{}, err
339                                                }
340                                            }
341                                            fmt.Printf("%s : %s \n", hostIPaddress, workerMAC)
342
343                                            allString += workerLabel + "  ansible_ssh_host="  + hostIPaddress + " ansible_ssh_port=22" + "\n"
344                                            if clusterType == "virtlet-vm" {
345                                                allString = masterLabel + "  ansible_ssh_host="  + hostIPaddress + " ansible_ssh_port=22" + " ansible_ssh_user=root" + " ansible_ssh_pass=root" + "\n"
346                                            }
347                                            workerString += workerLabel + "\n"
348                                            clusterData[workerTag + workerLabel] = hostIPaddress
349
350                                        //No host found that matches the worker MAC
351                                        } else {
352
353                                             err = fmt.Errorf("Host with MAC Address %s not found\n", workerMAC)
354                                             return reconcile.Result{}, err
355                                           }
356                                    }
357                              }
358                        }
359                    //No worker node specified, add master as worker node
360                    } else if len(workersList) == 0 && !strings.Contains(workerString, masterLabel) {
361                        workerString += masterLabel + "\n"
362
363                        //Add host to ip address config map with worker tag
364                        hostIPaddress = clusterData[masterTag + masterLabel]
365                        clusterData[workerTag + masterLabel] = hostIPaddress
366                    }
367
368                    //No host matching master MAC found
369                    } else {
370                       err = fmt.Errorf("Host with MAC Address %s not found\n", masterMAC)
371                       return reconcile.Result{}, err
372                    }
373              }
374         }
375
376         //Create host.ini file
377         //iniHostFilePath := kudInstallerScript + "/inventory/hosts.ini"
378         iniHostFilePath := clusterDir + "/hosts.ini"
379         newFile, err := os.Create(iniHostFilePath)
380         defer newFile.Close()
381
382
383         if err != nil {
384            fmt.Printf("Error occured while creating file \n %v", err)
385            return reconcile.Result{}, err
386         }
387
388         hostFile, err := ini.Load(iniHostFilePath)
389         if err != nil {
390            fmt.Printf("Error occured while Loading file \n %v", err)
391            return reconcile.Result{}, err
392         }
393
394         _, err = hostFile.NewRawSection("all", allString)
395         if err != nil {
396            fmt.Printf("Error occured while creating section \n %v", err)
397            return reconcile.Result{}, err
398         }
399         _, err = hostFile.NewRawSection("kube-master", masterString)
400         if err != nil {
401            fmt.Printf("Error occured while creating section \n %v", err)
402            return reconcile.Result{}, err
403         }
404
405         _, err = hostFile.NewRawSection("kube-node", workerString)
406         if err != nil {
407            fmt.Printf("Error occured while creating section \n %v", err)
408            return reconcile.Result{}, err
409         }
410
411         _, err = hostFile.NewRawSection("etcd", masterString)
412         if err != nil {
413            fmt.Printf("Error occured while creating section \n %v", err)
414            return reconcile.Result{}, err
415         }
416
417         _, err = hostFile.NewRawSection("ovn-central", masterString)
418         if err != nil {
419            fmt.Printf("Error occured while creating section \n %v", err)
420            return reconcile.Result{}, err
421         }
422
423         _, err = hostFile.NewRawSection("ovn-controller", workerString)
424         if err != nil {
425            fmt.Printf("Error occured while creating section \n %v", err)
426            return reconcile.Result{}, err
427         }
428
429         _, err = hostFile.NewRawSection("virtlet", workerString)
430         if err != nil {
431            fmt.Printf("Error occured while creating section \n %v", err)
432            return reconcile.Result{}, err
433         }
434
435         _, err = hostFile.NewRawSection("k8s-cluster:children", "kube-node\n" + "kube-master")
436         if err != nil {
437            fmt.Printf("Error occured while creating section \n %v", err)
438            return reconcile.Result{}, err
439         }
440
441
442         //Create host.ini file for KUD
443         hostFile.SaveTo(iniHostFilePath)
444
445         //Install KUD
446         err = createKUDinstallerJob(clusterName, request.Namespace, clusterLabel, kudPlugins,  r.clientset)
447         if err != nil {
448            fmt.Printf("Error occured while creating KUD Installer job for cluster %v\n ERROR: %v", clusterName, err)
449            return reconcile.Result{}, err
450         }
451
452         //Start separate thread to keep checking job status, Create an IP address configmap
453         //for cluster if KUD is successfully installed
454         go checkJob(clusterName, request.Namespace, clusterData, clusterLabel, r.clientset)
455
456         return reconcile.Result{}, nil
457
458        }
459
460
461
462         ///////////////////////////////////////////////////////////////////////////////////////////////
463         ////////////////         Software CR was created so install software         /////////////////
464         //////////////////////////////////////////////////////////////////////////////////////////////
465         softwareClusterName, masterSoftwareList, workerSoftwareList := getSoftwareList(softwareInstance)
466         defaultSSHPrivateKey := "/root/.ssh/id_rsa"
467
468         //Get IP address configmap for the cluster
469         clusterConfigMapData, err := getConfigMapData(request.Namespace, softwareClusterName, r.clientset)
470         if err != nil {
471            fmt.Printf("Error occured while retrieving IP address Data for cluster %s, ERROR: %v\n", softwareClusterName, err)
472            return reconcile.Result{}, err
473         }
474
475         for hostLabel, ipAddress := range clusterConfigMapData {
476
477             if strings.Contains(hostLabel, masterTag) {
478                // Its a master node, install master software
479                err = softwareInstaller(ipAddress, defaultSSHPrivateKey, masterSoftwareList)
480                if err != nil {
481                   fmt.Printf("Error occured while installing master software in host %s, ERROR: %v\n", hostLabel, err)
482                }
483             } else if strings.Contains(hostLabel, workerTag) {
484               // Its a worker node, install worker software
485               err = softwareInstaller(ipAddress, defaultSSHPrivateKey, workerSoftwareList)
486               if err != nil {
487                   fmt.Printf("Error occured while installing worker software in host %s, ERROR: %v\n", hostLabel, err)
488                }
489
490             }
491
492         }
493
494         return reconcile.Result{}, nil
495 }
496
497 //Function to Get List containing baremetal hosts
498 func listBareMetalHosts(bmhDynamicClient dynamic.Interface) (*unstructured.UnstructuredList, error) {
499
500     //Create GVR representing a BareMetalHost CR
501     bmhGVR := schema.GroupVersionResource{
502       Group:    "metal3.io",
503       Version:  "v1alpha1",
504       Resource: "baremetalhosts",
505     }
506
507     //Get List containing all BareMetalHosts CRs
508     bareMetalHosts, err := bmhDynamicClient.Resource(bmhGVR).List(metav1.ListOptions{})
509     if err != nil {
510        fmt.Printf("Error occured, cannot get BareMetalHosts list, Error: %v\n", err)
511        return &unstructured.UnstructuredList{}, err
512     }
513
514     return bareMetalHosts, nil
515 }
516
517
518 //Function to check if BareMetalHost containing MAC address exist
519 func checkMACaddress(bareMetalHostList *unstructured.UnstructuredList, macAddress string) (bool, string) {
520
521      //Convert macAddress to byte array for comparison
522      macAddressByte :=  []byte(macAddress)
523      macBool := false
524
525      for _, bareMetalHost := range bareMetalHostList.Items {
526          bmhJson, _ := bareMetalHost.MarshalJSON()
527
528          macBool = bytes.Contains(bmhJson, macAddressByte)
529          if macBool{
530              return macBool, bareMetalHost.GetName()
531          }
532
533       }
534
535          return macBool, ""
536
537 }
538
539
540 //Function to get the IP address of a host from the DHCP file
541 func getHostIPaddress(macAddress string, dhcpLeaseFilePath string ) (string, error) {
542
543      //Read the dhcp lease file
544      dhcpFile, err := ioutil.ReadFile(dhcpLeaseFilePath)
545      if err != nil {
546         fmt.Printf("Failed to read lease file\n")
547         return "", err
548      }
549
550      dhcpLeases := string(dhcpFile)
551
552      //Regex to use to search dhcpLeases
553      reg := "lease.*{|ethernet.*|\n. binding state.*"
554      re, err := regexp.Compile(reg)
555      if err != nil {
556         fmt.Printf("Could not create Regexp object, Error %v occured\n", err)
557         return "", err
558      }
559
560      //Get String containing leased Ip addresses and Corressponding MAC addresses
561      out := re.FindAllString(dhcpLeases, -1)
562      outString := strings.Join(out, " ")
563      stringReplacer := strings.NewReplacer("lease", "", "ethernet ", "", ";", "",
564      " binding state", "", "{", "")
565      replaced := stringReplacer.Replace(outString)
566      ipMacList := strings.Fields(replaced)
567
568
569      //Get IP addresses corresponding to Input MAC Address
570      for idx := len(ipMacList)-1 ; idx >= 0; idx -- {
571          item := ipMacList[idx]
572          if item == macAddress  {
573
574             leaseState := ipMacList[idx -1]
575             if leaseState != "active" {
576                err := fmt.Errorf("No active ip address lease found for MAC address %s \n", macAddress)
577                fmt.Printf("%v\n", err)
578                return "", err
579             }
580             ipAdd := ipMacList[idx - 2]
581             return ipAdd, nil
582     }
583
584  }
585      return "", nil
586 }
587
588 //Function to create configmap 
589 func createConfigMap(data, labels map[string]string, namespace string, clientset kubernetes.Interface) error{
590
591      configmapClient := clientset.CoreV1().ConfigMaps(namespace)
592
593      configmap := &corev1.ConfigMap{
594
595         ObjectMeta: metav1.ObjectMeta{
596                         Name: labels["cluster"] + "-configmap",
597                         Labels: labels,
598                 },
599         Data: data,
600      }
601
602
603       _, err := configmapClient.Create(configmap)
604       if err != nil {
605          return err
606
607       }
608       return nil
609
610 }
611
612 //Function to get configmap Data
613 func getConfigMapData(namespace, clusterName string, clientset kubernetes.Interface) (map[string]string, error) {
614
615      configmapClient := clientset.CoreV1().ConfigMaps(namespace)
616      configmapName := clusterName + "-configmap"
617      clusterConfigmap, err := configmapClient.Get(configmapName, metav1.GetOptions{})
618      if err != nil {
619         return nil, err
620      }
621
622      configmapData := clusterConfigmap.Data
623      return configmapData, nil
624 }
625
626 //Function to create job for KUD installation
627 func createKUDinstallerJob(clusterName, namespace string, labels map[string]string, kudPlugins []string, clientset kubernetes.Interface) error{
628
629     var backOffLimit int32 = 0
630     var privi bool = true
631
632     installerString := " ./installer --cluster " + clusterName
633
634     // Check if any plugin was specified
635     if len(kudPlugins) > 0 {
636             plugins := " --plugins"
637
638             for _, plug := range kudPlugins {
639                plugins += " " + plug
640             }
641
642            installerString += plugins
643     }
644
645
646     jobClient := clientset.BatchV1().Jobs("default")
647
648         job := &batchv1.Job{
649
650         ObjectMeta: metav1.ObjectMeta{
651                         Name: "kud-" + clusterName,
652                        Labels: labels,
653                 },
654                 Spec: batchv1.JobSpec{
655                       Template: corev1.PodTemplateSpec{
656                                 ObjectMeta: metav1.ObjectMeta{
657                                         Labels: labels,
658                                 },
659
660
661                         Spec: corev1.PodSpec{
662                               HostNetwork: true,
663                               Containers: []corev1.Container{{
664                                           Name: "kud",
665                                           Image: "github.com/onap/multicloud-k8s:latest",
666                                           ImagePullPolicy: "IfNotPresent",
667                                           VolumeMounts: []corev1.VolumeMount{{
668                                                         Name: "multi-cluster",
669                                                         MountPath: "/opt/kud/multi-cluster",
670                                                         },
671                                                         {
672                                                         Name: "secret-volume",
673                                                         MountPath: "/.ssh",
674                                                         },
675
676                                            },
677                                            Command: []string{"/bin/sh","-c"},
678                                            Args: []string{"cp -r /.ssh /root/; chmod -R 600 /root/.ssh;" + installerString},
679                                            SecurityContext: &corev1.SecurityContext{
680                                                             Privileged : &privi,
681
682                                            },
683                                           },
684                                  },
685                                  Volumes: []corev1.Volume{{
686                                           Name: "multi-cluster",
687                                           VolumeSource: corev1.VolumeSource{
688                                                        HostPath: &corev1.HostPathVolumeSource{
689                                                               Path : "/opt/kud/multi-cluster",
690                                                      }}},
691                                           {
692                                           Name: "secret-volume",
693                                           VolumeSource: corev1.VolumeSource{
694                                                         Secret: &corev1.SecretVolumeSource{
695                                                               SecretName: "ssh-key-secret",
696                                                         },
697
698                                           }}},
699                                  RestartPolicy: "Never",
700                               },
701
702                              },
703                              BackoffLimit : &backOffLimit,
704                              },
705
706                          }
707                     _, err := jobClient.Create(job)
708                     if err != nil {
709                        fmt.Printf("ERROR occured while creating job to install KUD\n ERROR:%v", err)
710                        return err
711                     }
712                     return nil
713
714 }
715
716 //Function to Check if job succeeded
717 func checkJob(clusterName, namespace string, data, labels map[string]string, clientset kubernetes.Interface) {
718
719      fmt.Printf("\nChecking job status for cluster %s\n", clusterName)
720      jobName := "kud-" + clusterName
721      jobClient := clientset.BatchV1().Jobs(namespace)
722
723      for {
724          time.Sleep(2 * time.Second)
725
726          job, err := jobClient.Get(jobName, metav1.GetOptions{})
727          if err != nil {
728             fmt.Printf("ERROR: %v occured while retrieving job: %s", err, jobName)
729             return
730          }
731          jobSucceeded := job.Status.Succeeded
732          jobFailed := job.Status.Failed
733
734          if jobSucceeded == 1 {
735             fmt.Printf("\n Job succeeded, KUD successfully installed in Cluster %s\n", clusterName)
736
737             //KUD was installed successfully create configmap to store IP address info for the cluster
738             err = createConfigMap(data, labels, namespace, clientset)
739             if err != nil {
740                fmt.Printf("Error occured while creating Ip address configmap for cluster %v\n ERROR: %v", clusterName, err)
741                return
742             }
743             return
744          }
745
746         if jobFailed == 1 {
747            fmt.Printf("\n Job Failed, KUD not installed in Cluster %s, check pod logs\n", clusterName)
748            return
749         }
750
751      }
752     return
753
754 }
755
756 //Function to get software list from software CR
757 func getSoftwareList(softwareCR *bpav1alpha1.Software) (string, []interface{}, []interface{}) {
758
759      CRclusterName := softwareCR.GetLabels()["cluster"]
760
761      masterSofwareList := softwareCR.Spec.MasterSoftware
762      workerSoftwareList := softwareCR.Spec.WorkerSoftware
763
764      return CRclusterName, masterSofwareList, workerSoftwareList
765 }
766
767 //Function to install software in clusterHosts
768 func softwareInstaller(ipAddress, sshPrivateKey string, softwareList []interface{}) error {
769
770      var installString string
771      for _, software := range softwareList {
772
773         switch t := software.(type){
774         case string:
775              installString += software.(string) + " "
776         case interface{}:
777              softwareMap, errBool := software.(map[string]interface{})
778              if !errBool {
779                 fmt.Printf("Error occured, cannot install software %v\n", software)
780              }
781              for softwareName, versionMap := range softwareMap {
782
783                  versionMAP, _ := versionMap.(map[string]interface{})
784                  version := versionMAP["version"].(string)
785                  installString += softwareName + "=" + version + " "
786              }
787         default:
788             fmt.Printf("invalid format %v\n", t)
789         }
790
791      }
792
793      err := sshInstaller(installString, sshPrivateKey, ipAddress)
794      if err != nil {
795         return err
796      }
797      return nil
798
799 }
800
801 //Function to Run Installation commands via ssh
802 func sshInstaller(softwareString, sshPrivateKey, ipAddress string) error {
803
804      buffer, err := ioutil.ReadFile(sshPrivateKey)
805      if err != nil {
806         return err
807      }
808
809      key, err := ssh.ParsePrivateKey(buffer)
810      if err != nil {
811         return err
812      }
813
814      sshConfig := &ssh.ClientConfig{
815         User: "root",
816         Auth: []ssh.AuthMethod{
817               ssh.PublicKeys(key),
818      },
819
820      HostKeyCallback: ssh.InsecureIgnoreHostKey(),
821      }
822
823     client, err := ssh.Dial("tcp", ipAddress + ":22", sshConfig)
824     if err != nil {
825        return err
826     }
827
828     session, err := client.NewSession()
829     if err != nil {
830        return err
831     }
832
833     defer session.Close()
834     defer client.Close()
835
836     cmd := "sudo apt-get update && apt-get install " + softwareString + "-y"
837     err = session.Start(cmd)
838
839     if err != nil {
840        return err
841     }
842
843     return nil
844
845 }
846
847 func listVirtletVMs(clientset kubernetes.Interface) ([]VirtletVM, error) {
848
849         var vmPodList []VirtletVM
850
851         pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
852         if err != nil {
853                 fmt.Printf("Could not get pod info, Error: %v\n", err)
854                 return []VirtletVM{}, err
855         }
856
857         for _, pod := range pods.Items {
858                 var podAnnotation map[string]interface{}
859                 var podStatus corev1.PodStatus
860                 var podDefaultNetStatus []NetworksStatus
861
862                 annotation, err := json.Marshal(pod.ObjectMeta.GetAnnotations())
863                 if err != nil {
864                         fmt.Printf("Could not get pod annotations, Error: %v\n", err)
865                         return []VirtletVM{}, err
866                 }
867
868                 json.Unmarshal([]byte(annotation), &podAnnotation)
869                 if podAnnotation != nil && podAnnotation["kubernetes.io/target-runtime"] != nil {
870                         runtime := podAnnotation["kubernetes.io/target-runtime"].(string)
871
872                         podStatusJson, _ := json.Marshal(pod.Status)
873                         json.Unmarshal([]byte(podStatusJson), &podStatus)
874
875                         if runtime  == "virtlet.cloud" && podStatus.Phase == "Running" && podAnnotation["k8s.v1.cni.cncf.io/networks-status"] != nil {
876                                 ns := podAnnotation["k8s.v1.cni.cncf.io/networks-status"].(string)
877                                 json.Unmarshal([]byte(ns), &podDefaultNetStatus)
878
879                                 vmPodList = append(vmPodList, VirtletVM{podStatus.PodIP, podDefaultNetStatus[0].Mac})
880                         }
881                 }
882         }
883
884         return vmPodList, nil
885 }
886
887 func getVMIPaddress(vmList []VirtletVM, macAddress string) (string, error) {
888
889         for i := 0; i < len(vmList); i++ {
890                 if vmList[i].MACaddress == macAddress {
891                         return vmList[i].IPaddress, nil
892                 }
893         }
894         return "", nil
895 }