blob: c4e27d5d86f25e223f2f91d9865fe80342245c06 [file] [log] [blame]
Carmelo Casconeb7524272017-06-05 16:53:13 -04001import os
Carmelo Cascone977ae3f2016-06-23 19:28:28 -07002import socket
Carmelo Casconeb7524272017-06-05 16:53:13 -04003import re
4import json
Brian O'Connor71167f92017-06-16 14:55:00 -07005import urllib2
Carmelo Cascone977ae3f2016-06-23 19:28:28 -07006
Carmelo Casconeb7524272017-06-05 16:53:13 -04007from mininet.log import info, warn, error
Carmelo Cascone785fada2016-06-16 18:34:16 -07008from mininet.node import Switch
Carmelo Cascone785fada2016-06-16 18:34:16 -07009
Carmelo Casconeb7524272017-06-05 16:53:13 -040010if 'ONOS_ROOT' not in os.environ:
11 error("ERROR: environment var $ONOS_ROOT not set")
12 exit()
13
Carmelo Cascone75e97992017-06-05 02:32:47 -040014BMV2_TARGET = 'simple_switch_grpc'
Carmelo Casconeb7524272017-06-05 16:53:13 -040015ONOS_ROOT = os.environ["ONOS_ROOT"]
Carmelo Cascone569d4ad2017-07-10 16:09:00 -040016CPU_PORT = 255
Carmelo Casconeb7524272017-06-05 16:53:13 -040017
Carmelo Cascone785fada2016-06-16 18:34:16 -070018
19class ONOSBmv2Switch(Switch):
Carmelo Casconeb7524272017-06-05 16:53:13 -040020 """BMv2 software switch with gRPC server"""
Carmelo Cascone785fada2016-06-16 18:34:16 -070021
Carmelo Cascone785fada2016-06-16 18:34:16 -070022 deviceId = 0
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070023 instanceCount = 0
Carmelo Cascone785fada2016-06-16 18:34:16 -070024
Carmelo Casconefb76b042017-07-17 19:42:00 -040025 def __init__(self, name, json=None, debugger=False, loglevel="warn", elogger=False,
Yi Tseng7875cb72017-08-08 10:15:58 -070026 persistent=False, grpcPort=None, thriftPort=None, netcfg=True,
27 pipeconfId="", **kwargs):
Carmelo Cascone785fada2016-06-16 18:34:16 -070028 Switch.__init__(self, name, **kwargs)
Carmelo Casconeb7524272017-06-05 16:53:13 -040029 self.grpcPort = ONOSBmv2Switch.pickUnusedPort() if not grpcPort else grpcPort
Carmelo Casconeaaf6d982017-07-29 19:52:58 -040030 self.thriftPort = ONOSBmv2Switch.pickUnusedPort() if not thriftPort else thriftPort
Carmelo Cascone75e97992017-06-05 02:32:47 -040031 if self.dpid:
32 self.deviceId = int(self.dpid, 0 if 'x' in self.dpid else 16)
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070033 else:
Carmelo Cascone75e97992017-06-05 02:32:47 -040034 self.deviceId = ONOSBmv2Switch.deviceId
35 ONOSBmv2Switch.deviceId += 1
Carmelo Casconefb76b042017-07-17 19:42:00 -040036 self.json = json
Carmelo Cascone785fada2016-06-16 18:34:16 -070037 self.debugger = debugger
38 self.loglevel = loglevel
39 self.logfile = '/tmp/bmv2-%d.log' % self.deviceId
Carmelo Cascone785fada2016-06-16 18:34:16 -070040 self.elogger = elogger
41 self.persistent = persistent
Carmelo Casconeb7524272017-06-05 16:53:13 -040042 self.netcfg = netcfg
43 self.netcfgfile = '/tmp/bmv2-%d-netcfg.json' % self.deviceId
Yi Tseng7875cb72017-08-08 10:15:58 -070044 self.pipeconfId = pipeconfId
Carmelo Cascone785fada2016-06-16 18:34:16 -070045 if persistent:
46 self.exectoken = "/tmp/bmv2-%d-exec-token" % self.deviceId
47 self.cmd("touch %s" % self.exectoken)
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070048 # Store thrift port for future uses.
Carmelo Cascone75e97992017-06-05 02:32:47 -040049 self.cmd("echo %d > /tmp/bmv2-%d-grpc-port" % (self.grpcPort, self.deviceId))
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070050
Yi Tseng7875cb72017-08-08 10:15:58 -070051 if 'longitude' in kwargs:
52 self.longitude = kwargs['longitude']
53 else:
54 self.longitude = None
55
56 if 'latitude' in kwargs:
57 self.latitude = kwargs['latitude']
58 else:
59 self.latitude = None
60
61 self.onosDeviceId = "device:bmv2:%d" % self.deviceId
62
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070063 @classmethod
64 def pickUnusedPort(cls):
65 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
66 s.bind(('localhost', 0))
67 addr, port = s.getsockname()
68 s.close()
69 return port
Carmelo Cascone785fada2016-06-16 18:34:16 -070070
Carmelo Casconeb7524272017-06-05 16:53:13 -040071 def getSourceIp(self, dstIP):
72 """
73 Queries the Linux routing table to get the source IP that can talk with dstIP, and vice
74 versa.
75 """
76 ipRouteOut = self.cmd('ip route get %s' % dstIP)
77 r = re.search(r"src (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", ipRouteOut)
78 return r.group(1) if r else None
79
Yi Tseng7875cb72017-08-08 10:15:58 -070080 def getDeviceConfig(self, srcIP):
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +020081 portData = {}
82 portId = 1
83 for intfName in self.intfNames():
84 if intfName == 'lo':
85 continue
86 portData[str(portId)] = {
87 "number": portId,
88 "name": intfName,
89 "enabled": True,
90 "removed": False,
91 "type": "copper",
92 "speed": 10000
93 }
94 portId += 1
95
Yi Tseng7875cb72017-08-08 10:15:58 -070096 basicCfg = {
97 "driver": "bmv2"
98 }
99
100 if self.longitude and self.latitude:
101 basicCfg["longitude"] = self.longitude
102 basicCfg["latitude"] = self.latitude
103
104 cfgData = {
105 "generalprovider": {
106 "p4runtime": {
107 "ip": srcIP,
108 "port": self.grpcPort,
109 "deviceId": self.deviceId,
110 "deviceKeyId": "p4runtime:%s" % self.onosDeviceId
111 }
112 },
113 "piPipeconf": {
114 "piPipeconfId": self.pipeconfId
115 },
116 "basic": basicCfg,
117 "ports": portData
118 }
119
120 return cfgData
121
122 def doOnosNetcfg(self, controllerIP):
123 """
124 Notifies ONOS about the new device via Netcfg.
125 """
126 srcIP = self.getSourceIp(controllerIP)
127 if not srcIP:
128 warn("WARN: unable to get device IP address, won't do onos-netcfg")
129 return
130
Carmelo Casconea11279b2017-06-22 04:30:08 -0400131 cfgData = {
132 "devices": {
Yi Tseng7875cb72017-08-08 10:15:58 -0700133 self.onosDeviceId: self.getDeviceConfig(srcIP)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400134 }
Carmelo Casconea11279b2017-06-22 04:30:08 -0400135 }
Carmelo Casconeb7524272017-06-05 16:53:13 -0400136 with open(self.netcfgfile, 'w') as fp:
137 json.dump(cfgData, fp, indent=4)
Brian O'Connor71167f92017-06-16 14:55:00 -0700138 # Build netcfg URL
139 url = 'http://%s:8181/onos/v1/network/configuration/' % controllerIP
140 # Instantiate password manager for HTTP auth
141 pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
142 pm.add_password(None, url, os.environ['ONOS_WEB_USER'], os.environ['ONOS_WEB_PASS'])
143 urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm)))
144 # Push config data to controller
Carmelo Casconea11279b2017-06-22 04:30:08 -0400145 req = urllib2.Request(url, json.dumps(cfgData), {'Content-Type': 'application/json'})
146 try:
147 f = urllib2.urlopen(req)
148 print f.read()
149 f.close()
150 except urllib2.URLError as e:
151 warn("WARN: unable to push config to ONOS (%s)" % e.reason)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400152
Carmelo Cascone785fada2016-06-16 18:34:16 -0700153 def start(self, controllers):
Carmelo Cascone75e97992017-06-05 02:32:47 -0400154 args = [BMV2_TARGET, '--device-id %s' % str(self.deviceId)]
Carmelo Cascone785fada2016-06-16 18:34:16 -0700155 for port, intf in self.intfs.items():
156 if not intf.IP():
157 args.append('-i %d@%s' % (port, intf.name))
Carmelo Cascone785fada2016-06-16 18:34:16 -0700158 if self.elogger:
159 nanomsg = 'ipc:///tmp/bmv2-%d-log.ipc' % self.deviceId
160 args.append('--nanolog %s' % nanomsg)
161 if self.debugger:
162 args.append('--debugger')
Carmelo Casconefb76b042017-07-17 19:42:00 -0400163 args.append('--log-console')
Carmelo Cascone9e6621f2017-06-27 16:06:33 -0400164 args.append('-L%s' % self.loglevel)
Carmelo Casconeaaf6d982017-07-29 19:52:58 -0400165 args.append('--thrift-port %d' % self.thriftPort)
Carmelo Casconefb76b042017-07-17 19:42:00 -0400166 if not self.json:
167 args.append('--no-p4')
168 else:
169 args.append(self.json)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400170
171 # gRPC target-specific options.
Carmelo Cascone785fada2016-06-16 18:34:16 -0700172 args.append('--')
Carmelo Cascone569d4ad2017-07-10 16:09:00 -0400173 args.append('--cpu-port %d' % CPU_PORT)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400174 args.append('--grpc-server-addr 0.0.0.0:%d' % self.grpcPort)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700175
176 bmv2cmd = " ".join(args)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700177 info("\nStarting BMv2 target: %s\n" % bmv2cmd)
Carmelo Casconefb76b042017-07-17 19:42:00 -0400178
Carmelo Cascone785fada2016-06-16 18:34:16 -0700179 if self.persistent:
Carmelo Casconeb7524272017-06-05 16:53:13 -0400180 # Bash loop to re-exec the switch if it crashes.
Carmelo Casconefb76b042017-07-17 19:42:00 -0400181 bmv2cmd = "(while [ -e {} ]; do {} ; sleep 1; done;)".format(self.exectoken, bmv2cmd)
182
183 cmdStr = "{} > {} 2>&1 &".format(bmv2cmd, self.logfile)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700184
Carmelo Casconeb7524272017-06-05 16:53:13 -0400185 # Starts the switch.
186 out = self.cmd(cmdStr)
187 if out:
188 print out
189
190 if self.netcfg:
191 try: # onos.py
192 clist = controllers[0].nodes()
193 except AttributeError:
194 clist = controllers
195 assert len(clist) > 0
196 cip = clist[0].IP()
197 self.doOnosNetcfg(cip)
198
199 def stop(self, deleteIntfs=True):
200 """Terminate switch."""
Carmelo Cascone977ae3f2016-06-23 19:28:28 -0700201 self.cmd("rm -f /tmp/bmv2-%d-*" % self.deviceId)
Carmelo Casconefb76b042017-07-17 19:42:00 -0400202 self.cmd("rm -f /tmp/bmv2-%d.log*" % self.deviceId)
Carmelo Cascone75e97992017-06-05 02:32:47 -0400203 self.cmd('kill %' + BMV2_TARGET)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400204 Switch.stop(self, deleteIntfs)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700205
206
Carmelo Casconeb7524272017-06-05 16:53:13 -0400207# Exports for bin/mn
Carmelo Cascone785fada2016-06-16 18:34:16 -0700208switches = {'onosbmv2': ONOSBmv2Switch}