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