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 --system-site-packages --never-download env'
115 ' && source env/bin/activate && pip install -r requirements.txt'
116 .format(con.REMOTE_FW_DIR), timeout=100, include_reason=True,
117 message="Failed install at node {host}".format(host=host))
118 logger.console('Virtualenv setup on {0} done.'.format(host))
121 def setup_node(node, tarball, remote_tarball, results=None):
122 """Copy a tarball to a node and extract it.
124 :param node: A node where the tarball will be copied and extracted.
125 :param tarball: Local path of tarball to be copied.
126 :param remote_tarball: Remote path of the tarball.
127 :param results: A list where to store the result of node setup, optional.
130 :type remote_tarball: str
132 :returns: True - success, False - error
137 copy_tarball_to_node(tarball, node)
138 extract_tarball_at_node(remote_tarball, node)
139 if node['type'] == NodeType.TG:
140 create_env_directory_at_node(node)
141 except RuntimeError as exc:
142 logger.console("Node {node} setup failed, error: {err!r}".format(
146 logger.console('Setup of node {ip} done.'.format(ip=host))
149 if isinstance(results, list):
150 results.append(result)
154 def delete_local_tarball(tarball):
155 """Delete local tarball to prevent disk pollution.
157 :param tarball: Path of local tarball to delete.
164 def delete_framework_dir(node):
165 """Delete framework directory in /tmp/ on given node.
167 :param node: Node to delete framework directory on.
172 'Deleting framework directory on {0} starts.'.format(host))
174 node, 'sudo rm -rf {0}'.format(con.REMOTE_FW_DIR),
175 message="Framework delete failed at node {host}".format(host=host),
176 timeout=100, include_reason=True)
178 'Deleting framework directory on {0} done.'.format(host))
181 def cleanup_node(node, results=None):
182 """Delete a tarball from a node.
184 :param node: A node where the tarball will be delete.
185 :param results: A list where to store the result of node cleanup, optional.
188 :returns: True - success, False - error
193 delete_framework_dir(node)
195 logger.error("Cleanup of node {0} failed.".format(host))
198 logger.console('Cleanup of node {0} done.'.format(host))
201 if isinstance(results, list):
202 results.append(result)
206 class SetupFramework(object):
207 """Setup suite run on topology nodes.
209 Many VAT/CLI based tests need the scripts at remote hosts before executing
210 them. This class packs the whole testing directory and copies it over
211 to all nodes in topology under /tmp/
215 def setup_framework(nodes):
216 """Pack the whole directory and extract in temp on each node.
218 :param nodes: Topology nodes.
220 :raises RuntimeError: If setup framework failed.
223 tarball = pack_framework_dir()
224 msg = 'Framework packed to {0}'.format(tarball)
227 remote_tarball = "/tmp/{0}".format(basename(tarball))
232 for node in nodes.values():
233 args = node, tarball, remote_tarball, results
234 thread = threading.Thread(target=setup_node, args=args)
236 threads.append(thread)
239 'Executing node setups in parallel, waiting for threads to end')
241 for thread in threads:
244 logger.info('Results: {0}'.format(results))
246 delete_local_tarball(tarball)
248 logger.console('All nodes are ready.')
249 for node in nodes.values():
250 logger.info('Setup of {type} node {ip} done.'.
251 format(type=node['type'], ip=node['host']))
253 raise RuntimeError('Failed to setup framework.')
256 class CleanupFramework(object):
257 """Clean up suite run on topology nodes."""
260 def cleanup_framework(nodes):
261 """Perform cleanup on each node.
263 :param nodes: Topology nodes.
265 :raises RuntimeError: If cleanup framework failed.
271 for node in nodes.values():
272 thread = threading.Thread(target=cleanup_node,
273 args=(node, results))
275 threads.append(thread)
278 'Executing node cleanups in parallel, waiting for threads to end.')
280 for thread in threads:
283 logger.info('Results: {0}'.format(results))
286 logger.console('All nodes cleaned up.')
288 raise RuntimeError('Failed to cleaned up framework.')