1 # Copyright (c) 2018 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.
20 from os import environ, remove
21 from os.path import basename
22 from shlex import split
23 from subprocess import Popen, PIPE
24 from tempfile import NamedTemporaryFile
27 from robot.api import logger
29 from resources.libraries.python.ssh import SSH
30 from resources.libraries.python.Constants import Constants as con
31 from resources.libraries.python.topology import NodeType
33 __all__ = ["SetupFramework"]
36 def pack_framework_dir():
37 """Pack the testing WS into temp file, return its name.
39 :returns: Tarball file name.
41 :raises Exception: When failed to pack testing framework.
45 directory = environ["TMPDIR"]
49 if directory is not None:
50 tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-",
51 dir="{0}".format(directory))
53 tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-")
54 file_name = tmpfile.name
58 split("tar --sparse --exclude-vcs --exclude=output*.xml "
59 "--exclude=./tmp -zcf {0} ."
60 .format(file_name)), stdout=PIPE, stderr=PIPE)
61 (stdout, stderr) = proc.communicate()
66 return_code = proc.wait()
68 raise RuntimeError("Could not pack testing framework.")
73 def copy_tarball_to_node(tarball, node):
74 """Copy tarball file from local host to remote node.
76 :param tarball: Path to tarball to upload.
77 :param node: Dictionary created from topology.
82 logger.console('Copying tarball to {0}'.format(node['host']))
86 ssh.scp(tarball, "/tmp/")
87 logger.console('Copying tarball to {0} done'.format(node['host']))
90 def extract_tarball_at_node(tarball, node):
91 """Extract tarball at given node.
93 Extracts tarball using tar on given node to specific CSIT location.
95 :param tarball: Path to tarball to upload.
96 :param node: Dictionary created from topology.
100 :raises RuntimeError: When failed to unpack tarball.
102 logger.console('Extracting tarball to {0} on {1}'
103 .format(con.REMOTE_FW_DIR, node['host']))
106 (ret_code, _, _) = ssh.exec_command(
107 'sudo rm -rf {1}; mkdir {1} ; tar -zxf {0} -C {1}; rm -f {0}'
108 .format(tarball, con.REMOTE_FW_DIR), timeout=30)
110 raise RuntimeError('Failed to extract {0} at node {1}'
111 .format(tarball, node['host']))
112 logger.console('Extracting tarball to {0} on {1} done'
113 .format(con.REMOTE_FW_DIR, node['host']))
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.
124 logger.console('Virtualenv setup including requirements.txt on {0}'
125 .format(node['host']))
128 (ret_code, _, _) = ssh.exec_command(
129 'cd {0} && rm -rf env && '
130 'virtualenv --system-site-packages --never-download env && '
131 '. env/bin/activate && '
132 'pip install -r requirements.txt'
133 .format(con.REMOTE_FW_DIR), timeout=100)
135 raise RuntimeError('Virtualenv setup including requirements.txt on {0}'
136 .format(node['host']))
138 logger.console('Virtualenv on {0} created'.format(node['host']))
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['type'] == NodeType.TG:
159 create_env_directory_at_node(node)
160 except RuntimeError as exc:
161 logger.error("Node {0} setup failed, error:'{1}'"
162 .format(node['host'], exc.message))
165 logger.console('Setup of node {0} done'.format(node['host']))
168 if isinstance(results, list):
169 results.append(result)
173 def delete_local_tarball(tarball):
174 """Delete local tarball to prevent disk pollution.
176 :param tarball: Path of local tarball to delete.
183 def delete_framework_dir(node):
184 """Delete framework directory in /tmp/ on given node.
186 :param node: Node to delete framework directory on.
189 logger.console('Deleting framework directory on {0}'
190 .format(node['host']))
193 (ret_code, _, _) = ssh.exec_command(
195 .format(con.REMOTE_FW_DIR), timeout=100)
197 raise RuntimeError('Deleting framework directory on {0} failed'
201 def cleanup_node(node, results=None):
202 """Delete a tarball from a node.
204 :param node: A node where the tarball will be delete.
205 :param results: A list where to store the result of node cleanup, optional.
208 :returns: True - success, False - error
212 delete_framework_dir(node)
214 logger.error("Cleanup of node {0} failed".format(node['host']))
217 logger.console('Cleanup of node {0} done'.format(node['host']))
220 if isinstance(results, list):
221 results.append(result)
225 class SetupFramework(object):
226 """Setup suite run on topology nodes.
228 Many VAT/CLI based tests need the scripts at remote hosts before executing
229 them. This class packs the whole testing directory and copies it over
230 to all nodes in topology under /tmp/
234 def setup_framework(nodes):
235 """Pack the whole directory and extract in temp on each node.
237 :param nodes: Topology nodes.
239 :raises RuntimeError: If setup framework failed.
242 tarball = pack_framework_dir()
243 msg = 'Framework packed to {0}'.format(tarball)
246 remote_tarball = "/tmp/{0}".format(basename(tarball))
251 for node in nodes.values():
252 thread = threading.Thread(target=setup_node, args=(node,
257 threads.append(thread)
260 'Executing node setups in parallel, waiting for threads to end')
262 for thread in threads:
265 logger.info('Results: {0}'.format(results))
267 delete_local_tarball(tarball)
269 logger.console('All nodes are ready')
271 raise RuntimeError('Failed to setup framework')
274 class CleanupFramework(object):
275 """Clean up suite run on topology nodes."""
278 def cleanup_framework(nodes):
279 """Perform cleanup on each node.
281 :param nodes: Topology nodes.
283 :raises RuntimeError: If cleanup framework failed.
289 for node in nodes.values():
290 thread = threading.Thread(target=cleanup_node,
291 args=(node, results))
293 threads.append(thread)
296 'Executing node cleanups in parallel, waiting for threads to end')
298 for thread in threads:
301 logger.info('Results: {0}'.format(results))
304 logger.console('All nodes cleaned up')
306 raise RuntimeError('Failed to cleaned up framework')