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