Code rewrite and Python3 support
[samplevnf.git] / VNFs / DPPD-PROX / helper-scripts / rapid / rapid_machine.py
1 #!/usr/bin/python
2
3 ##
4 ## Copyright (c) 2010-2020 Intel Corporation
5 ##
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
9 ##
10 ##     http://www.apache.org/licenses/LICENSE-2.0
11 ##
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.
17 ##
18
19 from rapid_log import RapidLog 
20 from prox_ctrl import prox_ctrl
21 import re
22
23 class RapidMachine(object):
24     """
25     Class to deal with rapid configuration files
26     """
27     @staticmethod
28     def ip2hex(ip):
29         ip = ip.split('.')
30         return(hex(int(ip[0]))[2:].zfill(2) + ' ' + hex(int(ip[1]))[2:].zfill(2) + ' ' + hex(int(ip[2]))[2:].zfill(2) + ' ' + hex(int(ip[3]))[2:].zfill(2))
31
32     def __init__(self, key, user, vim, rundir, machine_params):
33         self.name = machine_params['name']
34         self.ip = machine_params['admin_ip']
35         self.key = key
36         self.user = user
37         self.rundir = rundir
38         self.dp_ports = []
39         self.dpdk_port_index = []
40         index = 1
41         while True:
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)
48                 index += 1
49             else:
50                 break
51         self.rundir = rundir
52         self.machine_params = machine_params
53         self._client = prox_ctrl(self.ip, self.key, self.user)
54         self._client.connect()
55         if vim in ['OpenStack']:
56             self.devbind()
57         self.generate_lua(vim)
58         self._client.scp_put(self.machine_params['config_file'], '{}/{}'.format(self.rundir, machine_params['config_file']))
59
60     def get_cores(self):
61         return (self.machine_params['cores'])
62
63     def devbind(self):
64         # Script to bind the right network interface to the poll mode driver
65         for index, dp_port in enumerate(self.dp_ports, start = 1):
66             DevBindFileName = self.rundir + '/devbind-{}-port{}.sh'.format(self.ip, index)
67             self._client.scp_put('./devbind.sh', DevBindFileName)
68             cmd =  'sed -i \'s/MACADDRESS/' + dp_port['mac'] + '/\' ' + DevBindFileName 
69             result = self._client.run_cmd(cmd)
70             RapidLog.debug('devbind.sh MAC updated for port {} on {} {}'.format(index, self.name, result))
71             result = self._client.run_cmd(DevBindFileName)
72             RapidLog.debug('devbind.sh running for port {} on {} {}'.format(index, self.name, result))
73
74     def generate_lua(self, vim, appendix = ''):
75         PROXConfigfile =  open (self.machine_params['config_file'], 'r')
76         PROXConfig = PROXConfigfile.read()
77         PROXConfigfile.close()
78         self.all_tasks_for_this_cfg = set(re.findall("task\s*=\s*(\d+)",PROXConfig))
79         self.LuaFileName = 'parameters-{}.lua'.format(self.ip)
80         with open(self.LuaFileName, "w") as LuaFile:
81             LuaFile.write('name="%s"\n'% self.name)
82             for index, dp_port in enumerate(self.dp_ports, start = 1):
83                 LuaFile.write('local_ip{}="{}"\n'.format(index, dp_port['ip']))
84                 LuaFile.write('local_hex_ip{}="{}"\n'.format(index, self.ip2hex(dp_port['ip'])))
85             if vim in ['kubernetes']:
86                 LuaFile.write("eal=\"--socket-mem=512,0 --file-prefix %s --pci-whitelist %s\"\n" % (self.name, self.machine_params['dp_pci_dev']))
87             else:
88                 LuaFile.write("eal=\"\"\n")
89             if 'cores' in self.machine_params.keys():
90                 LuaFile.write('cores="%s"\n'% ','.join(map(str, self.machine_params['cores'])))
91             if 'ports' in self.machine_params.keys():
92                 LuaFile.write('ports="%s"\n'% ','.join(map(str, self.machine_params['ports'])))
93             if 'dest_ports' in self.machine_params.keys():
94                 for index, dest_port in enumerate(self.machine_params['dest_ports'], start = 1):
95                     LuaFile.write('dest_ip{}="{}"\n'.format(index, dest_port['ip']))
96                     LuaFile.write('dest_hex_ip{}="{}"\n'.format(index, self.ip2hex(dest_port['ip'])))
97                     LuaFile.write('dest_hex_ip{}="{}"\n'.format(index, self.ip2hex(dest_port['ip'])))
98                     LuaFile.write('dest_hex_mac{}="{}"\n'.format(index , dest_port['mac'].replace(':',' ')))
99             LuaFile.write(appendix)
100         self._client.scp_put(self.LuaFileName, self.rundir + '/parameters.lua')
101
102     def start_prox(self, autostart=''):
103         if self.machine_params['prox_launch_exit']:
104             cmd = 'sudo {}/prox {} -t -o cli -f {}/{}'.format(self.rundir, autostart, self.rundir, self.machine_params['config_file'])
105             result = self._client.fork_cmd(cmd, 'PROX Testing on {}'.format(self.name))
106             RapidLog.debug("Starting PROX on {}: {}, {}".format(self.name, cmd, result))
107         self.socket = self._client.connect_socket()
108
109     def start(self):
110         self.socket.start(self.get_cores())
111
112     def stop(self):
113         self.socket.stop(self.get_cores())
114
115     def reset_stats(self):
116         self.socket.reset_stats()
117
118     def core_stats(self):
119         return (self.socket.core_stats(self.get_cores(), self.all_tasks_for_this_cfg))
120
121     def multi_port_stats(self):
122         return (self.socket.multi_port_stats(self.self.dpdk_port_index))