def killprocs(patterns, timeout=10): """Reliably terminate processes matching a pattern (including args)""" # Try clean kill for p in patterns: mnclean.sh('pkill -SIGINT -f %s' % p) # Make sure they are gone t = 0 to_be_killed = {p: True for p in patterns} while any(to_be_killed.values()) or t >= timeout: for p in patterns: try: pids = check_output(['pgrep', '-f', p]) except CalledProcessError: pids = '' if not pids: log.info(p) to_be_killed[p] = False time.sleep(.5) t += .5 # Last resort for p in patterns: if to_be_killed[p]: log.info(p) mnclean.killprocs(p)
def launch_network(k=4, bw=10, ip_alias=True, fair_queues=False, cli=False): signal.signal(signal.SIGTERM, signal_term_handler) # Cleanup the network cleanup() sh("killall ospfd zebra getLoads.py nc") # Remove tmp files and old namespaces subprocess.call(['rm', '/tmp/*.log', '/tmp/*.pid', '/tmp/mice*']) subprocess.call(['rm', '/var/run/netns/*']) # Flush root namespace mangle table subprocess.call(["iptables", "-t", "mangle" ,"-F"]) subprocess.call(["iptables", "-t", "mangle" ,"-X"]) # Topology topo = FatTree(k=k, sflow=False, ovs_switches=False) # Interfaces if fair_queues: print("*** Using FairQueues at the network interfaces") intf = custom(DCTCIntf, bw=bw) else: print("*** Using normal pFIFO queues at the network interfaces") intf = custom(PrioFifoIntf, bw=bw) # Network net = IPNet(topo=topo, debug=_lib.DEBUG_FLAG, intf=intf) # Save the TopoDB object TopologyDB(net=net).save(cfg.DB_path) # Start the network net.start() # Setup hash seeds setupHashSeeds(topo) # Start intreface collectors startCounterCollectors(topo, interval=1) if ip_alias: setupSecondaryIps(net) if cli: # Start the Fibbing CLI FibbingCLI(net) else: print("*** Looping forever. Press CTRL+C to quit") while True: try: time.sleep(2) except KeyboardInterrupt: print("*** KeyboardInterrupt catched! Shutting down") break net.stop() stopCounterCollectors(topo)
def setUp( self ): # verify that sshd is not running self.assertFalse( self.connected() ) # create public key pair for testing sh( 'rm -rf /tmp/ssh' ) sh( 'mkdir /tmp/ssh' ) sh( "ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa" ) sh( 'cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys' ) # run example with custom sshd args cmd = ( 'python -m mininet.examples.baresshd ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no' ) sh( cmd )
def setUp(self): # verify that sshd is not running self.assertFalse(self.connected()) # create public key pair for testing sh('rm -rf /tmp/ssh') sh('mkdir /tmp/ssh') sh("ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa") sh('cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys') # run example with custom sshd args cmd = ('python -m mininet.examples.baresshd ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no') sh(cmd)
def setUp(self): # verify that sshd is not running self.assertFalse(self.connected()) # create public key pair for testing sh('rm -rf /tmp/ssh') sh('mkdir /tmp/ssh') sh("ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa") sh('cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys') # run example with custom sshd args cmd = ('python -m mininet.examples.baresshd ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no') p = pexpect.spawn(cmd) runOpts = [ 'You may now ssh into h1 at 10.0.0.1', 'after 5 seconds, h1 is not listening on port 22', pexpect.EOF, pexpect.TIMEOUT ] while True: index = p.expect(runOpts) if index == 0: break else: self.tearDown() self.fail('sshd failed to start in host h1')
def cleanup_wifi(cls): """Clean up junk which might be left over from old runs; do fast stuff before slow dp and link removal!""" info("*** Removing WiFi module and Configurations\n") try: co("lsmod | grep mac80211_hwsim", shell=True) os.system('rmmod mac80211_hwsim') except: pass try: co("lsmod | grep ifb", shell=True) os.system('rmmod ifb') except: pass killprocs('hostapd') if glob.glob('*-mn-telemetry.txt'): os.system('rm *-mn-telemetry.txt') if glob.glob('*.apconf'): os.system('rm *.apconf') if glob.glob('*.staconf'): os.system('rm *.staconf') if glob.glob('*wifiDirect.conf'): os.system('rm *wifiDirect.conf') if glob.glob('*.nodeParams'): os.system('rm *.nodeParams') try: os.system('pkill -f \'wpa_supplicant -B -Dnl80211\'') except: pass try: os.system('pkill -f \'babeld\'') except: pass info("*** Killing wmediumd\n") sh('pkill wmediumd') sixlowpan.cleanup_6lowpan()
def setUp( self ): # create public key pair for testing sh( 'rm -rf /tmp/ssh' ) sh( 'mkdir /tmp/ssh' ) sh( "ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa" ) sh( 'cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys' ) cmd = ( 'python -m mininet.examples.sshd -D ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no -o UseDNS=no -u0' ) # run example with custom sshd args self.net = pexpect.spawn( cmd ) self.net.expect( 'mininet>' )
def setUp(self): # create public key pair for testing sh('rm -rf /tmp/ssh') sh('mkdir /tmp/ssh') sh("ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa") sh('cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys') cmd = ('python -m mininet.examples.sshd -D ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no -o UseDNS=no -u0') # run example with custom sshd args self.net = pexpect.spawn(cmd) self.net.expect('mininet>')
def setUp(self): # create public key pair for testing sh("rm -rf /tmp/ssh") sh("mkdir /tmp/ssh") sh("ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa") sh("cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys") cmd = ( "python -m mininet.examples.sshd -D " "-o AuthorizedKeysFile=/tmp/ssh/authorized_keys " "-o StrictModes=no" ) # run example with custom sshd args self.net = pexpect.spawn(cmd) self.net.expect("mininet>")
def cleanup_wifi(cls): """Clean up junk which might be left over from old runs; do fast stuff before slow dp and link removal!""" info("*** Removing WiFi module and Configurations\n") try: co("lsmod | grep mac80211_hwsim", shell=True) os.system('rmmod mac80211_hwsim') except: pass try: co("lsmod | grep ifb", shell=True) os.system('rmmod ifb') except: pass killprocs('hostapd') if glob.glob("*.apconf"): os.system('rm *.apconf') if glob.glob("*.staconf"): os.system('rm *.staconf') if glob.glob("*wifiDirect.conf"): os.system('rm *wifiDirect.conf') if glob.glob("*.nodeParams"): os.system('rm *.nodeParams') try: os.system('pkill -f \'wpa_supplicant -B -Dnl80211\'') except: pass info("*** Killing wmediumd\n") sh('pkill wmediumd') sixlowpan.cleanup_6lowpan()
def createKeysAndCertificates(net, workDir): securityDir = "{}/security".format(workDir) if not os.path.exists(securityDir): os.mkdir(securityDir) # Create root certificate rootName = "/ndn" sh("ndnsec-keygen {} > {}/root.keys".format(rootName, securityDir)) sh("ndnsec-certgen -N {} -p {} {}/root.keys > {}/root.cert".format( rootName, rootName, securityDir, securityDir)) # Create necessary certificates for each site for host in net.hosts: nodeSecurityFolder = "{}/security".format(host.homeFolder) if not os.path.exists(nodeSecurityFolder): os.mkdir(nodeSecurityFolder) shutil.copyfile("{}/root.cert".format(securityDir), "{}/root.cert".format(nodeSecurityFolder)) # Create site certificate siteName = "/ndn/edu" siteKeyFile = "{}/site.keys".format(nodeSecurityFolder) siteCertFile = "{}/site.cert".format(nodeSecurityFolder) Nlsr.createKey(host, siteName, siteKeyFile) # Root key is in root namespace, must sign site key and then install on host sh("ndnsec-certgen -N {} -s {} -p {} {} > {}".format( siteName, rootName, siteName, siteKeyFile, siteCertFile)) host.cmd("ndnsec-cert-install -f {}".format(siteCertFile)) # Create operator certificate opName = "{}/%C1.Operator/op".format(siteName) opKeyFile = "{}/op.keys".format(nodeSecurityFolder) opCertFile = "{}/op.cert".format(nodeSecurityFolder) Nlsr.createKey(host, opName, opKeyFile) Nlsr.createCertificate(host, opName, opName, opKeyFile, opCertFile, signer=siteName) # Create router certificate routerName = "{}/%C1.Router/cs/{}".format(siteName, host.name) routerKeyFile = "{}/router.keys".format(nodeSecurityFolder) routerCertFile = "{}/router.cert".format(nodeSecurityFolder) Nlsr.createKey(host, routerName, routerKeyFile) Nlsr.createCertificate(host, routerName, routerName, routerKeyFile, routerCertFile, signer=opName)
def setUp( self ): # verify that sshd is not running self.assertFalse( self.connected() ) # create public key pair for testing sh( 'rm -rf /tmp/ssh' ) sh( 'mkdir /tmp/ssh' ) sh( "ssh-keygen -t rsa -P '' -f /tmp/ssh/test_rsa" ) sh( 'cat /tmp/ssh/test_rsa.pub >> /tmp/ssh/authorized_keys' ) # run example with custom sshd args cmd = ( 'python -m mininet.examples.baresshd ' '-o AuthorizedKeysFile=/tmp/ssh/authorized_keys ' '-o StrictModes=no' ) p = pexpect.spawn( cmd ) runOpts = [ 'You may now ssh into h1 at 10.0.0.1', 'after 5 seconds, h1 is not listening on port 22', pexpect.EOF, pexpect.TIMEOUT ] while True: index = p.expect( runOpts ) if index == 0: break else: self.tearDown() self.fail( 'sshd failed to start in host h1' )
def main(): args = get_args() #set logging level setLogLevel('info') #clean cleanup() if args.clean or args.only_clean: sh("rm -rf %s" % args.pcap_dir) sh("rm -rf %s" % args.log_dir) sh("rm -f %s" % "topology.db") if args.only_clean: return app = AppRunner(args.config, args.log_dir, args.pcap_dir, args.cli, args.quiet) app.run_app()
def createKeysAndCertificates(net, workDir): securityDir = "{}/security".format(workDir) if not os.path.exists(securityDir): os.mkdir(securityDir) # Create root certificate rootName = NETWORK sh("ndnsec-keygen {}".format( rootName)) # Installs a self-signed cert into the system sh("ndnsec-cert-dump -i {} > {}/root.cert".format( rootName, securityDir)) # Create necessary certificates for each site for host in net.hosts: nodeSecurityFolder = "{}/security".format(host.homeFolder) host.cmd("mkdir -p %s" % nodeSecurityFolder) # Create temp folders for remote nodes on this machine (localhost) to store site.key file # from RemoteNodes if not os.path.exists(nodeSecurityFolder) and isinstance( host, RemoteMixin) and host.isRemote: os.makedirs(nodeSecurityFolder) shutil.copyfile("{}/root.cert".format(securityDir), "{}/root.cert".format(nodeSecurityFolder)) # Create site certificate siteName = "{}{}-site".format(NETWORK, host.name) siteKeyFile = "{}/site.keys".format(nodeSecurityFolder) siteCertFile = "{}/site.cert".format(nodeSecurityFolder) Nlsr.createKey(host, siteName, siteKeyFile) # Copy siteKeyFile from remote for ndnsec-certgen if isinstance(host, RemoteMixin) and host.isRemote: login = "******".format(host.server) src = "{}:{}".format(login, siteKeyFile) dst = siteKeyFile scp(src, dst) # Root key is in root namespace, must sign site key and then install on host sh("ndnsec-certgen -s {} -r {} > {}".format( rootName, siteKeyFile, siteCertFile)) # Copy root.cert and site.cert from localhost to remote host if isinstance(host, RemoteMixin) and host.isRemote: login = "******".format(host.server) src = "{}/site.cert".format(nodeSecurityFolder) src2 = "{}/root.cert".format(nodeSecurityFolder) dst = "{}:/tmp/".format(login) scp(src, src2, dst) host.cmd("mv /tmp/*.cert {}".format(nodeSecurityFolder)) host.cmd("ndnsec-cert-install -f {}".format(siteCertFile)) # Create and install operator certificate opName = "{}/%C1.Operator/op".format(siteName) opKeyFile = "{}/op.keys".format(nodeSecurityFolder) opCertFile = "{}/op.cert".format(nodeSecurityFolder) Nlsr.createKey(host, opName, opKeyFile) Nlsr.createCertificate(host, siteName, opKeyFile, opCertFile) host.cmd("ndnsec-cert-install -f {}".format(opCertFile)) # Create and install router certificate routerName = "{}/%C1.Router/cs/{}".format(siteName, host.name) routerKeyFile = "{}/router.keys".format(nodeSecurityFolder) routerCertFile = "{}/router.cert".format(nodeSecurityFolder) Nlsr.createKey(host, routerName, routerKeyFile) Nlsr.createCertificate(host, opName, routerKeyFile, routerCertFile) host.cmd("ndnsec-cert-install -f {}".format(routerCertFile))
def __init__(self, conf_file, log_dir, pcap_dir, cli_enabled=True, quiet=False): """Initializes some attributes and reads the topology json. Args: conf_file (string): A json file which describes the mininet topology. switch_json (string): Path to a compiled p4 json to run in bmv2. log_dir (string): Path to a directory for storing logs. bmv2_exe (string): Path to the p4 behavioral model binary. cli_enabled (bool): Enable mininet CLI. pcap_dump (bool): Enable generation of pcap files for interfaces. quiet (bool): Disable script debug messages. """ self.quiet = quiet self.logger('Reading configuration file.') self.conf_file = conf_file if not os.path.isfile(conf_file): raise Exception("Configuration %s is not in the directory!" % conf_file) self.conf = load_conf(conf_file) self.cli_enabled = cli_enabled self.pcap_dir = pcap_dir self.log_dir = log_dir self.bmv2_exe = str(self.conf.get('switch', DEFAULT_SWITCH)) # Clean switches sh("killall %s" % self.bmv2_exe) # get configurations self.log_enabled = self.conf.get("enable_log", False) # Ensure that all the needed directories exist and are directories if self.log_enabled: if not os.path.isdir(self.log_dir): if os.path.exists(self.log_dir): raise Exception("'%s' exists and is not a directory!" % self.log_dir) os.mkdir(self.log_dir) self.pcap_dump = self.conf.get("pcap_dump", False) if self.pcap_dump: if not os.path.isdir(self.pcap_dir): if os.path.exists(self.pcap_dir): raise Exception("'%s' exists and is not a directory!" % self.pcap_dir) os.mkdir(self.pcap_dir) # load topology topology = self.conf.get('topology', False) if not topology: raise Exception("topology to create is not defined in %s" % self.conf) self.hosts = topology['hosts'] self.switches = topology['switches'] self.links = self.parse_links(topology['links']) os.environ['P4APP_LOGDIR'] = log_dir # Setting default builders self.app_topo = DefaultTopo self.app_controller = DefaultController self.app_topodb = DefaultTopoDB self.app_mininet = P4Mininet if self.conf.get('topo_module',None): self.app_topo = self.load_custom_object('topo_module') if self.conf.get('controller_module', None): self.app_controller = self.load_custom_object('controller_module') if self.conf.get('topodb_module', None): self.app_topodb = self.load_custom_object('topodb_module') if self.conf.get('mininet_module', None): self.app_mininet = self.load_custom_object('mininet_module')
def main(): args = get_args() #set logging level setLogLevel('info') #clean cleanup() #remove cli logs sh('find -type f -regex ".*cli_output.*" | xargs rm') if args.clean or args.clean_dir: sh("rm -rf %s" % args.pcap_dir) sh("rm -rf %s" % args.log_dir) sh('find -type f -regex ".*db" | xargs rm') sh('find -type f -regex ".*\(p4i\|p4rt\)" | xargs rm') #remove all the jsons that come from a p4 out = sh('find -type f -regex ".*p4"') p4_files = [x.split("/")[-1].strip() for x in out.split("\n") if x] for p4_file in p4_files: tmp = p4_file.replace("p4", "json") reg_str = ".*{}".format(tmp) sh('find -type f -regex {} | xargs rm -f'.format(reg_str)) if args.clean_dir: return app = AppRunner(args.config, args.log_dir, args.pcap_dir, args.cli, args.quiet) app.run_app()
def tearDown( self ): # kill the ssh process sh( "ps aux | grep 'ssh.*Banner' | awk '{ print $2 }' | xargs kill" ) cleanup() # remove public key pair sh( 'rm -rf /tmp/ssh' )
def tearDown(self): self.net.sendline("exit") self.net.wait() # remove public key pair sh("rm -rf /tmp/ssh")
def setup(self): print "Creating SSH keys" sh("mkdir -p /tmp/minindn") sh("rm -f /tmp/minindn/ssh_host_rsa_key") sh("ssh-keygen -q -t rsa -N '' -f /tmp/minindn/ssh_host_rsa_key") sh("rm -f /tmp/minindn/id_rsa") sh("ssh-keygen -q -t rsa -N '' -f /tmp/minindn/id_rsa") sh("cat /tmp/minindn/id_rsa.pub > /tmp/minindn/authorized_keys") sshd_cmd = ['/usr/sbin/sshd', '-q', '-o AuthorizedKeysFile=/tmp/minindn/authorized_keys', '-o HostKey=/tmp/minindn/ssh_host_rsa_key', '-o StrictModes=no'] for host in self.net.hosts: # Run SSH daemon host.cmd(sshd_cmd) # Create a wrapper script for ssh that uses the generated key as default SSH identity host.cmd("mkdir -p ~/bin") homedir = host.cmd("echo -n ${HOME}") ssh_wrapper = homedir + '/bin/ssh' with open(ssh_wrapper, 'w') as f: f.writelines([ '#!/bin/sh\n', 'exec /usr/bin/ssh -f -i /tmp/minindn/id_rsa -o StrictHostKeyChecking=no "$@"\n' ]) os.chmod(ssh_wrapper, 0755) host.cmd("export PATH=\"${HOME}/bin${PATH:+:}${PATH}\"") # Copy nfd configuration into default configuration location host.cmd("cp %s %s" % (host.nfd.confFile, "/usr/local/etc/ndn/nfd.conf")) if host.name == 'a': sh("cp -r %s %s" % ("integration-tests", homedir)) # Setup static routes between a and d self.net['a'].cmd("ip route add 192.168.3.0/24 via 192.168.2.3") self.net['d'].cmd("ip route add 192.168.2.0/24 via 192.168.3.2") # Enable IP forwarding on r self.net['r'].cmd("sysctl net.ipv4.ip_forward=1")
def kill_dhcp(self): output = re.findall('\d+', sh("netstat -uap | grep dhcpd | awk '{ print $6 }'")) if output: sh('kill %s' % output[0])
def main(): args = get_args() # set logging level setLogLevel('info') # clean cleanup() # remove cli logs sh('find -type f -regex ".*cli_output.*" | xargs rm') if args.clean or args.clean_dir: # removes first level pcap and log dirs sh("rm -rf %s" % args.pcap_dir) sh("rm -rf %s" % args.log_dir) # tries to recursively remove all pcap and log dirs if they are named 'log' and 'pcap' sh('find -type d -regex ".*pcap" | xargs rm -rf') sh('find -type d -regex ".*log" | xargs rm -rf') # removes topologies files sh('find -type f -regex ".*db" | xargs rm') # remove compiler outputs sh('find -type f -regex ".*\(p4i\|p4rt\)" | xargs rm') # remove all the jsons that come from a p4 out = sh('find -type f -regex ".*p4"') p4_files = [x.split("/")[-1].strip() for x in out.split("\n") if x] for p4_file in p4_files: tmp = p4_file.replace("p4", "json") reg_str = ".*{}".format(tmp) sh('find -type f -regex {} | xargs rm -f'.format(reg_str)) if args.clean_dir: return app = AppRunner(args.config, args.log_dir, args.pcap_dir, args.cli, args.quiet, args.empty_p4) app.run_app()
def tearDown(self): # kill the ssh process sh("ps aux | grep ssh |grep Banner| awk '{ print $2 }' | xargs kill") cleanup() # remove public key pair sh('rm -rf /tmp/ssh')
def createKeysAndCertificates(self): securityDir = '{}/security'.format(self.parameters['workDir']) if not os.path.exists(securityDir): os.mkdir(securityDir) rootName = self.network rootCertFile = '{}/root.cert'.format(securityDir) if not os.path.isfile(rootCertFile): # Create root certificate sh('ndnsec-keygen {}'.format(rootName)) # Installs a self-signed cert into the system sh('ndnsec-cert-dump -i {} > {}'.format(rootName, rootCertFile)) # Create necessary certificates for each site nodeSecurityFolder = '{}/security'.format(self.homeDir) self.node.cmd('mkdir -p {}'.format(nodeSecurityFolder)) # Create temp folders for remote nodes on this machine (localhost) to store site.key file # from RemoteNodes if not os.path.exists(nodeSecurityFolder) and \ isinstance(self.node, RemoteMixin) and self.node.isRemote: os.makedirs(nodeSecurityFolder) shutil.copyfile('{}/root.cert'.format(securityDir), '{}/root.cert'.format(nodeSecurityFolder)) # Create site certificate siteName = '{}{}-site'.format(self.network, self.node.name) siteKeyFile = '{}/site.keys'.format(nodeSecurityFolder) siteCertFile = '{}/site.cert'.format(nodeSecurityFolder) Nlsr.createKey(self.node, siteName, siteKeyFile) # Copy siteKeyFile from remote for ndnsec-certgen if isinstance(self.node, RemoteMixin) and self.node.isRemote: login = '******'.format(self.node.server) src = '{}:{}'.format(login, siteKeyFile) dst = siteKeyFile scp(src, dst) # Root key is in root namespace, must sign site key and then install on host sh('ndnsec-certgen -s {} -r {} > {}'.format(rootName, siteKeyFile, siteCertFile)) # Copy root.cert and site.cert from localhost to remote host if isinstance(self.node, RemoteMixin) and self.node.isRemote: login = '******'.format(self.node.server) src = '{}/site.cert'.format(nodeSecurityFolder) src2 = '{}/root.cert'.format(nodeSecurityFolder) dst = '{}:/tmp/'.format(login) scp(src, src2, dst) self.node.cmd('mv /tmp/*.cert {}'.format(nodeSecurityFolder)) self.node.cmd('ndnsec-cert-install -f {}'.format(siteCertFile)) # Create and install operator certificate opName = '{}/%C1.Operator/op'.format(siteName) opKeyFile = '{}/op.keys'.format(nodeSecurityFolder) opCertFile = '{}/op.cert'.format(nodeSecurityFolder) Nlsr.createKey(self.node, opName, opKeyFile) Nlsr.createCertificate(self.node, siteName, opKeyFile, opCertFile) self.node.cmd('ndnsec-cert-install -f {}'.format(opCertFile)) # Create and install router certificate routerName = '{}/%C1.Router/cs/{}'.format(siteName, self.node.name) routerKeyFile = '{}/router.keys'.format(nodeSecurityFolder) routerCertFile = '{}/router.cert'.format(nodeSecurityFolder) Nlsr.createKey(self.node, routerName, routerKeyFile) Nlsr.createCertificate(self.node, opName, routerKeyFile, routerCertFile) self.node.cmd('ndnsec-cert-install -f {}'.format(routerCertFile))
def tearDown( self ): self.net.sendline( 'exit' ) self.net.wait() # remove public key pair sh( 'rm -rf /tmp/ssh' )
def cleanUpOVS( cls ): "Clean up leftover ovsdb-server/ovs-vswitchd processes" info( '*** Shutting down extra ovsdb-server/ovs-vswitchd processes\n' ) sh( 'pkill -f mn.pid' )
def tearDown(self): self.net.sendline('exit') self.net.wait() # remove public key pair sh('rm -rf /tmp/ssh')
def cleanup(cls): """Clean up junk which might be left over from old runs; do fast stuff before slow dp and link removal!""" Cleanup_nm_wifi.cleanup_wifi() info("**** Removing excess controllers/ofprotocols/ofdatapaths/" "pings/noxes\n") zombies = ('controller ofprotocol ofdatapath ping nox_core' 'lt-nox_core ovs-openflowd ovs-controller' 'ovs-testcontroller udpbwtest mnexec ivs ryu-manager') # Note: real zombie processes can't actually be killed, since they # are already (un)dead. Then again, # you can't connect to them either, so they're mostly harmless. # Send SIGTERM first to give processes a chance to shutdown cleanly. sh('killall ' + zombies + ' 2> /dev/null') time.sleep(1) sh('killall -9 ' + zombies + ' 2> /dev/null') # And kill off sudo mnexec sh('pkill -9 -f "sudo mnexec"') info("*** Removing junk from /tmp\n") sh('rm -f /tmp/vconn* /tmp/vlogs* /tmp/*.out /tmp/*.log') info("*** Removing old X11 tunnels\n") cleanUpScreens() info("*** Removing excess kernel datapaths\n") dps = sh("ps ax | egrep -o 'dp[0-9]+' | sed 's/dp/nl:/'").splitlines() for dp in dps: if dp: sh('dpctl deldp ' + dp) info("*** Removing OVS datapaths\n") dps = sh("ovs-vsctl --timeout=1 list-br").strip().splitlines() if dps: sh("ovs-vsctl " + " -- ".join("--if-exists del-br " + dp for dp in dps if dp)) # And in case the above didn't work... dps = sh("ovs-vsctl --timeout=1 list-br").strip().splitlines() for dp in dps: sh('ovs-vsctl del-br ' + dp) info("*** Removing all links of the pattern foo-ethX\n") links = sh( "ip link show | " "egrep -o '([-_.[:alnum:]]+-eth[[:digit:]]+)'").splitlines() # Delete blocks of links n = 1000 # chunk size for i in range(0, len(links), n): cmd = ';'.join('ip link del %s' % link for link in links[i:i + n]) sh('( %s ) 2> /dev/null' % cmd) if 'tap9' in sh('ip link show'): info("*** Removing tap9 - assuming it's from cluster edition\n") sh('ip link del tap9') info("*** Killing stale mininet node processes\n") killprocs('mininet:') info("*** Shutting down stale tunnels\n") killprocs('Tunnel=Ethernet') killprocs('.ssh/mn') sh('rm -f ~/.ssh/mn/*') # Call any additional cleanup code if necessary for callback in cls.callbacks: callback() # Containernet should also cleanup pending Docker cmd = "docker rm -f $( docker ps --filter 'label=com.containernet' -a -q)" call(cmd, shell=True, stdout=open(os.devnull, 'wb'), stderr=open(os.devnull, 'wb')) # cleanup any remaining iptables rules from external SAPs with NAT # we use iptc module to iterate through the loops, but due to a bug, we cannot use iptc to delete the rules # we rely on iptables CLI to delete the found rules info("*** Removing SAP NAT rules\n") table = iptc.Table(iptc.Table.NAT) chain = iptc.Chain(table, 'POSTROUTING') for rule in chain.rules: if SAP_PREFIX in str(rule.out_interface): src_CIDR = str( ipaddress.IPv4Network(u'{}'.format(str(rule.src)))) rule0_ = "iptables -t nat -D POSTROUTING ! -o {0} -s {1} -j MASQUERADE".\ format(rule.out_interface.strip('!'), src_CIDR) p = Popen(shlex.split(rule0_)) p.communicate() info("delete NAT rule from SAP: {1} - {0} - {2}\n".format( rule.out_interface, rule.in_interface, src_CIDR)) table = iptc.Table(iptc.Table.FILTER) chain = iptc.Chain(table, 'FORWARD') for rule in chain.rules: src_CIDR = str(ipaddress.IPv4Network(u'{}'.format(str(rule.src)))) if SAP_PREFIX in str(rule.out_interface): rule1_ = "iptables -D FORWARD -o {0} -j ACCEPT".format( rule.out_interface) p = Popen(shlex.split(rule1_)) p.communicate() info("delete FORWARD rule from SAP: {1} - {0} - {2}\n".format( rule.out_interface, rule.in_interface, src_CIDR)) if SAP_PREFIX in str(rule.in_interface): rule2_ = "iptables -D FORWARD -i {0} -j ACCEPT".format( rule.in_interface) p = Popen(shlex.split(rule2_)) p.communicate() info("delete FORWARD rule from SAP: {1} - {0} - {2}\n".format( rule.out_interface, rule.in_interface, src_CIDR)) info("*** Cleanup complete.\n")