incubator-tashi-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rg...@apache.org
Subject svn commit: r1028821 - in /incubator/tashi/trunk: etc/ZoniDefaults.cfg src/zoni/client/zoni-cli.py src/zoni/extra/util.py src/zoni/hardware/dellswitch.py src/zoni/hardware/hpswitch.py
Date Fri, 29 Oct 2010 16:20:49 GMT
Author: rgass
Date: Fri Oct 29 16:20:48 2010
New Revision: 1028821

URL: http://svn.apache.org/viewvc?rev=1028821&view=rev
Log:
Switching to the logging facility for Python

Removing all the splits in the util file for the config parser since it doesn't seem to do
anything
Modified the hpswitch and dellswitch to use the logging facility
Added the options in the default zoni config file
Reformatted the hpswitch file

Modified:
    incubator/tashi/trunk/etc/ZoniDefaults.cfg
    incubator/tashi/trunk/src/zoni/client/zoni-cli.py
    incubator/tashi/trunk/src/zoni/extra/util.py
    incubator/tashi/trunk/src/zoni/hardware/dellswitch.py
    incubator/tashi/trunk/src/zoni/hardware/hpswitch.py

Modified: incubator/tashi/trunk/etc/ZoniDefaults.cfg
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/etc/ZoniDefaults.cfg?rev=1028821&r1=1028820&r2=1028821&view=diff
==============================================================================
--- incubator/tashi/trunk/etc/ZoniDefaults.cfg (original)
+++ incubator/tashi/trunk/etc/ZoniDefaults.cfg Fri Oct 29 16:20:48 2010
@@ -91,3 +91,32 @@ domainDescription = "/usr/local/tashi/et
 ZONI_HOME_DOMAIN = 1  #  Default domain for most switches
 ZONI_HOME_NETWORK = 10.10.0.0/20
 ZONI_IPMI_NETWORK = 10.10.16.0/20
+
+#  Logging
+[loggers]
+keys=root
+
+[handlers]
+keys=consoleHandler, fileHandler
+
+[formatters]
+keys=standardFormatter
+
+[logger_root]
+level=DEBUG
+handlers=consoleHandler, fileHandler
+
+[handler_consoleHandler]
+class=StreamHandler
+level=DEBUG
+formatter=standardFormatter
+args=(sys.stdout,)
+
+[handler_fileHandler]
+class = FileHandler
+level = NOTSET
+formatter = standardFormatter
+args = ("/var/tmp/zoni_logfile.txt",)
+
+[formatter_standardFormatter]
+format=%(asctime)s [%(name)s:%(levelname)s] %(message)s

Modified: incubator/tashi/trunk/src/zoni/client/zoni-cli.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/client/zoni-cli.py?rev=1028821&r1=1028820&r2=1028821&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/client/zoni-cli.py (original)
+++ incubator/tashi/trunk/src/zoni/client/zoni-cli.py Fri Oct 29 16:20:48 2010
@@ -24,6 +24,7 @@ import os
 import sys
 import optparse
 import socket
+import logging.config
 import getpass
 
 
@@ -62,9 +63,12 @@ def main():
 	ver = version.split(" ")[0]
 	rev = revision
 
-	configFile = getConfig()
-	#logit(configFile['logFile'], "Starting Zoni client")
-	#logit(configFile['logFile'], "Loading config file")
+	(configs, configFiles) = getConfig()
+
+	logging.config.fileConfig(configFiles)
+	log = logging.getLogger(os.path.basename(__file__))
+	#logit(configs['logFile'], "Starting Zoni client")
+	#logit(configs['logFile'], "Loading config file")
 
 	parser = optparse.OptionParser(usage="%prog [-n] [-u] [--uid] [-v]", version="%prog " +
ver + " " + rev)
 	parser.add_option("-n", "--nodeName", dest="nodeName", help="Specify node")
@@ -169,7 +173,7 @@ def main():
 	cmdargs = {}
 
 	#  setup db connection
-	query = zoni.data.resourcequerysql.ResourceQuerySql(configFile, options.verbosity)
+	query = zoni.data.resourcequerysql.ResourceQuerySql(configs, options.verbosity)
 
 	#  Get host info
 	host=None
@@ -181,10 +185,10 @@ def main():
 	#  Hardware control
 	if options.hardwareType:
 
-		if (options.hardwareType) and options.hardwareType not in configFile['hardware_control']:
+		if (options.hardwareType) and options.hardwareType not in configs['hardware_control']:
 			mesg = "Non support hardware type specified\n"
 			mesg += "Supported types:\n"
-			mesg += str(configFile['hardware_control'])
+			mesg += str(configs['hardware_control'])
 			mesg += "\n\n"
 			sys.stdout.write(mesg)
 			exit()
@@ -330,7 +334,7 @@ def main():
 	if (options.rgasstest):
 		#pdu = raritanDominionPx(host)
 		#print pdu
-		#bootit = pxe.Pxe(configFile, options.verbosity)
+		#bootit = pxe.Pxe(configs, options.verbosity)
 		#bootit.createPxeUpdateFile(query.getPxeImages())
 		#bootit.updatePxe()
 		#print "host is ", host
@@ -436,7 +440,7 @@ def main():
 			exit()
 
 		#  Update PXE 
-		bootit = pxe.Pxe(configFile, options.verbosity)
+		bootit = pxe.Pxe(configs, options.verbosity)
 		bootit.createPxeUpdateFile(query.getPxeImages())
 		bootit.updatePxe()
 		
@@ -470,7 +474,7 @@ def main():
 			host = query.getSwitchInfo(options.interactiveSwitchConfig)
 
 		HwSwitch = HwDellSwitch
-		hwswitch = HwSwitch(configFile, host)
+		hwswitch = HwSwitch(configs, host)
 		if options.verbosity:
 			hwswitch.setVerbose(True)
 
@@ -515,7 +519,7 @@ def main():
 		else:
 			if string.lower(args[0]) == "dell":
 				HwSwitch = HwDellSwitch
-				hw = HwSwitch(configFile)
+				hw = HwSwitch(configs)
 			elif string.lower(args[0]) == "raritan":
 				hw = raritanDominionPx()
 			else:
@@ -551,7 +555,7 @@ def main():
 		if options.addDns:
 			if len(args) < 2:
 				mesg = "ERROR:  Incorrect number of arguments\n"
-				mesg += "Example:  " + sys.argv[0] + " " + thisone + " hostname IP_Address\n"
+				mesg += "Example:  " + os.path.basename(sys.argv[0]) + " " + thisone + " hostname IP_Address\n"
 				print mesg
 				exit()
 			
@@ -560,7 +564,7 @@ def main():
 			if validIp(ip):
 				mesg = "Adding DNS entry: %s (%s) " % (hostName, ip)
 				sys.stdout.write(mesg)
-				dhcpdns = DhcpDns(configFile, verbose=options.verbosity)
+				dhcpdns = DhcpDns(configs, verbose=options.verbosity)
 				dhcpdns.addDns(hostName, ip)
 				try:
 					socket.gethostbyname(hostName)
@@ -576,11 +580,11 @@ def main():
 		if options.removeDns or options.removeDhcp or options.removeCname:
 			if len(args) < 1:
 				mesg = "ERROR:  Incorrect number of arguments\n"
-				mesg += "Example:  " + sys.argv[0] + " " + thisone + " hostname\n"
+				mesg += "Example:  " + os.path.basename(sys.argv[0]) + " " + thisone + " hostname\n"
 				sys.stdout.write(mesg)
 				exit()
 			hostName = args[0]
-			dhcpdns = DhcpDns(configFile, verbose=options.verbosity)
+			dhcpdns = DhcpDns(configs, verbose=options.verbosity)
 			if options.removeDns:	
 				mesg = "Removing DNS entry: %s " % (hostName)
 				sys.stdout.write(mesg)
@@ -607,7 +611,7 @@ def main():
 		if options.addDhcp:
 			if len(args) < 3:
 				mesg = "ERROR:  Incorrect number of arguments\n"
-				mesg += "Example:  " + sys.argv[0] + " " + thisone + " hostname IP_Address Mac_Address\n"
+				mesg += "Example:  " + os.path.basename(sys.argv[0]) + " " + thisone + " hostname IP_Address
Mac_Address\n"
 				print mesg
 				exit()
 			
@@ -615,7 +619,7 @@ def main():
 			ip = args[1]
 			mac = args[2]
 			if validIp(ip) and validMac(mac):
-				dhcpdns = DhcpDns(configFile, verbose=options.verbosity)
+				dhcpdns = DhcpDns(configs, verbose=options.verbosity)
 				dhcpdns.addDhcp(hostName, ip, mac)
 				if dhcpdns.error:
 					mesg = "ERROR:  Add DHCP Error " + dhcpdns.error + "\n"
@@ -634,14 +638,14 @@ def main():
 		if options.addCname:
 			if len(args) < 2:
 				mesg = "ERROR:  Incorrect number of arguments\n"
-				mesg += "Example:  " + sys.argv[0] + " " + thisone + "cname existing_name"
+				mesg += "Example:  " + os.path.basename(sys.argv[0]) + " " + thisone + "cname existing_name"
 				print mesg
 				exit()
 			hostName = args[1]
 			cname = args[0]
 			mesg = "Adding DNS CNAME entry: %s -> %s  " % (cname, hostName)
 			sys.stdout.write(mesg)
-			dhcpdns = DhcpDns(configFile, verbose=options.verbosity)
+			dhcpdns = DhcpDns(configs, verbose=options.verbosity)
 			dhcpdns.addCname(cname, hostName)
 			if dhcpdns.error: 
 				mesg = "[FAIL]  \n" + str(dhcpdns.error) + "\n" 

Modified: incubator/tashi/trunk/src/zoni/extra/util.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/extra/util.py?rev=1028821&r1=1028820&r2=1028821&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/extra/util.py (original)
+++ incubator/tashi/trunk/src/zoni/extra/util.py Fri Oct 29 16:20:48 2010
@@ -29,49 +29,50 @@ def loadConfigFile(parser):
 	#parser.read(filename)
 	config = {}
 	#  Install dir
-	config['installBaseDir'] = parser.get("home", "INSTALL_BASE_DIR").split()[0]
+	config['installBaseDir'] = parser.get("home", "INSTALL_BASE_DIR")
 
 	#  Logging
-	config['logFile'] = parser.get("logging", "LOG_FILE").split()[0]
+	#config['logFile'] = parser.get("logging", "LOG_FILE")
+	config['logFile'] = parser.get("logging", "LOG_FILE")
 	
 	#  DB connection
-	config['dbUser'] = parser.get("dbConnection", "DB_USER").split()[0]
+	config['dbUser'] = parser.get("dbConnection", "DB_USER")
 	config['dbPassword'] = config.get("dbPassword", "")
 	if not parser.get("dbConnection", "DB_PASSWORD") == "":
 		config['dbPassword'] = parser.get("dbConnection", "DB_PASSWORD").strip("\",'")
-	config['dbHost'] = parser.get("dbConnection", "DB_HOST").split()[0]
-	config['dbPort'] = int(parser.get("dbConnection", "DB_PORT").split()[0])
-	config['dbInst'] = parser.get("dbConnection", "DB_INST").split()[0]
+	config['dbHost'] = parser.get("dbConnection", "DB_HOST")
+	config['dbPort'] = int(parser.get("dbConnection", "DB_PORT"))
+	config['dbInst'] = parser.get("dbConnection", "DB_INST")
 
 	#  PXE info
-	config['tftpRootDir'] = parser.get("pxe", "TFTP_ROOT_DIR").split()[0]
-	config['tftpImageDir'] = parser.get("pxe", "TFTP_IMAGE_DIR").split()[0]
-	config['tftpBootOptionsDir'] = parser.get("pxe", "TFTP_BOOT_OPTIONS_DIR").split()[0]
-	config['tftpUpdateFile'] = parser.get("pxe", "TFTP_UPDATE_FILE").split()[0]
-	config['tftpBaseFile'] = parser.get("pxe", "TFTP_BASE_FILE").split()[0]
-	config['tftpBaseMenuFile'] = parser.get("pxe", "TFTP_BASE_MENU_FILE").split()[0]
-	config['pxeServerIP'] = parser.get("pxe", "PXE_SERVER_IP").split()[0]
-	config['initrdRoot'] = parser.get("pxe", "INITRD_ROOT").split()[0]
+	config['tftpRootDir'] = parser.get("pxe", "TFTP_ROOT_DIR")
+	config['tftpImageDir'] = parser.get("pxe", "TFTP_IMAGE_DIR")
+	config['tftpBootOptionsDir'] = parser.get("pxe", "TFTP_BOOT_OPTIONS_DIR")
+	config['tftpUpdateFile'] = parser.get("pxe", "TFTP_UPDATE_FILE")
+	config['tftpBaseFile'] = parser.get("pxe", "TFTP_BASE_FILE")
+	config['tftpBaseMenuFile'] = parser.get("pxe", "TFTP_BASE_MENU_FILE")
+	config['pxeServerIP'] = parser.get("pxe", "PXE_SERVER_IP")
+	config['initrdRoot'] = parser.get("pxe", "INITRD_ROOT")
 
 	#  Image store
-	config['imageServerIP'] = parser.get("imageStore", "IMAGE_SERVER_IP").split()[0]
-	config['fsImagesBaseDir'] = parser.get("imageStore", "FS_IMAGES_BASE_DIR").split()[0]
+	config['imageServerIP'] = parser.get("imageStore", "IMAGE_SERVER_IP")
+	config['fsImagesBaseDir'] = parser.get("imageStore", "FS_IMAGES_BASE_DIR")
 
 	#  WWW
-	config['wwwDocumentRoot'] = parser.get("www", "WWW_DOCUMENT_ROOT").split()[0]
-	config['registrationBaseDir'] = parser.get("www", "REGISTRATION_BASE_DIR").split()[0]
+	config['wwwDocumentRoot'] = parser.get("www", "WWW_DOCUMENT_ROOT")
+	config['registrationBaseDir'] = parser.get("www", "REGISTRATION_BASE_DIR")
 	
 	#  SNMP
-	config['snmpCommunity'] = parser.get("snmp", "SNMP_COMMUNITY").split()[0]
+	config['snmpCommunity'] = parser.get("snmp", "SNMP_COMMUNITY")
 
 	#  VLAN
 	#config['vlan_reserved'] = parser.get("vlan", "VLAN_RESERVED")
 	config['vlan_max'] = parser.get("vlan", "VLAN_MAX")
 
 	#  Domain
-	config['zoniHomeDomain'] = parser.get("domain", "ZONI_HOME_DOMAIN").split()[0]
-	config['zoniHomeNetwork'] = parser.get("domain", "ZONI_HOME_NETWORK").split()[0]
-	config['zoniIpmiNetwork'] = parser.get("domain", "ZONI_IPMI_NETWORK").split()[0]
+	config['zoniHomeDomain'] = parser.get("domain", "ZONI_HOME_DOMAIN")
+	config['zoniHomeNetwork'] = parser.get("domain", "ZONI_HOME_NETWORK")
+	config['zoniIpmiNetwork'] = parser.get("domain", "ZONI_IPMI_NETWORK")
 	#config['vlan_max'] = parser.get("vlan", "VLAN_MAX")
 
 	#  HARDWARE CONTROL
@@ -88,7 +89,7 @@ def loadConfigFile(parser):
 	config['dhcpKeyName'] = parser.get("DhcpDns", "dhcpKeyName")
 	config['dhcpSecretKey'] = parser.get("DhcpDns", "dhcpSecretKey")
 
-	#self.ap_model['radius'] = int(parser.get("wireless_range", "radius").split()[0])
+	#self.ap_model['radius'] = int(parser.get("wireless_range", "radius"))
 	return config
 
 def getConfig(additionalNames=[], additionalFiles=[]):
@@ -103,7 +104,9 @@ def getConfig(additionalNames=[], additi
 	if (len(configFiles) == 0):
 		raise Exception("No config file could be found: %s" % (str(allLocations)))
 
-	return loadConfigFile(config)
+	return (loadConfigFile(config), configFiles) 
+
+
 
 def logit(logfile, mesg):
 	fd = open(logfile, "a+");

Modified: incubator/tashi/trunk/src/zoni/hardware/dellswitch.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/dellswitch.py?rev=1028821&r1=1028820&r2=1028821&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/dellswitch.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/dellswitch.py Fri Oct 29 16:20:48 2010
@@ -28,11 +28,11 @@ import string
 import getpass
 import socket
 import tempfile
+import logging
 
 
 from zoni.hardware.hwswitchinterface import HwSwitchInterface
 from zoni.data.resourcequerysql import ResourceQuerySql
-from zoni.extra.util import logit
 
 
 '''  Using pexpect to control switches because couldn't get snmp to work 
@@ -40,9 +40,10 @@ from zoni.extra.util import logit
 
 class HwDellSwitch(HwSwitchInterface):
 	def __init__(self, config, host=None):
+		self.config = config
 		self.host = host
 		self.verbose = False
-		self.logFile = config['logFile']
+		self.log = logging.getLogger(os.path.basename(__file__))
 
 
  	def setVerbose(self, verbose):
@@ -72,9 +73,8 @@ class HwDellSwitch(HwSwitchInterface):
 			child.sendline(self.host['hw_password'])
 			i=child.expect(['console','#', 'Name:', pexpect.EOF, pexpect.TIMEOUT])
 			if i == 2:
-				mesg = "ERROR:  Login failed\n"
-				logit(self.logFile, mesg)
-				sys.stderr.write(mesg)
+				mesg = "ERROR:  Login to %s failed\n" % (self.host['hw_name'])
+				self.log.error(mesg)
 				exit(1)
 
 		if opt == 1:
@@ -125,8 +125,8 @@ class HwDellSwitch(HwSwitchInterface):
 		child.terminate()
 	
 	def addVlanToTrunk(self, vlan):
-		mesg = "Adding Vlan to trunks on switch"
-		logit(self.logFile, mesg)
+		mesg = "Adding Vlan %s to trunks on switch" % (vlan)
+		self.log.info(mesg)
 		child = self.__login()
 		child.sendline('config')
 		cmd = "interface range port-channel all"
@@ -137,9 +137,9 @@ class HwDellSwitch(HwSwitchInterface):
 		child.sendline('exit')
 
 	def createVlansThread(self, vlan, switch,host):
-		mesg = "Creating vlan " + str(vlan) + " on switch " + str(switch)
+		mesg = "Creating vlan %s on switch %s" % (str(vlan),str(switch))
 		print "host is ", host
-		logit(self.logFile, mesg)
+		self.log(mesg)
 		print "create"
 		self.createVlan(vlan)
 		print "cend"
@@ -151,16 +151,16 @@ class HwDellSwitch(HwSwitchInterface):
 			#print "working on switch ", switch
 			#self.host = query.getSwitchInfo(switch)
 			#thread.start_new_thread(self.createVlansThread, (vlan, switch, self.host))
-			mesg = "Creating vlan " + str(vlan) + " on switch " + str(switch)
-			logit(self.logFile, mesg)
+			mesg = "Creating vlan %s on switch %s" % (str(vlan), str(switch))
+			self.log.info(mesg)
 			self.host = query.getSwitchInfo(switch)
 			self.createVlan(vlan)
 			self.addVlanToTrunk(vlan);
 		
 	def removeVlans(self, vlan, switchlist, query):
 		for switch in switchlist:
-			mesg = "Deleting vlan " + str(vlan) + " on switch " + str(switch)
-			logit(self.logFile, mesg)
+			mesg = "Deleting vlan %s on switch %s" % (str(vlan),str(switch))
+			self.log.info(mesg)
 			self.host = query.getSwitchInfo(switch)
 			self.removeVlan(vlan)
 		
@@ -179,8 +179,8 @@ class HwDellSwitch(HwSwitchInterface):
 			#sys.stderr.write(mesg)
 			#exit(1)
 		if num > 4095 or num < 0:
-			mesg = "ERROR:  Vlan out of range.  Must be < 4095"
-			logit(self.logFile, mesg)
+			mesg = "Vlan out of range.  Must be < %s" % (self.config['vlan_max'])
+			self.log.error(mesg)
 			exit(1)
 		
 		child = self.__login()
@@ -227,7 +227,9 @@ class HwDellSwitch(HwSwitchInterface):
 		#print "after", child.after
 
 	def addNodeToVlan(self, vlan):
-		print "Adding Node to vlan ", vlan
+		mesg = "Adding Node to vlan %s" % (str(vlan))
+		self.log.info(mesg)
+		
 		child = self.__login()
 		child.sendline('config')
 		cmd = "interface ethernet g" + str(self.host['hw_port'])
@@ -242,7 +244,7 @@ class HwDellSwitch(HwSwitchInterface):
 		#  Vlan must exist in order to add a host to it.  
 		#  If it doesn't exist, try to create it
 		if i == 1:
-			sys.stderr.write("WARNING:  Vlan doesn't exist, trying to create\n")
+			self.log.warning("WARNING:  Vlan %sdoesn't exist, trying to create" % (vlan))
 			#  Add a tag showing this was created by PRS
 			newvlan = vlan + ":" + self.__getPrsLabel()
 			self.createVlan(newvlan)
@@ -251,9 +253,10 @@ class HwDellSwitch(HwSwitchInterface):
 		child.sendline('exit')
 		child.sendline('exit')
 		child.terminate()
-		sys.stdout.write("Success\n")
 
 	def removeNodeFromVlan(self, vlan):
+		mesg = "Removing Node from vlan %s" % (str(vlan))
+		self.log.info(mesg)
 		child = self.__login()
 		child.sendline('config')
 		cmd = "interface ethernet g" + str(self.host['hw_port'])
@@ -286,7 +289,7 @@ class HwDellSwitch(HwSwitchInterface):
 		child.sendline(cmd)
 		i=child.expect(['config-if', pexpect.EOF, pexpect.TIMEOUT])
 		if i > 0:
-			sys.stderr.write("ERROR: setNativeVlan ", cmd, " failed\n")
+			self.log.error("setNativeVlan %s failed" % (cmd))
 
 		NOVLAN = "VLAN was not created by user."
 		cmd = "switchport trunk native vlan " + vlan
@@ -295,7 +298,7 @@ class HwDellSwitch(HwSwitchInterface):
 		#  Vlan must exist in order to add a host to it.  
 		#  If it doesn't exist, try to create it
 		if i == 1:
-			sys.stderr.write("WARNING:  Vlan doesn't exist, trying to create")
+			self.log.warning("Vlan %s doesn't exist, trying to create" % (vlan))
 			#  Add a tag showing this was created by PRS
 			newvlan = vlan + ":" + self.__getPrsLabel()
 			self.createVlan(newvlan)
@@ -331,7 +334,7 @@ class HwDellSwitch(HwSwitchInterface):
 		child.sendline(cmd)
 		i=child.expect(['config-if', pexpect.EOF, pexpect.TIMEOUT])
 		if i > 0:
-			sys.stderr.write("ERROR: setNativeVlan ", cmd, " failed\n")
+			self.log.error("setNativeVlan %s failed" % (cmd))
 
 		NOVLAN = "VLAN was not created by user."
 		cmd = "switchport trunk allowed vlan remove all"
@@ -377,17 +380,17 @@ class HwDellSwitch(HwSwitchInterface):
 			try:
 				host = string.strip(socket.gethostbyaddr(ip)[0].split(".")[0])
 			except Exception, e:
-				mesg = "WARNING:  Host (" + host + ") not registered in DNS " + str(e)
-				logit(self.logFile,mesg)
+				mesg = "Host (%s) not registered in DNS, %s" % (host,str(e))
+				self.log.warning(mesg)
 		else:
 			#  Maybe a hostname was entered...
 			try:
 				ip = socket.gethostbyname(host)
 			except Exception, e:
-				mesg = "ERROR:  Host (" + host + ") not registered in DNS " + str(e)
-				logit(self.logFile,mesg)
+				mesg = "Host (%s) not registered in DNS, %s" % (host, str(e))
+				self.log.error(mesg)
 				mesg = "Unable to resolve hostname"
-				logit(self.logFile,mesg)
+				self.log.critical(mesg)
 				exit()
 
 		switchIp = "ssh " + user + "@" + ip
@@ -407,10 +410,8 @@ class HwDellSwitch(HwSwitchInterface):
 			child.sendline(password)
 			i=child.expect(['console',host, 'Name:', pexpect.EOF, pexpect.TIMEOUT])
 			if i == 2:
-				mesg = "ERROR:  Login failed\n"
-				logit(self.logFile, mesg)
-
-				sys.stderr.write(mesg)
+				mesg = "Login to switch %s failed" % (host)
+				self.log.error(mesg)
 				exit(1)
 
 		if opt == 1:

Modified: incubator/tashi/trunk/src/zoni/hardware/hpswitch.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/hpswitch.py?rev=1028821&r1=1028820&r2=1028821&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/hpswitch.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/hpswitch.py Fri Oct 29 16:20:48 2010
@@ -6,7 +6,7 @@
 # "License"); you may not use this file except in compliance
 # with the License.  You may obtain a copy of the License at
 #
-#   http://www.apache.org/licenses/LICENSE-2.0
+#http://www.apache.org/licenses/LICENSE-2.0
 #
 # Unless required by applicable law or agreed to in writing,
 # software distributed under the License is distributed on an
@@ -27,251 +27,236 @@ import datetime
 import thread
 import time
 import threading
+import logging
 
 
 from hwswitchinterface import HwSwitchInterface
 from resourcequerysql import ResourceQuerySql
-from util import logit
 
 
-'''  Using pexpect to control switches because couldn't get snmp to work
-'''
-
 class HwHPSwitch(HwSwitchInterface):
-       def __init__(self, config, host=None):
-               self.host = host
-               self.verbose = False
-               self.logFile = config['logFile']
-
-
-       def setVerbose(self, verbose):
-               self.verbose = verbose
-
-       def __login(self):
-
-               switchIp = "telnet " +  self.host['hw_name']
-               child = pexpect.spawn(switchIp)
-               opt = child.expect(['Name:', 'password:', pexpect.EOF, pexpect.TIMEOUT])
-               #XXX  Doesn't seem to do what I want:(
-               child.setecho(False)
-               if opt == 0:
-                       child.sendline(self.host['hw_userid'])
-
-               #  Be Verbose and print everything
-               if self.verbose:
-                       child.logfile = sys.stdout
-
-               child.sendline(self.host['hw_password'])
-               i=child.expect(['Main#', pexpect.EOF, pexpect.TIMEOUT])
-               if i == 2:
-                       mesg = "ERROR:  Login failed\n"
-                       logit(self.logFile, mesg)
-
-                       sys.stderr.write()
-                       exit(1)
-               return child
-
-       def __getPrsLabel(self):
-               dadate = datetime.datetime.now().strftime("%Y%m%d-%H%M-%S")
-               return "ZONI_" + dadate
-
-       def __saveConfig(self, child):
-               #child.logfile = sys.stdout
-               cmd = "save"
-               child.sendline(cmd)
-               opt = child.expect(["Confirm(.*)", "No save(.*)", pexpect.EOF, pexpect.TIMEOUT])
-               if opt == 0:
-                       print "saving to flash"
-                       child.sendline("y\n")
-               if opt == 1:
-                       print "no save needed"
-               child.sendline('exit')
-               child.terminate()
-
-       def enableHostPort(self):
-               child = self.__login()
-               cmd = "/cfg/port " + str(self.host['hw_port']) + " /ena/apply "
-               child.sendline(cmd)
-               #  testing this thread... Looks like this works ...
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-       def disableHostPort(self):
-               child = self.__login()
-               cmd = "/cfg/port " + str(self.host['hw_port']) + " /dis/apply "
-               child.sendline(cmd)
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-       def removeVlan(self, num):
-               print "removing vlan"
-               #  Check for important vlans
-               child = self.__login()
-
-               cmd = "/cfg / l2 / vlan " + num + " / del / apply"
-               child.sendline(cmd)
-               opt = child.expect(["Confirm(.*)", pexpect.EOF, pexpect.TIMEOUT])
-               if opt == 0:
-                       child.sendline("y\n")
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-
-       def addVlanToTrunk(self, vlan):
-               print "NOT IMPLEMENTED"
-               print "No trunks to test @ MIMOS"
-
-       def createVlansThread(self, vlan, switch,host):
-               mesg = "Creating vlan " + str(vlan) + " on switch " + str(switch)
-               print "host is ", host
-               logit(self.logFile, mesg)
-               print "create"
-               self.createVlan(vlan)
-               print "cend"
-               self.addVlanToTrunk(vlan);
-               thread.exit()
-
-       def createVlans(self, vlan, switchlist, query):
-               for switch in switchlist:
-                       #print "working on switch ", switch
-                       #self.host = query.getSwitchInfo(switch)
- #thread.start_new_thread(self.createVlansThread, (vlan, switch, self.host))
-                       mesg = "Creating vlan " + str(vlan) + " on switch " + str(switch)
-                       logit(self.logFile, mesg)
-                       self.host = query.getSwitchInfo(switch)
-                       self.createVlan(vlan)
-                       self.addVlanToTrunk(vlan);
-
-       def removeVlans(self, vlan, switchlist, query):
-               for switch in switchlist:
-                       mesg = "Deleting vlan " + str(vlan) + " on switch " + str(switch)
-                       logit(self.logFile, mesg)
-                       self.host = query.getSwitchInfo(switch)
-                       self.removeVlan(vlan)
-
-       def createVlan(self, val):
-
-               vlanname = False
-               if ":" in val:
-                       num = int(val.split(":")[0])
-                       vlanname = val.split(":")[1]
-               else:
-                       vlanname = self.__getPrsLabel()
-                       num = int(val)
-
-               #if type(num) != int:
-                       #mesg = "ERROR:  Vlan must be a number (0-4095)\n"
-                       #sys.stderr.write(mesg)
-                       #exit(1)
-               if num > 4095 or num < 0:
-                       mesg = "ERROR:  Vlan out of range.  Must be < 4095"
-                       logit(self.logFile, mesg)
-                       exit(1)
-
-               child = self.__login()
-               cmd = "/cfg / l2 / vlan " + str(num) + " / ena/ apply"
-               child.sendline(cmd)
-               cmd = "name " + str(vlanname) +  " / apply"
-               child.sendline(cmd)
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-
-       #  Raw Switch commands.  DEBUG ONLY!, Doesn't work!
-       def sendSwitchCommand(self, cmds):
-               if len(cmds) > 0:
-                       child = self.__login()
-                       child.logfile = sys.stdout
-               for cmd in cmds.split(";"):
-                       child.sendline(cmd)
-                       try:
-                               i=child.expect(['console','sw', 'Name:', pexpect.EOF, pexpect.TIMEOUT],
timeout=2)
-                               i=child.expect(['console','sw', 'Name:', pexpect.EOF, pexpect.TIMEOUT],
timeout=2)
-
-                       except EOF:
-                               print "EOF", i
-                               #child.sendline()
-                       except TIMEOUT:
-                               print "TIMEOUT", i
-               #child.interact(escape_character='\x1d', input_filter=None, output_filter=None)
-
-               child.terminate()
-               #print "before", child.before
-               #print "after", child.after
-
-       def addNodeToVlan(self, vlan):
-               child = self.__login()
-               cmd = "/cfg/l2/vlan " + str(vlan) + " /add " + str(self.host['hw_port']) +
" /apply "
-               child.sendline(cmd)
-               opt = child.expect(['(.*)#','(.*)needs to be enabled', pexpect.EOF, pexpect.TIMEOUT],
timeout=2)
-               if opt == 1:
-                       print "VLAN Created, Enabling..." + str(vlan)
-                       cmd = "/cfg/l2/vlan " + str(vlan) + " /ena/apply "
-                       child.sendline(cmd)
-
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-
-       def removeNodeFromVlan(self, vlan):
-               child = self.__login()
-               cmd = "/cfg/l2/vlan " + str(vlan) + " /rem " + str(self.host['hw_port']) +
"/apply"
-               child.sendline(cmd)
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-       def setNativeVlan(self, vlan):
-               child = self.__login()
-               #child.logfile = sys.stdout
-               cmd = "/cfg/port " + str(self.host['hw_port']) + "/pvid " + str(vlan) + "/apply"
-               child.sendline(cmd)
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-               #  HP switches allow more free control.  Example, if you set a port to a native
vlan
-               #  that doesn't exist, HP switches will happily create for you.
-               #  However, if you delete a vlan that exists on many ports, it will still
happily delete
-               #  the vlan, forcing all the other ports to default to some other native vlan.
 Need
-               #  to make sure we check before blasting vlans.
-
-       #  Restore Native Vlan.
-       def restoreNativeVlan(self):
-               child = self.__login()
-               cmd = "/cfg/port " + str(self.host['hw_port']) + "/pvid 1/apply"
-               child.sendline(cmd)
-               threading.Thread(target=self.__saveConfig(child)).start()
-
-       #  Setup the switch for node allocation
-       def allocateNode(self):
-               pass
-
-       #  Remove all vlans from the interface
-       def removeAllVlans(self):
-               child = self.__login()
-               cmd = "/cfg/port " + str(self.host['hw_port']) + "/tag d/apply"
-               #child.logfile = sys.stdout
-               child.sendline(cmd)
-
-       def showInterfaceConfig(self):
-               print "\n---------------" + self.host['hw_make'] + "---------------------"
-               print "SWITCH - " + self.host['hw_name'] + "/" + str(self.host['hw_port'])
-               print "NODE   - " + self.host['location']
-               print "------------------------------------\n"
-               #  using run and parsing output.  Still have issues an "rt" after the command.
 Fix later
-               #val = pexpect.run("telnet sw0-r4r1e1", withexitstatus=False, timeout=2, events=({'(?i)password:':
"admin\r\n", "Main#": "info\r\n", "Info(.*)" : "port\r\n"})) #, "Info(.*)" : "exit\n"}))
-               #  Just print everything for now, fix when back in the US
-               #print val
-
-
-               child = self.__login()
-               cmd = "/info/port " + str(self.host['hw_port'])
-               child.sendline(cmd)
-               child.logfile = sys.stdout
-               opt = child.expect(['Info(.*)', pexpect.EOF, pexpect.TIMEOUT])
-
-       #  this needs to be removed or rewritten
-       def interactiveSwitchConfig(self):
-               switchIp = "telnet " + self.host['hw_name']
-               child = pexpect.spawn(switchIp)
-               child.setecho(False)
-               #child.expect('Name:')
-               #child.sendline(self.host['hw_userid'])
-               #i=child.expect(['test','password:','Password:', pexpect.EOF, pexpect.TIMEOUT])
-               #child.logfile = sys.stdout
-               child.sendline(self.host['hw_password'])
-               child.interact(escape_character='\x1d', input_filter=None, output_filter=None)
+	def __init__(self, config, host=None):
+		self.config = config
+		self.host = host
+		self.verbose = False
+		self.log = logging.getLogger(os.path.basename(__file__))
+
+	def setVerbose(self, verbose):
+		self.verbose = verbose
+
+	def __login(self):
+		switchIp = "telnet " +  self.host['hw_name']
+		child = pexpect.spawn(switchIp)
+		opt = child.expect(['Name:', 'password:', pexpect.EOF, pexpect.TIMEOUT])
+		child.setecho(False)
+		if opt == 0:
+			child.sendline(self.host['hw_userid'])
+
+		#  Be Verbose and print everything
+		if self.verbose:
+			child.logfile = sys.stdout
+
+		child.sendline(self.host['hw_password'])
+		i=child.expect(['Main#', pexpect.EOF, pexpect.TIMEOUT])
+		if i == 2:
+			mesg = "Login to %s failed\n" % (self.host['hw_name'])
+			self.log.error(mesg)
+			exit(1)
+		return child
+
+	def __getPrsLabel(self):
+		dadate = datetime.datetime.now().strftime("%Y%m%d-%H%M-%S")
+		return "ZONI_" + dadate
+
+	def __saveConfig(self, child):
+		#child.logfile = sys.stdout
+		cmd = "save"
+		child.sendline(cmd)
+		opt = child.expect(["Confirm(.*)", "No save(.*)", pexpect.EOF, pexpect.TIMEOUT])
+		if opt == 0:
+				print "saving to flash"
+				child.sendline("y\n")
+		if opt == 1:
+				print "no save needed"
+		child.sendline('exit')
+		child.terminate()
+
+	def enableHostPort(self):
+		child = self.__login()
+		cmd = "/cfg/port " + str(self.host['hw_port']) + " /ena/apply "
+		child.sendline(cmd)
+		#  testing this thread... Looks like this works ...
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+	def disableHostPort(self):
+		child = self.__login()
+		cmd = "/cfg/port " + str(self.host['hw_port']) + " /dis/apply "
+		child.sendline(cmd)
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+	def removeVlan(self, num):
+		print "removing vlan"
+		#  Check for important vlans
+		child = self.__login()
+
+		cmd = "/cfg / l2 / vlan " + num + " / del / apply"
+		child.sendline(cmd)
+		opt = child.expect(["Confirm(.*)", pexpect.EOF, pexpect.TIMEOUT])
+		if opt == 0:
+			child.sendline("y\n")
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+
+	def addVlanToTrunk(self, vlan):
+		print "NOT IMPLEMENTED"
+		print "No trunks to test @ MIMOS"
+
+	def createVlansThread(self, vlan, switch,host):
+		mesg = "Creating vlan %s on switch %s" % (str(vlan), str(switch))
+		self.log.info(mesg)
+		self.createVlan(vlan)
+		self.addVlanToTrunk(vlan);
+		thread.exit()
+
+	def createVlans(self, vlan, switchlist, query):
+		for switch in switchlist:
+			#print "working on switch ", switch
+			#self.host = query.getSwitchInfo(switch)
+#thread.start_new_thread(self.createVlansThread, (vlan, switch, self.host))
+			mesg = "Creating vlan %s on switch %s" % (str(vlan), str(switch))
+			self.log.info(mesg)
+			self.host = query.getSwitchInfo(switch)
+			self.createVlan(vlan)
+			self.addVlanToTrunk(vlan);
+
+	def removeVlans(self, vlan, switchlist, query):
+		for switch in switchlist:
+			mesg = "Deleting vlan %s on switch %s" % (str(vlan), str(switch))
+			self.log.info(mesg)
+			self.host = query.getSwitchInfo(switch)
+			self.removeVlan(vlan)
+
+	def createVlan(self, val):
+		vlanname = False
+		if ":" in val:
+			num = int(val.split(":")[0])
+			vlanname = val.split(":")[1]
+		else:
+			vlanname = self.__getPrsLabel()
+			num = int(val)
+
+		if num > 4095 or num < 0:
+			mesg = "Vlan out of range.  Must be < %s" % (self.config['vlan_max'])
+			self.log.error(mesg)
+			exit(1)
+
+		child = self.__login()
+		cmd = "/cfg / l2 / vlan " + str(num) + " / ena/ apply"
+		child.sendline(cmd)
+		cmd = "name " + str(vlanname) +  " / apply"
+		child.sendline(cmd)
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+
+	#  Raw Switch commands.  DEBUG ONLY!, Doesn't work!
+	def sendSwitchCommand(self, cmds):
+		if len(cmds) > 0:
+			child = self.__login()
+			child.logfile = sys.stdout
+		for cmd in cmds.split(";"):
+			child.sendline(cmd)
+			try:
+				i=child.expect(['console','sw', 'Name:', pexpect.EOF, pexpect.TIMEOUT], timeout=2)
+				i=child.expect(['console','sw', 'Name:', pexpect.EOF, pexpect.TIMEOUT], timeout=2)
+
+			except EOF:
+				print "EOF", i
+				#child.sendline()
+			except TIMEOUT:
+				print "TIMEOUT", i
+		#child.interact(escape_character='\x1d', input_filter=None, output_filter=None)
+
+		child.terminate()
+		#print "before", child.before
+		#print "after", child.after
+
+	def addNodeToVlan(self, vlan):
+		child = self.__login()
+		cmd = "/cfg/l2/vlan " + str(vlan) + " /add " + str(self.host['hw_port']) + " /apply "
+		child.sendline(cmd)
+		opt = child.expect(['(.*)#','(.*)needs to be enabled', pexpect.EOF, pexpect.TIMEOUT], timeout=2)
+		if opt == 1:
+			print "VLAN Created, Enabling..." + str(vlan)
+			cmd = "/cfg/l2/vlan " + str(vlan) + " /ena/apply "
+			child.sendline(cmd)
+
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+
+	def removeNodeFromVlan(self, vlan):
+		child = self.__login()
+		cmd = "/cfg/l2/vlan " + str(vlan) + " /rem " + str(self.host['hw_port']) + "/apply"
+		child.sendline(cmd)
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+	def setNativeVlan(self, vlan):
+		child = self.__login()
+		#child.logfile = sys.stdout
+		cmd = "/cfg/port " + str(self.host['hw_port']) + "/pvid " + str(vlan) + "/apply"
+		child.sendline(cmd)
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+		#  HP switches allow more free control.  Example, if you set a port to a native vlan
+		#  that doesn't exist, HP switches will happily create for you.
+		#  However, if you delete a vlan that exists on many ports, it will still happily delete
+		#  the vlan, forcing all the other ports to default to some other native vlan.  Need
+		#  to make sure we check before blasting vlans.
+
+	#  Restore Native Vlan.
+	def restoreNativeVlan(self):
+		child = self.__login()
+		cmd = "/cfg/port " + str(self.host['hw_port']) + "/pvid 1/apply"
+		child.sendline(cmd)
+		threading.Thread(target=self.__saveConfig(child)).start()
+
+	#  Setup the switch for node allocation
+	def allocateNode(self):
+		pass
+
+	#  Remove all vlans from the interface
+	def removeAllVlans(self):
+		child = self.__login()
+		cmd = "/cfg/port " + str(self.host['hw_port']) + "/tag d/apply"
+		#child.logfile = sys.stdout
+		child.sendline(cmd)
+
+	def showInterfaceConfig(self):
+		print "\n---------------" + self.host['hw_make'] + "---------------------"
+		print "SWITCH - " + self.host['hw_name'] + "/" + str(self.host['hw_port'])
+		print "NODE- " + self.host['location']
+		print "------------------------------------\n"
+		#  using run and parsing output.  Still have issues an "rt" after the command.  Fix later
+		#val = pexpect.run("telnet sw0-r4r1e1", withexitstatus=False, timeout=2, events=({'(?i)password:':
"admin\r\n", "Main#": "info\r\n", "Info(.*)" : "port\r\n"})) #, "Info(.*)" : "exit\n"}))
+		#  Just print everything for now, fix when back in the US
+		#print val
+
+
+		child = self.__login()
+		cmd = "/info/port " + str(self.host['hw_port'])
+		child.sendline(cmd)
+		child.logfile = sys.stdout
+		opt = child.expect(['Info(.*)', pexpect.EOF, pexpect.TIMEOUT])
+
+	#  this needs to be removed or rewritten
+	def interactiveSwitchConfig(self):
+		switchIp = "telnet " + self.host['hw_name']
+		child = pexpect.spawn(switchIp)
+		child.setecho(False)
+		#child.expect('Name:')
+		#child.sendline(self.host['hw_userid'])
+		#i=child.expect(['test','password:','Password:', pexpect.EOF, pexpect.TIMEOUT])
+		#child.logfile = sys.stdout
+		child.sendline(self.host['hw_password'])
+		child.interact(escape_character='\x1d', input_filter=None, output_filter=None)
 
 



Mime
View raw message