822ead513bcbc6daab0a0e7bcedfdd48e119eb09
[samplevnf.git] / VNFs / DPPD-PROX / helper-scripts / rapid / rapid_k8s_deployment.py
1 ##
2 ## Copyright (c) 2019-2020 Intel Corporation
3 ##
4 ## Licensed under the Apache License, Version 2.0 (the "License");
5 ## you may not use this file except in compliance with the License.
6 ## You may obtain a copy of the License at
7 ##
8 ##     http://www.apache.org/licenses/LICENSE-2.0
9 ##
10 ## Unless required by applicable law or agreed to in writing, software
11 ## distributed under the License is distributed on an "AS IS" BASIS,
12 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ## See the License for the specific language governing permissions and
14 ## limitations under the License.
15 ##
16
17 import sys
18 from kubernetes import client, config
19 try:
20     import configparser
21 except ImportError:
22     # Python 2.x fallback
23     import ConfigParser as configparser
24 import logging
25 from logging import handlers
26
27 from rapid_k8s_pod import Pod
28
29 class K8sDeployment:
30     """Deployment class to create containers for test execution in Kubernetes
31     environment. 
32     """
33     LOG_FILE_NAME = "createrapidk8s.log"
34     SSH_PRIVATE_KEY = "./rapid_rsa_key"
35     SSH_USER = "centos"
36
37     POD_YAML_TEMPLATE_FILE_NAME = "pod-rapid.yaml"
38
39     _log = None
40     _create_config = None
41     _runtime_config = None
42     _total_number_of_pods = 0
43     _pods = []
44
45     def __init__(self):
46         # Configure logger
47         self._log = logging.getLogger("k8srapid")
48         self._log.setLevel(logging.DEBUG)
49
50         console_formatter = logging.Formatter("%(message)s")
51         console_handler = logging.StreamHandler(sys.stdout)
52         console_handler.setLevel(logging.DEBUG)
53         console_handler.setFormatter(console_formatter)
54
55         file_formatter = logging.Formatter("%(asctime)s - "
56                                            "%(levelname)s - "
57                                            "%(message)s")
58         file_handler = logging.handlers.RotatingFileHandler(self.LOG_FILE_NAME,
59                                                             backupCount=10)
60         file_handler.setLevel(logging.DEBUG)
61         file_handler.setFormatter(file_formatter)
62
63         self._log.addHandler(file_handler)
64         self._log.addHandler(console_handler)
65
66         # Initialize k8s plugin
67         config.load_kube_config()
68         Pod.k8s_CoreV1Api = client.CoreV1Api()
69
70     def load_create_config(self, config_file_name):
71         """Read and parse configuration file for the test environment.
72         """
73         self._log.info("Loading configuration file %s", config_file_name)
74         self._create_config = configparser.RawConfigParser()
75         try:
76             self._create_config.read(config_file_name)
77         except Exception as e:
78             self._log.error("Failed to read config file!\n%s\n" % e)
79             return -1
80
81         # Now parse config file content
82         # Parse [DEFAULT] section
83         if self._create_config.has_option("DEFAULT", "total_number_of_pods"):
84             self._total_number_of_pods = self._create_config.getint(
85                 "DEFAULT", "total_number_of_pods")
86         else:
87             self._log.error("No option total_number_of_pods in DEFAULT section")
88             return -1
89
90         self._log.debug("Total number of pods %d" % self._total_number_of_pods)
91
92         # Parse [PODx] sections
93         for i in range(1, int(self._total_number_of_pods) + 1):
94             # Search for POD name
95             if self._create_config.has_option("POD%d" % i,
96                                               "name"):
97                 pod_name = self._create_config.get(
98                     "POD%d" % i, "name")
99             else:
100                 pod_name = "pod-rapid-%d" % i
101
102             # Search for POD hostname
103             if self._create_config.has_option("POD%d" % i,
104                                               "nodeSelector_hostname"):
105                 pod_nodeselector_hostname = self._create_config.get(
106                     "POD%d" % i, "nodeSelector_hostname")
107             else:
108                 pod_nodeselector_hostname = None
109
110             # Search for POD dataplane static IP
111             if self._create_config.has_option("POD%d" % i,
112                                               "dp_ip"):
113                 pod_dp_ip = self._create_config.get(
114                     "POD%d" % i, "dp_ip")
115             else:
116                 pod_dp_ip = None
117
118             pod = Pod(pod_name)
119             pod.set_nodeselector(pod_nodeselector_hostname)
120             pod.set_dp_ip(pod_dp_ip)
121             pod.set_id(i)
122
123             # Add POD to the list of PODs which need to be created
124             self._pods.append(pod)
125
126         return 0
127
128     def create_pods(self):
129         """ Create test PODs and wait for them to start.
130         Collect information for tests to run.
131         """
132         self._log.info("Creating PODs...")
133
134         # Create PODs using template from yaml file
135         for pod in self._pods:
136             self._log.info("Creating POD %s...", pod.get_name())
137             pod.create_from_yaml(K8sDeployment.POD_YAML_TEMPLATE_FILE_NAME)
138
139         # Wait for PODs to start
140         for pod in self._pods:
141             pod.wait_for_start()
142
143         # Collect information from started PODs for test execution
144         for pod in self._pods:
145             pod.set_ssh_credentials(K8sDeployment.SSH_USER, K8sDeployment.SSH_PRIVATE_KEY)
146             pod.get_sriov_dev_mac()
147
148     def save_runtime_config(self, config_file_name):
149         self._log.info("Saving config %s for runrapid script...",
150                        config_file_name)
151         self._runtime_config = configparser.RawConfigParser()
152
153         # Section [DEFAULT]
154 #        self._runtime_config.set("DEFAULT",
155 #                                 "total_number_of_test_machines",
156 #                                 self._total_number_of_pods)
157
158         # Section [ssh]
159         self._runtime_config.add_section("ssh")
160         self._runtime_config.set("ssh",
161                                  "key",
162                                  K8sDeployment.SSH_PRIVATE_KEY)
163         self._runtime_config.set("ssh",
164                                  "user",
165                                  K8sDeployment.SSH_USER)
166
167         # Section [rapid]
168         self._runtime_config.add_section("rapid")
169         self._runtime_config.set("rapid",
170                                  "total_number_of_machines",
171                                  self._total_number_of_pods)
172
173         # Export information about each pod
174         # Sections [Mx]
175         for pod in self._pods:
176             self._runtime_config.add_section("M%d" % pod.get_id())
177             self._runtime_config.set("M%d" % pod.get_id(),
178                                      "admin_ip", pod.get_admin_ip())
179             self._runtime_config.set("M%d" % pod.get_id(),
180                                      "dp_mac1", pod.get_dp_mac())
181             self._runtime_config.set("M%d" % pod.get_id(),
182                                      "dp_pci_dev", pod.get_dp_pci_dev())
183             self._runtime_config.set("M%d" % pod.get_id(),
184                                      "dp_ip1", pod.get_dp_ip())
185
186         # Section [Varia]
187         self._runtime_config.add_section("Varia")
188         self._runtime_config.set("Varia",
189                                  "vim",
190                                  "kubernetes")
191
192         # Write runtime config file
193         with open(config_file_name, "w") as file:
194             self._runtime_config.write(file)
195
196     def delete_pods(self):
197         for pod in self._pods:
198             pod.terminate()