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, vim, rundir, resultsdir, machine_params,
30 self.name = machine_params['name']
31 self.ip = machine_params['admin_ip']
35 self.resultsdir = resultsdir
37 self.dpdk_port_index = []
38 self.configonly = configonly
41 ip_key = 'dp_ip{}'.format(index)
42 mac_key = 'dp_mac{}'.format(index)
43 if ip_key in machine_params.keys() and mac_key in machine_params.keys():
44 dp_port = {'ip': machine_params[ip_key], 'mac' : machine_params[mac_key]}
45 self.dp_ports.append(dict(dp_port))
46 self.dpdk_port_index.append(index - 1)
50 self.machine_params = machine_params
52 self.cpu_mapping = None
53 if 'config_file' in self.machine_params.keys():
54 PROXConfigfile = open (self.machine_params['config_file'], 'r')
55 PROXConfig = PROXConfigfile.read()
56 PROXConfigfile.close()
57 self.all_tasks_for_this_cfg = set(re.findall("task\s*=\s*(\d+)",PROXConfig))
60 if ((not self.configonly) and self.machine_params['prox_socket']):
61 self._client.scp_get('/prox.log', '{}/{}.prox.log'.format(
62 self.resultsdir, self.name))
65 return (self.machine_params['cores'])
67 def expand_cpuset(self, cpuset):
68 """Expand cpuset provided as comma-separated list of CPU numbers and
69 CPU ranges of numbers. For more information please see
70 https://man7.org/linux/man-pages/man7/cpuset.7.html
73 for cpu in cpuset.split(','):
75 cpu_range = cpu.split('-')
76 cpuset_expanded += range(int(cpu_range[0]), int(cpu_range[1]) + 1)
78 cpuset_expanded.append(int(cpu))
79 return cpuset_expanded
81 def read_cpuset(self):
82 """Read list of cpus on which we allowed to execute
84 cmd = 'cat /sys/fs/cgroup/cpuset/cpuset.cpus'
85 cpuset_cpus = self._client.run_cmd(cmd).decode().rstrip()
86 RapidLog.debug('{} ({}): Allocated cpuset: {}'.format(self.name, self.ip, cpuset_cpus))
87 self.cpu_mapping = self.expand_cpuset(cpuset_cpus)
88 RapidLog.debug('{} ({}): Expanded cpuset: {}'.format(self.name, self.ip, self.cpu_mapping))
90 # Log CPU core mapping for user information
92 for i in range(len(self.cpu_mapping)):
93 cpu_mapping_str = cpu_mapping_str + '[' + str(i) + '->' + str(self.cpu_mapping[i]) + '], '
94 cpu_mapping_str = cpu_mapping_str[:-2]
95 RapidLog.debug('{} ({}): CPU mapping: {}'.format(self.name, self.ip, cpu_mapping_str))
97 def remap_cpus(self, cpus):
98 """Convert relative cpu ids provided as function parameter to match
99 cpu ids from allocated list
103 cpus_remapped.append(self.cpu_mapping[cpu])
106 def remap_all_cpus(self):
107 """Convert relative cpu ids for different parameters (mcore, cores)
109 if self.cpu_mapping is None:
110 RapidLog.debug('{} ({}): cpu mapping is not defined! Please check the configuration!'.format(self.name, self.ip))
113 if 'mcore' in self.machine_params.keys():
114 cpus_remapped = self.remap_cpus(self.machine_params['mcore'])
115 RapidLog.debug('{} ({}): mcore {} remapped to {}'.format(self.name, self.ip, self.machine_params['mcore'], cpus_remapped))
116 self.machine_params['mcore'] = cpus_remapped
118 if 'cores' in self.machine_params.keys():
119 cpus_remapped = self.remap_cpus(self.machine_params['cores'])
120 RapidLog.debug('{} ({}): cores {} remapped to {}'.format(self.name, self.ip, self.machine_params['cores'], cpus_remapped))
121 self.machine_params['cores'] = cpus_remapped
124 # Script to bind the right network interface to the poll mode driver
125 for index, dp_port in enumerate(self.dp_ports, start = 1):
126 DevBindFileName = self.rundir + '/devbind-{}-port{}.sh'.format(self.ip, index)
127 self._client.scp_put('./devbind.sh', DevBindFileName)
128 cmd = 'sed -i \'s/MACADDRESS/' + dp_port['mac'] + '/\' ' + DevBindFileName
129 result = self._client.run_cmd(cmd)
130 RapidLog.debug('devbind.sh MAC updated for port {} on {} {}'.format(index, self.name, result))
131 if ((not self.configonly) and self.machine_params['prox_launch_exit']):
132 result = self._client.run_cmd(DevBindFileName)
133 RapidLog.debug('devbind.sh running for port {} on {} {}'.format(index, self.name, result))
135 def generate_lua(self, appendix = ''):
136 self.LuaFileName = 'parameters-{}.lua'.format(self.ip)
137 with open(self.LuaFileName, "w") as LuaFile:
138 LuaFile.write('require "helper"\n')
139 LuaFile.write('name="%s"\n'% self.name)
140 for index, dp_port in enumerate(self.dp_ports, start = 1):
141 LuaFile.write('local_ip{}="{}"\n'.format(index, dp_port['ip']))
142 LuaFile.write('local_hex_ip{}=convertIPToHex(local_ip{})\n'.format(index, index))
143 if self.vim in ['kubernetes']:
144 LuaFile.write("eal=\"--socket-mem=512,0 --file-prefix %s --pci-whitelist %s\"\n" % (self.name, self.machine_params['dp_pci_dev']))
146 LuaFile.write("eal=\"\"\n")
147 if 'mcore' in self.machine_params.keys():
148 LuaFile.write('mcore="%s"\n'% ','.join(map(str, self.machine_params['mcore'])))
149 if 'cores' in self.machine_params.keys():
150 LuaFile.write('cores="%s"\n'% ','.join(map(str, self.machine_params['cores'])))
151 if 'ports' in self.machine_params.keys():
152 LuaFile.write('ports="%s"\n'% ','.join(map(str, self.machine_params['ports'])))
153 if 'dest_ports' in self.machine_params.keys():
154 for index, dest_port in enumerate(self.machine_params['dest_ports'], start = 1):
155 LuaFile.write('dest_ip{}="{}"\n'.format(index, dest_port['ip']))
156 LuaFile.write('dest_hex_ip{}=convertIPToHex(dest_ip{})\n'.format(index, index))
157 LuaFile.write('dest_hex_mac{}="{}"\n'.format(index , dest_port['mac'].replace(':',' ')))
158 if 'gw_vm' in self.machine_params.keys():
159 for index, gw_ip in enumerate(self.machine_params['gw_ips'],
161 LuaFile.write('gw_ip{}="{}"\n'.format(index, gw_ip))
162 LuaFile.write('gw_hex_ip{}=convertIPToHex(gw_ip{})\n'.
163 format(index, index))
164 LuaFile.write(appendix)
165 self._client.scp_put(self.LuaFileName, self.rundir + '/parameters.lua')
166 self._client.scp_put('helper.lua', self.rundir + '/helper.lua')
168 def start_prox(self, autostart=''):
169 if self.machine_params['prox_socket']:
170 self._client = prox_ctrl(self.ip, self.key, self.user)
171 self._client.connect()
172 if self.vim in ['OpenStack']:
174 if self.vim in ['kubernetes']:
176 self.remap_all_cpus()
177 _, prox_config_file_name = os.path.split(self.machine_params['config_file'])
179 self._client.scp_put(self.machine_params['config_file'], '{}/{}'.format(self.rundir, prox_config_file_name))
180 if ((not self.configonly) and self.machine_params['prox_launch_exit']):
181 cmd = 'sudo {}/prox {} -t -o cli -f {}/{}'.format(self.rundir, autostart, self.rundir, prox_config_file_name)
182 RapidLog.debug("Starting PROX on {}: {}".format(self.name, cmd))
183 result = self._client.run_cmd(cmd, 'PROX Testing on {}'.format(self.name))
184 RapidLog.debug("Finished PROX on {}: {}".format(self.name, cmd))
186 def close_prox(self):
187 if (not self.configonly) and self.machine_params['prox_socket'] and self.machine_params['prox_launch_exit']:
188 self.socket.quit_prox()
190 def connect_prox(self):
191 if self.machine_params['prox_socket']:
192 self.socket = self._client.connect_socket()
195 self.socket.start(self.get_cores())
198 self.socket.stop(self.get_cores())
200 def reset_stats(self):
201 self.socket.reset_stats()
203 def core_stats(self):
204 return (self.socket.core_stats(self.get_cores(), self.all_tasks_for_this_cfg))
206 def multi_port_stats(self):
207 return (self.socket.multi_port_stats(self.dpdk_port_index))