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
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 && ANSIBLE_SKIP_CONFLICT_CHECK=1 " \
130 f"pip3 install -r requirements.txt"
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']}"
137 f"Virtualenv setup on {node[u'type']} host {node[u'host']}, "
138 f"port {node[u'port']} done."
142 def setup_node(node, tarball, remote_tarball, results=None):
143 """Copy a tarball to a node and extract it.
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.
151 :type remote_tarball: str
153 :returns: True - success, False - error
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:
163 f"Node {node[u'type']} host {node[u'host']}, port {node[u'port']} "
164 f"setup failed, error: {exc!r}"
169 f"Setup of node {node[u'type']} host {node[u'host']}, "
170 f"port {node[u'port']} done."
174 if isinstance(results, list):
175 results.append(result)
179 def delete_local_tarball(tarball):
180 """Delete local tarball to prevent disk pollution.
182 :param tarball: Path of local tarball to delete.
189 def delete_framework_dir(node):
190 """Delete framework directory in /tmp/ on given node.
192 :param node: Node to delete framework directory on.
196 f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
197 f" port {node[u'port']} starts."
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
206 f"Deleting framework directory on {node[u'type']} host {node[u'host']},"
207 f" port {node[u'port']} done."
211 def cleanup_node(node, results=None):
212 """Delete a tarball from a node.
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.
218 :returns: True - success, False - error
222 delete_framework_dir(node)
225 f"Cleanup of node {node[u'type']} host {node[u'host']}, "
226 f"port {node[u'port']} failed."
231 f"Cleanup of node {node[u'type']} host {node[u'host']}, "
232 f"port {node[u'port']} done."
236 if isinstance(results, list):
237 results.append(result)
241 class SetupFramework:
242 """Setup suite run on topology nodes.
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/
250 def setup_framework(nodes):
251 """Pack the whole directory and extract in temp on each node.
253 :param nodes: Topology nodes.
255 :raises RuntimeError: If setup framework failed.
258 tarball = pack_framework_dir()
259 msg = f"Framework packed to {tarball}"
262 remote_tarball = f"{tarball}"
267 for node in nodes.values():
268 args = node, tarball, remote_tarball, results
269 thread = threading.Thread(target=setup_node, args=args)
271 threads.append(thread)
274 f"Executing node setups in parallel, waiting for threads to end"
277 for thread in threads:
280 logger.info(f"Results: {results}")
282 delete_local_tarball(tarball)
284 logger.console(u"All nodes are ready.")
285 for node in nodes.values():
287 f"Setup of node {node[u'type']} host {node[u'host']}, "
288 f"port {node[u'port']} done."
291 raise RuntimeError(u"Failed to setup framework.")
294 class CleanupFramework:
295 """Clean up suite run on topology nodes."""
298 def cleanup_framework(nodes):
299 """Perform cleanup on each node.
301 :param nodes: Topology nodes.
303 :raises RuntimeError: If cleanup framework failed.
309 for node in nodes.values():
310 thread = threading.Thread(target=cleanup_node, args=(node, results))
312 threads.append(thread)
315 u"Executing node cleanups in parallel, waiting for threads to end."
318 for thread in threads:
321 logger.info(f"Results: {results}")
324 logger.console(u"All nodes cleaned up.")
326 raise RuntimeError(u"Failed to cleaned up framework.")