Compatibility fixes with Ubuntu 18.04
[csit.git] / resources / libraries / python / SetupFramework.py
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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13
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.
17 """
18
19 from shlex import split
20 from subprocess import Popen, PIPE, call
21 from multiprocessing import Pool
22 from tempfile import NamedTemporaryFile
23 from os.path import basename
24 from os import environ
25
26 from robot.api import logger
27 from robot.libraries.BuiltIn import BuiltIn
28
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
32
33 __all__ = ["SetupFramework"]
34
35
36 def pack_framework_dir():
37     """Pack the testing WS into temp file, return its name.
38
39     :returns: Tarball file name.
40     :rtype: str
41     :raises Exception: When failed to pack testing framework.
42     """
43
44     try:
45         directory = environ["TMPDIR"]
46     except KeyError:
47         directory = None
48
49     if directory is not None:
50         tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-",
51                                      dir="{0}".format(directory))
52     else:
53         tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-")
54     file_name = tmpfile.name
55     tmpfile.close()
56
57     proc = Popen(
58         split("tar --sparse --exclude-vcs --exclude=output*.xml "
59               "--exclude=./tmp --exclude=*.deb --exclude=*.rpm -zcf {0} ."
60               .format(file_name)), stdout=PIPE, stderr=PIPE)
61     (stdout, stderr) = proc.communicate()
62
63     logger.debug(stdout)
64     logger.debug(stderr)
65
66     return_code = proc.wait()
67     if return_code != 0:
68         raise RuntimeError("Could not pack testing framework.")
69
70     return file_name
71
72
73 def copy_tarball_to_node(tarball, node):
74     """Copy tarball file from local host to remote node.
75
76     :param tarball: Path to tarball to upload.
77     :param node: Dictionary created from topology.
78     :type tarball: str
79     :type node: dict
80     :returns: nothing
81     """
82     logger.console('Copying tarball to {0}'.format(node['host']))
83     ssh = SSH()
84     ssh.connect(node)
85
86     ssh.scp(tarball, "/tmp/")
87     logger.console('Copying tarball to {0} done'.format(node['host']))
88
89
90 def extract_tarball_at_node(tarball, node):
91     """Extract tarball at given node.
92
93     Extracts tarball using tar on given node to specific CSIT location.
94
95     :param tarball: Path to tarball to upload.
96     :param node: Dictionary created from topology.
97     :type tarball: str
98     :type node: dict
99     :returns: nothing
100     :raises RuntimeError: When failed to unpack tarball.
101     """
102     logger.console('Extracting tarball to {0} on {1}'
103                    .format(con.REMOTE_FW_DIR, node['host']))
104     ssh = SSH()
105     ssh.connect(node)
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)
109     if ret_code != 0:
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']))
114
115
116 def create_env_directory_at_node(node):
117     """Create fresh virtualenv to a directory, install pip requirements.
118
119     :param node: Node to create virtualenv on.
120     :type node: dict
121     :returns: nothing
122     :raises RuntimeError: When failed to setup virtualenv.
123     """
124     logger.console('Virtualenv setup including requirements.txt on {0}'
125                    .format(node['host']))
126     ssh = SSH()
127     ssh.connect(node)
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)
134     if ret_code != 0:
135         raise RuntimeError('Virtualenv setup including requirements.txt on {0}'
136                            .format(node['host']))
137
138     logger.console('Virtualenv on {0} created'.format(node['host']))
139
140
141 def setup_node(args):
142     """Run all set-up methods for a node.
143
144     This method is used as map_async parameter. It receives tuple with all
145     parameters as passed to map_async function.
146
147     :param args: All parameters needed to setup one node.
148     :type args: tuple
149     :returns: True - success, False - error
150     :rtype: bool
151     """
152     tarball, remote_tarball, node = args
153     try:
154         copy_tarball_to_node(tarball, node)
155         extract_tarball_at_node(remote_tarball, node)
156         if node['type'] == NodeType.TG:
157             create_env_directory_at_node(node)
158     except RuntimeError as exc:
159         logger.error("Node {0} setup failed, error:'{1}'"
160                      .format(node['host'], exc.message))
161         return False
162     else:
163         logger.console('Setup of node {0} done'.format(node['host']))
164         return True
165
166
167 def delete_local_tarball(tarball):
168     """Delete local tarball to prevent disk pollution.
169
170     :param tarball: Path to tarball to upload.
171     :type tarball: str
172     :returns: nothing
173     """
174     call(split('sh -c "rm {0} > /dev/null 2>&1"'.format(tarball)))
175
176
177 def delete_framework_dir(node):
178     """Delete framework directory in /tmp/ on given node.
179
180     :param node: Node to delete framework directory on.
181     :type node: dict
182     """
183     logger.console('Deleting framework directory on {0}'
184                    .format(node['host']))
185     ssh = SSH()
186     ssh.connect(node)
187     (ret_code, _, _) = ssh.exec_command(
188         'sudo rm -rf {0}'
189         .format(con.REMOTE_FW_DIR), timeout=100)
190     if ret_code != 0:
191         raise RuntimeError('Deleting framework directory on {0} failed'
192                            .format(node))
193
194
195 def cleanup_node(node):
196     """Run all clean-up methods for a node.
197
198     This method is used as map_async parameter. It receives tuple with all
199     parameters as passed to map_async function.
200
201     :param node: Node to do cleanup on.
202     :type node: dict
203     :returns: True - success, False - error
204     :rtype: bool
205     """
206     try:
207         delete_framework_dir(node)
208     except RuntimeError:
209         logger.error("Cleanup of node {0} failed".format(node['host']))
210         return False
211     else:
212         logger.console('Cleanup of node {0} done'.format(node['host']))
213         return True
214
215
216 class SetupFramework(object):
217     """Setup suite run on topology nodes.
218
219     Many VAT/CLI based tests need the scripts at remote hosts before executing
220     them. This class packs the whole testing directory and copies it over
221     to all nodes in topology under /tmp/
222     """
223
224     @staticmethod
225     def setup_framework(nodes):
226         """Pack the whole directory and extract in temp on each node.
227
228         :param nodes: Topology nodes.
229         :type nodes: dict
230         :raises RuntimeError: If setup framework failed.
231         """
232
233         tarball = pack_framework_dir()
234         msg = 'Framework packed to {0}'.format(tarball)
235         logger.console(msg)
236         logger.trace(msg)
237         remote_tarball = "/tmp/{0}".format(basename(tarball))
238
239         # Turn off logging since we use multiprocessing
240         log_level = BuiltIn().set_log_level('NONE')
241         params = ((tarball, remote_tarball, node) for node in nodes.values())
242         pool = Pool(processes=len(nodes))
243         result = pool.map_async(setup_node, params)
244         pool.close()
245         pool.join()
246
247         # Turn on logging
248         BuiltIn().set_log_level(log_level)
249
250         logger.info(
251             'Executing node setups in parallel, waiting for processes to end')
252         result.wait()
253
254         results = result.get()
255         node_success = all(results)
256         logger.info('Results: {0}'.format(results))
257
258         delete_local_tarball(tarball)
259         if node_success:
260             logger.console('All nodes are ready')
261         else:
262             raise RuntimeError('Failed to setup framework')
263
264
265 class CleanupFramework(object):
266     """Clean up suite run on topology nodes."""
267
268     @staticmethod
269     def cleanup_framework(nodes):
270         """Perform cleaning on each node.
271
272         :param nodes: Topology nodes.
273         :type nodes: dict
274         :raises RuntimeError: If cleanup framework failed.
275         """
276         # Turn off logging since we use multiprocessing
277         log_level = BuiltIn().set_log_level('NONE')
278         params = (node for node in nodes.values())
279         pool = Pool(processes=len(nodes))
280         result = pool.map_async(cleanup_node, params)
281         pool.close()
282         pool.join()
283
284         # Turn on logging
285         BuiltIn().set_log_level(log_level)
286
287         logger.info(
288             'Executing node cleanups in parallel, waiting for processes to end')
289         result.wait()
290
291         results = result.get()
292         node_success = all(results)
293         logger.info('Results: {0}'.format(results))
294
295         if node_success:
296             logger.console('All nodes cleaned up')
297         else:
298             raise RuntimeError('Failed to cleaned up framework')