blob: e23b11c23969b694eed556761611ba034e90f888 [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"]
Brian O'Connor71167f92017-06-16 14:55:00 -070016INIT_BMV2_JSON = '%s/tools/test/p4src/p4-16/p4c-out/empty.json' % ONOS_ROOT
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 Cascone75e97992017-06-05 02:32:47 -040025 def __init__(self, name, debugger=False, loglevel="warn", elogger=False, persistent=False,
Carmelo Casconeb7524272017-06-05 16:53:13 -040026 logflush=False, thriftPort=None, grpcPort=None, netcfg=True, **kwargs):
Carmelo Cascone785fada2016-06-16 18:34:16 -070027 Switch.__init__(self, name, **kwargs)
Carmelo Casconeb7524272017-06-05 16:53:13 -040028 self.thriftPort = ONOSBmv2Switch.pickUnusedPort() if not thriftPort else thriftPort
29 self.grpcPort = ONOSBmv2Switch.pickUnusedPort() if not grpcPort else grpcPort
Carmelo Cascone75e97992017-06-05 02:32:47 -040030 if self.dpid:
31 self.deviceId = int(self.dpid, 0 if 'x' in self.dpid else 16)
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070032 else:
Carmelo Cascone75e97992017-06-05 02:32:47 -040033 self.deviceId = ONOSBmv2Switch.deviceId
34 ONOSBmv2Switch.deviceId += 1
Carmelo Cascone785fada2016-06-16 18:34:16 -070035 self.debugger = debugger
36 self.loglevel = loglevel
37 self.logfile = '/tmp/bmv2-%d.log' % self.deviceId
Carmelo Cascone785fada2016-06-16 18:34:16 -070038 self.elogger = elogger
39 self.persistent = persistent
Carmelo Cascone75e97992017-06-05 02:32:47 -040040 self.logflush = logflush
Carmelo Casconeb7524272017-06-05 16:53:13 -040041 self.netcfg = netcfg
42 self.netcfgfile = '/tmp/bmv2-%d-netcfg.json' % self.deviceId
Carmelo Cascone785fada2016-06-16 18:34:16 -070043 if persistent:
44 self.exectoken = "/tmp/bmv2-%d-exec-token" % self.deviceId
45 self.cmd("touch %s" % self.exectoken)
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070046 # Store thrift port for future uses.
47 self.cmd("echo %d > /tmp/bmv2-%d-thrift-port" % (self.thriftPort, self.deviceId))
Carmelo Cascone75e97992017-06-05 02:32:47 -040048 self.cmd("echo %d > /tmp/bmv2-%d-grpc-port" % (self.grpcPort, self.deviceId))
Carmelo Cascone977ae3f2016-06-23 19:28:28 -070049
50 @classmethod
51 def pickUnusedPort(cls):
52 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
53 s.bind(('localhost', 0))
54 addr, port = s.getsockname()
55 s.close()
56 return port
Carmelo Cascone785fada2016-06-16 18:34:16 -070057
Carmelo Casconeb7524272017-06-05 16:53:13 -040058 def getSourceIp(self, dstIP):
59 """
60 Queries the Linux routing table to get the source IP that can talk with dstIP, and vice
61 versa.
62 """
63 ipRouteOut = self.cmd('ip route get %s' % dstIP)
64 r = re.search(r"src (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", ipRouteOut)
65 return r.group(1) if r else None
66
67 def doOnosNetcfg(self, controllerIP):
68 """
69 Notifies ONOS about the new device via Netcfg.
70 """
71 srcIP = self.getSourceIp(controllerIP)
72 if not srcIP:
73 warn("WARN: unable to get device IP address, won't do onos-netcfg")
74 return
Carmelo Casconea11279b2017-06-22 04:30:08 -040075 onosDeviceId = "bmv2:%s" % self.deviceId
76 cfgData = {
77 "devices": {
78 "device:%s" % onosDeviceId: {
79 "generalprovider": {
80 "p4runtime": {
81 "ip": srcIP,
82 "port": self.grpcPort,
83 "deviceKeyId": "p4runtime:%s" % onosDeviceId
84 }
85 },
86 "basic": {
87 "driver": "bmv2"
88 }
Carmelo Casconeb7524272017-06-05 16:53:13 -040089 }
90 }
Carmelo Casconea11279b2017-06-22 04:30:08 -040091 }
Carmelo Casconeb7524272017-06-05 16:53:13 -040092 with open(self.netcfgfile, 'w') as fp:
93 json.dump(cfgData, fp, indent=4)
Brian O'Connor71167f92017-06-16 14:55:00 -070094 # Build netcfg URL
95 url = 'http://%s:8181/onos/v1/network/configuration/' % controllerIP
96 # Instantiate password manager for HTTP auth
97 pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
98 pm.add_password(None, url, os.environ['ONOS_WEB_USER'], os.environ['ONOS_WEB_PASS'])
99 urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm)))
100 # Push config data to controller
Carmelo Casconea11279b2017-06-22 04:30:08 -0400101 req = urllib2.Request(url, json.dumps(cfgData), {'Content-Type': 'application/json'})
102 try:
103 f = urllib2.urlopen(req)
104 print f.read()
105 f.close()
106 except urllib2.URLError as e:
107 warn("WARN: unable to push config to ONOS (%s)" % e.reason)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400108
Carmelo Cascone785fada2016-06-16 18:34:16 -0700109 def start(self, controllers):
Carmelo Cascone75e97992017-06-05 02:32:47 -0400110 args = [BMV2_TARGET, '--device-id %s' % str(self.deviceId)]
Carmelo Cascone785fada2016-06-16 18:34:16 -0700111 for port, intf in self.intfs.items():
112 if not intf.IP():
113 args.append('-i %d@%s' % (port, intf.name))
114 if self.thriftPort:
115 args.append('--thrift-port %d' % self.thriftPort)
116 if self.elogger:
117 nanomsg = 'ipc:///tmp/bmv2-%d-log.ipc' % self.deviceId
118 args.append('--nanolog %s' % nanomsg)
119 if self.debugger:
120 args.append('--debugger')
Carmelo Cascone75e97992017-06-05 02:32:47 -0400121 args.append('--log-file %s -L%s' % (self.logfile, self.loglevel))
122 if self.logflush:
123 args.append('--log-flush')
Carmelo Casconeb7524272017-06-05 16:53:13 -0400124
125 args.append(INIT_BMV2_JSON)
126
127 # gRPC target-specific options.
Carmelo Cascone785fada2016-06-16 18:34:16 -0700128 args.append('--')
Carmelo Cascone75e97992017-06-05 02:32:47 -0400129 args.append('--enable-swap')
Carmelo Casconeb7524272017-06-05 16:53:13 -0400130 args.append('--grpc-server-addr 0.0.0.0:%d' % self.grpcPort)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700131
132 bmv2cmd = " ".join(args)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700133 info("\nStarting BMv2 target: %s\n" % bmv2cmd)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700134 if self.persistent:
Carmelo Casconeb7524272017-06-05 16:53:13 -0400135 # Bash loop to re-exec the switch if it crashes.
Carmelo Cascone785fada2016-06-16 18:34:16 -0700136 cmdStr = "(while [ -e {} ]; " \
137 "do {} ; " \
138 "sleep 1; " \
Carmelo Cascone75e97992017-06-05 02:32:47 -0400139 "done;) &".format(self.exectoken, bmv2cmd)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700140 else:
Carmelo Cascone75e97992017-06-05 02:32:47 -0400141 cmdStr = "{} &".format(bmv2cmd)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700142
Carmelo Casconeb7524272017-06-05 16:53:13 -0400143 # Starts the switch.
144 out = self.cmd(cmdStr)
145 if out:
146 print out
147
148 if self.netcfg:
149 try: # onos.py
150 clist = controllers[0].nodes()
151 except AttributeError:
152 clist = controllers
153 assert len(clist) > 0
154 cip = clist[0].IP()
155 self.doOnosNetcfg(cip)
156
157 def stop(self, deleteIntfs=True):
158 """Terminate switch."""
Carmelo Cascone977ae3f2016-06-23 19:28:28 -0700159 self.cmd("rm -f /tmp/bmv2-%d-*" % self.deviceId)
Carmelo Cascone75e97992017-06-05 02:32:47 -0400160 # wildcard end as BMv2 might create log files with .txt extension
161 self.cmd("rm -f /tmp/bmv2-%d.log*" % self.deviceId)
162 self.cmd('kill %' + BMV2_TARGET)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400163 Switch.stop(self, deleteIntfs)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700164
165
Carmelo Casconeb7524272017-06-05 16:53:13 -0400166# Exports for bin/mn
Carmelo Cascone785fada2016-06-16 18:34:16 -0700167switches = {'onosbmv2': ONOSBmv2Switch}