Fix: SetupFramework sparse file handling
[csit.git] / resources / libraries / python / SetupFramework.py
1 # Copyright (c) 2016 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     try:
40         directory = environ["TMPDIR"]
41     except KeyError:
42         directory = None
43
44     if directory is not None:
45         tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="openvpp-testing-",
46                                      dir="{0}".format(directory))
47     else:
48         tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="openvpp-testing-")
49     file_name = tmpfile.name
50     tmpfile.close()
51
52     proc = Popen(
53         split("tar --sparse --exclude-vcs "
54               "--exclude=./tmp --exclude=*.deb -zcf {0} .".
55               format(file_name)), stdout=PIPE, stderr=PIPE)
56     (stdout, stderr) = proc.communicate()
57
58     logger.debug(stdout)
59     logger.debug(stderr)
60
61     return_code = proc.wait()
62     if return_code != 0:
63         raise Exception("Could not pack testing framework.")
64
65     return file_name
66
67
68 def copy_tarball_to_node(tarball, node):
69     """Copy tarball file from local host to remote node.
70
71     :param tarball: Path to tarball to upload.
72     :param node: Dictionary created from topology.
73     :type tarball: str
74     :type node: dict
75     :returns: nothing
76     """
77     logger.console('Copying tarball to {0}'.format(node['host']))
78     ssh = SSH()
79     ssh.connect(node)
80
81     ssh.scp(tarball, "/tmp/")
82
83
84 def extract_tarball_at_node(tarball, node):
85     """Extract tarball at given node.
86
87     Extracts tarball using tar on given node to specific CSIT location.
88
89     :param tarball: Path to tarball to upload.
90     :param node: Dictionary created from topology.
91     :type tarball: str
92     :type node: dict
93     :returns: nothing
94     """
95     logger.console('Extracting tarball to {0} on {1}'.format(
96         con.REMOTE_FW_DIR, node['host']))
97     ssh = SSH()
98     ssh.connect(node)
99
100     cmd = 'sudo rm -rf {1}; mkdir {1} ; tar -zxf {0} -C {1}; ' \
101         'rm -f {0}'.format(tarball, con.REMOTE_FW_DIR)
102     (ret_code, _, stderr) = ssh.exec_command(cmd, timeout=30)
103     if ret_code != 0:
104         logger.error('Unpack error: {0}'.format(stderr))
105         raise Exception('Failed to unpack {0} at node {1}'.format(
106             tarball, node['host']))
107
108
109 def create_env_directory_at_node(node):
110     """Create fresh virtualenv to a directory, install pip requirements."""
111     logger.console('Extracting virtualenv, installing requirements.txt '
112                    'on {0}'.format(node['host']))
113     ssh = SSH()
114     ssh.connect(node)
115     (ret_code, stdout, stderr) = ssh.exec_command(
116         'cd {0} && rm -rf env && '
117         'virtualenv --system-site-packages --never-download env && '
118         '. env/bin/activate && '
119         'pip install -r requirements.txt'
120         .format(con.REMOTE_FW_DIR), timeout=100)
121     if ret_code != 0:
122         logger.error('Virtualenv creation error: {0}'.format(stdout + stderr))
123         raise Exception('Virtualenv setup failed')
124     else:
125         logger.console('Virtualenv created on {0}'.format(node['host']))
126
127
128 # pylint: disable=broad-except
129 def setup_node(args):
130     """Run all set-up methods for a node.
131
132     This method is used as map_async parameter. It receives tuple with all
133     parameters as passed to map_async function.
134
135     :param args: All parameters needed to setup one node.
136     :type args: tuple
137     :returns: True - success, False - error
138     :rtype: bool
139     """
140     tarball, remote_tarball, node = args
141     try:
142         copy_tarball_to_node(tarball, node)
143         extract_tarball_at_node(remote_tarball, node)
144         if node['type'] == NodeType.TG:
145             create_env_directory_at_node(node)
146     except Exception as exc:
147         logger.error("Node setup failed, error:'{0}'".format(exc.message))
148         return False
149     else:
150         logger.console('Setup of node {0} done'.format(node['host']))
151         return True
152
153
154 def delete_local_tarball(tarball):
155     """Delete local tarball to prevent disk pollution.
156
157     :param tarball: Path to tarball to upload.
158     :type tarball: str
159     :returns: nothing
160     """
161     call(split('sh -c "rm {0} > /dev/null 2>&1"'.format(tarball)))
162
163
164 class SetupFramework(object):
165     """Setup suite run on topology nodes.
166
167     Many VAT/CLI based tests need the scripts at remote hosts before executing
168     them. This class packs the whole testing directory and copies it over
169     to all nodes in topology under /tmp/
170     """
171
172     @staticmethod
173     def setup_framework(nodes):
174         """Pack the whole directory and extract in temp on each node."""
175
176         tarball = pack_framework_dir()
177         msg = 'Framework packed to {0}'.format(tarball)
178         logger.console(msg)
179         logger.trace(msg)
180         remote_tarball = "/tmp/{0}".format(basename(tarball))
181
182         # Turn off logging since we use multiprocessing
183         log_level = BuiltIn().set_log_level('NONE')
184         params = ((tarball, remote_tarball, node) for node in nodes.values())
185         pool = Pool(processes=len(nodes))
186         result = pool.map_async(setup_node, params)
187         pool.close()
188         pool.join()
189
190         # Turn on logging
191         BuiltIn().set_log_level(log_level)
192
193         logger.info(
194             'Executed node setups in parallel, waiting for processes to end')
195         result.wait()
196
197         logger.info('Results: {0}'.format(result.get()))
198
199         logger.trace('Test framework copied to all topology nodes')
200         delete_local_tarball(tarball)
201         logger.console('All nodes are ready')