9aff15278e6ecda3a234706a6569c410f41f268e
[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 import datetime
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
25 import threading
26
27 from robot.api import logger
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 -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(node, tarball, remote_tarball, results=None):
142     """Copy a tarball to a node and extract it.
143
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.
148     :type node: dict
149     :type tarball: str
150     :type remote_tarball: str
151     :type results: list
152     :returns: True - success, False - error
153     :rtype: bool
154     """
155     try:
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))
163         result = False
164     else:
165         logger.console('Setup of node {0} done'.format(node['host']))
166         result = True
167
168     if isinstance(results, list):
169         results.append(result)
170     return result
171
172
173 def delete_local_tarball(tarball):
174     """Delete local tarball to prevent disk pollution.
175
176     :param tarball: Path of local tarball to delete.
177     :type tarball: str
178     :returns: nothing
179     """
180     remove(tarball)
181
182
183 def delete_framework_dir(node):
184     """Delete framework directory in /tmp/ on given node.
185
186     :param node: Node to delete framework directory on.
187     :type node: dict
188     """
189     logger.console('Deleting framework directory on {0}'
190                    .format(node['host']))
191     ssh = SSH()
192     ssh.connect(node)
193     (ret_code, _, _) = ssh.exec_command(
194         'sudo rm -rf {0}'
195         .format(con.REMOTE_FW_DIR), timeout=100)
196     if ret_code != 0:
197         raise RuntimeError('Deleting framework directory on {0} failed'
198                            .format(node))
199
200
201 def cleanup_node(node, results=None):
202     """Delete a tarball from a node.
203
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.
206     :type node: dict
207     :type results: list
208     :returns: True - success, False - error
209     :rtype: bool
210     """
211     try:
212         delete_framework_dir(node)
213     except RuntimeError:
214         logger.error("Cleanup of node {0} failed".format(node['host']))
215         result = False
216     else:
217         logger.console('Cleanup of node {0} done'.format(node['host']))
218         result = True
219
220     if isinstance(results, list):
221         results.append(result)
222     return result
223
224
225 class SetupFramework(object):
226     """Setup suite run on topology nodes.
227
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/
231     """
232
233     @staticmethod
234     def setup_framework(nodes):
235         """Pack the whole directory and extract in temp on each node.
236
237         :param nodes: Topology nodes.
238         :type nodes: dict
239         :raises RuntimeError: If setup framework failed.
240         """
241
242         tarball = pack_framework_dir()
243         msg = 'Framework packed to {0}'.format(tarball)
244         logger.console(msg)
245         logger.trace(msg)
246         remote_tarball = "/tmp/{0}".format(basename(tarball))
247
248         results = []
249         threads = []
250
251         for node in nodes.values():
252             thread = threading.Thread(target=setup_node, args=(node,
253                                                                tarball,
254                                                                remote_tarball,
255                                                                results))
256             thread.start()
257             threads.append(thread)
258
259         logger.info(
260             'Executing node setups in parallel, waiting for threads to end')
261
262         for thread in threads:
263             thread.join()
264
265         logger.info('Results: {0}'.format(results))
266
267         delete_local_tarball(tarball)
268         if all(results):
269             logger.console('All nodes are ready')
270         else:
271             raise RuntimeError('Failed to setup framework')
272
273
274 class CleanupFramework(object):
275     """Clean up suite run on topology nodes."""
276
277     @staticmethod
278     def cleanup_framework(nodes):
279         """Perform cleanup on each node.
280
281         :param nodes: Topology nodes.
282         :type nodes: dict
283         :raises RuntimeError: If cleanup framework failed.
284         """
285
286         results = []
287         threads = []
288
289         for node in nodes.values():
290             thread = threading.Thread(target=cleanup_node,
291                                       args=(node, results))
292             thread.start()
293             threads.append(thread)
294
295         logger.info(
296             'Executing node cleanups in parallel, waiting for threads to end')
297
298         for thread in threads:
299             thread.join()
300
301         logger.info('Results: {0}'.format(results))
302
303         if all(results):
304             logger.console('All nodes cleaned up')
305         else:
306             raise RuntimeError('Failed to cleaned up framework')