blob: eab92c2c87433c5539562915d0aac47c52e377fd [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
31class Router(Host):
Charles Chan76128b62017-03-27 20:28:14 -070032
Jonathan Hartce97e5b2016-04-19 01:41:31 -070033 """An L3 router.
34 Configures the Linux kernel for L3 forwarding and supports rich interface
35 configuration of IP addresses, MAC addresses and VLANs."""
Charles Chan76128b62017-03-27 20:28:14 -070036
Jonathan Hartce97e5b2016-04-19 01:41:31 -070037 def __init__(self, name, interfaces, *args, **kwargs):
38 super(Router, self).__init__(name, **kwargs)
39
40 self.interfaces = interfaces
Charles Chan76128b62017-03-27 20:28:14 -070041
Jonathan Hartce97e5b2016-04-19 01:41:31 -070042 def config(self, **kwargs):
43 super(Host, self).config(**kwargs)
Charles Chan76128b62017-03-27 20:28:14 -070044
Jonathan Hartce97e5b2016-04-19 01:41:31 -070045 self.cmd('sysctl net.ipv4.ip_forward=1')
46 self.cmd('sysctl net.ipv4.conf.all.rp_filter=0')
Charles Chan76128b62017-03-27 20:28:14 -070047 self.cmd('sysctl net.ipv6.conf.all.forwarding=1')
Jonathan Hartce97e5b2016-04-19 01:41:31 -070048
49 for intf, configs in self.interfaces.items():
Charles Chan76128b62017-03-27 20:28:14 -070050 self.cmd('ip -4 addr flush dev %s' % intf)
Jonathan Hartce97e5b2016-04-19 01:41:31 -070051 self.cmd( 'sysctl net.ipv4.conf.%s.rp_filter=0' % intf )
Charles Chan76128b62017-03-27 20:28:14 -070052
Jonathan Hartce97e5b2016-04-19 01:41:31 -070053 if not isinstance(configs, list):
54 configs = [configs]
Charles Chan76128b62017-03-27 20:28:14 -070055
Jonathan Hartce97e5b2016-04-19 01:41:31 -070056 for attrs in configs:
Charles Chan76128b62017-03-27 20:28:14 -070057 # Configure the vlan if there is one
Jonathan Hartce97e5b2016-04-19 01:41:31 -070058 if 'vlan' in attrs:
59 vlanName = '%s.%s' % (intf, attrs['vlan'])
Charles Chan76128b62017-03-27 20:28:14 -070060 self.cmd('ip link add link %s name %s type vlan id %s' %
Jonathan Hartce97e5b2016-04-19 01:41:31 -070061 (intf, vlanName, attrs['vlan']))
62 self.cmd('ip link set %s up' % vlanName)
63 addrIntf = vlanName
64 else:
65 addrIntf = intf
Charles Chan76128b62017-03-27 20:28:14 -070066
Jonathan Hartce97e5b2016-04-19 01:41:31 -070067 # Now configure the addresses on the vlan/native interface
68 if 'mac' in attrs:
69 self.cmd('ip link set %s down' % addrIntf)
70 self.cmd('ip link set %s address %s' % (addrIntf, attrs['mac']))
71 self.cmd('ip link set %s up' % addrIntf)
72 for addr in attrs['ipAddrs']:
73 self.cmd('ip addr add %s dev %s' % (addr, addrIntf))
74
75class QuaggaRouter(Router):
Charles Chan76128b62017-03-27 20:28:14 -070076
Jonathan Hartce97e5b2016-04-19 01:41:31 -070077 """Runs Quagga to create a router that can speak routing protocols."""
Charles Chan76128b62017-03-27 20:28:14 -070078
Jonathan Hartce97e5b2016-04-19 01:41:31 -070079 binDir = '/usr/lib/quagga'
Jonathan Hartd5d80872017-01-16 13:55:41 -080080 logDir = '/var/log/quagga'
Charles Chan76128b62017-03-27 20:28:14 -070081
Jonathan Hartce97e5b2016-04-19 01:41:31 -070082 def __init__(self, name, interfaces,
83 defaultRoute=None,
84 zebraConfFile=None,
85 protocols=[],
86 fpm=None,
87 runDir='/var/run/quagga', *args, **kwargs):
88 super(QuaggaRouter, self).__init__(name, interfaces, **kwargs)
Charles Chan76128b62017-03-27 20:28:14 -070089
Jonathan Hartce97e5b2016-04-19 01:41:31 -070090 self.protocols = protocols
91 self.fpm = fpm
Charles Chan76128b62017-03-27 20:28:14 -070092
Jonathan Hartce97e5b2016-04-19 01:41:31 -070093 for p in self.protocols:
94 p.setQuaggaRouter(self)
Charles Chan76128b62017-03-27 20:28:14 -070095
Jonathan Hartce97e5b2016-04-19 01:41:31 -070096 self.runDir = runDir
97 self.defaultRoute = defaultRoute
Charles Chan76128b62017-03-27 20:28:14 -070098
Jonathan Hartd5d80872017-01-16 13:55:41 -080099 # Ensure required directories exist
100 try:
101 original_umask = os.umask(0)
102 if (not os.path.isdir(QuaggaRouter.logDir)):
103 os.makedirs(QuaggaRouter.logDir, 0777)
104 if (not os.path.isdir(self.runDir)):
105 os.makedirs(self.runDir, 0777)
106 finally:
107 os.umask(original_umask)
108
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700109 self.zebraConfFile = zebraConfFile
110 if (self.zebraConfFile is None):
111 self.zebraConfFile = '%s/zebrad%s.conf' % (self.runDir, self.name)
112 self.generateZebra()
Charles Chan76128b62017-03-27 20:28:14 -0700113
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700114 self.socket = '%s/zebra%s.api' % (self.runDir, self.name)
Charles Chan76128b62017-03-27 20:28:14 -0700115
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700116 self.zebraPidFile = '%s/zebra%s.pid' % (self.runDir, self.name)
117
118 def generateZebra(self):
119 configFile = open(self.zebraConfFile, 'w+')
Jonathan Hartd5d80872017-01-16 13:55:41 -0800120 configFile.write('log file %s/zebrad%s.log\n' % (QuaggaRouter.logDir, self.name))
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700121 configFile.write('hostname zebra-%s\n' % self.name)
Jonathan Harte6b897f2017-01-24 17:09:58 -0800122 configFile.write('password %s\n' % 'quagga')
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700123 if (self.fpm is not None):
124 configFile.write('fpm connection ip %s port 2620' % self.fpm)
125 configFile.close()
126
127 def config(self, **kwargs):
128 super(QuaggaRouter, self).config(**kwargs)
129
130 self.cmd('%s/zebra -d -f %s -z %s -i %s'
131 % (QuaggaRouter.binDir, self.zebraConfFile, self.socket, self.zebraPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700132
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700133 for p in self.protocols:
134 p.config(**kwargs)
Charles Chan76128b62017-03-27 20:28:14 -0700135
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700136 if self.defaultRoute:
137 self.cmd('ip route add default via %s' % self.defaultRoute)
Charles Chan76128b62017-03-27 20:28:14 -0700138
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700139 def terminate(self, **kwargs):
Charles Chan76128b62017-03-27 20:28:14 -0700140 self.cmd("ps ax | grep '%s' | awk '{print $1}' | xargs kill"
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700141 % (self.socket))
Charles Chan76128b62017-03-27 20:28:14 -0700142
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700143 for p in self.protocols:
144 p.terminate(**kwargs)
145
146 super(QuaggaRouter, self).terminate()
Charles Chan76128b62017-03-27 20:28:14 -0700147
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700148class Protocol(object):
Charles Chan76128b62017-03-27 20:28:14 -0700149
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700150 """Base abstraction of a protocol that the QuaggaRouter can run."""
Charles Chan76128b62017-03-27 20:28:14 -0700151
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700152 def setQuaggaRouter(self, qr):
153 self.qr = qr
Charles Chan76128b62017-03-27 20:28:14 -0700154
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700155 def config(self, **kwargs):
156 pass
Charles Chan76128b62017-03-27 20:28:14 -0700157
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700158 def terminate(self, **kwargs):
159 pass
Charles Chan76128b62017-03-27 20:28:14 -0700160
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700161class BgpProtocol(Protocol):
Charles Chan76128b62017-03-27 20:28:14 -0700162
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700163 """Configures and runs the BGP protocol in Quagga."""
Charles Chan76128b62017-03-27 20:28:14 -0700164
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700165 def __init__(self, configFile=None, asNum=None, neighbors=[], routes=[], *args, **kwargs):
166 self.configFile = configFile
Charles Chan76128b62017-03-27 20:28:14 -0700167
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700168 self.asNum = asNum
169 self.neighbors = neighbors
170 self.routes = routes
Charles Chan76128b62017-03-27 20:28:14 -0700171
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700172 def config(self, **kwargs):
173 if self.configFile is None:
174 self.configFile = '%s/bgpd%s.conf' % (self.qr.runDir, self.qr.name)
175 self.generateConfig()
Charles Chan76128b62017-03-27 20:28:14 -0700176
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700177 bgpdPidFile = '%s/bgpd%s.pid' % (self.qr.runDir, self.qr.name)
Charles Chan76128b62017-03-27 20:28:14 -0700178
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700179 self.qr.cmd('%s/bgpd -d -f %s -z %s -i %s'
180 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, bgpdPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700181
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700182 def generateConfig(self):
183 conf = ConfigurationWriter(self.configFile)
Charles Chan76128b62017-03-27 20:28:14 -0700184
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700185 def getRouterId(interfaces):
186 intfAttributes = interfaces.itervalues().next()
187 print intfAttributes
188 if isinstance(intfAttributes, list):
189 # Try use the first set of attributes, but if using vlans they might not have addresses
190 intfAttributes = intfAttributes[1] if not intfAttributes[0]['ipAddrs'] else intfAttributes[0]
191 return intfAttributes['ipAddrs'][0].split('/')[0]
Charles Chan76128b62017-03-27 20:28:14 -0700192
Jonathan Hartd5d80872017-01-16 13:55:41 -0800193 conf.writeLine('log file %s/bgpd%s.log' % (QuaggaRouter.logDir, self.qr.name))
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700194 conf.writeLine('hostname bgp-%s' % self.qr.name);
Jonathan Harte6b897f2017-01-24 17:09:58 -0800195 conf.writeLine('password %s' % 'quagga')
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700196 conf.writeLine('!')
197 conf.writeLine('router bgp %s' % self.asNum)
Charles Chan76128b62017-03-27 20:28:14 -0700198
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700199 conf.indent()
Charles Chan76128b62017-03-27 20:28:14 -0700200
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700201 conf.writeLine('bgp router-id %s' % getRouterId(self.qr.interfaces))
202 conf.writeLine('timers bgp %s' % '3 9')
203 conf.writeLine('!')
Charles Chan76128b62017-03-27 20:28:14 -0700204
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700205 for neighbor in self.neighbors:
206 conf.writeLine('neighbor %s remote-as %s' % (neighbor['address'], neighbor['as']))
207 conf.writeLine('neighbor %s ebgp-multihop' % neighbor['address'])
208 conf.writeLine('neighbor %s timers connect %s' % (neighbor['address'], '5'))
209 conf.writeLine('neighbor %s advertisement-interval %s' % (neighbor['address'], '5'))
210 if 'port' in neighbor:
211 conf.writeLine('neighbor %s port %s' % (neighbor['address'], neighbor['port']))
212 conf.writeLine('!')
Charles Chan76128b62017-03-27 20:28:14 -0700213
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700214 for route in self.routes:
215 conf.writeLine('network %s' % route)
Charles Chan76128b62017-03-27 20:28:14 -0700216
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700217 conf.close()
Charles Chan76128b62017-03-27 20:28:14 -0700218
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700219class OspfProtocol(Protocol):
Charles Chan76128b62017-03-27 20:28:14 -0700220
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700221 """Configures and runs the OSPF protocol in Quagga."""
Charles Chan76128b62017-03-27 20:28:14 -0700222
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700223 def __init__(self, configFile=None, *args, **kwargs):
224 self.configFile = configFile
Charles Chan76128b62017-03-27 20:28:14 -0700225
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700226 def config(self, **kwargs):
227 if self.configFile is None:
228 self.configFile = '%s/ospfd%s.conf' % (self.qr.runDir, self.qr.name)
229 self.generateConfig()
Charles Chan76128b62017-03-27 20:28:14 -0700230
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700231 ospfPidFile = '%s/ospf%s.pid' % (self.qr.runDir, self.qr.name)
Charles Chan76128b62017-03-27 20:28:14 -0700232
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700233 self.qr.cmd('%s/ospfd -d -f %s -z %s -i %s'
234 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, ospfPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700235
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700236 def generateConfig(self):
237 conf = ConfigurationWriter(self.configFile)
Charles Chan76128b62017-03-27 20:28:14 -0700238
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700239 def getRouterId(interfaces):
240 intfAttributes = interfaces.itervalues().next()
241 print intfAttributes
242 if isinstance(intfAttributes, list):
243 # Try use the first set of attributes, but if using vlans they might not have addresses
244 intfAttributes = intfAttributes[1] if not intfAttributes[0]['ipAddrs'] else intfAttributes[0]
245 return intfAttributes['ipAddrs'][0].split('/')[0]
Charles Chan76128b62017-03-27 20:28:14 -0700246
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700247 conf.writeLine('hostname ospf-%s' % self.qr.name);
248 conf.writeLine('password %s' % 'hello')
249 conf.writeLine('!')
250 conf.writeLine('router ospf')
Charles Chan76128b62017-03-27 20:28:14 -0700251
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700252 conf.indent()
Charles Chan76128b62017-03-27 20:28:14 -0700253
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700254 conf.writeLine('ospf router-id %s' % getRouterId(self.qr.interfaces))
255 conf.writeLine('!')
Charles Chan76128b62017-03-27 20:28:14 -0700256
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700257 for name, intf in self.qr.interfaces.items():
258 for ip in intf['ipAddrs']:
259 conf.writeLine('network %s area 0' % ip)
260 #if intf['ipAddrs'][0].startswith('192.168'):
261 # writeLine(1, 'passive-interface %s' % name)
Charles Chan76128b62017-03-27 20:28:14 -0700262
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700263 conf.close()
Charles Chan76128b62017-03-27 20:28:14 -0700264
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700265class PimProtocol(Protocol):
Charles Chan76128b62017-03-27 20:28:14 -0700266
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700267 """Configures and runs the PIM protcol in Quagga."""
Charles Chan76128b62017-03-27 20:28:14 -0700268
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700269 def __init__(self, configFile=None, *args, **kwargs):
270 self.configFile = configFile
Charles Chan76128b62017-03-27 20:28:14 -0700271
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700272 def config(self, **kwargs):
273 pimPidFile = '%s/pim%s.pid' % (self.qr.runDir, self.qr.name)
Charles Chan76128b62017-03-27 20:28:14 -0700274
Jonathan Hart09608592016-05-19 09:39:22 -0700275 self.qr.cmd('%s/pimd -Z -d -f %s -z %s -i %s'
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700276 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, pimPidFile))
Charles Chan76128b62017-03-27 20:28:14 -0700277
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700278class ConfigurationWriter(object):
Charles Chan76128b62017-03-27 20:28:14 -0700279
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700280 """Utility class for writing a configuration file."""
Charles Chan76128b62017-03-27 20:28:14 -0700281
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700282 def __init__(self, filename):
283 self.filename = filename
284 self.indentValue = 0;
Charles Chan76128b62017-03-27 20:28:14 -0700285
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700286 self.configFile = open(self.filename, 'w+')
Charles Chan76128b62017-03-27 20:28:14 -0700287
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700288 def indent(self):
289 self.indentValue += 1
Charles Chan76128b62017-03-27 20:28:14 -0700290
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700291 def unindent(self):
292 if (self.indentValue > 0):
293 self.indentValue -= 1
Charles Chan76128b62017-03-27 20:28:14 -0700294
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700295 def write(self, string):
296 self.configFile.write(string)
Charles Chan76128b62017-03-27 20:28:14 -0700297
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700298 def writeLine(self, string):
299 intentStr = ''
300 for _ in range(0, self.indentValue):
301 intentStr += ' '
302 self.write('%s%s\n' % (intentStr, string))
Charles Chan76128b62017-03-27 20:28:14 -0700303
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700304 def close(self):
305 self.configFile.close()
306
307#Backward compatibility for BGP-only use case
308class BgpRouter(QuaggaRouter):
Charles Chan76128b62017-03-27 20:28:14 -0700309
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700310 """Quagga router running the BGP protocol."""
Charles Chan76128b62017-03-27 20:28:14 -0700311
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700312 def __init__(self, name, interfaces,
Charles Chandfa13bd2017-03-24 21:40:10 -0700313 asNum=0, neighbors=[], routes=[],
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700314 defaultRoute=None,
315 quaggaConfFile=None,
316 zebraConfFile=None,
317 *args, **kwargs):
318 bgp = BgpProtocol(configFile=quaggaConfFile, asNum=asNum, neighbors=neighbors, routes=routes)
Charles Chan76128b62017-03-27 20:28:14 -0700319
320 super(BgpRouter, self).__init__(name, interfaces,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700321 zebraConfFile=zebraConfFile,
322 defaultRoute=defaultRoute,
323 protocols=[bgp],
324 *args, **kwargs)
Charles Chan76128b62017-03-27 20:28:14 -0700325
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700326class RouterData(object):
Charles Chan76128b62017-03-27 20:28:14 -0700327
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700328 """Internal data structure storing information about a router."""
Charles Chan76128b62017-03-27 20:28:14 -0700329
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700330 def __init__(self, index):
331 self.index = index;
332 self.neighbors = []
333 self.interfaces = {}
334 self.switches = []
Charles Chan76128b62017-03-27 20:28:14 -0700335
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700336 def addNeighbor(self, theirAddress, theirAsNum):
337 self.neighbors.append({'address':theirAddress.ip, 'as':theirAsNum})
Charles Chan76128b62017-03-27 20:28:14 -0700338
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700339 def addInterface(self, intf, vlan, address):
340 if not intf in self.interfaces:
341 self.interfaces[intf] = InterfaceData(intf)
Charles Chan76128b62017-03-27 20:28:14 -0700342
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700343 self.interfaces[intf].addAddress(vlan, address)
Charles Chan76128b62017-03-27 20:28:14 -0700344
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700345 def setSwitch(self, switch):
346 self.switches.append(switch)
Charles Chan76128b62017-03-27 20:28:14 -0700347
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700348class InterfaceData(object):
Charles Chan76128b62017-03-27 20:28:14 -0700349
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700350 """Internal data structure storing information about an interface."""
Charles Chan76128b62017-03-27 20:28:14 -0700351
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700352 def __init__(self, number):
353 self.number = number
354 self.addressesByVlan = {}
Charles Chan76128b62017-03-27 20:28:14 -0700355
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700356 def addAddress(self, vlan, address):
357 if not vlan in self.addressesByVlan:
358 self.addressesByVlan[vlan] = []
Charles Chan76128b62017-03-27 20:28:14 -0700359
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700360 self.addressesByVlan[vlan].append(address.with_prefixlen)
Charles Chan76128b62017-03-27 20:28:14 -0700361
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700362class RoutedNetwork(object):
Charles Chan76128b62017-03-27 20:28:14 -0700363
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700364 """Creates a host behind a router. This is common boilerplate topology
365 segment in routed networks."""
Charles Chan76128b62017-03-27 20:28:14 -0700366
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700367 @staticmethod
368 def build(topology, router, hostName, networks):
369 # There's a convention that the router's addresses are already set up,
370 # and it has the last address in the network.
Charles Chan76128b62017-03-27 20:28:14 -0700371
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700372 def getFirstAddress(network):
373 return '%s/%s' % (network[1], network.prefixlen)
Charles Chan76128b62017-03-27 20:28:14 -0700374
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700375 defaultRoute = AutonomousSystem.getLastAddress(networks[0]).ip
Charles Chan76128b62017-03-27 20:28:14 -0700376
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700377 host = topology.addHost(hostName, cls=RoutedHost,
378 ips=[getFirstAddress(network) for network in networks],
379 gateway=defaultRoute)
380
381 topology.addLink(router, host)
382
383class AutonomousSystem(object):
Charles Chan76128b62017-03-27 20:28:14 -0700384
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700385 """Base abstraction of an autonomous system, which implies some internal
386 topology and connections to other topology elements (switches/other ASes)."""
Charles Chan76128b62017-03-27 20:28:14 -0700387
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700388 psIdx = 1
Charles Chan76128b62017-03-27 20:28:14 -0700389
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700390 def __init__(self, asNum, numRouters):
391 self.asNum = asNum
392 self.numRouters = numRouters
393 self.routers = {}
394 for i in range(1, numRouters + 1):
395 self.routers[i] = RouterData(i)
Charles Chan76128b62017-03-27 20:28:14 -0700396
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700397 self.routerNodes={}
Charles Chan76128b62017-03-27 20:28:14 -0700398
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700399 self.neighbors=[]
400 self.vlanAddresses={}
Charles Chan76128b62017-03-27 20:28:14 -0700401
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700402 def peerWith(self, myRouter, myAddress, theirAddress, theirAsNum, intf=1, vlan=None):
403 router = self.routers[myRouter]
Charles Chan76128b62017-03-27 20:28:14 -0700404
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700405 router.addInterface(intf, vlan, myAddress)
406 router.addNeighbor(theirAddress, theirAsNum)
407
408 def getRouter(self, i):
409 return self.routerNodes[i]
410
411 @staticmethod
412 def generatePeeringAddresses():
413 network = ip_network(u'10.0.%s.0/24' % AutonomousSystem.psIdx)
414 AutonomousSystem.psIdx += 1
Charles Chan76128b62017-03-27 20:28:14 -0700415
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700416 return ip_interface('%s/%s' % (network[1], network.prefixlen)), \
417 ip_interface('%s/%s' % (network[2], network.prefixlen))
Charles Chan76128b62017-03-27 20:28:14 -0700418
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700419 @staticmethod
420 def addPeering(as1, as2, router1=1, router2=1, intf1=1, intf2=1, address1=None, address2=None, useVlans=False):
421 vlan = AutonomousSystem.psIdx if useVlans else None
Charles Chan76128b62017-03-27 20:28:14 -0700422
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700423 if address1 is None or address2 is None:
424 (address1, address2) = AutonomousSystem.generatePeeringAddresses()
Charles Chan76128b62017-03-27 20:28:14 -0700425
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700426 as1.peerWith(router1, address1, address2, as2.asNum, intf=intf1, vlan=vlan)
427 as2.peerWith(router2, address2, address1, as1.asNum, intf=intf2, vlan=vlan)
Charles Chan76128b62017-03-27 20:28:14 -0700428
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700429 @staticmethod
430 def getLastAddress(network):
431 return ip_interface(network.network_address + network.num_addresses - 2)
Charles Chan76128b62017-03-27 20:28:14 -0700432
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700433 @staticmethod
434 def getIthAddress(network, i):
435 return ip_interface('%s/%s' % (network[i], network.prefixlen))
436
437class BasicAutonomousSystem(AutonomousSystem):
438
439 """Basic autonomous system containing one host and one or more routers
440 which peer with other ASes."""
441
442 def __init__(self, num, routes, numRouters=1):
443 super(BasicAutonomousSystem, self).__init__(65000+num, numRouters)
444 self.num = num
445 self.routes = routes
Charles Chan76128b62017-03-27 20:28:14 -0700446
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700447 def addLink(self, switch, router=1):
448 self.routers[router].setSwitch(switch)
449
450 def build(self, topology):
451 self.addRouterAndHost(topology)
452
453 def addRouterAndHost(self, topology):
Charles Chan76128b62017-03-27 20:28:14 -0700454
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700455 # TODO implementation is messy and needs to be cleaned up
Charles Chan76128b62017-03-27 20:28:14 -0700456
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700457 intfs = {}
Charles Chan76128b62017-03-27 20:28:14 -0700458
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700459 router = self.routers[1]
460 for i, router in self.routers.items():
Charles Chan76128b62017-03-27 20:28:14 -0700461
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700462 #routerName = 'r%i%i' % (self.num, i)
463 routerName = 'r%i' % self.num
464 if not i==1:
465 routerName += ('%i' % i)
Charles Chan76128b62017-03-27 20:28:14 -0700466
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700467 hostName = 'h%i' % self.num
Charles Chan76128b62017-03-27 20:28:14 -0700468
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700469 for j, interface in router.interfaces.items():
470 nativeAddresses = interface.addressesByVlan.pop(None, [])
471 peeringIntf = [{'mac' : '00:00:%02x:00:%02x:%02x' % (self.num, i, j),
472 'ipAddrs' : nativeAddresses}]
Charles Chan76128b62017-03-27 20:28:14 -0700473
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700474 for vlan, addresses in interface.addressesByVlan.items():
475 peeringIntf.append({'vlan':vlan,
476 'mac':'00:00:%02x:%02x:%02x:%02x' % (self.num, vlan, i, j),
477 'ipAddrs':addresses})
Charles Chan76128b62017-03-27 20:28:14 -0700478
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700479 intfs.update({'%s-eth%s' % (routerName, j-1) : peeringIntf})
Charles Chan76128b62017-03-27 20:28:14 -0700480
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700481 # Only add the host to the first router for now
482 if i==1:
483 internalAddresses=[]
484 for route in self.routes:
485 internalAddresses.append('%s/%s' % (AutonomousSystem.getLastAddress(route).ip, route.prefixlen))
Charles Chan76128b62017-03-27 20:28:14 -0700486
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700487 internalIntf = {'ipAddrs' : internalAddresses}
Charles Chan76128b62017-03-27 20:28:14 -0700488
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700489 # This is the configuration of the next interface after all the peering interfaces
490 intfs.update({'%s-eth%s' % (routerName, len(router.interfaces.keys())) : internalIntf})
Charles Chan76128b62017-03-27 20:28:14 -0700491
492 routerNode = topology.addHost(routerName,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700493 asNum=self.asNum, neighbors=router.neighbors,
494 routes=self.routes,
495 cls=BgpRouter, interfaces=intfs)
Charles Chan76128b62017-03-27 20:28:14 -0700496
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700497 self.routerNodes[i] = routerNode
498
499 for switch in router.switches:
500 topology.addLink(switch, routerNode)
501
502 # Only add the host to the first router for now
503 if i==1:
504 defaultRoute = internalAddresses[0].split('/')[0]
Charles Chan76128b62017-03-27 20:28:14 -0700505
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700506 host = topology.addHost(hostName, cls=RoutedHost,
507 ips=[self.getFirstAddress(route) for route in self.routes],
508 gateway=defaultRoute)
Charles Chan76128b62017-03-27 20:28:14 -0700509
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700510 topology.addLink(routerNode, host)
511
512 #def getLastAddress(self, network):
513 # return ip_address(network.network_address + network.num_addresses - 2)
Charles Chan76128b62017-03-27 20:28:14 -0700514
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700515 def getFirstAddress(self, network):
516 return '%s/%s' % (network[1], network.prefixlen)
517
518# TODO fix this AS - doesn't currently work
519class RouteServerAutonomousSystem(BasicAutonomousSystem):
520
521 def __init__(self, routerAddress, *args, **kwargs):
522 BasicAutonomousSystem.__init__(self, *args, **kwargs)
523
524 self.routerAddress = routerAddress
525
526 def build(self, topology, connectAtSwitch):
527
528 switch = topology.addSwitch('as%isw' % self.num, cls=OVSBridge)
529
530 self.addRouterAndHost(topology, self.routerAddress, switch)
531
532 rsName = 'rs%i' % self.num
533 routeServer = topology.addHost(rsName,
534 self.asnum, self.neighbors,
535 cls=BgpRouter,
536 interfaces={'%s-eth0' % rsName : {'ipAddrs':[self.peeringAddress]}})
537
538 topology.addLink(routeServer, switch)
539 topology.addLink(switch, connectAtSwitch)
Charles Chan76128b62017-03-27 20:28:14 -0700540
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700541class SdnAutonomousSystem(AutonomousSystem):
Charles Chan76128b62017-03-27 20:28:14 -0700542
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700543 """Runs the internal BGP speakers needed for ONOS routing apps like
544 SDN-IP."""
Charles Chan76128b62017-03-27 20:28:14 -0700545
Jonathan Harte6b897f2017-01-24 17:09:58 -0800546 routerIdx = 1
Charles Chan76128b62017-03-27 20:28:14 -0700547
Jonathan Harte6b897f2017-01-24 17:09:58 -0800548 def __init__(self, onosIps, num=1, numBgpSpeakers=1, asNum=65000, externalOnos=True,
Jonathan Hartfc0af772017-01-16 13:15:08 -0800549 peerIntfConfig=None, withFpm=False):
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700550 super(SdnAutonomousSystem, self).__init__(asNum, numBgpSpeakers)
551 self.onosIps = onosIps
Jonathan Harte6b897f2017-01-24 17:09:58 -0800552 self.num = num
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700553 self.numBgpSpeakers = numBgpSpeakers
554 self.peerIntfConfig = peerIntfConfig
Jonathan Hartfc0af772017-01-16 13:15:08 -0800555 self.withFpm = withFpm
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700556 self.externalOnos= externalOnos
557 self.internalPeeringSubnet = ip_network(u'1.1.1.0/24')
Charles Chan76128b62017-03-27 20:28:14 -0700558
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700559 for router in self.routers.values():
560 # Add iBGP sessions to ONOS nodes
561 for onosIp in onosIps:
562 router.neighbors.append({'address':onosIp, 'as':asNum, 'port':2000})
Charles Chan76128b62017-03-27 20:28:14 -0700563
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700564 # Add iBGP sessions to other BGP speakers
565 for i, router2 in self.routers.items():
566 if router == router2:
567 continue
Jonathan Harte6b897f2017-01-24 17:09:58 -0800568 cpIpBase = self.num*10
569 ip = AutonomousSystem.getIthAddress(self.internalPeeringSubnet, cpIpBase+i)
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700570 router.neighbors.append({'address':ip.ip, 'as':asNum})
Charles Chan76128b62017-03-27 20:28:14 -0700571
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700572 def build(self, topology, connectAtSwitch, controlSwitch):
Charles Chan76128b62017-03-27 20:28:14 -0700573
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700574 natIp = AutonomousSystem.getLastAddress(self.internalPeeringSubnet)
Charles Chan76128b62017-03-27 20:28:14 -0700575
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700576 for i, router in self.routers.items():
Jonathan Harte6b897f2017-01-24 17:09:58 -0800577 num = SdnAutonomousSystem.routerIdx
578 SdnAutonomousSystem.routerIdx += 1
579 name = 'bgp%s' % num
Charles Chan76128b62017-03-27 20:28:14 -0700580
Jonathan Harte6b897f2017-01-24 17:09:58 -0800581 cpIpBase = self.num*10
582 ip = AutonomousSystem.getIthAddress(self.internalPeeringSubnet, cpIpBase+i)
Charles Chan76128b62017-03-27 20:28:14 -0700583
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700584 eth0 = { 'ipAddrs' : [ str(ip) ] }
585 if self.peerIntfConfig is not None:
586 eth1 = self.peerIntfConfig
587 else:
588 nativeAddresses = router.interfaces[1].addressesByVlan.pop(None, [])
Charles Chan76128b62017-03-27 20:28:14 -0700589 eth1 = [{ 'mac':'00:00:00:00:00:%02x' % num,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700590 'ipAddrs' : nativeAddresses }]
Charles Chan76128b62017-03-27 20:28:14 -0700591
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700592 for vlan, addresses in router.interfaces[1].addressesByVlan.items():
593 eth1.append({'vlan':vlan,
Jonathan Harte6b897f2017-01-24 17:09:58 -0800594 'mac':'00:00:00:%02x:%02x:00' % (num, vlan),
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700595 'ipAddrs':addresses})
Charles Chan76128b62017-03-27 20:28:14 -0700596
597
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700598 intfs = { '%s-eth0' % name : eth0,
599 '%s-eth1' % name : eth1 }
Charles Chan76128b62017-03-27 20:28:14 -0700600
601 bgp = topology.addHost( name, cls=BgpRouter, asNum=self.asNum,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700602 neighbors=router.neighbors,
Charles Chan76128b62017-03-27 20:28:14 -0700603 interfaces=intfs,
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700604 defaultRoute=str(natIp.ip),
Jonathan Hartfc0af772017-01-16 13:15:08 -0800605 fpm=self.onosIps[0] if self.withFpm else None )
Charles Chan76128b62017-03-27 20:28:14 -0700606
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700607 topology.addLink( bgp, controlSwitch )
608 topology.addLink( bgp, connectAtSwitch )
Charles Chan76128b62017-03-27 20:28:14 -0700609
610
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700611 if self.externalOnos:
Charles Chan76128b62017-03-27 20:28:14 -0700612 nat = topology.addHost('nat', cls=NAT,
613 ip='%s/%s' % (natIp.ip, self.internalPeeringSubnet.prefixlen),
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700614 subnet=str(self.internalPeeringSubnet), inNamespace=False);
615 topology.addLink(controlSwitch, nat)
616
Charles Chan76128b62017-03-27 20:28:14 -0700617
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700618def generateRoutes(baseRange, numRoutes, subnetSize=None):
619 baseNetwork = ip_network(baseRange)
Charles Chan76128b62017-03-27 20:28:14 -0700620
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700621 # We need to get at least 2 addresses out of each subnet, so the biggest
622 # prefix length we can have is /30
623 maxPrefixLength = baseNetwork.max_prefixlen - 2
Charles Chan76128b62017-03-27 20:28:14 -0700624
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700625 if subnetSize is not None:
626 return list(baseNetwork.subnets(new_prefix=subnetSize))
Charles Chan76128b62017-03-27 20:28:14 -0700627
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700628 trySubnetSize = baseNetwork.prefixlen + 1
629 while trySubnetSize <= maxPrefixLength and \
630 len(list(baseNetwork.subnets(new_prefix=trySubnetSize))) < numRoutes:
631 trySubnetSize += 1
Charles Chan76128b62017-03-27 20:28:14 -0700632
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700633 if trySubnetSize > maxPrefixLength:
634 raise Exception("Can't get enough routes from input parameters")
Charles Chan76128b62017-03-27 20:28:14 -0700635
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700636 return list(baseNetwork.subnets(new_prefix=trySubnetSize))[:numRoutes]
Charles Chan76128b62017-03-27 20:28:14 -0700637
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700638class RoutingCli( CLI ):
Charles Chan76128b62017-03-27 20:28:14 -0700639
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700640 """CLI command that can bring a host up or down. Useful for simulating router failure."""
Charles Chan76128b62017-03-27 20:28:14 -0700641
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700642 def do_host( self, line ):
643 args = line.split()
644 if len(args) != 2:
645 error( 'invalid number of args: host <host name> {up, down}\n' )
646 return
Charles Chan76128b62017-03-27 20:28:14 -0700647
Jonathan Hartce97e5b2016-04-19 01:41:31 -0700648 host = args[ 0 ]
649 command = args[ 1 ]
650 if host not in self.mn or self.mn.get( host ) not in self.mn.hosts:
651 error( 'invalid host: %s\n' % args[ 1 ] )
652 else:
653 if command == 'up':
654 op = 'up'
655 elif command == 'down':
656 op = 'down'
657 else:
658 error( 'invalid command: host <host name> {up, down}\n' )
659 return
660
661 for intf in self.mn.get( host ).intfList( ):
662 intf.link.intf1.ifconfig( op )
663 intf.link.intf2.ifconfig( op )