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:
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
23 from robot.api import logger
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
30 __all__ = [u"SetupFramework"]
33 def pack_framework_dir():
34 """Pack the testing WS into temp file, return its name.
36 :returns: Tarball file name.
38 :raises Exception: When failed to pack testing framework.
42 directory = environ[u"TMPDIR"]
46 if directory is not None:
47 tmpfile = NamedTemporaryFile(
48 suffix=u".tgz", prefix=u"csit-testing-", dir=f"{directory}"
51 tmpfile = NamedTemporaryFile(suffix=u".tgz", prefix=u"csit-testing-")
52 file_name = tmpfile.name
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"
65 def copy_tarball_to_node(tarball, node):
66 """Copy tarball file from local host to remote node.
68 :param tarball: Path to tarball to upload.
69 :param node: Dictionary created from topology.
75 f"Copying tarball to {node[u'type']} host {node[u'host']}, "
76 f"port {node[u'port']} starts."
78 scp_node(node, tarball, u"/tmp/")
80 f"Copying tarball to {node[u'type']} host {node[u'host']}, "
81 f"port {node[u'port']} done."
85 def extract_tarball_at_node(tarball, node):
86 """Extract tarball at given node.
88 Extracts tarball using tar on given node to specific CSIT location.
90 :param tarball: Path to tarball to upload.
91 :param node: Dictionary created from topology.
95 :raises RuntimeError: When failed to unpack tarball.
98 f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
99 f"host {node[u'host']}, port {node[u'port']} starts."
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}"
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
110 f"Extracting tarball to {con.REMOTE_FW_DIR} on {node[u'type']} "
111 f"host {node[u'host']}, port {node[u'port']} done."
115 def create_env_directory_at_node(node):
116 """Create fresh virtualenv to a directory, install pip requirements.
118 :param node: Node to create virtualenv on.
121 :raises RuntimeError: When failed to setup virtualenv.
124 f"Virtualenv setup including requirements.txt on {node[u'type']} "
125 f"host {node[u'host']}, port {node[u'port']} starts."
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"
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']}"
136 f"Virtualenv setup on {node[u'type']} host {node[u'host']}, "
137 f"port {node[u'port']} done."
141 def setup_node(node, tarball, remote_tarball, results=None):
142 """Copy a tarball to a node and extract it.
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.
150 :type remote_tarball: str
152 :returns: True - success, False - error
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:
162 f"Node {node[u'type']} host {node[u'host']}, port {node[u'port']} "
163 f"setup failed, error: {exc!r}"
168 f"Setup of node {node[u'type']} host {node[u'host']}, "
169 f"port {node[u'port']} done."
173 if isinstance(results, list):
174 results.append(result)
178 def delete_local_tarball(tarball):
179 """Delete local tarball to prevent disk pollution.
181 :param tarball: Path of local tarball to delete.
188 def delete_framework_dir(node):
189 """Delete framework directory in /tmp/ on given node.
191 :param node: Node to delete framework directory on.
195 f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
196 f" port {node[u'port']} starts."
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
205 f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
206 f" port {node[u'port']} done."
210 def cleanup_node(node, results=None):
211 """Delete a tarball from a node.
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.
217 :returns: True - success, False - error
221 delete_framework_dir(node)
224 f"Cleanup of node {node[u'type']} host {node[u'host']}, "
225 f"port {node[u'port']} failed."
230 f"Cleanup of node {node[u'type']} host {node[u'host']}, "
231 f"port {node[u'port']} done."
235 if isinstance(results, list):
236 results.append(result)
240 class SetupFramework:
241 """Setup suite run on topology nodes.
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/
249 def setup_framework(nodes):
250 """Pack the whole directory and extract in temp on each node.
252 :param nodes: Topology nodes.
254 :raises RuntimeError: If setup framework failed.
257 tarball = pack_framework_dir()
258 msg = f"Framework packed to {tarball}"
261 remote_tarball = f"{tarball}"
266 for node in nodes.values():
267 args = node, tarball, remote_tarball, results
268 thread = threading.Thread(target=setup_node, args=args)
270 threads.append(thread)
273 f"Executing node setups in parallel, waiting for threads to end"
276 for thread in threads:
279 logger.info(f"Results: {results}")
281 delete_local_tarball(tarball)
283 logger.console(u"All nodes are ready.")
284 for node in nodes.values():
286 f"Setup of node {node[u'type']} host {node[u'host']}, "
287 f"port {node[u'port']} done."
290 raise RuntimeError(u"Failed to setup framework.")
293 class CleanupFramework:
294 """Clean up suite run on topology nodes."""
297 def cleanup_framework(nodes):
298 """Perform cleanup on each node.
300 :param nodes: Topology nodes.
302 :raises RuntimeError: If cleanup framework failed.
308 for node in nodes.values():
309 thread = threading.Thread(target=cleanup_node, args=(node, results))
311 threads.append(thread)
314 u"Executing node cleanups in parallel, waiting for threads to end."
317 for thread in threads:
320 logger.info(f"Results: {results}")
323 logger.console(u"All nodes cleaned up.")
325 raise RuntimeError(u"Failed to cleaned up framework.")