e0c3a4cb6159e7a13909c51dadb0fe1cf2e8b211
[csit.git] / resources / libraries / python / SetupFramework.py
1 # Copyright (c) 2021 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """This module exists to provide setup utilities for the framework on topology
15 nodes. All tasks required to be run before the actual tests are started is
16 supposed to end up here.
17 """
18
19 from os import environ, remove
20 from tempfile import NamedTemporaryFile
21 import threading
22 import traceback
23
24 from robot.api import logger
25
26 from resources.libraries.python.Constants import Constants as con
27 from resources.libraries.python.ssh import exec_cmd_no_error, scp_node
28 from resources.libraries.python.LocalExecution import run
29 from resources.libraries.python.topology import NodeType
30
31 __all__ = [u"SetupFramework"]
32
33
34 def pack_framework_dir():
35     """Pack the testing WS into temp file, return its name.
36
37     :returns: Tarball file name.
38     :rtype: str
39     :raises Exception: When failed to pack testing framework.
40     """
41
42     try:
43         directory = environ[u"TMPDIR"]
44     except KeyError:
45         directory = None
46
47     if directory is not None:
48         tmpfile = NamedTemporaryFile(
49             suffix=u".tgz", prefix=u"csit-testing-", dir=f"{directory}"
50         )
51     else:
52         tmpfile = NamedTemporaryFile(suffix=u".tgz", prefix=u"csit-testing-")
53     file_name = tmpfile.name
54     tmpfile.close()
55
56     run(
57         [
58             u"tar", u"--sparse", u"--exclude-vcs", u"--exclude=output*.xml",
59             u"--exclude=./tmp", u"-zcf", file_name, u"."
60         ], msg=u"Could not pack testing framework"
61     )
62
63     return file_name
64
65
66 def copy_tarball_to_node(tarball, node):
67     """Copy tarball file from local host to remote node.
68
69     :param tarball: Path to tarball to upload.
70     :param node: Dictionary created from topology.
71     :type tarball: str
72     :type node: dict
73     :returns: nothing
74     """
75     logger.console(
76         f"Copying tarball to {node[u'type']} host {node[u'host']}, "
77         f"port {node[u'port']} starts."
78     )
79     scp_node(node, tarball, u"/tmp/")
80     logger.console(
81         f"Copying tarball to {node[u'type']} host {node[u'host']}, "
82         f"port {node[u'port']} done."
83     )
84
85
86 def extract_tarball_at_node(tarball, node):
87     """Extract tarball at given node.
88
89     Extracts tarball using tar on given node to specific CSIT location.
90
91     :param tarball: Path to tarball to upload.
92     :param node: Dictionary created from topology.
93     :type tarball: str
94     :type node: dict
95     :returns: nothing
96     :raises RuntimeError: When failed to unpack tarball.
97     """
98     logger.console(
99         f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
100         f"host {node[u'host']}, port {node[u'port']} starts."
101     )
102     cmd = f"sudo rm -rf {con.REMOTE_FW_DIR}; mkdir {con.REMOTE_FW_DIR}; " \
103         f"tar -zxf {tarball} -C {con.REMOTE_FW_DIR}; rm -f {tarball}"
104     exec_cmd_no_error(
105         node, cmd,
106         message=f"Failed to extract {tarball} at node {node[u'type']} "
107         f"host {node[u'host']}, port {node[u'port']}",
108         timeout=240, include_reason=True
109     )
110     logger.console(
111         f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
112         f"host {node[u'host']}, port {node[u'port']} done."
113     )
114
115
116 def create_env_directory_at_node(node):
117     """Create fresh virtualenv to a directory, install pip requirements.
118
119     Return stdout and stderr of the command,
120     so we see which installs are behaving weird (e.g. attempting download).
121
122     :param node: Node to create virtualenv on.
123     :type node: dict
124     :returns: Stdout and stderr.
125     :rtype: str, str
126     :raises RuntimeError: When failed to setup virtualenv.
127     """
128     logger.console(
129         f"Virtualenv setup including requirements.txt on {node[u'type']} "
130         f"host {node[u'host']}, port {node[u'port']} starts."
131     )
132     cmd = f"cd {con.REMOTE_FW_DIR} && rm -rf env && virtualenv " \
133         f"-p $(which python3) --system-site-packages --never-download env " \
134         f"&& source env/bin/activate && ANSIBLE_SKIP_CONFLICT_CHECK=1 " \
135         f"pip3 install -r requirements.txt"
136     stdout, stderr = exec_cmd_no_error(
137         node, cmd, timeout=100, include_reason=True,
138         message=f"Failed install at node {node[u'type']} host {node[u'host']}, "
139         f"port {node[u'port']}"
140     )
141     logger.console(
142         f"Virtualenv setup on {node[u'type']} host {node[u'host']}, "
143         f"port {node[u'port']} done."
144     )
145     return stdout, stderr
146
147
148 def setup_node(node, tarball, remote_tarball, results=None, logs=None):
149     """Copy a tarball to a node and extract it.
150
151     :param node: A node where the tarball will be copied and extracted.
152     :param tarball: Local path of tarball to be copied.
153     :param remote_tarball: Remote path of the tarball.
154     :param results: A list where to store the result of node setup, optional.
155     :param logs: A list where to store anything that should be logged.
156     :type node: dict
157     :type tarball: str
158     :type remote_tarball: str
159     :type results: list
160     :type logs: list
161     :returns: True - success, False - error
162     :rtype: bool
163     """
164     try:
165         copy_tarball_to_node(tarball, node)
166         extract_tarball_at_node(remote_tarball, node)
167         if node[u"type"] == NodeType.TG:
168             stdout, stderr = create_env_directory_at_node(node)
169             if isinstance(logs, list):
170                 logs.append(f"{node[u'host']} Env stdout: {stdout}")
171                 logs.append(f"{node[u'host']} Env stderr: {stderr}")
172     except Exception:
173         # any exception must result in result = False
174         # since this runs in a thread and can't be caught anywhere else
175         err_msg = f"Node {node[u'type']} host {node[u'host']}, " \
176                   f"port {node[u'port']} setup failed."
177         logger.console(err_msg)
178         if isinstance(logs, list):
179             logs.append(f"{err_msg} Exception: {traceback.format_exc()}")
180         result = False
181     else:
182         logger.console(
183             f"Setup of node {node[u'type']} host {node[u'host']}, "
184             f"port {node[u'port']} done."
185         )
186         result = True
187
188     if isinstance(results, list):
189         results.append(result)
190     return result
191
192
193 def delete_local_tarball(tarball):
194     """Delete local tarball to prevent disk pollution.
195
196     :param tarball: Path of local tarball to delete.
197     :type tarball: str
198     :returns: nothing
199     """
200     remove(tarball)
201
202
203 def delete_framework_dir(node):
204     """Delete framework directory in /tmp/ on given node.
205
206     :param node: Node to delete framework directory on.
207     :type node: dict
208     """
209     logger.console(
210         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
211         f" port {node[u'port']} starts."
212     )
213     exec_cmd_no_error(
214         node, f"sudo rm -rf {con.REMOTE_FW_DIR}",
215         message=f"Framework delete failed at node {node[u'type']} "
216         f"host {node[u'host']}, port {node[u'port']}",
217         timeout=100, include_reason=True
218     )
219     logger.console(
220         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
221         f" port {node[u'port']} done."
222     )
223
224
225 def cleanup_node(node, results=None, logs=None):
226     """Delete a tarball from a node.
227
228     :param node: A node where the tarball will be delete.
229     :param results: A list where to store the result of node cleanup, optional.
230     :param logs: A list where to store anything that should be logged.
231     :type node: dict
232     :type results: list
233     :type logs: list
234     :returns: True - success, False - error
235     :rtype: bool
236     """
237     try:
238         delete_framework_dir(node)
239     except Exception:
240         err_msg = f"Cleanup of node {node[u'type']} host {node[u'host']}, " \
241                   f"port {node[u'port']} failed."
242         logger.console(err_msg)
243         if isinstance(logs, list):
244             logs.append(f"{err_msg} Exception: {traceback.format_exc()}")
245         result = False
246     else:
247         logger.console(
248             f"Cleanup of node {node[u'type']} host {node[u'host']}, "
249             f"port {node[u'port']} done."
250         )
251         result = True
252
253     if isinstance(results, list):
254         results.append(result)
255     return result
256
257
258 class SetupFramework:
259     """Setup suite run on topology nodes.
260
261     Many VAT/CLI based tests need the scripts at remote hosts before executing
262     them. This class packs the whole testing directory and copies it over
263     to all nodes in topology under /tmp/
264     """
265
266     @staticmethod
267     def setup_framework(nodes):
268         """Pack the whole directory and extract in temp on each node.
269
270         :param nodes: Topology nodes.
271         :type nodes: dict
272         :raises RuntimeError: If setup framework failed.
273         """
274
275         tarball = pack_framework_dir()
276         msg = f"Framework packed to {tarball}"
277         logger.console(msg)
278         logger.trace(msg)
279         remote_tarball = f"{tarball}"
280
281         results = list()
282         logs = list()
283         threads = list()
284
285         for node in nodes.values():
286             args = node, tarball, remote_tarball, results, logs
287             thread = threading.Thread(target=setup_node, args=args)
288             thread.start()
289             threads.append(thread)
290
291         logger.info(
292             u"Executing node setups in parallel, waiting for threads to end."
293         )
294
295         for thread in threads:
296             thread.join()
297
298         logger.info(f"Results: {results}")
299
300         for log in logs:
301             logger.trace(log)
302
303         delete_local_tarball(tarball)
304         if all(results):
305             logger.console(u"All nodes are ready.")
306             for node in nodes.values():
307                 logger.info(
308                     f"Setup of node {node[u'type']} host {node[u'host']}, "
309                     f"port {node[u'port']} done."
310                 )
311         else:
312             raise RuntimeError(u"Failed to setup framework.")
313
314
315 class CleanupFramework:
316     """Clean up suite run on topology nodes."""
317
318     @staticmethod
319     def cleanup_framework(nodes):
320         """Perform cleanup on each node.
321
322         :param nodes: Topology nodes.
323         :type nodes: dict
324         :raises RuntimeError: If cleanup framework failed.
325         """
326
327         results = list()
328         logs = list()
329         threads = list()
330
331         for node in nodes.values():
332             thread = threading.Thread(target=cleanup_node,
333                                       args=(node, results, logs))
334             thread.start()
335             threads.append(thread)
336
337         logger.info(
338             u"Executing node cleanups in parallel, waiting for threads to end."
339         )
340
341         for thread in threads:
342             thread.join()
343
344         logger.info(f"Results: {results}")
345
346         for log in logs:
347             logger.trace(log)
348
349         if all(results):
350             logger.console(u"All nodes cleaned up.")
351         else:
352             raise RuntimeError(u"Failed to cleaned up framework.")