incubator-tashi-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rg...@apache.org
Subject svn commit: r1034085 - in /incubator/tashi/trunk: etc/ src/zoni/client/ src/zoni/data/ src/zoni/extra/ src/zoni/hardware/ src/zoni/install/db/
Date Thu, 11 Nov 2010 19:56:31 GMT
Author: rgass
Date: Thu Nov 11 19:56:30 2010
New Revision: 1034085

URL: http://svn.apache.org/viewvc?rev=1034085&view=rev
Log:
Many changes to the DB layout as well as adding default values via the setup script.
Switched some tables over to INNODB to support foreign keys and cascading deletes.
Added support for initial hardware additions (some dell switches and a raritan pdu)




Modified:
    incubator/tashi/trunk/etc/ZoniDefaults.cfg
    incubator/tashi/trunk/src/zoni/client/zoni-cli.py
    incubator/tashi/trunk/src/zoni/data/infostore.py
    incubator/tashi/trunk/src/zoni/data/resourcequerysql.py
    incubator/tashi/trunk/src/zoni/extra/util.py
    incubator/tashi/trunk/src/zoni/hardware/dellswitch.py
    incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py
    incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py

Modified: incubator/tashi/trunk/etc/ZoniDefaults.cfg
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/etc/ZoniDefaults.cfg?rev=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/etc/ZoniDefaults.cfg (original)
+++ incubator/tashi/trunk/etc/ZoniDefaults.cfg Thu Nov 11 19:56:30 2010
@@ -76,6 +76,8 @@ HARDWARE_PDU = "raritan"
 HARDWARE_DRAC = "DELL DRAC"
 
 [DhcpDns]
+dnsEnabled = True
+reverseDns = True
 #  Key file must be in the same directory or this will get denied
 dnsKeyFile = xx_Kname.+157+36480.private_xx
 dnsServer = xx_dns_server_ip_xx xx_port_xx

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=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/client/zoni-cli.py (original)
+++ incubator/tashi/trunk/src/zoni/client/zoni-cli.py Thu Nov 11 19:56:30 2010
@@ -26,6 +26,7 @@ import optparse
 import socket
 import logging.config
 import getpass
+import re
 
 
 
@@ -76,10 +77,15 @@ def main():
 	parser.add_option("-u", "--userName", dest="userName", help="Specify user name")
 	parser.add_option("--uid", dest="uid", help="Specify user id")
 	parser.add_option("-v", "--verbose", dest="verbosity", help="Be verbose", action="store_true", default=False)
+	parser.add_option("--Name", "--name", dest="Name", help="Specify name of entry")
+	parser.add_option("--Show", "--show", dest="show", help="Show something", default=None, action="store_true")
+	parser.add_option("-d", "--domain", dest="domain", help="Work with this domain")
+	parser.add_option("--notes", "--Notes",  dest="myNotes", help="Notes", default="")
+	parser.add_option("--force",  dest="forcefully", help="Apply gentle pressure", default=False, action="store_true")
 
 
 	#  Hardware controller
-	group = optparse.OptionGroup(parser, "Hardware control", "Options to control power on nodes")
+	group = optparse.OptionGroup(parser, "Hardware control", "Options for node power control")
 	group.add_option("--hw", dest="hardwareType", help="Make hardware call to ipmi|drac|pdu")
 	group.add_option("--powerStatus", "--powerstatus", dest="POWERSTATUS", help="Get power status on node", action="store_true", default=False)
 	group.add_option("--reboot", "--reboot", dest="REBOOTNODE", help="Reboot node (Soft)", action="store_true", default=False)
@@ -94,25 +100,23 @@ def main():
 	group = optparse.OptionGroup(parser, "Query Interface", "Query current systems and allocations")
 	group.add_option("-R", "--showReservation", "--showreservation", dest="showReservation", help="Show current node reservations", action="store_true", default=False)
 	group.add_option("-A", "--showAllocation", "--showallocation", dest="showAllocation", help="Show current node allocation", action="store_true", default=False)
-	group.add_option("-s", "--showResources", dest="showResources", help="Show available resources to choose from", action="store_true", default=False)
+	group.add_option("-S", "--showResources", dest="showResources", help="Show available resources to choose from", action="store_true", default=False)
 	group.add_option("-p", "--procs", dest="numProcs", help="Set number of processors" )
 	group.add_option("-c", "--clock", dest="clockSpeed", help="Processor clock" )
 	group.add_option("--memory", dest="numMemory", help="Amount of memory (Bytes)" )
 	group.add_option("-f", "--cpuflags", dest="cpuFlags", help="CPU flags" )
 	group.add_option("--cores", dest="numCores", help="Number of Cores" )
-	group.add_option("-i", "--showPxeImages", "--showpxeimages", dest="showPxeImages", help="Show available PXE images to choose from", action="store_true", default=False)
-	group.add_option("-m", "--showPxeImageMap", "--showpxeimagemap", dest="showPxeImageMap", help="Show PXE images host mapping", action="store_true", default=False)
-	group.add_option("--showArchive", "--showarchive", dest="showArchive", help="Show allocation archive", action="store_true", default=False)
+	group.add_option("-I", "--showPxeImages", "--showpxeimages", dest="showPxeImages", help="Show available PXE images to choose from", action="store_true", default=False)
+	group.add_option("-M", "--showPxeImageMap", "--showpxeimagemap", dest="showPxeImageMap", help="Show PXE images host mapping", action="store_true", default=False)
 	parser.add_option_group(group)
 	#parser.add_option("-p", "--printResources", dest="printResources", help="Print available resources to choose from", action="store_true", default=False)
 
 	#  Admin Interface
 	group = optparse.OptionGroup(parser, "Admin Interface", "Administration Interface:")
 	group.add_option("--admin", dest="ADMIN", help="Enter Admin mode", action="store_true", default=False)
-	group.add_option("--addPxeImage", "--addpxeimage", dest="imageName", help="Add PXE image to database", action="store_true", default=False)
 	group.add_option("--enableHostPort", "--enablehostport", dest="enableHostPort", help="Enable a switch port", action="store_true", default=False)
 	group.add_option("--disableHostPort", "--disablehostport", dest="disableHostPort", help="Disable a switch port", action="store_true", default=False)
-	group.add_option("--removeVlan", "--removevlan", dest="removeVlanId", help="Remove vlan from all switches")
+	group.add_option("--destroyVlan", "--destroyvlan", dest="removeVlanId", help="Remove vlan from all switches")
 	group.add_option("--createVlan", "--createvlan", dest="createVlanId", help="Create a vlan on all switches")
 	group.add_option("--addNodeToVlan", "--addnodetovlan", dest="add2Vlan", help="Add node to a vlan")
 	group.add_option("--removeNodeFromVlan", "--removenodefromvlan", dest="removeFromVlan", help="Remove node from a vlan")
@@ -134,27 +138,36 @@ def main():
 	#group.add_option("--addVlanToTrunks", "--addvlantotrunks", dest="addVlanToTrunks", help="")
 	
 
+	#  Domain Interface
+	group = optparse.OptionGroup(parser, "Domain Interface", "Manage Zoni Domain:")
+	group.add_option("-D", "--showDomains", "--showdomains", dest="showDomains", help="Show Zoni domains", action="store_true", default=False)
+	group.add_option("--addDomain", "--adddomain", dest="addDomain", help="Add new domain to Zoni", action="store_true", default=False)
+	group.add_option("--removeDomain", "--removedomain", dest="removeDomain", help="remove a domain from Zoni", action="store_true", default=False)
+	group.add_option("-V", "--showVlans", "--showvlans", dest="showVlans", help="Show an from Zoni", action="store_true", default=False)
+	group.add_option("--addVlan", "--addvlan", dest="addVlan", help="Add new vlan to Zoni", action="store_true", default=False)
+	group.add_option("--removeVlan", "--removevlan", dest="removeVlan", help="Remove an from Zoni", action="store_true", default=False)
+	group.add_option("--assignVlan", "--assignvlan", dest="assignVlan", help="Assign vlan to a domain")
+	parser.add_option_group(group)
+
 	#  Allocation Interface
 	group = optparse.OptionGroup(parser, "Allocation Interface", "Change current systems allocations:")
-	#group.add_option("-a", "--allocateResources", dest="allocateResources", help="Allocate resource", action="store_true", default=False)
 	group.add_option("--addImage", "--addimage", dest="addImage", help="Add image to Zoni - amd64-image:dist:dist_ver")
 	group.add_option("--delImage", "--delimage", dest="delImage", help="Delete PXE image")
-	group.add_option("--assignImage", "--assignimage", dest="assignImage", help="Assign image to resource")
+	#group.add_option("--addPxeImage", "--addpxeimage", dest="imageName", help="Add PXE image to database", action="store_true", default=False)
+	group.add_option("--imageName", "--imagename", dest="imageName", help="Assign image to resource")
 
 	group.add_option("--allocateNode", "--allocatenode", dest="allocateNode", help="Assign node to a user", action="store_true", default=False)
-	group.add_option("--allocationNotes", "--allocationnotes", dest="allocationNotes", help="Description of allocation")
+	group.add_option("--vlaninfo", "--vlanInfo", dest="vlanInfo", help="Specify vlan info for allocation")
 	group.add_option("--vlanIsolate", "--vlanisolate", dest="vlanIsolate", help="Specify vlan for network isolation")
 	group.add_option("--hostName", "--hostname", dest="hostName", help="Specify hostname for node")
 	group.add_option("--ipaddr", dest="ipAddr", help="Specify ip address for node")
 
 	group.add_option("--releaseNode", "--releasenode", dest="releaseNode", help="Release current node allocation", action="store_true", default=False)
 	group.add_option("--reservationDuration", "--reservationduration", dest="reservationDuration", help="Specify duration of node reservation - YYYYMMDD format")
-	group.add_option("--reservationId", "--reservationid", dest="reservationId", help="Reservation ID")
-	group.add_option("--reservationNotes", "--reservationnotes", dest="reservationNotes", help="Description of reservation")
+	group.add_option("-r", "--reservationId", "--reservationid", dest="reservationId", help="Reservation ID")
 	group.add_option("--addReservation", "--addreservation", dest="addReservation", help="Add a Reservation", action="store_true", default=False)
 	group.add_option("--updateReservation", "--updatereservation", dest="updateReservation", help="Update Reservation", action="store_true", default=False)
 	group.add_option("--delReservation", "--delreservation", dest="delReservation", help="Delete Reservation")
-	#group.add_option("-a", "--allocateResources", dest="allocateResources", help="Allocate resource", action="store_true", default=False)
 	group.add_option("--rgasstest", dest="rgasstest", help="Debug testing function", action="store_true", default=False)
 	parser.add_option_group(group)
 
@@ -170,6 +183,7 @@ def main():
 
 	(options, args) = parser.parse_args()
 
+	
 	cmdargs = {}
 
 	#  setup db connection
@@ -199,7 +213,7 @@ def main():
 				hw = Ipmi(options.nodeName, host["ipmi_user"], host["ipmi_password"])
 
 			if options.hardwareType == "pdu":
-				hw = raritanDominionPx(host)
+				hw = raritanDominionPx(configs, host)
 
 			if options.hardwareType == "drac":
 				#  Check if node has drac card
@@ -263,7 +277,7 @@ def main():
 	if (options.cpuFlags):
 		cmdargs["cpu_flags"] = options.cpuFlags
 	if (options.nodeName):
-		cmdargs["node_id"] = options.nodeName
+		cmdargs["sys_id"] = options.nodeName
 
 	if 	(options.numCores or options.clockSpeed or options.numMemory or options.numProcs or options.cpuFlags) and not options.showResources:
 			usage = "MISSING OPTION: When specifying hardware parameters, you need the -s or --showResources switch"
@@ -272,9 +286,8 @@ def main():
 			exit()
 
 	#  Show current allocations 
-	if (options.showAllocation):
+	if (options.showAllocation) or (options.show and re.match(".lloca.*", args[0])):
 		if options.uid:
-			print "set"
 			nameorid = int(options.uid)
 		else: 
 			nameorid = options.userName
@@ -283,45 +296,32 @@ def main():
 		exit()
 
 	#  Show current reservation
-	if (options.showReservation):
+	if options.showReservation or (options.show and re.match(".eserv.*", args[0])):
 		if options.uid:
-			print "set"
 			nameorid = int(options.uid)
 		else: 
 			nameorid = options.userName
 
 		query.showReservation(nameorid)
-		exit()
-
-	#  Show allocation Archive
-	if (options.showArchive):
-		query.showArchive()
 
 	#  Print all Resources
-	if (options.showResources):
+	if options.showResources or (options.show and re.match(".esour.*", args[0])):
 		query.showResources(cmdargs)
 
 	#  Show PXE images
-	if (options.showPxeImages):
+	#if (options.show and re.match(".esour.*", args[0])):
+	if options.showPxeImages or (options.show and re.match("pxei.*", args[0])):
 		query.showPxeImages()
 
 	#  Show machine to PXE image mapping
-	if (options.showPxeImageMap):
+	if options.showPxeImageMap or (options.show and re.match("pxem.*", args[0])):
 		query.showPxeImagesToSystemMap(cmdargs)
-		exit()
 
 	if (len(sys.argv) == 1):
 		parser.print_help()
 		exit()
 
 
-	#  Get the host object
-	#hostObj = getHostObject()
-	#if (options.allocateResources) and options.nodeName:
-		#query.getHostInfo(options.nodeName)
-		
-		#exit()
-
 	#  Delete reservation
 	if (options.delReservation):
 		query.removeReservation(options.delReservation)
@@ -346,7 +346,7 @@ def main():
 		#drac.powerReset()
 		#drac.getPowerStatus()
 		print "host is ", host
-		pdu = raritanDominionPx(host)
+		pdu = raritanDominionPx(configs, host)
 		print "pdu", pdu
 		pdu.getPowerStatus()
 		exit()
@@ -359,8 +359,7 @@ def main():
 				mesg += "  Username:  --userName=username or --uid 1000\n"
 
 			mesg += "  Reservation Duration:  --reservationDuration YYYYMMDD or numdays(optional, default 15 days)\n"
-			#mesg += "  ReservationId:  --reservationId IDNUM(optional, you want this if you want to add nodes to an existing reservation)\n"
-			mesg += "  Notes:  --reservationNotes(optional)\n"
+			mesg += "  Notes:  --notes(optional)\n"
 			sys.stderr.write(mesg)		
 			exit()
 
@@ -368,15 +367,29 @@ def main():
 		if not options.uid:
 			userId = usermgt.getUserId(options.userName)
 
-		reservationId = query.addReservation(userId, options.reservationDuration, options.reservationNotes)
+		reservationId = query.addReservation(userId, options.reservationDuration, options.myNotes + " " + str(string.join(args[0:len(args)])))
 
 
 	#  Allocate node to user
 	if (options.allocateNode):
-		vlanNum = 999
-		if (options.vlanIsolate):
-			vlanNum = options.vlanIsolate
+		if options.reservationId and options.domain and options.vlanInfo and options.nodeName and options.imageName:
+			host = query.getHostInfo(options.nodeName)
+			#  optparse does not pass multiple args that are quoted anymore?  
+			#  Used to work with python 2.5.2.  Doesn't work with python 2.6.5.  
+			query.allocateNode(options.reservationId, options.domain, host['sys_id'], options.vlanInfo, options.imageName, options.myNotes + " " + str(string.join(args[0:len(args)])))
+		else:
+			mesg = "USAGE: %s --allocateNode --nodeName nodeName --domain domainname --reservationId ID --vlanInfo vlanNums:info, --imageName imagename [--notes]\n" % (sys.argv[0])
+			mesg += "Options\n"
+			mesg += "  --domain testdomain\n"
+			mesg += "  --reservationId 10\n"
+			mesg += "  --vlanInfo 999:native,1000:tagged,1001:tagged\n"
+			mesg += "  --imageName imageName (see available images with 'zoni -I')\n"
+			mesg += "  --hostName mynode01 (optional)\n"
+			mesg += "  --notes \"your notes here \"(optional)\n"
+			sys.stdout.write(mesg)
+			exit()
 		
+		exit()  #remove this
 		if not (options.reservationId) or not options.nodeName: 
 			mesg = "ERROR:  AllocateNode requires the following arguments...\n"
 			if not (options.nodeName):
@@ -387,11 +400,12 @@ def main():
 			mesg += "  Hostname:  --hostName mynode01\n"
 			mesg += "  Domain:  --vlanIsolate vlan_num(default 999)\n"
 			mesg += "  IP address:  --ipaddr 172.17.10.100\n"
-			mesg += "  Notes:  --allocationNotes(optional)\n"
+			mesg += "  Notes:  --notes(optional)\n"
 			sys.stderr.write(mesg)		
 			exit()
 
-		query.allocateNode(options.reservationId, host['node_id'], options.hostName,  vlanNum, options.ipAddr, options.allocationNotes)
+		print host['sys_id']
+		query.allocateNode(options.reservationId, host['sys_id'], options.hostName,  vlanNum, options.ipAddr, options.Notes)
 		exit()
 
 	#  Update allocation
@@ -404,7 +418,7 @@ def main():
 			mesg += "  Username:  --userName=username or --uid 1000 (optional)\n"
 			mesg += "  Reservation Duration:  --reservationDuration YYYYMMDD or numdays (optional, default 15 days)\n"
 			mesg += "  Vlan:  --vlanIsolate vlan_num(optional)\n"
-			mesg += "  Notes:  --reservationNotes(optional)\n"
+			mesg += "  Notes:  --notes(optional)\n"
 			sys.stderr.write(mesg)		
 			exit()
 
@@ -415,8 +429,8 @@ def main():
 			if not options.uid:
 				userId = usermgt.getUserId(options.userName)
 
-		print options.reservationId, userId, options.reservationDuration, options.vlanIsolate, options.reservationNotes
-		query.updateReservation(options.reservationId, userId, options.reservationDuration, options.vlanIsolate, options.reservationNotes)
+		print options.reservationId, userId, options.reservationDuration, options.vlanIsolate, options.Notes
+		query.updateReservation(options.reservationId, userId, options.reservationDuration, options.vlanIsolate, options.Notes)
 
 	#  Release node allocation
 	if (options.releaseNode):
@@ -430,19 +444,19 @@ def main():
 		query.releaseNode(options.nodeName)
 		
 	#  Assign image to host
-	if (options.assignImage):
-		if not options.nodeName:
-			usage = "Node not specified.  Please specify a node with --nodeName or -n"
-			print usage
-			exit()
-		if query.assignImagetoHost(host, options.assignImage):
-			print "ERROR"
-			exit()
-
+	#if (options.assignImage):
+		#if not options.nodeName:
+			#usage = "Node not specified.  Please specify a node with --nodeName or -n"
+			#print usage
+			#exit()
+		#if query.assignImagetoHost(host, options.assignImage):
+			#print "ERROR"
+			#exit()
+#
 		#  Update PXE 
-		bootit = pxe.Pxe(configs, options.verbosity)
-		bootit.createPxeUpdateFile(query.getPxeImages())
-		bootit.updatePxe()
+		#bootit = pxe.Pxe(configs, options.verbosity)
+		#bootit.createPxeUpdateFile(query.getPxeImages())
+		#bootit.updatePxe()
 		
 	
 	#  Add image to database
@@ -452,6 +466,51 @@ def main():
 	if (options.delImage):
 		query.delImage(options.delImage)
 
+	#  Domain interface
+	if (options.showDomains):
+		query.showDomains()
+	if (options.addDomain):
+		if len(args) > 2 and options.reservationId:
+			query.addDomain(args[0], string.join(args[1:len(args)]), options.reservationId)
+		else:
+			mesg = "USAGE: %s --addDomain domainname domaindesc --reservationId ID\n" % (sys.argv[0])
+			sys.stdout.write(mesg)
+			exit()
+	if (options.removeDomain):
+		if len(args) > 0:
+			query.removeDomain(args[0])
+		else:
+			mesg = "USAGE: %s --removeDomain domainname \n" % (sys.argv[0])
+			sys.stdout.write(mesg)
+			exit()
+
+	if (options.showVlans):
+		query.showVlans()
+	if (options.addVlan):
+		print len(args)
+		if len(args) > 0:
+			query.addVlan(args[0], string.join(args[1:len(args)]))
+		else:
+			mesg = "USAGE: %s --addVlan vlanNumber [VlanDesc]\n" % (sys.argv[0])
+			sys.stdout.write(mesg)
+			exit()
+	if (options.removeVlan):
+		if len(args) > 1:
+			query.removeVlan(args[0])
+		else:
+			mesg = "USAGE: %s --removeVlan VlanNumber\n" % (sys.argv[0])
+			sys.stdout.write(mesg)
+			exit()
+
+	if (options.assignVlan):
+		print len(args)
+		if len(args) > 0:
+			query.assignVlan(options.assignVlan, args[0], options.forcefully)
+		else:
+			mesg = "USAGE: %s --assignVlan vlannum DomainName\n" % (sys.argv[0])
+			sys.stdout.write(mesg)
+			exit()
+		
 	#  Admin Interface
 	#  snmpwalk -v2c -c zoni-domain sw0-r1r1 .1.3.6.1.2.1.17.7.1.4.3.1.5    
 	if (options.ADMIN):
@@ -521,7 +580,7 @@ def main():
 				HwSwitch = HwDellSwitch
 				hw = HwSwitch(configs)
 			elif string.lower(args[0]) == "raritan":
-				hw = raritanDominionPx()
+				hw = raritanDominionPx(configs)
 			else:
 				mesg = "Undefined hardware type\nSupported Hardware" + str(supported_hardware) + "\n"
 				sys.stderr.write(mesg)
@@ -535,7 +594,7 @@ def main():
 			data = hw.registerToZoni(args[1], password, args[2])
 
 			#  Register to DB
-			query.registerHardware(data)
+			#query.registerHardware(data)
 			
 	#  Zoni Helper
 	if options.addDns or options.removeDns or options.addDhcp or options.removeDhcp or options.addCname or options.removeCname:

Modified: incubator/tashi/trunk/src/zoni/data/infostore.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/data/infostore.py?rev=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/data/infostore.py (original)
+++ incubator/tashi/trunk/src/zoni/data/infostore.py Thu Nov 11 19:56:30 2010
@@ -32,6 +32,26 @@ class InfoStore (object):
 	#def updateDatabase(self, query):
 		#raise NotImplementedError
 
+	def addDomain(self):
+		raise NotImplementedError
+
+	def removeDomain(self):
+		raise NotImplementedError
+
+	def showDomains(self):
+		raise NotImplementedError
+
+	def addVlan(self):
+		raise NotImplementedError
+
+	def removeVlan(self):
+		raise NotImplementedError
+
+	def showVlans(self):
+		raise NotImplementedError
+
+	def assignVlan(self):
+		raise NotImplementedError
 
 	def printAll(self):
 		raise NotImplementedError
@@ -56,3 +76,12 @@ class InfoStore (object):
 		'''
 		raise NotImplementedError
 	
+	def addPxeImage(self):
+		raise NotImplementedError
+
+	def removePxeImage(self):
+		raise NotImplementedError
+
+	def assignPxeImage(self):
+		raise NotImplementedError
+

Modified: incubator/tashi/trunk/src/zoni/data/resourcequerysql.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/data/resourcequerysql.py?rev=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/data/resourcequerysql.py (original)
+++ incubator/tashi/trunk/src/zoni/data/resourcequerysql.py Thu Nov 11 19:56:30 2010
@@ -24,11 +24,11 @@ import string
 import MySQLdb
 import subprocess
 import traceback
+import logging
 
 import usermanagement
-
 from zoni.data.infostore import InfoStore
-from zoni.extra.util import logit, checkSuper
+from zoni.extra.util import checkSuper
 from zoni.agents.dhcpdns import DhcpDns
 
 class ResourceQuerySql(InfoStore):
@@ -39,12 +39,13 @@ class ResourceQuerySql(InfoStore):
 		self.user = config['dbUser']
 		self.passwd = config['dbPassword']
 		self.db = config['dbInst']
+		#self.log = logging.getLogger(os.path.basename(__name__))
+		self.log = logging.getLogger(__name__)
 		
 		self.tftpRootDir = config['tftpRootDir']
 		self.tftpImageDir = config['tftpImageDir']
 		self.tftpBootOptionsDir = config['tftpBootOptionsDir']
 
-		self.logFile = config['logFile']
 
 		if config['dbPort'] == "":
 			config['dbPort'] = 3306
@@ -65,13 +66,135 @@ class ResourceQuerySql(InfoStore):
 				print "ERROR : ", e
 				exit(1)
 
+	def getNote(self):
+		return "Created by Zoni"
+
+	def addDomain(self, name, desc, reservationId):
+		#  Check if there is a reservation
+		query = "select * from reservationinfo where reservation_id = %s" % (reservationId)
+		result = self.__selectDb(query)
+		if result.rowcount < 1:
+			mesg = "Reservation does not exist : %s" % (reservationId)
+			self.log.error(mesg)
+			return -1
+
+		if desc == None:
+			desc = self.getNote()
+
+		print name
+		if self.__checkDup("domaininfo", "domain_name", name):
+			self.log.error("Domain (%s) already exists" % (name))
+			return -1
+		query = "insert into domaininfo (domain_name, domain_desc, reservation_id) values ('%s','%s', '%s')" % (name, desc, reservationId)
+		try:
+			result = self.__insertDb(query)
+			mesg = "Adding domain %s(%s)" % (name, desc)
+			self.log.info(mesg)
+		except Exception, e:
+			mesg = "Adding domain %s(%s) failed : %s" % (name, desc, e)
+			self.log.error(mesg)
+		
+
+	def removeDomain(self, name):
+		mesg = "Removing domain %s" % (name)
+		self.log.info(mesg)
+		query = "delete from domaininfo where domain_name = '%s'" % (name)
+		result = self.__deleteDb(query)
+		#  Need to remove any vlans attached to this domain
+
+	def showDomains(self):
+		query = "select domain_name, domain_desc from domaininfo"
+		result = self.__selectDb(query)
+		desc = result.description
+		if result.rowcount > 0:
+			print "%s\t%s\n-------------------------------------" % (result.description[0][0], result.description[1][0])
+			for row in result.fetchall():
+				print "%s\t\t%s" % (row[0], row[1])
+			return 0
+		else:
+			mesg = "No Domains exist"
+			self.log.info(mesg)
+			return -1
+
+	def addVlan(self, vnumber, desc=None):
+		if desc == None:
+			desc = "Created by Zoni"
+		if int(vnumber) > self.vlan_max:
+			self.log.error("Max vlan size is %s" % (self.vlan_max))
+			return -1
+
+		if self.__checkDup("vlaninfo", "vlan_num", vnumber):
+			self.log.error("Vlan %s already exists" % (vnumber))
+			return -1
+		query = "insert into vlaninfo (vlan_num, vlan_desc) values ('%s','%s')" % (vnumber, desc)
+		try:
+			result = self.__insertDb(query)
+			mesg = "Adding vlan %s(%s)" % (vnumber, desc)
+			self.log.info(mesg)
+		except Exception, e:
+			mesg = "Adding vlan %s(%s) failed : %s" % (vnumber, desc, e)
+			self.log.error(mesg)
+		
+
+	def removeVlan(self, vnumber):
+		query = "delete from vlaninfo where vlan_num = '%s'" % (vnumber)
+		result = self.__deleteDb(query)
+		if result > 0:
+			mesg = "Successfully removed vlan %s" % (vnumber)
+			self.log.info(mesg)
+			return 0
+		else:
+			mesg = "Failed to removed vlan %s" % (vnumber)
+			self.log.info(mesg)
+			return -1
+		#  Need to remove any vlans attached to this vlan 
+
+	def showVlans (self):
+		query = "select vlan_num, vlan_desc from vlaninfo order by vlan_num"
+		try:
+			result = self.__selectDb(query)
+			print "%s\t%s\n-------------------------------------" % (result.description[0][0], result.description[1][0])
+			for row in result.fetchall():
+				print "%s\t\t%s" % (row[0], row[1])
+			return 0
+		except Exception, e:
+			mesg = "No Vlans defined: %s" % (e)
+			self.log.info(mesg)
+			return -1
+
+	def assignVlan(self, vlan, domain, force=None):
+		domainId = self.__getSomething("domain_id", "domaininfo", "domain_name", domain)
+		vlanId = self.__getSomething("vlan_id", "vlaninfo", "vlan_num", vlan)
+		query = "select * from domainmembermap m, vlaninfo v, domaininfo d where d.domain_id = '%s' and v.vlan_id = %s and v.vlan_id = m.vlan_id and m.domain_id = d.domain_id" % (int(domainId), int(vlanId))
+		if self.__selectDb(query).rowcount > 0:
+			self.log.warning("Vlan %s already assigned to domain %s" % (vlan, domain));
+			return 0
+
+		# warning if vlan already assigned to another domain
+		query = "select * from domainmembermap where vlan_id = %s" % (vlanId)
+		if self.__selectDb(query).rowcount > 0:
+			self.log.warning("Vlan %s already assigned to a domain" % (vlan));
+			if not force:
+				return -1
+
+		self.log.info("Assigning vlan %s to domain %s" % (vlan, domain))
+		query = "insert into domainmembermap (domain_id, vlan_id) values (%s, %s)" % (domainId, vlanId)
+		self.__insertDb(query)
+
+	def __getSomething(self, fieldname, table, critField, crit):
+		query = "select %s from %s where %s = '%s'" % (fieldname, table, critField, crit)
+		result = self.__selectDb(query)
+		return result.fetchall()[0][0]
+
+
 	def __checkDup (self, table, colname, value, colname2=None, value2=None):
 		cond = "where %s = '%s' " % (colname, value)
 		if (colname2 != None and value2 != None):
 			cond += " and %s = '%s'" % (colname2, value2)
 		query = "select * from %s %s" % (table, cond)
 		result = self.__selectDb(query)
-		#j$val = $this->set_num_rows ($result);
+		if result.rowcount == 0:
+			return []
 		return result.fetchall()
 
 	def __create_queryopts(self, cmdargs, extra=None):
@@ -189,7 +312,7 @@ class ResourceQuerySql(InfoStore):
 				break
 		if not myvlan:
 			mesg = "No Vlans for you!  You Go Now\n"
-			logit(self.logFile, mesg)
+			self.log.info(mesg)
 		return myvlan
 	
 	def isVlanAvailable(self, vlan):
@@ -207,9 +330,9 @@ class ResourceQuerySql(InfoStore):
 		if result.rowcount > 0:
 			return result.fetchall()[0][0]
 		else:
-			mesg = "ERROR: VLAN does not exist: " + str(vlan)
-			logit(self.logFile, mesg)
-			exit()
+			mesg = "VLAN does not exist: " + str(vlan)
+			self.log.error(mesg)
+			return -1 
 
 	def isIpAvailable(self, ip_addr, vlan_id):
 		query = "select * from allocationinfo where ip_addr = \"" + str(ip_addr) + "\" and vlan_id = \"" + str(vlan_id) + "\""
@@ -251,11 +374,11 @@ class ResourceQuerySql(InfoStore):
 		return ip_addr
 
 
-	def showArchive(self):
-		query = "select * from allocationarchive"
-		result = self.__selectDb(query)
-		for i in result:
-			print i
+	#def showArchive(self):
+		#query = "select * from allocationarchive"
+		#result = self.__selectDb(query)
+		#for i in result:
+			#print i
 
 	def showAllocation(self, userId=None):
 		#from IPython.Shell import IPShellEmbed
@@ -263,27 +386,27 @@ class ResourceQuerySql(InfoStore):
 		#shell(local_ns=locals(), global_ns=globals())
 
 		#  specify usermanagement - ldap or files
-		usermgt = usermanagement.ldap()
+		usermgt = eval("usermanagement.%s" % (self.config['userManagement']) + "()")
 
-		query = "select r.user_id, s.location, s.num_cores, s.mem_total, \
-				r.reservation_expiration, r.notes, r.reservation_id, v.vlan_num, a.ip_addr, a.hostname,\
-				a.notes, i.image_name \
-				from allocationinfo a, sysinfo s, reservationinfo r, vlaninfo v, imageinfo i, imagemap m where \
-				s.mac_addr = m.mac_addr and \
-				m.image_id = i.image_id and \
-				s.sys_id = a.sys_id  and \
-				v.vlan_id = a.vlan_id and \
-				r.reservation_id = a.reservation_id "
+		query = "select r.user_id, d.domain_name, s.location, s.num_cores, \
+				s.mem_total, r.reservation_expiration, r.notes, r.reservation_id, a.hostname, \
+				a.notes, i.image_name from \
+				sysinfo s, imageinfo i, \
+				allocationinfo a, domaininfo d, reservationinfo r, imagemap j where \
+				i.image_id = j.image_id \
+				and r.reservation_id = a.reservation_id \
+				and d.domain_id = a.domain_id and s.sys_id = a.sys_id "
 		if userId:
 			myid = userId
 			if type(userId) == str:
 				#  convert username to id
 				myid = usermgt.getUserId(userId)
 				
-			query += " and user_id = " + myid + " " 
+			query += " and user_id = '%s' " % (myid)
 
 		query += "order by r.reservation_id asc, s.location"
 
+		print query
 		result = self.__selectDb(query)
 		
 		print "NODE ALLOCATION"
@@ -292,30 +415,30 @@ class ResourceQuerySql(InfoStore):
 			#print "Res_id\tUser    \tNode    \tCores\tMemory  \tExpiration\t\tVLAN\tHOSTNAME    \tIPADDR    \t\tReservationNotes|AllocationNotes"
 			print "%-5s%-10s%-10s%-12s%-12s%-5s%-15s%-18s%-24s%s" % ("Res", "User", "Host", "Cores/Mem","Expiration", "Vlan", "Hostname", "IP Addr", "Boot Image Name", "Notes")
 		else:
-			print "%-10s%-10s%-12s%-12s%s" % ("User", "Node", "Cores/Mem","Expiration", "Notes")
+			print "%-10s%-10s%-13s%-12s%s" % ("User", "Node", "Cores/Mem","Expiration", "Notes")
 
 		for i in result.fetchall():
 			uid = i[0]
-			host = i[1]
-			cores = i[2]
-			memory = i[3]
-			expire = str(i[4])[0:10]
+			domain = i[1]
+			host = i[2]
+			cores = i[3]
+			memory = i[4]
+			expire = str(i[5])[0:10]
 			if expire == "None":
 				expire = "0000-00-00"
-			rnotes = i[5]
-			resId= i[6]
-			vlanId= i[7]
-			ip_addr = i[8]
-			hostname = i[9]
-			anotes = i[10]
-			image_name = i[11]
+			rnotes = i[6]
+			resId= i[7]
+			hostname = i[8]
+			anotes = i[9]
+			image_name = i[10]
 			userName = usermgt.getUserName(uid)
 			combined_notes = str(rnotes) + "|" + str(anotes)
 			if self.verbose:
-				#print "%s\t%s    \t%s    \t%s\t%s  \t%s\t%s\t%s    \t%s    \t%s" % (resId, userName, host, cores, memory,expire, vlanId, hostname, ip_addr, combined_notes)
-				print "%-5s%-10s%-10s%-2s%-10s%-12s%-5s%-15s%-18s%-24s%s" % (resId, userName, host, cores, memory,expire, vlanId, hostname, ip_addr, image_name, combined_notes)
+				vlanId = 1000
+				ip_addr = "10.0.0.10"
+				print "%-5s%-10s%-10s%-2s/%-10s%-12s%-5s%-15s%-18s%-24s%s" % (resId, userName, host, cores, memory,expire, vlanId, hostname, ip_addr, image_name, combined_notes)
 			else:
-				print "%-10s%-10s%-2s%-10s%-12s%s" % (userName, host, cores, memory,expire, combined_notes)
+				print "%-10s%-10s%-2s/%-10s%-12s%s" % (userName, host, cores, memory,expire, combined_notes)
 		print "---------------------------------------------------------------------------------"
 		print str(result.rowcount) + " systems returned"
 
@@ -404,7 +527,6 @@ class ResourceQuerySql(InfoStore):
 	def showPxeImagesToSystemMap(self, cmdargs):
 		extra = "l.mac_addr = j.mac_addr and j.image_id = i.image_id"
 		queryopt = self.__create_queryopts(cmdargs, extra=extra)
-		print queryopt
 
 		query = "select  l.location, j.mac_addr, i.image_name from sysinfo l , imageinfo i, imagemap j " + queryopt + " order by l.location"
 		#print query
@@ -426,7 +548,6 @@ class ResourceQuerySql(InfoStore):
 	def getHostInfo(self, node):
 		host = {}
 		query = "select sys_id, mac_addr, num_procs, num_cores, mem_total, clock_speed, sys_vendor, sys_model, proc_vendor, proc_model, proc_cache, cpu_flags, bios_rev, location, system_serial_number, ip_addr from sysinfo where location = \"" + node + "\"" 
-		#print "query is ", query
 		result = self.__selectDb(query)
 		if result.rowcount > 1:
 			print "Multiple entries for system exist.  Please correct"
@@ -471,7 +592,7 @@ class ResourceQuerySql(InfoStore):
 			host['ipmi_addr'] = i[2]
 
 		#  Get image info
-		query = "select image_name from imagemap i, imageinfo j where i.image_id = j.image_id and mac_addr = \"" + host['mac_addr'] + "\"" 
+		query = "select image_name from imagemap i, imageinfo j where i.image_id = j.image_id" 
 		result = self.__selectDb(query)
 		if result.rowcount == 0:
 			host['pxe_image_name'] = "None"
@@ -539,21 +660,28 @@ class ResourceQuerySql(InfoStore):
 
 	def __queryDb(self, query):
 		cursor = self.conn.cursor()
-		cursor.execute (query)
-		row = cursor.fetchall()
-		desc = cursor.description
+		try:
+			cursor.execute (query)
+			self.conn.commit()
+			row = cursor.fetchall()
+			desc = cursor.description
+		except MySQLdb.OperationalError, e:
+			msg = "%s : %s" % (e[1], query)
+			self.log.error(msg)
+			#traceback.print_exc(sys.exc_info())
+
 		return row
 
 	def execQuery(self, query):
 		cursor = self.conn.cursor()
 		try:
 			cursor.execute (query)
+			self.conn.commit()
 		#except Exception:
 			#traceback.print_exc(sys.exc_info())
 		except MySQLdb.OperationalError, e:
-			msg = "ERROR: " + e[1]
-			sys.stderr.write(msg)
-			logit(self.logFile, msg)
+			msg = "%s : %s" % (e[1], query)
+			self.log.error(msg)
 			#traceback.print_exc(sys.exc_info())
 			exit()
 		return cursor
@@ -565,43 +693,57 @@ class ResourceQuerySql(InfoStore):
 		#except Exception:
 			#traceback.print_exc(sys.exc_info())
 		except MySQLdb.OperationalError, e:
-			msg = "ERROR: " + e[1]
+			msg = "SELECT Failed : %s : %s" % (e[1], query)
+			self.log.error(msg)
+			#traceback.print_exc(sys.exc_info())
+			return -1 
+		return cursor
+
+	def __deleteDb(self, query):
+		cursor = self.conn.cursor()
+		try:
+			cursor.execute (query)
+			self.conn.commit()
+		except MySQLdb.OperationalError, e:
+			msg = "DELETE Failed : %s : %s" % (e[1], query)
 			sys.stderr.write(msg)
-			logit(self.logFile, msg)
+			self.log.error(msg)
 			#traceback.print_exc(sys.exc_info())
-			exit()
+			return -1
 		return cursor
 
 	def __updateDb(self, query):
 		cursor = self.conn.cursor()
 		try:
 			cursor.execute (query)
+			self.conn.commit()
 		except MySQLdb.OperationalError, e:
-			msg = "ERROR: " + e[1]
+			msg = "UPDATE Failed : %s : %s" % (e[1], query)
 			sys.stderr.write(msg)
-			logit(self.logFile, msg)
+			self.log.error(msg)
 			#traceback.print_exc(sys.exc_info())
-			exit()
+			return -1
+		return cursor
 
 	def __insertDb(self, query):
 		cursor = self.conn.cursor()
 		try:
 			cursor.execute (query)
+			self.conn.commit()
 		#except Exception:
 			#traceback.print_exc(sys.exc_info())
 		except MySQLdb.OperationalError, e:
-			msg = "ERROR: " + e[1]
-			sys.stderr.write(msg)
-			logit(self.logFile, msg)
+			msg = "INSERT Failed : %s : %s" % (e[1], query)
+			self.log.error(msg)
 			#traceback.print_exc(sys.exc_info())
-			exit()
+			return -1
+		return cursor
 
 
 	def updateReservation (self, reservationId, userId=None, reservationDuration=None, vlanIsolate=None, allocationNotes=None):
 
-
-		mesg = "Updating reservation"
-		logit(self.logFile, mesg)
+		mesg = "Updating reservation %s" % (str(reservationId))
+		self.log.info(mesg)
 
 		if reservationDuration:
 			if len(resDuration) == 8:
@@ -612,30 +754,29 @@ class ResourceQuerySql(InfoStore):
 				p = os.popen(cmd)
 				expireDate = string.strip(p.read())
 			else:
-				mesg = "ERROR: Invalid reservation duration\n"
-				sys.stderr.write(mesg)
-				logit(self.logFile, mesg)
+				mesg = "ERROR: Invalid reservation duration"
+				self.log.error(mesg)
 				exit()
 
 			mesg = "Updating reservationDuration :" + resDuration
-			logit(self.logFile, mesg)
+			self.log.info(mesg)
 			query = "update reservationinfo set reservation_exiration = \"" + expireDate_ + "\" where reservation_id = \"" + str(reservationId) + "\""
 			self.__updateDb(query)
 
 		if allocationNotes:
 			mesg = "Updating allocationNotes to " + allocationNotes 
-			logit(self.logFile, mesg)
+			self.log.info(mesg)
 			query = "update reservationinfo set notes = \"" + allocationNotes + "\" where reservation_id = \"" + str(reservationId) + "\""
 			self.__updateDb(query)
 		if vlanIsolate:
 			mesg = "UPDATING Vlan: " 
-			logit(self.logFile, mesg)
+			self.log.info(mesg)
 			query = "update reservationinfo set vlan_num = " + vlanIsolate + " where reservation_id = \"" + str(reservationId) + "\""
 			print "query is ", query
 			self.__updateDb(query)
 		if userId:
 			mesg = "UPDATING USER:"
-			logit(self.logFile, mesg)
+			self.log.info(mesg)
 			query = "update reservationinfo set user_id = " + userId + " where reservation_id = \"" + str(reservationId) + "\""
 			self.__updateDb(query)
 
@@ -657,120 +798,92 @@ class ResourceQuerySql(InfoStore):
 			expireDate = string.strip(p.read())
 		else:
 			mesg = "ERROR: Invalid reservation duration\n"
-			sys.stderr.write(mesg)
-			logit(self.logFile, mesg)
+			self.log.info(mesg)
 			exit()
 
 		#  create reservation
 		#  Create the reservation
 		print userId, expireDate,reservationNotes
-		query = "insert into reservationinfo (user_id, reservation_expiration, notes) values (\"" + str(userId) + "\", " + str(expireDate) + ", \"" + reservationNotes + "\")"
-		mesg = "Creating new reservation\n" + query
-		logit(self.logFile, mesg)
-		self.__selectDb(query)
+		query = "insert into reservationinfo (user_id, reservation_expiration, notes) values (\"" + str(userId) + "\", " + str(expireDate) + ", \"" + str(reservationNotes) + "\")"
+		mesg = "Creating new reservation : " + query
+		self.log.info(mesg)
+		self.__insertDb(query)
 		#  Get the res_id
 		query = "select max(reservation_id) from reservationinfo"
 		res_id = self.__selectDb(query).fetchone()[0]
 		mesg = "  Reservation created - ID :" + str(res_id)
-		logit(self.logFile, mesg) 
-		return res_id
+		self.log.info(mesg)
 
+		return res_id
 
-	def archiveAllocation(self, nodeId, ip_addr, hostName, vlan_id, user_id, reservation_type, res_notes, notes):
-		combined_notes = str(res_notes) + "|" + str(notes)
-		mesg = "Insert to allocation archive:"
-		query = "insert into allocationarchive (sys_id, ip_addr, hostname, vlan_id, user_id, reservation_type, notes) \
-				values (\"" + \
-				str(nodeId) + "\", \"" + str(ip_addr) + "\", \"" + \
-				str(hostName) + "\", \"" + str(vlan_id) + "\", \"" + \
-				str(user_id) + "\", \"" + str(reservation_type) + "\", \"" + \
-				str(combined_notes) + "\")" 
 
-		self.__insertDb(query)
+	#def archiveAllocation(self, nodeId, ip_addr, hostName, vlan_id, user_id, reservation_type, res_notes, notes):
+		#combined_notes = str(res_notes) + "|" + str(notes)
+		#mesg = "Insert to allocation archive:"
+		#query = "insert into allocationarchive (sys_id, ip_addr, hostname, vlan_id, user_id, reservation_type, notes) \
+				#values (\"" + \
+				#str(nodeId) + "\", \"" + str(ip_addr) + "\", \"" + \
+				#str(hostName) + "\", \"" + str(vlan_id) + "\", \"" + \
+				#str(user_id) + "\", \"" + str(reservation_type) + "\", \"" + \
+				#str(combined_notes) + "\")" 
+#
+		#self.__insertDb(query)
 
-	@checkSuper
-	def allocateNode(self, reservationId, nodeId, hostName, vlanIsolate=None, ip_addr=None, notes=None):
-		#print "nodeId", nodeId, self.getMacFromSysId(nodeId)
+	def allocateNode(self, reservationId, domain, sysId, vlanInfo, imageName, notes=None):
+		print "reservationId", reservationId, domain, sysId, vlanInfo, imageName, notes
 
 		#  Check if node is already allocated
-		query = "select * from allocationinfo where sys_id = \"" + str(nodeId) + "\""
-		result = self.__selectDb(query)
-		if result.rowcount > 0:
-			val = str(result.fetchone())
-			mesg = "ERROR:  Node already allocated " + val + "\n"
-			logit(self.logFile, mesg)
-			exit()
-
+		result = self.__checkDup("allocationinfo", "sys_id", sysId)
+		if len(result) > 0:
+			mesg = "Node already allocated : %s" % (result)
+			self.log.info(mesg)
+			return -1
 
 		#  Check if reservation exists
-
-		query = "select reservation_id, user_id, reservation_date, \
-				reservation_expiration, notes  from reservationinfo \
-				where reservation_id = \"" + str(reservationId) + "\""
-		result = self.__selectDb(query)
-
-		if result.rowcount > 0:
-			res_results = result.fetchall()[0]
-			val = str(res_results)
-			res_id= res_results[0]
-			user_id = res_results[1]
-			res_notes = res_results[4]
-			if self.verbose:
-				mesg = "Reservation: " + val
-				logit(self.logFile, mesg)
-		else:
-			mesg = "ERROR: Reservation does not exist: " + reservationId + "\n"
-			logit(self.logFile, mesg)
-			exit()
-
-		
-		if not vlanIsolate:
-			vlan = self.getAvailableVlan()
+		result = self.__checkDup("reservationinfo", "reservation_id", reservationId)
+		if len(result) == 0:
+			mesg = "Reservation does not exist: " + reservationId + "\n"
+			self.log.error(mesg)
+			return -1
 		else:
-			vlan = vlanIsolate
-
-		#  Allocate nodes to the reservation
-		#  Reserve the node and assign to user
-		vlan_id = self.getVlanId(vlan)
-		if vlan != 999:
-			if not ip_addr:
-				ip_addr  = self.getDomainIp(vlan)
-			else:
-				# Check to see if IP is free
-				query = "select * from allocationinfo where ip_addr = \"" + str(ip_addr) + "\""
-				result = self.__selectDb(query)
-				if result.rowcount > 0:
-					mesg = "ERROR: IP Address specified (" + str(ip_addr) + ") already in use\n"
-					mesg += str(result.fetchone())
-					logit(self.logFile, mesg)
-					exit()
-		else:
-			ip_addr = self.getIpFromSysId(nodeId)	
-		#print "ip is ", ip_addr
-
-		#  If there is no hostname, set to default
-		if not hostName:
-			hostName = self.getLocationFromSysId(nodeId)
+			resinfo = result[0]
 
-		#print "hostname is ", hostName, "ip is ", ip_addr, "vlan is ", vlan_id
-
-		#  Assign IP address to node
-		dhcpdns = DhcpDns(self.config, verbose=1)
-		dnscheck = dhcpdns.addDhcp(hostName, ip_addr, self.getMacFromSysId(nodeId))
-		dhcpdns.addDns(hostName, ip_addr)
-
-
-		mesg = "Insert to Node allocation:"
-		query = "insert into allocationinfo (reservation_id, sys_id, ip_addr, hostname, vlan_id, notes) \
-				values (\"" + str(reservationId) + "\", \"" +  str(nodeId) + "\", \"" + \
-				str(ip_addr) + "\", \"" + str(hostName) + "\", \"" + str(vlan_id) + "\", \"" + \
-				str(notes) + "\")"
-		self.__insertDb(query)
-
-		#Archive
-		reservation_type = "allocation"
-		self.archiveAllocation(nodeId, ip_addr, hostName, vlan_id, user_id, reservation_type, res_notes, notes)
+		#  Check if domain exists
+		domainId = self.__getSomething("domain_id", "domaininfo", "domain_name", domain)
+		if len(self.__checkDup("domaininfo", "domain_id", domainId)) == 0:
+			mesg = "Domain does not exist: %s(%s)" % (domainId, domain)
+			self.log.error(mesg)
+			return -1
+		
+		#  Check that all the vlans exist
+		for i in vlanInfo.split(","):
+			v = i.split(":")[0]
+			if self.getVlanId(v) < 0:
+				return -1
+
+		#  Insert to allocationinfo
+		nodeName = self.getLocationFromSysId(sysId)
+		mesg = "allocateNode %s : domain %s : reservation %s(%s)" % (nodeName, domain, reservationId, resinfo[4])
+		self.log.info(mesg)
+		query = "insert into allocationinfo (sys_id, reservation_id, domain_id, notes) values ('%s', '%s', '%s', '%s')" % (sysId, reservationId, domainId, notes)
+		result = self.__insertDb(query)
+		allocationId = result.lastrowid
 
+		#  Parse vlan info and add to vlanmembermap
+		for i in vlanInfo.split(","):
+			print i
+			v = i.split(":")[0]
+			vId = self.getVlanId(v)
+			t = i.split(":")[1]
+			query = "insert into vlanmembermap (allocation_id, vlan_id, vlan_type) values ('%s', '%s', '%s')" % (allocationId, vId, t)
+			result = self.__insertDb(query)
+			mesg = "Adding vlan %s to node %s" % (v, nodeName)
+			self.log.info(mesg)
+
+		#  Insert into imagemap
+		image_id = self.__getSomething("image_id", "imageinfo", "image_name", imageName)
+		query = "insert into imagemap (allocation_id, image_id) values ('%s', '%s')" % (allocationId, image_id)
+		result = self.__insertDb(query)
 
 	def rgasstest(self, vlan_num):
 		query = "select * from vlaninfo where vlan_num = " + vlan_num
@@ -797,7 +910,7 @@ class ResourceQuerySql(InfoStore):
 			exit(1)
 		if result.rowcount > 1:
 			mesg = "WARNING:  Node allocated multiple times (" + str(result.rowcount) + ")"
-			logit(self.logFile, mesg)
+			self.log.warning(mesg)
 
 		val = result.fetchone()
 		nodeId = int(val[0])
@@ -837,11 +950,11 @@ class ResourceQuerySql(InfoStore):
 		
 		#  Eventually should add count =1 so deletes do get out of control
 		query = "delete from allocationinfo where reservation_id = " + str(resId) + " and sys_id = " + str(nodeId)
-		result = self.__selectDb(query)
+		result = self.__deleteDb(query)
 
 		#  Archive node release
-		reservation_type = "release"
-		self.archiveAllocation(nodeId, ip_addr, hostName, vlan_id, user_id, reservation_type, reservation_notes, allocation_notes)
+		#reservation_type = "release"
+		#self.archiveAllocation(nodeId, ip_addr, hostName, vlan_id, user_id, reservation_type, reservation_notes, allocation_notes)
 
 	def addImage(self, imageName):
 		name = ""
@@ -864,7 +977,7 @@ class ResourceQuerySql(InfoStore):
 		
 		if name == "":
 			mesg = "ERROR:  Image details not specified\n"
-			logit(self.logFile, mesg)
+			self.log.error(mesg)
 			mesg = "Example amd64-rgass-testing:Ubuntu:8.04\n"
 			mesg += "or amd64-rgass-testing::\n"
 			sys.stderr.write(mesg)
@@ -876,7 +989,7 @@ class ResourceQuerySql(InfoStore):
 
 	def delImage(self, imageName):
 		query = "delete from imageinfo where image_name = \"" + imageName + "\""
-		result = self.__selectDb(query)
+		result = self.__deleteDb(query)
 		if result.rowcount == 0:
 			mesg = "ERROR:  No images match your entry\n"
 			sys.stderr.write(mesg)
@@ -892,7 +1005,7 @@ class ResourceQuerySql(InfoStore):
 		row = self.__queryDb(query)
 		if len(row) < 1: 
 			mesg = "ERROR: Image \"" + image + "\" does not exist"
-			logit(self.logFile, mesg)
+			self.log.error(mesg)
 			exit()
 		new_image_id = str(row[0][0])
 
@@ -901,12 +1014,12 @@ class ResourceQuerySql(InfoStore):
 		result = self.__selectDb(query)
 		if result.rowcount > 0:
 			query = "delete from imagemap where mac_addr = \"" + host['mac_addr'] + "\""
-			result = self.__selectDb(query)
+			result = self.__deleteDb(query)
 			
 
 		#  update the database entry with the new image for the host
 		query = "insert into imagemap (mac_addr, image_id) values (\"" + host['mac_addr'] + "\", " + new_image_id + ")"
-		self.__selectDb(query)
+		self.__insertDb(query)
 		
 
 		#  Update tftp link
@@ -931,7 +1044,7 @@ class ResourceQuerySql(InfoStore):
 		try:
 			os.symlink(newlink, maclink)
 			mesg = "Image assignment Successful " +  host['location'] + " " + host['mac_addr'] + " " + image
-			logit(self.logFile, mesg)
+			self.log.info(mesg)
 		except Exception, e:
 			if OSError:
 				mesg = "Cannot modify file.  Please use sudo\n"
@@ -973,10 +1086,10 @@ class ResourceQuerySql(InfoStore):
 			try:
 				self.__insertDb(statement)
 				mesg = "Device (%s) registered successfully\n" % (data['hw_name'])
-				logit(self.logFile, mesg)
+				self.log.info(mesg)
 			except Exception, e:
 				mesg = "Registration failed to add Device (%s) - %s\n" % (data['hw_name'], e)
-				logit(self.logFile, mesg)
+				self.log.warning(mesg)
 		else:
 			mesg = "INFO:  Device (%s) already registered\n" % (data['hw_name'])
 			sys.stderr.write(mesg)

Modified: incubator/tashi/trunk/src/zoni/extra/util.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/extra/util.py?rev=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/extra/util.py (original)
+++ incubator/tashi/trunk/src/zoni/extra/util.py Thu Nov 11 19:56:30 2010
@@ -34,6 +34,10 @@ def loadConfigFile(parser):
 	#  Logging
 	config['logFile'] = parser.get("logging", "LOG_FILE").split()[0]
 	
+	#  Management
+	config['userManagement'] = parser.get("management", "USER_MANAGEMENT").split()[0]
+	config['infoStore'] = parser.get("management", "INFO_STORE").split()[0]
+	
 	#  DB connection
 	config['dbUser'] = parser.get("dbConnection", "DB_USER").split()[0]
 	config['dbPassword'] = config.get("dbPassword", "")
@@ -66,7 +70,7 @@ def loadConfigFile(parser):
 
 	#  VLAN
 	#config['vlan_reserved'] = parser.get("vlan", "VLAN_RESERVED")
-	config['vlan_max'] = parser.get("vlan", "VLAN_MAX")
+	config['vlan_max'] = int(parser.get("vlan", "VLAN_MAX"))
 
 	#  Domain
 	config['zoniHomeDomain'] = parser.get("domain", "ZONI_HOME_DOMAIN").split()[0]
@@ -78,6 +82,8 @@ def loadConfigFile(parser):
 	config['hardware_control'] = parser.get("hardware", "HARDWARE_CONTROL")
 
 	#  DHCP/DNS
+	config['dnsEnabled'] = parser.get("DhcpDns", "dnsEnabled")
+	config['reverseDns'] = parser.get("DhcpDns", "reverseDns")
 	#config['dnsKeyFile'] = parser.get("DhcpDns", "dnsKeyfile")
 	config['dnsKeyName'] = parser.get("DhcpDns", "dnsKeyName")
 	config['dnsSecretKey'] = parser.get("DhcpDns", "dnsSecretKey")
@@ -119,6 +125,7 @@ def logit(logfile, mesg):
 
 def checkSuper(f):
 	def myF(*args, **kw):
+		res = f(*args, **kw)
 		if os.getuid() != 0:
 			print "Please use sudo!"
 			exit()

Modified: incubator/tashi/trunk/src/zoni/hardware/dellswitch.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/dellswitch.py?rev=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/dellswitch.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/dellswitch.py Thu Nov 11 19:56:30 2010
@@ -30,9 +30,11 @@ import socket
 import tempfile
 import logging
 
-
+#import zoni
+from zoni.data.resourcequerysql import *
 from zoni.hardware.hwswitchinterface import HwSwitchInterface
 from zoni.data.resourcequerysql import ResourceQuerySql
+from zoni.agents.dhcpdns import DhcpDns
 
 
 '''  Using pexpect to control switches because couldn't get snmp to work 
@@ -472,6 +474,22 @@ class HwDellSwitch(HwSwitchInterface):
 		cmdgen.UdpTransportTarget((host, 161)), oid)
 		a['hw_make'] = str(varBinds[0][1])
 
-		return a
+		#  Register in dns
+		if self.config['dnsEnabled']:
+			try:
+				mesg = "Adding %s(%s) to dns" % (host, ip)
+				self.log.info(mesg)
+				DhcpDns(self.config, verbose=self.verbose).addDns(host, ip)
+				mesg = "Adding %s(%s) to dhcp" % (host, ip)
+				self.log.info(mesg)
+				DhcpDns(self.config, verbose=self.verbose).addDhcp(host, ip, a['hw_mac'])
+			except:
+				mesg = "Adding %s(%s) %s to dhcp/dns failed" % (host, ip, a['hw_mac'])
+				self.log.error(mesg)
+			
+		#  Add to db
+		#  Register to DB
+		query = ResourceQuerySql(self.config, self.verbose)
+		query.registerHardware(a)
 
 

Modified: incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py?rev=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py Thu Nov 11 19:56:30 2010
@@ -22,14 +22,14 @@ import sys
 import os 
 import string
 import warnings
+import logging
 import time
 warnings.filterwarnings("ignore")
 
 from pysnmp.entity.rfc3413.oneliner import cmdgen
 from pysnmp.proto import rfc1902
-
-
-from systemmanagementinterface import SystemManagementInterface
+from zoni.data.resourcequerysql import *
+from zoni.hardware.systemmanagementinterface import SystemManagementInterface
 
 
 #class systemmagement():
@@ -37,8 +37,12 @@ from systemmanagementinterface import Sy
 		#self.proto = proto
 
 class raritanDominionPx(SystemManagementInterface):
-	def __init__(self, host=None):
+	def __init__(self, config, host=None):
 		#  Register
+		self.config = config
+		self.log = logging.getLogger(__name__)
+		self.verbose = False
+
 		if host != None:
 			self.host = host['location']
 			self.pdu_name = host['pdu_name']
@@ -50,7 +54,6 @@ class raritanDominionPx(SystemManagement
 			self.oid_name = ",2"
 			self.oid_set = ",3"
 			self.oid_status = ",3"
-			self.verbose = False
 
 			if self.getOffset():
 				self.port = host['pdu_port'] - 1
@@ -177,6 +180,12 @@ class raritanDominionPx(SystemManagement
 		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
 		cmdgen.CommunityData('my-agent', user, 0), \
 		cmdgen.UdpTransportTarget((host, 161)), oid)
+
+		if len(varBinds) < 1:
+			mesg = "Incorrect authentication details"
+			self.log.error(mesg)
+			return -1
+
 		a['hw_make'] = str(varBinds[0][1])
 
 		oid = eval("1,3,6,1,4,1,13742,4,1,1,6,0")
@@ -218,5 +227,20 @@ class raritanDominionPx(SystemManagement
 		a['hw_userid'] = user
 		a['hw_password'] = password
 
-		return a
-
+		#  Register in dns
+		if self.config['dnsEnabled']:
+			try:
+				mesg = "Adding %s(%s) to dns" % (host, ip)
+				self.log.info(mesg)
+				DhcpDns(self.config, verbose=self.verbose).addDns(host, ip)
+				mesg = "Adding %s(%s) to dhcp" % (host, ip)
+				self.log.info(mesg)
+				DhcpDns(self.config, verbose=self.verbose).addDhcp(host, ip, a['hw_mac'])
+			except:
+				mesg = "Adding %s(%s) %s to dhcp/dns failed" % (host, ip, a['hw_mac'])
+				self.log.error(mesg)
+
+		#  Add to db
+		#  Register to DB
+		query = ResourceQuerySql(self.config, self.verbose)
+		query.registerHardware(a)

Modified: incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py?rev=1034085&r1=1034084&r2=1034085&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py (original)
+++ incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py Thu Nov 11 19:56:30 2010
@@ -82,10 +82,13 @@ def CreateZoniDb(config, adminUser, admi
 	createDatabase(conn, adminUser, adminPassword, db)
 	setPriviledges(conn, user, passwd, db)
 	conn.close()
-	conn = connectDb(host, port, adminUser, adminPassword, db)
+	#conn = connectDb(host, port, adminUser, adminPassword, db)
+	conn = connectDb(host, port, user, passwd, db)
 	createTables(conn)
 	createRegistration(conn, config)
 	addInitialConfig(conn, config)
+	conn.commit()
+	conn.close()
 	sys.stdout.write("Finished\n")
 
 def connectDb (host, port, user, passwd, db=None):
@@ -115,7 +118,7 @@ def createDatabase (conn, user, passwd, 
 
 def setPriviledges(conn, user, passwd, db):
 	sys.stdout.write("Setting user priviledges...")
-	cmd = "grant select, insert, update, delete on " + db + ".* to " + user + "@\'%\' identified by \'" + passwd + "\';"
+	cmd = "grant create, select, insert, update, delete on " + db + ".* to " + user + "@\'%\' identified by \'" + passwd + "\';"
 	execQuery(conn, cmd)
 	sys.stdout.write("Success\n")
 
@@ -126,61 +129,61 @@ def createTables(conn):
 	'''  Create Tables  '''
 	#  Create sysinfo 
 	sys.stdout.write("    Creating sysinfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `sysinfo` (`sys_id` int(8) NOT NULL auto_increment, `mac_addr` char(64) NOT NULL, `num_procs` int(10) unsigned default NULL, `num_cores` int(10) unsigned default NULL, `mem_sticks` int(10) unsigned default NULL, `mem_slots` int(10) unsigned default NULL, `mem_total` int(10) unsigned default NULL, `mem_limit` int(10) unsigned default NULL, `clock_speed` int(10) unsigned default NULL, `sys_vendor` text, `sys_model` text, `proc_vendor` char(64) default NULL, `proc_model` char(128) default NULL, `proc_cache` char(32) default NULL, `system_serial_number` char(128) default NULL, `chassis_serial_number` char(128) default NULL, `system_uuid` char(254) default NULL, `cpu_flags` text, `location` text, `bios_rev` char(32) default NULL, `ip_addr` varchar(64) NOT NULL, `init_checkin` timestamp NOT NULL default CURRENT_TIMESTAMP, `last_update` timestamp, PRIMARY KEY  (`sys_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `sysinfo` (`sys_id` int(11) unsigned NOT NULL auto_increment, `mac_addr` char(64) NOT NULL, `num_procs` int(10) unsigned default NULL, `num_cores` int(10) unsigned default NULL, `mem_sticks` int(10) unsigned default NULL, `mem_slots` int(10) unsigned default NULL, `mem_total` int(10) unsigned default NULL, `mem_limit` int(10) unsigned default NULL, `clock_speed` int(10) unsigned default NULL, `sys_vendor` text, `sys_model` text, `proc_vendor` char(64) default NULL, `proc_model` char(128) default NULL, `proc_cache` char(32) default NULL, `system_serial_number` char(128) default NULL, `chassis_serial_number` char(128) default NULL, `system_uuid` char(254) default NULL, `cpu_flags` text, `location` text, `bios_rev` char(32) default NULL, `ip_addr` varchar(64) NOT NULL, `init_checkin` timestamp NOT NULL default CURRENT_TIMESTAMP, `last_update` timestamp, state_id int(11) DEFAULT 1,max_reservation int(10) default -1, PRIMARY KEY  (`sys
 _id`))")
 	sys.stdout.write("Success\n")
 
 	#  Create hardwareinfo
 	sys.stdout.write("    Creating hardwareinfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `hardwareinfo` ( `hw_id` int(8) NOT NULL auto_increment, `hw_type` varchar(64) NOT NULL, `hw_mac` varchar(64) default NULL, `hw_name` varchar(256) NOT NULL, `hw_make` varchar(64), `hw_model` varchar(64), `hw_version_sw` varchar(64), `hw_version_fw` varchar(64), `hw_ipaddr` varchar(64) NOT NULL, `hw_userid` varchar(64) default NULL, `hw_password` varchar(64) default NULL, `hw_notes` longtext, PRIMARY KEY  (`hw_id`))") 
-	sys.stdout.write("Success\n")
- 	#  Create allocationinfo
-	sys.stdout.write("    Creating allocationinfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `allocationinfo` ( `allocation_id` int(8) NOT NULL auto_increment, `sys_id` int(8) NOT NULL, `reservation_id` int(8) NOT NULL, `ip_addr` varchar(64) NOT NULL, `hostname` varchar(64) default NULL, `domain_id` int(11) NOT NULL, `notes` tinytext, PRIMARY KEY  (`allocation_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `hardwareinfo` ( `hw_id` int(11) unsigned NOT NULL auto_increment, `hw_type` varchar(64) NOT NULL, `hw_mac` varchar(64) default NULL, `hw_name` varchar(256) NOT NULL, `hw_make` varchar(64), `hw_model` varchar(64), `hw_version_sw` varchar(64), `hw_version_fw` varchar(64), `hw_ipaddr` varchar(64) NOT NULL, `hw_userid` varchar(64) default NULL, `hw_password` varchar(64) default NULL, `hw_notes` longtext, PRIMARY KEY  (`hw_id`))") 
 	sys.stdout.write("Success\n")
 	#  Create imageinfo
 	sys.stdout.write("    Creating imageinfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `imageinfo` ( `image_id` int(11) unsigned NOT NULL auto_increment, `image_name` varchar(256) NOT NULL, `dist` varchar(128) NOT NULL, `dist_ver` varchar(128) NOT NULL, `kernel_id` int(11), `initrd_id` int(11), PRIMARY KEY  (`image_id`))")
-	sys.stdout.write("Success\n")
-	#  Create imagemap
-	sys.stdout.write("    Creating imagemap...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `imagemap` ( `mac_addr` char(64) NOT NULL, `image_id` int(11) NOT NULL, PRIMARY KEY  (`mac_addr`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `imageinfo` ( `image_id` int(11) unsigned NOT NULL auto_increment, `image_name` varchar(256) NOT NULL, `dist` varchar(128), `dist_ver` varchar(128), `kernel_id` int(11), `initrd_id` int(11), PRIMARY KEY  (`image_id`))")
 	sys.stdout.write("Success\n")
 	#  Create reservationinfo
 	sys.stdout.write("    Creating reservationinfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `reservationinfo` ( `reservation_id` int(8) NOT NULL auto_increment, `user_id` int(8) NOT NULL, `reservation_date` timestamp NOT NULL default CURRENT_TIMESTAMP, `reservation_expiration` datetime NOT NULL, `notes` tinytext, PRIMARY KEY  (`reservation_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `reservationinfo` ( `reservation_id` int(11) unsigned NOT NULL auto_increment, `user_id` int(11) NOT NULL, `reservation_date` timestamp NOT NULL default CURRENT_TIMESTAMP, `reservation_expiration` datetime NOT NULL, `notes` tinytext, PRIMARY KEY  (`reservation_id`)) ENGINE=INNODB")
 	sys.stdout.write("Success\n")
 	#  Create portmap 
 	sys.stdout.write("    Creating portmap...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `portmap` (`hw_id` int(8) NOT NULL, `sys_id` int(8) NOT NULL, `port_num` int(8))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `portmap` (`hw_id` int(11) unsigned NOT NULL, `sys_id` int(11) unsigned NOT NULL, `port_num` int(11))")
 	sys.stdout.write("Success\n")
 	#  Create vlan
 	sys.stdout.write("    Creating vlaninfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `vlaninfo` ( `vlan_id` int(11) NOT NULL auto_increment, `vlan_num` int(11) NOT NULL, `vlan_desc` varchar(256) NOT NULL, PRIMARY KEY  (`vlan_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `vlaninfo` ( `vlan_id` int(11) unsigned NOT NULL auto_increment, `vlan_num` int(11) NOT NULL, `vlan_desc` varchar(256) NOT NULL, PRIMARY KEY  (`vlan_id`))")
 	sys.stdout.write("Success\n")
 	#  Create domaininfo
 	sys.stdout.write("    Creating domaininfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `domaininfo` ( `domain_id` int(11) NOT NULL auto_increment, `domain_name` varchar(64) NOT NULL, `domain_desc` varchar(256) NOT NULL, PRIMARY KEY  (`domain_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `domaininfo` ( `domain_id` int(11) unsigned NOT NULL auto_increment, `domain_name` varchar(64) NOT NULL, `domain_desc` varchar(256) NOT NULL, `reservation_id` int(11) unsigned NOT NULL,  PRIMARY KEY  (`domain_id`), INDEX (reservation_id), FOREIGN KEY (reservation_id) REFERENCES reservationinfo(reservation_id) on DELETE CASCADE) ENGINE=INNODB")
 	sys.stdout.write("Success\n")
 	#  Create domainmap
 	sys.stdout.write("    Creating domainmembermap...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `domainmembermap` (`domain_id` int(11) NOT NULL, `vlan_id` int(11) NOT NULL)")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `domainmembermap` (`domain_id` int(11) unsigned NOT NULL, `vlan_id` int(11) unsigned NOT NULL, INDEX (domain_id), FOREIGN KEY (domain_id) REFERENCES domaininfo(domain_id) on DELETE CASCADE) ENGINE=INNODB")
 	sys.stdout.write("Success\n")
 	#  Create system, domain member map
 	sys.stdout.write("    Creating sysdomainmembermap...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `sysdomainmembermap` (`sys_id` int(11) NOT NULL, `domain_id` int(11) NOT NULL)")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `sysdomainmembermap` (`sys_id` int(11) unsigned NOT NULL, `domain_id` int(11) NOT NULL)")
+	sys.stdout.write("Success\n")
+ 	#  Create allocationinfo
+	sys.stdout.write("    Creating allocationinfo...")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `allocationinfo` ( `allocation_id` int(11) unsigned NOT NULL auto_increment, `sys_id` int(11) unsigned NOT NULL, `reservation_id` int(11) unsigned NOT NULL, `pool_id` int(11) unsigned NULL, `hostname` varchar(64) default NULL, `domain_id` int(11) unsigned NOT NULL, `notes` tinytext, PRIMARY KEY  (`allocation_id`), INDEX (domain_id), FOREIGN KEY (domain_id) REFERENCES domaininfo (domain_id) on DELETE CASCADE) ENGINE=INNODB")
+	sys.stdout.write("Success\n")
+	#  Create imagemap
+	sys.stdout.write("    Creating imagemap...")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `imagemap` ( `allocation_id` int(11) unsigned NOT NULL, `image_id` int(11) unsigned NOT NULL, INDEX(allocation_id), FOREIGN KEY (allocation_id) REFERENCES allocationinfo(allocation_id) on DELETE CASCADE)ENGINE=INNODB")
 	sys.stdout.write("Success\n")
 	#  Create poolinfo
 	sys.stdout.write("    Creating poolinfo...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `poolinfo` (`pool_id` int(11) NOT NULL auto_increment, `pool_name` varchar(64) NOT NULL, `pool_ip_network` varchar(64) NOT NULL, PRIMARY KEY (`pool_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `poolinfo` (`pool_id` int(11) unsigned NOT NULL auto_increment, `pool_name` varchar(64) NOT NULL, `pool_ip_network` varchar(64) NOT NULL, PRIMARY KEY (`pool_id`))")
 	sys.stdout.write("Success\n")
 	#  Create poolmap
 	sys.stdout.write("    Creating poolmap...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `poolmap` (`pool_id` int(11) NOT NULL, `vlan_id` int(11) NOT NULL)")
-	sys.stdout.write("Success\n")
-	#  Create allocationarchive
-	sys.stdout.write("    Creating allocationarchive...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `allocationarchive` ( `ar_id` smallint(8) NOT NULL auto_increment, `sys_id` int(8) NOT NULL, `ip_addr` varchar(64) NOT NULL, `hostname` varchar(64) NOT NULL, `domain_id` int(11) NOT NULL, `user_id` int(8) NOT NULL, `cur_time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, `reservation_type` varchar(64) NOT NULL, `notes` tinytext, PRIMARY KEY  (`ar_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `poolmap` (`pool_id` int(11) NOT NULL, `vlan_id` int(11) unsigned NOT NULL)")
 	sys.stdout.write("Success\n")
+	##  Create allocationarchive
+	#sys.stdout.write("    Creating allocationarchive...")
+	#execQuery(conn, "CREATE TABLE IF NOT EXISTS `allocationarchive` ( `ar_id` int(11) unsigned NOT NULL auto_increment, `sys_id` int(11) NOT NULL, `ip_addr` varchar(64) NOT NULL, `hostname` varchar(64) NOT NULL, `domain_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `cur_time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, `reservation_type` varchar(64) NOT NULL, `notes` tinytext, PRIMARY KEY  (`ar_id`))")
+	#sys.stdout.write("Success\n")
 	#  Create kernelinfo 
 	sys.stdout.write("    Creating kernelinfo...")
 	execQuery(conn, "CREATE TABLE IF NOT EXISTS `kernelinfo` ( `kernel_id` int(11) unsigned NOT NULL auto_increment, `kernel_name` varchar(256) NOT NULL, `kernel_release` varchar(128) NOT NULL, `kernel_arch` varchar(128) NOT NULL, PRIMARY KEY  (`kernel_id`))")
@@ -193,6 +196,14 @@ def createTables(conn):
 	sys.stdout.write("    Creating diskmap...")
 	execQuery(conn, "CREATE TABLE IF NOT EXISTS `diskmap` ( `disk_id` int(11) unsigned NOT NULL auto_increment, `sys_id` int(11) NOT NULL, `disk_name` varchar(128), `disk_size` varchar(256), PRIMARY KEY  (`disk_id`))")
 	sys.stdout.write("Success\n")
+	#  Create stateinfo
+	sys.stdout.write("    Creating stateinfo...")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `stateinfo` ( `state_id` int(11) unsigned NOT NULL auto_increment, `state_name` varchar(256) NOT NULL, `state_extra` varchar(256), PRIMARY KEY  (`state_id`))")
+	sys.stdout.write("Success\n")
+	#  Create vlanmembermap
+	sys.stdout.write("    Creating vlanmembermap...")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `vlanmembermap` (`vlanmember_id` int(11) unsigned NOT NULL auto_increment, `allocation_id` int(11) unsigned NOT NULL, `vlan_id` int(11) unsigned NOT NULL, vlan_type varchar(128) NOT NULL, PRIMARY KEY (`vlanmember_id`), INDEX(allocation_id), FOREIGN KEY (allocation_id) REFERENCES allocationinfo(allocation_id) on DELETE CASCADE) ENGINE=INNODB")
+	sys.stdout.write("Success\n")
 
 def createRegistration(conn, config):
 
@@ -237,6 +248,14 @@ def createRegistration(conn, config):
 		sys.stdout.write("Yes\n")    
 		initrdIdInteractive = str(checkVal[1][0][0])
 
+	#  Insert disk option
+	sys.stdout.write("    Adding Disk to imageinfo...")
+	query = "select * from imageinfo where image_name = 'disk'"
+	r = execQuery(conn, query)
+	if len(r.fetchall()) < 1:
+		execQuery(conn, "INSERT into `imageinfo` (image_name) values ('disk')")
+		sys.stdout.write("Success\n")
+
 	#  Link initrd and kernel to image
 	sys.stdout.write("    Registering initrd and kernel to registration image...")
 	query = "select * from imageinfo where image_name = 'zoni-register-64' and kernel_id = " + kernelId + " and initrd_id = " + initrdId
@@ -252,8 +271,20 @@ def createRegistration(conn, config):
 
 
 def addInitialConfig(conn, config):
-	#  Add the home vlan
 	sys.stdout.write("    Adding initial configuration info into DB...\n")
+	#  Create Initial reservation
+	sys.stdout.write("        Adding zoni reservation...")
+	checkVal =  entryExists(conn, "reservationinfo", "reservation_id", '1')
+	if checkVal:
+		sys.stdout.write("Reservation already exists in DB...\n")
+		#  Get the domainId 
+		vlanId = str(checkVal[1][0][0])
+	else:
+		r = execQuery(conn, "INSERT into `reservationinfo` (user_id, reservation_expiration, notes) values (0, '9999-12-31', 'Zoni Default Registration')")
+		vlanId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+
+	#  Add the home vlan
 	sys.stdout.write("        Adding vlan info...")
 	checkVal =  entryExists(conn, "vlaninfo", "vlan_num", config['zoniHomeDomain'])
 	if checkVal:
@@ -267,13 +298,13 @@ def addInitialConfig(conn, config):
 
 	#  Create the Zoni Home domain
 	sys.stdout.write("        Creating Zoni Home Domain...")
-	checkVal =  entryExists(conn, "domaininfo", "domain_name", "ZoniHome")
+	checkVal =  entryExists(conn, "domaininfo", "domain_name", "Zoni")
 	if checkVal:
 		sys.stdout.write("Default Domain (ZoniHome) already exists in DB...\n")
 		#  Get the domainId 
 		domainId = str(checkVal[1][0][0])
 	else:
-		r = execQuery(conn, "INSERT into `domaininfo` (domain_name, domain_desc) values (" + config['zoniHomeDomain'] + ", 'Zoni Home Domain' )")
+		r = execQuery(conn, "INSERT into `domaininfo` (domain_name, domain_desc, reservation_id) values ('Zoni', 'Zoni Home Domain',1)")
 		domainId = str(r.lastrowid)
 		sys.stdout.write("Success\n")
 
@@ -334,11 +365,24 @@ def addInitialConfig(conn, config):
 		domainId = str(r.lastrowid)
 		sys.stdout.write("Success\n")
 	
+	#  Add default states
+	sys.stdout.write("        Adding default states..")
+	checkVal =  entryExists(conn, "stateinfo", "state_name", 'normal')
+	if checkVal:
+		sys.stdout.write("Default state (default) already exists...\n")
+	else:
+		r = execQuery(conn, "INSERT into `stateinfo` (state_name) values ('normal')")
+		r = execQuery(conn, "INSERT into `stateinfo` (state_name) values ('off')")
+		r = execQuery(conn, "INSERT into `stateinfo` (state_name) values ('drained')")
+		r = execQuery(conn, "INSERT into `stateinfo` (state_name) values ('reserved')")
+		r = execQuery(conn, "INSERT into `stateinfo` (state_name) values ('restricted')")
+		sys.stdout.write("Success\n")
 
 def execQuery(conn, query):
 	cursor = conn.cursor()
 	try:
 		cursor.execute (query)
+		conn.commit()
 	#except Exception:
 		#traceback.print_exc(sys.exc_info())
 	except MySQLdb.OperationalError, e:



Mime
View raw message