Preparation for packet mis-ordering stats
[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             # Search for POD dataplane subnet
119             if self._create_config.has_option("POD%d" % i,
120                                               "dp_subnet"):
121                 pod_dp_subnet = self._create_config.get(
122                     "POD%d" % i, "dp_subnet")
123             else:
124                 pod_dp_subnet = "24"
125
126             pod = Pod(pod_name)
127             pod.set_nodeselector(pod_nodeselector_hostname)
128             pod.set_dp_ip(pod_dp_ip)
129             pod.set_dp_subnet(pod_dp_subnet)
130             pod.set_id(i)
131
132             # Add POD to the list of PODs which need to be created
133             self._pods.append(pod)
134
135         return 0
136
137     def create_pods(self):
138         """ Create test PODs and wait for them to start.
139         Collect information for tests to run.
140         """
141         self._log.info("Creating PODs...")
142
143         # Create PODs using template from yaml file
144         for pod in self._pods:
145             self._log.info("Creating POD %s...", pod.get_name())
146             pod.create_from_yaml(K8sDeployment.POD_YAML_TEMPLATE_FILE_NAME)
147
148         # Wait for PODs to start
149         for pod in self._pods:
150             pod.wait_for_start()
151
152         # Collect information from started PODs for test execution
153         for pod in self._pods:
154             pod.set_ssh_credentials(K8sDeployment.SSH_USER, K8sDeployment.SSH_PRIVATE_KEY)
155             pod.get_sriov_dev_mac()
156
157     def save_runtime_config(self, config_file_name):
158         self._log.info("Saving config %s for runrapid script...",
159                        config_file_name)
160         self._runtime_config = configparser.RawConfigParser()
161
162         # Section [DEFAULT]
163 #        self._runtime_config.set("DEFAULT",
164 #                                 "total_number_of_test_machines",
165 #                                 self._total_number_of_pods)
166
167         # Section [ssh]
168         self._runtime_config.add_section("ssh")
169         self._runtime_config.set("ssh",
170                                  "key",
171                                  K8sDeployment.SSH_PRIVATE_KEY)
172         self._runtime_config.set("ssh",
173                                  "user",
174                                  K8sDeployment.SSH_USER)
175
176         # Section [rapid]
177         self._runtime_config.add_section("rapid")
178         self._runtime_config.set("rapid",
179                                  "total_number_of_machines",
180                                  self._total_number_of_pods)
181
182         # Export information about each pod
183         # Sections [Mx]
184         for pod in self._pods:
185             self._runtime_config.add_section("M%d" % pod.get_id())
186             self._runtime_config.set("M%d" % pod.get_id(),
187                                      "admin_ip", pod.get_admin_ip())
188             self._runtime_config.set("M%d" % pod.get_id(),
189                                      "dp_mac1", pod.get_dp_mac())
190             self._runtime_config.set("M%d" % pod.get_id(),
191                                      "dp_pci_dev", pod.get_dp_pci_dev())
192             self._runtime_config.set("M%d" % pod.get_id(),
193                                      "dp_ip1", pod.get_dp_ip() + "/" +
194                                      pod.get_dp_subnet())
195
196         # Section [Varia]
197         self._runtime_config.add_section("Varia")
198         self._runtime_config.set("Varia",
199                                  "vim",
200                                  "kubernetes")
201
202         # Write runtime config file
203         with open(config_file_name, "w") as file:
204             self._runtime_config.write(file)
205
206     def delete_pods(self):
207         for pod in self._pods:
208             pod.terminate()