def index(self, guestID, guestName): try: if not general.isGoodName(guestName): return 'Name ' + guestName + ' cannot be a guestName, please choose the new one.' infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute( "SELECT `guestID` FROM `guests` WHERE `guestID`=%s" % (guestID)) if cursor.fetchone() == None: db.close() return shortcut.response('error', '', 'no guest found') if guestName == '': db.close() return shortcut.response('error', '', 'invalid guest name') cursor.execute( "UPDATE `guests` SET `guestName`='%s' WHERE `guestID`=%s" % (guestName, guestID)) db.close() except: return shortcut.response( 'error', '', MySQLdb.escape_string(traceback.format_exc())) content = '' return shortcut.response('success', content, 'Your guest has been renamed')
def index(self, taskID): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute( '''SELECT `opcode`,`detail`,`status`,`finishStatus`,`finishMessage`,`createTimestamp`,`finishTimestamp` FROM `tasks` WHERE `taskID`=%s ''' % (str(taskID))) db.close() taskData = cursor.fetchone() if taskData == None: return shortcut.response('error', '', 'taskID not found') templateString = open(setting.MAIN_PATH + 'webapi/template/task_poll.xml').read() content = templateString % { 'taskID': str(taskID), 'opcode': str(taskData[0]), 'detail': taskData[1], 'status': str(taskData[2]), 'finishStatus': str(taskData[3]), 'finishMessage': taskData[4], 'createTimestamp': taskData[5], 'finishTimestamp': taskData[6] } return shortcut.response('success', content)
def index(self, guestID): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() #find hostIPAddress, UUID cursor.execute('''SELECT `hosts`.`IPAddress` , `lastUUID` FROM `hosts` INNER JOIN `guests` ON `hosts`.`hostID`=`guests`.`lastHostID` AND `guests`.`status`=1 AND `guests`.`activity`=0 AND `guests`.`guestID`=%s;''' % (guestID)) targetData = cursor.fetchone() db.close() if targetData == None: return shortcut.response( 'error', '', 'Invalid guestID or Machine was closed or doing activity') hostIP = targetData[0] UUID = targetData[1] result = connection.socketCall(hostIP, setting.LOCAL_PORT, 'guest_send_reboot_signal', [UUID]) if result != "OK": return shortcut.response('error', '', result) #no content return shortcut.response( 'success', '', 'Reboot signal was sending to the guest.')
def index(self, hostID=None): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() if hostID == None: conditionString = "" else: conditionString = "WHERE `hostID`=%s" % (str(hostID)) cursor.execute('''SELECT `hostID`, `IPAddress` FROM `hosts`''' + conditionString + ";") table = cursor.fetchall() if len(table) == 0: return shortcut.response('error', '', 'hostID not found') if hostID == None: argv = [] else: argv = [str(table[0][1])] #IPAddr data = connection.socketCall("localhost", setting.MONITOR_PORT, "get_current_memory_info", argv) data = json.loads(data) templateString = open( setting.MAIN_PATH + 'webapi/template/host_getCurrentMemoryInfo.xml').read() result = '' for row in table: hostDict = {'hostID': str(row[0]), 'IP': str(row[1])} #set default value in case of no data hostDict['memTotal'] = "-" hostDict['memTotalUnit'] = "-" hostDict['memFree'] = "-" hostDict['memFreeUnit'] = "-" for element in data: if element['IP'] == hostDict['IP']: hostDict['memTotal'] = element['memory_info'][ 'MemTotal'][0] hostDict['memTotalUnit'] = element['memory_info'][ 'MemTotal'][1] hostDict['memFree'] = element['memory_info'][ 'MemFree'][0] hostDict['memFreeUnit'] = element['memory_info'][ 'MemFree'][1] break result += templateString % hostDict db.close() return shortcut.response('success', result)
def index(self, guestID): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() #find hostIPAddress, UUID cursor.execute('''SELECT `hosts`.`IPAddress` , `lastUUID` FROM `hosts` INNER JOIN `guests` ON `hosts`.`hostID`=`guests`.`lastHostID` AND `guests`.`status`=1 AND `guests`.`activity`=0 AND `guests`.`guestID`=%s;''' % (guestID)) targetData = cursor.fetchone() db.close() if targetData == None: return shortcut.response( 'error', '', 'Invalid guestID or cannot suspend in this status') hostIP = targetData[0] UUID = targetData[1] result = connection.socketCall(hostIP, setting.LOCAL_PORT, 'guest_get_current_info', [UUID, 'io']) try: result = json.loads(result) except: if type(result) == type('str'): return shortcut.response('error', '', result) else: return shortcut.response('error', '', 'May be network error') rx = result['ioInfo']['rxRate'] wx = result['ioInfo']['wxRate'] sumRx = result['ioInfo']['rxUsed'] sumWx = result['ioInfo']['wxUsed'] content = ''' <guest guestID="%s"> <rx>%s</rx> <wx>%s</wx> <sumRx>%s</sumRx> <sumWx>%s</sumWx> </guest> ''' % (str(guestID), str(rx), str(wx), str(sumRx), str(sumWx)) return shortcut.response('success', content)
def index(self): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute("SELECT `key`,`value` FROM `cloud_variables`") cloudData = cursor.fetchall() valDict = {} for element in cloudData: valDict[element[0]] = element[1] cursor.execute("SELECT `IPAddress` FROM `guest_ip_pool`") poolData = cursor.fetchall() ipList = [] for element in poolData: ipList.append(element[0]) valDict['guestIPPoolList'] = ','.join(ipList) templateString = open(setting.MAIN_PATH + 'webapi/template/cloud_getInfo.xml').read() content = templateString % valDict db.close() return shortcut.response('success', content)
def index(self,templateID=None): infoHost=cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME ) cursor = db.cursor() if templateID==None: conditionString=""; else: conditionString="WHERE `templateID`=%s"%(str(templateID)) cursor.execute('''SELECT `templateID`, `OS`,`size`,`description`,`minimumMemory`,`maximumMemory`,`activity` FROM `templates`'''+conditionString+";") table=cursor.fetchall() db.close() templateString=open(setting.MAIN_PATH+'webapi/template/template_getInfo.xml').read() result='' for row in table: templateDict={ 'templateID':str(row[0]), 'OS':str(row[1]), 'size':str(row[2]), 'description':str(row[3]), 'minimumMemory':str(row[4]), 'maximumMemory':str(row[5]), 'activity':str(row[6]) } result+=templateString%templateDict return shortcut.response('success', result)
def index(self, guestIP, targetHostID=None): #resolve for guestID infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute( "SELECT `guestID` FROM `guests` WHERE `IPAddress`='%s' " % (guestIP)) guestID = cursor.fetchone() db.close() if guestID != None: guestID = guestID[0] else: return shortcut.response('error', '', 'guestIP not found') detail = {'command': 'guest_start', 'guestID': guestID} if targetHostID != None: detail['targetHostID'] = targetHostID taskID = queue.enqueue(detail) return shortcut.responseTaskID(taskID)
def index(self, mode): if mode not in ['0', '1']: return shortcut.response('error', '', 'mode can be 0 or 1 only') infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute( "UPDATE `cloud_variables` SET `value`='%s' WHERE `key`='hold_all_log'" % (mode)) db.close() content = '' return shortcut.response('success', content)
def index(self,fileName,OS,description,minimumMemory,maximumMemory): #number format checking try: if int(minimumMemory)<0 or int(maximumMemory)<int(minimumMemory): return shortcut.response('error', '', 'maximumMemory must larger or equal to minimumMemory') except: return shortcut.response('error', '', 'memory must be integer') infoHost=cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME ) cursor = db.cursor() #search for fileName (must ask to the nfs server) cursor.execute("SELECT `IPAddress` FROM `hosts` WHERE `isStorageHolder`=1") storageHolderIP=cursor.fetchone()[0] result=connection.socketCall(str(storageHolderIP),setting.LOCAL_PORT,'get_file_size',[setting.TEMPLATE_PATH+fileName]) try: fileSize=int(json.loads(result)[0]) if fileSize<=0: return shortcut.response('error', '', 'file not found') except: return shortcut.response('error', '', result) #check replication of fileName cursor.execute("SELECT `fileName` FROM `templates` WHERE `fileName`='%s'"%(fileName)) if cursor.fetchone()!=None: return shortcut.response('error', '', 'fileName was used by other template') #template use different directory with guest #cursor.execute("SELECT `volumeFileName` FROM `guests` WHERE `volumeFileName`='%s'"%(fileName)) #if cursor.fetchone()!=None: # return shortcut.response('error', '', 'fileName was used by a guest') if not fileName.endswith('.img'): return shortcut.response('error', '', 'please set fileName in pattern of something.img format') cursor.execute(''' INSERT INTO `templates` (`fileName`, `OS`, `description`, `minimumMemory`, `maximumMemory`,`size`,`activity`) VALUES ('%(fileName)s', '%(OS)s', '%(description)s', '%(minimumMemory)s', '%(maximumMemory)s', '%(size)s', '%(activity)s'); '''%{ 'fileName':fileName, 'OS':MySQLdb.escape_string(OS), 'description':MySQLdb.escape_string(description), 'minimumMemory':minimumMemory, 'maximumMemory':maximumMemory, 'size':fileSize, 'activity':0, }) templateID=cursor.lastrowid db.close() content='<template templateID="%s" />'%(str(templateID)) return shortcut.response('success', content)
def index(self, hostID, isHost): if isHost != '0' and isHost != '1': return shortcut.response('error', '', 'invalid syntax') infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute("SELECT `isHost` FROM `hosts` WHERE `hostID`=%s" % (hostID)) tmp = cursor.fetchone() if tmp == None: return shortcut.response('error', '', 'hostID not found') if isHost == str(tmp[0]): return shortcut.response('success', '', 'you did not change anything') if isHost == '0': #check many things in this case cursor.execute( "SELECT `hostID` FROM `hosts` WHERE `hostID`<>%s AND `isHost`=1 AND `status`=1 AND `activity`=0" % (hostID)) if cursor.fetchone() == None: return shortcut.response( 'error', '', 'you need at least one active host that have isHost=1 and activity=0' ) detail = {'command': 'host_evacuate_mission', 'hostID': hostID} taskID = queue.enqueue(detail) cursor.execute("UPDATE `hosts` SET `isHost`=%s WHERE `hostID`=%s" % (isHost, hostID)) db.close() result = '' return shortcut.response('success', result)
def index(self): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute("DELETE FROM `oldHostLoad` WHERE 1") cursor.execute("DELETE FROM `oldGuestLoad` WHERE 1") db.close() content = '' return shortcut.response('success', content)
def index(self, hostID, mode): if mode not in ['standby', 'hibernate', 'shutdown']: return shortcut.response('error', '', 'invalid mode') detail = { 'command': 'host_close', 'hostID': hostID, 'mode': mode #{'standby','hibernate','shutdown'} } taskID = queue.enqueue(detail) return shortcut.responseTaskID(taskID)
def index(self,templateID): infoHost=cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME ) cursor = db.cursor() cursor.execute("SELECT `guestID` FROM `guests` WHERE `templateID`=%s"%(str(templateID))) tmp=cursor.fetchone() db.close() if tmp!=None: return shortcut.response('error', '', 'There are guests that use this template') detail={ 'command':'template_remove', 'templateID':templateID } taskID=queue.enqueue(detail) return shortcut.responseTaskID(taskID)
def index(self, guestID=None): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() if guestID == None: conditionString = "" else: conditionString = "WHERE `guestID`=%s" % (str(guestID)) cursor.execute('''SELECT `guestID`, `guestName`,`MACAddress`,`IPAddress`,`templateID`,`lastHostID`,`lastUUID`,`memory`,`vCPU`,`inboundBandwidth`,`outboundBandwidth` FROM `guests`''' + conditionString + ";") table = cursor.fetchall() db.close() templateString = open(setting.MAIN_PATH + 'webapi/template/guest_getInfo.xml').read() result = '' for row in table: guestDict = { 'guestID': str(row[0]), 'guestName': str(row[1]), 'MACAddress': str(row[2]), 'IPAddress': str(row[3]), 'templateID': str(row[4]), 'lastHostID': str(row[5]), 'lastUUID': str(row[6]), 'memory': str(row[7] * 1024 * 1024), #MB to Byte 'vCPU': str(row[8]), 'inboundBandwidth': str(row[9]), 'outboundBandwidth': str(row[10]) } #print "~~~~~~~~~~~~~~~~~~~~~~~" #print templateString #print guestDict #print "#######################" result += templateString % guestDict return shortcut.response('success', result)
def index(self): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() cursor.execute('''SELECT `hostID`, `IPAddress` FROM `hosts` WHERE `isStorageHolder`=1''') hostData = cursor.fetchone() hostID = hostData[0] hostIP = hostData[1] data = connection.socketCall("localhost", setting.MONITOR_PORT, "get_current_storage_info", [hostIP]) data = json.loads(data) if len(data) == 0: errorMessage = "Data is not ready" capacity = errorMessage free = errorMessage image_usage = errorMessage maekin_usage = errorMessage else: data = data[0] capacity = data['storage_info']['capacity'] free = data['storage_info']['free'] image_usage = data['storage_info']['image_usage'] maekin_usage = data['storage_info']['maekin_usage'] content = ''' <capacity>%s</capacity> <maekinUsage>%s</maekinUsage> <imageUsage>%s</imageUsage> <free>%s</free> ''' % (str(capacity), str(maekin_usage), str(image_usage), str(free)) db.close() return shortcut.response('success', content)
def index(self, cpu, memory, network, io, guestIDs): #validate input enables = [cpu, memory, network, io] for element in enables: if element != '1' and element != '0': return shortcut.response( 'error', '', 'invalid parameter (enabler path)') if int(cpu) + int(memory) + int(network) + int(io) == 0: return shortcut.response( 'error', '', 'invalid parameter (nothing to monitor)') guestList = [] if guestIDs != None: for element in guestIDs.split(','): try: guestList.append(str(int(element))) except: return shortcut.response( 'error', '', 'invalid parameter (guestIDs path)') if guestList == []: return shortcut.response('error', '', 'invalid guestIDs') optionList = [] if cpu == '1': optionList.append('cpu') if memory == '1': optionList.append('memory') if network == '1': optionList.append('network') if io == '1': optionList.append('io') infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() #find hostIPAddress, UUID cursor.execute( '''SELECT `hosts`.`IPAddress` , `lastUUID`, `guests`.`guestID` FROM `hosts` INNER JOIN `guests` ON `hosts`.`hostID`=`guests`.`lastHostID` AND `guests`.`status`=1 AND `guests`.`activity`=0 AND `guests`.`guestID` IN (%s);''' % (','.join(guestList))) fetchedData = cursor.fetchall() content = '' for guestID in guestList: inGuest = '' #search guestID in fetchedData selectedData = None for element in fetchedData: if str(element[2]) == str(guestID): selectedData = element break if selectedData == None: content += '<guest guestID="%s" polling="error">cannot get info from this guest. (guest not found or guest is busy)</guest>' % ( str(guestID)) continue hostIP = selectedData[0] UUID = selectedData[1] result = connection.socketCall(hostIP, setting.LOCAL_PORT, 'guest_get_current_info', [UUID] + optionList) try: result = json.loads(result) except: if type(result) == type('str'): content += '<guest guestID="%s" polling="error">cannot get info from this guest. (json convert state)</guest>' % ( str(guestID)) continue else: content += '<guest guestID="%s" polling="error">cannot get info from this guest. (maybe network error)</guest>' % ( str(guestID)) continue if cpu == '1': percent = result['cpuInfo']['usage'] cpuTime = result['cpuInfo']['cpuTime'] inGuest += ''' <cpuInfo guestID="%s"> <average>%s</average> <cpuTime>%s</cpuTime> </cpuInfo> ''' % (str(guestID), percent, cpuTime) if memory == '1': memTotal = result['memoryInfo']['total'] memUsage = result['memoryInfo']['usage'] inGuest += ''' <memoryInfo guestID="%s"> <memTotal>%s</memTotal> <memUse>%s</memUse> </memoryInfo> ''' % (str(guestID), str(memTotal), str(memUsage)) if network == '1': rx = result['networkInfo']['rxRate'] tx = result['networkInfo']['txRate'] sumRx = result['networkInfo']['rxUsed'] sumTx = result['networkInfo']['txUsed'] inGuest += ''' <networkInfo guestID="%s"> <rx>%s</rx> <tx>%s</tx> <sumRx>%s</sumRx> <sumTx>%s</sumTx> </networkInfo> ''' % (str(guestID), str(rx), str(tx), str(sumRx), str(sumTx)) if io == '1': rx = result['ioInfo']['rxRate'] wx = result['ioInfo']['wxRate'] sumRx = result['ioInfo']['rxUsed'] sumWx = result['ioInfo']['wxUsed'] inGuest += ''' <ioInfo guestID="%s"> <rx>%s</rx> <wx>%s</wx> <sumRx>%s</sumRx> <sumWx>%s</sumWx> </ioInfo> ''' % (str(guestID), str(rx), str(wx), str(sumRx), str(sumWx)) content += '<guest guestID="%s" polling="success">%s</guest>' % ( str(guestID), inGuest) return shortcut.response('success', content)
def index(self, guestID, inbound=None, outbound=None): try: infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() #checking parameter cursor.execute( "SELECT `guestID` FROM `guests` WHERE `guestID`=%s" % (guestID)) if cursor.fetchone() == None: db.close() return shortcut.response('error', '', 'no guest found') if inbound == None and outbound == None: db.close() return shortcut.response( 'error', '', 'please set parameter inbound or outbound') if inbound not in [None, 'infinite']: try: tmp = int(inbound) except: db.close() return shortcut.response('error', '', 'invalid parameter inbound') if outbound not in [None, 'infinite']: try: tmp = int(outbound) except: db.close() return shortcut.response('error', '', 'invalid parameter outbound') #set value in database if inbound != None: if inbound == 'infinite': cursor.execute( "UPDATE `guests` SET `inboundBandwidth`=NULL WHERE `guestID`=%s" % (guestID)) else: cursor.execute( "UPDATE `guests` SET `inboundBandwidth`=%s WHERE `guestID`=%s" % (inbound, guestID)) if outbound != None: if outbound == 'infinite': cursor.execute( "UPDATE `guests` SET `outboundBandwidth`=NULL WHERE `guestID`=%s" % (guestID)) else: cursor.execute( "UPDATE `guests` SET `outboundBandwidth`=%s WHERE `guestID`=%s" % (outbound, guestID)) db.close() except: return shortcut.response( 'error', '', MySQLdb.escape_string(traceback.format_exc())) content = '' return shortcut.response( 'success', content, "Your guest's bandwidth will be changed when you're turning it on" )
def index(self): content=''' <token>hello</token> ''' return shortcut.response('success', content, "this is a token")
def index(self, guestID=None): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() if guestID != None: condition = " WHERE `guestID`=%s" % (str(guestID)) else: condition = "" cursor.execute( "SELECT `status`, `activity`, `guestID`, `guestName` FROM `guests`" + condition) guestDataList = cursor.fetchall() content = '' templateString = open(setting.MAIN_PATH + 'webapi/template/guest_getState.xml').read() for oldData in guestDataList: status = oldData[0] activity = oldData[1] currentGuestID = oldData[2] currentGuestName = oldData[3] if status != 1: # No need to update status runningState = 0 elif status == 1: # real status can be 0, must be update #find hostIPAddress, UUID cursor.execute('''SELECT `hosts`.`IPAddress` , `lastUUID` FROM `hosts` INNER JOIN `guests` ON `hosts`.`hostID`=`guests`.`lastHostID` AND `guests`.`status`=1 AND `guests`.`guestID`=%s;''' % (currentGuestID)) lastData = cursor.fetchone() print lastData if lastData != None: hostIP = lastData[0] UUID = lastData[1] if hostIP != None and UUID != None: guestStatus = connection.socketCall( hostIP, setting.LOCAL_PORT, 'guest_update_status', [UUID, str(currentGuestID)]) try: guestStatus = json.loads(guestStatus) status = guestStatus['status'] runningState = guestStatus['runningState'] except: return shortcut.response( 'error', '', guestStatus) else: return shortcut.response( 'error', '', 'hostIP & UUID was made to be NULL before (it is bug)' ) else: return shortcut.response('error', '', 'Invalid guestID') else: return shortcut.response('error', '', 'Status error (bug sure)') stateDict = { 'guestID': currentGuestID, 'guestName': currentGuestName, 'status': status, 'activity': activity, 'runningState': runningState } content += templateString % stateDict return shortcut.response('success', content)
def index(self, hostID=None): #get data from database infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() if hostID == None: conditionString = "" else: conditionString = "WHERE `hostID`=%s" % (str(hostID)) cursor.execute('''SELECT `hostID`, `hostName`,`status`,`activity`,`MACAddress`,`IPAddress`,`isHost`,`isGlobalController`,`isInformationServer`,`isStorageHolder`,`isCA` FROM `hosts`''' + conditionString + ";") table = cursor.fetchall() if len(table) == 0: return shortcut.response('error', '', 'hostID not found') if hostID == None: argv = [] else: argv = [str(table[0][5])] #IPAddr specData = connection.socketCall("localhost", setting.MONITOR_PORT, "get_host_spec", argv) #print "#############specData##############" #print specData specData = json.loads(specData) templateString = open(setting.MAIN_PATH + 'webapi/template/host_getInfo.xml').read() result = '' for row in table: hostDict = { 'hostID': str(row[0]), 'hostName': str(row[1]), 'status': str(row[2]), 'activity': str(row[3]), 'MAC': str(row[4]), 'IP': str(row[5]), 'isHost': str(row[6]), 'isGlobalController': str(row[7]), 'isInformationServer': str(row[8]), 'isNFSServer': str(row[9]), 'isCA': str(row[10]) } specFound = False for element in specData: if element['IP'] == hostDict['IP']: hostDict['mem_size'] = element['spec']['memory'][ 'size'] hostDict['mem_type'] = element['spec']['memory'][ 'type'] hostDict['mem_speed'] = element['spec']['memory'][ 'speed'] hostDict['cpu_number'] = element['spec']['cpu'][ 'number'] hostDict['cpu_model'] = element['spec']['cpu']['model'] hostDict['cpu_cache'] = element['spec']['cpu']['cache'] hostDict['cpu_speed'] = element['spec']['cpu']['speed'] specFound = True break if not specFound: errorMessage = "Data is not ready" hostDict['mem_size'] = errorMessage hostDict['mem_type'] = errorMessage hostDict['mem_speed'] = errorMessage hostDict['cpu_number'] = errorMessage hostDict['cpu_model'] = errorMessage hostDict['cpu_cache'] = errorMessage hostDict['cpu_speed'] = errorMessage result += templateString % hostDict db.close() return shortcut.response('success', result)
def index(self, hostID=None): infoHost = cacheFile.getDatabaseIP() db = MySQLdb.connect(infoHost, setting.DB_USERNAME, setting.DB_PASSWORD, setting.DB_NAME) cursor = db.cursor() if hostID == None: conditionString = "" else: conditionString = "WHERE `hostID`=%s" % (str(hostID)) cursor.execute('''SELECT `hostID`, `IPAddress` FROM `hosts`''' + conditionString) table = cursor.fetchall() if len(table) == 0: return shortcut.response('error', '', 'hostID not found') if hostID == None: argv = [] else: argv = [str(table[0][1])] #IPAddr data = connection.socketCall("localhost", setting.MONITOR_PORT, "get_current_info", argv) data = json.loads(data) cpuTemplateString = open( setting.MAIN_PATH + 'webapi/template/host_getCurrentCPUInfo.xml').read() memoryTemplateString = open( setting.MAIN_PATH + 'webapi/template/host_getCurrentMemoryInfo.xml').read() networkTemplateString = open( setting.MAIN_PATH + 'webapi/template/host_getCurrentNetworkInfo.xml').read() storageTemplateString = open( setting.MAIN_PATH + 'webapi/template/host_getCurrentStorageInfo.xml').read() result = '' for row in table: inHost = '' hostDict = {'hostID': str(row[0]), 'IP': str(row[1])} #search for current element in data currentData = None for element in data: if element['IP'] == hostDict['IP']: currentData = element if currentData == None: result += '<host hostID="%s" polling="error">Info not found</host>' % ( str(row[0])) continue #cpuInfo percent_list = currentData['cpu_info'] total = 0.0 for p in percent_list: total += float(p) hostDict['average'] = str(total / float(len(percent_list))) inHost += cpuTemplateString % hostDict #memoryInfo hostDict['memTotal'] = currentData['memory_info']['MemTotal'][ 0] hostDict['memTotalUnit'] = currentData['memory_info'][ 'MemTotal'][1] hostDict['memFree'] = currentData['memory_info']['MemFree'][0] hostDict['memFreeUnit'] = currentData['memory_info'][ 'MemFree'][1] inHost += memoryTemplateString % hostDict #networkInfo for interface in currentData['network_info']: if interface['interface'] == 'eth0': hostDict['transmit_rate'] = interface['tx'] hostDict['recieve_rate'] = interface['rx'] break inHost += networkTemplateString % hostDict #storageInfo hostDict['capacity'] = currentData['storage_info']['capacity'] hostDict['free'] = currentData['storage_info']['free'] hostDict['maekin_usage'] = currentData['storage_info'][ 'maekin_usage'] hostDict['image_usage'] = currentData['storage_info'][ 'image_usage'] inHost += storageTemplateString % hostDict result += '<host hostID="%s" polling="success">%s</host>' % ( str(row[0]), inHost) db.close() return shortcut.response('success', result)