4 ## Copyright (c) 2020 Intel Corporation
6 ## Licensed under the Apache License, Version 2.0 (the "License");
7 ## you may not use this file except in compliance with the License.
8 ## You may obtain a copy of the License at
10 ## http://www.apache.org/licenses/LICENSE-2.0
12 ## Unless required by applicable law or agreed to in writing, software
13 ## distributed under the License is distributed on an "AS IS" BASIS,
14 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 ## See the License for the specific language governing permissions and
16 ## limitations under the License.
19 from rapid_log import RapidLog
20 from prox_ctrl import prox_ctrl
24 class RapidMachine(object):
26 Class to deal with a PROX instance (VM, bare metal, container)
28 def __init__(self, key, user, password, vim, rundir, resultsdir,
29 machine_params, configonly):
30 self.name = machine_params['name']
31 self.ip = machine_params['admin_ip']
34 self.password = password
36 self.resultsdir = resultsdir
38 self.dpdk_port_index = []
39 self.configonly = configonly
42 ip_key = 'dp_ip{}'.format(index)
43 mac_key = 'dp_mac{}'.format(index)
44 if ip_key in machine_params.keys() and mac_key in machine_params.keys():
45 dp_port = {'ip': machine_params[ip_key], 'mac' : machine_params[mac_key]}
46 self.dp_ports.append(dict(dp_port))
47 self.dpdk_port_index.append(index - 1)
51 self.machine_params = machine_params
53 self.cpu_mapping = None
54 if 'config_file' in self.machine_params.keys():
55 PROXConfigfile = open (self.machine_params['config_file'], 'r')
56 PROXConfig = PROXConfigfile.read()
57 PROXConfigfile.close()
58 self.all_tasks_for_this_cfg = set(re.findall("task\s*=\s*(\d+)",PROXConfig))
61 return (self.machine_params['cores'])
63 def expand_list_format(self, list):
64 """Expand cpuset list format provided as comma-separated list of
65 numbers and ranges of numbers. For more information please see
66 https://man7.org/linux/man-pages/man7/cpuset.7.html
69 for num in list.split(','):
71 num_range = num.split('-')
72 list_expanded += range(int(num_range[0]), int(num_range[1]) + 1)
74 list_expanded.append(int(num))
77 def read_cpuset(self):
78 """Read list of cpus on which we allowed to execute
80 cmd = 'cat /sys/fs/cgroup/cpuset/cpuset.cpus'
81 cpuset_cpus = self._client.run_cmd(cmd).decode().rstrip()
82 RapidLog.debug('{} ({}): Allocated cpuset: {}'.format(self.name, self.ip, cpuset_cpus))
83 self.cpu_mapping = self.expand_list_format(cpuset_cpus)
84 RapidLog.debug('{} ({}): Expanded cpuset: {}'.format(self.name, self.ip, self.cpu_mapping))
86 # Log CPU core mapping for user information
88 for i in range(len(self.cpu_mapping)):
89 cpu_mapping_str = cpu_mapping_str + '[' + str(i) + '->' + str(self.cpu_mapping[i]) + '], '
90 cpu_mapping_str = cpu_mapping_str[:-2]
91 RapidLog.debug('{} ({}): CPU mapping: {}'.format(self.name, self.ip, cpu_mapping_str))
93 def remap_cpus(self, cpus):
94 """Convert relative cpu ids provided as function parameter to match
95 cpu ids from allocated list
99 cpus_remapped.append(self.cpu_mapping[cpu])
102 def remap_all_cpus(self):
103 """Convert relative cpu ids for different parameters (mcore, cores)
105 if self.cpu_mapping is None:
106 RapidLog.debug('{} ({}): cpu mapping is not defined! Please check the configuration!'.format(self.name, self.ip))
109 if 'mcore' in self.machine_params.keys():
110 cpus_remapped = self.remap_cpus(self.machine_params['mcore'])
111 RapidLog.debug('{} ({}): mcore {} remapped to {}'.format(self.name, self.ip, self.machine_params['mcore'], cpus_remapped))
112 self.machine_params['mcore'] = cpus_remapped
114 if 'cores' in self.machine_params.keys():
115 cpus_remapped = self.remap_cpus(self.machine_params['cores'])
116 RapidLog.debug('{} ({}): cores {} remapped to {}'.format(self.name, self.ip, self.machine_params['cores'], cpus_remapped))
117 self.machine_params['cores'] = cpus_remapped
120 # Script to bind the right network interface to the poll mode driver
121 for index, dp_port in enumerate(self.dp_ports, start = 1):
122 DevBindFileName = self.rundir + '/devbind-{}-port{}.sh'.format(self.ip, index)
123 self._client.scp_put('./devbind.sh', DevBindFileName)
124 cmd = 'sed -i \'s/MACADDRESS/' + dp_port['mac'] + '/\' ' + DevBindFileName
125 result = self._client.run_cmd(cmd)
126 RapidLog.debug('devbind.sh MAC updated for port {} on {} {}'.format(index, self.name, result))
127 if ((not self.configonly) and self.machine_params['prox_launch_exit']):
128 result = self._client.run_cmd(DevBindFileName)
129 RapidLog.debug('devbind.sh running for port {} on {} {}'.format(index, self.name, result))
131 def generate_lua(self, appendix = ''):
132 self.LuaFileName = 'parameters-{}.lua'.format(self.ip)
133 with open(self.LuaFileName, "w") as LuaFile:
134 LuaFile.write('require "helper"\n')
135 LuaFile.write('name="%s"\n'% self.name)
136 for index, dp_port in enumerate(self.dp_ports, start = 1):
137 LuaFile.write('local_ip{}="{}"\n'.format(index, dp_port['ip']))
138 LuaFile.write('local_hex_ip{}=convertIPToHex(local_ip{})\n'.format(index, index))
139 if self.vim in ['kubernetes']:
140 LuaFile.write("eal=\"--file-prefix %s --pci-whitelist %s\"\n" % (self.name, self.machine_params['dp_pci_dev']))
142 LuaFile.write("eal=\"\"\n")
143 if 'mcore' in self.machine_params.keys():
144 LuaFile.write('mcore="%s"\n'% ','.join(map(str, self.machine_params['mcore'])))
145 if 'cores' in self.machine_params.keys():
146 LuaFile.write('cores="%s"\n'% ','.join(map(str, self.machine_params['cores'])))
147 if 'ports' in self.machine_params.keys():
148 LuaFile.write('ports="%s"\n'% ','.join(map(str, self.machine_params['ports'])))
149 if 'dest_ports' in self.machine_params.keys():
150 for index, dest_port in enumerate(self.machine_params['dest_ports'], start = 1):
151 LuaFile.write('dest_ip{}="{}"\n'.format(index, dest_port['ip']))
152 LuaFile.write('dest_hex_ip{}=convertIPToHex(dest_ip{})\n'.format(index, index))
153 LuaFile.write('dest_hex_mac{}="{}"\n'.format(index , dest_port['mac'].replace(':',' ')))
154 if 'gw_vm' in self.machine_params.keys():
155 for index, gw_ip in enumerate(self.machine_params['gw_ips'],
157 LuaFile.write('gw_ip{}="{}"\n'.format(index, gw_ip))
158 LuaFile.write('gw_hex_ip{}=convertIPToHex(gw_ip{})\n'.
159 format(index, index))
160 LuaFile.write(appendix)
161 self._client.scp_put(self.LuaFileName, self.rundir + '/parameters.lua')
162 self._client.scp_put('helper.lua', self.rundir + '/helper.lua')
164 def start_prox(self, autostart=''):
165 if self.machine_params['prox_socket']:
166 self._client = prox_ctrl(self.ip, self.key, self.user,
168 self._client.test_connection()
169 if self.vim in ['OpenStack']:
171 if self.vim in ['kubernetes']:
173 self.remap_all_cpus()
174 _, prox_config_file_name = os.path.split(self.
175 machine_params['config_file'])
176 if self.machine_params['prox_launch_exit']:
178 self._client.scp_put(self.machine_params['config_file'], '{}/{}'.
179 format(self.rundir, prox_config_file_name))
180 if not self.configonly:
181 cmd = 'sudo {}/prox {} -t -o cli -f {}/{}'.format(self.rundir,
182 autostart, self.rundir, prox_config_file_name)
183 RapidLog.debug("Starting PROX on {}: {}".format(self.name,
185 result = self._client.run_cmd(cmd)
186 RapidLog.debug("Finished PROX on {}: {}".format(self.name,
189 def close_prox(self):
190 if (not self.configonly) and self.machine_params[
191 'prox_socket'] and self.machine_params['prox_launch_exit']:
192 self.socket.quit_prox()
193 self._client.scp_get('/prox.log', '{}/{}.prox.log'.format(
194 self.resultsdir, self.name))
196 def connect_prox(self):
197 if self.machine_params['prox_socket']:
198 self.socket = self._client.connect_socket()
201 self.socket.start(self.get_cores())
204 self.socket.stop(self.get_cores())
206 def reset_stats(self):
207 self.socket.reset_stats()
209 def core_stats(self):
210 return (self.socket.core_stats(self.get_cores(), self.all_tasks_for_this_cfg))
212 def multi_port_stats(self):
213 return (self.socket.multi_port_stats(self.dpdk_port_index))