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