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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
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.
19 from os import environ, remove
20 from tempfile import NamedTemporaryFile
24 from robot.api import logger
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
31 __all__ = [u"SetupFramework"]
34 def pack_framework_dir():
35 """Pack the testing WS into temp file, return its name.
37 :returns: Tarball file name.
39 :raises Exception: When failed to pack testing framework.
43 directory = environ[u"TMPDIR"]
47 if directory is not None:
48 tmpfile = NamedTemporaryFile(
49 suffix=u".tgz", prefix=u"csit-testing-", dir=f"{directory}"
52 tmpfile = NamedTemporaryFile(suffix=u".tgz", prefix=u"csit-testing-")
53 file_name = tmpfile.name
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"
66 def copy_tarball_to_node(tarball, node):
67 """Copy tarball file from local host to remote node.
69 :param tarball: Path to tarball to upload.
70 :param node: Dictionary created from topology.
76 f"Copying tarball to {node[u'type']} host {node[u'host']}, "
77 f"port {node[u'port']} starts."
79 scp_node(node, tarball, u"/tmp/")
81 f"Copying tarball to {node[u'type']} host {node[u'host']}, "
82 f"port {node[u'port']} done."
86 def extract_tarball_at_node(tarball, node):
87 """Extract tarball at given node.
89 Extracts tarball using tar on given node to specific CSIT location.
91 :param tarball: Path to tarball to upload.
92 :param node: Dictionary created from topology.
96 :raises RuntimeError: When failed to unpack tarball.
99 f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
100 f"host {node[u'host']}, port {node[u'port']} starts."
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}"
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
111 f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
112 f"host {node[u'host']}, port {node[u'port']} done."
116 def create_env_directory_at_node(node):
117 """Create fresh virtualenv to a directory, install pip requirements.
119 :param node: Node to create virtualenv on.
122 :raises RuntimeError: When failed to setup virtualenv.
125 f"Virtualenv setup including requirements.txt on {node[u'type']} "
126 f"host {node[u'host']}, port {node[u'port']} starts."
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"
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']}"
138 f"Virtualenv setup on {node[u'type']} host {node[u'host']}, "
139 f"port {node[u'port']} done."
143 def setup_node(node, tarball, remote_tarball, results=None, logs=None):
144 """Copy a tarball to a node and extract it.
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 :param logs: A list where to store anything that should be logged.
153 :type remote_tarball: str
156 :returns: True - success, False - error
160 copy_tarball_to_node(tarball, node)
161 extract_tarball_at_node(remote_tarball, node)
162 if node[u"type"] == NodeType.TG:
163 create_env_directory_at_node(node)
165 # any exception must result in result = False
166 # since this runs in a thread and can't be caught anywhere else
167 err_msg = f"Node {node[u'type']} host {node[u'host']}, " \
168 f"port {node[u'port']} setup failed."
169 logger.console(err_msg)
170 if isinstance(logs, list):
171 logs.append(f"{err_msg} Exception: {traceback.format_exc()}")
175 f"Setup of node {node[u'type']} host {node[u'host']}, "
176 f"port {node[u'port']} done."
180 if isinstance(results, list):
181 results.append(result)
185 def delete_local_tarball(tarball):
186 """Delete local tarball to prevent disk pollution.
188 :param tarball: Path of local tarball to delete.
195 def delete_framework_dir(node):
196 """Delete framework directory in /tmp/ on given node.
198 :param node: Node to delete framework directory on.
202 f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
203 f" port {node[u'port']} starts."
206 node, f"sudo rm -rf {con.REMOTE_FW_DIR}",
207 message=f"Framework delete failed at node {node[u'type']} "
208 f"host {node[u'host']}, port {node[u'port']}",
209 timeout=100, include_reason=True
212 f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
213 f" port {node[u'port']} done."
217 def cleanup_node(node, results=None, logs=None):
218 """Delete a tarball from a node.
220 :param node: A node where the tarball will be delete.
221 :param results: A list where to store the result of node cleanup, optional.
222 :param logs: A list where to store anything that should be logged.
226 :returns: True - success, False - error
230 delete_framework_dir(node)
232 err_msg = f"Cleanup of node {node[u'type']} host {node[u'host']}, " \
233 f"port {node[u'port']} failed."
234 logger.console(err_msg)
235 if isinstance(logs, list):
236 logs.append(f"{err_msg} Exception: {traceback.format_exc()}")
240 f"Cleanup of node {node[u'type']} host {node[u'host']}, "
241 f"port {node[u'port']} done."
245 if isinstance(results, list):
246 results.append(result)
250 class SetupFramework:
251 """Setup suite run on topology nodes.
253 Many VAT/CLI based tests need the scripts at remote hosts before executing
254 them. This class packs the whole testing directory and copies it over
255 to all nodes in topology under /tmp/
259 def setup_framework(nodes):
260 """Pack the whole directory and extract in temp on each node.
262 :param nodes: Topology nodes.
264 :raises RuntimeError: If setup framework failed.
267 tarball = pack_framework_dir()
268 msg = f"Framework packed to {tarball}"
271 remote_tarball = f"{tarball}"
277 for node in nodes.values():
278 args = node, tarball, remote_tarball, results, logs
279 thread = threading.Thread(target=setup_node, args=args)
281 threads.append(thread)
284 u"Executing node setups in parallel, waiting for threads to end."
287 for thread in threads:
290 logger.info(f"Results: {results}")
295 delete_local_tarball(tarball)
297 logger.console(u"All nodes are ready.")
298 for node in nodes.values():
300 f"Setup of node {node[u'type']} host {node[u'host']}, "
301 f"port {node[u'port']} done."
304 raise RuntimeError(u"Failed to setup framework.")
307 class CleanupFramework:
308 """Clean up suite run on topology nodes."""
311 def cleanup_framework(nodes):
312 """Perform cleanup on each node.
314 :param nodes: Topology nodes.
316 :raises RuntimeError: If cleanup framework failed.
323 for node in nodes.values():
324 thread = threading.Thread(target=cleanup_node,
325 args=(node, results, logs))
327 threads.append(thread)
330 u"Executing node cleanups in parallel, waiting for threads to end."
333 for thread in threads:
336 logger.info(f"Results: {results}")
342 logger.console(u"All nodes cleaned up.")
344 raise RuntimeError(u"Failed to cleaned up framework.")