FIX: SetupFramework to detect failures
[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
88
89 def extract_tarball_at_node(tarball, node):
90     """Extract tarball at given node.
91
92     Extracts tarball using tar on given node to specific CSIT location.
93
94     :param tarball: Path to tarball to upload.
95     :param node: Dictionary created from topology.
96     :type tarball: str
97     :type node: dict
98     :returns: nothing
99     :raises RuntimeError: When failed to unpack tarball.
100     """
101     logger.console('Extracting tarball to {0} on {1}'
102                    .format(con.REMOTE_FW_DIR, node['host']))
103     ssh = SSH()
104     ssh.connect(node)
105     (ret_code, _, _) = ssh.exec_command(
106         'sudo rm -rf {1}; mkdir {1} ; tar -zxf {0} -C {1}; rm -f {0}'
107         .format(tarball, con.REMOTE_FW_DIR), timeout=30)
108     if ret_code != 0:
109         raise RuntimeError('Failed to extract {0} at node {1}'
110                            .format(tarball, node['host']))
111
112
113 def create_env_directory_at_node(node):
114     """Create fresh virtualenv to a directory, install pip requirements.
115
116     :param node: Node to create virtualenv on.
117     :type node: dict
118     :returns: nothing
119     :raises RuntimeError: When failed to setup virtualenv.
120     """
121     logger.console('Virtualenv setup including requirements.txt on {0}'
122                    .format(node['host']))
123     ssh = SSH()
124     ssh.connect(node)
125     (ret_code, _, _) = ssh.exec_command(
126         'cd {0} && rm -rf env && '
127         'virtualenv --system-site-packages --never-download env && '
128         '. env/bin/activate && '
129         'pip install -r requirements.txt'
130         .format(con.REMOTE_FW_DIR), timeout=100)
131     if ret_code != 0:
132         raise RuntimeError('Virtualenv setup including requirements.txt on {0}'
133                            .format(node['host']))
134     else:
135         logger.console('Virtualenv on {0} created'.format(node['host']))
136
137
138 def setup_node(args):
139     """Run all set-up methods for a node.
140
141     This method is used as map_async parameter. It receives tuple with all
142     parameters as passed to map_async function.
143
144     :param args: All parameters needed to setup one node.
145     :type args: tuple
146     :returns: True - success, False - error
147     :rtype: bool
148     """
149     tarball, remote_tarball, node = args
150     try:
151         copy_tarball_to_node(tarball, node)
152         extract_tarball_at_node(remote_tarball, node)
153         if node['type'] == NodeType.TG:
154             create_env_directory_at_node(node)
155     except RuntimeError as exc:
156         logger.error("Node {0} setup failed, error:'{1}'"
157                      .format(node['host'], exc.message))
158         return False
159     else:
160         logger.console('Setup of node {0} done'.format(node['host']))
161         return True
162
163
164 def delete_local_tarball(tarball):
165     """Delete local tarball to prevent disk pollution.
166
167     :param tarball: Path to tarball to upload.
168     :type tarball: str
169     :returns: nothing
170     """
171     call(split('sh -c "rm {0} > /dev/null 2>&1"'.format(tarball)))
172
173
174 def delete_framework_dir(node):
175     """Delete framework directory in /tmp/ on given node.
176
177     :param node: Node to delete framework directory on.
178     :type node: dict
179     """
180     logger.console('Deleting framework directory on {0}'
181                    .format(node['host']))
182     ssh = SSH()
183     ssh.connect(node)
184     (ret_code, _, _) = ssh.exec_command(
185         'sudo rm -rf {0}'
186         .format(con.REMOTE_FW_DIR), timeout=100)
187     if ret_code != 0:
188         raise RuntimeError('Deleting framework directory on {0} failed'
189                            .format(node))
190
191
192 def cleanup_node(node):
193     """Run all clean-up methods for a node.
194
195     This method is used as map_async parameter. It receives tuple with all
196     parameters as passed to map_async function.
197
198     :param node: Node to do cleanup on.
199     :type node: dict
200     :returns: True - success, False - error
201     :rtype: bool
202     """
203     try:
204         delete_framework_dir(node)
205     except RuntimeError:
206         logger.error("Cleanup of node {0} failed".format(node['host']))
207         return False
208     else:
209         logger.console('Cleanup of node {0} done'.format(node['host']))
210         return True
211
212
213 class SetupFramework(object):
214     """Setup suite run on topology nodes.
215
216     Many VAT/CLI based tests need the scripts at remote hosts before executing
217     them. This class packs the whole testing directory and copies it over
218     to all nodes in topology under /tmp/
219     """
220
221     @staticmethod
222     def setup_framework(nodes):
223         """Pack the whole directory and extract in temp on each node.
224
225         :param nodes: Topology nodes.
226         :type nodes: dict
227         :returns: True - success, False - error
228         :rtype: bool
229         """
230
231         tarball = pack_framework_dir()
232         msg = 'Framework packed to {0}'.format(tarball)
233         logger.console(msg)
234         logger.trace(msg)
235         remote_tarball = "/tmp/{0}".format(basename(tarball))
236
237         # Turn off logging since we use multiprocessing
238         log_level = BuiltIn().set_log_level('NONE')
239         params = ((tarball, remote_tarball, node) for node in nodes.values())
240         pool = Pool(processes=len(nodes))
241         result = pool.map_async(setup_node, params)
242         pool.close()
243         pool.join()
244
245         # Turn on logging
246         BuiltIn().set_log_level(log_level)
247
248         logger.info(
249             'Executing node setups in parallel, waiting for processes to end')
250         result.wait()
251
252         results = result.get()
253         node_success = all(results)
254         logger.info('Results: {0}'.format(results))
255
256         delete_local_tarball(tarball)
257         if node_success:
258             logger.console('All nodes are ready')
259             return True
260         else:
261             logger.console('Failed to setup framework')
262             return False
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         :returns: True - success, False - error
275         :rtype: bool
276         """
277         # Turn off logging since we use multiprocessing
278         log_level = BuiltIn().set_log_level('NONE')
279         params = (node for node in nodes.values())
280         pool = Pool(processes=len(nodes))
281         result = pool.map_async(cleanup_node, params)
282         pool.close()
283         pool.join()
284
285         # Turn on logging
286         BuiltIn().set_log_level(log_level)
287
288         logger.info(
289             'Executing node cleanups in parallel, waiting for processes to end')
290         result.wait()
291
292         results = result.get()
293         node_success = all(results)
294         logger.info('Results: {0}'.format(results))
295
296         if node_success:
297             logger.console('All nodes cleaned up')
298             return True
299         else:
300             logger.console('Failed to cleaned up framework')
301             return False