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