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