Honeycomb setup and utils
[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 import shlex
20 from subprocess import Popen, PIPE, call
21 from multiprocessing import Pool
22 from tempfile import NamedTemporaryFile
23 from os.path import basename
24
25 from robot.api import logger
26 from robot.libraries.BuiltIn import BuiltIn
27
28 from resources.libraries.python.ssh import SSH
29 from resources.libraries.python.constants import Constants as con
30 from resources.libraries.python.topology import NodeType
31
32 __all__ = ["SetupFramework"]
33
34 def pack_framework_dir():
35     """Pack the testing WS into temp file, return its name."""
36
37     tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="openvpp-testing-")
38     file_name = tmpfile.name
39     tmpfile.close()
40
41     proc = Popen(
42         shlex.split("tar --exclude-vcs -zcf {0} .".format(file_name)),
43         stdout=PIPE, stderr=PIPE)
44     (stdout, stderr) = proc.communicate()
45
46     logger.debug(stdout)
47     logger.debug(stderr)
48
49     return_code = proc.wait()
50     if 0 != return_code:
51         raise Exception("Could not pack testing framework.")
52
53     return file_name
54
55
56 def copy_tarball_to_node(tarball, node):
57     """Copy tarball file from local host to remote node.
58
59     :param tarball: path to tarball to upload
60     :param node: dictionary created from topology
61     :type tarball: string
62     :type node: dict
63     :return: nothing
64     """
65     logger.console('Copying tarball to {0}'.format(node['host']))
66     ssh = SSH()
67     ssh.connect(node)
68
69     ssh.scp(tarball, "/tmp/")
70
71
72 def extract_tarball_at_node(tarball, node):
73     """Extract tarball at given node.
74
75     Extracts tarball using tar on given node to specific CSIT loocation.
76
77     :param tarball: path to tarball to upload
78     :param node: dictionary created from topology
79     :type tarball: string
80     :type node: dict
81     :return: nothing
82     """
83     logger.console('Extracting tarball to {0} on {1}'.format(
84         con.REMOTE_FW_DIR, node['host']))
85     ssh = SSH()
86     ssh.connect(node)
87
88     cmd = 'sudo rm -rf {1}; mkdir {1} ; tar -zxf {0} -C {1}; ' \
89         'rm -f {0}'.format(tarball, con.REMOTE_FW_DIR)
90     (ret_code, _, stderr) = ssh.exec_command(cmd, timeout=30)
91     if 0 != ret_code:
92         logger.error('Unpack error: {0}'.format(stderr))
93         raise Exception('Failed to unpack {0} at node {1}'.format(
94             tarball, node['host']))
95
96
97 def create_env_directory_at_node(node):
98     """Create fresh virtualenv to a directory, install pip requirements."""
99     logger.console('Extracting virtualenv, installing requirements.txt '
100                    'on {0}'.format(node['host']))
101     ssh = SSH()
102     ssh.connect(node)
103     (ret_code, stdout, stderr) = ssh.exec_command(
104         'cd {0} && rm -rf env && virtualenv env && . env/bin/activate && '
105         'pip install -r requirements.txt'.format(con.REMOTE_FW_DIR),
106                                                  timeout=100)
107     if 0 != ret_code:
108         logger.error('Virtualenv creation error: {0}'.format(stdout + stderr))
109         raise Exception('Virtualenv setup failed')
110     else:
111         logger.console('Virtualenv created on {0}'.format(node['host']))
112
113 def setup_node(args):
114     """Run all set-up methods for a node.
115
116     This method is used as map_async parameter. It receives tuple with all
117     parameters as passed to map_async function.
118
119     :param args: all parameters needed to setup one node
120     :type args: tuple
121     :return: nothing
122     """
123     tarball, remote_tarball, node = args
124     copy_tarball_to_node(tarball, node)
125     extract_tarball_at_node(remote_tarball, node)
126     if node['type'] == NodeType.TG:
127         create_env_directory_at_node(node)
128     logger.console('Setup of node {0} done'.format(node['host']))
129
130 def delete_local_tarball(tarball):
131     """Delete local tarball to prevent disk pollution.
132
133     :param tarball: path to tarball to upload
134     :type tarball: string
135     :return: nothing
136     """
137     call(shlex.split('sh -c "rm {0} > /dev/null 2>&1"'.format(tarball)))
138
139 class SetupFramework(object): # pylint: disable=too-few-public-methods
140     """Setup suite run on topology nodes.
141
142     Many VAT/CLI based tests need the scripts at remote hosts before executing
143     them. This class packs the whole testing directory and copies it over
144     to all nodes in topology under /tmp/
145     """
146
147     def __init__(self):
148         pass
149
150     @staticmethod
151     def setup_framework(nodes):
152         """Pack the whole directory and extract in temp on each node."""
153
154         tarball = pack_framework_dir()
155         msg = 'Framework packed to {0}'.format(tarball)
156         logger.console(msg)
157         logger.trace(msg)
158         remote_tarball = "/tmp/{0}".format(basename(tarball))
159
160         # Turn off loggining since we use multiprocessing
161         log_level = BuiltIn().set_log_level('NONE')
162         params = ((tarball, remote_tarball, node) for node in nodes.values())
163         pool = Pool(processes=len(nodes))
164         result = pool.map_async(setup_node, params)
165         pool.close()
166         pool.join()
167
168         logger.info(
169             'Executed node setups in parallel, waiting for processes to end')
170         result.wait()
171
172         logger.info('Results: {0}'.format(result.get()))
173
174         # Turn on loggining
175         BuiltIn().set_log_level(log_level)
176         logger.trace('Test framework copied to all topology nodes')
177         delete_local_tarball(tarball)
178         logger.console('All nodes are ready')
179