feat(model): Cleanup and introduce telemetry
[csit.git] / resources / libraries / python / SetupFramework.py
1 # Copyright (c) 2022 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"--exclude=./env", u"--exclude=./.git",
60             u"-zcf", file_name, u"."
61         ], msg=u"Could not pack testing framework"
62     )
63
64     return file_name
65
66
67 def copy_tarball_to_node(tarball, node):
68     """Copy tarball file from local host to remote node.
69
70     :param tarball: Path to tarball to upload.
71     :param node: Dictionary created from topology.
72     :type tarball: str
73     :type node: dict
74     :returns: nothing
75     """
76     logger.console(
77         f"Copying tarball to {node[u'type']} host {node[u'host']}, "
78         f"port {node[u'port']} starts."
79     )
80     scp_node(node, tarball, u"/tmp/")
81     logger.console(
82         f"Copying tarball to {node[u'type']} host {node[u'host']}, "
83         f"port {node[u'port']} done."
84     )
85
86
87 def extract_tarball_at_node(tarball, node):
88     """Extract tarball at given node.
89
90     Extracts tarball using tar on given node to specific CSIT location.
91
92     :param tarball: Path to tarball to upload.
93     :param node: Dictionary created from topology.
94     :type tarball: str
95     :type node: dict
96     :returns: nothing
97     :raises RuntimeError: When failed to unpack tarball.
98     """
99     logger.console(
100         f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
101         f"host {node[u'host']}, port {node[u'port']} starts."
102     )
103     cmd = f"sudo rm -rf {con.REMOTE_FW_DIR}; mkdir {con.REMOTE_FW_DIR}; " \
104         f"tar -zxf {tarball} -C {con.REMOTE_FW_DIR}; rm -f {tarball}"
105     exec_cmd_no_error(
106         node, cmd,
107         message=f"Failed to extract {tarball} at node {node[u'type']} "
108         f"host {node[u'host']}, port {node[u'port']}",
109         timeout=240, include_reason=True
110     )
111     logger.console(
112         f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
113         f"host {node[u'host']}, port {node[u'port']} done."
114     )
115
116
117 def create_env_directory_at_node(node):
118     """Create fresh virtualenv to a directory, install pip requirements.
119
120     Return stdout and stderr of the command,
121     so we see which installs are behaving weird (e.g. attempting download).
122
123     :param node: Node to create virtualenv on.
124     :type node: dict
125     :returns: Stdout and stderr.
126     :rtype: str, str
127     :raises RuntimeError: When failed to setup virtualenv.
128     """
129     logger.console(
130         f"Virtualenv setup including requirements.txt on {node[u'type']} "
131         f"host {node[u'host']}, port {node[u'port']} starts."
132     )
133     cmd = f"cd {con.REMOTE_FW_DIR} && rm -rf env && virtualenv " \
134         f"-p $(which python3) --system-site-packages --never-download env " \
135         f"&& source env/bin/activate && ANSIBLE_SKIP_CONFLICT_CHECK=1 " \
136         f"pip3 install -r requirements.txt"
137     stdout, stderr = exec_cmd_no_error(
138         node, cmd, timeout=300, include_reason=True,
139         message=f"Failed install at node {node[u'type']} host {node[u'host']}, "
140         f"port {node[u'port']}"
141     )
142     logger.console(
143         f"Virtualenv setup on {node[u'type']} host {node[u'host']}, "
144         f"port {node[u'port']} done."
145     )
146     return stdout, stderr
147
148
149 def setup_node(node, tarball, remote_tarball, results=None, logs=None):
150     """Copy a tarball to a node and extract it.
151
152     :param node: A node where the tarball will be copied and extracted.
153     :param tarball: Local path of tarball to be copied.
154     :param remote_tarball: Remote path of the tarball.
155     :param results: A list where to store the result of node setup, optional.
156     :param logs: A list where to store anything that should be logged.
157     :type node: dict
158     :type tarball: str
159     :type remote_tarball: str
160     :type results: list
161     :type logs: list
162     :returns: True - success, False - error
163     :rtype: bool
164     """
165     try:
166         copy_tarball_to_node(tarball, node)
167         extract_tarball_at_node(remote_tarball, node)
168         if node[u"type"] == NodeType.TG:
169             stdout, stderr = create_env_directory_at_node(node)
170             if isinstance(logs, list):
171                 logs.append(f"{node[u'host']} Env stdout: {stdout}")
172                 logs.append(f"{node[u'host']} Env stderr: {stderr}")
173     except Exception:
174         # any exception must result in result = False
175         # since this runs in a thread and can't be caught anywhere else
176         err_msg = f"Node {node[u'type']} host {node[u'host']}, " \
177                   f"port {node[u'port']} setup failed."
178         logger.console(err_msg)
179         if isinstance(logs, list):
180             logs.append(f"{err_msg} Exception: {traceback.format_exc()}")
181         result = False
182     else:
183         logger.console(
184             f"Setup of node {node[u'type']} host {node[u'host']}, "
185             f"port {node[u'port']} done."
186         )
187         result = True
188
189     if isinstance(results, list):
190         results.append(result)
191     return result
192
193
194 def delete_local_tarball(tarball):
195     """Delete local tarball to prevent disk pollution.
196
197     :param tarball: Path of local tarball to delete.
198     :type tarball: str
199     :returns: nothing
200     """
201     remove(tarball)
202
203
204 def delete_framework_dir(node):
205     """Delete framework directory in /tmp/ on given node.
206
207     :param node: Node to delete framework directory on.
208     :type node: dict
209     """
210     logger.console(
211         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
212         f" port {node[u'port']} starts."
213     )
214     exec_cmd_no_error(
215         node, f"sudo rm -rf {con.REMOTE_FW_DIR}",
216         message=f"Framework delete failed at node {node[u'type']} "
217         f"host {node[u'host']}, port {node[u'port']}",
218         timeout=100, include_reason=True,
219     )
220     logger.console(
221         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
222         f" port {node[u'port']} done."
223     )
224
225
226 def cleanup_node(node, results=None, logs=None):
227     """Delete a tarball from a node.
228
229     :param node: A node where the tarball will be delete.
230     :param results: A list where to store the result of node cleanup, optional.
231     :param logs: A list where to store anything that should be logged.
232     :type node: dict
233     :type results: list
234     :type logs: list
235     :returns: True - success, False - error
236     :rtype: bool
237     """
238     try:
239         delete_framework_dir(node)
240     except Exception:
241         err_msg = f"Cleanup of node {node[u'type']} host {node[u'host']}, " \
242                   f"port {node[u'port']} failed."
243         logger.console(err_msg)
244         if isinstance(logs, list):
245             logs.append(f"{err_msg} Exception: {traceback.format_exc()}")
246         result = False
247     else:
248         logger.console(
249             f"Cleanup of node {node[u'type']} host {node[u'host']}, "
250             f"port {node[u'port']} done."
251         )
252         result = True
253
254     if isinstance(results, list):
255         results.append(result)
256     return result
257
258
259 class SetupFramework:
260     """Setup suite run on topology nodes.
261
262     Many VAT/CLI based tests need the scripts at remote hosts before executing
263     them. This class packs the whole testing directory and copies it over
264     to all nodes in topology under /tmp/
265     """
266
267     @staticmethod
268     def setup_framework(nodes):
269         """Pack the whole directory and extract in temp on each node.
270
271         :param nodes: Topology nodes.
272         :type nodes: dict
273         :raises RuntimeError: If setup framework failed.
274         """
275
276         tarball = pack_framework_dir()
277         msg = f"Framework packed to {tarball}"
278         logger.console(msg)
279         logger.trace(msg)
280         remote_tarball = f"{tarball}"
281
282         results = list()
283         logs = list()
284         threads = list()
285
286         for node in nodes.values():
287             args = node, tarball, remote_tarball, results, logs
288             thread = threading.Thread(target=setup_node, args=args)
289             thread.start()
290             threads.append(thread)
291
292         logger.info(
293             u"Executing node setups in parallel, waiting for threads to end."
294         )
295
296         for thread in threads:
297             thread.join()
298
299         logger.info(f"Results: {results}")
300
301         for log in logs:
302             logger.trace(log)
303
304         delete_local_tarball(tarball)
305         if all(results):
306             logger.console(u"All nodes are ready.")
307             for node in nodes.values():
308                 logger.info(
309                     f"Setup of node {node[u'type']} host {node[u'host']}, "
310                     f"port {node[u'port']} done."
311                 )
312         else:
313             raise RuntimeError(u"Failed to setup framework.")
314
315
316 class CleanupFramework:
317     """Clean up suite run on topology nodes."""
318
319     @staticmethod
320     def cleanup_framework(nodes):
321         """Perform cleanup on each node.
322
323         :param nodes: Topology nodes.
324         :type nodes: dict
325         :raises RuntimeError: If cleanup framework failed.
326         """
327
328         results = list()
329         logs = list()
330         threads = list()
331
332         for node in nodes.values():
333             thread = threading.Thread(target=cleanup_node,
334                                       args=(node, results, logs))
335             thread.start()
336             threads.append(thread)
337
338         logger.info(
339             u"Executing node cleanups in parallel, waiting for threads to end."
340         )
341
342         for thread in threads:
343             thread.join()
344
345         logger.info(f"Results: {results}")
346
347         for log in logs:
348             logger.trace(log)
349
350         if all(results):
351             logger.console(u"All nodes cleaned up.")
352         else:
353             raise RuntimeError(u"Failed to cleaned up framework.")