blob: 621b372ed950d76dc7816a5c6e69560faa7e7858 [file] [log] [blame]
Jonghwan Hyun3731d6a2017-10-19 11:59: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
12import os
13
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
25 self.cmd('ip -4 addr flush dev %s' % self.defaultIntf())
26 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 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
48class Router(Host):
49
50 """An L3 router.
51 Configures the Linux kernel for L3 forwarding and supports rich interface
52 configuration of IP addresses, MAC addresses and VLANs."""
53
54 def __init__(self, name, interfaces, *args, **kwargs):
55 super(Router, self).__init__(name, **kwargs)
56
57 self.interfaces = interfaces
58
59 def config(self, **kwargs):
60 super(Host, self).config(**kwargs)
61
62 self.cmd('sysctl net.ipv4.ip_forward=1')
63 self.cmd('sysctl net.ipv4.conf.all.rp_filter=0')
64 self.cmd('sysctl net.ipv6.conf.all.forwarding=1')
65
66 for intf, configs in self.interfaces.items():
67 self.cmd('ip -4 addr flush dev %s' % intf)
68 self.cmd( 'sysctl net.ipv4.conf.%s.rp_filter=0' % intf )
69
70 if not isinstance(configs, list):
71 configs = [configs]
72
73 for attrs in configs:
74 # Configure the vlan if there is one
75 if 'vlan' in attrs:
76 vlanName = '%s.%s' % (intf, attrs['vlan'])
77 self.cmd('ip link add link %s name %s type vlan id %s' %
78 (intf, vlanName, attrs['vlan']))
79 self.cmd('ip link set %s up' % vlanName)
80 addrIntf = vlanName
81 else:
82 addrIntf = intf
83
84 # 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):
93
94 """Runs Quagga to create a router that can speak routing protocols."""
95
96 binDir = '/usr/lib/quagga'
97 logDir = '/var/log/quagga'
98
99 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)
106
107 self.protocols = protocols
108 self.fpm = fpm
109
110 for p in self.protocols:
111 p.setQuaggaRouter(self)
112
113 self.runDir = runDir
114 self.defaultRoute = defaultRoute
115
116 # 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
126 self.zebraConfFile = zebraConfFile
127 if (self.zebraConfFile is None):
128 self.zebraConfFile = '%s/zebrad%s.conf' % (self.runDir, self.name)
129 self.generateZebra()
130
131 self.socket = '%s/zebra%s.api' % (self.runDir, self.name)
132
133 self.zebraPidFile = '%s/zebra%s.pid' % (self.runDir, self.name)
134
135 def generateZebra(self):
136 configFile = open(self.zebraConfFile, 'w+')
137 configFile.write('log file %s/zebrad%s.log\n' % (QuaggaRouter.logDir, self.name))
138 configFile.write('hostname zebra-%s\n' % self.name)
139 configFile.write('password %s\n' % 'quagga')
140 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))
Andreas Pantelopoulos971c91d2018-02-12 11:28:10 -0800149 print("\n")
150 print('%s/zebra -d -f %s -z %s -i %s'
151 % (QuaggaRouter.binDir, self.zebraConfFile, self.socket, self.zebraPidFile))
Jonghwan Hyun3731d6a2017-10-19 11:59:31 -0700152
153 for p in self.protocols:
154 p.config(**kwargs)
155
156 if self.defaultRoute:
157 self.cmd('ip route add default via %s' % self.defaultRoute)
158
159 def terminate(self, **kwargs):
160 self.cmd("ps ax | grep '%s' | awk '{print $1}' | xargs kill"
161 % (self.socket))
162
163 for p in self.protocols:
164 p.terminate(**kwargs)
165
166 super(QuaggaRouter, self).terminate()
167
168class Protocol(object):
169
170 """Base abstraction of a protocol that the QuaggaRouter can run."""
171
172 def setQuaggaRouter(self, qr):
173 self.qr = qr
174
175 def config(self, **kwargs):
176 pass
177
178 def terminate(self, **kwargs):
179 pass
180
181class BgpProtocol(Protocol):
182
183 """Configures and runs the BGP protocol in Quagga."""
184
185 def __init__(self, configFile=None, asNum=None, neighbors=[], routes=[], *args, **kwargs):
186 self.configFile = configFile
187
188 self.asNum = asNum
189 self.neighbors = neighbors
190 self.routes = routes
191
192 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()
196
197 bgpdPidFile = '%s/bgpd%s.pid' % (self.qr.runDir, self.qr.name)
198
199 self.qr.cmd('%s/bgpd -d -f %s -z %s -i %s'
200 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, bgpdPidFile))
201
202 def generateConfig(self):
203 conf = ConfigurationWriter(self.configFile)
204
205 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]
212
213 conf.writeLine('log file %s/bgpd%s.log' % (QuaggaRouter.logDir, self.qr.name))
214 conf.writeLine('hostname bgp-%s' % self.qr.name)
215 conf.writeLine('password %s' % 'quagga')
216 conf.writeLine('!')
217 conf.writeLine('router bgp %s' % self.asNum)
218
219 conf.indent()
220
221 conf.writeLine('bgp router-id %s' % getRouterId(self.qr.interfaces))
222 conf.writeLine('timers bgp %s' % '3 9')
223 conf.writeLine('!')
224
225 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('!')
233
234 for route in self.routes:
235 conf.writeLine('network %s' % route)
236
237 conf.close()
238
239class OspfProtocol(Protocol):
240
241 """Configures and runs the OSPF protocol in Quagga."""
242
243 def __init__(self, configFile=None, *args, **kwargs):
244 self.configFile = configFile
245
246 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()
250
251 ospfPidFile = '%s/ospf%s.pid' % (self.qr.runDir, self.qr.name)
252
253 self.qr.cmd('%s/ospfd -d -f %s -z %s -i %s'
254 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, ospfPidFile))
255
256 def generateConfig(self):
257 conf = ConfigurationWriter(self.configFile)
258
259 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]
266
267 conf.writeLine('hostname ospf-%s' % self.qr.name)
268 conf.writeLine('password %s' % 'hello')
269 conf.writeLine('!')
270 conf.writeLine('router ospf')
271
272 conf.indent()
273
274 conf.writeLine('ospf router-id %s' % getRouterId(self.qr.interfaces))
275 conf.writeLine('!')
276
277 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)
282
283 conf.close()
284
285class PimProtocol(Protocol):
286
287 """Configures and runs the PIM protcol in Quagga."""
288
289 def __init__(self, configFile=None, *args, **kwargs):
290 self.configFile = configFile
291
292 def config(self, **kwargs):
293 pimPidFile = '%s/pim%s.pid' % (self.qr.runDir, self.qr.name)
294
295 self.qr.cmd('%s/pimd -Z -d -f %s -z %s -i %s'
296 % (QuaggaRouter.binDir, self.configFile, self.qr.socket, pimPidFile))
297
298class ConfigurationWriter(object):
299
300 """Utility class for writing a configuration file."""
301
302 def __init__(self, filename):
303 self.filename = filename
304 self.indentValue = 0
305
306 self.configFile = open(self.filename, 'w+')
307
308 def indent(self):
309 self.indentValue += 1
310
311 def unindent(self):
312 if (self.indentValue > 0):
313 self.indentValue -= 1
314
315 def write(self, string):
316 self.configFile.write(string)
317
318 def writeLine(self, string):
319 intentStr = ''
320 for _ in range(0, self.indentValue):
321 intentStr += ' '
322 self.write('%s%s\n' % (intentStr, string))
323
324 def close(self):
325 self.configFile.close()
326
327# Backward compatibility for BGP-only use case
328class BgpRouter(QuaggaRouter):
329
330 """Quagga router running the BGP protocol."""
331
332 def __init__(self, name, interfaces,
333 asNum=0, neighbors=[], routes=[],
334 defaultRoute=None,
335 quaggaConfFile=None,
336 zebraConfFile=None,
337 *args, **kwargs):
338 bgp = BgpProtocol(configFile=quaggaConfFile, asNum=asNum, neighbors=neighbors, routes=routes)
339
340 super(BgpRouter, self).__init__(name, interfaces,
341 zebraConfFile=zebraConfFile,
342 defaultRoute=defaultRoute,
343 protocols=[bgp],
344 *args, **kwargs)
345
346class RouterData(object):
347
348 """Internal data structure storing information about a router."""
349
350 def __init__(self, index):
351 self.index = index
352 self.neighbors = []
353 self.interfaces = {}
354 self.switches = []
355
356 def addNeighbor(self, theirAddress, theirAsNum):
357 self.neighbors.append({'address': theirAddress.ip, 'as': theirAsNum})
358
359 def addInterface(self, intf, vlan, address):
360 if intf not in self.interfaces:
361 self.interfaces[intf] = InterfaceData(intf)
362
363 self.interfaces[intf].addAddress(vlan, address)
364
365 def setSwitch(self, switch):
366 self.switches.append(switch)
367
368class InterfaceData(object):
369
370 """Internal data structure storing information about an interface."""
371
372 def __init__(self, number):
373 self.number = number
374 self.addressesByVlan = {}
375
376 def addAddress(self, vlan, address):
377 if vlan not in self.addressesByVlan:
378 self.addressesByVlan[vlan] = []
379
380 self.addressesByVlan[vlan].append(address.with_prefixlen)
381
382class RoutedNetwork(object):
383
384 """Creates a host behind a router. This is common boilerplate topology
385 segment in routed networks."""
386
387 @staticmethod
388 def build(topology, router, hostName, networks):
389 # There's a convention that the router's addresses are already set up,
390 # and it has the last address in the network.
391
392 def getFirstAddress(network):
393 return '%s/%s' % (network[1], network.prefixlen)
394
395 defaultRoute = AutonomousSystem.getLastAddress(networks[0]).ip
396
397 host = topology.addHost(hostName, cls=RoutedHost,
398 ips=[getFirstAddress(network) for network in networks],
399 gateway=defaultRoute)
400
401 topology.addLink(router, host)
402
403class AutonomousSystem(object):
404
405 """Base abstraction of an autonomous system, which implies some internal
406 topology and connections to other topology elements (switches/other ASes)."""
407
408 psIdx = 1
409
410 def __init__(self, asNum, numRouters):
411 self.asNum = asNum
412 self.numRouters = numRouters
413 self.routers = {}
414 for i in range(1, numRouters + 1):
415 self.routers[i] = RouterData(i)
416
417 self.routerNodes = {}
418
419 self.neighbors = []
420 self.vlanAddresses = {}
421
422 def peerWith(self, myRouter, myAddress, theirAddress, theirAsNum, intf=1, vlan=None):
423 router = self.routers[myRouter]
424
425 router.addInterface(intf, vlan, myAddress)
426 router.addNeighbor(theirAddress, theirAsNum)
427
428 def getRouter(self, i):
429 return self.routerNodes[i]
430
431 @staticmethod
432 def generatePeeringAddresses():
433 network = ip_network(u'10.0.%s.0/24' % AutonomousSystem.psIdx)
434 AutonomousSystem.psIdx += 1
435
436 return ip_interface('%s/%s' % (network[1], network.prefixlen)), \
437 ip_interface('%s/%s' % (network[2], network.prefixlen))
438
439 @staticmethod
440 def addPeering(as1, as2, router1=1, router2=1, intf1=1, intf2=1, address1=None, address2=None, useVlans=False):
441 vlan = AutonomousSystem.psIdx if useVlans else None
442
443 if address1 is None or address2 is None:
444 (address1, address2) = AutonomousSystem.generatePeeringAddresses()
445
446 as1.peerWith(router1, address1, address2, as2.asNum, intf=intf1, vlan=vlan)
447 as2.peerWith(router2, address2, address1, as1.asNum, intf=intf2, vlan=vlan)
448
449 @staticmethod
450 def getLastAddress(network):
451 return ip_interface(network.network_address + network.num_addresses - 2)
452
453 @staticmethod
454 def getIthAddress(network, i):
455 return ip_interface('%s/%s' % (network[i], network.prefixlen))
456
457class BasicAutonomousSystem(AutonomousSystem):
458
459 """Basic autonomous system containing one host and one or more routers
460 which peer with other ASes."""
461
462 def __init__(self, num, routes, numRouters=1):
463 super(BasicAutonomousSystem, self).__init__(65000+num, numRouters)
464 self.num = num
465 self.routes = routes
466
467 def addLink(self, switch, router=1):
468 self.routers[router].setSwitch(switch)
469
470 def build(self, topology):
471 self.addRouterAndHost(topology)
472
473 def addRouterAndHost(self, topology):
474
475 # TODO implementation is messy and needs to be cleaned up
476
477 intfs = {}
478
479 router = self.routers[1]
480 for i, router in self.routers.items():
481
482 # routerName = 'r%i%i' % (self.num, i)
483 routerName = 'r%i' % self.num
484 if not i == 1:
485 routerName += ('%i' % i)
486
487 hostName = 'h%i' % self.num
488
489 for j, interface in router.interfaces.items():
490 nativeAddresses = interface.addressesByVlan.pop(None, [])
491 peeringIntf = [{'mac' : '00:00:%02x:00:%02x:%02x' % (self.num, i, j),
492 'ipAddrs' : nativeAddresses}]
493
494 for vlan, addresses in interface.addressesByVlan.items():
495 peeringIntf.append({'vlan': vlan,
496 'mac': '00:00:%02x:%02x:%02x:%02x' % (self.num, vlan, i, j),
497 'ipAddrs': addresses})
498
499 intfs.update({'%s-eth%s' % (routerName, j-1) : peeringIntf})
500
501 # Only add the host to the first router for now
502 if i == 1:
503 internalAddresses = []
504 for route in self.routes:
505 internalAddresses.append('%s/%s' % (AutonomousSystem.getLastAddress(route).ip, route.prefixlen))
506
507 internalIntf = {'ipAddrs' : internalAddresses}
508
509 # This is the configuration of the next interface after all the peering interfaces
510 intfs.update({'%s-eth%s' % (routerName, len(router.interfaces.keys())) : internalIntf})
511
512 routerNode = topology.addHost(routerName,
513 asNum=self.asNum, neighbors=router.neighbors,
514 routes=self.routes,
515 cls=BgpRouter, interfaces=intfs)
516
517 self.routerNodes[i] = routerNode
518
519 for switch in router.switches:
520 topology.addLink(switch, routerNode)
521
522 # Only add the host to the first router for now
523 if i == 1:
524 defaultRoute = internalAddresses[0].split('/')[0]
525
526 host = topology.addHost(hostName, cls=RoutedHost,
527 ips=[self.getFirstAddress(route) for route in self.routes],
528 gateway=defaultRoute)
529
530 topology.addLink(routerNode, host)
531
532 # def getLastAddress(self, network):
533 # return ip_address(network.network_address + network.num_addresses - 2)
534
535 def getFirstAddress(self, network):
536 return '%s/%s' % (network[1], network.prefixlen)
537
538# TODO fix this AS - doesn't currently work
539class RouteServerAutonomousSystem(BasicAutonomousSystem):
540
541 def __init__(self, routerAddress, *args, **kwargs):
542 BasicAutonomousSystem.__init__(self, *args, **kwargs)
543
544 self.routerAddress = routerAddress
545
546 def build(self, topology, connectAtSwitch):
547
548 switch = topology.addSwitch('as%isw' % self.num, cls=OVSBridge)
549
550 self.addRouterAndHost(topology, self.routerAddress, switch)
551
552 rsName = 'rs%i' % self.num
553 routeServer = topology.addHost(rsName,
554 self.asnum, self.neighbors,
555 cls=BgpRouter,
556 interfaces={'%s-eth0' % rsName : {'ipAddrs': [self.peeringAddress]}})
557
558 topology.addLink(routeServer, switch)
559 topology.addLink(switch, connectAtSwitch)
560
561class SdnAutonomousSystem(AutonomousSystem):
562
563 """Runs the internal BGP speakers needed for ONOS routing apps like
564 SDN-IP."""
565
566 routerIdx = 1
567
568 def __init__(self, onosIps, num=1, numBgpSpeakers=1, asNum=65000, externalOnos=True,
569 peerIntfConfig=None, withFpm=False):
570 super(SdnAutonomousSystem, self).__init__(asNum, numBgpSpeakers)
571 self.onosIps = onosIps
572 self.num = num
573 self.numBgpSpeakers = numBgpSpeakers
574 self.peerIntfConfig = peerIntfConfig
575 self.withFpm = withFpm
576 self.externalOnos = externalOnos
577 self.internalPeeringSubnet = ip_network(u'1.1.1.0/24')
578
579 for router in self.routers.values():
580 # Add iBGP sessions to ONOS nodes
581 for onosIp in onosIps:
582 router.neighbors.append({'address': onosIp, 'as': asNum, 'port': 2000})
583
584 # Add iBGP sessions to other BGP speakers
585 for i, router2 in self.routers.items():
586 if router == router2:
587 continue
588 cpIpBase = self.num*10
589 ip = AutonomousSystem.getIthAddress(self.internalPeeringSubnet, cpIpBase+i)
590 router.neighbors.append({'address': ip.ip, 'as': asNum})
591
592 def build(self, topology, connectAtSwitch, controlSwitch):
593
594 natIp = AutonomousSystem.getLastAddress(self.internalPeeringSubnet)
595
596 for i, router in self.routers.items():
597 num = SdnAutonomousSystem.routerIdx
598 SdnAutonomousSystem.routerIdx += 1
599 name = 'bgp%s' % num
600
601 cpIpBase = self.num*10
602 ip = AutonomousSystem.getIthAddress(self.internalPeeringSubnet, cpIpBase+i)
603
604 eth0 = { 'ipAddrs' : [ str(ip) ] }
605 if self.peerIntfConfig is not None:
606 eth1 = self.peerIntfConfig
607 else:
608 nativeAddresses = router.interfaces[1].addressesByVlan.pop(None, [])
609 eth1 = [{ 'mac': '00:00:00:00:00:%02x' % num,
610 'ipAddrs' : nativeAddresses }]
611
612 for vlan, addresses in router.interfaces[1].addressesByVlan.items():
613 eth1.append({'vlan': vlan,
614 'mac': '00:00:00:%02x:%02x:00' % (num, vlan),
615 'ipAddrs': addresses})
616
617 intfs = { '%s-eth0' % name : eth0,
618 '%s-eth1' % name : eth1 }
619
620 bgp = topology.addHost( name, cls=BgpRouter, asNum=self.asNum,
621 neighbors=router.neighbors,
622 interfaces=intfs,
623 defaultRoute=str(natIp.ip),
624 fpm=self.onosIps[0] if self.withFpm else None )
625
626 topology.addLink( bgp, controlSwitch )
627 topology.addLink( bgp, connectAtSwitch )
628
629 if self.externalOnos:
630 nat = topology.addHost('nat', cls=NAT,
631 ip='%s/%s' % (natIp.ip, self.internalPeeringSubnet.prefixlen),
632 subnet=str(self.internalPeeringSubnet), inNamespace=False)
633 topology.addLink(controlSwitch, nat)
634
635def generateRoutes(baseRange, numRoutes, subnetSize=None):
636 baseNetwork = ip_network(baseRange)
637
638 # We need to get at least 2 addresses out of each subnet, so the biggest
639 # prefix length we can have is /30
640 maxPrefixLength = baseNetwork.max_prefixlen - 2
641
642 if subnetSize is not None:
643 return list(baseNetwork.subnets(new_prefix=subnetSize))
644
645 trySubnetSize = baseNetwork.prefixlen + 1
646 while trySubnetSize <= maxPrefixLength and \
647 len(list(baseNetwork.subnets(new_prefix=trySubnetSize))) < numRoutes:
648 trySubnetSize += 1
649
650 if trySubnetSize > maxPrefixLength:
651 raise Exception("Can't get enough routes from input parameters")
652
653 return list(baseNetwork.subnets(new_prefix=trySubnetSize))[:numRoutes]
654
655class RoutingCli( CLI ):
656
657 """CLI command that can bring a host up or down. Useful for simulating router failure."""
658
659 def do_host( self, line ):
660 args = line.split()
661 if len(args) != 2:
662 error( 'invalid number of args: host <host name> {up, down}\n' )
663 return
664
665 host = args[ 0 ]
666 command = args[ 1 ]
667 if host not in self.mn or self.mn.get( host ) not in self.mn.hosts:
668 error( 'invalid host: %s\n' % args[ 1 ] )
669 else:
670 if command == 'up':
671 op = 'up'
672 elif command == 'down':
673 op = 'down'
674 else:
675 error( 'invalid command: host <host name> {up, down}\n' )
676 return
677
678 for intf in self.mn.get( host ).intfList( ):
679 intf.link.intf1.ifconfig( op )
680 intf.link.intf2.ifconfig( op )