blob: c0ed9106cdc58c0759960f378cc68b6744cc3d15 [file] [log] [blame]
Jonathan Hartce97e5b2016-04-19 01:41:31 -07001#!/usr/bin/python
2
3"""
4Libraries for creating L3 topologies with routing protocols.
5"""
6
7from mininet.node import Host, OVSBridge
8from mininet.nodelib import NAT
9from mininet.log import info, debug, error
10from mininet.cli import CLI
11from ipaddress import ip_network, ip_address, ip_interface
Jonathan Hartd5d80872017-01-16 13:55:41 -080012import os
Jonathan Hartce97e5b2016-04-19 01:41:31 -070013
14class RoutedHost(Host):
15 """Host that can be configured with multiple IP addresses."""
16 def __init__(self, name, ips, gateway, *args, **kwargs):
17 super(RoutedHost, self).__init__(name, *args, **kwargs)
18
19 self.ips = ips
20 self.gateway = gateway
21
22 def config(self, **kwargs):
23 Host.config(self, **kwargs)
24
Charles Chan76128b62017-03-27 20:28:14 -070025 self.cmd('ip -4 addr flush dev %s' % self.defaultIntf())
Jonathan Hartce97e5b2016-04-19 01:41:31 -070026 for ip in self.ips:
27 self.cmd('ip addr add %s dev %s' % (ip, self.defaultIntf()))
28
29 self.cmd('ip route add default via %s' % self.gateway)
30
Yi Tseng45ee6922017-07-17 14:49:17 -070031class RoutedHost6(Host):
32 """Host that can be configured with multiple IP addresses."""
33 def __init__(self, name, ips, gateway, *args, **kwargs):
34 super(RoutedHost6, self).__init__(name, *args, **kwargs)
35
36 self.ips = ips
37 self.gateway = gateway
38
39 def config(self, **kwargs):
40 Host.config(self, **kwargs)
41
42 self.cmd('ip -6 addr flush dev %s' % self.defaultIntf())
43 for ip in self.ips:
44 self.cmd('ip -6 addr add %s dev %s' % (ip, self.defaultIntf()))
45
46 self.cmd('ip -6 route add default via %s' % self.gateway)
47
Jonathan Hartce97e5b2016-04-19 01:41:31 -070048class Router(Host):
Charles Chan76128b62017-03-27 20:28:14 -070049
Jonathan Hartce97e5b2016-04-19 01:41:31 -070050 """An L3 router.
51 Configures the Linux kernel for L3 forwarding and supports rich interface
52 configuration of IP addresses, MAC addresses and VLANs."""
Charles Chan76128b62017-03-27 20:28:14 -070053
Jonathan Hartce97e5b2016-04-19 01:41:31 -070054 def __init__(self, name, interfaces, *args, **kwargs):
55 super(Router, self).__init__(name, **kwargs)
56
57 self.interfaces = interfaces
Charles Chan76128b62017-03-27 20:28:14 -070058
Jonathan Hartce97e5b2016-04-19 01:41:31 -070059 def config(self, **kwargs):
60 super(Host, self).config(**kwargs)
Charles Chan76128b62017-03-27 20:28:14 -070061
Jonathan Hartce97e5b2016-04-19 01:41:31 -070062 self.cmd('sysctl net.ipv4.ip_forward=1')
63 self.cmd('sysctl net.ipv4.conf.all.rp_filter=0')
Charles Chan76128b62017-03-27 20:28:14 -070064 self.cmd('sysctl net.ipv6.conf.all.forwarding=1')
Jonathan Hartce97e5b2016-04-19 01:41:31 -070065
66 for intf, configs in self.interfaces.items():
Charles Chan76128b62017-03-27 20:28:14 -070067 self.cmd('ip -4 addr flush dev %s' % intf)
Jonathan Hartce97e5b2016-04-19 01:41:31 -070068 self.cmd( 'sysctl net.ipv4.conf.%s.rp_filter=0' % intf )
Charles Chan76128b62017-03-27 20:28:14 -070069
Jonathan Hartce97e5b2016-04-19 01:41:31 -070070 if not isinstance(configs, list):
71 configs = [configs]
Charles Chan76128b62017-03-27 20:28:14 -070072
Jonathan Hartce97e5b2016-04-19 01:41:31 -070073 for attrs in configs:
Charles Chan76128b62017-03-27 20:28:14 -070074 # Configure the vlan if there is one
Jonathan Hartce97e5b2016-04-19 01:41:31 -070075 if 'vlan' in attrs:
76 vlanName = '%s.%s' % (intf, attrs['vlan'])
Charles Chan76128b62017-03-27 20:28:14 -070077 self.cmd('ip link add link %s name %s type vlan id %s' %
Jonathan Hartce97e5b2016-04-19 01:41:31 -070078 (intf, vlanName, attrs['vlan']))
79 self.cmd('ip link set %s up' % vlanName)
80 addrIntf = vlanName
81 else:
82 addrIntf = intf
Charles Chan76128b62017-03-27 20:28:14 -070083
Jonathan Hartce97e5b2016-04-19 01:41:31 -070084 # Now configure the addresses on the vlan/native interface
85 if 'mac' in attrs:
86 self.cmd('ip link set %s down' % addrIntf)
87 self.cmd('ip link set %s address %s' % (addrIntf, attrs['mac']))
88 self.cmd('ip link set %s up' % addrIntf)
89 for addr in attrs['ipAddrs']:
90 self.cmd('ip addr add %s dev %s' % (addr, addrIntf))
91
92class QuaggaRouter(Router):
Charles Chan76128b62017-03-27 20:28:14 -070093
Jonathan Hartce97e5b2016-04-19 01:41:31 -070094 """Runs Quagga to create a router that can speak routing protocols."""
Charles Chan76128b62017-03-27 20:28:14 -070095
Jonathan Hartce97e5b2016-04-19 01:41:31 -070096 binDir = '/usr/lib/quagga'
Jonathan Hartd5d80872017-01-16 13:55:41 -080097 logDir = '/var/log/quagga'
Charles Chan76128b62017-03-27 20:28:14 -070098
Jonathan Hartce97e5b2016-04-19 01:41:31 -070099 def __init__(self, name, interfaces,
100 defaultRoute=None,
101 zebraConfFile=None,
102 protocols=[],
103 fpm=None,
104 runDir='/var/run/quagga', *args, **kwargs):
105 super(QuaggaRouter, self).__init__(name, interfaces, **kwargs)
Charles Chan76128b62017-03-27 20:28:14 -0700106
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700107 self.protocols = protocols
108 self.fpm = fpm
Charles Chan76128b62017-03-27 20:28:14 -0700109
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700110 for p in self.protocols:
111 p.setQuaggaRouter(self)
Charles Chan76128b62017-03-27 20:28:14 -0700112
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700113 self.runDir = runDir
114 self.defaultRoute = defaultRoute
Charles Chan76128b62017-03-27 20:28:14 -0700115
Jonathan Hartd5d80872017-01-16 13:55:41 -0800116 # Ensure required directories exist
117 try:
118 original_umask = os.umask(0)
119 if (not os.path.isdir(QuaggaRouter.logDir)):
120 os.makedirs(QuaggaRouter.logDir, 0777)
121 if (not os.path.isdir(self.runDir)):
122 os.makedirs(self.runDir, 0777)
123 finally:
124 os.umask(original_umask)
125
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700126 self.zebraConfFile = zebraConfFile
127 if (self.zebraConfFile is None):
128 self.zebraConfFile = '%s/zebrad%s.conf' % (self.runDir, self.name)
129 self.generateZebra()
Charles Chan76128b62017-03-27 20:28:14 -0700130
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700131 self.socket = '%s/zebra%s.api' % (self.runDir, self.name)
Charles Chan76128b62017-03-27 20:28:14 -0700132
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700133 self.zebraPidFile = '%s/zebra%s.pid' % (self.runDir, self.name)
134
135 def generateZebra(self):
136 configFile = open(self.zebraConfFile, 'w+')
Jonathan Hartd5d80872017-01-16 13:55:41 -0800137 configFile.write('log file %s/zebrad%s.log\n' % (QuaggaRouter.logDir, self.name))
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700138 configFile.write('hostname zebra-%s\n' % self.name)
Jonathan Harte6b897f2017-01-24 17:09:58 -0800139 configFile.write('password %s\n' % 'quagga')
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700140 if (self.fpm is not None):
141 configFile.write('fpm connection ip %s port 2620' % self.fpm)
142 configFile.close()
143
144 def config(self, **kwargs):
145 super(QuaggaRouter, self).config(**kwargs)
146
147 self.cmd('%s/zebra -d -f %s -z %s -i %s'
148 % (QuaggaRouter.binDir, self.zebraConfFile, self.socket, self.zebraPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700149
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700150 for p in self.protocols:
151 p.config(**kwargs)
Charles Chan76128b62017-03-27 20:28:14 -0700152
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700153 if self.defaultRoute:
154 self.cmd('ip route add default via %s' % self.defaultRoute)
Charles Chan76128b62017-03-27 20:28:14 -0700155
Charles Chane7e8cdb2019-10-22 23:38:39 -0700156 for interface in self.interfaces:
157 disable_offload(self, interface)
158
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700159 def terminate(self, **kwargs):
Charles Chan76128b62017-03-27 20:28:14 -0700160 self.cmd("ps ax | grep '%s' | awk '{print $1}' | xargs kill"
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700161 % (self.socket))
Charles Chan76128b62017-03-27 20:28:14 -0700162
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700163 for p in self.protocols:
164 p.terminate(**kwargs)
165
166 super(QuaggaRouter, self).terminate()
Charles Chan76128b62017-03-27 20:28:14 -0700167
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700168class Protocol(object):
Charles Chan76128b62017-03-27 20:28:14 -0700169
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700170 """Base abstraction of a protocol that the QuaggaRouter can run."""
Charles Chan76128b62017-03-27 20:28:14 -0700171
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700172 def setQuaggaRouter(self, qr):
173 self.qr = qr
Charles Chan76128b62017-03-27 20:28:14 -0700174
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700175 def config(self, **kwargs):
176 pass
Charles Chan76128b62017-03-27 20:28:14 -0700177
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700178 def terminate(self, **kwargs):
179 pass
Charles Chan76128b62017-03-27 20:28:14 -0700180
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700181class BgpProtocol(Protocol):
Charles Chan76128b62017-03-27 20:28:14 -0700182
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700183 """Configures and runs the BGP protocol in Quagga."""
Charles Chan76128b62017-03-27 20:28:14 -0700184
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700185 def __init__(self, configFile=None, asNum=None, neighbors=[], routes=[], *args, **kwargs):
186 self.configFile = configFile
Charles Chan76128b62017-03-27 20:28:14 -0700187
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700188 self.asNum = asNum
189 self.neighbors = neighbors
190 self.routes = routes
Charles Chan76128b62017-03-27 20:28:14 -0700191
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700192 def config(self, **kwargs):
193 if self.configFile is None:
194 self.configFile = '%s/bgpd%s.conf' % (self.qr.runDir, self.qr.name)
195 self.generateConfig()
Charles Chan76128b62017-03-27 20:28:14 -0700196
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700197 bgpdPidFile = '%s/bgpd%s.pid' % (self.qr.runDir, self.qr.name)
Charles Chan76128b62017-03-27 20:28:14 -0700198
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700199 self.qr.cmd('%s/bgpd -d -f %s -z %s -i %s'
200 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, bgpdPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700201
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700202 def generateConfig(self):
203 conf = ConfigurationWriter(self.configFile)
Charles Chan76128b62017-03-27 20:28:14 -0700204
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700205 def getRouterId(interfaces):
206 intfAttributes = interfaces.itervalues().next()
207 print intfAttributes
208 if isinstance(intfAttributes, list):
209 # Try use the first set of attributes, but if using vlans they might not have addresses
210 intfAttributes = intfAttributes[1] if not intfAttributes[0]['ipAddrs'] else intfAttributes[0]
211 return intfAttributes['ipAddrs'][0].split('/')[0]
Charles Chan76128b62017-03-27 20:28:14 -0700212
Jonathan Hartd5d80872017-01-16 13:55:41 -0800213 conf.writeLine('log file %s/bgpd%s.log' % (QuaggaRouter.logDir, self.qr.name))
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700214 conf.writeLine('hostname bgp-%s' % self.qr.name);
Jonathan Harte6b897f2017-01-24 17:09:58 -0800215 conf.writeLine('password %s' % 'quagga')
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700216 conf.writeLine('!')
217 conf.writeLine('router bgp %s' % self.asNum)
Charles Chan76128b62017-03-27 20:28:14 -0700218
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700219 conf.indent()
Charles Chan76128b62017-03-27 20:28:14 -0700220
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700221 conf.writeLine('bgp router-id %s' % getRouterId(self.qr.interfaces))
222 conf.writeLine('timers bgp %s' % '3 9')
223 conf.writeLine('!')
Charles Chan76128b62017-03-27 20:28:14 -0700224
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700225 for neighbor in self.neighbors:
226 conf.writeLine('neighbor %s remote-as %s' % (neighbor['address'], neighbor['as']))
227 conf.writeLine('neighbor %s ebgp-multihop' % neighbor['address'])
228 conf.writeLine('neighbor %s timers connect %s' % (neighbor['address'], '5'))
229 conf.writeLine('neighbor %s advertisement-interval %s' % (neighbor['address'], '5'))
230 if 'port' in neighbor:
231 conf.writeLine('neighbor %s port %s' % (neighbor['address'], neighbor['port']))
232 conf.writeLine('!')
Charles Chan76128b62017-03-27 20:28:14 -0700233
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700234 for route in self.routes:
235 conf.writeLine('network %s' % route)
Charles Chan76128b62017-03-27 20:28:14 -0700236
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700237 conf.close()
Charles Chan76128b62017-03-27 20:28:14 -0700238
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700239class OspfProtocol(Protocol):
Charles Chan76128b62017-03-27 20:28:14 -0700240
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700241 """Configures and runs the OSPF protocol in Quagga."""
Charles Chan76128b62017-03-27 20:28:14 -0700242
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700243 def __init__(self, configFile=None, *args, **kwargs):
244 self.configFile = configFile
Charles Chan76128b62017-03-27 20:28:14 -0700245
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700246 def config(self, **kwargs):
247 if self.configFile is None:
248 self.configFile = '%s/ospfd%s.conf' % (self.qr.runDir, self.qr.name)
249 self.generateConfig()
Charles Chan76128b62017-03-27 20:28:14 -0700250
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700251 ospfPidFile = '%s/ospf%s.pid' % (self.qr.runDir, self.qr.name)
Charles Chan76128b62017-03-27 20:28:14 -0700252
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700253 self.qr.cmd('%s/ospfd -d -f %s -z %s -i %s'
254 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, ospfPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700255
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700256 def generateConfig(self):
257 conf = ConfigurationWriter(self.configFile)
Charles Chan76128b62017-03-27 20:28:14 -0700258
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700259 def getRouterId(interfaces):
260 intfAttributes = interfaces.itervalues().next()
261 print intfAttributes
262 if isinstance(intfAttributes, list):
263 # Try use the first set of attributes, but if using vlans they might not have addresses
264 intfAttributes = intfAttributes[1] if not intfAttributes[0]['ipAddrs'] else intfAttributes[0]
265 return intfAttributes['ipAddrs'][0].split('/')[0]
Charles Chan76128b62017-03-27 20:28:14 -0700266
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700267 conf.writeLine('hostname ospf-%s' % self.qr.name);
268 conf.writeLine('password %s' % 'hello')
269 conf.writeLine('!')
270 conf.writeLine('router ospf')
Charles Chan76128b62017-03-27 20:28:14 -0700271
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700272 conf.indent()
Charles Chan76128b62017-03-27 20:28:14 -0700273
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700274 conf.writeLine('ospf router-id %s' % getRouterId(self.qr.interfaces))
275 conf.writeLine('!')
Charles Chan76128b62017-03-27 20:28:14 -0700276
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700277 for name, intf in self.qr.interfaces.items():
278 for ip in intf['ipAddrs']:
279 conf.writeLine('network %s area 0' % ip)
280 #if intf['ipAddrs'][0].startswith('192.168'):
281 # writeLine(1, 'passive-interface %s' % name)
Charles Chan76128b62017-03-27 20:28:14 -0700282
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700283 conf.close()
Charles Chan76128b62017-03-27 20:28:14 -0700284
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700285class PimProtocol(Protocol):
Charles Chan76128b62017-03-27 20:28:14 -0700286
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700287 """Configures and runs the PIM protcol in Quagga."""
Charles Chan76128b62017-03-27 20:28:14 -0700288
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700289 def __init__(self, configFile=None, *args, **kwargs):
290 self.configFile = configFile
Charles Chan76128b62017-03-27 20:28:14 -0700291
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700292 def config(self, **kwargs):
293 pimPidFile = '%s/pim%s.pid' % (self.qr.runDir, self.qr.name)
Charles Chan76128b62017-03-27 20:28:14 -0700294
Jonathan Hart09608592016-05-19 09:39:22 -0700295 self.qr.cmd('%s/pimd -Z -d -f %s -z %s -i %s'
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700296 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, pimPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700297
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700298class ConfigurationWriter(object):
Charles Chan76128b62017-03-27 20:28:14 -0700299
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700300 """Utility class for writing a configuration file."""
Charles Chan76128b62017-03-27 20:28:14 -0700301
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700302 def __init__(self, filename):
303 self.filename = filename
304 self.indentValue = 0;
Charles Chan76128b62017-03-27 20:28:14 -0700305
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700306 self.configFile = open(self.filename, 'w+')
Charles Chan76128b62017-03-27 20:28:14 -0700307
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700308 def indent(self):
309 self.indentValue += 1
Charles Chan76128b62017-03-27 20:28:14 -0700310
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700311 def unindent(self):
312 if (self.indentValue > 0):
313 self.indentValue -= 1
Charles Chan76128b62017-03-27 20:28:14 -0700314
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700315 def write(self, string):
316 self.configFile.write(string)
Charles Chan76128b62017-03-27 20:28:14 -0700317
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700318 def writeLine(self, string):
319 intentStr = ''
320 for _ in range(0, self.indentValue):
321 intentStr += ' '
322 self.write('%s%s\n' % (intentStr, string))
Charles Chan76128b62017-03-27 20:28:14 -0700323
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700324 def close(self):
325 self.configFile.close()
326
327#Backward compatibility for BGP-only use case
328class BgpRouter(QuaggaRouter):
Charles Chan76128b62017-03-27 20:28:14 -0700329
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700330 """Quagga router running the BGP protocol."""
Charles Chan76128b62017-03-27 20:28:14 -0700331
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700332 def __init__(self, name, interfaces,
Charles Chandfa13bd2017-03-24 21:40:10 -0700333 asNum=0, neighbors=[], routes=[],
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700334 defaultRoute=None,
335 quaggaConfFile=None,
336 zebraConfFile=None,
337 *args, **kwargs):
338 bgp = BgpProtocol(configFile=quaggaConfFile, asNum=asNum, neighbors=neighbors, routes=routes)
Charles Chan76128b62017-03-27 20:28:14 -0700339
340 super(BgpRouter, self).__init__(name, interfaces,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700341 zebraConfFile=zebraConfFile,
342 defaultRoute=defaultRoute,
343 protocols=[bgp],
344 *args, **kwargs)
Charles Chane7e8cdb2019-10-22 23:38:39 -0700345 def config(self, **kwargs):
346 super(BgpRouter, self).config(**kwargs)
Charles Chan76128b62017-03-27 20:28:14 -0700347
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700348class RouterData(object):
Charles Chan76128b62017-03-27 20:28:14 -0700349
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700350 """Internal data structure storing information about a router."""
Charles Chan76128b62017-03-27 20:28:14 -0700351
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700352 def __init__(self, index):
353 self.index = index;
354 self.neighbors = []
355 self.interfaces = {}
356 self.switches = []
Charles Chan76128b62017-03-27 20:28:14 -0700357
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700358 def addNeighbor(self, theirAddress, theirAsNum):
359 self.neighbors.append({'address':theirAddress.ip, 'as':theirAsNum})
Charles Chan76128b62017-03-27 20:28:14 -0700360
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700361 def addInterface(self, intf, vlan, address):
362 if not intf in self.interfaces:
363 self.interfaces[intf] = InterfaceData(intf)
Charles Chan76128b62017-03-27 20:28:14 -0700364
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700365 self.interfaces[intf].addAddress(vlan, address)
Charles Chan76128b62017-03-27 20:28:14 -0700366
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700367 def setSwitch(self, switch):
368 self.switches.append(switch)
Charles Chan76128b62017-03-27 20:28:14 -0700369
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700370class InterfaceData(object):
Charles Chan76128b62017-03-27 20:28:14 -0700371
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700372 """Internal data structure storing information about an interface."""
Charles Chan76128b62017-03-27 20:28:14 -0700373
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700374 def __init__(self, number):
375 self.number = number
376 self.addressesByVlan = {}
Charles Chan76128b62017-03-27 20:28:14 -0700377
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700378 def addAddress(self, vlan, address):
379 if not vlan in self.addressesByVlan:
380 self.addressesByVlan[vlan] = []
Charles Chan76128b62017-03-27 20:28:14 -0700381
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700382 self.addressesByVlan[vlan].append(address.with_prefixlen)
Charles Chan76128b62017-03-27 20:28:14 -0700383
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700384class RoutedNetwork(object):
Charles Chan76128b62017-03-27 20:28:14 -0700385
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700386 """Creates a host behind a router. This is common boilerplate topology
387 segment in routed networks."""
Charles Chan76128b62017-03-27 20:28:14 -0700388
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700389 @staticmethod
390 def build(topology, router, hostName, networks):
391 # There's a convention that the router's addresses are already set up,
392 # and it has the last address in the network.
Charles Chan76128b62017-03-27 20:28:14 -0700393
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700394 def getFirstAddress(network):
395 return '%s/%s' % (network[1], network.prefixlen)
Charles Chan76128b62017-03-27 20:28:14 -0700396
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700397 defaultRoute = AutonomousSystem.getLastAddress(networks[0]).ip
Charles Chan76128b62017-03-27 20:28:14 -0700398
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700399 host = topology.addHost(hostName, cls=RoutedHost,
400 ips=[getFirstAddress(network) for network in networks],
401 gateway=defaultRoute)
402
403 topology.addLink(router, host)
404
405class AutonomousSystem(object):
Charles Chan76128b62017-03-27 20:28:14 -0700406
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700407 """Base abstraction of an autonomous system, which implies some internal
408 topology and connections to other topology elements (switches/other ASes)."""
Charles Chan76128b62017-03-27 20:28:14 -0700409
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700410 psIdx = 1
Charles Chan76128b62017-03-27 20:28:14 -0700411
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700412 def __init__(self, asNum, numRouters):
413 self.asNum = asNum
414 self.numRouters = numRouters
415 self.routers = {}
416 for i in range(1, numRouters + 1):
417 self.routers[i] = RouterData(i)
Charles Chan76128b62017-03-27 20:28:14 -0700418
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700419 self.routerNodes={}
Charles Chan76128b62017-03-27 20:28:14 -0700420
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700421 self.neighbors=[]
422 self.vlanAddresses={}
Charles Chan76128b62017-03-27 20:28:14 -0700423
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700424 def peerWith(self, myRouter, myAddress, theirAddress, theirAsNum, intf=1, vlan=None):
425 router = self.routers[myRouter]
Charles Chan76128b62017-03-27 20:28:14 -0700426
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700427 router.addInterface(intf, vlan, myAddress)
428 router.addNeighbor(theirAddress, theirAsNum)
429
430 def getRouter(self, i):
431 return self.routerNodes[i]
432
433 @staticmethod
434 def generatePeeringAddresses():
435 network = ip_network(u'10.0.%s.0/24' % AutonomousSystem.psIdx)
436 AutonomousSystem.psIdx += 1
Charles Chan76128b62017-03-27 20:28:14 -0700437
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700438 return ip_interface('%s/%s' % (network[1], network.prefixlen)), \
439 ip_interface('%s/%s' % (network[2], network.prefixlen))
Charles Chan76128b62017-03-27 20:28:14 -0700440
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700441 @staticmethod
442 def addPeering(as1, as2, router1=1, router2=1, intf1=1, intf2=1, address1=None, address2=None, useVlans=False):
443 vlan = AutonomousSystem.psIdx if useVlans else None
Charles Chan76128b62017-03-27 20:28:14 -0700444
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700445 if address1 is None or address2 is None:
446 (address1, address2) = AutonomousSystem.generatePeeringAddresses()
Charles Chan76128b62017-03-27 20:28:14 -0700447
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700448 as1.peerWith(router1, address1, address2, as2.asNum, intf=intf1, vlan=vlan)
449 as2.peerWith(router2, address2, address1, as1.asNum, intf=intf2, vlan=vlan)
Charles Chan76128b62017-03-27 20:28:14 -0700450
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700451 @staticmethod
452 def getLastAddress(network):
453 return ip_interface(network.network_address + network.num_addresses - 2)
Charles Chan76128b62017-03-27 20:28:14 -0700454
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700455 @staticmethod
456 def getIthAddress(network, i):
457 return ip_interface('%s/%s' % (network[i], network.prefixlen))
458
459class BasicAutonomousSystem(AutonomousSystem):
460
461 """Basic autonomous system containing one host and one or more routers
462 which peer with other ASes."""
463
464 def __init__(self, num, routes, numRouters=1):
465 super(BasicAutonomousSystem, self).__init__(65000+num, numRouters)
466 self.num = num
467 self.routes = routes
Charles Chan76128b62017-03-27 20:28:14 -0700468
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700469 def addLink(self, switch, router=1):
470 self.routers[router].setSwitch(switch)
471
472 def build(self, topology):
473 self.addRouterAndHost(topology)
474
475 def addRouterAndHost(self, topology):
Charles Chan76128b62017-03-27 20:28:14 -0700476
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700477 # TODO implementation is messy and needs to be cleaned up
Charles Chan76128b62017-03-27 20:28:14 -0700478
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700479 intfs = {}
Charles Chan76128b62017-03-27 20:28:14 -0700480
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700481 router = self.routers[1]
482 for i, router in self.routers.items():
Charles Chan76128b62017-03-27 20:28:14 -0700483
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700484 #routerName = 'r%i%i' % (self.num, i)
485 routerName = 'r%i' % self.num
486 if not i==1:
487 routerName += ('%i' % i)
Charles Chan76128b62017-03-27 20:28:14 -0700488
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700489 hostName = 'h%i' % self.num
Charles Chan76128b62017-03-27 20:28:14 -0700490
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700491 for j, interface in router.interfaces.items():
492 nativeAddresses = interface.addressesByVlan.pop(None, [])
493 peeringIntf = [{'mac' : '00:00:%02x:00:%02x:%02x' % (self.num, i, j),
494 'ipAddrs' : nativeAddresses}]
Charles Chan76128b62017-03-27 20:28:14 -0700495
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700496 for vlan, addresses in interface.addressesByVlan.items():
497 peeringIntf.append({'vlan':vlan,
498 'mac':'00:00:%02x:%02x:%02x:%02x' % (self.num, vlan, i, j),
499 'ipAddrs':addresses})
Charles Chan76128b62017-03-27 20:28:14 -0700500
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700501 intfs.update({'%s-eth%s' % (routerName, j-1) : peeringIntf})
Charles Chan76128b62017-03-27 20:28:14 -0700502
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700503 # Only add the host to the first router for now
504 if i==1:
505 internalAddresses=[]
506 for route in self.routes:
507 internalAddresses.append('%s/%s' % (AutonomousSystem.getLastAddress(route).ip, route.prefixlen))
Charles Chan76128b62017-03-27 20:28:14 -0700508
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700509 internalIntf = {'ipAddrs' : internalAddresses}
Charles Chan76128b62017-03-27 20:28:14 -0700510
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700511 # This is the configuration of the next interface after all the peering interfaces
512 intfs.update({'%s-eth%s' % (routerName, len(router.interfaces.keys())) : internalIntf})
Charles Chan76128b62017-03-27 20:28:14 -0700513
514 routerNode = topology.addHost(routerName,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700515 asNum=self.asNum, neighbors=router.neighbors,
516 routes=self.routes,
517 cls=BgpRouter, interfaces=intfs)
Charles Chan76128b62017-03-27 20:28:14 -0700518
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700519 self.routerNodes[i] = routerNode
520
521 for switch in router.switches:
522 topology.addLink(switch, routerNode)
523
524 # Only add the host to the first router for now
525 if i==1:
526 defaultRoute = internalAddresses[0].split('/')[0]
Charles Chan76128b62017-03-27 20:28:14 -0700527
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700528 host = topology.addHost(hostName, cls=RoutedHost,
529 ips=[self.getFirstAddress(route) for route in self.routes],
530 gateway=defaultRoute)
Charles Chan76128b62017-03-27 20:28:14 -0700531
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700532 topology.addLink(routerNode, host)
533
534 #def getLastAddress(self, network):
535 # return ip_address(network.network_address + network.num_addresses - 2)
Charles Chan76128b62017-03-27 20:28:14 -0700536
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700537 def getFirstAddress(self, network):
538 return '%s/%s' % (network[1], network.prefixlen)
539
540# TODO fix this AS - doesn't currently work
541class RouteServerAutonomousSystem(BasicAutonomousSystem):
542
543 def __init__(self, routerAddress, *args, **kwargs):
544 BasicAutonomousSystem.__init__(self, *args, **kwargs)
545
546 self.routerAddress = routerAddress
547
548 def build(self, topology, connectAtSwitch):
549
550 switch = topology.addSwitch('as%isw' % self.num, cls=OVSBridge)
551
552 self.addRouterAndHost(topology, self.routerAddress, switch)
553
554 rsName = 'rs%i' % self.num
555 routeServer = topology.addHost(rsName,
556 self.asnum, self.neighbors,
557 cls=BgpRouter,
558 interfaces={'%s-eth0' % rsName : {'ipAddrs':[self.peeringAddress]}})
559
560 topology.addLink(routeServer, switch)
561 topology.addLink(switch, connectAtSwitch)
Charles Chan76128b62017-03-27 20:28:14 -0700562
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700563class SdnAutonomousSystem(AutonomousSystem):
Charles Chan76128b62017-03-27 20:28:14 -0700564
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700565 """Runs the internal BGP speakers needed for ONOS routing apps like
566 SDN-IP."""
Charles Chan76128b62017-03-27 20:28:14 -0700567
Jonathan Harte6b897f2017-01-24 17:09:58 -0800568 routerIdx = 1
Charles Chan76128b62017-03-27 20:28:14 -0700569
Jonathan Harte6b897f2017-01-24 17:09:58 -0800570 def __init__(self, onosIps, num=1, numBgpSpeakers=1, asNum=65000, externalOnos=True,
Jonathan Hartfc0af772017-01-16 13:15:08 -0800571 peerIntfConfig=None, withFpm=False):
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700572 super(SdnAutonomousSystem, self).__init__(asNum, numBgpSpeakers)
573 self.onosIps = onosIps
Jonathan Harte6b897f2017-01-24 17:09:58 -0800574 self.num = num
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700575 self.numBgpSpeakers = numBgpSpeakers
576 self.peerIntfConfig = peerIntfConfig
Jonathan Hartfc0af772017-01-16 13:15:08 -0800577 self.withFpm = withFpm
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700578 self.externalOnos= externalOnos
579 self.internalPeeringSubnet = ip_network(u'1.1.1.0/24')
Charles Chan76128b62017-03-27 20:28:14 -0700580
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700581 for router in self.routers.values():
582 # Add iBGP sessions to ONOS nodes
583 for onosIp in onosIps:
584 router.neighbors.append({'address':onosIp, 'as':asNum, 'port':2000})
Charles Chan76128b62017-03-27 20:28:14 -0700585
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700586 # Add iBGP sessions to other BGP speakers
587 for i, router2 in self.routers.items():
588 if router == router2:
589 continue
Jonathan Harte6b897f2017-01-24 17:09:58 -0800590 cpIpBase = self.num*10
591 ip = AutonomousSystem.getIthAddress(self.internalPeeringSubnet, cpIpBase+i)
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700592 router.neighbors.append({'address':ip.ip, 'as':asNum})
Charles Chan76128b62017-03-27 20:28:14 -0700593
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700594 def build(self, topology, connectAtSwitch, controlSwitch):
Charles Chan76128b62017-03-27 20:28:14 -0700595
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700596 natIp = AutonomousSystem.getLastAddress(self.internalPeeringSubnet)
Charles Chan76128b62017-03-27 20:28:14 -0700597
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700598 for i, router in self.routers.items():
Jonathan Harte6b897f2017-01-24 17:09:58 -0800599 num = SdnAutonomousSystem.routerIdx
600 SdnAutonomousSystem.routerIdx += 1
601 name = 'bgp%s' % num
Charles Chan76128b62017-03-27 20:28:14 -0700602
Jonathan Harte6b897f2017-01-24 17:09:58 -0800603 cpIpBase = self.num*10
604 ip = AutonomousSystem.getIthAddress(self.internalPeeringSubnet, cpIpBase+i)
Charles Chan76128b62017-03-27 20:28:14 -0700605
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700606 eth0 = { 'ipAddrs' : [ str(ip) ] }
607 if self.peerIntfConfig is not None:
608 eth1 = self.peerIntfConfig
609 else:
610 nativeAddresses = router.interfaces[1].addressesByVlan.pop(None, [])
Charles Chan76128b62017-03-27 20:28:14 -0700611 eth1 = [{ 'mac':'00:00:00:00:00:%02x' % num,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700612 'ipAddrs' : nativeAddresses }]
Charles Chan76128b62017-03-27 20:28:14 -0700613
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700614 for vlan, addresses in router.interfaces[1].addressesByVlan.items():
615 eth1.append({'vlan':vlan,
Jonathan Harte6b897f2017-01-24 17:09:58 -0800616 'mac':'00:00:00:%02x:%02x:00' % (num, vlan),
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700617 'ipAddrs':addresses})
Charles Chan76128b62017-03-27 20:28:14 -0700618
619
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700620 intfs = { '%s-eth0' % name : eth0,
621 '%s-eth1' % name : eth1 }
Charles Chan76128b62017-03-27 20:28:14 -0700622
623 bgp = topology.addHost( name, cls=BgpRouter, asNum=self.asNum,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700624 neighbors=router.neighbors,
Charles Chan76128b62017-03-27 20:28:14 -0700625 interfaces=intfs,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700626 defaultRoute=str(natIp.ip),
Jonathan Hartfc0af772017-01-16 13:15:08 -0800627 fpm=self.onosIps[0] if self.withFpm else None )
Charles Chan76128b62017-03-27 20:28:14 -0700628
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700629 topology.addLink( bgp, controlSwitch )
630 topology.addLink( bgp, connectAtSwitch )
Charles Chan76128b62017-03-27 20:28:14 -0700631
632
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700633 if self.externalOnos:
Charles Chan76128b62017-03-27 20:28:14 -0700634 nat = topology.addHost('nat', cls=NAT,
635 ip='%s/%s' % (natIp.ip, self.internalPeeringSubnet.prefixlen),
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700636 subnet=str(self.internalPeeringSubnet), inNamespace=False);
637 topology.addLink(controlSwitch, nat)
638
Charles Chan76128b62017-03-27 20:28:14 -0700639
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700640def generateRoutes(baseRange, numRoutes, subnetSize=None):
641 baseNetwork = ip_network(baseRange)
Charles Chan76128b62017-03-27 20:28:14 -0700642
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700643 # We need to get at least 2 addresses out of each subnet, so the biggest
644 # prefix length we can have is /30
645 maxPrefixLength = baseNetwork.max_prefixlen - 2
Charles Chan76128b62017-03-27 20:28:14 -0700646
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700647 if subnetSize is not None:
648 return list(baseNetwork.subnets(new_prefix=subnetSize))
Charles Chan76128b62017-03-27 20:28:14 -0700649
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700650 trySubnetSize = baseNetwork.prefixlen + 1
651 while trySubnetSize <= maxPrefixLength and \
652 len(list(baseNetwork.subnets(new_prefix=trySubnetSize))) < numRoutes:
653 trySubnetSize += 1
Charles Chan76128b62017-03-27 20:28:14 -0700654
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700655 if trySubnetSize > maxPrefixLength:
656 raise Exception("Can't get enough routes from input parameters")
Charles Chan76128b62017-03-27 20:28:14 -0700657
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700658 return list(baseNetwork.subnets(new_prefix=trySubnetSize))[:numRoutes]
Charles Chan76128b62017-03-27 20:28:14 -0700659
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700660class RoutingCli( CLI ):
Charles Chan76128b62017-03-27 20:28:14 -0700661
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700662 """CLI command that can bring a host up or down. Useful for simulating router failure."""
Charles Chan76128b62017-03-27 20:28:14 -0700663
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700664 def do_host( self, line ):
665 args = line.split()
666 if len(args) != 2:
667 error( 'invalid number of args: host <host name> {up, down}\n' )
668 return
Charles Chan76128b62017-03-27 20:28:14 -0700669
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700670 host = args[ 0 ]
671 command = args[ 1 ]
672 if host not in self.mn or self.mn.get( host ) not in self.mn.hosts:
673 error( 'invalid host: %s\n' % args[ 1 ] )
674 else:
675 if command == 'up':
676 op = 'up'
677 elif command == 'down':
678 op = 'down'
679 else:
680 error( 'invalid command: host <host name> {up, down}\n' )
681 return
682
683 for intf in self.mn.get( host ).intfList( ):
684 intf.link.intf1.ifconfig( op )
685 intf.link.intf2.ifconfig( op )
Charles Chane7e8cdb2019-10-22 23:38:39 -0700686
687# Disable NIC offloading
688def disable_offload(host, intf):
689 for attr in ["rx", "tx", "sg"]:
690 cmd = "/sbin/ethtool --offload %s %s off" % (intf, attr)
691 host.cmd(cmd)