Remove old Drivers
diff --git a/README.md b/README.md
index bd2fa6f..b29c092 100644
--- a/README.md
+++ b/README.md
@@ -24,15 +24,11 @@
Dependencies
------------
-1. Zookeeper
+1. ONOS
-2. Cassandra
+2. Mininet
-3. ONOS
-
-4. Mininet
-
-5. Install python packages configObj and pexpect. they can be installed as :
+3. Install python packages configObj and pexpect. they can be installed as :
$ sudo pip install configObj
diff --git a/TestON/drivers/common/api/onosapi/__init__.py b/TestON/drivers/common/api/onosapi/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/TestON/drivers/common/api/onosapi/__init__.py
+++ /dev/null
diff --git a/TestON/drivers/common/cli/cassandraclidriver.py b/TestON/drivers/common/cli/cassandraclidriver.py
deleted file mode 100644
index bad8c4e..0000000
--- a/TestON/drivers/common/cli/cassandraclidriver.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/env python
-'''
-Created on 31-May-2013
-
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
-
-
- TestON is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
-
- TestON is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-
-CassandraCliDriver is the basic driver which will handle the Cassandra functions
-'''
-
-import pexpect
-import struct
-import fcntl
-import os
-import signal
-import re
-import sys
-import core.teston
-import time
-
-sys.path.append("../")
-from drivers.common.clidriver import CLI
-
-class CassandraCliDriver(CLI):
- '''
- CassandraCliDriver is the basic driver which will handle the Cassandra's functions
- '''
- def __init__(self):
- super(CLI, self).__init__()
- self.handle = self
- self.wrapped = sys.modules[__name__]
-
- def connect(self, **connectargs):
- # Here the main is the TestON instance after creating all the log handles.
- self.port = None
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- self.handle = super(CassandraCliDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
-
- self.ssh_handle = self.handle
- if self.handle :
- #self.start()
- return main.TRUE
- else :
- main.log.error(self.name + ": Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error(self.name + ": Failed to connect to the Onos system")
- return main.FALSE
-
-
- def start(self):
- '''
- This Function will start the Cassandra
- '''
- main.log.info(self.name + ": Starting Cassandra" )
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("~/ONOS/start-cassandra.sh start")
- self.handle.expect("start-cassandra.sh start")
- self.handle.expect("\$")
- response = self.handle.before + self.handle.after
- time.sleep(5)
- if re.search("Starting\scassandra(.*)", response):
- main.log.info(self.name + ": Cassandra Started ")
- return main.TRUE
- else:
- main.log.error(self.name + ": Failed to start Cassandra"+ response)
- return main.FALSE
-
- def status(self):
- '''
- This Function will return the Status of the Cassandra
- '''
- time.sleep(5)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- response = self.execute(cmd="~/ONOS/start-cassandra.sh status ",prompt="\d+\sinstance\sof\scassandra\srunning(.*)",timeout=10)
-
-
- #self.execute(cmd="\n",prompt="\$",timeout=10)
- #return response
-
- if re.search("0\sinstance\sof\scassandra\srunning(.*)",response) :
- main.log.info(self.name + ": Cassandra not running")
- return main.FALSE
- elif re.search("1\sinstance\sof\scassandra\srunning(.*)",response):
- main.log.warn(self.name + ": Cassandra Running")
- return main.TRUE
- elif re.search("\sinstance\sof\scassandra\srunning(.*)",response):
- main.log.warn(self.name + ": Multiple instances of Cassandra Running on the same machine!")
- #Known bug: Once ONOS starts the script shows 2 instances
- return main.TRUE
- else:
- main.log.warn(self.name + ": Cannot determine cassandra status")
- return main.False
-
- def stop(self):
- '''
- This Function will stop the Cassandra if it is Running
- '''
- self.execute(cmd="\n",prompt="\$",timeout=10)
- time.sleep(5)
- response = self.execute(cmd="~/ONOS/start-cassandra.sh stop ",prompt="Killed\sexisting\sprosess(.*)",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- if re.search("Killed\sexisting\sprosess(.*)",response):
- main.log.info(self.name + ": Cassandra Stopped")
- return main.TRUE
- else:
- main.log.warn(self.name + ": Cassndra is not Running")
- return main.FALSE
-
- def disconnect(self):
- '''
- Called at the end of the test to disconnect the ssh handle.
- '''
- response = ''
- if self.handle:
- self.handle.sendline("exit")
- self.handle.expect("closed")
- else :
- main.log.error(self.name + ": Connection failed to the host")
- response = main.FALSE
- return response
-
- def isup(self):
- '''
- A more complete status check of cassandra.
- Tries 5 times to call start-cassandra.sh status
- returns TRUE if it sees four occurances of both Up, and Normal
- '''
- tries = 5
- main.log.info(self.name + ": trying %i times" % tries )
- for i in range(tries):
- self.execute(cmd="\n",prompt="\$",timeout=10)
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("~/ONOS/start-cassandra.sh status")
- self.handle.expect("sh status")
- self.handle.expect("\$")
- result = self.handle.before + self.handle.after
- #pattern = '(.*)Up(.*)Normal(.*)\n(.*)Up(.*)Normal(.*)\n(.*)Up(.*)Normal(.*)\n(.*)Up(.*)Normal(.*)'
- pattern = '(' + self.ip_address.replace('.', '\\.') + '.*)Up(.*)Normal(.*)'
- if re.search(pattern, result):
- return main.TRUE
- return main.FALSE
diff --git a/TestON/drivers/common/cli/onosclidriver.py b/TestON/drivers/common/cli/onosclidriver.py
deleted file mode 100644
index 40e4cf0..0000000
--- a/TestON/drivers/common/cli/onosclidriver.py
+++ /dev/null
@@ -1,1746 +0,0 @@
-#!/usr/bin/env python
-'''
-Created on 31-May-2013
-
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
-
-TestON is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 of the License, or
-(at your option) any later version.
-
-TestON is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-
-'''
-import time
-import pexpect
-import struct, fcntl, os, sys, signal
-import re
-import json
-import traceback
-import urllib2
-from urllib2 import URLError, HTTPError
-from socket import timeout
-
-sys.path.append("../")
-from drivers.common.clidriver import CLI
-
-URL_TIMEOUT = 10
-
-class OnosCliDriver(CLI):
-
- def __init__(self):
- super(CLI, self).__init__()
-
- def connect(self,**connectargs):
- '''
- Creates ssh handle for ONOS.
- '''
- try:
- for key in connectargs:
- vars(self)[key] = connectargs[key]
- self.home = "~/ONOS"
- for key in self.options:
- if key == "home":
- self.home = self.options['home']
- break
-
-
- self.name = self.options['name']
- self.handle = super(OnosCliDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd, home = self.home)
-
- if self.handle:
- return self.handle
- else :
- main.log.info("NO ONOS HANDLE")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def portKill(self, port):
- try:
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- cmd = "sudo tcpkill -i eth0 port " + str(port) + " 2>/dev/null 1>/dev/null &"
- self.handle.sendline(cmd)
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def endPortKill(self,port):
- try:
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("sudo pkill tcpkill")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def start(self, env = ''):
- '''
- Starts ONOS on remote machine.
- Returns false if any errors were encountered.
- '''
- try:
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline(env + "./onos.sh core start")
- i=self.handle.expect(["STARTED","FAILED",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + str(self.handle.after)
- if i==0:
- j = self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT], timeout=60)
- if re.search("Killed",response):
- main.log.warn(self.name + ": Killed existing process")
- if j==0:
- main.log.info(self.name + ": ONOS Started ")
- return main.TRUE
- elif j==1:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- elif j==2:
- main.log.info(self.name + ": ONOS NOT Started, stuck while waiting for it to start ")
- return main.FALSE
- else:
- main.log.warn(self.name +": Unexpected response in start")
- return main.TRUE
- elif i==1:
- main.log.error(self.name + ": ONOS Failed to start")
- return main.FALSE
- elif i==2:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- elif i==3:
- main.log.error(self.name + ": ONOS timedout while starting")
- return main.FALSE
- else:
- main.log.error(self.name + ": ONOS start expect script missed something... ")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def start_all(self):
- '''
- starts ZK, RC, and ONOS
- '''
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh start")
- self.handle.expect("./onos.sh start")
- self.handle.expect(["\$",pexpect.TIMEOUT])
-
-
-
- def start_rest(self):
- '''
- Starts the rest server on ONOS.
- '''
- try:
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd= "./start-rest.sh start",prompt="\$",timeout=10)
- if re.search("admin",response):
- main.log.info(self.name + ": Rest Server Started Successfully")
- time.sleep(5)
- return main.TRUE
- else :
- main.log.warn(self.name + ": Failed to start Rest Server")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def status(self):
- '''
- Called onos.sh core status and returns TRUE/FALSE accordingly
- '''
- try:
- self.execute(cmd="\n",prompt="\$",timeout=10)
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd="./onos.sh core status ",prompt="\d+\sinstance\sof\sonos\srunning",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- if re.search("1\sinstance\sof\sonos\srunning",response):
- return main.TRUE
- elif re.search("0\sinstance\sof\sonos\srunning",response):
- return main.FALSE
- elif re.search("Expected\sPrompt\snot found\s,\sTime Out!!",response):
- return main.ERROR
- else :
- main.log.warn(self.name + " WARNING: status recieved unknown response")
- main.log.warn(response)
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def isup(self):
- '''
- A more complete check to see if ONOS is up and running properly.
- First, it checks if the process is up.
- Second, it reads the logs for "Exception: Connection refused"
- Third, it makes sure the logs are actually moving.
- returns TRUE/FALSE accordingly.
- '''
- try:
- self.execute(cmd="\n",prompt="\$",timeout=10)
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd= "./onos.sh core status ",prompt="running",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- tail1 = self.execute(cmd="tail " + self.home + "/onos-logs/onos.*.log",prompt="\$",timeout=10)
- time.sleep(10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- tail2 = self.execute(cmd="tail " + self.home + "/onos-logs/onos.*.log",prompt="\$",timeout=10)
- pattern = '(.*)1 instance(.*)'
- pattern2 = '(.*)Exception: Connection refused(.*)'
- # if utilities.assert_matches(expect=pattern,actual=response,onpass="ONOS process is running...",onfail="ONOS process not running..."):
- running = self.execute(cmd="cat "+self.home+"/onos-logs/onos.*.log | grep 'Sending LLDP out on all ports'",prompt="\$",timeout=10)
- if re.search(pattern, response):
- if running != "":
- main.log.info(self.name + ": ONOS process is running...")
- if tail1 == tail2:
- main.log.error(self.name + ": ONOS is frozen...")#logs aren't moving
- return main.FALSE
- elif re.search( pattern2,tail1 ):
- main.log.info(self.name + ": Connection Refused found in onos log")
- return main.FALSE
- elif re.search( pattern2,tail2 ):
- main.log.info(self.name + ": Connection Refused found in onos log")
- return main.FALSE
- else:
- main.log.info(self.name + ": Onos log is moving! It's looking good!")
- return main.TRUE
- else:
- main.log.info(self.name + ": ONOS not yet sending out LLDP messages")
- return main.FALSE
- else:
- main.log.error(self.name + ": ONOS process not running...")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def rest_status(self):
- '''
- Checks if the rest server is running.
- '''
- try:
- response = self.execute(cmd= self.home + "/start-rest.sh status ",prompt="running",timeout=10)
- if re.search("rest\sserver\sis\srunning",response):
- main.log.info(self.name + ": Rest Server is running")
- return main.TRUE
- elif re.search("rest\sserver\sis\snot\srunning",response):
- main.log.warn(self.name + ": Rest Server is not Running")
- return main.FALSE
- else :
- main.log.error(self.name + ": No response" +response)
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def stop_all(self):
- '''
- Runs ./onos.sh stop
- '''
- try:
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh stop")
- self.handle.expect(["./onos.sh stop",pexpect.EOF,pexpect.TIMEOUT])
- i=self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT],60)
- result = self.handle.before
- if re.search("Killed", result):
- main.log.info(self.name + ": ONOS Killed Successfully")
- return main.TRUE
- else :
- main.log.warn(self.name + ": ONOS wasn't running")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def stop(self):
- '''
- Runs ./onos.sh core stop to stop ONOS
- '''
- try:
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh core stop")
- self.handle.expect(["./onos.sh stop",pexpect.EOF,pexpect.TIMEOUT])
- i=self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT],60)
- result = self.handle.before
- if re.search("Killed", result):
- main.log.info(self.name + ": ONOS Killed Successfully")
- return main.TRUE
- else :
- main.log.warn(self.name + ": ONOS wasn't running")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-#**********************************************************************************************
-#**********************************************************************************************
-# The purpose of comp_intents is to find if the high level intents have changed. preIntents
-# and postIntents should be the output of curl of the intents. preIntents being the original
-# and postIntents being the later. We are looking at the intents with the same id from both
-# and comparing the dst and src DPIDs and macs, and the state. If any of these are changed
-# we print that there are changes, then return a list of the intents that have changes`
-#**********************************************************************************************
-#**********************************************************************************************
- def comp_intents(self,preIntents,postIntents):
- import json
- preDecoded = json.loads(preIntents)
- postDecoded = json.loads(postIntents)
- changes = []
- if not preDecoded:
- if postDecoded:
- print "THERE ARE CHANGES TO THE HIGH LEVEL INTENTS!!!!"
- return postDecoded
- for k in preDecoded:
- for l in postDecoded:
- if l['id']==k['id']:
- if k['dstSwitchDpid']==l['dstSwitchDpid'] and k['srcMac']==l['srcMac'] and k['dstMac']==l['dstMac'] and k['srcSwitchDpid']==l['srcSwitchDpid'] and k['state']==l['state']:
- postDecoded.remove(l)
- else:
- changes.append(k)
- print ("THERE ARE CHANGES TO THE HIGH LEVEL INTENTS!!!")
- return changes
-
-#**********************************************************************************************
-#**********************************************************************************************
-# the purpose of comp_low is to find if the low level intents have changed. The main idea
-# is to determine if the path has changed. Again, like with the comp_intents function, the
-# pre and post Intents variables are the json dumps of wm/onos/intent/low. The variables
-# that will be compared are the state, and the path.
-#**********************************************************************************************
-#**********************************************************************************************
- def comp_low(self, preIntents,postIntents):
- import json
- preDecoded = json.loads(preIntents)
- postDecoded = json.loads(postIntents)
- changes = []
- if not preDecoded:
- if postDecoded:
- print "THERE ARE CHANGES TO THE LOW LEVEL INTENTS!!!"
- return postDecoded
- for k in preDecoded:
- for l in postDecoded:
- if l['id']==k['id']:
- if l['path']!=k['path']:
- changes.append(l)
- print "\n\n\n\nTHERE ARE CHANGES TO THE LOW LEVEL INTENTS!!!"
- else:
- if k['state']!=l['state']:
- changes.append(l)
- print "\n\n\n\nTHERE ARE CHANGES TO THE LOW LEVEL INTENTS!!!"
- else:
- print "NO CHANGES SO FAR\n\n\n"
-
-
- return changes
-
-
- def rest_stop(self):
- '''
- Runs ./start-rest.sh stop to stop ONOS rest server
- '''
- try:
- response = self.execute(cmd= self.home + "/start-rest.sh stop ",prompt="killing",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- if re.search("killing", response):
- main.log.info(self.name + ": Rest Server Stopped")
- return main.TRUE
- else :
- main.log.error(self.name + ": Failed to Stop, Rest Server is not Running")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def kill(self):
- import re
- try:
- self.handle.sendline("ps -ef |grep 'ONOS/conf/logback' |awk 'NR==1 {print $2}' |xargs sudo kill -9")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("ps -ef |grep 'ONOS/conf/logback' |wc -l")
- self.handle.expect(["wc -l",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.after
- if re.search("1",response):
- return "ONOS Killed!"
- else:
- return "ERROR!!! ONOS MAY NOT HAVE BEEN KILLED PROPERLY!!!"
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.hane + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
-
- def disconnect(self):
- '''
- Called when Test is complete to disconnect the ONOS handle.
- '''
- response = ''
- try:
- self.handle.sendline("exit")
- self.handle.expect("closed")
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- except:
- main.log.error(self.name + ": Connection failed to the host")
- response = main.FALSE
- return response
-
- def print_version(self):
- '''
- Writes the COMMIT number to the report to be parsed by Jenkins data collecter.
- '''
- try:
- self.handle.sendline("export TERM=xterm-256color")
- self.handle.expect("xterm-256color")
- self.handle.expect("\$")
- self.handle.sendline("cd " + self.home + "; git log -1 --pretty=fuller --decorate=short | grep -A 5 \"commit\" --color=never; cd \.\.")
- self.handle.expect("cd ..")
- self.handle.expect("\$")
- response=(self.name +": \n"+ str(self.handle.before + self.handle.after))
- main.log.report(response)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- def get_version(self):
- '''
- Writes the COMMIT number to the report to be parsed by Jenkins data collecter.
- '''
- try:
- self.handle.sendline("export TERM=xterm-256color")
- self.handle.expect("xterm-256color")
- self.handle.expect("\$")
- self.handle.sendline("cd " + self.home + "; git log -1 --pretty=fuller --decorate=short | grep -A 5 \"commit\" --color=never; cd \.\.")
- self.handle.expect("cd ..")
- self.handle.expect("\$")
- response=(self.name +": \n"+ str(self.handle.before + self.handle.after))
- lines=response.splitlines()
- for line in lines:
- print line
- return lines[2]
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
-
-#*********************************************************************
-#*********************************************************************
-# shortest_path is a command to find the shortest path between two
-# switches. It is called using the IP, port, and source and
-# destination dpids
-#*********************************************************************
-#*********************************************************************
-
- def shortest_path(self,ONOSIP,ONOSPort,srcDPID,dstDPID):
- main.log.report("Finding the shortest Path between "+str(srcDPID) + " to " + str(dstDPID))
- url = "http://%s:%s/wm/onos/intent/path/switch/%s/shortest-path/%s"%(ONOSIP,ONOSPort,srcDPID,dstDPID)
- parsed_result = []
- try:
- response = urllib2.urlopen(url, timeout=URL_TIMEOUT)
- result = response.read()
- response.close()
- if len(result) != 0:
- parsed_result = json.loads(result)
- except HTTPError as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- # NOTE: exc.fp contains the object with the response payload
- error_payload = json.loads(exc.fp.read())
- print " REST Error Code: %s" % (error_payload['code'])
- print " REST Error Summary: %s" % (error_payload['summary'])
- print " REST Error Description: %s" % (error_payload['formattedDescription'])
- print " HTTP Error Code: %s" % exc.code
- print " HTTP Error Reason: %s" % exc.reason
- except URLError as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- print " URL Error Reason: %s" % exc.reason
- except timeout as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- print " URL Error Reason: %s" % exc.message
- main.log.error("Socket timeout connecting to: %s", url)
- return main.ERROR
-
- if len(parsed_result)==0:
- return
- result = json.dumps(parsed_result,indent=4)
- print(str(result))
- return result
-
-
-#*********************************************************************
-#*********************************************************************
-# show_intent is a command to show intents.
-# Parameters include intentIP, intentPort, intentURL, and intent_id
-# Based on the url, it will show either high or low intents
-# If intent_id is left blank, it will show all high or all low intents
-# Else it will show the intent with the id
-#*********************************************************************
-#*********************************************************************
-
-
-
- def show_intent(self,intentIP,intentPort=8080,intentURL="wm/onos/intent",intent_type="high",intent_id="all"):
- main.log.report("Getting (an) intent(s)")
- if intent_id=="all":
- url = "http://%s:%s/%s/%s"%(intentIP,intentPort,intentURL,intent_type)
- else:
- url = "http://%s:%s/%s/%s/%s"%(intentIP,intentPort,intentURL,intent_type,intent_id)
- print(url)
- parsed_result = []
- try:
- response = urllib2.urlopen(url, timeout=URL_TIMEOUT)
- result = response.read()
- response.close()
- if len(result) != 0:
- parsed_result = json.loads(result)
- except HTTPError as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- # NOTE: exc.fp contains the object with the response payload
- error_payload = json.loads(exc.fp.read())
- print " REST Error Code: %s" % (error_payload['code'])
- print " REST Error Summary: %s" % (error_payload['summary'])
- print " REST Error Description: %s" % (error_payload['formattedDescription'])
- print " HTTP Error Code: %s" % exc.code
- print " HTTP Error Reason: %s" % exc.reason
- return str(error_payload['code'])
- except URLError as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- print " URL Error Reason: %s" % exc.reason
- return str(error_payload['code'])
- except timeout as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- print " URL Error Reason: %s" % exc.message
- main.log.error("Socket timeout connecting to: %s", url)
- return main.ERROR
-
- if len(parsed_result)==0:
- return
- result = json.dumps(parsed_result,indent=4)
- print(str(result))
- return result
-
-
-#*********************************************************************
-#*********************************************************************
-# del_intent is to delete either all or some or one intents
-# if intent_id is left blank, it will delete all intents
-# else, intent_id should be of the form "intent_id=1,2,3"
-#*********************************************************************
-#*********************************************************************
-
- def del_intent(self,intentIP,intentPort=8080,intentURL="wm/onos/intent",intent_id="all"):
- main.log.report("Deleting (an) intent(s)")
- if intent_id=="all":
- url = "http://%s:%s/%s/high"%(intentIP,intentPort,intentURL)
- else:
- url = "http://%s:%s/%s/high?%s"%(intentIP,intentPort,intentURL,intent_id)
-
- print(url)
-
- parsed_result = []
- try:
- request = urllib2.Request(url)
- request.get_method = lambda: 'DELETE'
- response = urllib2.urlopen(request, timeout=URL_TIMEOUT)
- result = response.read()
- response.close()
- if len(result) != 0:
- parsed_result = json.loads(result)
- print(parsed_result)
- return parsed_result
- return main.TRUE
- except HTTPError as exc:
- print "ERROR:"
- print " REST DELETE URL: %s" % url
- # NOTE: exc.fp contains the object with the response payload
- error_payload = json.loads(exc.fp.read())
- print " REST Error Code: %s" % (error_payload['code'])
- print " REST Error Summary: %s" % (error_payload['summary'])
- print " REST Error Description: %s" % (error_payload['formattedDescription'])
- print " HTTP Error Code: %s" % exc.code
- print " HTTP Error Reason: %s" % exc.reason
- except URLError as exc:
- print "ERROR:"
- print " REST DELETE URL: %s" % url
- print " URL Error Reason: %s" % exc.reason
- except timeout as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- print " URL Error Reason: %s" % exc.message
- main.log.error("Socket timeout connecting to: %s", url)
- return main.ERROR
- return main.ERROR
-
-#*********************************************************************
-#*********************************************************************
-# add_intent will add a single intent by using dpids and macs.
-#*********************************************************************
-#*********************************************************************
-
-
- def add_intent(self, intent_id,src_dpid,dst_dpid,src_mac,dst_mac,intentIP,intentPort=8080,intentURL="wm/onos/intent" , intent_type = 'SHORTEST_PATH', static_path=False, src_port=1,dst_port=1):
- "CLI command callback: set intent"
-
- intents = []
- oper = {}
- # Create the POST payload
- oper['intentId'] = intent_id
- oper['intentType'] = intent_type # XXX: Hardcoded
- oper['staticPath'] = static_path # XXX: Hardcoded
- oper['srcSwitchDpid'] = src_dpid
- oper['srcSwitchPort'] = src_port
- oper['dstSwitchDpid'] = dst_dpid
- oper['dstSwitchPort'] = dst_port
- oper['matchSrcMac'] = src_mac
- oper['matchDstMac'] = dst_mac
- intents.append(oper)
- url = "http://%s:%s/%s/high"%(intentIP,intentPort,intentURL)
- parsed_result = []
- data_json = json.dumps(intents)
- result = main.FALSE
- try:
- request = urllib2.Request(url,data_json)
- request.add_header("Content-Type", "application/json")
- response=urllib2.urlopen(request, timeout=URL_TIMEOUT)
- result = response.read()
- response.close()
- if len(result) != 0:
- parsed_result = json.loads(result)
- return parsed_result
- return main.TRUE
- except HTTPError as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- # NOTE: exc.fp contains the object with the response payload
- error_payload = json.loads(exc.fp.read())
- print " REST Error Code: %s" % (error_payload['code'])
- print " REST Error Summary: %s" % (error_payload['summary'])
- print " REST Error Description: %s" % (error_payload['formattedDescription'])
- print " HTTP Error Code: %s" % exc.code
- print " HTTP Error Reason: %s" % exc.reason
- return " HTTP Error Code: %s, Reason: %s" % exc.code, exc.reason
- except URLError as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- print " URL Error Reason: %s" % exc.reason
- return " HTTP Error Reason: %s" % exc.reason
- except timeout as exc:
- print "ERROR:"
- print " REST GET URL: %s" % url
- print " URL Error Reason: %s" % exc.message
- main.log.error("Socket timeout connecting to: %s", url)
- return main.ERROR
- return main.ERROR
-
-
-
- def add_intents(self):
- main.log.info("Sending new intents to ONOS")
- self.handle.sendline("cd "+self.home+ "/scripts")
- self.handle.expect("scripts")
- main.log.info("Adding intents")
- self.handle.sendline("./pyintents.py")
- self.handle.expect(["$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before
- self.handle.sendline("cd "+self.home)
- return main.TRUE
-
- def rm_intents(self):
- main.log.info("Deleteing Intents from ONOS")
- self.handle.sendline("cd "+self.home+ "/scripts")
- self.handle.expect("scripts")
- main.log.info("Deleting Intnents")
- self.handle.sendline("./rmpyintents.py")
- self.handle.expect(["$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before
- self.handle.sendline("cd "+self.home)
- return main.TRUE
-
- def purge_intents(self):
- main.log.info("Purging dead intents")
- self.handle.sendline("cd "+self.home+ "/scripts")
- self.handle.expect("scripts")
- main.log.info("Sending Purge Intent Rest call to ONOS")
- self.handle.sendline("./purgeintents.py")
- self.handle.sendline("cd "+self.home)
- return main.TRUE
-
-
-
- def add_flow(self, testONip, user = "admin", password = "", flowDef = "/flowdef.txt"):
- '''
- Copies the flowdef file from TestStation -> ONOS machine
- Then runs ./add_flow.py to add the flows to ONOS
- '''
- try:
- main.log.info("Adding Flows...")
- self.handle.sendline("scp %s@%s:%s /tmp/flowtmp" %(user,testONip,flowDef))
- i=self.handle.expect(['[pP]assword:', '100%', pexpect.TIMEOUT],30)
- if(i==0):
- self.handle.sendline("%s" %(password))
- self.handle.sendline("")
- self.handle.expect("100%")
- self.handle.expect("\$", 30)
- self.handle.sendline(self.home + "/web/add_flow.py -m onos -f /tmp/flowtmp")
- self.handle.expect("\$", 1000)
- main.log.info("Flows added")
- return main.TRUE
-
- elif(i==1):
- self.handle.sendline("")
- self.handle.expect("\$", 10)
- self.handle.sendline( self.home + "/web/add_flow.py -m onos -f /tmp/flowtmp")
- self.handle.expect("\$", 1000)
- main.log.info("Flows added")
- return main.TRUE
-
- elif(i==2):
- main.log.error("Flow Def file SCP Timed out...")
- return main.FALSE
-
- else:
- main.log.error("Failed to add flows...")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def delete_flow(self, *delParams):
- '''
- Deletes a specific flow, a range of flows, or all flows.
- '''
- try:
- if len(delParams)==1:
- if str(delParams[0])=="all":
- main.log.info(self.name + ": Deleting ALL flows...")
- #self.execute(cmd="~/ONOS/scripts/TestON_delete_flow.sh all",prompt="done",timeout=150)
- self.handle.sendline(self.home + "/web/delete_flow.py all")
- self.handle.expect("delete_flow")
- self.handle.expect("\$",1000)
- main.log.info(self.name + ": Flows deleted")
- else:
- main.log.info(self.name + ": Deleting flow "+str(delParams[0])+"...")
- #self.execute(cmd="~/ONOS/scripts/TestON_delete_flow.sh "+str(delParams[0]),prompt="done",timeout=150)
- #self.execute(cmd="\n",prompt="\$",timeout=60)
- self.handle.sendline(self.home +"/web/delete_flow.py %d" % int(delParams[0]))
- self.handle.expect("delete_flow")
- self.handle.expect("\$",60)
- main.log.info(self.name + ": Flow deleted")
- elif len(delParams)==2:
- main.log.info(self.name + ": Deleting flows "+str(delParams[0])+" through "+str(delParams[1])+"...")
- #self.execute(cmd="~/ONOS/scripts/TestON_delete_flow.sh "+str(delParams[0])+" "+str(delParams[1]),prompt="done",timeout=150)
- #self.execute(cmd="\n",prompt="\$",timeout=60)
- self.handle.sendline(self.home + "/web/delete_flow.py %d %d" % (int(delParams[0]), int(delParams[1])))
- self.handle.expect("delete_flow")
- self.handle.expect("\$",600)
- main.log.info(self.name + ": Flows deleted")
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_flow(self):
- '''
- Calls the ./get_flow.py all and checks:
- - If each FlowPath has at least one FlowEntry
- - That there are no "NOT"s found
- returns TRUE/FALSE
- '''
- try:
- flowEntryDetect = 1
- count = 0
- self.handle.sendline("clear")
- time.sleep(1)
- self.handle.sendline(self.home + "/web/get_flow.py all")
- self.handle.expect("get_flow")
- for x in range(15):
- i=self.handle.expect(['FlowPath','FlowEntry','NOT','\$',pexpect.TIMEOUT],timeout=180)
- if i==0:
- count = count + 1
- if flowEntryDetect == 0:
- main.log.info(self.name + ": FlowPath without FlowEntry")
- return main.FALSE
- else:
- flowEntryDetect = 0
- elif i==1:
- flowEntryDetect = 1
- elif i==2:
- main.log.error(self.name + ": Found a NOT")
- return main.FALSE
- elif i==3:
- if count == 0:
- main.log.info(self.name + ": There don't seem to be any flows here...")
- return main.FALSE
- else:
- main.log.info(self.name + ": All flows pass")
- main.log.info(self.name + ": Number of FlowPaths: "+str(count))
- return main.TRUE
- elif i==4:
- main.log.error(self.name + ":Check_flow() - Command Timeout!")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def get_flow(self, *flowParams):
- '''
- Returns verbose output of ./get_flow.py
- '''
- try:
- if len(flowParams)==1:
- if str(flowParams[0])=="all":
- self.execute(cmd="\n",prompt="\$",timeout=60)
- main.log.info(self.name + ": Getting all flow data...")
- data = self.execute(cmd=self.home + "/scripts/TestON_get_flow.sh all",prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- else:
- main.log.info(self.name + ": Retrieving flow "+str(flowParams[0])+" data...")
- data = self.execute(cmd=self.home +"/scripts/TestON_get_flow.sh "+str(flowParams[0]),prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- elif len(flowParams)==5:
- main.log.info(self.name + ": Retrieving flow installer data...")
- data = self.execute(cmd=self.home + "/scripts/TestON_get_flow.sh "+str(flowParams[0])+" "+str(flowParams[1])+" "+str(flowParams[2])+" "+str(flowParams[3])+" "+str(flowParams[4]),prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- elif len(flowParams)==4:
- main.log.info(self.name + ": Retrieving flow endpoints...")
- data = self.execute(cmd=self.home + "/scripts/TestON_get_flow.sh "+str(flowParams[0])+" "+str(flowParams[1])+" "+str(flowParams[2])+" "+str(flowParams[3]),prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
-# http://localhost:8080/wm/onos/topology/switches
-# http://localhost:8080/wm/onos/topology/links
-# http://localhost:8080/wm/onos/registry/controllers/json
-# http://localhost:8080/wm/onos/registry/switches/json"
-
- def get_json(self, url):
- '''
- Helper functions used to parse the json output of a rest call
- '''
- try:
- try:
- command = "curl -s %s" % (url)
- result = os.popen(command).read()
- parsedResult = json.loads(result)
- except:
- print "REST IF %s has issue" % command
- parsedResult = ""
-
- if type(parsedResult) == 'dict' and parsedResult.has_key('code'):
- print "REST %s returned code %s" % (command, parsedResult['code'])
- parsedResult = ""
- return parsedResult
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def num_switch(self,RestIP,RestPort="8080"):
- url = "http://%s:%s/wm/onos/topology/switches" %(RestIP,RestPort)
- parsedResult = self.get_json(url)
- if parsedResult == "":
- retcode = 1
- return (retcode, "RestAPI has an issue")
- url = "http://%s:%s/wm/onos/registry/switches/json" %(RestIP,RestPort)
- registry = self.get_json(url)
- if registry == "":
- retcode = 1
- return (retcode, "REST API has an Issue")
- cnt = 0
- active = 0
- for s in parsedResult:
- cnt +=1
- if s['state']=="ACTIVE":
- active+=1
- return (cnt,active)
-
-
- def check_switch(self,RestIP,correct_nr_switch, RestPort ="8080" ):
- '''
- Used by check_status
- '''
- try:
- buf = ""
- retcode = 0
- url="http://%s:%s/wm/onos/topology/switches" % (RestIP, RestPort)
- parsedResult = self.get_json(url)
- if parsedResult == "":
- retcode = 1
- return (retcode, "Rest API has an issue")
- url = "http://%s:%s/wm/onos/registry/switches/json" % (RestIP, RestPort)
- registry = self.get_json(url)
-
- if registry == "":
- retcode = 1
- return (retcode, "Rest API has an issue")
-
- cnt = 0
- active = 0
-
- for s in parsedResult:
- cnt += 1
- if s['state'] == "ACTIVE":
- active += 1
-
- buf += "switch: network %d : %d switches %d active\n" % (0+1, cnt, active)
- if correct_nr_switch != cnt:
- buf += "switch fail: network %d should have %d switches but has %d\n" % (1, correct_nr_switch, cnt)
- retcode = 1
-
- if correct_nr_switch != active:
- buf += "switch fail: network %d should have %d active switches but has %d\n" % (1, correct_nr_switch, active)
- retcode = 1
-
- return (retcode, buf)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def num_link(self,RestIP,RestPort="8080"):
- url = "http://%s:%s/wm/onos/topology/links" % (RestIP,RestPort)
- parsedResult = self.get_json(url)
- if parsedResult == "":
- retcode = 1
- return (retcode,"RestAPI has an issue")
- intra = 0
- for s in parsedResult:
- intra+=1
- return intra
-
- def check_link(self,RestIP, nr_links, RestPort = "8080"):
- '''
- Used by check_status
- '''
- try:
- buf = ""
- retcode = 0
-
- url = "http://%s:%s/wm/onos/topology/links" % (RestIP, RestPort)
- parsedResult = self.get_json(url)
-
- if parsedResult == "":
- retcode = 1
- return (retcode, "Rest API has an issue")
-
- buf += "link: total %d links (correct : %d)\n" % (len(parsedResult), nr_links)
- intra = 0
- interlink=0
-
- for s in parsedResult:
- intra = intra + 1
-
- if intra != nr_links:
- buf += "link fail\n"
- retcode = 1
-
- return (retcode, buf)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_status_report(self, ip, numoswitch, numolink, port="8080"):
- '''
- Checks the number of swithes & links that ONOS sees against the supplied values.
- Writes to the report log.
- '''
- try:
- main.log.info(self.name + ": Making some rest calls...")
- switch = self.check_switch(ip, int(numoswitch), port)
- link = self.check_link(ip, int(numolink), port)
- value = switch[0]
- value += link[0]
- main.log.report( self.name + ": \n-----\n%s%s-----\n" % ( switch[1], link[1]) )
- if value != 0:
- return main.FALSE
- else:
- # "PASS"
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_status(self, ip, numoswitch, numolink, port = "8080"):
- '''
- Checks the number of swithes & links that ONOS sees against the supplied values.
- Writes to the main log.
- '''
- try:
- main.log.info(self.name + ": Making some rest calls...")
- switch = self.check_switch(ip, int(numoswitch), port)
- link = self.check_link(ip, int(numolink), port)
- value = switch[0]
- value += link[0]
- main.log.info(self.name + ": \n-----\n%s%s-----\n" % ( switch[1], link[1]) )
- if value != 0:
- return main.FALSE
- else:
- # "PASS"
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def detailed_status(self, log_filename):
- '''
- Reports RUNNING, STARTING, STOPPED, FROZEN, ERROR (and reason)
- '''
- try:
- process_up = False
- self.execute(cmd="\n", prompt="\$", timeout=10)
- self.handle.sendline("cd " + self.home)
- response = self.execute(cmd="./onos.sh core status ",prompt="\d+\sinstance\sof\sonos\srunning",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- if re.search("1\sinstance\sof\sonos\srunning",response):
- process_up = True
- elif re.search("0\sinstance\sof\sonos\srunning",response):
- process_up = False
- return 'STOPPED'
- elif re.search("Expected\sPrompt\snot found\s,\sTime Out!!",response):
- return "ERROR", "Time out on ./onos.sh core status"
- else :
- main.log.warn(self.name + " WARNING: status recieved unknown response")
- main.log.warn(response)
- return 'Error', "Unknown response: %s" % response
- '''
- self.execute(cmd="\n",prompt="\$",timeout=10)
- tail1 = self.execute(cmd="tail " + self.home + "%s" % log_filename, prompt="\$", timeout=10)
- time.sleep(10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- tail2 = self.execute(cmd="tail " + self.home + "%s" % log_filename, prompt="\$", timeout=10)
- '''
-
- pattern = '(.*)1 instance(.*)'
- pattern2 = '(.*)Exception: Connection refused(.*)'
- # if utilities.assert_matches(expect=pattern,actual=response,onpass="ONOS process is running...",onfail="ONOS process not running..."):
- running = self.execute(cmd="cat " + self.home + " %s | grep 'Sending LLDP out on all ports'" % log_filename,prompt="\$",timeout=10)
- if re.search(pattern, response):
- if running == '':
- return 'STARTING',
- else:
- return 'RUNNING'
- else:
- main.log.error(self.name + ": ONOS process not running...")
- return 'STOPPED'
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def git_pull(self, comp1=""):
- '''
- Assumes that "git pull" works without login
-
- This function will perform a git pull on the ONOS instance.
- If used as git_pull("NODE") it will do git pull + NODE. This is
- for the purpose of pulling from other nodes if necessary.
-
- Otherwise, this function will perform a git pull in the
- ONOS repository. If it has any problems, it will return main.ERROR
- If it successfully does a git_pull, it will return a 1.
- If it has no updates, it will return a 0.
-
- '''
- try:
- # main.log.info(self.name + ": Stopping ONOS")
- #self.stop()
- self.handle.sendline("cd " + self.home)
- self.handle.expect("ONOS\$")
- if comp1=="":
- self.handle.sendline("git pull")
- else:
- self.handle.sendline("git pull " + comp1)
-
- uptodate = 0
- i=self.handle.expect(['fatal',
- 'Username\sfor\s(.*):\s',
- '\sfile(s*) changed,\s',
- 'Already up-to-date',
- 'Aborting',
- 'You\sare\snot\scurrently\son\sa\sbranch',
- 'You\sasked\sme\sto\spull\swithout\stelling\sme\swhich\sbranch\syou',
- 'Pull\sis\snot\spossible\sbecause\syou\shave\sunmerged\sfiles',
- pexpect.TIMEOUT],
- timeout=300)
- #debug
- #main.log.report(self.name +": \n"+"git pull response: " + str(self.handle.before) + str(self.handle.after))
- if i==0:
- main.log.error(self.name + ": Git pull had some issue...")
- return main.ERROR
- elif i==1:
- main.log.error(self.name + ": Git Pull Asking for username. ")
- return main.ERROR
- elif i==2:
- main.log.info(self.name + ": Git Pull - pulling repository now")
- self.handle.expect("ONOS\$", 120)
- return 0
- elif i==3:
- main.log.info(self.name + ": Git Pull - Already up to date")
- return 1
- elif i==4:
- main.log.info(self.name + ": Git Pull - Aborting... Are there conflicting git files?")
- return main.ERROR
- elif i==5:
- main.log.info(self.name + ": Git Pull - You are not currently on a branch so git pull failed!")
- return main.ERROR
- elif i==6:
- main.log.info(self.name + ": Git Pull - You have not configured an upstream branch to pull from. Git pull failed!")
- return main.ERROR
- elif i==7:
- main.log.info(self.name + ": Git Pull - Pull is not possible because you have unmerged files.")
- return main.ERROR
- elif i==8:
- main.log.error(self.name + ": Git Pull - TIMEOUT")
- main.log.error(self.name + " Response was: " + str(self.handle.before))
- return main.ERROR
- else:
- main.log.error(self.name + ": Git Pull - Unexpected response, check for pull errors")
- return main.ERROR
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-#********************************************************
-
-
-
-
- def git_checkout(self, branch="onos13integration"):
- '''
- Assumes that "git pull" works without login
-
- This function will perform a git pull on the ONOS instance.
- If used as git_pull("NODE") it will do git pull + NODE. This is
- for the purpose of pulling from other nodes if necessary.
-
- Otherwise, this function will perform a git pull in the
- ONOS repository. If it has any problems, it will return main.ERROR
- If it successfully does a git_pull, it will return a 1.
- If it has no updates, it will return a 0.
-
- '''
- try:
- # main.log.info(self.name + ": Stopping ONOS")
- #self.stop()
- self.handle.sendline("cd " + self.home)
- self.handle.expect("ONOS\$")
- if branch != 'master':
- #self.handle.sendline('git stash')
- #self.handle.expect('ONOS\$')
- #print "After issuing git stash cmnd: ", self.handle.before
- cmd = "git checkout "+branch
- print "checkout cmd = ", cmd
- self.handle.sendline(cmd)
- uptodate = 0
- i=self.handle.expect(['fatal','Username\sfor\s(.*):\s','Already\son\s\'onos13integration\'','Switched\sto\sbranch\s\'onos13integration\'', pexpect.TIMEOUT],timeout=60)
- else:
- #self.handle.sendline('git stash apply')
- #self.handle.expect('ONOS\$')
- #print "After issuing git stash apply cmnd: ", self.handle.before
- cmd = "git checkout "+branch
- print "checkout cmd = ", cmd
- self.handle.sendline(cmd)
- uptodate = 0
- switchedToMaster = 0
- i=self.handle.expect(['fatal','Username\sfor\s(.*):\s','Already\son\s\'master\'','Switched\sto\sbranch\s\'master\'', pexpect.TIMEOUT],timeout=60)
-
-
- if i==0:
- main.log.error(self.name + ": Git checkout had some issue...")
- return main.ERROR
- elif i==1:
- main.log.error(self.name + ": Git checkout Asking for username!!! BADD!")
- return main.ERROR
- elif i==2:
- main.log.info(self.name + ": Git Checkout %s : Already on this branch" %branch)
- self.handle.expect("ONOS\$")
- print "after checkout cmd = ", self.handle.before
- switchedToMaster = 1
- return 1
- elif i==3:
- main.log.info(self.name + ": Git checkout %s - Switched to this branch" %branch)
- self.handle.expect("ONOS\$")
- print "after checkout cmd = ", self.handle.before
- switchedToMaster = 1
- return 1
- elif i==4:
- main.log.error(self.name + ": Git Checkout- TIMEOUT")
- main.log.error(self.name + " Response was: " + str(self.handle.before))
- return main.ERROR
- else:
- main.log.error(self.name + ": Git Checkout - Unexpected response, check for pull errors")
- return main.ERROR
-
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-#********************************************************
- self.handle.sendline("git branch")
- self.handle.expect("ONOS\$")
- print "git branch output = ", self.handle.before
- print "*****************************************"
- self.handle.sendline('cd\.\.')
- self.handle.expect("\$")
-
-
-
-
-
-
-
-
- def git_compile(self):
- '''
- Compiles ONOS
- First runs mvn clean then mvn compile
- '''
- try:
- main.log.info(self.name + ": mvn clean")
- self.handle.sendline("cd " + self.home)
- self.handle.sendline("mvn clean")
- while 1:
- i=self.handle.expect(['There\sis\sinsufficient\smemory\sfor\sthe\sJava\sRuntime\sEnvironment\sto\scontinue','BUILD\sFAILURE','BUILD\sSUCCESS','ONOS\$',pexpect.TIMEOUT],timeout=30)
- if i == 0:
- main.log.error(self.name + ":There is insufficient memory for the Java Runtime Environment to continue.")
- return main.FALSE
- elif i == 1:
- main.log.error(self.name + ": Clean failure!")
- return main.FALSE
- elif i == 2:
- main.log.info(self.name + ": Clean success!")
- elif i == 3:
- main.log.info(self.name + ": Clean complete")
- break;
- elif i == 4:
- main.log.error(self.name + ": mvn clean TIMEOUT!")
- return main.FALSE
- else:
- main.log.error(self.name + ": unexpected response from mvn clean")
- return main.FALSE
-
- main.log.info(self.name + ": mvn compile")
- self.handle.sendline("mvn compile")
- while 1:
- i=self.handle.expect(['There\sis\sinsufficient\smemory\sfor\sthe\sJava\sRuntime\sEnvironment\sto\scontinue','BUILD\sFAILURE','BUILD\sSUCCESS','ONOS\$',pexpect.TIMEOUT],timeout=60)
- if i == 0:
- main.log.error(self.name + ":There is insufficient memory for the Java Runtime Environment to continue.")
- return main.FALSE
- if i == 1:
- main.log.error(self.name + ": Build failure!")
- return main.FALSE
- elif i == 2:
- main.log.info(self.name + ": Build success!")
- elif i == 3:
- main.log.info(self.name + ": Build complete")
- self.handle.expect("\$", timeout=60)
- return main.TRUE
- elif i == 4:
- main.log.error(self.name + ": mvn compile TIMEOUT!")
- return main.FALSE
- else:
- main.log.error(self.name + ": unexpected response from mvn compile")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def tcpdump(self, intf = "eth0"):
- '''
- Runs tpdump on an intferface and saves in onos-logs under the ONOS home directory
- intf can be specified, or the default eth0 is used
- '''
- try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("sudo tcpdump -n -i "+ intf + " -s0 -w " + self.home +"/onos-logs/tcpdump &")
- i=self.handle.expect(['No\ssuch\device','listening\son',pexpect.TIMEOUT],timeout=10)
- if i == 0:
- main.log.error(self.name + ": tcpdump - No such device exists. tcpdump attempted on: " + intf)
- return main.FALSE
- elif i == 1:
- main.log.info(self.name + ": tcpdump started on " + intf)
- return main.TRUE
- elif i == 2:
- main.log.error(self.name + ": tcpdump command timed out! Check interface name, given interface was: " + intf)
- return main.FALSE
- else:
- main.log.error(self.name + ": tcpdump - unexpected response")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def kill_tcpdump(self):
- '''
- Kills any tcpdump processes running
- '''
- try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("sudo kill -9 `ps -ef | grep \"tcpdump -n\" | grep -v grep | awk '{print $2}'`")
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def find_host(self,RestIP,RestPort,RestAPI,hostMAC):
- retcode = 0 # number of hosts found with given MAC
- retswitch = [] # Switch DPID's of hosts found with MAC
- retport = [] # Switch port connected to to hosts found with MAC
- foundHost = []
- try:
- ##### device rest API is: 'host:8080/wm/onos/topology/switches' ###
- url ="http://%s:%s%s" %(RestIP,RestPort,RestAPI)
-
- try:
- command = "curl -s %s" % (url)
- result = os.popen(command).read()
- parsedResult = json.loads(result)
- # print parsedResult
- except:
- print "REST IF %s has issue" % command
- parsedResult = ""
-
- if parsedResult == "":
- return (retcode, "Rest API has an error", retport)
- else:
- for host in enumerate(parsedResult):
- if (host[1] != []):
- try:
- foundHost = host[1]['mac']
- except:
- print "Error in detecting MAC address."
- if foundHost == hostMAC:
- for switch in enumerate(host[1]['attachmentPoints']):
- retswitch.append(switch[1]['dpid'])
- retport.append(switch[1]['portNumber'])
- retcode = retcode +1
- foundHost =''
- '''
- for switch in enumerate(parsedResult):
- for port in enumerate(switch[1]['ports']):
- if ( port[1]['hosts'] != [] ):
- try:
- foundHost = port[1]['hosts'][0]['ipv4addresses'][0]['ipv4']
- except:
- print "Error in detecting MAC address."
- if foundHost == hostMAC:
- retswitch.append(switch[1]['dpid'])
- retport.append(port[1]['desc'])
- retmac.append(port[1]['hosts'][0]['mac'])
- retcode = retcode +1
- foundHost =''
- '''
- return(retcode, retswitch, retport)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_exceptions(self):
- '''
- Greps the logs for "xception"
- '''
- try:
- output = ''
- self.handle.sendline("")
- i = self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- main.log.warn("first expect response: " +str(i))
- self.handle.sendline("cd "+self.home+"/onos-logs")
- i = self.handle.expect(["onos-logs\$",pexpect.EOF,pexpect.TIMEOUT])
- main.log.warn("second expect response: " +str(i))
-
- self.handle.sendline("zgrep \"xception\" *.log *.log.gz *.stderr")
- #i = self.handle.expect(["\*.stdout",pexpect.EOF,pexpect.TIMEOUT])
- #main.log.warn("third expect response: " +str(i))
- print self.handle.before
- print
- print self.handle.after
- i = self.handle.expect(["ONOS/onos-logs\$",pexpect.EOF,pexpect.TIMEOUT],timeout=120)
- main.log.warn("fourth expect response: " +str(i))
- response = self.handle.before
- print response
- count = 0
- print response
- for line in response.splitlines():
- if re.search("gzip: \*\.log\.gz:", line):
- #gzip complaining about file not found
- pass
- elif re.search("log\.gz:",line):
- output+="Exceptions found in " + line + "\n"
- count +=1
- elif re.search("log:", line):
- output +="Exceptions found in " + line + "\n"
- count +=1
- elif re.search("std...:",line):
- output+="Exceptions found in " + line + "\n"
- count +=1
- else:
- pass
- #these should be the old logs
- main.log.report(str(count) + " Exceptions were found on "+self.name)
- return output
- except pexpect.TIMEOUT:
- main.log.error(self.name + ": Timeout exception found in check_exceptions function")
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def block_peer(self, ip_address):
- '''
- Block traffic to the destination IP address.
- '''
- try:
- for chain in ['INPUT', 'OUTPUT']:
- check_block_cmd = "sudo iptables -L %s -n | grep \"DROP.*%s\"" % (chain, ip_address)
- add_block_cmd = "sudo iptables -I %s 1 -s %s -j DROP" % (chain, ip_address)
- response1 = self.execute(cmd=check_block_cmd,prompt="\$",timeout=10)
- if ip_address in response1:
- main.log.error("Already blocked: %s" % response1)
- return main.TRUE
- response2 = self.execute(cmd=add_block_cmd,prompt="\$",timeout=10)
- main.log.info("add_block_cmd: %s" % response2)
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def unblock_peer(self, ip_address):
- '''
- Unblock traffic to the destination IP address.
- '''
- try:
- for chain in ['INPUT', 'OUTPUT']:
- # To make sure all rules are deleted in case there were multiple
- # installed in the iptables
- max_iterations = 10
- for i in range(max_iterations):
- check_block_cmd = "sudo iptables -L %s -n | grep \"DROP.*%s\"" % (chain, ip_address)
- remove_block_cmd = "sudo iptables -D %s -s %s -j DROP" % (chain, ip_address)
- response1 = self.execute(cmd=check_block_cmd,prompt="\$",timeout=10)
- if ip_address not in response1:
- main.log.warn("Already unblocked: %s" % response1)
- return main.TRUE
- response2 = self.execute(cmd=remove_block_cmd,prompt="\$",timeout=10)
- main.log.info("remove_block_cmd: %s" % response2)
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def unblock_all(self):
- '''
- Remove all controller block rules
- '''
- try:
- unblock_cmd = "sudo iptables --flush"
- response = self.execute(cmd=unblock_cmd,prompt="\$", timeout=10)
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
- return main.ERROR
diff --git a/TestON/drivers/common/cli/onossanityclidriver.py b/TestON/drivers/common/cli/onossanityclidriver.py
deleted file mode 100644
index 24502ae..0000000
--- a/TestON/drivers/common/cli/onossanityclidriver.py
+++ /dev/null
@@ -1,1193 +0,0 @@
-#!/usr/bin/env python
-'''
-'''
-
-import pexpect
-import struct
-import fcntl
-import os
-import signal
-import re
-import sys
-import core.teston
-import time
-import json
-import traceback
-import requests
-
-sys.path.append("../")
-from drivers.common.clidriver import CLI
-
-class onossanityclidriver(CLI):
- '''
- '''
- def __init__(self):
- super(CLI, self).__init__()
-
- def connect(self,**connectargs):
- '''
- Creates ssh handle for ONOS.
- '''
- try:
- for key in connectargs:
- vars(self)[key] = connectargs[key]
- self.home = "~/ONOS"
- for key in self.options:
- if key == "home":
- self.home = self.options['home']
- break
-
-
- self.name = self.options['name']
- self.handle = super(onossanityclidriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd, home = self.home)
-
- if self.handle:
- return self.handle
- else :
- main.log.info("NO ONOS HANDLE")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def start(self):
- '''
- Starts ONOS on remote machine.
- Returns false if any errors were encountered.
- '''
- try:
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh zk start")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("./onos.sh rc deldb")
- self.handle.sendline("y")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- #Send a confirmation to delete ramcloud
- #self.handle.sendline("y")
- main.log.info("Ramcloud db deleted")
- #self.handle.sendline("./onos.sh zk start")
- #Check if zookeeper is running
- #delete database ./onos.sh rc deldb
- #main.log.info(self.name + ": ZooKeeper Started Separately")
- time.sleep(2)
- self.handle.sendline("./onos.sh start")
- i=self.handle.expect(["STARTED","FAILED","running",pexpect.EOF,pexpect.TIMEOUT])
- if i==0:
- main.log.info(self.name + ": ZooKeeper, Ramcloud and ONOS Started ")
- return main.TRUE
- elif i==1:
- main.log.error(self.name + ": Failed to start")
- return main.FALSE
- elif i==2:
- main.log.info(self.name + ": Already running, so Restarting ONOS")
- self.handle.sendline("./onos.sh restart")
- j=self.handle.expect(["STARTED","FAILED",pexpect.EOF,pexpect.TIMEOUT])
- if j==0:
- main.log.info(self.name + ": ZooKeeper, Ramcloud and ONOS Started ")
- return main.TRUE
- else:
- main.log.error(self.name + ": ONOS Failed to Start")
- elif i==3:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- elif i==2:
- main.log.info(self.name + ": Already running, so Restarting ONOS")
- self.handle.sendline("./onos.sh restart")
- j=self.handle.expect(["STARTED","FAILED",pexpect.EOF,pexpect.TIMEOUT])
- if j==0:
- main.log.info(self.name + ": ZooKeeper, Ramcloud and ONOS Started ")
- return main.TRUE
- elif j==1:
- main.log.error(self.name + ": ONOS Failed to Start")
- main.log.info(self.name + ": cleaning up and exiting...")
- main.cleanup()
- main.exit()
- elif j==2:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.log.info(self.name + ": cleaning up and exiting...")
- main.cleanup()
- main.exit()
- elif i==3:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- elif i==4:
- main.log.error(self.name + ": ONOS timedout while starting")
- return main.FALSE
- else:
- main.log.error(self.name + ": ONOS start expect script missed something... ")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def status(self):
- '''
- Calls onos.sh core status and returns TRUE/FALSE accordingly
- '''
- try:
- self.execute(cmd="\n",prompt="\$",timeout=10)
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd="./onos.sh core status ",prompt="\d+\sinstance\sof\sonos\srunning",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- if re.search("1\sinstance\sof\sonos\srunning",response):
- return main.TRUE
- elif re.search("0\sinstance\sof\sonos\srunning",response):
- return main.FALSE
- else :
- main.log.info( self.name + " WARNING: status recieved unknown response")
- main.log.info( self.name + " For details: check onos core status manually")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def zk_status(self):
- '''
- Calls the zookeeper status and returns TRUE if it has an assigned Mode to it.
- '''
- try:
- self.execute(cmd="\n",prompt="\$",timeout=10)
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh zk status")
- i=self.handle.expect(["standalone","Error",pexpect.EOF,pexpect.TIMEOUT])
- if i==0:
- main.log.info(self.name + ": Zookeeper is running.")
- return main.TRUE
- elif i==1:
- main.log.error(self.name + ": Error with zookeeper")
- main.log.info(self.name + ": Directory used: "+self.home)
- return main.FALSE
- elif i==3:
- main.log.error(self.name + ": Zookeeper timed out")
- main.log.info(self.name + ": Directory used: "+self.home)
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def rcs_status(self):
- '''
- This Function will return the Status of the RAMCloud Server
- '''
- main.log.info(self.name + ": Getting RC-Server Status")
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc-server status")
- self.handle.expect(["onos.sh rc-server status",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
-
- if re.search("0\sRAMCloud\sserver\srunning", response) :
- main.log.info(self.name+": RAMCloud not running")
- return main.TRUE
- elif re.search("1\sRAMCloud\sserver\srunning",response):
- main.log.warn(self.name+": RAMCloud Running")
- return main.TRUE
- else:
- main.log.info( self.name+": WARNING: status recieved unknown response")
- return main.FALSE
-
- def rcc_status(self):
- '''
- This Function will return the Status of the RAMCloud Coord
- '''
- main.log.info(self.name + ": Getting RC-Coord Status")
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc-coord status")
- i=self.handle.expect(["onos.sh rc-coord status",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
- #return response
-
- if re.search("0\sRAMCloud\scoordinator\srunning", response) :
- main.log.warn(self.name+": RAMCloud Coordinator not running")
- return main.TRUE
- elif re.search("1\sRAMCloud\scoordinator\srunning", response):
- main.log.info(self.name+": RAMCloud Coordinator Running")
- return main.TRUE
- else:
- main.log.warn( self.name+": coordinator status recieved unknown response")
- return main.FALSE
-
- def stop(self):
- '''
- Runs ./onos.sh core stop to stop ONOS
- '''
- try:
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh stop")
- i=self.handle.expect(["Stop",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT], 60)
- result = self.handle.before
- if re.search("Killed", result):
- main.log.info(self.name + ": ONOS Killed Successfully")
- return main.TRUE
- else :
- main.log.warn(self.name + ": ONOS wasn't running")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def start_rest(self):
- '''
- Starts the rest server on ONOS.
- '''
- try:
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd= "./start-rest.sh start",prompt="\$",timeout=10)
- if re.search(self.user_name,response):
- main.log.info(self.name + ": Rest Server Started Successfully")
- time.sleep(5)
- return main.TRUE
- else :
- main.log.warn(self.name + ": Failed to start Rest Server")
- main.log.info(self.name + ": Directory used: "+self.home )
- main.log.info(self.name + ": Rest server response: "+response)
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def rest_stop(self):
- '''
- Runs ./start-rest.sh stop to stop ONOS rest server
- '''
- try:
- response = self.execute(cmd= self.home + "./start-rest.sh stop ",prompt="killing",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- if re.search("killing", response):
- main.log.info(self.name + ": Rest Server Stopped")
- return main.TRUE
- else :
- main.log.error(self.name + ": Failed to Stop, Rest Server is not Running")
- main.log.info(self.name + ": Directory used: "+self.home)
- main.log.info(self.name + ": Rest server response: " + response)
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def rest_status(self):
- '''
- Checks if the rest server is running.
- '''
- #this function does not capture the status response correctly...
- #when cmd is executed, the prompt expected should be a string containing
- #status message, but instead returns the user@user$ Therefore prompt="running"
- #was changed to prompt="\$"
- try:
- response = self.execute(cmd= self.home + "./start-rest.sh status ",prompt="\$",timeout=10)
- if re.search(self.user_name,response):
- main.log.info(self.name + ": Rest Server is running")
- return main.TRUE
- elif re.search("rest\sserver\sis\snot\srunning",response):
- main.log.warn(self.name + ": Rest Server is not Running")
- return main.FALSE
- else :
- main.log.error(self.name + ": No response" +response)
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def disconnect(self):
- '''
- Called when Test is complete to disconnect the ONOS handle.
- '''
- response = ''
- try:
- self.handle.sendline("exit")
- self.handle.expect("closed")
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- except:
- main.log.error(self.name + ": Connection failed to the host")
- response = main.FALSE
- return response
-
- def print_version(self):
- '''
- Writes the COMMIT number to the report to be parsed by Jenkins data collecter.
- '''
- try:
- self.handle.sendline("export TERM=xterm-256color")
- self.handle.expect("xterm-256color")
- self.handle.expect("\$")
- self.handle.sendline("cd " + self.home + "; git log -1 --pretty=fuller | grep -A 5 \"commit\"; cd \.\.")
- self.handle.expect("cd ..")
- self.handle.expect("\$")
- response=(self.name +": \n"+ str(self.handle.before + self.handle.after))
- main.log.report(response)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- def get_version(self):
- '''
- Writes the COMMIT number to the report to be parsed by Jenkins data collecter.
- '''
- try:
- self.handle.sendline("export TERM=xterm-256color")
- self.handle.expect("xterm-256color")
- self.handle.expect("\$")
- self.handle.sendline("cd " + self.home + "; git log -1 --pretty=fuller | grep -A 5 \"commit\"; cd \.\.")
- self.handle.expect("cd ..")
- self.handle.expect("\$")
- response=(self.name +": \n"+ str(self.handle.before + self.handle.after))
- lines=response.splitlines()
- for line in lines:
- print line
- return lines[2]
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def add_flow(self, intentFile, path):
- try:
- main.log.info("add_flow running...")
- main.log.info("using directory: "+path)
- time.sleep(10)
- self.handle.sendline("cd " + path)
- self.handle.expect("tests")
- self.handle.sendline("./"+intentFile)
- time.sleep(10)
- self.handle.sendline("cd "+self.home)
- return main.TRUE
- except pexepct.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def delete_flow(self, intentFile, path):
- try:
- main.log.info("delete_flow running...")
- main.log.info("using directory: " + path)
- main.log.info("using file: " + intentFile)
- self.handle.sendline("cd " + path)
- self.handle.expect("tests")
- self.handle.sendline("./" + intentFile)
- time.sleep(10)
- self.handle.sendline("cd "+self.home)
- return main.TRUE
- except pexepct.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_flow(self):
- '''
- Calls the ./get_flow.py all and checks:
- - If each FlowPath has at least one FlowEntry
- - That there are no "NOT"s found
- returns TRUE/FALSE
- '''
- try:
- flowEntryDetect = 1
- count = 0
- self.handle.sendline("clear")
- time.sleep(1)
- self.handle.sendline(self.home + "/web/get_flow.py all")
- self.handle.expect("get_flow")
- while 1:
- i=self.handle.expect(['FlowPath','FlowEntry','NOT','\$',pexpect.TIMEOUT],timeout=180)
- if i==0:
- count = count + 1
- if flowEntryDetect == 0:
- main.log.info(self.name + ": FlowPath without FlowEntry")
- return main.FALSE
- else:
- flowEntryDetect = 0
- elif i==1:
- flowEntryDetect = 1
- elif i==2:
- main.log.error(self.name + ": Found a NOT")
- return main.FALSE
- elif i==3:
- if count == 0:
- main.log.info(self.name + ": There don't seem to be any flows here...")
- return main.FALSE
- else:
- main.log.info(self.name + ": All flows pass")
- main.log.info(self.name + ": Number of FlowPaths: "+str(count))
- return main.TRUE
- elif i==4:
- main.log.error(self.name + ":Check_flow() - Command Timeout!")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def get_flow(self, *flowParams):
- '''
- Returns verbose output of ./get_flow.py
- '''
- try:
- if len(flowParams)==1:
- if str(flowParams[0])=="all":
- self.execute(cmd="\n",prompt="\$",timeout=60)
- main.log.info(self.name + ": Getting all flow data...")
- data = self.execute(cmd=self.home + "/scripts/TestON_get_flow.sh all",prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- else:
- main.log.info(self.name + ": Retrieving flow "+str(flowParams[0])+" data...")
- data = self.execute(cmd=self.home +"/scripts/TestON_get_flow.sh "+str(flowParams[0]),prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- elif len(flowParams)==5:
- main.log.info(self.name + ": Retrieving flow installer data...")
- data = self.execute(cmd=self.home + "/scripts/TestON_get_flow.sh "+str(flowParams[0])+" "+str(flowParams[1])+" "+str(flowParams[2])+" "+str(flowParams[3])+" "+str(flowParams[4]),prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- elif len(flowParams)==4:
- main.log.info(self.name + ": Retrieving flow endpoints...")
- data = self.execute(cmd=self.home + "/scripts/TestON_get_flow.sh "+str(flowParams[0])+" "+str(flowParams[1])+" "+str(flowParams[2])+" "+str(flowParams[3]),prompt="done",timeout=150)
- self.execute(cmd="\n",prompt="\$",timeout=60)
- return data
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
-# http://localhost:8080/wm/onos/ng/switches/json
-# http://localhost:8080/wm/onos/ng/links/json
-# http://localhost:8080/wm/onos/registry/controllers/json
-# http://localhost:8080/wm/onos/registry/switches/json"
-
- def get_json(self, url):
- '''
- Helper functions used to parse the json output of a rest call
- '''
- try:
- try:
- command = "curl -s %s" % (url)
- result = os.popen(command).read()
- parsedResult = json.loads(result)
- except:
- print "REST IF %s has issue" % command
- parsedResult = ""
-
- if type(parsedResult) == 'dict' and parsedResult.has_key('code'):
- print "REST %s returned code %s" % (command, parsedResult['code'])
- parsedResult = ""
- return parsedResult
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_switch(self,RestIP,correct_nr_switch, RestPort ="8080" ):
- '''
- Used by check_status
- '''
- try:
- buf = ""
- retcode = 0
- url="http://%s:%s/wm/onos/topology/switches" % (RestIP, RestPort)
- parsedResult = self.get_json(url)
- if parsedResult == "":
- retcode = 1
- return (retcode, "Rest API has an issue")
- url = "http://%s:%s/wm/onos/registry/switches" % (RestIP, RestPort)
- registry = self.get_json(url)
-
- if registry == "":
- retcode = 1
- return (retcode, "Rest API has an issue")
-
- cnt = 0
- active = 0
-
- for s in parsedResult:
- cnt += 1
- if s['state'] == "ACTIVE":
- active += 1
-
- buf += "switch: network %d : %d switches %d active\n" % (0+1, cnt, active)
- if correct_nr_switch != cnt:
- buf += "switch fail: network %d should have %d switches but has %d\n" % (1, correct_nr_switch, cnt)
- retcode = 1
-
- if correct_nr_switch != active:
- buf += "switch fail: network %d should have %d active switches but has %d\n" % (1, correct_nr_switch, active)
- retcode = 1
-
- return (retcode, buf)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_link(self,RestIP, nr_links, RestPort = "8080"):
- '''
- Used by check_status
- '''
- try:
- buf = ""
- retcode = 0
-
- url = "http://%s:%s/wm/onos/topology/links" % (RestIP, RestPort)
- parsedResult = self.get_json(url)
-
- if parsedResult == "":
- retcode = 1
- return (retcode, "Rest API has an issue")
-
- buf += "link: total %d links (correct : %d)\n" % (len(parsedResult), nr_links)
- intra = 0
- interlink=0
-
- for s in parsedResult:
- intra = intra + 1
-
- if intra != nr_links:
- buf += "link fail\n"
- retcode = 1
-
- return (retcode, buf)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_status_report(self, ip, numoswitch, numolink, port="8080"):
- '''
- Checks the number of swithes & links that ONOS sees against the supplied values.
- Writes to the report log.
- '''
- try:
- main.log.info(self.name + ": Making some rest calls...")
- switch = self.check_switch(ip, int(numoswitch), port)
- link = self.check_link(ip, int(numolink), port)
- value = switch[0]
- value += link[0]
- main.log.report( self.name + ": \n-----\n%s%s-----\n" % ( switch[1], link[1]) )
- if value != 0:
- return main.FALSE
- else:
- # "PASS"
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_status(self, ip, numoswitch, numolink, port = "8080"):
- '''
- Checks the number of swithes & links that ONOS sees against the supplied values.
- Writes to the main log.
- '''
- try:
- main.log.info(self.name + ": Making some rest calls...")
- switch = self.check_switch(ip, int(numoswitch), port)
- link = self.check_link(ip, int(numolink), port)
- value = switch[0]
- value += link[0]
- main.log.info(self.name + ": \n-----\n%s%s-----\n" % ( switch[1], link[1]) )
- if value != 0:
- return main.FALSE
- else:
- # "PASS"
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def check_for_no_exceptions(self):
- '''
- TODO: Rewrite
- Used by CassndraCheck.py to scan ONOS logs for Exceptions
- '''
- try:
- self.handle.sendline("dsh 'grep Exception ~/ONOS/onos-logs/onos.*.log'")
- self.handle.expect("\$ dsh")
- self.handle.expect("\$")
- output = self.handle.before
- main.log.info(self.name + ": " + output )
- if re.search("Exception",output):
- return main.FALSE
- else :
- return main.TRUE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
- def git_pull(self, comp1=""):
- '''
- Assumes that "git pull" works without login
-
- This function will perform a git pull on the ONOS instance.
- If used as git_pull("NODE") it will do git pull + NODE. This is
- for the purpose of pulling from other nodes if necessary.
-
- Otherwise, this function will perform a git pull in the
- ONOS repository. If it has any problems, it will return main.ERROR
- If it successfully does a git_pull, it will return a 1.
- If it has no updates, it will return a 0.
-
- '''
- try:
- main.log.info(self.name + ": Stopping ONOS")
- self.stop()
- self.handle.sendline("cd " + self.home)
- self.handle.expect("ONOS\$")
- if comp1=="":
- self.handle.sendline("git pull")
- else:
- self.handle.sendline("git pull " + comp1)
-
- uptodate = 0
- i=self.handle.expect(['fatal','Username\sfor\s(.*):\s','Unpacking\sobjects',pexpect.TIMEOUT,'Already up-to-date','Aborting'],timeout=1800)
- #debug
- #main.log.report(self.name +": \n"+"git pull response: " + str(self.handle.before) + str(self.handle.after))
- if i==0:
- main.log.error(self.name + ": Git pull had some issue...")
- return main.ERROR
- elif i==1:
- main.log.error(self.name + ": Git Pull Asking for username!!! BADD!")
- return main.ERROR
- elif i==2:
- main.log.info(self.name + ": Git Pull - pulling repository now")
- self.handle.expect("ONOS\$", 120)
- return 0
- elif i==3:
- main.log.error(self.name + ": Git Pull - TIMEOUT")
- return main.ERROR
- elif i==4:
- main.log.info(self.name + ": Git Pull - Already up to date")
- return 1
- elif i==5:
- main.log.info(self.name + ": Git Pull - Aborting... Are there conflicting git files?")
- return main.ERROR
- else:
- main.log.error(self.name + ": Git Pull - Unexpected response, check for pull errors")
- return main.ERROR
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-#********************************************************
-
-
- def git_compile(self):
- '''
- Compiles ONOS
- First runs mvn clean then mvn compile
- '''
- try:
- main.log.info(self.name + ": mvn clean")
- self.handle.sendline("cd " + self.home)
- self.handle.sendline("mvn clean")
- while 1:
- i=self.handle.expect(['There\sis\sinsufficient\smemory\sfor\sthe\sJava\sRuntime\sEnvironment\sto\scontinue','BUILD\sFAILURE','BUILD\sSUCCESS','ONOS\$',pexpect.TIMEOUT],timeout=30)
- if i == 0:
- main.log.error(self.name + ":There is insufficient memory for the Java Runtime Environment to continue.")
- return main.FALSE
- elif i == 1:
- main.log.error(self.name + ": Clean failure!")
- return main.FALSE
- elif i == 2:
- main.log.info(self.name + ": Clean success!")
- elif i == 3:
- main.log.info(self.name + ": Clean complete")
- break;
- elif i == 4:
- main.log.error(self.name + ": mvn clean TIMEOUT!")
- return main.FALSE
- else:
- main.log.error(self.name + ": unexpected response from mvn clean")
- return main.FALSE
-
- main.log.info(self.name + ": mvn compile")
- self.handle.sendline("mvn compile")
- while 1:
- i=self.handle.expect(['There\sis\sinsufficient\smemory\sfor\sthe\sJava\sRuntime\sEnvironment\sto\scontinue','BUILD\sFAILURE','BUILD\sSUCCESS','ONOS\$',pexpect.TIMEOUT],timeout=60)
- if i == 0:
- main.log.error(self.name + ":There is insufficient memory for the Java Runtime Environment to continue.")
- return main.FALSE
- if i == 1:
- main.log.error(self.name + ": Build failure!")
- return main.FALSE
- elif i == 2:
- main.log.info(self.name + ": Build success!")
- return main.TRUE
- elif i == 3:
- main.log.info(self.name + ": Build complete")
- return main.TRUE
- elif i == 4:
- main.log.error(self.name + ": mvn compile TIMEOUT!")
- return main.FALSE
- else:
- main.log.error(self.name + ": unexpected response from mvn compile")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def tcpdump(self, intf = "eth0"):
- '''
- Runs tpdump on an intferface and saves in onos-logs under the ONOS home directory
- intf can be specified, or the default eth0 is used
- '''
- try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("sudo tcpdump -n -i "+ intf + " -s0 -w " + self.home +"/onos-logs/tcpdump &")
- i=self.handle.expect(['No\ssuch\device','listening\son',pexpect.TIMEOUT],timeout=10)
- if i == 0:
- main.log.error(self.name + ": tcpdump - No such device exists. tcpdump attempted on: " + intf)
- return main.FALSE
- elif i == 1:
- main.log.info(self.name + ": tcpdump started on " + intf)
- return main.TRUE
- elif i == 2:
- main.log.error(self.name + ": tcpdump command timed out! Check interface name, given interface was: " + intf)
- return main.FALSE
- else:
- main.log.error(self.name + ": tcpdump - unexpected response")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def kill_tcpdump(self):
- '''
- Kills any tcpdump processes running
- '''
- try:
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("sudo kill -9 `ps -ef | grep \"tcpdump -n\" | grep -v grep | awk '{print $2}'`")
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def find_host(self,RestIP,RestPort,RestAPI,hostIP):
- retcode = 0
- retswitch = []
- retport = []
- retmac = []
- foundIP = []
- try:
- ##### device rest API is: 'host:8080/wm/onos/ng/switches/json' ###
- url ="http://%s:%s%s" %(RestIP,RestPort,RestAPI)
- print url
-
- try:
- command = "curl -s %s" % (url)
- result = os.popen(command).read()
- parsedResult = json.loads(result)
- print parsedResult
- except:
- print "REST IF %s has issue" % command
- parsedResult = ""
-
- if parsedResult == "":
- return (retcode, "Rest API has an error", retport, retmac)
- else:
- for switch in enumerate(parsedResult):
- #print switch
- for port in enumerate(switch[1]['ports']):
- if ( port[1]['devices'] != [] ):
- try:
- foundIP = port[1]['devices'][0]['ipv4addresses'][0]['ipv4']
- except:
- print "Error in detecting IP address."
- if foundIP == hostIP:
- retswitch.append(switch[1]['dpid'])
- retport.append(port[1]['desc'])
- retmac.append(port[1]['devices'][0]['mac'])
- retcode = retcode +1
- foundIP =''
- return(retcode, retswitch, retport, retmac)
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-#Perf test related functions
-
- def addPerfFlows(self, flowdef, numflows):
- main.log.info("ADD_FLOW RUNNING!!!! ")
- startTime=time.time()
- self.execute(cmd="/home/admin/ONOS/scripts"+"/add_"+str(numflows)+".py",prompt="\$",timeout=10)
- elapsedTime=time.time()-startTime
- main.log.info("AddFlows script run time: " + str(elapsedTime) + " seconds")
- time.sleep(15)
- return main.TRUE
-
- def removePerfFlows(self, flowdef, numflows):
- main.log.info("REMOVE_FLOW RUNNING!!!! ")
- startTime=time.time()
- self.execute(cmd="/home/admin/ONOS/scripts"+"/remove_"+str(numflows)+".py",prompt="\$",timeout=10)
- elapsedTime=time.time()-startTime
- main.log.info("RemoveFlows script run time: " + str(elapsedTime) + " seconds")
- time.sleep(15)
- return main.TRUE
-
- def start_tshark(self,flowtype, numflows):
- self.handle.sendline("")
- self.handle.expect("\$")
- self.execute(cmd='''rm /tmp/wireshark*''')
- self.handle.sendline("y")
- self.handle.expect("\$")
- self.execute(cmd='''tshark -i lo -t e | grep --color=auto CSM | grep --color=auto -E 'Flow|Barrier' > /tmp/tdump_'''+flowtype+"_"+str(numflows)+".txt &",prompt="Capturing",timeout=10)
- self.handle.sendline("")
- self.handle.expect("\$")
- main.log.info("TSHARK STARTED!!!")
- return main.TRUE
-
- def stop_tshark(self):
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("sudo kill -9 `ps -ef | grep \"tshark -i\" | grep -v grep | awk '{print $2}'`")
- self.handle.sendline("")
- self.handle.expect("\$")
- main.log.info("TSHARK STOPPED!!!")
- return main.TRUE
-
- def generateFlows(self, flowdef, flowtype, numflows, ip):
- main.log.info("GENERATE FLOWS RUNNING!!!")
- #main.log.info("Test" + flowdef+"/"+flowtype+"_"+str(numflows)+".py")
- f = open(flowdef+"/"+flowtype+"_"+str(numflows)+".py", 'w')
- f.write('''#! /usr/bin/python\n''')
- f.write('import json\n')
- f.write('import requests\n')
- f.write('''url = 'http://'''+ip+''':8080/wm/onos/datagrid/add/intents/json'\n''')
- f.write('''headers = {'Content-type': 'application/json', 'Accept': 'application/json'}\n''')
-
- intents = []
- idx = 0
- for i in range(6,(numflows+6)):
- mac3 = idx / 255
- mac4 = idx % 255
- str_mac3 = "%0.2x" % mac3
- str_mac4 = "%0.2x" % mac4
- srcMac = '00:01:'+str_mac3+':'+str_mac4+':00:00'
- dstMac = '00:02:'+str_mac3+':'+str_mac4+':00:00'
- srcSwitch = '00:00:00:00:00:00:10:00'
- dstSwitch = '00:00:00:00:00:00:10:00'
- srcPort = 1
- dstPort = 2
-
- intent = {'intent_id': '%d' %(i),'intent_type':'shortest_intent_type','intent_op':flowtype,'srcSwitch':srcSwitch,'srcPort':srcPort,'srcMac':srcMac,'dstSwitch':dstSwitch,'dstPort':dstPort,'dstMac':dstMac}
- intents.append(intent)
- idx = idx + 1
- f.write('''s=''')
- f.write(json.dumps(intents, sort_keys = True))
- f.write('''\nr = requests.post(url, data=json.dumps(s), headers = headers)''')
- #f.flush()
- #subprocess.Popen(flowdef, stdout=f, stderr=f, shell=True)
- #f.close()
- os.system("chmod a+x "+flowdef+"/"+flowtype+"_"+str(numflows)+".py")
-
- return main.TRUE
-
- def getFile(self, numflows, ip, directory, flowparams):
- main.log.info("GETTING FILES FROM TEST STATION: "+str(ip))
- #for i in range(0,3):
- print str(numflows) + " "+str(flowparams[numflows])
- self.handle.sendline("scp admin@10.128.7.7:/home/admin/TestON/tests/OnosFlowPerf/add_"+str(flowparams[numflows])+".py admin@10.128.5.51:/home/admin/ONOS/scripts/" )
-
- self.handle.sendline("scp admin@10.128.7.7:/home/admin/TestON/tests/OnosFlowPerf/remove_"+str(flowparams[numflows])+".py admin@10.128.5.51:/home/admin/ONOS/scripts/" )
-
- return main.TRUE
-
- def printPerfResults(self, flowtype, numflows, stime):
- import datetime
- self.handle.sendline("")
- self.handle.expect("\$")
- for (i,j) in zip(numflows,stime):
- startTime=datetime.datetime.fromtimestamp(j)
- tshark_file=open("/tmp/tdump_"+flowtype+"_"+str(i)+".txt",'r')
- allFlowmods=tshark_file.readlines()
- time.sleep(5)
- firstFlowmod=allFlowmods[0]
- lastBarrierReply=allFlowmods[-1]
- #self.handle.sendline("")
- #self.handle.expect("\$")
- #self.handle.sendline("head -1 /tmp/tdump_"+flowtype+"_"+str(i)+".txt")
- #self.handle.expect("\(CSM\)")
- #firstFlowmod=self.handle.before
- #firstFlowmod=self.execute(cmd="head -1 /tmp/tdump_"+flowtype+"_"+str(i)+".txt",prompt="\$",timeout=10)
- #lastBarrierReply=self.execute(cmd="tail -n 1 /tmp/tdump_"+flowtype+"_"+str(i)+".txt",prompt="\$",timeout=10)
- firstFlowmodSplit=firstFlowmod.split()
- firstFlowmodTS=datetime.datetime.fromtimestamp(float(firstFlowmodSplit[0]))
- lastBarrierSplit=lastBarrierReply.split()
- lastBarrierTS=datetime.datetime.fromtimestamp(float(lastBarrierSplit[0]))
- main.log.report("Number of Flows: " + str(i))
- #main.log.info("Add Flow Start Time: " + str(startTime))
- main.log.report("First Flow mod seen after: " + str(float(datetime.timedelta.total_seconds(firstFlowmodTS-startTime)*1000))+"ms")
- main.log.report("Last Barrier Reply seen after: " + str(float(datetime.timedelta.total_seconds(lastBarrierTS-startTime)*1000))+"ms\n")
- main.log.report("Total Flow Setup Delay(from first flowmod): " + str(float(datetime.timedelta.total_seconds(lastBarrierTS-firstFlowmodTS)*1000))+"ms")
- main.log.report("Total Flow Setup Delay(from start): " + str(float(datetime.timedelta.total_seconds(lastBarrierTS-startTime)*1000))+"ms\n")
- main.log.report("Flow Setup Rate (using first flowmod TS): " + str(int(1000/datetime.timedelta.total_seconds(lastBarrierTS-firstFlowmodTS)))+" flows/sec")
- main.log.report("Flow Setup Rate (using start time): " + str(int(1000/datetime.timedelta.total_seconds(lastBarrierTS-startTime)))+" flows/sec")
- print "*****************************************************************"
- #main.log.info("first: " + str(firstFlowmod))
- #main.log.info(firstFlowmodSplit)
- #main.log.info("last: " + str(lastBarrierReply))
- tshark_file.close()
- return main.TRUE
-
- def isup(self):
- '''
- A more complete check to see if ONOS is up and running properly.
- First, it checks if the process is up.
- Second, it reads the logs for "Exception: Connection refused"
- Third, it makes sure the logs are actually moving.
- returns TRUE/FALSE accordingly.
- '''
- try:
- self.execute(cmd="\n",prompt="\$",timeout=10)
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd= "./onos.sh core status ",prompt="running",timeout=10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- tail1 = self.execute(cmd="tail " + self.home + "/onos-logs/onos.*.log",prompt="\$",timeout=10)
- time.sleep(10)
- self.execute(cmd="\n",prompt="\$",timeout=10)
- tail2 = self.execute(cmd="tail " + self.home + "/onos-logs/onos.*.log",prompt="\$",timeout=10)
- pattern = '(.*)1 instance(.*)'
- patternUp = 'Sending LLDP out'
- pattern2 = '(.*)Exception: Connection refused(.*)'
- # if utilities.assert_matches(expect=pattern,actual=response,onpass="ONOS process is running...",onfail="ONOS process not running..."):
-
- if re.search(pattern, response):
- if re.search(patternUp,tail2):
- main.log.info(self.name + ": ONOS process is running...")
- if tail1 == tail2:
- main.log.error(self.name + ": ONOS is frozen...")#logs aren't moving
- return main.FALSE
- elif re.search( pattern2,tail1 ):
- main.log.info(self.name + ": Connection Refused found in onos log")
- return main.FALSE
- elif re.search( pattern2,tail2 ):
- main.log.info(self.name + ": Connection Refused found in onos log")
- return main.FALSE
- else:
- main.log.info(self.name + ": Onos log is moving! It's looking good!")
- return main.TRUE
- else:
- main.log.info(self.name + ": ONOS not yet sending out LLDP messages")
- return main.FALSE
- else:
- main.log.error(self.name + ": ONOS process not running...")
- return main.FALSE
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.name + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def sendline(self, cmd):
- self.handle.sendline(cmd)
diff --git a/TestON/drivers/common/cli/ramcloudclidriver.py b/TestON/drivers/common/cli/ramcloudclidriver.py
deleted file mode 100644
index 5b19508..0000000
--- a/TestON/drivers/common/cli/ramcloudclidriver.py
+++ /dev/null
@@ -1,289 +0,0 @@
-#!/usr/bin/env python
-'''
-Created on 31-May-2013
-
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
-
-
- TestON is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
-
- TestON is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-
-RamCloudCliDriver is the basic driver which will handle the RamCloud server functions
-'''
-
-import pexpect
-import struct
-import fcntl
-import os
-import signal
-import re
-import sys
-import core.teston
-import time
-
-sys.path.append("../")
-from drivers.common.clidriver import CLI
-
-class RamCloudCliDriver(CLI):
- '''
-RamCloudCliDriver is the basic driver which will handle the RamCloud server functions
- '''
- def __init__(self):
- super(CLI, self).__init__()
- self.handle = self
- self.wrapped = sys.modules[__name__]
-
- def connect(self, **connectargs):
- # Here the main is the TestON instance after creating all the log handles.
- self.port = None
- for key in connectargs:
- vars(self)[key] = connectargs[key]
- self.home = "~/ONOS"
- for key in self.options:
- if key == "ONOShome":
- self.home = self.options['ONOShome']
- break
-
-
- self.name = self.options['name']
- self.handle = super(RamCloudCliDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd, home = self.home)
-
- self.ssh_handle = self.handle
- if self.handle :
- return main.TRUE
- else :
- main.log.error(self.name+": Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error(self.name+": Failed to connect to the Onos system")
- return main.FALSE
-
- def kill_serv(self):
- import re
- try:
- self.handle.sendline("ps -ef |grep 'master/server' |awk 'NR==1 {print $2}' |xargs sudo kill -9")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("ps -ef |grep 'master/server' |wc -l")
- self.handle.expect(["wc -l",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.after
- if re.search("1",response):
- return "RAMCloud Server Killed!"
- else:
- return "ERROR!!! RAMCLOUd SERVER MAY NOT HAVE BEEN KILLED PROPERLY!!!"
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.hane + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
- def kill_coord(self):
- import re
- try:
- self.handle.sendline("ps -ef |grep 'master/coordinator' |awk 'NR==1 {print $2}' |xargs sudo kill -9")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("ps -ef |grep 'master/coordinator' |wc -l")
- self.handle.expect(["wc -l",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.after
- if re.search("1",response):
- return "RAMCloud Coordinator Killed!"
- else:
- return "ERROR!!! RAMCLOUD COORDINATOR MAY NOT HAVE BEEN KILLED PROPERLY!!!"
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.hane + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
-
- def start_serv(self):
- '''
- This Function will start RamCloud Servers
- '''
- main.log.info(self.name+": Starting RAMCloud Server" )
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc-server start")
- self.handle.expect(["onos.sh rc-server start",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
- #print ("RESPONSE IS: "+response)
- time.sleep(5)
- if re.search("Killed\sexisting\sprocess", response):
- main.log.info(self.name + ": Previous RAMCloud killed. ")
- if re.search("Starting\sRAMCloud\sserver",response):
- main.log.info(self.name + ": RAMCloud Server Started")
- return main.TRUE
- else:
- main.log.info(self.name + ": Failed to start RAMCloud Server"+response)
- return main.FALSE
- elif re.search("Starting\sRAMCloud\sserver",response):
- main.log.info(self.name + ": RAMCloud Server Started")
- return main.TRUE
- else:
- main.log.info(self.name + ": Failed to start RAMCloud Server"+response)
- return main.FALSE
-
-
- def start_coor(self):
- '''
- This Function will start RamCloud
- '''
- main.log.info(self.name+": Starting RAMCloud Coordinator" )
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc-coord start")
- self.handle.expect(["onos.sh rc-coord start",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
- if re.search("Starting\sRAMCloud\scoordinator\s", response):
- if re.search("Killed\sexisting\sprocess", response):
- main.log.warn(self.name+": Process was already running, killing existing process")
- main.log.info(self.name+": RAMCloud Coordinator Started ")
- return main.TRUE
- else:
- main.log.error(self.name+": Failed to start RAMCloud Coordinator"+ response)
- return main.FALSE
-
- def status_serv(self):
- '''
- This Function will return the Status of the RAMCloud
- '''
- main.log.info(self.name + ": Getting RC-Server Status")
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc-server status")
- self.handle.expect(["onos.sh rc-server status",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
-
- if re.search("0\sRAMCloud\sserver\srunning", response) :
- main.log.info(self.name+": RAMCloud not running")
- return main.FALSE
- elif re.search("1\sRAMCloud\sserver\srunning",response):
- main.log.warn(self.name+": RAMCloud Running")
- return main.TRUE
- else:
- main.log.info( self.name+": WARNING: status recieved unknown response")
- return main.FALSE
-
- def status_coor(self):
- '''
- This Function will return the Status of the RAMCloud
- '''
- main.log.info(self.name + ": Getting RC-Coord Status")
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc-coord status")
- i=self.handle.expect(["onos.sh rc-coord status",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
- #return response
-
- if re.search("0\sRAMCloud\scoordinator\srunning", response) :
- main.log.warn(self.name+": RAMCloud Coordinator not running")
- return main.FALSE
- elif re.search("1\sRAMCloud\scoordinator\srunning", response):
- main.log.info(self.name+": RAMCloud Coordinator Running")
- return main.TRUE
- else:
- main.log.warn( self.name+": coordinator status recieved unknown response")
- return main.FALSE
-
- def stop_serv(self):
- '''
- This Function will stop the RAMCloud if it is Running
- '''
- main.log.info(self.name + ": Stopping RC-Server")
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc-server stop")
- self.handle.expect(["onos.sh rc-server stop",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
- if re.search("Killed\sexisting\sprocess",response):
- main.log.info("RAMCloud Server Stopped")
- return main.TRUE
- else:
- main.log.warn(self.name+": RAMCloud is not Running")
- return main.FALSE
-
- def del_db(self):
- '''
- This function will clean out the database
- '''
- main.log.info(self.name + ": Deleting RC Database")
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh rc deldb")
- self.handle.expect(["\[y/N\]",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("y")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
- if re.search("DONE",response) or re.search("Terminated",response):
- main.log.info("RAMCloud Database Cleaned")
- return main.TRUE
- else:
- main.log.warn("Something wrong in Cleaning Database")
- main.log.warn(self.handle.before)
- return main.FALSE
-
-
- def stop_coor(self):
- '''
- This Function will stop the RAMCloud if it is Running
- '''
- main.log.info(self.name + ": Stopping RC-Coord")
- self.handle.sendline("")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("cd "+self.home)
- self.handle.sendline( "./onos.sh rc-coord stop")
- self.handle.expect(["onos.sh rc-coord stop",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.before + self.handle.after
- if re.search("Killed\sexisting\sprocess",response):
- main.log.info(self.name+": RAMCloud Coordinator Stopped")
- return main.TRUE
- else:
- main.log.warn(self.name+": RAMCloud was not Running")
- return main.FALSE
-
- def disconnect(self):
- '''
- Called at the end of the test to disconnect the ssh handle.
- '''
- response = ''
- if self.handle:
- self.handle.sendline("exit")
- self.handle.expect(["closed",pexpect.EOF,pexpect.TIMEOUT])
- else :
- main.log.error("Connection failed to the host when trying to disconnect from RAMCloud component")
- response = main.FALSE
- return response
diff --git a/TestON/drivers/common/cli/ramcloudclidriver.py.wip b/TestON/drivers/common/cli/ramcloudclidriver.py.wip
deleted file mode 100644
index 6a961ee..0000000
--- a/TestON/drivers/common/cli/ramcloudclidriver.py.wip
+++ /dev/null
@@ -1,151 +0,0 @@
-#!/usr/bin/env python
-'''
-Created on 31-May-2013
-
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
-
-
- TestON is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
-
- TestON is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-
-CassandraCliDriver is the basic driver which will handle the Cassandra functions
-'''
-
-import pexpect
-import struct
-import fcntl
-import os
-import signal
-import re
-import sys
-import core.teston
-import time
-
-sys.path.append("../")
-from drivers.common.clidriver import CLI
-
-class CassandraCliDriver(CLI):
- '''
- CassandraCliDriver is the basic driver which will handle the Cassandra's functions
- '''
- def __init__(self):
- super(CLI, self).__init__()
- self.handle = self
- self.wrapped = sys.modules[__name__]
-
- def connect(self, **connectargs):
- # Here the main is the TestON instance after creating all the log handles.
- self.port = None
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- self.handle = super(CassandraCliDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
-
- self.ssh_handle = self.handle
- if self.handle :
- #self.start()
- return main.TRUE
- else :
- main.log.error("Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error("Failed to connect to the Onos system")
- return main.FALSE
-
-
- def start(self):
- '''
- This Function will start the Cassandra
- '''
- main.log.info( "Starting Cassandra" )
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("~/ONOS/start-cassandra.sh start")
- self.handle.expect("start-cassandra.sh start")
- self.handle.expect("\$")
- response = self.handle.before + self.handle.after
- time.sleep(5)
- if re.search("Starting\scassandra(.*)", response):
- main.log.info("Cassandra Started ")
- return main.TRUE
- else:
- main.log.error("Failed to start Cassandra"+ response)
- return main.FALSE
-
- def status(self):
- '''
- This Function will return the Status of the Cassandra
- '''
- time.sleep(5)
- self.execute(cmd="\r",prompt="\$",timeout=10)
- response = self.execute(cmd="~/ONOS/start-cassandra.sh status ",prompt="\d+\sinstance\sof\scassandra\srunning(.*)",timeout=10)
-
-
- self.execute(cmd="\r",prompt="\$",timeout=10)
- return response
-
- if re.search("0\sinstance\sof\scassandra\srunning(.*)") :
- main.log.info("Cassandra not running")
- return main.TRUE
- elif re.search("1\sinstance\sof\scassandra\srunning(.*)"):
- main.log.warn("Cassandra Running")
- return main.TRUE
-
- def stop(self):
- '''
- This Function will stop the Cassandra if it is Running
- '''
- self.execute(cmd="\r",prompt="\$",timeout=10)
- time.sleep(5)
- response = self.execute(cmd="~/ONOS/start-cassandra.sh stop ",prompt="Killed\sexisting\sprosess(.*)",timeout=10)
- self.execute(cmd="\r",prompt="\$",timeout=10)
- if re.search("Killed\sexisting\sprosess(.*)",response):
- main.log.info("Cassandra Stopped")
- return main.TRUE
- else:
- main.log.warn("Cassndra is not Running")
- return main.FALSE
-
- def disconnect(self):
- '''
- Called at the end of the test to disconnect the ssh handle.
- '''
- response = ''
- if self.handle:
- self.handle.sendline("exit")
- self.handle.expect("closed")
- else :
- main.log.error("Connection failed to the host")
- response = main.FALSE
- return response
-
- def isup(self):
- '''
- A more complete status check of cassandra.
- Tries 5 times to call start-cassandra.sh status
- returns TRUE if it sees four occurances of both Up, and Normal
- '''
- tries = 5
- main.log.info("trying %i times" % tries )
- for i in range(tries):
- self.execute(cmd="\r",prompt="\$",timeout=10)
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("~/ONOS/start-cassandra.sh status")
- self.handle.expect("sh status")
- self.handle.expect("\$")
- result = self.handle.before + self.handle.after
- pattern = '(.*)Up(.*)Normal(.*)\n(.*)Up(.*)Normal(.*)\n(.*)Up(.*)Normal(.*)\n(.*)Up(.*)Normal(.*)'
- if re.search(pattern, result):
- return main.TRUE
- return main.FALSE
diff --git a/TestON/drivers/common/cli/sdnipclidriver.py b/TestON/drivers/common/cli/sdnipclidriver.py
deleted file mode 100644
index 58dfb03..0000000
--- a/TestON/drivers/common/cli/sdnipclidriver.py
+++ /dev/null
@@ -1,73 +0,0 @@
-import time
-import pexpect
-import struct, fcntl, os, sys, signal
-import sys
-import re
-import json
-sys.path.append("../")
-from drivers.common.clidriver import CLI
-
-
-class SDNIPCliDriver(CLI):
-
- def __init__(self):
- super(CLI, self).__init__()
-
- def connect(self, **connectargs):
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- self.name = self.options['name']
- self.handle = super(SDNIPCliDriver,self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd)
-
- if self.handle:
- return self.handle
- else :
- main.log.info("NO HANDLE")
- return main.FALSE
-
- def check_routes(self, brand, ip, user, pw):
- self.handle.sendline("")
- self.handle.expect("\$")
- main.log.info("Connecting to Pronto switch")
- child = pexpect.spawn("telnet " + ip)
- i = child.expect(["login:", "CLI#",pexpect.TIMEOUT])
- if i == 0:
- main.log.info("Username and password required. Passing login info.")
- child.sendline(user)
- child.expect("Password:")
- child.sendline(pw)
- child.expect("CLI#")
- main.log.info("Logged in, getting flowtable.")
- child.sendline("flowtable brief")
- for t in range (9):
- t2 = 9 - t
- main.log.info("\r" + str(t2))
- sys.stdout.write("\033[F")
- time.sleep(1)
- time.sleep(10)
- main.log.info("Scanning flowtable")
- child.expect("Flow table show")
- count = 0
- while 1:
- i = child.expect(['17\d\.\d{1,3}\.\d{1,3}\.\d{1,3}','CLI#',pexpect.TIMEOUT])
- if i == 0:
- count = count + 1
- elif i == 1:
- a ="Pronto flows: " + str(count) + "\nDone\n"
- main.log.info(a)
- break
- else:
- break
- return count
- def disconnect(self):
- '''
- Called when Test is complete to disconnect the Quagga handle.
- '''
- response = ''
- try:
- self.handle.close()
- except:
- main.log.error("Connection failed to the host")
- response = main.FALSE
- return response
diff --git a/TestON/drivers/common/cli/zookeeperclidriver.py b/TestON/drivers/common/cli/zookeeperclidriver.py
deleted file mode 100644
index 9a35366..0000000
--- a/TestON/drivers/common/cli/zookeeperclidriver.py
+++ /dev/null
@@ -1,197 +0,0 @@
-#!/usr/bin/env python
-'''
-Created on 31-May-2013
-
-@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
-
-
- TestON is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
-
- TestON is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-
-ZookeeperCliDriver is the basic driver which will handle the Zookeeper functions
-'''
-
-import pexpect
-import struct
-import fcntl
-import os
-import signal
-import re
-import sys
-import core.teston
-import time
-
-sys.path.append("../")
-from drivers.common.clidriver import CLI
-
-class ZookeeperCliDriver(CLI):
- '''
- ZookeeperCliDriver is the basic driver which will handle the Zookeeper's functions
- '''
- def __init__(self):
- super(CLI, self).__init__()
- self.handle = self
- self.wrapped = sys.modules[__name__]
-
- def kill(self):
- import re
- try:
- self.handle.sendline("ps -ef |grep 'zookeeper.log.dir' |awk 'NR==1 {print $2}' |xargs sudo kill -9")
- self.handle.expect(["\$",pexpect.EOF,pexpect.TIMEOUT])
- self.handle.sendline("ps -ef |grep 'zookeeper.log.dir' |wc -l")
- self.handle.expect(["wc -l",pexpect.EOF,pexpect.TIMEOUT])
- response = self.handle.after
- if re.search("1",response):
- return "Zookeeper Killed!"
- else:
- return "ERROR!!! ZOOKEEPER MAY NOT HAVE BEEN KILLED PROPERLY!!!"
- except pexpect.EOF:
- main.log.error(self.name + ": EOF exception found")
- main.log.error(self.hane + ": " + self.handle.before)
- main.cleanup()
- main.exit()
- except:
- main.log.info(self.name + ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.log.error( traceback.print_exc() )
- main.log.info(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
- main.cleanup()
- main.exit()
-
-
-
- def connect(self, **connectargs):
- # Here the main is the TestON instance after creating all the log handles.
- self.port = None
- for key in connectargs:
- vars(self)[key] = connectargs[key]
- self.home = "~/ONOS"
- self.zkhome = "~/zookeeper-3.4.6"
- self.clustername = "sanity-rc-onos"
- #self.home = "~/zookeeper-3.4.5"
- for key in self.options:
- if key == "home":
- self.home = self.options['home']
- break
-
- self.name = self.options['name']
- self.handle = super(ZookeeperCliDriver, self).connect(user_name = self.user_name, ip_address = self.ip_address,port = self.port, pwd = self.pwd, home = self.home)
-
- self.ssh_handle = self.handle
- if self.handle :
- return main.TRUE
- else :
- main.log.error("Connection failed to the host "+self.user_name+"@"+self.ip_address)
- main.log.error(self.name + ": Failed to connect to Zookeeper")
- return main.FALSE
-
-
- def start(self):
- '''
- This Function will start the Zookeeper
- '''
- main.log.info(self.name + ": Starting Zookeeper" )
- self.handle.sendline("")
- self.handle.expect("\$")
- self.handle.sendline("cd "+self.home)
- self.handle.sendline("./onos.sh zk start")
- self.handle.expect("zk start")
- self.handle.expect("\$")
- response = self.handle.before + self.handle.after
- if re.search("STARTED", response):
- main.log.info(self.name + ": Zookeeper Started ")
- return main.TRUE
- elif re.search("running", response):
- main.log.warn(self.name +": zookeeper ... already running")
- return main.TRUE
- else:
- main.log.error(self.name + ": Failed to start Zookeeper"+ response)
- return main.FALSE
-
- def status(self):
- '''
- This Function will return the Status of the Zookeeper
- '''
- self.execute(cmd="\n",prompt="\$",timeout=10)
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd="./onos.sh zk status ",prompt="JMX",timeout=10)
- response=self.handle.after
- self.execute(cmd="\n",prompt="\$",timeout=10)
- return self.handle.before + self.handle.after
-
- def stop(self):
- '''
- This Function will stop the Zookeeper if it is Running
- '''
- self.execute(cmd="\n",prompt="\$",timeout=10)
- time.sleep(1)
- self.handle.sendline("cd "+self.home)
- response = self.execute(cmd="./onos.sh zk stop ",prompt="$",timeout=10)
- if re.search("stopping",response):
- main.log.info(self.name + ": Zookeeper Stopped")
- return main.TRUE
- else:
- main.log.warn(self.name + ": No zookeeper to stop")
- return main.FALSE
-
- def disconnect(self):
- '''
- Called at the end of the test to disconnect the ZK handle
- '''
- response = ''
- if self.handle:
- self.handle.sendline("exit")
- self.handle.expect("closed")
- else :
- main.log.error(self.name + ": Connection failed to the host")
- response = main.FALSE
- return response
-
-#**********************************************************************************************
-#**********************************************************************************************
-# findMaster is used to determine the master controller of a switch.
-# it uses the switchList which is a json dict, and finds the first controller of
-# each switch
-#**********************************************************************************************
-#**********************************************************************************************
-
-
- def findMaster(self, switchDPID, switchList):
- import json
- decoded = json.loads(switchList)
- if switchList=="":
- return "NO CONTROLLERS FOUND"
- for k in decoded.iteritems():
- k2 = json.dumps(k)
- if re.search(switchDPID,k2):
- k3 = k2.split(',')
- k4 = k3[1].split()
- k5 = k4[1].split('"')
- return k5[1]
- return "NO CONTROLLERS FOUND"
-
- def isup(self):
- '''
- Calls the zookeeper status and returns TRUE if it has an assigned Mode to it.
- '''
- self.execute(cmd="\n",prompt="\$",timeout=10)
- response = self.execute(cmd=self.home + "/onos.sh zk status ",prompt="Mode",timeout=10)
- pattern = '(.*)Mode(.*)'
- if re.search(pattern, response):
- main.log.info(self.name + ": Zookeeper is up.")
- return main.TRUE
- else:
- main.log.info(self.name + ": Zookeeper is down.")
- return main.FALSE
-
-
diff --git a/TestON/drivers/common/clidriver.py_back b/TestON/drivers/common/clidriver.py_back
deleted file mode 100644
index 0406e48..0000000
--- a/TestON/drivers/common/clidriver.py_back
+++ /dev/null
@@ -1,218 +0,0 @@
-#!/usr/bin/env python
-'''
-Created on 24-Oct-2012
-
-@authors: Anil Kumar (anilkumar.s@paxterrasolutions.com),
- Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
-
-
- TestON is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
-
- TestON is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-
-
-'''
-import pexpect
-import struct, fcntl, os, sys, signal
-import sys, re
-sys.path.append("../")
-
-from drivers.component import Component
-class CLI(Component):
- '''
- This will define common functions for CLI included.
- '''
- def __init__(self):
- super(Component, self).__init__()
-
- def connect(self,**connectargs):
- '''
- Connection will establish to the remote host using ssh.
- It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- connect_result = super(CLI, self).connect()
- ssh_newkey = 'Are you sure you want to continue connecting'
- refused = "ssh: connect to host "+self.ip_address+" port 22: Connection refused"
- if self.port:
- self.handle =pexpect.spawn('ssh -p '+self.port+' '+self.user_name+'@'+self.ip_address,maxread=50000)
- else :
- self.handle =pexpect.spawn('ssh -X '+self.user_name+'@'+self.ip_address,maxread=50000)
-
- self.handle.logfile = self.logfile_handler
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused,'>|#|$'],120)
-
- if i==0:
- main.log.info("ssh key confirmation received, send yes")
- self.handle.sendline('yes')
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
- if i==1:
- main.log.info("ssh connection asked for password, gave password")
- self.handle.sendline(self.pwd)
- self.handle.expect('>|#|$')
-
- elif i==2:
- main.log.error("Connection timeout")
- return main.FALSE
- elif i==3: #timeout
- main.log.error("No route to the Host "+self.user_name+"@"+self.ip_address)
- return main.FALSE
- elif i==4:
- main.log.error("ssh: connect to host "+self.ip_address+" port 22: Connection refused")
- return main.FALSE
- elif i==5:
- main.log.info("Password not required logged in")
-
- self.handle.sendline("\r")
- self.handle.expect('>|#|$', 2)
- return self.handle
-
-
- def disconnect(self):
- result = super(CLI, self).disconnect(self)
- result = main.TRUE
- #self.execute(cmd="exit",timeout=120,prompt="(.*)")
-
-
- def execute(self, **execparams):
- '''
- It facilitates the command line execution of a given command. It has arguments as :
- cmd => represents command to be executed,
- prompt => represents expect command prompt or output,
- timeout => timeout for command execution,
- more => to provide a key press if it is on.
-
- It will return output of command exection.
- '''
-
- result = super(CLI, self).execute(self)
- defaultPrompt = '.*[$>\#]'
- args = utilities.parse_args(["CMD", "TIMEOUT", "PROMPT", "MORE"], **execparams)
- expectPrompt = args["PROMPT"] if args["PROMPT"] else defaultPrompt
- self.LASTRSP = ""
- timeoutVar = args["TIMEOUT"] if args["TIMEOUT"] else 10
- cmd = ''
- if args["CMD"]:
- cmd = args["CMD"]
- else :
- return 0
- if args["MORE"] == None:
- args["MORE"] = " "
- self.handle.sendline(cmd)
- self.lastCommand = cmd
- index = self.handle.expect([expectPrompt, "--More--", 'Command not found.', pexpect.TIMEOUT,"^:$"], timeout = timeoutVar)
- if index == 0:
- self.LASTRSP = self.LASTRSP + self.handle.before + self.handle.after
- main.log.info("Executed :"+str(cmd)+" \t\t Expected Prompt '"+ str(expectPrompt)+"' Found")
- elif index == 1:
- self.LASTRSP = self.LASTRSP + self.handle.before
- self.handle.send(args["MORE"])
- main.log.info("Found More screen to go , Sending a key to proceed")
- indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
- while indexMore == 0:
- main.log.info("Found anoother More screen to go , Sending a key to proceed")
- self.handle.send(args["MORE"])
- indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
- self.LASTRSP = self.LASTRSP + self.handle.before
- elif index ==2:
- main.log.error("Command not found")
- self.LASTRSP = self.LASTRSP + self.handle.before
- elif index ==3:
- main.log.error("Expected Prompt not found , Time Out!!")
- main.log.error( expectPrompt )
- return "Expected Prompt not found , Time Out!!"
-
- elif index == 4:
- self.LASTRSP = self.LASTRSP + self.handle.before
- #self.handle.send(args["MORE"])
- self.handle.sendcontrol("D")
- main.log.info("Found More screen to go , Sending a key to proceed")
- indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
- while indexMore == 0:
- main.log.info("Found anoother More screen to go , Sending a key to proceed")
- self.handle.sendcontrol("D")
- indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
- self.LASTRSP = self.LASTRSP + self.handle.before
-
- main.last_response = self.remove_contol_chars(self.LASTRSP)
- return self.LASTRSP
-
- def remove_contol_chars(self,response):
- #RE_XML_ILLEGAL = '([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])|([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])'%(unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff))
- #response = re.sub(RE_XML_ILLEGAL, "\n", response)
- response = re.sub(r"[\x01-\x1F\x7F]", "", response)
- #response = re.sub(r"\[\d+\;1H", "\n", response)
- response = re.sub(r"\[\d+\;\d+H", "", response)
- return response
-
- def runAsSudoUser(self,handle,pwd,default):
-
- i = handle.expect([".ssword:*",default, pexpect.EOF])
- if i==0:
- handle.sendline(pwd)
- handle.sendline("\r")
-
- if i==1:
- handle.expect(default)
-
- if i==2:
- main.log.error("Unable to run as Sudo user")
-
- return handle
-
- def onfail(self):
- if main.componentDictionary[self.name].has_key('onfail'):
- commandList = main.componentDictionary[self.name]['onfail'].split(",")
- for command in commandList :
- response = self.execute(cmd=command,prompt="(.*)",timeout=120)
-
- def secureCopy(self,user_name, ip_address,filepath, pwd,dst_path):
-
- #scp openflow@192.168.56.101:/home/openflow/sample /home/paxterra/Desktop/
-
- '''
- Connection will establish to the remote host using ssh.
- It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
- ssh_newkey = 'Are you sure you want to continue connecting'
- refused = "ssh: connect to host "+ip_address+" port 22: Connection refused"
- self.handle =pexpect.spawn('scp '+user_name+'@'+ip_address+':'+filepath+' '+dst_path)
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused],120)
-
- if i==0:
- main.log.info("ssh key confirmation received, send yes")
- self.handle.sendline('yes')
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
- if i==1:
- main.log.info("ssh connection asked for password, gave password")
- self.handle.sendline(pwd)
- #self.handle.expect(user_name)
-
- elif i==2:
- main.log.error("Connection timeout")
- pass
- elif i==3: #timeout
- main.log.error("No route to the Host "+user_name+"@"+ip_address)
- return main.FALSE
- elif i==4:
- main.log.error("ssh: connect to host "+ip_address+" port 22: Connection refused")
- return main.FALSE
-
- self.handle.sendline("\r")
-
- return self.handle
-
diff --git a/TestON/drivers/common/clidriver.py_new b/TestON/drivers/common/clidriver.py_new
deleted file mode 100644
index 9db8f6f..0000000
--- a/TestON/drivers/common/clidriver.py_new
+++ /dev/null
@@ -1,218 +0,0 @@
-#!/usr/bin/env python
-'''
-Created on 24-Oct-2012
-
-@authors: Anil Kumar (anilkumar.s@paxterrasolutions.com),
- Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
-
-
- TestON is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 2 of the License, or
- (at your option) any later version.
-
- TestON is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with TestON. If not, see <http://www.gnu.org/licenses/>.
-
-
-
-'''
-import pexpect
-import struct, fcntl, os, sys, signal
-import sys, re
-sys.path.append("../")
-
-from drivers.component import Component
-class CLI(Component):
- '''
- This will define common functions for CLI included.
- '''
- def __init__(self):
- super(Component, self).__init__()
-
- def connect(self,**connectargs):
- '''
- Connection will establish to the remote host using ssh.
- It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
- for key in connectargs:
- vars(self)[key] = connectargs[key]
-
- connect_result = super(CLI, self).connect()
- ssh_newkey = 'Are you sure you want to continue connecting'
- refused = "ssh: connect to host "+self.ip_address+" port 22: Connection refused"
- if self.port:
- self.handle =pexpect.spawn('ssh -p '+self.port+' '+self.user_name+'@'+self.ip_address,maxread=50000)
- else :
- self.handle =pexpect.spawn('ssh -X '+self.user_name+'@'+self.ip_address,maxread=50000)
-
- self.handle.logfile = self.logfile_handler
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused,'>|#|\$'],120)
-
- if i==0:
- main.log.info("ssh key confirmation received, send yes")
- self.handle.sendline('yes')
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
- if i==1:
- main.log.info("ssh connection asked for password, gave password")
- self.handle.sendline(self.pwd)
- self.handle.expect('>|#|\$')
-
- elif i==2:
- main.log.error("Connection timeout")
- return main.FALSE
- elif i==3: #timeout
- main.log.error("No route to the Host "+self.user_name+"@"+self.ip_address)
- return main.FALSE
- elif i==4:
- main.log.error("ssh: connect to host "+self.ip_address+" port 22: Connection refused")
- return main.FALSE
- elif i==5:
- main.log.info("Password not required logged in")
-
- self.handle.sendline("\n")
- self.handle.expect('>|#|\$', 2)
- return self.handle
-
-
- def disconnect(self):
- result = super(CLI, self).disconnect(self)
- result = main.TRUE
- #self.execute(cmd="exit",timeout=120,prompt="(.*)")
-
-
- def execute(self, **execparams):
- '''
- It facilitates the command line execution of a given command. It has arguments as :
- cmd => represents command to be executed,
- prompt => represents expect command prompt or output,
- timeout => timeout for command execution,
- more => to provide a key press if it is on.
-
- It will return output of command exection.
- '''
-
- result = super(CLI, self).execute(self)
- defaultPrompt = '.*[\$>\#]'
- args = utilities.parse_args(["CMD", "TIMEOUT", "PROMPT", "MORE"], **execparams)
- expectPrompt = args["PROMPT"] if args["PROMPT"] else defaultPrompt
- self.LASTRSP = ""
- timeoutVar = args["TIMEOUT"] if args["TIMEOUT"] else 10
- cmd = ''
- if args["CMD"]:
- cmd = args["CMD"]
- else :
- return 0
- if args["MORE"] == None:
- args["MORE"] = " "
- self.handle.sendline(cmd)
- self.lastCommand = cmd
- index = self.handle.expect([expectPrompt, "--More--", 'Command not found.', pexpect.TIMEOUT,"^:$"], timeout = timeoutVar)
- if index == 0:
- self.LASTRSP = self.LASTRSP + self.handle.before + self.handle.after
- main.log.info("Executed :"+str(cmd)+" \t\t Expected Prompt '"+ str(expectPrompt)+"' Found")
- elif index == 1:
- self.LASTRSP = self.LASTRSP + self.handle.before
- self.handle.send(args["MORE"])
- main.log.info("Found More screen to go , Sending a key to proceed")
- indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
- while indexMore == 0:
- main.log.info("Found anoother More screen to go , Sending a key to proceed")
- self.handle.send(args["MORE"])
- indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
- self.LASTRSP = self.LASTRSP + self.handle.before
- elif index ==2:
- main.log.error("Command not found")
- self.LASTRSP = self.LASTRSP + self.handle.before
- elif index ==3:
- main.log.error("Expected Prompt not found , Time Out!!")
- main.log.error( expectPrompt )
- return "Expected Prompt not found , Time Out!!"
-
- elif index == 4:
- self.LASTRSP = self.LASTRSP + self.handle.before
- #self.handle.send(args["MORE"])
- self.handle.sendcontrol("D")
- main.log.info("Found More screen to go , Sending a key to proceed")
- indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
- while indexMore == 0:
- main.log.info("Found anoother More screen to go , Sending a key to proceed")
- self.handle.sendcontrol("D")
- indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
- self.LASTRSP = self.LASTRSP + self.handle.before
-
- main.last_response = self.remove_contol_chars(self.LASTRSP)
- return self.LASTRSP
-
- def remove_contol_chars(self,response):
- #RE_XML_ILLEGAL = '([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])|([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])'%(unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff))
- #response = re.sub(RE_XML_ILLEGAL, "\n", response)
- response = re.sub(r"[\x01-\x1F\x7F]", "", response)
- #response = re.sub(r"\[\d+\;1H", "\n", response)
- response = re.sub(r"\[\d+\;\d+H", "", response)
- return response
-
- def runAsSudoUser(self,handle,pwd,default):
-
- i = handle.expect([".ssword:*",default, pexpect.EOF])
- if i==0:
- handle.sendline(pwd)
- handle.sendline("\n")
-
- if i==1:
- handle.expect(default)
-
- if i==2:
- main.log.error("Unable to run as Sudo user")
-
- return handle
-
- def onfail(self):
- if main.componentDictionary[self.name].has_key('onfail'):
- commandList = main.componentDictionary[self.name]['onfail'].split(",")
- for command in commandList :
- response = self.execute(cmd=command,prompt="(.*)",timeout=120)
-
- def secureCopy(self,user_name, ip_address,filepath, pwd,dst_path):
-
- #scp openflow@192.168.56.101:/home/openflow/sample /home/paxterra/Desktop/
-
- '''
- Connection will establish to the remote host using ssh.
- It will take user_name ,ip_address and password as arguments<br>
- and will return the handle.
- '''
- ssh_newkey = 'Are you sure you want to continue connecting'
- refused = "ssh: connect to host "+ip_address+" port 22: Connection refused"
- self.handle =pexpect.spawn('scp '+user_name+'@'+ip_address+':'+filepath+' '+dst_path)
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused],120)
-
- if i==0:
- main.log.info("ssh key confirmation received, send yes")
- self.handle.sendline('yes')
- i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
- if i==1:
- main.log.info("ssh connection asked for password, gave password")
- self.handle.sendline(pwd)
- #self.handle.expect(user_name)
-
- elif i==2:
- main.log.error("Connection timeout")
- pass
- elif i==3: #timeout
- main.log.error("No route to the Host "+user_name+"@"+ip_address)
- return main.FALSE
- elif i==4:
- main.log.error("ssh: connect to host "+ip_address+" port 22: Connection refused")
- return main.FALSE
-
- self.handle.sendline("\n")
-
- return self.handle
-