You are viewing a plain text version of this content. The canonical link for it is here.
Posted to tashi-commits@incubator.apache.org by rg...@apache.org on 2010/10/28 20:37:52 UTC

svn commit: r1028463 [1/2] - in /incubator/tashi/trunk: etc/ src/zoni/client/ src/zoni/data/ src/zoni/hardware/ src/zoni/install/db/ src/zoni/install/www/ src/zoni/system/registration/register/ src/zoni/system/registration/www/ src/zoni/system/registra...

Author: rgass
Date: Thu Oct 28 20:37:52 2010
New Revision: 1028463

URL: http://svn.apache.org/viewvc?rev=1028463&view=rev
Log:
A bunch of changes adding support for configuring and setting up a node in Zoni.

Adding some install features to setup directories and files for the local apache server
Adding the registration php file that will add nodes to zoni
Adding a template for use with node automated additions to the cluster
Adding some helper php functions 
Modifications to the database layout
Adding registration helpers to the zoni-cli and implemented them for dell switches and raritan pdus
Updates to zoniDefaults




Added:
    incubator/tashi/trunk/src/zoni/hardware/dellswitch.py
      - copied, changed from r979310, incubator/tashi/trunk/src/zoni/hardware/hwswitch.py
    incubator/tashi/trunk/src/zoni/install/www/
    incubator/tashi/trunk/src/zoni/install/www/zoniWebSetup.py   (with props)
    incubator/tashi/trunk/src/zoni/system/registration/register/register_automate
    incubator/tashi/trunk/src/zoni/system/registration/www/include/
    incubator/tashi/trunk/src/zoni/system/registration/www/include/zoni_functions.php
    incubator/tashi/trunk/src/zoni/system/registration/www/zoni-register.php   (with props)
Removed:
    incubator/tashi/trunk/src/zoni/hardware/hwswitch.py
Modified:
    incubator/tashi/trunk/etc/ZoniDefaults.cfg
    incubator/tashi/trunk/src/zoni/client/zoni-cli.py
    incubator/tashi/trunk/src/zoni/data/resourcequerysql.py
    incubator/tashi/trunk/src/zoni/hardware/hwswitchinterface.py
    incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py
    incubator/tashi/trunk/src/zoni/hardware/systemmanagementinterface.py
    incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py
    incubator/tashi/trunk/src/zoni/system/registration/register/register_node

Modified: incubator/tashi/trunk/etc/ZoniDefaults.cfg
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/etc/ZoniDefaults.cfg?rev=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/etc/ZoniDefaults.cfg (original)
+++ incubator/tashi/trunk/etc/ZoniDefaults.cfg Thu Oct 28 20:37:52 2010
@@ -60,12 +60,16 @@ REGISTRATION_BASE_DIR = zoni #  Relative
 [snmp]
 SNMP_COMMUNITY = xx_snmp_community_name_xx
 
-#  Vlan Config
+#  Domain Config
+[domain]
+domainDescription = "/usr/local/tashi/etc/ZoniDomains.xml"
+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
+
 [vlan]
-VLAN_RESERVED = {10, {"name", internal}, 999,{"name", "tashi-vm"}, 1000, {"name", "management"}, 1001, {"name", "dmz"}}
 VLAN_MAX = 4095
 
-
 [hardware]
 HARDWARE_CONTROL = ["ipmi", "drac", "pdu"]
 HARDWARE_PDU = "raritan"
@@ -80,3 +84,10 @@ dnsExpire = 60
 dhcpServer = xx_dhcpserver_host_or_ip_xx
 dhcpKeyName = xx_dhcpservername_xx
 dhcpSecretKey = xx_secretkey_xx
+
+#  Domain Config
+[domain]
+domainDescription = "/usr/local/tashi/etc/ZoniDomains.xml"
+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

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=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/client/zoni-cli.py (original)
+++ incubator/tashi/trunk/src/zoni/client/zoni-cli.py Thu Oct 28 20:37:52 2010
@@ -23,6 +23,8 @@
 import os
 import sys
 import optparse
+import socket
+import getpass
 
 
 
@@ -40,9 +42,11 @@ from zoni.bootstrap.pxe import Pxe
 from zoni.hardware.systemmanagementinterface import SystemManagementInterface
 from zoni.hardware.ipmi import Ipmi
 from zoni.hardware.hwswitchinterface import HwSwitchInterface
-from zoni.hardware.hwswitch import HwDellSwitch
+from zoni.hardware.dellswitch import HwDellSwitch
 from zoni.hardware.raritanpdu import raritanDominionPx
 from zoni.hardware.delldrac import dellDrac
+from zoni.agents.dhcpdns import DhcpDns
+
 
 from zoni.extra.util import * 
 from zoni.version import *
@@ -114,8 +118,10 @@ def main():
 	group.add_option("--sendSwitchCommand", "--sendswitchcommand", dest="sendSwitchCommand", help="Send Raw Switch Command, VERY DANGEROUS.  config;interface switchport ethernet g14;etc")
 	group.add_option("--interactiveSwitchConfig", "--interactiveswitchconfig", dest="interactiveSwitchConfig", help="Interactively configure a switch.  switchhname")
 	group.add_option("--showSwitchConfig", "--showswitchconfig", dest="showSwitchConfig", help="Show switch config for node", action="store_true", default=False)
+	group.add_option("--register", dest="register", help="Register hardware to Zoni", action="store_true", default=False)
 	parser.add_option_group(group)
 
+
 	#  Switch
 	#group = optparse.OptionGroup(parser, "Switch Interface", "Switch Interface:")
 	#group.add_option("--rawswitch", dest="RAWSWITCH", help="Enter RAW Switch Admin mode", action="store_true", default=False)
@@ -148,6 +154,16 @@ def main():
 	group.add_option("--rgasstest", dest="rgasstest", help="Debug testing function", action="store_true", default=False)
 	parser.add_option_group(group)
 
+	#  Zoni Helpers
+	group = optparse.OptionGroup(parser, "Zoni Helpers", "Helper functions:")
+	group.add_option("--addDns", dest="addDns", help="Add a DNS entry", action="store_true", default=False)
+	group.add_option("--removeDns", dest="removeDns", help="Remove a DNS entry", action="store_true", default=False)
+	group.add_option("--addCname", dest="addCname", help="Add a DNS Cname entry", action="store_true", default=False)
+	group.add_option("--removeCname", dest="removeCname", help="Remove a DNS Cname entry", action="store_true", default=False)
+	group.add_option("--addDhcp", dest="addDhcp", help="Add a DHCP entry", action="store_true", default=False)
+	group.add_option("--removeDhcp", dest="removeDhcp", help="Remove a DHCP entry", action="store_true", default=False)
+	parser.add_option_group(group)
+
 	(options, args) = parser.parse_args()
 
 	cmdargs = {}
@@ -486,8 +502,153 @@ def main():
 			hwswitch.interactiveSwitchConfig()
 		if options.showSwitchConfig and (options.nodeName or options.switchPort):
 			hwswitch.showInterfaceConfig()
+		
+	#  Register hardware
+	if options.register: 
 
+		supported_hardware = ['dell', 'raritan']
+		if len(args) < 3:
+			mesg = "ERROR:  Expecting username and ip address of hardware to be registered\n"
+			mesg += os.path.basename(sys.argv[0]) + " --register HARDWARE username ipaddr\n"
+			mesg += "Supported hardware " + str(supported_hardware) + "\n"
+			sys.stderr.write(mesg)
+		else:
+			if string.lower(args[0]) == "dell":
+				HwSwitch = HwDellSwitch
+				hw = HwSwitch(configFile)
+			elif string.lower(args[0]) == "raritan":
+				hw = raritanDominionPx()
+			else:
+				mesg = "Undefined hardware type\nSupported Hardware" + str(supported_hardware) + "\n"
+				sys.stderr.write(mesg)
+				exit()
+				
+			if options.verbosity:
+				hw.setVerbose(True)
 
+			print args
+			password = getpass.getpass()
+			data = hw.registerToZoni(args[1], password, args[2])
+
+			#  Register to DB
+			query.registerHardware(data)
+			
+	#  Zoni Helper
+	if options.addDns or options.removeDns or options.addDhcp or options.removeDhcp or options.addCname or options.removeCname:
+		if options.addDns:
+			thisone = "--addDns"
+		if options.removeDns:
+			thisone = "--removeDns"
+		if options.removeDhcp:
+			thisone = "--removeDhcp"
+		if options.addDhcp:
+			thisone = "--addDhcp"
+		if options.addCname:
+			thisone = "--addCname"
+		if options.removeCname:
+			thisone = "--removeCname"
+
+		if options.addDns:
+			if len(args) < 2:
+				mesg = "ERROR:  Incorrect number of arguments\n"
+				mesg += "Example:  " + sys.argv[0] + " " + thisone + " hostname IP_Address\n"
+				print mesg
+				exit()
+			
+			hostName = args[0]
+			ip = args[1]
+			if validIp(ip):
+				mesg = "Adding DNS entry: %s (%s) " % (hostName, ip)
+				sys.stdout.write(mesg)
+				dhcpdns = DhcpDns(configFile, verbose=options.verbosity)
+				dhcpdns.addDns(hostName, ip)
+				try:
+					socket.gethostbyname(hostName)
+					sys.stdout.write("[Success]\n")
+				except Exception, e:
+					sys.stdout.write("[Fail]\n")
+			else:
+				mesg = "ERROR:  Malformed IP Address\n"
+				mesg += "Use the dotted quad notation, e.g. 10.0.0.10\n"
+				print mesg
+				exit()
+
+		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"
+				sys.stdout.write(mesg)
+				exit()
+			hostName = args[0]
+			dhcpdns = DhcpDns(configFile, verbose=options.verbosity)
+			if options.removeDns:	
+				mesg = "Removing DNS entry: %s " % (hostName)
+				sys.stdout.write(mesg)
+				dhcpdns.removeDns(hostName)
+				try:
+					socket.gethostbyname(hostName)
+					sys.stdout.write("[Fail]\n")
+				except Exception, e:
+					sys.stdout.write("[Success]\n")
+			if options.removeDhcp:	
+				dhcpdns.removeDhcp(hostName)
+			if options.removeCname:	
+				mesg = "Removing DNS CNAME entry: %s  " % (hostName)
+				sys.stdout.write(mesg)
+				dhcpdns.removeCname(hostName)
+				if dhcpdns.error:
+					mesg = "[FAIL]  " + str(dhcpdns.error) + "\n"
+					sys.stdout.write(mesg)
+				else:
+					mesg = "[SUCCESS]" + "\n"
+					sys.stdout.write(mesg)
+					
+
+		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"
+				print mesg
+				exit()
+			
+			hostName = args[0]
+			ip = args[1]
+			mac = args[2]
+			if validIp(ip) and validMac(mac):
+				dhcpdns = DhcpDns(configFile, verbose=options.verbosity)
+				dhcpdns.addDhcp(hostName, ip, mac)
+				if dhcpdns.error:
+					mesg = "ERROR:  Add DHCP Error " + dhcpdns.error + "\n"
+			else:
+				if not validIp(ip):
+					mesg = "ERROR:  Malformed IP Address\n"
+					mesg += "Use the dotted quad notation, e.g. 10.0.0.10\n"
+					print mesg
+					exit()
+				if not validMac(mac):
+					mesg = "ERROR:  Malformed MAC Address\n"
+					mesg += "Example 10:20:30:40:50:60\n"
+					print mesg
+					exit()
+		
+		if options.addCname:
+			if len(args) < 2:
+				mesg = "ERROR:  Incorrect number of arguments\n"
+				mesg += "Example:  " + 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.addCname(cname, hostName)
+			if dhcpdns.error: 
+				mesg = "[FAIL]  \n" + str(dhcpdns.error) + "\n" 
+				sys.stdout.write(mesg) 
+			else: 
+				mesg = "[SUCCESS]" + "\n" 
+				sys.stdout.write(mesg) 
 
 if __name__ == "__main__":
 	main()

Modified: incubator/tashi/trunk/src/zoni/data/resourcequerysql.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/data/resourcequerysql.py?rev=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/data/resourcequerysql.py (original)
+++ incubator/tashi/trunk/src/zoni/data/resourcequerysql.py Thu Oct 28 20:37:52 2010
@@ -52,7 +52,7 @@ class ResourceQuerySql(InfoStore):
 		self.port = config['dbPort']
 
 		self.vlan_max = config['vlan_max']
-		self.vlan_reserved = config['vlan_reserved']
+		#self.vlan_reserved = config['vlan_reserved']
 		
 		#  Connect to DB
 		try:
@@ -65,6 +65,15 @@ class ResourceQuerySql(InfoStore):
 				print "ERROR : ", e
 				exit(1)
 
+	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);
+		return result.fetchall()
+
 	def __create_queryopts(self, cmdargs, extra=None):
 		cmdlen = len(cmdargs)
 		queryopt = ""
@@ -89,7 +98,7 @@ class ResourceQuerySql(InfoStore):
 					queryopt += k + " = " + v + " "
 				if k == "cpu_flags":
 					queryopt += k + " like \"%" + v + "%\" "
-				if k == "node_id":
+				if k == "sys_id":
 					queryopt += " location = " + "\'" + v + "\' "
 
 				if num > 1:
@@ -160,7 +169,7 @@ class ResourceQuerySql(InfoStore):
 			switchList.append(switch[0])
 
 		#  Use static list until we get all switches installed
-		switchList =  ['sw1-r1r2', 'sw0-r1r1', 'sw0-r1r2', 'sw0-r1r3', 'sw0-r1r4', 'sw0-r2r3', 'sw0-r3r3', 'sw0-r3r2', 'sw0-r2r1c3', 'sw2-r1r2']
+		#switchList =  ['sw1-r1r2', 'sw0-r1r1', 'sw0-r1r2', 'sw0-r1r3', 'sw0-r1r4', 'sw0-r2r3', 'sw0-r3r3', 'sw0-r3r2', 'sw0-r2r1c3', 'sw2-r1r2']
 		#switchList =  ['sw2-r1r2']
 		#switchList =  ['sw1-r1r2']
 
@@ -262,7 +271,7 @@ class ResourceQuerySql(InfoStore):
 				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.node_id  and \
+				s.sys_id = a.sys_id  and \
 				v.vlan_id = a.vlan_id and \
 				r.reservation_id = a.reservation_id "
 		if userId:
@@ -416,11 +425,11 @@ class ResourceQuerySql(InfoStore):
 
 	def getHostInfo(self, node):
 		host = {}
-		query = "select * from sysinfo where location = \"" + node + "\"" 
+		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 "Mulitple entries for system exist.  Please correct"
+			print "Multiple entries for system exist.  Please correct"
 			exit()
 		if result.rowcount < 1:
 			mesg = "node does not exist :" + str(node) + "\n"
@@ -429,37 +438,37 @@ class ResourceQuerySql(InfoStore):
 		
 		for i in result.fetchall():
 			host['mac_addr'] = host.get("mac_addr", "")
-			host['node_id'] = int(i[0])
+			host['sys_id'] = int(i[0])
 			host['mac_addr'] = i[1]
 			host['num_procs'] = int(i[2])
 			host['num_cores'] = int(i[3])
-			host['mem_total'] = int(i[6])
-			host['clock_speed'] = int(i[8])
-			host['sys_vendor'] = i[9]
-			host['sys_model'] = i[10]
-			host['proc_vendor'] = i[11]
-			host['proc_model'] = i[12]
-			host['proc_cache'] = i[13]
-			host['cpu_flags'] = i[15]
-			host['bios_rev'] = i[17]
-			host['location'] = i[16]
-			host['dell_tag'] = host.get("dell_tag", "")
-			host['dell_tag'] = i[14]
+			host['mem_total'] = int(i[4])
+			host['clock_speed'] = int(i[5])
+			host['sys_vendor'] = i[6]
+			host['sys_model'] = i[7]
+			host['proc_vendor'] = i[8]
+			host['proc_model'] = i[9]
+			host['proc_cache'] = i[10]
+			host['cpu_flags'] = i[11]
+			host['bios_rev'] = i[12]
+			host['location'] = i[13]
+			host['system_serial_number'] = i[14]
+			host['ip_addr'] = i[14]
 		'''
 		for k, v in host.iteritems():
 			print k, v, "\n"
 		'''
 		
 		#  Get IPMI info
-		query = "select * from ipmiinfo where node_id = " + str(host['node_id']) + "" 
+		query = "select h.hw_userid, h.hw_password, h.hw_ipaddr from hardwareinfo h, portmap p, sysinfo s where p.sys_id = s.sys_id and h.hw_id = p.hw_id and h.hw_type = 'ipmi' and s.sys_id = " + str(host['sys_id']) + "" 
 		result = self.__selectDb(query)
 		if result.rowcount> 1:
-			print "Mulitple entries for system exist.  Please correct"
+			print "Multiple entries for system exist.  Please correct"
 			exit()
 		for i in result.fetchall():
-			host['ipmi_user'] = i[2]
-			host['ipmi_password'] = i[3]
-			host['ipmi_addr'] = i[1]
+			host['ipmi_user'] = i[0]
+			host['ipmi_password'] = i[1]
+			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'] + "\"" 
@@ -471,7 +480,7 @@ class ResourceQuerySql(InfoStore):
 				host['pxe_image_name'] = i[0]
 
 		#  Get switch info
-		query = "select h.hw_id, h.hw_name, h.hw_model, h.hw_ipaddr, h.hw_userid, h.hw_password, p.port_num from hardwareinfo h, portmap p where p.hw_id = h.hw_id and hw_type = 'switch' and node_id = " +  str(host['node_id'])
+		query = "select h.hw_id, h.hw_name, h.hw_model, h.hw_ipaddr, h.hw_userid, h.hw_password, p.port_num from hardwareinfo h, portmap p where p.hw_id = h.hw_id and hw_type = 'switch' and sys_id = " +  str(host['sys_id'])
 		result = self.__selectDb(query)
 		for i in result.fetchall():
 			host['hw_id'] = int(i[0])
@@ -483,7 +492,7 @@ class ResourceQuerySql(InfoStore):
 			host['hw_port'] = int(i[6])
 
 		#  Get drac info
-		query = "select h.hw_id, h.hw_name, h.hw_model, h.hw_ipaddr, h.hw_userid, h.hw_password, p.port_num from hardwareinfo h, portmap p where p.hw_id = h.hw_id and hw_type = 'drac' and node_id = " +  str(host['node_id'])
+		query = "select h.hw_id, h.hw_name, h.hw_model, h.hw_ipaddr, h.hw_userid, h.hw_password, p.port_num from hardwareinfo h, portmap p where p.hw_id = h.hw_id and hw_type = 'drac' and sys_id = " +  str(host['sys_id'])
 		result = self.__selectDb(query)
 		if result.rowcount > 0:
 			for i in result.fetchall():
@@ -496,7 +505,7 @@ class ResourceQuerySql(InfoStore):
 				host['drac_port'] = int(i[6])
 
 		#  Get PDU info
-		query = "select h.hw_id, h.hw_name, h.hw_model, h.hw_ipaddr, h.hw_userid, h.hw_password, p.port_num from hardwareinfo h, portmap p where p.hw_id = h.hw_id and hw_type = 'pdu' and node_id = " +  str(host['node_id'])
+		query = "select h.hw_id, h.hw_name, h.hw_model, h.hw_ipaddr, h.hw_userid, h.hw_password, p.port_num from hardwareinfo h, portmap p where p.hw_id = h.hw_id and h.hw_type = 'pdu' and p.sys_id = " +  str(host['sys_id'])
 		result = self.__selectDb(query)
 		for i in result.fetchall():
 			host['pdu_id'] = int(i[0])
@@ -670,7 +679,7 @@ class ResourceQuerySql(InfoStore):
 	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 (node_id, ip_addr, hostname, vlan_id, user_id, reservation_type, notes) \
+		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) + "\", \"" + \
@@ -684,7 +693,7 @@ class ResourceQuerySql(InfoStore):
 		#print "nodeId", nodeId, self.getMacFromSysId(nodeId)
 
 		#  Check if node is already allocated
-		query = "select * from allocationinfo where node_id = \"" + str(nodeId) + "\""
+		query = "select * from allocationinfo where sys_id = \"" + str(nodeId) + "\""
 		result = self.__selectDb(query)
 		if result.rowcount > 0:
 			val = str(result.fetchone())
@@ -752,7 +761,7 @@ class ResourceQuerySql(InfoStore):
 
 
 		mesg = "Insert to Node allocation:"
-		query = "insert into allocationinfo (reservation_id, node_id, ip_addr, hostname, vlan_id, notes) \
+		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) + "\")"
@@ -779,7 +788,7 @@ class ResourceQuerySql(InfoStore):
 	@checkSuper
 	def releaseNode(self, nodeName):
 		#  Get the nodeId
-		query = "select node_id, r.reservation_id, a.ip_addr, hostname, vlan_id, a.notes, r.notes,r.user_id from allocationinfo a, sysinfo s, reservationinfo r where a.node_id = s.sys_id and a.reservation_id = r.reservation_id and location = \"" + nodeName + "\""
+		query = "select sys_id, r.reservation_id, a.ip_addr, hostname, vlan_id, a.notes, r.notes,r.user_id from allocationinfo a, sysinfo s, reservationinfo r where a.sys_id = s.sys_id and a.reservation_id = r.reservation_id and location = \"" + nodeName + "\""
 		print query
 		result = self.__selectDb(query)
 		if result.rowcount == 0:
@@ -807,7 +816,7 @@ class ResourceQuerySql(InfoStore):
 		dhcpdns.removeDhcp(hostName)
 
 		'''
-		query = "select reservation_id, notes from reservationinfo where node_id = " + str(nodeId)
+		query = "select reservation_id, notes from reservationinfo where sys_id = " + str(nodeId)
 		result = self.__selectDb(query)
 		for i in result:
 			print i
@@ -817,7 +826,7 @@ class ResourceQuerySql(InfoStore):
 			logit(self.logFile, mesg)
 			exit(1)
 		if result.rowcount > 1:
-			mesg = "WARNING:  Muliple reservations exist (" + str(result.rowcount) + ")"
+			mesg = "WARNING:  Multiple reservations exist (" + str(result.rowcount) + ")"
 			logit(self.logFile, mesg)
 		
 		resId = int(result.fetchone()[0])
@@ -827,7 +836,7 @@ 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 node_id = " + str(nodeId)
+		query = "delete from allocationinfo where reservation_id = " + str(resId) + " and sys_id = " + str(nodeId)
 		result = self.__selectDb(query)
 
 		#  Archive node release
@@ -933,3 +942,41 @@ class ResourceQuerySql(InfoStore):
 
 		return 0
 
+	
+	def registerHardware(self, data):
+
+		if len(self.__checkDup("hardwareinfo", "hw_name", data['hw_name'])) == 0:
+			statement = "insert into hardwareinfo (" 
+			fields = []
+			entries = []
+			for key, value in data.iteritems(): 
+				fields.append(key)
+				entries.append(value)
+			c = len(fields)
+			count = 1
+			for i in fields:
+				if c != count:
+					statement += i + ","
+				else:
+					statement += i + ")"
+				count += 1
+
+			statement += "values ("
+			c = len(entries)
+			count = 1
+			for i in entries:
+				if c != count:
+					statement += "'" + i + "', "
+				else:
+					statement += "'" + i + "') "
+				count += 1
+			try:
+				self.__insertDb(statement)
+				mesg = "Device (%s) registered successfully\n" % (data['hw_name'])
+				logit(self.logFile, mesg)
+			except Exception, e:
+				mesg = "Registration failed to add Device (%s) - %s\n" % (data['hw_name'], e)
+				logit(self.logFile, mesg)
+		else:
+			mesg = "INFO:  Device (%s) already registered\n" % (data['hw_name'])
+			sys.stderr.write(mesg)

Copied: incubator/tashi/trunk/src/zoni/hardware/dellswitch.py (from r979310, incubator/tashi/trunk/src/zoni/hardware/hwswitch.py)
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/dellswitch.py?p2=incubator/tashi/trunk/src/zoni/hardware/dellswitch.py&p1=incubator/tashi/trunk/src/zoni/hardware/hwswitch.py&r1=979310&r2=1028463&rev=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/hwswitch.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/dellswitch.py Thu Oct 28 20:37:52 2010
@@ -22,7 +22,12 @@ import os
 import sys
 import pexpect
 import datetime
+import time
 import thread
+import string
+import getpass
+import socket
+import tempfile
 
 
 from zoni.hardware.hwswitchinterface import HwSwitchInterface
@@ -47,31 +52,40 @@ class HwDellSwitch(HwSwitchInterface):
 		
 		switchIp = "ssh " +  self.host['hw_userid'] + "@" + self.host['hw_name']
 		child = pexpect.spawn(switchIp)
-		opt = child.expect(['Name:', 'password:', pexpect.EOF, pexpect.TIMEOUT])
-		print "opt is ", opt
-		#XXX  Doesn't seem to do what I want:(
-		child.setecho(False)
-		if opt == 0:
-			child.sendline(self.host['hw_userid'])
-		#i=child.expect(['test','password:','Password:', pexpect.EOF, pexpect.TIMEOUT])
 
 		#  Be Verbose and print everything
 		if self.verbose:
 			child.logfile = sys.stdout
 
-		child.sendline(self.host['hw_password'])
-		i=child.expect(['console','sw', 'Name:', pexpect.EOF, pexpect.TIMEOUT])
-		if i == 2:
-			mesg = "ERROR:  Login failed\n"
-			logit(self.logFile, mesg)
+		opt = child.expect(['Name:', 'assword:', 'Are you sure.*', pexpect.EOF, pexpect.TIMEOUT])
+		#XXX  Doesn't seem to do what I want:(
+		child.setecho(False)
+
+		#  Send a yes to register authenticity of host for ssh
+		if opt == 2:
+			child.sendline("yes")
+			opt = child.expect(['Name:', 'assword:', 'Are you sure.*', pexpect.EOF, pexpect.TIMEOUT])
+			
+		if opt == 0:
+			child.sendline(self.host['hw_userid'])
+			i = child.expect(['assword:', 'Connection',  pexpect.EOF, pexpect.TIMEOUT])
+			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)
+				exit(1)
 
-			sys.stderr.write()
-			exit(1)
-		#  on the 6448 dell, need to send enable
 		if opt == 1:
+			#  the 6448 doesn't prompt for username
+			child.sendline(self.host['hw_password'])
+			i=child.expect(['console','>', 'Name:', pexpect.EOF, pexpect.TIMEOUT])
+			#  on the 6448 dell, need to send enable, just send to all
 			child.sendline('enable')
 			i=child.expect(['#', pexpect.EOF, pexpect.TIMEOUT])
-		
+
+
 		return child
 
 	def __getPrsLabel(self):
@@ -198,8 +212,8 @@ class HwDellSwitch(HwSwitchInterface):
 		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)
+				i=child.expect(['console','#', 'Name:', pexpect.EOF, pexpect.TIMEOUT], timeout=2)
+				i=child.expect(['console','#', 'Name:', pexpect.EOF, pexpect.TIMEOUT], timeout=2)
 				
 			except EOF:
 				print "EOF", i
@@ -341,8 +355,7 @@ class HwDellSwitch(HwSwitchInterface):
 		child.logfile = sys.stdout
 		cmd = "show interface switchport ethernet g" + str(self.host['hw_port'])
 		child.sendline(cmd)
-		i = child.expect(['sw(.*)', pexpect.EOF, pexpect.TIMEOUT])
-		i = child.expect(['sw(.*)', pexpect.EOF, pexpect.TIMEOUT])
+		i = child.expect(['#', pexpect.EOF, pexpect.TIMEOUT])
 		child.terminate()
 
 	def interactiveSwitchConfig(self):
@@ -355,5 +368,109 @@ class HwDellSwitch(HwSwitchInterface):
 		#child.logfile = sys.stdout
 		child.sendline(self.host['hw_password'])
 		child.interact(escape_character='\x1d', input_filter=None, output_filter=None)
+	
+	def registerToZoni(self, user, password, host):
+		host = string.strip(str(host))
+		#  Get hostname of the switch
+		if len(host.split(".")) == 4:
+			ip = host
+			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)
+		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 = "Unable to resolve hostname"
+				logit(self.logFile,mesg)
+				exit()
+
+		switchIp = "ssh " + user + "@" + ip
+		child = pexpect.spawn(switchIp)
+		opt = child.expect(['Name:', 'assword:', 'Are you sure.*', pexpect.EOF, pexpect.TIMEOUT])
+		#XXX  Doesn't seem to do what I want:(
+		child.setecho(False)
+
+		#  Send a yes to register authenticity of host for ssh
+		if opt == 2:
+			child.sendline("yes")
+			opt = child.expect(['Name:', 'assword:', 'Are you sure.*', pexpect.EOF, pexpect.TIMEOUT])
+			
+		if opt == 0:
+			child.sendline(user)
+			i = child.expect(['assword:', 'Connection',  pexpect.EOF, pexpect.TIMEOUT])
+			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)
+				exit(1)
+
+		if opt == 1:
+			child.sendline(password)
+			i=child.expect(['console',host, 'Name:', pexpect.EOF, pexpect.TIMEOUT])
+			#  on the 6448 dell, need to send enable, just send to all
+			child.sendline('enable')
+			i=child.expect(['#', pexpect.EOF, pexpect.TIMEOUT])
+
+		fout = tempfile.TemporaryFile()
+		child.logfile = fout
+
+		cmd = "show system"
+		child.sendline(cmd)
+		val = host + "#"
+		i = child.expect([val, '\n\r\n\r', pexpect.EOF, pexpect.TIMEOUT])
+		cmd = "show version"
+		child.sendline(cmd)
+		i = child.expect([val, '\n\r\n\r', pexpect.EOF, pexpect.TIMEOUT])
+
+		fout.seek(0)
+		a={}
+		for i in fout.readlines():
+			if "System Location:" in i:
+				datime = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())
+				val = "Registered by Zoni on : " + datime
+				a['hw_notes'] = val + "; " + string.strip(i.split(':', 1)[1])
+			if "System MAC" in i:
+				a['hw_mac'] = string.strip(i.split(':', 1)[1])
+			if "SW version" in i:
+				a['hw_version_sw'] = string.strip(i.split('   ')[1].split()[0])
+			if "HW version" in i:
+				a['hw_version_fw'] = string.strip(i.split('   ')[1].split()[0])
+				
+		a['hw_type'] = "switch"
+		a['hw_make'] = "dell"
+		a['hw_name'] = host
+		a['hw_ipaddr'] = ip
+		a['hw_userid'] = user
+		a['hw_password'] = password
+		child.sendline('exit')
+		child.sendline('exit')
+		child.terminate()
+
+		#  Try to get more info via snmp
+		from pysnmp.entity.rfc3413.oneliner import cmdgen
+		from pysnmp.proto import rfc1902
+
+		user = "public"
+		oid = eval("1,3,6,1,4,1,674,10895,3000,1,2,100,1,0")
+		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
+		cmdgen.CommunityData('my-agent', user, 0), \
+		cmdgen.UdpTransportTarget((host, 161)), oid)
+		a['hw_model'] = str(varBinds[0][1])
+		oid = eval("1,3,6,1,4,1,674,10895,3000,1,2,100,3,0")
+		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
+		cmdgen.CommunityData('my-agent', user, 0), \
+		cmdgen.UdpTransportTarget((host, 161)), oid)
+		a['hw_make'] = str(varBinds[0][1])
+
+		return a
 
 

Modified: incubator/tashi/trunk/src/zoni/hardware/hwswitchinterface.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/hwswitchinterface.py?rev=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/hwswitchinterface.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/hwswitchinterface.py Thu Oct 28 20:37:52 2010
@@ -63,3 +63,6 @@ class HwSwitchInterface(object):
 	def isolateNetwork(self):
 		raise NotImplementedError
 
+	def registerToZoni(self):
+		raise NotImplementedError
+

Modified: incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py?rev=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/raritanpdu.py Thu Oct 28 20:37:52 2010
@@ -13,22 +13,22 @@
 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
-# under the License.    
+# under the License.	
 #
 #  $Id$
 #
 
 import sys
 import os 
+import string
 import warnings
+import time
 warnings.filterwarnings("ignore")
 
 from pysnmp.entity.rfc3413.oneliner import cmdgen
 from pysnmp.proto import rfc1902
 
 
-#import netsnmp
-
 from systemmanagementinterface import SystemManagementInterface
 
 
@@ -37,19 +37,24 @@ from systemmanagementinterface import Sy
 		#self.proto = proto
 
 class raritanDominionPx(SystemManagementInterface):
-	def __init__(self, host):
-		self.host = host['location']
-		self.pdu_name = host['pdu_name']
-		self.port = host['pdu_port']
-		self.user = host['pdu_userid']
-		self.password = host['pdu_password']
-		self.oid = "1,3,6,1,4,1,13742,4,1,2,2,1"
-		self.oid_name = ",2"
-		self.oid_set = ",3"
-		self.oid_status = ",3"
+	def __init__(self, host=None):
+		#  Register
+		if host != None:
+			self.host = host['location']
+			self.pdu_name = host['pdu_name']
+			self.port = host['pdu_port']
+			self.user = host['pdu_userid']
+			self.password = host['pdu_password']
+
+			self.oid = "1,3,6,1,4,1,13742,4,1,2,2,1"
+			self.oid_name = ",2"
+			self.oid_set = ",3"
+			self.oid_status = ",3"
+			self.verbose = False
+
+			if self.getOffset():
+				self.port = host['pdu_port'] - 1
 
-		if self.getOffset():
-			self.port = host['pdu_port'] - 1
 
 		#  this works
 		#errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(cmdgen.CommunityData('my-agent', 'public', 0), cmdgen.UdpTransportTarget(('pdu0-r1r1', 161)), (1,3,6,1,4,1,13742,4,1,2,2,1,3,2))
@@ -71,6 +76,8 @@ class raritanDominionPx(SystemManagement
 		#self.powerStatus = None
 		#print self.__dict__
 
+	def setVerbose(self, verbose):
+		self.verbose = verbose
 	''' 
 	Just discovered that some PDUs start numbering ports in the SNMP mib
 	with 0.  Adding a check to update the port number to match the labels on the
@@ -140,3 +147,76 @@ class raritanDominionPx(SystemManagement
 		
 	def powerReset(self):
 		self.powerCycle()
+
+	def registerToZoni(self, user, password, host):
+		import socket
+
+		host = string.strip(str(host))
+		#  Get hostname of the switch
+		if len(host.split(".")) == 4:
+			ip = host
+			try:
+				host = string.strip(socket.gethostbyaddr(ip)[0].split(".")[0])
+			except Exception, e:
+				mesg = "WARNING:  Host (" + host + ") not registered in DNS " + str(e) + "\n"
+				sys.stderr.write(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) + "\n"
+				sys.stderr.write(mesg)
+				mesg = "Unable to resolve hostname" + "\n"
+				sys.stderr.write(mesg)
+				exit()
+
+
+		a={}
+		oid = eval(str("1,3,6,1,2,1,1,1,0"))
+		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
+		cmdgen.CommunityData('my-agent', user, 0), \
+		cmdgen.UdpTransportTarget((host, 161)), oid)
+		a['hw_make'] = str(varBinds[0][1])
+
+		oid = eval("1,3,6,1,4,1,13742,4,1,1,6,0")
+		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
+		cmdgen.CommunityData('my-agent', user, 0), \
+		cmdgen.UdpTransportTarget((host, 161)), oid)
+		x = []
+		for d in ['%x' % ord(i) for i in varBinds[0][1]]:
+			if len(d) == 1:
+				d = "0" + str(d)
+			x.append(d)
+		a['hw_mac'] = ":".join(['%s' % d for d in x])
+
+		oid = eval("1,3,6,1,4,1,13742,4,1,1,2,0")
+		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
+		cmdgen.CommunityData('my-agent', user, 0), \
+		cmdgen.UdpTransportTarget((host, 161)), oid)
+		serial = str(varBinds[0][1])
+
+		datime = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())
+		val = "Registered by Zoni on : " + datime
+		a['hw_notes'] = val + "; Serial " + serial
+
+		oid = eval("1,3,6,1,4,1,13742,4,1,1,1,0")
+		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
+		cmdgen.CommunityData('my-agent', user, 0), \
+		cmdgen.UdpTransportTarget((host, 161)), oid)
+		a['hw_version_fw'] = str(varBinds[0][1])
+
+		oid = eval("1,3,6,1,4,1,13742,4,1,1,12,0")
+		errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \
+		cmdgen.CommunityData('my-agent', user, 0), \
+		cmdgen.UdpTransportTarget((host, 161)), oid)
+		a['hw_model'] = str(varBinds[0][1])
+
+		a['hw_type'] = "pdu"
+		a['hw_name'] = host
+		a['hw_ipaddr'] = ip
+		a['hw_userid'] = user
+		a['hw_password'] = password
+
+		return a
+

Modified: incubator/tashi/trunk/src/zoni/hardware/systemmanagementinterface.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/hardware/systemmanagementinterface.py?rev=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/hardware/systemmanagementinterface.py (original)
+++ incubator/tashi/trunk/src/zoni/hardware/systemmanagementinterface.py Thu Oct 28 20:37:52 2010
@@ -58,6 +58,10 @@ class SystemManagementInterface(object):
 		'''  Activate Console'''
 		raise NotImplementedError
 
+	def registerToZoni(self):
+		'''  register hardware to zoni'''
+		raise NotImplementedError
+
 
 
 

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=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py (original)
+++ incubator/tashi/trunk/src/zoni/install/db/zoniDbSetup.py Thu Oct 28 20:37:52 2010
@@ -24,6 +24,14 @@ import string
 import MySQLdb
 import traceback
 import optparse
+import getpass
+
+a = os.path.join("../")
+sys.path.append(a)
+a = os.path.join("../../")
+sys.path.append(a)
+a = os.path.join("../../..")
+sys.path.append(a)
 
 from zoni.extra.util import *
 from zoni.version import *
@@ -35,20 +43,23 @@ def main():
 	rev = revision
 
 
-	parser = optparse.OptionParser(usage="%prog -u username -p password  ", version="%prog " + ver + " " + rev)
+	parser = optparse.OptionParser(usage="%prog -u username ", version="%prog " + ver + " " + rev)
 	parser.add_option("-u", "--userName", "--username", dest="userName", help="Mysql username")
 	parser.add_option("-p", "--password", dest="password", help="Admin mysql password")
 	#parser.add_option("-v", "--verbose", dest="verbosity", help="Be verbose", action="store_true", default=False)
 	(options, args) = parser.parse_args()
 
-	if not options.userName or not options.password:
+	if not options.userName:
 		parser.print_help()
 		exit(1)
 
+	password = options.password
+	if not options.password:
+		password = getpass.getpass()
 
 	configFile = getConfig()
 
-	CreateZoniDb(configFile, options.userName, options.password)
+	CreateZoniDb(configFile, options.userName, password)
 
 
 def CreateZoniDb(config, adminUser, adminPassword):
@@ -73,6 +84,7 @@ def CreateZoniDb(config, adminUser, admi
 	conn = connectDb(host, port, adminUser, adminPassword, db)
 	createTables(conn)
 	createRegistration(conn, config)
+	addInitialConfig(conn, config)
 	sys.stdout.write("Finished\n")
 
 def connectDb (host, port, user, passwd, db=None):
@@ -113,16 +125,16 @@ 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, `service_tag` char(64) default NULL, `express_service_code` char(64) 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, PRIMARY KEY  (`sys_id`))")
+	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`))")
 	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) NOT NULL, `hw_model` varchar(64) NOT NULL, `hw_ipaddr` varchar(64) NOT NULL, `hw_userid` varchar(64) default NULL, `hw_password` varchar(64) default NULL, `hw_notes` longtext NOT NULL, PRIMARY KEY  (`hw_id`))") 
+	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, `node_id` int(8) NOT NULL, `reservation_id` int(8) NOT NULL, `ip_addr` varchar(64) NOT NULL, `hostname` varchar(64) default NULL, `vlan_id` int(11) NOT NULL, `notes` tinytext, PRIMARY KEY  (`allocation_id`))")
+	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`))")
 	sys.stdout.write("Success\n")
 	#  Create imageinfo
 	sys.stdout.write("    Creating imageinfo...")
@@ -138,15 +150,35 @@ def createTables(conn):
 	sys.stdout.write("Success\n")
 	#  Create portmap 
 	sys.stdout.write("    Creating portmap...")
-	execQuery(conn, "CREATE TABLE IF NOT EXISTS `portmap` ( `port_id` int(8) NOT NULL auto_increment, `hw_id` int(8) NOT NULL, `node_id` int(8) NOT NULL, `port_num` int(8) NOT NULL, PRIMARY KEY  (`port_id`))")
+	execQuery(conn, "CREATE TABLE IF NOT EXISTS `portmap` (`hw_id` int(8) NOT NULL, `sys_id` int(8) NOT NULL, `port_num` int(8))")
 	sys.stdout.write("Success\n")
-	#  Create vlaninfo
+	#  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, `ip_network` varchar(64) NOT NULL, `domain` varchar(64) NOT NULL, PRIMARY KEY  (`vlan_id`))")
+	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`))")
+	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`))")
+	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)")
+	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)")
+	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`))")
+	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, `node_id` int(8) NOT NULL, `ip_addr` varchar(64) NOT NULL, `hostname` varchar(64) NOT NULL, `vlan_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 `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`))")
 	sys.stdout.write("Success\n")
 	#  Create kernelinfo 
 	sys.stdout.write("    Creating kernelinfo...")
@@ -156,10 +188,14 @@ def createTables(conn):
 	sys.stdout.write("    Creating initrdinfo...")
 	execQuery(conn, "CREATE TABLE IF NOT EXISTS `initrdinfo` ( `initrd_id` int(11) unsigned NOT NULL auto_increment, `initrd_name` varchar(256) NOT NULL, `initrd_arch` varchar(128) NOT NULL, `initrd_options` varchar(1024) NOT NULL, PRIMARY KEY  (`initrd_id`))")
 	sys.stdout.write("Success\n")
+	#  Create diskinfo
+	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")
 
 def createRegistration(conn, config):
 
-	sys.stdout.write("Inserting initial Registration info into DB...\n")
+	sys.stdout.write("    Inserting initial Registration info into DB...\n")
 
 	#  Check if already there...
 	checkVal =  entryExists(conn, "kernelinfo", "kernel_name", "linux-2.6.24-19-server")
@@ -170,7 +206,7 @@ def createRegistration(conn, config):
 	else:
 		r = execQuery(conn, "INSERT into `kernelinfo` (kernel_name, kernel_release, kernel_arch) values ('linux-2.6.24-19-server', '2.6.24-19-server', 'x86_64' )")
 		kernelId = str(r.lastrowid)
-		sys.stdout.write("Success\n")
+		sys.stdout.write("    Success\n")
 
 	#  Initrd
 	checkVal =  entryExists(conn, "initrdinfo", "initrd_name", "zoni-register-64")
@@ -214,6 +250,89 @@ def createRegistration(conn, config):
 	sys.stdout.write("Success\n")
 
 
+def addInitialConfig(conn, config):
+	#  Add the home vlan
+	sys.stdout.write("    Adding initial configuration info into DB...\n")
+	sys.stdout.write("        Adding vlan info...")
+	checkVal =  entryExists(conn, "vlaninfo", "vlan_num", config['zoniHomeDomain'])
+	if checkVal:
+		sys.stdout.write("Vlan already exists in DB...\n")
+		#  Get the domainId 
+		vlanId = str(checkVal[1][0][0])
+	else:
+		r = execQuery(conn, "INSERT into `vlaninfo` (vlan_num, vlan_desc) values (" + config['zoniHomeDomain'] + ", 'Zoni Home Vlan' )")
+		vlanId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+
+	#  Create the Zoni Home domain
+	sys.stdout.write("        Creating Zoni Home Domain...")
+	checkVal =  entryExists(conn, "domaininfo", "domain_name", "ZoniHome")
+	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' )")
+		domainId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+
+	#  link the vlan and domain
+	sys.stdout.write("        Linking Domain and vlan...")
+	checkVal =  entryExists(conn, "domainmembermap", "domain_id", domainId)
+	if checkVal:
+		sys.stdout.write("Default Domain (ZoniHome) already linked to vlan " + config['zoniHomeDomain'] + "...\n")
+		#  Get the domainId 
+		valId = str(checkVal[1][0][0])
+	else:
+		r = execQuery(conn, "INSERT into `domainmembermap` (domain_id, vlan_id) values (" + domainId + ", " + vlanId + ")")
+		domainId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+
+	#  Add the pools
+	sys.stdout.write("        Adding default pools (Zoni home) from config file...")
+	checkVal =  entryExists(conn, "poolinfo", "pool_name", 'ZoniHome')
+	if checkVal:
+		sys.stdout.write("Default pool (ZoniHome) already exists...\n")
+		zoniPoolId = str(checkVal[1][0][0])
+	else:
+		r = execQuery(conn, "INSERT into `poolinfo` (pool_name, pool_ip_network) values ('ZoniHome', '" + config['zoniHomeNetwork'] + "')")
+		zoniPoolId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+
+	sys.stdout.write("        Adding default pools (IPMI home) from config file...")
+	checkVal =  entryExists(conn, "poolinfo", "pool_name", 'IpmiHome')
+	if checkVal:
+		sys.stdout.write("Default pool (IpmiHome) already exists...\n")
+		zoniIpmiId = str(checkVal[1][0][0])
+	else:
+		r = execQuery(conn, "INSERT into `poolinfo` (pool_name, pool_ip_network) values ('IpmiHome', '" + config['zoniIpmiNetwork'] + "')")
+		zoniIpmiId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+
+	#  link the pools
+	sys.stdout.write("        Linking default pools (Zoni home)...")
+	checkVal =  entryExists(conn, "poolmap", "pool_id", zoniPoolId)
+	if checkVal:
+		sys.stdout.write("Default pool (ZoniHome) already exists...\n")
+		#  Get the domainId 
+		poolId = str(checkVal[1][0][0])
+	else:
+		r = execQuery(conn, "INSERT into `poolmap` (pool_id, vlan_id) values (" + zoniPoolId + ", " + vlanId + ")")
+		domainId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+
+	sys.stdout.write("        Linking default pools (IPMI home)...")
+	checkVal =  entryExists(conn, "poolmap", "pool_id", zoniIpmiId)
+	if checkVal:
+		sys.stdout.write("Default pool (ZoniHome) already exists...\n")
+		#  XXX probably should delete first then add, do it later
+		#  Get the domainId 
+		poolId = str(checkVal[1][0][0])
+	else:
+		r = execQuery(conn, "INSERT into `poolmap` (pool_id, vlan_id) values (" + zoniIpmiId + ", " + vlanId + ")")
+		domainId = str(r.lastrowid)
+		sys.stdout.write("Success\n")
+	
 
 def execQuery(conn, query):
 	cursor = conn.cursor()

Added: incubator/tashi/trunk/src/zoni/install/www/zoniWebSetup.py
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/install/www/zoniWebSetup.py?rev=1028463&view=auto
==============================================================================
--- incubator/tashi/trunk/src/zoni/install/www/zoniWebSetup.py (added)
+++ incubator/tashi/trunk/src/zoni/install/www/zoniWebSetup.py Thu Oct 28 20:37:52 2010
@@ -0,0 +1,151 @@
+#!/usr/bin/env python
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "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
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.    
+#
+#  $Id$
+#
+
+import os 
+import sys
+import time
+import string
+import traceback
+import optparse
+import shutil
+import urllib
+import tarfile
+
+a = os.path.join("../")
+sys.path.append(a)
+a = os.path.join("../../")
+sys.path.append(a)
+a = os.path.join("../../..")
+sys.path.append(a)
+
+from zoni.extra.util import *
+from zoni.version import *
+from zoni.bootstrap.pxe import Pxe
+
+
+def main():
+	''' This file sets up the web files for Zoni '''
+
+	ver = version.split(" ")[0]
+	rev = revision
+
+	parser = optparse.OptionParser(usage="%prog ", version="%prog " + ver + " " + rev)
+	(options, args) = parser.parse_args()
+
+	configFile = getConfig()
+
+	ZoniWebSetup(configFile)
+	ZoniCreateWebConfigFile(configFile)
+
+
+def ZoniCreateWebConfigFile(config):
+	zoniBaseDir = config['installBaseDir']
+	docRoot = config['wwwDocumentRoot']
+	baseDir = config['registrationBaseDir']
+	dbHost = config['dbHost']
+	dbPort = str(config['dbPort'])
+	dbInst = config['dbInst']
+	dbUser = config['dbUser']
+	dbPassword = config['dbPassword']
+
+	zoniHomeDomain = config['zoniHomeDomain']
+	zoniHomeNetwork = config['zoniHomeNetwork']
+	zoniIpmiNetwork = config['zoniIpmiNetwork']
+
+	zoniRoot = os.path.join(docRoot, baseDir)
+
+	includeDir = os.path.join(docRoot, baseDir, "include")
+	includeFile = os.path.join(includeDir, "zoni_www_registration.conf")
+
+	a = "<?php\n"
+	a += "/*  Generated by Zoni on " + time.asctime() + "  */\n\n\n"
+	a += "function init_globals() {\n"
+	a += "	$G = array();\n"
+	a += "\n"
+	a += "	//  Zoni Install Base\n";
+	a += "	$G['ZONI_BASE_DIR'] = \"" + zoniBaseDir + "\";\n"
+	a += "\n"
+	a += "	//  webserver directories\n";
+	a += "	$G['ABSROOT'] = \"" + zoniRoot + "\";\n"
+	a += "	$G['WEBROOT'] = \"" + baseDir + "\";\n"
+	a += "\n"
+	a += "	//  DB info\n";
+	a += "	$G['DB_HOST'] = \"" + dbHost + "\";\n"
+	a += "	$G['DB_USER'] = \"" + dbUser + "\";\n"
+	a += "	$G['DB_PASS'] = \"" + dbPassword + "\";\n"
+	a += "	$G['DB_INST'] = \"" + dbInst + "\";\n"
+	a += "	$G['DB_PORT'] = \"" + dbPort + "\";\n"
+	a += "\n"
+	a += "	//  Zoni Home Domain \n";
+	a += "	$G['ZONI_HOME_DOMAIN'] = \"" + zoniHomeDomain + "\";\n"
+	a += "	$G['ZONI_HOME_NETWORK'] = \"" + zoniHomeNetwork + "\";\n"
+	a += "	$G['ZONI_IPMI_NETWORK'] = \"" + zoniIpmiNetwork + "\";\n"
+	a += "\n"
+	a += "	ini_set('display_errors', 1);\n"
+	a += "	ini_set('error_reporting', E_ALL);\n"
+	a += "\n"
+	a += "	return $G;\n"
+	a += "}\n"
+	a += "?>\n"
+
+	#  Rename any existing
+	if os.path.exists(includeFile):
+		includeFileBak = os.path.join(includeFile + "." + str(int(time.time())))
+		shutil.move(includeFile, includeFileBak)
+
+	f = open(includeFile, "w")
+	f.write(a)
+	f.close()
+
+
+
+@checkSuper
+def ZoniWebSetup(config):
+	docRoot = config['wwwDocumentRoot']
+	baseDir = config['registrationBaseDir']
+	zoniInstallDir = config['installBaseDir']
+
+	zoniWebRoot = os.path.join(docRoot, baseDir )
+	createDir(zoniWebRoot, 1)
+	zoniIncludeDir = os.path.join(zoniWebRoot, "include")
+	createDir(zoniIncludeDir)
+	zoniRegisterDir = os.path.join(zoniWebRoot, "register")
+	createDir(zoniRegisterDir)
+
+	sys.stdout.write("	Copying zoni_function.php\n")
+	zoniIncludeSrcFile = os.path.join(zoniInstallDir, "src", "zoni", "system", "registration", "www", "include", "zoni_functions.php") 
+	shutil.copy(zoniIncludeSrcFile, zoniIncludeDir)  
+
+	sys.stdout.write("	Copying register_node\n")
+	zoniRegisterSrcFile = os.path.join(zoniInstallDir, "src", "zoni", "system", "registration", "register", "register_node") 
+	shutil.copy(zoniRegisterSrcFile, zoniRegisterDir)  
+
+	sys.stdout.write("	Copying register_automate\n")
+	zoniRegisterAutoSrcFile = os.path.join(zoniInstallDir, "src", "zoni", "system", "registration", "register", "register_automate") 
+	shutil.copy(zoniRegisterAutoSrcFile, zoniRegisterDir)  
+
+	sys.stdout.write("	Copying zoni-register.php\n")
+	zoniRegisterSrcFile = os.path.join(zoniInstallDir, "src", "zoni", "system", "registration", "www", "zoni-register.php") 
+	shutil.copy(zoniRegisterSrcFile, zoniWebRoot)  
+
+
+if __name__ in "__main__":
+	main()

Propchange: incubator/tashi/trunk/src/zoni/install/www/zoniWebSetup.py
------------------------------------------------------------------------------
    svn:keywords = Id

Added: incubator/tashi/trunk/src/zoni/system/registration/register/register_automate
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/system/registration/register/register_automate?rev=1028463&view=auto
==============================================================================
--- incubator/tashi/trunk/src/zoni/system/registration/register/register_automate (added)
+++ incubator/tashi/trunk/src/zoni/system/registration/register/register_automate Thu Oct 28 20:37:52 2010
@@ -0,0 +1,48 @@
+#! /bin/sh
+#
+#  $Id:$
+#
+# This program takes two args:
+# register_automate <svg_tag|mac_addr> <"location"|"switchinfo"|"pduinfo"">
+#
+# Based on the the service tag or the mac address of the machine, it returns 
+# the intented location, hostname, or IP address of the machine, respectively.
+# It is intented to short-circuit the question phase of registration.
+#
+
+#  Example Chassis r2r1c1 : note, the line must begin with a "#"
+#  tag|mac|uuid location switchname:portnum pduname:portnum
+#  hostname is set to the location of the physical machine.  Your naming convention may differ.
+#  r2r1c1b9 - row 2, rack 1, chassis 1, blade 9
+
+#  XXX  Don't FORGET!!!  the line must begin with a "#"
+
+#XXXXXXX r2r1c1b9 sw0-r2r1c1:1 drac-r2r1c1:1 x86_64-tashi_nm
+#XXXXXX1 r1r2u29 sw0-r1r2:16 pdu1-r1r2:9 x86_64-default
+
+#6h30lm1 r1r2u29 sw0-r1r2:16 pdu1-r1r2:9 zoni-register-64
+#8q0nfk1 rgass-desk sw0-r1r2:17 pdu1-r1r2:15 zoni-register-64
+
+
+
+SVC_TAG=$1
+REQUEST=$2
+
+res=""
+if [[ "$REQUEST" == "location" ]]; then
+    res=`cat /register_automate | grep -i "^#$SVC_TAG" | awk '{print $2}'`
+elif [[ "$REQUEST" == "switchinfo" ]]; then
+    res=`cat /register_automate | grep -i "^#$SVC_TAG" | awk '{print $3}'`
+elif [[ "$REQUEST" == "pduinfo" ]]; then
+    res=`cat /register_automate | grep -i "^#$SVC_TAG" | awk '{print $4}'`
+elif [[ "$REQUEST" == "image" ]]; then
+    res=`cat /register_automate | grep -i "^#$SVC_TAG" | awk '{print $5}'`
+fi
+
+if [[ `echo -n $res | wc -c` -gt 1 ]]; then
+    echo $res
+    exit 0
+else
+    echo "No entry found" >&2
+    exit 1
+fi

Modified: incubator/tashi/trunk/src/zoni/system/registration/register/register_node
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/system/registration/register/register_node?rev=1028463&r1=1028462&r2=1028463&view=diff
==============================================================================
--- incubator/tashi/trunk/src/zoni/system/registration/register/register_node (original)
+++ incubator/tashi/trunk/src/zoni/system/registration/register/register_node Thu Oct 28 20:37:52 2010
@@ -27,6 +27,7 @@ DEBUG () {
 }
 
 #  Capture vars passed via kernal args
+VERBOSE=0
 for x in $(cat /proc/cmdline); do
     case $x in
     imagename=*)
@@ -50,65 +51,96 @@ done
 IMAGE_URL="${PXESERVER}/${IMAGE_ROOT}/"
 
 #  Scrape system for specs
-/sbin/getSystemId > /tmp/sysinfo
-cat /proc/cpuinfo >> /tmp/sysinfo
+#/sbin/getSystemId > /tmp/sysinfo
+#  moving to dmidecode because getSystemId is now python code and 
+#  I don't want to include python in the image if I dont have to
+cat /proc/cpuinfo > /tmp/sysinfo
 cat /proc/meminfo >> /tmp/sysinfo
 ifconfig eth0 >> /tmp/sysinfo
-#fdisk >> /tmp/sysinfo
+fdisk -l | grep Disk | grep dev 1>> /tmp/sysinfo
 
-DEBUG "pxeserver is ", ${PXESERVER}
+DEBUG "pxeserver is " ${PXESERVER}
 
-
-(echo -n "MAC:          "; ifconfig eth0 | grep "HWaddr" | awk '{print $5}') >> /tmp/sysinfo
+#(echo -n "MAC:          "; ifconfig eth0 | grep "HWaddr" | awk '{print $5}') >> /tmp/sysinfo
 
 DEBUG $(cat /tmp/sysinfo)
 sleep 1
+IPADDR=$(cat /tmp/sysinfo | grep "inet addr" | awk '{print $2}' | awk -F: '{print $2}')
 MAC=$(cat /tmp/sysinfo | grep "HWaddr" | awk '{print $5}') 
 DEBUG MAC - $MAC
-MOD_MAC=`cat /tmp/sysinfo | grep "^MAC" | cut -c 15- | sed 's/:/-/g' | sed 'y/ABCDEF/abcdef/'`
+MOD_MAC=$(echo ${MAC} | sed 's/:/-/g' | sed 'y/ABCDEF/abcdef/')
 DEBUG MOD_MAC - $MOD_MAC
-SYS_MODEL=$(cat /tmp/sysinfo | grep "^Product Name:" | cut -c 15- | sed 's/ /+/g')
+SYS_MODEL=$(/sbin/dmidecode -s system-product-name | sed 's/ /+/g')
 DEBUG SYS_MODEL is $SYS_MODEL
-SERVICE_TAG=$(cat /tmp/sysinfo | grep "^Service Tag:" | cut -c 15- | sed 's/ /+/g')
-DEBUG SERVICE_TAG is $SERVICE_TAG
-EXPRESS_SERVICE_CODE=$(cat /tmp/sysinfo | grep "^Express Service Code:" | cut -c 15- | sed 's/ /+/g')
-DEBUG EXPRESS_SERVICE_CODE is $EXPRESS_SERVICE_CODE
-BIOS_REV=$(cat /tmp/sysinfo | grep "^BIOS Version:" | cut -c 15- | sed 's/ /+/g')
+SYSTEM_SERIAL_NUMBER=$(/sbin/dmidecode -s system-serial-number | sed 's/ /+/g')
+DEBUG SYSTEM_SERIAL_NUMBER is $SYSTEM_SERIAL_NUMBER
+CHASSIS_SERIAL_NUMBER=$(/sbin/dmidecode -s chassis-serial-number | sed 's/ /+/g')
+DEBUG CHASSIS_SERIAL_NUMBER is $CHASSIS_SERIAL_NUMBER
+SYSTEM_UUID=$(/sbin/dmidecode -s system-uuid | sed 's/ /+/g')
+DEBUG SYSTEM_UUID is $SYSTEM_UUID
+BIOS_REV=$(/sbin/dmidecode -s bios-version | sed 's/ /+/g')
 DEBUG BIOS_REV - $BIOS_REV
-SYS_VENDOR=$(cat /tmp/sysinfo | grep "^Vendor:" | cut -c 15- | sed 's/ /+/g')
-#NUM_PROC=$(cat /proc/cpuinfo | grep processor | wc -l);
-
+SYS_VENDOR=$(/sbin/dmidecode -s system-manufacturer | sed 's/ /+/g')
+DEBUG SYS_VENDOR - $SYS_VENDOR
 PROC_VENDOR=$(cat /tmp/sysinfo | grep vendor_id | cut -d ":" -f 2 | tail -n1 | sed 's/ /+/g');
+DEBUG PROC_VENDOR - $PROC_VENDOR
 PROC_MODEL=$(cat /tmp/sysinfo | grep "model name"| cut -d ":" -f 2 | tail -n1 | sed 's/ /+/g');
+DEBUG PROC_MODEL - $PROC_MODEL
 CLOCK_SPEED=$(cat /tmp/sysinfo | grep "cpu MHz"| cut -d ":" -f 2 | tail -n1 | sed 's/ /+/g');
+DEBUG CLOCK_SPEED - $CLOCK_SPEED
 PROC_CACHE=$(cat /tmp/sysinfo | grep "cache size"| cut -d ":" -f 2 | tail -n1 | sed 's/ /+/g');
+DEBUG PROC_CACHE - $PROC_CACHE
 CPU_FLAGS=$(cat /tmp/sysinfo | grep "flags"| cut -d ":" -f 2 | tail -n1 | sed 's/ /+/g');
+DEBUG CPU_FLAGS - $CPU_FLAGS
 NUM_PROCS=$(cat /tmp/sysinfo | grep "physical id" | sort | uniq | wc -l | sed 's/ /+/g');
+DEBUG NUM_PROCS - $NUM_PROCS
 DA_PROCS=$(cat /tmp/sysinfo | grep "physical id" | sort | uniq | wc -l);
+DEBUG DA_PROCS - $DA_PROCS
 #NUM_CORES=$(cat /tmp/sysinfo | grep "cpu cores"| cut -d ":" -f 2 | tail -n1 | sed 's/ /+/g');
 DA_CORES=$(cat /tmp/sysinfo | grep "cpu cores"| cut -d ":" -f 2 | tail -n1);
+DEBUG DA_CORES - $DA_CORES
 NUM_CORES=$(echo $(($DA_PROCS * $DA_CORES)))
+DEBUG NUM_CORES - $NUM_CORES
 MEM_TOTAL=$(cat /tmp/sysinfo | grep "MemTotal"| awk '{print $2}' | sed 's/ /+/g');
-SUBNET=$(cat /tmp/sysinfo | grep "inet addr"| awk '{print $2}' | cut -d ":" -f 2 | awk -F "." '{print $3}');
+DEBUG MEM_TOTAL - $MEM_TOTAL
+NUM_DISKS=$(cat /tmp/sysinfo | grep "Disk"| grep "dev" |  wc -l)
+DEBUG NUM_DISKS - $NUM_DISKS
+
+DISK_INFO=""
+i=1
+
+while [ $i -le ${NUM_DISKS} ];do 
+	val=$(cat /tmp/sysinfo | tail -n $i | head -n 1 | awk '{print $2$5}')
+	echo $val
+	if [ $i -eq 1 ];then
+		DISK_INFO=$val
+	else
+		DISK_INFO="${DISK_INFO} $val"
+	fi
+	i=$(($i+1))
+done
+tmp=$(echo $DISK_INFO | sed 's/ /+/g')
+DISK_INFO=$tmp
+DEBUG DISK_INFO - ${DISK_INFO}
 
 #disk_size=$(cat /tmp/sysinfo | grep "Disk"| awk '{print $5}');
 
 #  Register sysinfo to DB
-DEBUG 'running cmd - wget -O- "http://${IMAGE_URL}/zoni-register.php?action=register_system&mac=$MAC&mod_mac=$MOD_MAC&sys_model=$SYS_MODEL&bios_rev=$BIOS_REV&service_tag=$SERVICE_TAG&express_service_code=$EXPRESS_SERVICE_CODE&sys_vendor=$SYS_VENDOR&proc_vendor=$PROC_VENDOR&proc_model=$PROC_MODEL&clock_speed=$CLOCK_SPEED&proc_cache=$PROC_CACHE&num_procs=$NUM_PROCS&num_cores=$NUM_CORES&mem_total=$MEM_TOTAL&cpu_flags=$CPU_FLAGS"'
-wget -O- "http://${IMAGE_URL}/zoni-register.php?action=register_system&mac=$MAC&mod_mac=$MOD_MAC&sys_model=$SYS_MODEL&bios_rev=$BIOS_REV&service_tag=$SERVICE_TAG&express_service_code=$EXPRESS_SERVICE_CODE&sys_vendor=$SYS_VENDOR&proc_vendor=$PROC_VENDOR&proc_model=$PROC_MODEL&clock_speed=$CLOCK_SPEED&proc_cache=$PROC_CACHE&num_procs=$NUM_PROCS&num_cores=$NUM_CORES&mem_total=$MEM_TOTAL&cpu_flags=$CPU_FLAGS"
+DEBUG "wget -O- http://${IMAGE_URL}/zoni-register.php?action=register_system&mac=$MAC&mod_mac=$MOD_MAC&sys_model=$SYS_MODEL&bios_rev=$BIOS_REV&system_serial_number=$SYSTEM_SERIAL_NUMBER&chassis_serial_number=${CHASSIS_SERIAL_NUMBER}&system_uuid=$SYSTEM_UUID&sys_vendor=$SYS_VENDOR&proc_vendor=$PROC_VENDOR&proc_model=$PROC_MODEL&clock_speed=$CLOCK_SPEED&proc_cache=$PROC_CACHE&num_procs=$NUM_PROCS&num_cores=$NUM_CORES&mem_total=$MEM_TOTAL&cpu_flags=$CPU_FLAGS&num_disks=${NUM_DISKS}&disk_info=${DISK_INFO}"
+wget "http://${IMAGE_URL}/zoni-register.php?action=register_system&mac=$MAC&mod_mac=$MOD_MAC&sys_model=$SYS_MODEL&bios_rev=$BIOS_REV&system_serial_number=$SYSTEM_SERIAL_NUMBER&chassis_serial_number=${CHASSIS_SERIAL_NUMBER}&system_uuid=$SYSTEM_UUID&sys_vendor=$SYS_VENDOR&proc_vendor=$PROC_VENDOR&proc_model=$PROC_MODEL&clock_speed=$CLOCK_SPEED&proc_cache=$PROC_CACHE&num_procs=$NUM_PROCS&num_cores=$NUM_CORES&mem_total=$MEM_TOTAL&cpu_flags=$CPU_FLAGS&num_disks=${NUM_DISKS}&disk_info=${DISK_INFO}"
 
 #  Get more info either from cheat file or from user entered info
 ec=1
 if [[ -e /register_automate ]]; then
-	switchinfo=`/register_automate $SERVICE_TAG switchinfo`
+	switchinfo=`/register_automate $SYSTEM_SERIAL_NUMBER switchinfo`
 	switchport=$(echo $switchinfo | cut -d ":" -f 2)
 	switch=$(echo $switchinfo | cut -d ":" -f 1)
-	pduinfo=`/register_automate $SERVICE_TAG pduinfo`
+	pduinfo=`/register_automate $SYSTEM_SERIAL_NUMBER pduinfo`
 	pduport=$(echo $pduinfo | cut -d ":" -f 2)
 	pdu_name=$(echo $pduinfo | cut -d ":" -f 1)
-	location=`/register_automate $SERVICE_TAG location`
-	hn=`/register_automate $SERVICE_TAG hostname`
-	ip_addr=`/register_automate $SERVICE_TAG ipaddr`
+	location=`/register_automate $SYSTEM_SERIAL_NUMBER location`
+	#ip_addr=`/register_automate $SYSTEM_SERIAL_NUMBER ipaddr`
+	daimage=`/register_automate $SYSTEM_SERIAL_NUMBER image`
 	ec=$?
 	DEBUG "Register automate completed"
 	DEBUG "ec is $ec"
@@ -123,29 +155,29 @@ fi
 #val=${#answer}
 #if [ $val -gt 0 ];then
 
+#  No automate entry found, prompt user for info
 if [[ $ec -ne 0 ]]; then
 	ans=n;
 	while [ $ans == "n" ] || [ $ans == "N" ]; do
-		echo -n "Please enter the location for this node: "
+		echo -n "Please enter the location/hostname for this node: "
 		read location
-		#echo -n "Please enter the hostname for this node: "
-		#read hn
-		echo -n "Please enter the IP address for this node: "
-		read ip_addr
-		echo -n "if you know what image you want, enter it here: "
-		read daimage
+		#echo -n "Please enter the IP address for this node: "
+		#read ip_addr
 		echo -n "Enter Switch name:port e.g. sw0-r3r2:8: "
 		read switchinfo
 		echo -n "Enter PDU name:port e.g. pdu0-r3r2:8: "
 		read pduinfo
+		echo -n "if you know what image you want, enter it here: "
+		read daimage
 
 		##  Confirm summary
 		echo "--  Summary --"
 		echo "Location: $location"
 		#echo "Hostname: $hn"
-		echo "IP address: $ip_addr"
-		echo "Image name: $daimage"
+		#echo "IP address: $ip_addr"
 		echo "SwitchInfo: $switchinfo"
+		echo "PDUInfo: $pduinfo"
+		echo "Image name: $daimage"
 		echo "Save Configuation? [y/n]"
 		read ans
 		##  Submit some stuff that was entered
@@ -157,78 +189,103 @@ if [[ $ec -ne 0 ]]; then
 		pdu_name=$(echo $pduinfo | cut -d ":" -f 1)
 
 	done
-	#  Update IP_ADDR
-	if [ $ip_addr ];then 
-		DEBUG "Update ip $ip_addr"
-		wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addip&mac=$MAC&ip_addr=$ip_addr"
-	fi
-	if [ $location ];then 
-		DEBUG "Set location"
-		wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addlocation&mac=$MAC&location=$location"
-	fi
-	#  If we set the imagename, register it
-	if [ $daimage ];then
-		DEBUG "setting image name"
-		wget -O- "http://${IMAGE_URL}/zoni-register.php?action=assign_image&mac=$MAC&image_name=$daimage&location=$location"
-	#else
-		#wget -O- "http://${IMAGE_URL}/zoni-register.php?action=bootopt&machine_type=generic&mac=$MAC&image_name=$DEFAULTIMAGE"
-	fi
-#############################
-##  USE REGISTER_AUTOMATE  ##
-#############################
-else
-	# using register automate file info
-	DEBUG "Getting bootopt..."
-	bootopt=$(/register_automate $SERVICE_TAG bootopt)
-	ec=$?
-	if [[ $ec -eq 0 ]]; then
-		wget -O- "http://${IMAGE_URL}/zoni-register.php?action=assign_image&mac=$MAC&image_name=$bootopt&location=$location"
-	fi 
-	DEBUG "about to update ip $ip_addr in automate"
-	if [ $ip_addr ];then 
-		echo wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addip&mac=$MAC&ip_addr=$ip_addr"
-		wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addip&mac=$MAC&ip_addr=$ip_addr"
-	fi
-	if [ $location ];then 
-		wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addlocation&mac=$MAC&location=$location"
-	fi
 fi
+
+#  Update IP_ADDR
+#  Removing IP address.   Let DHCP do the work
+#if [ $ip_addr ];then 
+	#DEBUG "Update ip $ip_addr"
+	#wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addip&mac=$MAC&ip_addr=$ip_addr"
+#fi
+VERBOSE=0
+if [ $location ];then 
+	DEBUG "Set location ${location}"
+	echo "wget -O- http://${IMAGE_URL}/zoni-register.php?action=addlocation&verbose=${VERBOSE}&mac=$MAC&location=$location"
+	wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addlocation&verbose=${VERBOSE}&mac=$MAC&location=$location"
+fi
+#  If we set the imagename, register it
+if [ $daimage ];then
+	DEBUG "setting image name"
+	wget -O- "http://${IMAGE_URL}/zoni-register.php?action=assign_image&verbose=${VERBOSE}&mac=$MAC&image_name=$daimage&location=$location"
+fi
+
 if [ $switchport ];then 
-	wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addswitchinfo&mac=$MAC&switch=${switch}&switchport=${switchport}"
+	DEBUG "setting switchport : ${switch} ${switchport}"
+	wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addhardwareinfo&verbose=${VERBOSE}&mac=$MAC&hwdev=${switch}&hwport=${switchport}"
 fi
 
 if [ $pduport ];then 
-	wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addswitchinfo&mac=$MAC&switch=${pdu_name}&switchport=${pduport}"
+	DEBUG "setting pduport : ${pdu_name} ${pduport}"
+	wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addhardwareinfo&verbose=${VERBOSE}&mac=$MAC&hwdev=${pdu_name}&hwport=${pduport}"
 fi
 
-#  Add IPMI info 
-wget -O/outfile.txt "http://${IMAGE_URL}/zoni-register.php?action=add_ipmi&mac=$MAC&location=$location"
-IPMI_ADDR=$(cat /outfile.txt | grep IPMI_ADDR | awk '{print $2}')
-IPMI_PASSWORD=$(cat /outfile.txt | grep IPMI_ADDR | awk '{print $4}')
-
-echo $IPMI_ADDR and $IPMI_PASSWORD
-
-ipmitool lan set 1 ipaddr $IPMI_ADDR
-ipmitool lan set 1 vlan id 998 
-ipmitool lan set 1 defgw ipaddr 0.0.0.0
-ipmitool lan set 1 netmask 255.255.255.0
-ipmitool lan set 1 password $IPMI_PASSWORD
-ipmitool lan set 1 access on
-
-#  Make user 2 be root with random password
-ipmitool user set name 2 root
-ipmitool user set password 2 $IPMI_PASSWORD
-ipmitool channel setaccess 1 2 callin=on ipmi=on link=on privilege=4
-ipmitool user enable 2
+	#wget -O- "http://${IMAGE_URL}/zoni-register.php?action=addip&mac=$MAC&ip_addr=$ip_addr"
+#fi
 
 #  Add dns and dhcp
-wget -O- "http://${IMAGE_URL}/zoni-register.php?action=updatednsdhcp&mac=${MAC}&location=$location&ip_addr=$ip_addr&ipmi_addr=$IPMI_ADDR"
+DEBUG "adding to dhcp and dns"
+wget -O- "http://${IMAGE_URL}/zoni-register.php?action=updatednsdhcp&verbose=${VERBOSE}&mac=${MAC}&location=$location&ip_addr=$IPADDR"
 
+#  Setup the management interface, if any
 
-#  If default image is set as kernel opt, override automate file
-DEBUG "def image is $DEFAULTIMAGE "
-if [ $DEFAULTIMAGE ] ; then 
-	wget -O- "http://${IMAGE_URL}/zoni-register.php?action=assign_image&mac=$MAC&image_name=$DEFAULTIMAGE&location=$location"
+#  Check for ipmi
+#  Check for the existance of the module.  
+cat /proc/modules | grep ipmi_si 
+if [ $? -eq 0 ];then 
+	#  Assigning IP address to IPMI card since they don't seem to every accept an address from DHCP
+	#  Subnet is selected from config file
+	#  Get IPMI card mac address
+	ipmi_mac=$(ipmitool lan print |  grep -i "MAC Address" | awk -F ": " '{print $2}')
+	ipmi_ver=$(ipmitool mc info |  grep -i "IPMI Version" | awk -F ": " '{print $2}')
+	ipmi_rev=$(ipmitool mc info |  grep -i "Firmware Revision" | awk -F ": " '{print $2}')
+
+	vlan_disable=$(ipmitool lan print |  grep -i "Vlan" | awk -F ": " '{print $2}')
+
+	#  Add IPMI info 
+VERBOSE=1
+	wget -O/outfile.txt "http://${IMAGE_URL}/zoni-register.php?action=add_ipmi&verbose=${VERBOSE}&mac=$MAC&location=${location}&ip_addr=${IPADDR}&ipmi_mac=${ipmi_mac}&ipmi_ver=${ipmi_ver}&ipmi_rev=${ipmi_rev}"
+	IPMI_ADDR=$(cat /outfile.txt | grep IPMI_ADDR | awk '{print $2}')
+	IPMI_PASSWORD=$(cat /outfile.txt | grep IPMI_PASSWORD | awk '{print $2}')
+	IPMI_DOMAIN=$(cat /outfile.txt | grep IPMI_DOMAIN| awk '{print $2}')
+	IPMI_NETMASK=$(cat /outfile.txt | grep IPMI_NETMASK| awk '{print $2}')
+	IPMI_GATEWAY=$(cat /outfile.txt | grep IPMI_GATEWAY| awk '{print $2}')
+
+
+	
+	if [ ${IPMI_DOMAIN} -eq 1 ];then 
+		IPMI_DOMAIN="off"
+	fi
+	DEBUG "ip $IPMI_ADDR pass $IPMI_PASSWORD domain $IPMI_DOMAIN netmask $IPMI_NETMASK gateway $IPMI_GATEWAY "
+	ipmitool lan set 1 ipsrc static
+	ipmitool lan set 1 ipaddr ${IPMI_ADDR}
+	ipmitool lan set 1 vlan id ${IPMI_DOMAIN}
+	ipmitool lan set 1 defgw ipaddr ${IPMI_GATEWAY}
+	ipmitool lan set 1 netmask ${IPMI_NETMASK}
+	ipmitool lan set 1 password ${IPMI_PASSWORD}
+	ipmitool lan set 1 access on
+
+	#  Make user 2 be root with random password
+	ipmitool user set name 2 root
+	ipmitool user set password 2 $IPMI_PASSWORD
+	ipmitool channel setaccess 1 2 callin=on ipmi=on link=on privilege=4
+	ipmitool user enable 2
+
+	#DEBUG "adding to dhcp and dns"
+	#wget -O- "http://${IMAGE_URL}/zoni-register.php?action=updatednsdhcp&verbose=${VERBOSE}&mac=${ipmi_mac}&location=${location}$&ip_addr=${IPMI_ADDR}"
+
+else
+	DEBUG "IPMI interface not found"
 fi
+
+
+#  check for iLo 
+#  Code for ilo goes here...
+
+
+#  If default image is set as kernel opt, override automate file
+#DEBUG "def image is $DEFAULTIMAGE "
+#if [ $DEFAULTIMAGE ] ; then 
+	#wget -O- "http://${IMAGE_URL}/zoni-register.php?action=assign_image&mac=$MAC&image_name=$DEFAULTIMAGE&location=$location"
+#fi
 #else
 	#echo "Interactive mode canceled due to no keyboard input"

Added: incubator/tashi/trunk/src/zoni/system/registration/www/include/zoni_functions.php
URL: http://svn.apache.org/viewvc/incubator/tashi/trunk/src/zoni/system/registration/www/include/zoni_functions.php?rev=1028463&view=auto
==============================================================================
--- incubator/tashi/trunk/src/zoni/system/registration/www/include/zoni_functions.php (added)
+++ incubator/tashi/trunk/src/zoni/system/registration/www/include/zoni_functions.php Thu Oct 28 20:37:52 2010
@@ -0,0 +1,448 @@
+<?php
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "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
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.	
+#
+#  $Id$
+#
+function DEBUG($verbose, $val) {
+	if ($verbose == 1) {
+		if (is_array($val)) {
+			print "DEBUG:";
+			print_r($val);
+		} else {
+			print "DEBUG: $val<br>\n";
+		}
+
+	}
+}
+
+function get_netmask ($cidr) {
+	$val = $cidr;
+	$count = 4;
+	$mask = "";
+	$oct = "";
+	while ($val > 0) {
+		if ($val >= 8){
+			$mask = $mask . "255.";
+			$val -= 8;
+			$count -= 1;
+			
+		} 
+		if ($val < 8 ){
+			for ($i=0;$i<8;$i++){
+				if ($i < $val){
+					$oct = $oct . "1";
+				}else {
+					$oct = $oct . "0";
+				}
+			}
+			$lastoct = base_convert($oct, 2, 10);
+			$val -= 8;
+			$count -= 1;
+			$mask = $mask . $lastoct;
+		}
+		if ($val <= 0){
+			for ($i=0;$i<$count;$i++){
+				$mask = $mask  . ".0";
+			}
+		}
+	}
+	return $mask;
+}
+
+function createPassword($length=8) {
+	$pass = NULL;
+	for($i=0; $i<$length; $i++) {
+		$char = chr(rand(48,122));
+		while (!preg_match("/[a-zA-Z0-9]/", $char)){
+			$char = chr(rand(48,122));
+		}
+		$pass .= $char;
+	}
+	return $pass;
+}
+
+
+
+class db_connection {
+	var $conn;
+	var $status;
+	var $mydb;
+	var $table_headings;
+	var $num_rows;
+	var $num_fields;
+	var $field_names;
+	var $results_array;
+	var $me;
+
+	function db_connection ($HOST, $DBUSER, $password=NULL, $dbinst) {
+		$this->conn = mysql_connect ($HOST, $DBUSER, $password);
+		if (!$this->conn) {
+			die("Could not connect to $HOST as $DBUSER; " . mysql_error());
+		}
+
+		$this->mydb = mysql_select_db ($dbinst, $this->conn);
+		if (!$this->mydb) {
+			die ("Can't use $dbinst: " . mysql_error());
+		}
+		if (isset($_SESSION['user_id'])) {
+			$this->me =  $_SESSION['user_id'];
+		}
+		return $this->conn;
+
+	}
+	function close () {
+		mysql_close ($this->conn);
+	}
+
+
+	//  will return the results of the query
+	//  if index is set to 1, array key will be the field names
+	function query ($query, $index=NULL) {
+		#$result = mysql_query($query) or die('Query failed: ' . mysql_error());
+		$result = $this->run_query($query);
+		if (!(is_bool($result))) {
+			$this->num_fields = $this->set_num_fields($result);
+			$this->num_rows = $this->set_num_rows($result);
+			$this->field_names = $this->set_field_names($result);
+			$this->results_array = array();
+			while ($row = mysql_fetch_array($result)) {
+				$tmp = array();
+				//  number index
+				if ($index == 0) {
+					for ($i = 0; $i < $this->get_num_fields($result); $i++) {
+						array_push ($tmp, $row[$i]);
+					}
+					array_push($this->results_array, $tmp);
+				//  print field labels as array index
+				} else {
+					for ($i = 0; $i < $this->get_num_fields($result); $i++) {
+						$val = $this->field_names[$i];
+						$tmp[$val] = $row[$i];
+					}
+					array_push($this->results_array, $tmp);
+
+				}
+			}
+		}
+		if ($this->get_num_rows($result) == 0) {
+			return -1;
+		} else {
+			return $this->results_array;
+		}
+	}
+	function set_num_fields ($result) {
+		return mysql_num_fields($result);
+	}
+
+	function get_num_fields () {
+		return $this->num_fields;
+	}
+
+	function set_num_rows ($result) {
+		return mysql_num_rows($result);
+	}
+	function get_num_rows () {
+		return $this->num_rows;
+	}
+
+	function set_field_names ($result) {
+		$this->field_names = array();
+		for ($i = 0; $i < $this->num_fields; $i++) {
+		   $var = mysql_field_name($result, $i);
+		   array_push ($this->field_names, $var);
+		}
+		return $this->field_names;
+	}
+
+	function get_field_names () {
+		return $this->field_names;
+	}
+
+	function get_results () {
+		return $this->results_array;
+	}
+
+
+	function system_exists ($mac) {
+		$query = "select * from sysinfo where mac_addr = '$mac'";
+		$result = mysql_query ($query)
+			or die ('Check dup query failed: ' . mysql_error());
+		$val = $this->set_num_rows ($result);
+		if ($val > 0) {
+			return 1;
+		} else {
+			return 0;
+		}
+	}
+
+	function get_ip_addr($mac) {
+		$query = "select ip_addr from sysinfo where mac_addr = '$mac'";
+		$val = $this->query($query, 1);
+		return $val[0]['ip_addr'];
+	}
+	function get_location ($sys_id) {
+
+		#  location is not defined in here so get it from db
+		$query = "select location from sysinfo where sys_id = '$sys_id'";
+		$results = $this->query($query, 1);
+		$location = $results[0]['location'];
+		return $location;
+
+	}
+	function get_sys_id($mac) {
+		$query = "select sys_id from sysinfo where mac_addr = '$mac'";
+		$val = $this->query($query, 1);
+		return $val[0]['sys_id'];
+	}
+
+	function check_dup ($table, $colname, $value, $colname2=NULL, $value2=NULL) {
+		$cond = "where $colname = '$value'";
+		if ($colname2 != NULL && $value2 != NULL) {
+			$cond .= " and $colname2 = '$value2'";
+		}
+		$query = "select * from $table $cond";
+		$result = mysql_query($query)
+					or die('Check dup query failed: ' . mysql_error());
+		$val = $this->set_num_rows ($result);
+		return $val;
+
+	}
+	function add_system ($G, $u) {
+		$val = $this->check_dup ("users", "username", $u['username']);
+		if ($val < 1) {
+			$user_info = $this->create_new_user($u);
+			$msg = "SUCCESS<br> $user_info";
+		} else {
+			$msg = "A username by this name ";
+			$msg .= "({$u['username']}) already exists<br>";
+		}
+		return $msg;
+	}
+
+	/**
+	 * This function returns all info about a system 
+	 *
+	 * @param $G Global var
+	 * @return Returns an array of the contents indexed by mac address.
+	 */
+
+	function get_system_summary () {
+		$query = "select s.mac_addr, s.location, ";
+		$query .= "s.num_procs, s.num_cores, s.mem_total, s.clock_speed, ";
+		$query .= "s.sys_vendor, s.sys_model, s.proc_vendor, s.proc_model, ";
+		#$query .= "s.proc_cache, s.dell_tag, s.cpu_flags, s.bios_rev ";
+		$query .= "s.proc_cache, s.dell_tag, s.bios_rev ";
+		// $query .= "d.disk_size ";
+		#$query .= "from sysinfo s, diskinfo d ";
+		$query .= "from sysinfo s";
+		//$query .= "where s.mac_addr = d.mac_addr";
+		$results = $this->query($query, 1);
+
+		return $results;
+	}
+
+	/**
+	 * This function returns all images
+	 *
+	 * @return Returns an array of the contents 
+	 */
+	function get_images () {
+		$image_array = array();
+		$query = "select image_name from imageinfo";
+		$val = $this->query($query, 1);
+		for ($i = 0; $i < count($val); $i++) {
+			foreach ($val[$i] as $key => $image) {
+				array_push($image_array, $image);
+			}
+		}
+		return $image_array;
+	}
+
+	function get_something ($fieldname, $table, $crit_field, $crit) {
+		$query = "select $fieldname from $table ";
+		$query .= "where $crit_field = '$crit'";
+		$val = $this->query($query, 1);
+		return $val[0]["$fieldname"];
+
+	}
+ 
+	function get_mac_addr_from_hostname ($node) {
+		$query = "select mac_addr from sysinfo ";
+		$query .= "where location = '$node' ";
+		$val = $this->query($query, 1);
+		return $val[0]['mac_addr'];
+
+	}
+	function get_hostname_from_mac_addr($mac_addr) {
+		$query = "select location from hostinfo ";
+		$query .= "where mac_addr = '$mac_addr' ";
+		$val = $this->query($query, 1);
+		if ($this->num_rows == 1) {
+			return $val[0]['location'];
+		} else {
+			$query = "select location from ";
+			$query .= "where mac_addr = '$mac_addr' ";
+			$val = $this->query($query, 1);
+			return $val[0]['location'];
+		}
+
+
+	}
+
+	function get_image_id_from_image_name ($name) {
+		$query = "select image_id from imageinfo ";
+		$query .= "where image_name = '$name'";
+		$val = $this->query($query, 1);
+		return $val[0]['image_id'];
+	}
+
+
+
+	/**
+	 * This function returns image from mac_addr
+	 *
+	 * @return Returns an array of the contents 
+	 */
+	function get_current_image($mac_addr) {
+		#$mac_addr = $this->get_mac_addr_from_hostname ($node);
+		$query = "select image_name from ";
+		$query .= "imageinfo i, imagemap j ";
+		$query .= "where i.image_id = j.image_id ";
+		$query .= "and j.mac_addr = '$mac_addr'";
+		$val = $this->query($query, 1);
+		return $val[0]['image_name'];
+	}
+
+
+	/**
+	 * This function returns all projects
+	 *
+	 * @return Returns an array of the contents 
+	 */
+	function get_projects () {
+		$my_array = array();
+		$query = "select project_id, project_name, description from projectinfo";
+		$val = $this->query($query, 1);
+		if ($this->get_num_rows() == 0) {
+			return 0;
+		}
+#		for ($i = 0; $i < count($val); $i++) {
+#			foreach ($val[$i] as $key => $value) {
+#				array_push($my_array, $value);
+#			}
+#		}
+		return $val;
+	}
+
+	/**
+	 * This function adds a projects
+	 *
+	 * @return Returns string message
+	 * @param  $project_name  
+	 * @param  $description  desc of project
+	 */
+	function add_project ($project_name, $description) {
+		$val = $this->check_dup ("projectinfo", "project_name", $project_name);
+		if ($val < 1) {
+			$query = "insert into projectinfo ";
+			$query .= "(project_name, description) ";
+			$query .= "values ('$project_name', '$description')";
+			$result = mysql_query($query)
+				or die('insert into projectinfo query failed: ' . mysql_error());
+
+			return "Entry added to database";
+		} else {
+			return "Project $project_name exists";
+		}
+	}
+
+	/*
+	 * This function deletes a projects
+	 *
+	 */
+	function del_project($id) {
+		$query = "delete from projectinfo ";
+		$query .= "where project_id = '$id' ";
+		$result = mysql_query($query)
+			or die('Deleting projectinfo query failed: ' . mysql_error());
+	}
+
+	/*
+	 * This function gets all users
+	 *
+	 * @return Returns array of users
+	 */
+	function get_users() {
+		$my_array = array();
+		$query = "select * from userinfo";
+		$val = $this->query($query, 1);
+		if ($this->get_num_rows() == 0) {
+			return 0;
+		}
+		return $val;
+	}
+
+	/*
+	 * This function adds a user
+	 *
+	 * @return Returns string message
+	 */
+	function add_user($surname, $fname, $user_name, $position, $affil, $notes) {
+		$val = $this->check_dup ("userinfo", "user_name", $user_name);
+		if ($val < 1) {
+			$query = "insert into userinfo ";
+			$query .= "(surname, fname, user_name, position, "; 
+			$query .= "affiliation, notes ) ";
+			$query .= "values ('$surname', '$fname', '$user_name', ";
+			$query .= "'$position', '$affil', '$notes')";
+			$result = mysql_query($query)
+				or die('insert into userinfo query failed: ' . mysql_error());
+
+			return "Entry added to database";
+		} else {
+			return "User $fname $surname exists";
+		}
+	}
+
+	/*
+	 * This function deletes a user
+	 *
+	 * @return 
+	 */
+	function del_user($user_id) {
+		$query = "delete from userinfo ";
+		$query .= "where user_id = '$user_id' ";
+		$result = mysql_query($query)
+			or die('Deleting userinfo query failed: ' . mysql_error());
+	}
+
+	/**
+	 * This runs a generic query
+	 *
+	 * @ return 0 on success
+	 */
+	function run_query($query) {
+		$result = mysql_query($query)
+			or die('Query failed: ' . mysql_error() . "\n$query");
+		return $result;
+	}
+
+}
+
+
+?>