d94a3837868ed447f83f0f416f89bee1ef7f5e8b
[csit.git] / resources / libraries / python / DPDK / SetupDPDKTest.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
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__ = ["SetupDPDKTest"]
34
35
36 def pack_framework_dir():
37     """Pack the testing WS into temp file, return its name."""
38
39     tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="DPDK-testing-")
40     file_name = tmpfile.name
41     tmpfile.close()
42
43     proc = Popen(
44         split("tar --exclude-vcs -zcf {0} .".format(file_name)),
45         stdout=PIPE, stderr=PIPE)
46     (stdout, stderr) = proc.communicate()
47
48     logger.debug(stdout)
49     logger.debug(stderr)
50
51     return_code = proc.wait()
52     if return_code != 0:
53         raise Exception("Could not pack testing framework.")
54
55     return file_name
56
57
58 def copy_tarball_to_node(tarball, node):
59     """Copy tarball file from local host to remote node.
60
61     :param tarball: Path to tarball to upload.
62     :param node: Dictionary created from topology.
63     :type tarball: str
64     :type node: dict
65     :returns: nothing
66     """
67     logger.console('Copying tarball to {0}'.format(node['host']))
68     ssh = SSH()
69     ssh.connect(node)
70
71     ssh.scp(tarball, "/tmp/")
72
73
74 def extract_tarball_at_node(tarball, node):
75     """Extract tarball at given node.
76
77     Extracts tarball using tar on given node to specific CSIT loocation.
78
79     :param tarball: Path to tarball to upload.
80     :param node: Dictionary created from topology.
81     :type tarball: str
82     :type node: dict
83     :returns: nothing
84     """
85     logger.console('Extracting tarball to {0} on {1}'.format(
86         con.REMOTE_FW_DIR, node['host']))
87     ssh = SSH()
88     ssh.connect(node)
89
90     cmd = 'sudo rm -rf {1}; mkdir {1} ; tar -zxf {0} -C {1}; ' \
91         'rm -f {0}'.format(tarball, con.REMOTE_FW_DIR)
92     (ret_code, _, stderr) = ssh.exec_command(cmd, timeout=30)
93     if ret_code != 0:
94         logger.error('Unpack error: {0}'.format(stderr))
95         raise Exception('Failed to unpack {0} at node {1}'.format(
96             tarball, node['host']))
97
98
99 def create_env_directory_at_node(node):
100     """
101     Create fresh virtualenv to a directory, install pip requirements.
102
103     :param node: Dictionary created from topology, will only install in the TG
104     :type node: dict
105     :returns: nothing
106     """
107     logger.console('Extracting virtualenv, installing requirements.txt '
108                    'on {0}'.format(node['host']))
109     ssh = SSH()
110     ssh.connect(node)
111     (ret_code, stdout, stderr) = ssh.exec_command(
112         'cd {0} && rm -rf env && virtualenv env && '
113         '. env/bin/activate && pip install -r requirements.txt'
114         .format(con.REMOTE_FW_DIR), timeout=100)
115     if ret_code != 0:
116         logger.error('Virtualenv creation error: {0}'.format(stdout + stderr))
117         raise Exception('Virtualenv setup failed')
118     else:
119         logger.console('Virtualenv created on {0}'.format(node['host']))
120
121 def install_dpdk_test(node):
122     """
123     Prepare the DPDK test envrionment
124
125     :param node: Dictionary created from topology
126     :type node: dict
127     :returns: nothing
128     """
129     arch = Topology.get_node_arch(node)
130     logger.console('Install the DPDK on {0} ({1})'.format(node['host'],
131                                                           arch))
132
133     ssh = SSH()
134     ssh.connect(node)
135
136     (ret_code, _, stderr) = ssh.exec_command(
137         'cd {0}/tests/dpdk/dpdk_scripts/ && ./install_dpdk.sh {1}'
138         .format(con.REMOTE_FW_DIR, arch), timeout=600)
139
140     if ret_code != 0:
141         logger.error('Install the DPDK error: {0}'.format(stderr))
142         raise Exception('Install the DPDK failed')
143     else:
144         logger.console('Install the DPDK on {0} success!'.format(node['host']))
145
146 #pylint: disable=broad-except
147 def setup_node(args):
148     """Run all set-up methods for a node.
149
150     This method is used as map_async parameter. It receives tuple with all
151     parameters as passed to map_async function.
152
153     :param args: All parameters needed to setup one node.
154     :type args: tuple
155     :returns: True - success, False - error
156     :rtype: bool
157     """
158     tarball, remote_tarball, node = args
159
160     # if unset, arch defaults to x86_64
161     if 'arch' not in node or not node['arch']:
162         node['arch'] = 'x86_64'
163
164     try:
165         copy_tarball_to_node(tarball, node)
166         extract_tarball_at_node(remote_tarball, node)
167         if node['type'] == NodeType.DUT:
168             install_dpdk_test(node)
169         if node['type'] == NodeType.TG:
170             create_env_directory_at_node(node)
171     except Exception as exc:
172         logger.error("Node setup failed, error:'{0}'".format(exc.message))
173         return False
174     else:
175         logger.console('Setup of node {0} done'.format(node['host']))
176         return True
177 #pylint: enable=broad-except
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 SetupDPDKTest(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_dpdk_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         results = result.get()
223         node_setup_success = all(results)
224         logger.info('Results: {0}'.format(results))
225
226         logger.trace('Test framework copied to all topology nodes')
227         delete_local_tarball(tarball)
228         if node_setup_success:
229             logger.console('All nodes are ready')
230         else:
231             logger.console('Failed to setup dpdk on all the nodes')