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 os.path import basename
21 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__ = ["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["TMPDIR"]
47 if directory is not None:
48 tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-",
49 dir="{0}".format(directory))
51 tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-")
52 file_name = tmpfile.name
55 run(["tar", "--sparse", "--exclude-vcs", "--exclude=output*.xml",
56 "--exclude=./tmp", "-zcf", file_name, "."],
57 msg="Could not pack testing framework")
62 def copy_tarball_to_node(tarball, node):
63 """Copy tarball file from local host to remote node.
65 :param tarball: Path to tarball to upload.
66 :param node: Dictionary created from topology.
72 logger.console('Copying tarball to {0} starts.'.format(host))
73 scp_node(node, tarball, "/tmp/")
74 logger.console('Copying tarball to {0} done.'.format(host))
77 def extract_tarball_at_node(tarball, node):
78 """Extract tarball at given node.
80 Extracts tarball using tar on given node to specific CSIT location.
82 :param tarball: Path to tarball to upload.
83 :param node: Dictionary created from topology.
87 :raises RuntimeError: When failed to unpack tarball.
90 logger.console('Extracting tarball to {0} on {1} starts.'
91 .format(con.REMOTE_FW_DIR, host))
93 node, "sudo rm -rf {1}; mkdir {1}; tar -zxf {0} -C {1};"
94 " rm -f {0}".format(tarball, con.REMOTE_FW_DIR),
95 message='Failed to extract {0} at node {1}'.format(tarball, host),
96 timeout=30, include_reason=True)
97 logger.console('Extracting tarball to {0} on {1} done.'
98 .format(con.REMOTE_FW_DIR, host))
101 def create_env_directory_at_node(node):
102 """Create fresh virtualenv to a directory, install pip requirements.
104 :param node: Node to create virtualenv on.
107 :raises RuntimeError: When failed to setup virtualenv.
110 logger.console('Virtualenv setup including requirements.txt on {0} starts.'
113 node, 'cd {0} && rm -rf env'
114 ' && virtualenv -p $(which python3) '
115 '--system-site-packages --never-download env'
116 ' && source env/bin/activate && pip3 install -r requirements.txt'
117 .format(con.REMOTE_FW_DIR), timeout=100, include_reason=True,
118 message="Failed install at node {host}".format(host=host))
119 logger.console('Virtualenv setup on {0} done.'.format(host))
122 def setup_node(node, tarball, remote_tarball, results=None):
123 """Copy a tarball to a node and extract it.
125 :param node: A node where the tarball will be copied and extracted.
126 :param tarball: Local path of tarball to be copied.
127 :param remote_tarball: Remote path of the tarball.
128 :param results: A list where to store the result of node setup, optional.
131 :type remote_tarball: str
133 :returns: True - success, False - error
138 copy_tarball_to_node(tarball, node)
139 extract_tarball_at_node(remote_tarball, node)
140 if node['type'] == NodeType.TG:
141 create_env_directory_at_node(node)
142 except RuntimeError as exc:
143 logger.console("Node {node} setup failed, error: {err!r}".format(
147 logger.console('Setup of node {ip} done.'.format(ip=host))
150 if isinstance(results, list):
151 results.append(result)
155 def delete_local_tarball(tarball):
156 """Delete local tarball to prevent disk pollution.
158 :param tarball: Path of local tarball to delete.
165 def delete_framework_dir(node):
166 """Delete framework directory in /tmp/ on given node.
168 :param node: Node to delete framework directory on.
173 'Deleting framework directory on {0} starts.'.format(host))
175 node, 'sudo rm -rf {0}'.format(con.REMOTE_FW_DIR),
176 message="Framework delete failed at node {host}".format(host=host),
177 timeout=100, include_reason=True)
179 'Deleting framework directory on {0} done.'.format(host))
182 def cleanup_node(node, results=None):
183 """Delete a tarball from a node.
185 :param node: A node where the tarball will be delete.
186 :param results: A list where to store the result of node cleanup, optional.
189 :returns: True - success, False - error
194 delete_framework_dir(node)
196 logger.error("Cleanup of node {0} failed.".format(host))
199 logger.console('Cleanup of node {0} done.'.format(host))
202 if isinstance(results, list):
203 results.append(result)
207 class SetupFramework(object):
208 """Setup suite run on topology nodes.
210 Many VAT/CLI based tests need the scripts at remote hosts before executing
211 them. This class packs the whole testing directory and copies it over
212 to all nodes in topology under /tmp/
216 def setup_framework(nodes):
217 """Pack the whole directory and extract in temp on each node.
219 :param nodes: Topology nodes.
221 :raises RuntimeError: If setup framework failed.
224 tarball = pack_framework_dir()
225 msg = 'Framework packed to {0}'.format(tarball)
228 remote_tarball = "/tmp/{0}".format(basename(tarball))
233 for node in nodes.values():
234 args = node, tarball, remote_tarball, results
235 thread = threading.Thread(target=setup_node, args=args)
237 threads.append(thread)
240 'Executing node setups in parallel, waiting for threads to end')
242 for thread in threads:
245 logger.info('Results: {0}'.format(results))
247 delete_local_tarball(tarball)
249 logger.console('All nodes are ready.')
250 for node in nodes.values():
251 logger.info('Setup of {type} node {ip} done.'.
252 format(type=node['type'], ip=node['host']))
254 raise RuntimeError('Failed to setup framework.')
257 class CleanupFramework(object):
258 """Clean up suite run on topology nodes."""
261 def cleanup_framework(nodes):
262 """Perform cleanup on each node.
264 :param nodes: Topology nodes.
266 :raises RuntimeError: If cleanup framework failed.
272 for node in nodes.values():
273 thread = threading.Thread(target=cleanup_node,
274 args=(node, results))
276 threads.append(thread)
279 'Executing node cleanups in parallel, waiting for threads to end.')
281 for thread in threads:
284 logger.info('Results: {0}'.format(results))
287 logger.console('All nodes cleaned up.')
289 raise RuntimeError('Failed to cleaned up framework.')