blob: c4ec15f7c6ce64d1135d0c0db297a41bfb9267ad [file] [log] [blame]
Carmelo Cascone44448a52018-06-25 23:36:57 +02001import json
Carmelo Cascone3c216fa2018-06-22 14:52:15 +02002import multiprocessing
Carmelo Casconeb7524272017-06-05 16:53:13 -04003import os
Carmelo Cascone44448a52018-06-25 23:36:57 +02004import random
Carmelo Casconeb7524272017-06-05 16:53:13 -04005import re
Carmelo Cascone44448a52018-06-25 23:36:57 +02006import socket
Carmelo Casconef11513d2018-01-16 00:31:14 -08007import threading
Carmelo Cascone46d360b2017-08-29 20:20:32 +02008import time
Carmelo Cascone44448a52018-06-25 23:36:57 +02009import urllib2
Carmelo Casconef11513d2018-01-16 00:31:14 -080010from contextlib import closing
Carmelo Cascone44448a52018-06-25 23:36:57 +020011from mininet.log import info, warn
Carmelo Cascone34433252017-08-25 20:27:18 +020012from mininet.node import Switch, Host
Carmelo Cascone785fada2016-06-16 18:34:16 -070013
Carmelo Casconef11513d2018-01-16 00:31:14 -080014SIMPLE_SWITCH_GRPC = 'simple_switch_grpc'
Carmelo Cascone34433252017-08-25 20:27:18 +020015PKT_BYTES_TO_DUMP = 80
Carmelo Cascone46d360b2017-08-29 20:20:32 +020016VALGRIND_PREFIX = 'valgrind --leak-check=yes'
Carmelo Casconef11513d2018-01-16 00:31:14 -080017SWITCH_START_TIMEOUT = 5 # seconds
18BMV2_LOG_LINES = 5
Carmelo Casconec2821332018-05-14 18:15:33 -070019BMV2_DEFAULT_DEVICE_ID = 0
Carmelo Casconef11513d2018-01-16 00:31:14 -080020
Carmelo Cascone46d360b2017-08-29 20:20:32 +020021
22def parseBoolean(value):
23 if value in ['1', 1, 'true', 'True']:
24 return True
25 else:
26 return False
Carmelo Cascone34433252017-08-25 20:27:18 +020027
28
Carmelo Casconef11513d2018-01-16 00:31:14 -080029def pickUnusedPort():
30 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31 s.bind(('localhost', 0))
32 addr, port = s.getsockname()
33 s.close()
34 return port
35
36
37def writeToFile(path, value):
38 with open(path, "w") as f:
39 f.write(str(value))
40
41
42def watchDog(sw):
43 while True:
Carmelo Cascone3c216fa2018-06-22 14:52:15 +020044 if ONOSBmv2Switch.mininet_exception == 1:
45 sw.killBmv2(log=False)
46 return
Carmelo Casconef11513d2018-01-16 00:31:14 -080047 if sw.stopped:
48 return
49 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
50 if s.connect_ex(('127.0.0.1', sw.grpcPort)) == 0:
51 time.sleep(1)
52 else:
Carmelo Casconedf32bea2018-06-19 17:45:54 +020053 warn("\n*** WARN: BMv2 instance %s died!\n" % sw.name)
Carmelo Casconef11513d2018-01-16 00:31:14 -080054 sw.printBmv2Log()
55 print ("-" * 80) + "\n"
56 return
57
58
Carmelo Cascone34433252017-08-25 20:27:18 +020059class ONOSHost(Host):
60 def __init__(self, name, inNamespace=True, **params):
61 Host.__init__(self, name, inNamespace=inNamespace, **params)
62
63 def config(self, **params):
64 r = super(Host, self).config(**params)
65 for off in ["rx", "tx", "sg"]:
Carmelo Casconef11513d2018-01-16 00:31:14 -080066 cmd = "/sbin/ethtool --offload %s %s off" \
Carmelo Cascone6ec8f8f2017-11-22 14:27:06 -080067 % (self.defaultIntf(), off)
Carmelo Cascone34433252017-08-25 20:27:18 +020068 self.cmd(cmd)
69 # disable IPv6
70 self.cmd("sysctl -w net.ipv6.conf.all.disable_ipv6=1")
71 self.cmd("sysctl -w net.ipv6.conf.default.disable_ipv6=1")
72 self.cmd("sysctl -w net.ipv6.conf.lo.disable_ipv6=1")
73 return r
Carmelo Casconeb7524272017-06-05 16:53:13 -040074
Carmelo Cascone785fada2016-06-16 18:34:16 -070075
76class ONOSBmv2Switch(Switch):
Carmelo Casconeb7524272017-06-05 16:53:13 -040077 """BMv2 software switch with gRPC server"""
Carmelo Cascone3c216fa2018-06-22 14:52:15 +020078 # Shared value used to notify to all instances of this class that a Mininet
79 # exception occurred. Mininet exception handling doesn't call the stop()
80 # method, so the mn process would hang after clean-up since Bmv2 would still
81 # be running.
82 mininet_exception = multiprocessing.Value('i', 0)
Carmelo Cascone785fada2016-06-16 18:34:16 -070083
Carmelo Casconef11513d2018-01-16 00:31:14 -080084 def __init__(self, name, json=None, debugger=False, loglevel="warn",
Carmelo Casconeeaa8b1d2018-04-11 14:12:17 -070085 elogger=False, grpcport=None, cpuport=255,
86 thriftport=None, netcfg=True, dryrun=False, pipeconf="",
87 pktdump=False, valgrind=False, gnmi=False,
Carmelo Cascone55965c62018-05-17 18:13:16 -070088 portcfg=True, onosdevid=None, **kwargs):
Carmelo Cascone785fada2016-06-16 18:34:16 -070089 Switch.__init__(self, name, **kwargs)
Carmelo Cascone3c216fa2018-06-22 14:52:15 +020090 self.grpcPort = grpcport
91 self.thriftPort = thriftport
Carmelo Casconeeaa8b1d2018-04-11 14:12:17 -070092 self.cpuPort = cpuport
Carmelo Casconefb76b042017-07-17 19:42:00 -040093 self.json = json
Carmelo Cascone46d360b2017-08-29 20:20:32 +020094 self.debugger = parseBoolean(debugger)
Carmelo Cascone785fada2016-06-16 18:34:16 -070095 self.loglevel = loglevel
Carmelo Casconef11513d2018-01-16 00:31:14 -080096 # Important: Mininet removes all /tmp/*.log files in case of exceptions.
97 # We want to be able to see the bmv2 log if anything goes wrong, hence
98 # avoid the .log extension.
Carmelo Casconec2821332018-05-14 18:15:33 -070099 self.logfile = '/tmp/bmv2-%s-log' % self.name
Carmelo Cascone46d360b2017-08-29 20:20:32 +0200100 self.elogger = parseBoolean(elogger)
101 self.pktdump = parseBoolean(pktdump)
Carmelo Cascone46d360b2017-08-29 20:20:32 +0200102 self.netcfg = parseBoolean(netcfg)
103 self.dryrun = parseBoolean(dryrun)
104 self.valgrind = parseBoolean(valgrind)
Carmelo Casconec2821332018-05-14 18:15:33 -0700105 self.netcfgfile = '/tmp/bmv2-%s-netcfg.json' % self.name
Carmelo Casconeeaa8b1d2018-04-11 14:12:17 -0700106 self.pipeconfId = pipeconf
107 self.injectPorts = parseBoolean(portcfg)
108 self.withGnmi = parseBoolean(gnmi)
Carmelo Casconef11513d2018-01-16 00:31:14 -0800109 self.longitude = kwargs['longitude'] if 'longitude' in kwargs else None
110 self.latitude = kwargs['latitude'] if 'latitude' in kwargs else None
Carmelo Cascone55965c62018-05-17 18:13:16 -0700111 if onosdevid is not None and len(onosdevid) > 0:
112 self.onosDeviceId = onosdevid
113 else:
114 self.onosDeviceId = "device:bmv2:%s" % self.name
Carmelo Casconef11513d2018-01-16 00:31:14 -0800115 self.logfd = None
116 self.bmv2popen = None
117 self.stopped = False
Yi Tseng7875cb72017-08-08 10:15:58 -0700118
Carmelo Casconef11513d2018-01-16 00:31:14 -0800119 # Remove files from previous executions
120 self.cleanupTmpFiles()
121
Carmelo Casconeb7524272017-06-05 16:53:13 -0400122 def getSourceIp(self, dstIP):
123 """
Carmelo Casconef11513d2018-01-16 00:31:14 -0800124 Queries the Linux routing table to get the source IP that can talk with
125 dstIP, and vice versa.
Carmelo Casconeb7524272017-06-05 16:53:13 -0400126 """
127 ipRouteOut = self.cmd('ip route get %s' % dstIP)
128 r = re.search(r"src (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", ipRouteOut)
129 return r.group(1) if r else None
130
Yi Tseng7875cb72017-08-08 10:15:58 -0700131 def getDeviceConfig(self, srcIP):
Carmelo Cascone2cad9ef2017-08-01 21:52:07 +0200132
Yi Tseng7875cb72017-08-08 10:15:58 -0700133 basicCfg = {
134 "driver": "bmv2"
135 }
136
137 if self.longitude and self.latitude:
138 basicCfg["longitude"] = self.longitude
139 basicCfg["latitude"] = self.latitude
140
141 cfgData = {
Carmelo Cascone34433252017-08-25 20:27:18 +0200142 "generalprovider": {
143 "p4runtime": {
144 "ip": srcIP,
145 "port": self.grpcPort,
Carmelo Casconec2821332018-05-14 18:15:33 -0700146 "deviceId": BMV2_DEFAULT_DEVICE_ID,
Carmelo Cascone34433252017-08-25 20:27:18 +0200147 "deviceKeyId": "p4runtime:%s" % self.onosDeviceId
148 }
149 },
150 "piPipeconf": {
151 "piPipeconfId": self.pipeconfId
152 },
Andrea Campanellabf9e5ce2017-12-06 14:26:36 +0100153 "basic": basicCfg
Yi Tseng7875cb72017-08-08 10:15:58 -0700154 }
155
Carmelo Cascone4f985cd2018-02-11 17:36:42 -0800156 if self.withGnmi:
157 cfgData["generalprovider"]["gnmi"] = {
158 "ip": srcIP,
159 "port": self.grpcPort
160 }
161
162 if self.injectPorts:
Andrea Campanellabf9e5ce2017-12-06 14:26:36 +0100163 portData = {}
164 portId = 1
165 for intfName in self.intfNames():
166 if intfName == 'lo':
167 continue
168 portData[str(portId)] = {
169 "number": portId,
170 "name": intfName,
171 "enabled": True,
172 "removed": False,
173 "type": "copper",
174 "speed": 10000
175 }
176 portId += 1
177
178 cfgData['ports'] = portData
179
Yi Tseng7875cb72017-08-08 10:15:58 -0700180 return cfgData
181
182 def doOnosNetcfg(self, controllerIP):
183 """
184 Notifies ONOS about the new device via Netcfg.
185 """
186 srcIP = self.getSourceIp(controllerIP)
187 if not srcIP:
Carmelo Casconef11513d2018-01-16 00:31:14 -0800188 warn("*** WARN: unable to get switch IP address, won't do netcfg\n")
Yi Tseng7875cb72017-08-08 10:15:58 -0700189 return
190
Carmelo Casconea11279b2017-06-22 04:30:08 -0400191 cfgData = {
192 "devices": {
Yi Tseng7875cb72017-08-08 10:15:58 -0700193 self.onosDeviceId: self.getDeviceConfig(srcIP)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400194 }
Carmelo Casconea11279b2017-06-22 04:30:08 -0400195 }
Carmelo Casconeb7524272017-06-05 16:53:13 -0400196 with open(self.netcfgfile, 'w') as fp:
197 json.dump(cfgData, fp, indent=4)
Carmelo Cascone46d360b2017-08-29 20:20:32 +0200198
199 if not self.netcfg:
200 # Do not push config to ONOS.
201 return
202
Brian O'Connor71167f92017-06-16 14:55:00 -0700203 # Build netcfg URL
204 url = 'http://%s:8181/onos/v1/network/configuration/' % controllerIP
205 # Instantiate password manager for HTTP auth
206 pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
Carmelo Casconef11513d2018-01-16 00:31:14 -0800207 pm.add_password(None, url,
208 os.environ['ONOS_WEB_USER'],
209 os.environ['ONOS_WEB_PASS'])
210 urllib2.install_opener(urllib2.build_opener(
211 urllib2.HTTPBasicAuthHandler(pm)))
Brian O'Connor71167f92017-06-16 14:55:00 -0700212 # Push config data to controller
Carmelo Casconef11513d2018-01-16 00:31:14 -0800213 req = urllib2.Request(url, json.dumps(cfgData),
214 {'Content-Type': 'application/json'})
Carmelo Casconea11279b2017-06-22 04:30:08 -0400215 try:
216 f = urllib2.urlopen(req)
217 print f.read()
218 f.close()
219 except urllib2.URLError as e:
Carmelo Casconef11513d2018-01-16 00:31:14 -0800220 warn("*** WARN: unable to push config to ONOS (%s)\n" % e.reason)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400221
Carmelo Cascone785fada2016-06-16 18:34:16 -0700222 def start(self, controllers):
Carmelo Casconef11513d2018-01-16 00:31:14 -0800223 bmv2Args = [SIMPLE_SWITCH_GRPC] + self.grpcTargetArgs()
224 if self.valgrind:
225 bmv2Args = VALGRIND_PREFIX.split() + bmv2Args
226
227 cmdString = " ".join(bmv2Args)
228
229 if self.dryrun:
230 info("\n*** DRY RUN (not executing bmv2)")
231
232 info("\nStarting BMv2 target: %s\n" % cmdString)
233
Carmelo Cascone3c216fa2018-06-22 14:52:15 +0200234 writeToFile("/tmp/bmv2-%s-grpc-port" % self.name, self.grpcPort)
235 writeToFile("/tmp/bmv2-%s-thrift-port" % self.name, self.thriftPort)
236
Carmelo Casconef11513d2018-01-16 00:31:14 -0800237 try:
238 if not self.dryrun:
239 # Start the switch
240 self.logfd = open(self.logfile, "w")
241 self.bmv2popen = self.popen(cmdString,
242 stdout=self.logfd,
243 stderr=self.logfd)
244 self.waitBmv2Start()
245 # We want to be notified if BMv2 dies...
246 threading.Thread(target=watchDog, args=[self]).start()
247
248 self.doOnosNetcfg(self.controllerIp(controllers))
Carmelo Cascone3c216fa2018-06-22 14:52:15 +0200249 except Exception:
250 ONOSBmv2Switch.mininet_exception = 1
Carmelo Casconef11513d2018-01-16 00:31:14 -0800251 self.killBmv2()
252 self.printBmv2Log()
Carmelo Cascone3c216fa2018-06-22 14:52:15 +0200253 raise
Carmelo Casconef11513d2018-01-16 00:31:14 -0800254
255 def grpcTargetArgs(self):
Carmelo Cascone3c216fa2018-06-22 14:52:15 +0200256 if self.grpcPort is None:
257 self.grpcPort = pickUnusedPort()
258 if self.thriftPort is None:
259 self.thriftPort = pickUnusedPort()
Carmelo Casconec2821332018-05-14 18:15:33 -0700260 args = ['--device-id %s' % str(BMV2_DEFAULT_DEVICE_ID)]
Carmelo Cascone785fada2016-06-16 18:34:16 -0700261 for port, intf in self.intfs.items():
262 if not intf.IP():
263 args.append('-i %d@%s' % (port, intf.name))
Carmelo Casconec2821332018-05-14 18:15:33 -0700264 args.append('--thrift-port %s' % self.thriftPort)
265 ntfaddr = 'ipc:///tmp/bmv2-%s-notifications.ipc' % self.name
266 args.append('--notifications-addr %s' % ntfaddr)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700267 if self.elogger:
Carmelo Casconec2821332018-05-14 18:15:33 -0700268 nanologaddr = 'ipc:///tmp/bmv2-%s-nanolog.ipc' % self.name
269 args.append('--nanolog %s' % nanologaddr)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700270 if self.debugger:
Carmelo Casconec2821332018-05-14 18:15:33 -0700271 dbgaddr = 'ipc:///tmp/bmv2-%s-debug.ipc' % self.name
272 args.append('--debugger-addr %s' % dbgaddr)
Carmelo Casconefb76b042017-07-17 19:42:00 -0400273 args.append('--log-console')
Carmelo Cascone34433252017-08-25 20:27:18 +0200274 if self.pktdump:
Carmelo Casconef11513d2018-01-16 00:31:14 -0800275 args.append('--pcap --dump-packet-data %s' % PKT_BYTES_TO_DUMP)
Carmelo Cascone9e6621f2017-06-27 16:06:33 -0400276 args.append('-L%s' % self.loglevel)
Carmelo Casconefb76b042017-07-17 19:42:00 -0400277 if not self.json:
278 args.append('--no-p4')
279 else:
280 args.append(self.json)
Carmelo Casconef11513d2018-01-16 00:31:14 -0800281 # gRPC target-specific options
Carmelo Cascone785fada2016-06-16 18:34:16 -0700282 args.append('--')
Carmelo Casconef11513d2018-01-16 00:31:14 -0800283 args.append('--cpu-port %s' % self.cpuPort)
284 args.append('--grpc-server-addr 0.0.0.0:%s' % self.grpcPort)
285 return args
Carmelo Cascone785fada2016-06-16 18:34:16 -0700286
Carmelo Casconef11513d2018-01-16 00:31:14 -0800287 def waitBmv2Start(self):
288 # Wait for switch to open gRPC port, before sending ONOS the netcfg.
289 # Include time-out just in case something hangs.
290 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
291 endtime = time.time() + SWITCH_START_TIMEOUT
292 while True:
293 result = sock.connect_ex(('127.0.0.1', self.grpcPort))
294 if result == 0:
295 # The port is open. Let's go! (Close socket first)
296 sock.close()
297 break
298 # Port is not open yet. If there is time, we wait a bit.
299 if endtime > time.time():
Carmelo Cascone3c216fa2018-06-22 14:52:15 +0200300 time.sleep(0.1)
Carmelo Casconef11513d2018-01-16 00:31:14 -0800301 else:
302 # Time's up.
303 raise Exception("Switch did not start before timeout")
Carmelo Casconefb76b042017-07-17 19:42:00 -0400304
Carmelo Casconef11513d2018-01-16 00:31:14 -0800305 def printBmv2Log(self):
306 if os.path.isfile(self.logfile):
307 print "-" * 80
Carmelo Casconec2821332018-05-14 18:15:33 -0700308 print "%s log (from %s):" % (self.name, self.logfile)
Carmelo Casconef11513d2018-01-16 00:31:14 -0800309 with open(self.logfile, 'r') as f:
310 lines = f.readlines()
311 if len(lines) > BMV2_LOG_LINES:
312 print "..."
313 for line in lines[-BMV2_LOG_LINES:]:
314 print line.rstrip()
Carmelo Casconefb76b042017-07-17 19:42:00 -0400315
Carmelo Casconef11513d2018-01-16 00:31:14 -0800316 @staticmethod
317 def controllerIp(controllers):
318 try:
319 # onos.py
Carmelo Cascone46d360b2017-08-29 20:20:32 +0200320 clist = controllers[0].nodes()
321 except AttributeError:
322 clist = controllers
323 assert len(clist) > 0
Carmelo Cascone44448a52018-06-25 23:36:57 +0200324 return random.choice(clist).IP()
Keesjan Karsten8539f082018-01-04 17:03:31 +0100325
Carmelo Casconef11513d2018-01-16 00:31:14 -0800326 def killBmv2(self, log=False):
327 if self.bmv2popen is not None:
328 self.bmv2popen.kill()
329 if self.logfd is not None:
330 if log:
331 self.logfd.write("*** PROCESS TERMINATED BY MININET ***\n")
332 self.logfd.close()
Keesjan Karsten8539f082018-01-04 17:03:31 +0100333
Carmelo Casconef11513d2018-01-16 00:31:14 -0800334 def cleanupTmpFiles(self):
Carmelo Casconec2821332018-05-14 18:15:33 -0700335 self.cmd("rm -f /tmp/bmv2-%s-*" % self.name)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400336
337 def stop(self, deleteIntfs=True):
338 """Terminate switch."""
Carmelo Casconef11513d2018-01-16 00:31:14 -0800339 self.stopped = True
340 self.killBmv2(log=True)
Carmelo Casconeb7524272017-06-05 16:53:13 -0400341 Switch.stop(self, deleteIntfs)
Carmelo Cascone785fada2016-06-16 18:34:16 -0700342
343
Carmelo Casconeb7524272017-06-05 16:53:13 -0400344# Exports for bin/mn
Carmelo Cascone785fada2016-06-16 18:34:16 -0700345switches = {'onosbmv2': ONOSBmv2Switch}
Carmelo Cascone34433252017-08-25 20:27:18 +0200346hosts = {'onoshost': ONOSHost}