Python3: PIP requirement
[csit.git] / resources / libraries / python / SetupFramework.py
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:
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 os import environ, remove
20 from os.path import basename
21 from tempfile import NamedTemporaryFile
22 import threading
23
24 from robot.api import logger
25
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
30
31 __all__ = ["SetupFramework"]
32
33
34 def pack_framework_dir():
35     """Pack the testing WS into temp file, return its name.
36
37     :returns: Tarball file name.
38     :rtype: str
39     :raises Exception: When failed to pack testing framework.
40     """
41
42     try:
43         directory = environ["TMPDIR"]
44     except KeyError:
45         directory = None
46
47     if directory is not None:
48         tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-",
49                                      dir="{0}".format(directory))
50     else:
51         tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="csit-testing-")
52     file_name = tmpfile.name
53     tmpfile.close()
54
55     run(["tar", "--sparse", "--exclude-vcs", "--exclude=output*.xml",
56          "--exclude=./tmp", "-zcf", file_name, "."],
57         msg="Could not pack testing framework")
58
59     return file_name
60
61
62 def copy_tarball_to_node(tarball, node):
63     """Copy tarball file from local host to remote node.
64
65     :param tarball: Path to tarball to upload.
66     :param node: Dictionary created from topology.
67     :type tarball: str
68     :type node: dict
69     :returns: nothing
70     """
71     host = node['host']
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))
75
76
77 def extract_tarball_at_node(tarball, node):
78     """Extract tarball at given node.
79
80     Extracts tarball using tar on given node to specific CSIT location.
81
82     :param tarball: Path to tarball to upload.
83     :param node: Dictionary created from topology.
84     :type tarball: str
85     :type node: dict
86     :returns: nothing
87     :raises RuntimeError: When failed to unpack tarball.
88     """
89     host = node['host']
90     logger.console('Extracting tarball to {0} on {1} starts.'
91                    .format(con.REMOTE_FW_DIR, host))
92     exec_cmd_no_error(
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))
99
100
101 def create_env_directory_at_node(node):
102     """Create fresh virtualenv to a directory, install pip requirements.
103
104     :param node: Node to create virtualenv on.
105     :type node: dict
106     :returns: nothing
107     :raises RuntimeError: When failed to setup virtualenv.
108     """
109     host = node['host']
110     logger.console('Virtualenv setup including requirements.txt on {0} starts.'
111                    .format(host))
112     exec_cmd_no_error(
113         node, 'cd {0} && rm -rf env'
114         ' && virtualenv -p $(which python3) '
115         '--system-site-packages --never-download env'
116         ' && source env/bin/activate && pip3 install -r requirements.txt'
117         .format(con.REMOTE_FW_DIR), timeout=100, include_reason=True,
118         message="Failed install at node {host}".format(host=host))
119     logger.console('Virtualenv setup on {0} done.'.format(host))
120
121
122 def setup_node(node, tarball, remote_tarball, results=None):
123     """Copy a tarball to a node and extract it.
124
125     :param node: A node where the tarball will be copied and extracted.
126     :param tarball: Local path of tarball to be copied.
127     :param remote_tarball: Remote path of the tarball.
128     :param results: A list where to store the result of node setup, optional.
129     :type node: dict
130     :type tarball: str
131     :type remote_tarball: str
132     :type results: list
133     :returns: True - success, False - error
134     :rtype: bool
135     """
136     host = node['host']
137     try:
138         copy_tarball_to_node(tarball, node)
139         extract_tarball_at_node(remote_tarball, node)
140         if node['type'] == NodeType.TG:
141             create_env_directory_at_node(node)
142     except RuntimeError as exc:
143         logger.console("Node {node} setup failed, error: {err!r}".format(
144             node=host, err=exc))
145         result = False
146     else:
147         logger.console('Setup of node {ip} done.'.format(ip=host))
148         result = True
149
150     if isinstance(results, list):
151         results.append(result)
152     return result
153
154
155 def delete_local_tarball(tarball):
156     """Delete local tarball to prevent disk pollution.
157
158     :param tarball: Path of local tarball to delete.
159     :type tarball: str
160     :returns: nothing
161     """
162     remove(tarball)
163
164
165 def delete_framework_dir(node):
166     """Delete framework directory in /tmp/ on given node.
167
168     :param node: Node to delete framework directory on.
169     :type node: dict
170     """
171     host = node['host']
172     logger.console(
173         'Deleting framework directory on {0} starts.'.format(host))
174     exec_cmd_no_error(
175         node, 'sudo rm -rf {0}'.format(con.REMOTE_FW_DIR),
176         message="Framework delete failed at node {host}".format(host=host),
177         timeout=100, include_reason=True)
178     logger.console(
179         'Deleting framework directory on {0} done.'.format(host))
180
181
182 def cleanup_node(node, results=None):
183     """Delete a tarball from a node.
184
185     :param node: A node where the tarball will be delete.
186     :param results: A list where to store the result of node cleanup, optional.
187     :type node: dict
188     :type results: list
189     :returns: True - success, False - error
190     :rtype: bool
191     """
192     host = node['host']
193     try:
194         delete_framework_dir(node)
195     except RuntimeError:
196         logger.error("Cleanup of node {0} failed.".format(host))
197         result = False
198     else:
199         logger.console('Cleanup of node {0} done.'.format(host))
200         result = True
201
202     if isinstance(results, list):
203         results.append(result)
204     return result
205
206
207 class SetupFramework(object):
208     """Setup suite run on topology nodes.
209
210     Many VAT/CLI based tests need the scripts at remote hosts before executing
211     them. This class packs the whole testing directory and copies it over
212     to all nodes in topology under /tmp/
213     """
214
215     @staticmethod
216     def setup_framework(nodes):
217         """Pack the whole directory and extract in temp on each node.
218
219         :param nodes: Topology nodes.
220         :type nodes: dict
221         :raises RuntimeError: If setup framework failed.
222         """
223
224         tarball = pack_framework_dir()
225         msg = 'Framework packed to {0}'.format(tarball)
226         logger.console(msg)
227         logger.trace(msg)
228         remote_tarball = "/tmp/{0}".format(basename(tarball))
229
230         results = []
231         threads = []
232
233         for node in nodes.values():
234             args = node, tarball, remote_tarball, results
235             thread = threading.Thread(target=setup_node, args=args)
236             thread.start()
237             threads.append(thread)
238
239         logger.info(
240             'Executing node setups in parallel, waiting for threads to end')
241
242         for thread in threads:
243             thread.join()
244
245         logger.info('Results: {0}'.format(results))
246
247         delete_local_tarball(tarball)
248         if all(results):
249             logger.console('All nodes are ready.')
250             for node in nodes.values():
251                 logger.info('Setup of {type} node {ip} done.'.
252                             format(type=node['type'], ip=node['host']))
253         else:
254             raise RuntimeError('Failed to setup framework.')
255
256
257 class CleanupFramework(object):
258     """Clean up suite run on topology nodes."""
259
260     @staticmethod
261     def cleanup_framework(nodes):
262         """Perform cleanup on each node.
263
264         :param nodes: Topology nodes.
265         :type nodes: dict
266         :raises RuntimeError: If cleanup framework failed.
267         """
268
269         results = []
270         threads = []
271
272         for node in nodes.values():
273             thread = threading.Thread(target=cleanup_node,
274                                       args=(node, results))
275             thread.start()
276             threads.append(thread)
277
278         logger.info(
279             'Executing node cleanups in parallel, waiting for threads to end.')
280
281         for thread in threads:
282             thread.join()
283
284         logger.info('Results: {0}'.format(results))
285
286         if all(results):
287             logger.console('All nodes cleaned up.')
288         else:
289             raise RuntimeError('Failed to cleaned up framework.')