Infra: Ansible 2.10
[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
23 from robot.api import logger
24
25 from resources.libraries.python.Constants import Constants as con
26 from resources.libraries.python.ssh import exec_cmd_no_error, scp_node
27 from resources.libraries.python.LocalExecution import run
28 from resources.libraries.python.topology import NodeType
29
30 __all__ = [u"SetupFramework"]
31
32
33 def pack_framework_dir():
34     """Pack the testing WS into temp file, return its name.
35
36     :returns: Tarball file name.
37     :rtype: str
38     :raises Exception: When failed to pack testing framework.
39     """
40
41     try:
42         directory = environ[u"TMPDIR"]
43     except KeyError:
44         directory = None
45
46     if directory is not None:
47         tmpfile = NamedTemporaryFile(
48             suffix=u".tgz", prefix=u"csit-testing-", dir=f"{directory}"
49         )
50     else:
51         tmpfile = NamedTemporaryFile(suffix=u".tgz", prefix=u"csit-testing-")
52     file_name = tmpfile.name
53     tmpfile.close()
54
55     run(
56         [
57             u"tar", u"--sparse", u"--exclude-vcs", u"--exclude=output*.xml",
58             u"--exclude=./tmp", u"-zcf", file_name, u"."
59         ], msg=u"Could not pack testing framework"
60     )
61
62     return file_name
63
64
65 def copy_tarball_to_node(tarball, node):
66     """Copy tarball file from local host to remote node.
67
68     :param tarball: Path to tarball to upload.
69     :param node: Dictionary created from topology.
70     :type tarball: str
71     :type node: dict
72     :returns: nothing
73     """
74     logger.console(
75         f"Copying tarball to {node[u'type']} host {node[u'host']}, "
76         f"port {node[u'port']} starts."
77     )
78     scp_node(node, tarball, u"/tmp/")
79     logger.console(
80         f"Copying tarball to {node[u'type']} host {node[u'host']}, "
81         f"port {node[u'port']} done."
82     )
83
84
85 def extract_tarball_at_node(tarball, node):
86     """Extract tarball at given node.
87
88     Extracts tarball using tar on given node to specific CSIT location.
89
90     :param tarball: Path to tarball to upload.
91     :param node: Dictionary created from topology.
92     :type tarball: str
93     :type node: dict
94     :returns: nothing
95     :raises RuntimeError: When failed to unpack tarball.
96     """
97     logger.console(
98         f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
99         f"host {node[u'host']}, port {node[u'port']} starts."
100     )
101     cmd = f"sudo rm -rf {con.REMOTE_FW_DIR}; mkdir {con.REMOTE_FW_DIR}; " \
102         f"tar -zxf {tarball} -C {con.REMOTE_FW_DIR}; rm -f {tarball}"
103     exec_cmd_no_error(
104         node, cmd,
105         message=f"Failed to extract {tarball} at node {node[u'type']} "
106         f"host {node[u'host']}, port {node[u'port']}",
107         timeout=30, include_reason=True
108     )
109     logger.console(
110         f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
111         f"host {node[u'host']}, port {node[u'port']} done."
112     )
113
114
115 def create_env_directory_at_node(node):
116     """Create fresh virtualenv to a directory, install pip requirements.
117
118     :param node: Node to create virtualenv on.
119     :type node: dict
120     :returns: nothing
121     :raises RuntimeError: When failed to setup virtualenv.
122     """
123     logger.console(
124         f"Virtualenv setup including requirements.txt on {node[u'type']} "
125         f"host {node[u'host']}, port {node[u'port']} starts."
126     )
127     cmd = f"cd {con.REMOTE_FW_DIR} && rm -rf env && virtualenv " \
128         f"-p $(which python3) --system-site-packages --never-download env " \
129         f"&& source env/bin/activate && ANSIBLE_SKIP_CONFLICT_CHECK=1 " \
130         f"pip3 install -r requirements.txt"
131     exec_cmd_no_error(
132         node, cmd, timeout=100, include_reason=True,
133         message=f"Failed install at node {node[u'type']} host {node[u'host']}, "
134         f"port {node[u'port']}"
135     )
136     logger.console(
137         f"Virtualenv setup on {node[u'type']} host {node[u'host']}, "
138         f"port {node[u'port']} done."
139     )
140
141
142 def setup_node(node, tarball, remote_tarball, results=None):
143     """Copy a tarball to a node and extract it.
144
145     :param node: A node where the tarball will be copied and extracted.
146     :param tarball: Local path of tarball to be copied.
147     :param remote_tarball: Remote path of the tarball.
148     :param results: A list where to store the result of node setup, optional.
149     :type node: dict
150     :type tarball: str
151     :type remote_tarball: str
152     :type results: list
153     :returns: True - success, False - error
154     :rtype: bool
155     """
156     try:
157         copy_tarball_to_node(tarball, node)
158         extract_tarball_at_node(remote_tarball, node)
159         if node[u"type"] == NodeType.TG:
160             create_env_directory_at_node(node)
161     except RuntimeError as exc:
162         logger.console(
163             f"Node {node[u'type']} host {node[u'host']}, port {node[u'port']} "
164             f"setup failed, error: {exc!r}"
165         )
166         result = False
167     else:
168         logger.console(
169             f"Setup of node {node[u'type']} host {node[u'host']}, "
170             f"port {node[u'port']} done."
171         )
172         result = True
173
174     if isinstance(results, list):
175         results.append(result)
176     return result
177
178
179 def delete_local_tarball(tarball):
180     """Delete local tarball to prevent disk pollution.
181
182     :param tarball: Path of local tarball to delete.
183     :type tarball: str
184     :returns: nothing
185     """
186     remove(tarball)
187
188
189 def delete_framework_dir(node):
190     """Delete framework directory in /tmp/ on given node.
191
192     :param node: Node to delete framework directory on.
193     :type node: dict
194     """
195     logger.console(
196         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
197         f" port {node[u'port']} starts."
198     )
199     exec_cmd_no_error(
200         node, f"sudo rm -rf {con.REMOTE_FW_DIR}",
201         message=f"Framework delete failed at node {node[u'type']} "
202         f"host {node[u'host']}, port {node[u'port']}",
203         timeout=100, include_reason=True
204     )
205     logger.console(
206         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
207         f" port {node[u'port']} done."
208     )
209
210
211 def cleanup_node(node, results=None):
212     """Delete a tarball from a node.
213
214     :param node: A node where the tarball will be delete.
215     :param results: A list where to store the result of node cleanup, optional.
216     :type node: dict
217     :type results: list
218     :returns: True - success, False - error
219     :rtype: bool
220     """
221     try:
222         delete_framework_dir(node)
223     except RuntimeError:
224         logger.error(
225             f"Cleanup of node {node[u'type']} host {node[u'host']}, "
226             f"port {node[u'port']} failed."
227         )
228         result = False
229     else:
230         logger.console(
231             f"Cleanup of node {node[u'type']} host {node[u'host']}, "
232             f"port {node[u'port']} done."
233         )
234         result = True
235
236     if isinstance(results, list):
237         results.append(result)
238     return result
239
240
241 class SetupFramework:
242     """Setup suite run on topology nodes.
243
244     Many VAT/CLI based tests need the scripts at remote hosts before executing
245     them. This class packs the whole testing directory and copies it over
246     to all nodes in topology under /tmp/
247     """
248
249     @staticmethod
250     def setup_framework(nodes):
251         """Pack the whole directory and extract in temp on each node.
252
253         :param nodes: Topology nodes.
254         :type nodes: dict
255         :raises RuntimeError: If setup framework failed.
256         """
257
258         tarball = pack_framework_dir()
259         msg = f"Framework packed to {tarball}"
260         logger.console(msg)
261         logger.trace(msg)
262         remote_tarball = f"{tarball}"
263
264         results = list()
265         threads = list()
266
267         for node in nodes.values():
268             args = node, tarball, remote_tarball, results
269             thread = threading.Thread(target=setup_node, args=args)
270             thread.start()
271             threads.append(thread)
272
273         logger.info(
274             f"Executing node setups in parallel, waiting for threads to end"
275         )
276
277         for thread in threads:
278             thread.join()
279
280         logger.info(f"Results: {results}")
281
282         delete_local_tarball(tarball)
283         if all(results):
284             logger.console(u"All nodes are ready.")
285             for node in nodes.values():
286                 logger.info(
287                     f"Setup of node {node[u'type']} host {node[u'host']}, "
288                     f"port {node[u'port']} done."
289                 )
290         else:
291             raise RuntimeError(u"Failed to setup framework.")
292
293
294 class CleanupFramework:
295     """Clean up suite run on topology nodes."""
296
297     @staticmethod
298     def cleanup_framework(nodes):
299         """Perform cleanup on each node.
300
301         :param nodes: Topology nodes.
302         :type nodes: dict
303         :raises RuntimeError: If cleanup framework failed.
304         """
305
306         results = list()
307         threads = list()
308
309         for node in nodes.values():
310             thread = threading.Thread(target=cleanup_node, args=(node, results))
311             thread.start()
312             threads.append(thread)
313
314         logger.info(
315             u"Executing node cleanups in parallel, waiting for threads to end."
316         )
317
318         for thread in threads:
319             thread.join()
320
321         logger.info(f"Results: {results}")
322
323         if all(results):
324             logger.console(u"All nodes cleaned up.")
325         else:
326             raise RuntimeError(u"Failed to cleaned up framework.")