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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
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.
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
25 from robot.api import logger
26 from robot.libraries.BuiltIn import BuiltIn
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
32 __all__ = ["SetupDPDKTest"]
35 def pack_framework_dir():
36 """Pack the testing WS into temp file, return its name."""
38 tmpfile = NamedTemporaryFile(suffix=".tgz", prefix="DPDK-testing-")
39 file_name = tmpfile.name
43 split("tar --exclude-vcs -zcf {0} .".format(file_name)),
44 stdout=PIPE, stderr=PIPE)
45 (stdout, stderr) = proc.communicate()
50 return_code = proc.wait()
52 raise Exception("Could not pack testing framework.")
57 def copy_tarball_to_node(tarball, node):
58 """Copy tarball file from local host to remote node.
60 :param tarball: Path to tarball to upload.
61 :param node: Dictionary created from topology.
66 logger.console('Copying tarball to {0}'.format(node['host']))
70 ssh.scp(tarball, "/tmp/")
73 def extract_tarball_at_node(tarball, node):
74 """Extract tarball at given node.
76 Extracts tarball using tar on given node to specific CSIT loocation.
78 :param tarball: Path to tarball to upload.
79 :param node: Dictionary created from topology.
84 logger.console('Extracting tarball to {0} on {1}'.format(
85 con.REMOTE_FW_DIR, node['host']))
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)
93 logger.error('Unpack error: {0}'.format(stderr))
94 raise Exception('Failed to unpack {0} at node {1}'.format(
95 tarball, node['host']))
98 def create_env_directory_at_node(node):
100 Create fresh virtualenv to a directory, install pip requirements.
102 :param node: Dictionary created from topology, will only install in the TG
106 logger.console('Extracting virtualenv, installing requirements.txt '
107 'on {0}'.format(node['host']))
110 (ret_code, stdout, stderr) = ssh.exec_command(
111 'cd {0} && rm -rf env && virtualenv env && '
112 '. env/bin/activate && pip install -r requirements.txt'
113 .format(con.REMOTE_FW_DIR), timeout=100)
115 logger.error('Virtualenv creation error: {0}'.format(stdout + stderr))
116 raise Exception('Virtualenv setup failed')
118 logger.console('Virtualenv created on {0}'.format(node['host']))
120 def install_dpdk_test(node):
122 Prepare the DPDK test envrionment
124 :param node: Dictionary created from topology
128 logger.console('Install the DPDK on {0}'.format(node['host']))
133 (ret_code, _, stderr) = ssh.exec_command(
134 'cd {0}/tests/dpdk/dpdk_scripts/ && ./install_dpdk.sh'
135 .format(con.REMOTE_FW_DIR), timeout=600)
138 logger.error('Install the DPDK error: {0}'.format(stderr))
139 raise Exception('Install the DPDK failed')
141 logger.console('Install the DPDK on {0} success!'.format(node['host']))
143 #pylint: disable=broad-except
144 def setup_node(args):
145 """Run all set-up methods for a node.
147 This method is used as map_async parameter. It receives tuple with all
148 parameters as passed to map_async function.
150 :param args: All parameters needed to setup one node.
152 :returns: True - success, False - error
155 tarball, remote_tarball, node = args
157 copy_tarball_to_node(tarball, node)
158 extract_tarball_at_node(remote_tarball, node)
159 if node['type'] == NodeType.DUT:
160 install_dpdk_test(node)
161 if node['type'] == NodeType.TG:
162 create_env_directory_at_node(node)
163 except Exception as exc:
164 logger.error("Node setup failed, error:'{0}'".format(exc.message))
167 logger.console('Setup of node {0} done'.format(node['host']))
170 def delete_local_tarball(tarball):
171 """Delete local tarball to prevent disk pollution.
173 :param tarball: Path to tarball to upload.
177 call(split('sh -c "rm {0} > /dev/null 2>&1"'.format(tarball)))
180 class SetupDPDKTest(object):
181 """Setup suite run on topology nodes.
183 Many VAT/CLI based tests need the scripts at remote hosts before executing
184 them. This class packs the whole testing directory and copies it over
185 to all nodes in topology under /tmp/
189 def setup_dpdk_test(nodes):
190 """Pack the whole directory and extract in temp on each node."""
192 tarball = pack_framework_dir()
193 msg = 'Framework packed to {0}'.format(tarball)
196 remote_tarball = "/tmp/{0}".format(basename(tarball))
198 # Turn off logging since we use multiprocessing
199 log_level = BuiltIn().set_log_level('NONE')
200 params = ((tarball, remote_tarball, node) for node in nodes.values())
201 pool = Pool(processes=len(nodes))
202 result = pool.map_async(setup_node, params)
207 BuiltIn().set_log_level(log_level)
210 'Executed node setups in parallel, waiting for processes to end')
213 logger.info('Results: {0}'.format(result.get()))
215 logger.trace('Test framework copied to all topology nodes')
216 delete_local_tarball(tarball)
217 logger.console('All nodes are ready')