FrameworkSetup: Detect socket.timeout
[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 import socket  # For catching socket.timeout.
21 from tempfile import NamedTemporaryFile
22 import threading
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=30, 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     :param node: Node to create virtualenv on.
120     :type node: dict
121     :returns: nothing
122     :raises RuntimeError: When failed to setup virtualenv.
123     """
124     logger.console(
125         f"Virtualenv setup including requirements.txt on {node[u'type']} "
126         f"host {node[u'host']}, port {node[u'port']} starts."
127     )
128     cmd = f"cd {con.REMOTE_FW_DIR} && rm -rf env && virtualenv " \
129         f"-p $(which python3) --system-site-packages --never-download env " \
130         f"&& source env/bin/activate && ANSIBLE_SKIP_CONFLICT_CHECK=1 " \
131         f"pip3 install -r requirements.txt"
132     exec_cmd_no_error(
133         node, cmd, timeout=100, include_reason=True,
134         message=f"Failed install at node {node[u'type']} host {node[u'host']}, "
135         f"port {node[u'port']}"
136     )
137     logger.console(
138         f"Virtualenv setup on {node[u'type']} host {node[u'host']}, "
139         f"port {node[u'port']} done."
140     )
141
142
143 def setup_node(node, tarball, remote_tarball, results=None):
144     """Copy a tarball to a node and extract it.
145
146     :param node: A node where the tarball will be copied and extracted.
147     :param tarball: Local path of tarball to be copied.
148     :param remote_tarball: Remote path of the tarball.
149     :param results: A list where to store the result of node setup, optional.
150     :type node: dict
151     :type tarball: str
152     :type remote_tarball: str
153     :type results: list
154     :returns: True - success, False - error
155     :rtype: bool
156     """
157     try:
158         copy_tarball_to_node(tarball, node)
159         extract_tarball_at_node(remote_tarball, node)
160         if node[u"type"] == NodeType.TG:
161             create_env_directory_at_node(node)
162     except (RuntimeError, socket.timeout) as exc:
163         logger.console(
164             f"Node {node[u'type']} host {node[u'host']}, port {node[u'port']} "
165             f"setup failed, error: {exc!r}"
166         )
167         result = False
168     else:
169         logger.console(
170             f"Setup of node {node[u'type']} host {node[u'host']}, "
171             f"port {node[u'port']} done."
172         )
173         result = True
174
175     if isinstance(results, list):
176         results.append(result)
177     return result
178
179
180 def delete_local_tarball(tarball):
181     """Delete local tarball to prevent disk pollution.
182
183     :param tarball: Path of local tarball to delete.
184     :type tarball: str
185     :returns: nothing
186     """
187     remove(tarball)
188
189
190 def delete_framework_dir(node):
191     """Delete framework directory in /tmp/ on given node.
192
193     :param node: Node to delete framework directory on.
194     :type node: dict
195     """
196     logger.console(
197         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
198         f" port {node[u'port']} starts."
199     )
200     exec_cmd_no_error(
201         node, f"sudo rm -rf {con.REMOTE_FW_DIR}",
202         message=f"Framework delete failed at node {node[u'type']} "
203         f"host {node[u'host']}, port {node[u'port']}",
204         timeout=100, include_reason=True
205     )
206     logger.console(
207         f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
208         f" port {node[u'port']} done."
209     )
210
211
212 def cleanup_node(node, results=None):
213     """Delete a tarball from a node.
214
215     :param node: A node where the tarball will be delete.
216     :param results: A list where to store the result of node cleanup, optional.
217     :type node: dict
218     :type results: list
219     :returns: True - success, False - error
220     :rtype: bool
221     """
222     try:
223         delete_framework_dir(node)
224     except RuntimeError:
225         logger.error(
226             f"Cleanup of node {node[u'type']} host {node[u'host']}, "
227             f"port {node[u'port']} failed."
228         )
229         result = False
230     else:
231         logger.console(
232             f"Cleanup of node {node[u'type']} host {node[u'host']}, "
233             f"port {node[u'port']} done."
234         )
235         result = True
236
237     if isinstance(results, list):
238         results.append(result)
239     return result
240
241
242 class SetupFramework:
243     """Setup suite run on topology nodes.
244
245     Many VAT/CLI based tests need the scripts at remote hosts before executing
246     them. This class packs the whole testing directory and copies it over
247     to all nodes in topology under /tmp/
248     """
249
250     @staticmethod
251     def setup_framework(nodes):
252         """Pack the whole directory and extract in temp on each node.
253
254         :param nodes: Topology nodes.
255         :type nodes: dict
256         :raises RuntimeError: If setup framework failed.
257         """
258
259         tarball = pack_framework_dir()
260         msg = f"Framework packed to {tarball}"
261         logger.console(msg)
262         logger.trace(msg)
263         remote_tarball = f"{tarball}"
264
265         results = list()
266         threads = list()
267
268         for node in nodes.values():
269             args = node, tarball, remote_tarball, results
270             thread = threading.Thread(target=setup_node, args=args)
271             thread.start()
272             threads.append(thread)
273
274         logger.info(
275             u"Executing node setups in parallel, waiting for threads to end."
276         )
277
278         for thread in threads:
279             thread.join()
280
281         logger.info(f"Results: {results}")
282
283         delete_local_tarball(tarball)
284         if all(results):
285             logger.console(u"All nodes are ready.")
286             for node in nodes.values():
287                 logger.info(
288                     f"Setup of node {node[u'type']} host {node[u'host']}, "
289                     f"port {node[u'port']} done."
290                 )
291         else:
292             raise RuntimeError(u"Failed to setup framework.")
293
294
295 class CleanupFramework:
296     """Clean up suite run on topology nodes."""
297
298     @staticmethod
299     def cleanup_framework(nodes):
300         """Perform cleanup on each node.
301
302         :param nodes: Topology nodes.
303         :type nodes: dict
304         :raises RuntimeError: If cleanup framework failed.
305         """
306
307         results = list()
308         threads = list()
309
310         for node in nodes.values():
311             thread = threading.Thread(target=cleanup_node, args=(node, results))
312             thread.start()
313             threads.append(thread)
314
315         logger.info(
316             u"Executing node cleanups in parallel, waiting for threads to end."
317         )
318
319         for thread in threads:
320             thread.join()
321
322         logger.info(f"Results: {results}")
323
324         if all(results):
325             logger.console(u"All nodes cleaned up.")
326         else:
327             raise RuntimeError(u"Failed to cleaned up framework.")