def run(): while 1: cmd = input('input command (ex. Get index.html): ') cmd = cmd.split() if cmd[0] == 'exit': # type exit to exit break # Request command to server if cmd[0] == 'POST': try: server = 'http://' + XmlParser.agentIP( ) + ':' + XmlParser.agentPORT() print(server) #server='http://127.0.0.1:81' print('sending to ip:', server) AgentPORT = XmlParser.agentPORT() print('Sending to port:', AgentPORT) payload = {'POST': 'SEND POST DATA FROM SERVER'} r = requests.post(server, json=payload) print(r.text) except IOError: print(IOError) if cmd[0] == 'GET': try: server = 'http://' + XmlParser.agentIP() print('Server ip is:', server) AgentPORT = XmlParser.agentPORT() print('Server port is:', AgentPORT) payload = {'some': 'data'} r = requests.get(server, json=payload) print(r.text) except IOError: print(IOError)
def run_server(): serverIP = XmlParser.serverIP() serverPORT = XmlParser.serverPORT() print('Server address is:', serverIP, ':', serverPORT) server_address = (serverIP, int(serverPORT)) httpd = ThreadedHTTPServer(serverIP, int(serverPORT), request_handler=myHTTPRequstHandler) print('~~~~~~~~~ Server is online - welcome to SKYNET~~~~~~~~~') httpd.server_thread.start()
def main(argv): '''Usage python prsxmlparser.py input output ''' if len(argv) == 3: if '.xml' in argv[2]: XmlParser.start(argv[2], argv[1]) if '.prs' in argv[2]: PrsParser.start(argv[1], argv[2]) else: print(main.__doc__)
def run(): print('Starting Agent..please hold..') agentIP = XmlParser.agentIP() print(agentIP) agentPORT = XmlParser.agentPORT() print(agentPORT) server_address = (agentIP, int(agentPORT)) # httpd = HTTPServer(server_address, myHTTPRequstHandler) httpd = ThreadedHTTPServer(agentIP,int(agentPORT),request_handler=myHTTPRequstHandlerAgent) # print('~~~~~~~~~ Agent',XmlParser.agentID(args.agentid),' is online - welcome to SKYNET~~~~~~~~~') print('~~~~~~~~~ Agent', XmlParser.agentID('1'), ' is online - welcome to SKYNET~~~~~~~~~') httpd.server_thread.start()
def TempUpdate() -> None: resources = ParlamentResources() database = DatabaseConnector() parser = XmlParser() sessionsXml = resources.GetData('seimo_sesijos?ar_visos=T') sessions = parser.ParseSessionsFromXml(sessionsXml) for s in sessions: meetingsXml = resources.GetData('seimo_posedziai?sesijos_id=' + s.Id) meetingDocuments = parser.ParseMeetingDocumentsFromXml(meetingsXml) database.WriteToDatabase(meetingDocuments, 'Meetings', meetingDocumentMap, ['MeetingId', 'Value'])
def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) # gets defined in the UI file l = QVBoxLayout(self.graph) self.dc = PlanCanvas(self.graph, width=10, height=4, dpi=100) l.addWidget(self.dc) self.robthread = RobThreadClass() self.robthread.start() self.robthread.date_signal.connect(self.showdate) self.robthread.shift_num_signal.connect(self.showshift) self.hours = ['07:20-08:00', '08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00'] self.robthread.graph_signal.connect(self.plot) self.robthread.hours_signal.connect(self.hours_show) self.robthread.plan_signal.connect(self.show_plan) self.robthread.bdt_signal.connect(self.show_bdt) config = XmlParser.ConfigParse(config_file) logopixmap = QPixmap(config.logopicture()) self.label_2.setText(config.logotext()) h = self.logo.height() w = self.logo.width() self.logo.setPixmap(logopixmap.scaled(w, h, QtCore.Qt.KeepAspectRatio))
def setMembershipListXml(self, xml): '''modify the structure with a new MembershipList xml if it is the first xml that you send, send first the dynamic items''' self.contactManager.lists['Allow'] = [] self.contactManager.lists['Block'] = [] self.contactManager.lists['Reverse'] = [] self.contactManager.lists['Pending'] = [] #ml = minidom.parseString(xml) ml = XmlParser.MembershipParser(xml) for i in ml.memberships: memberRole = i['MemberRole'] for j in i['Members']: try: email = j['PassportName'].lower() if email not in self.contactManager.lists[memberRole]: self.contactManager.lists[memberRole].append(email) else: pass if memberRole == 'Pending' and 'DisplayName' in j: self.contactManager.pendingNicks[email] = \ j['DisplayName'] except Exception, e: pass
def Setup(interfaceParams): # Declare global (module-scope) variables. global sensorList # Parse the XML file to get the information regarding the sensors to test. # Validate file containing sensors to monitor. sensorListFile = Config.sensorListXmlFile # File containing list of sensors to monitor. if (not os.path.isfile(sensorListFile)): UtilLogger.verboseLogger.error( "SensorReadingStressTest.py: File path " + sensorListFile + " is invalid.") return False xmlParserObj = XmlParser.XmlParser(sensorListFile) if not xmlParserObj.root: UtilLogger.verboseLogger.error("SensorReadingStressTest.py - XmlParser: " + \ "failed to parse sensor list XML file.") return False # Store info regarding all sensors to be monitored in sensorList. for sensorEntry in xmlParserObj.root: sensorName = sensorEntry.attrib["name"] nominalValue = sensorEntry.attrib["nominal"] tolerance = sensorEntry.attrib["tolerance"] gotSensorIdSuccess, sensorId = IpmiUtil.GetIpmiUtilSensorId( interfaceParams, sensorName) if (not gotSensorIdSuccess): UtilLogger.verboseLogger.error("SensorReadingStressTest.py - Setup(): " + \ "Failed to get sensor ID for sensor '%s'." % sensorName) return False sensorList.append( (sensorName, sensorId, float(nominalValue), float(tolerance))) return True
def search(request): if request.method == 'POST': # If the form has been submitted... product = str(request.POST['product']) # look for variable product in POST results = DoRequest.findByKeyword(product) # get the results for the search items = XmlParser.processMessage(results) return render_to_response('searchResults.html', {'items': items, 'searchTerm': product}) else: return render_to_response('home.html')
def ValidateGPIOslotID(expectedData): global gpioTestPassOrFail, fileName global GPIOLen try: # remove two bits (bits [5:0] in the response) IPMISlotIDdataFilter = expectedData & 0x3f # incode to GPIO slot ID (PMDU_NODE_INCODE dictionary) SlotIdIncode = PMDU_NODE_INCODE.get(IPMISlotIDdataFilter) # GPIO slot ID binary bits GPIOSlotIDBin = "{0:06b}".format(SlotIdIncode) GPIOSlotID = list(GPIOSlotIDBin) # read slot id gpio definition from getgpioslotid.xml xmlParserObj = XmlParser.XmlParser(Config.J2010getGpioSlotIDFilePath) if not xmlParserObj.root: UtilLogger.verboseLogger.error(("[GPIOgetTest error]%s: failed to parse Xml file. Will not execute test." %(fileName))) return False gpioTestPassOrFail = True GPIOLen = len(GPIOSlotID) # Verify Get GPIO for each GPIO number listed in XML for gpioInfo in xmlParserObj.root: signal = gpioInfo.attrib['signal'] gpio_pin = gpioInfo.attrib['gpio_pin'] UtilLogger.verboseLogger.info("[GPIOgetTest info]%s: running Execute for Signal %s and gpio_pin %s" %(fileName, signal, gpio_pin)) execCmds = ['\n'] execCmds.append("gpioutil -p %s\n" %(gpio_pin)) expectedSlotId = GPIOSlotID[GPIOLen-1] regexPattern = r'(\d)\s+j2010' (execPassOrFail, sshOutputs, parsedCmdOutputs) = Ssh.sshExecuteCommand( execCmds, username=Config.bmcUser, password=Config.bmcPassword, expectedOutput = expectedSlotId, regExpPattern = regexPattern ) gpioTestPassOrFail &= execPassOrFail if (execPassOrFail): #timeout or channel not ready, it don't judge the result correct or not actualSlotId = parsedCmdOutputs if not actualSlotId: UtilLogger.verboseLogger.error("%s: Signal Slot ID failed: Actual Slot Id was returned an empty string" %(fileName)) gpioTestPassOrFail = False if (actualSlotId == expectedSlotId): UtilLogger.verboseLogger.info("%s: Signal Slot ID successful: '%s'; Slot ID value: %s" %(fileName, signal, parsedCmdOutputs)) else: UtilLogger.verboseLogger.error("%s: failed: %s slot ID is not correct " %(fileName, signal)) gpioTestPassOrFail = False else: UtilLogger.verboseLogger.error("%s: failed to find '%s' in response" %(fileName, signal)) gpioTestPassOrFail = False GPIOLen = GPIOLen-1 except Exception, e: UtilLogger.verboseLogger.error( fileName + ": Test failed with exception - " + str(e)) gpioTestPassOrFail = False
def Execute(interfaceParams): global testPassOrFail, fileName # Parse Get Gpio List xml file try: xmlParserObj = XmlParser.XmlParser(Config.G50getGpioListFilePath) if not xmlParserObj.root: UtilLogger.verboseLogger.error(("%s: failed to parse Xml file. Will not execute test." %(fileName))) return False testPassOrFail = True # Verify Get GPIO for each GPIO number listed in XML for gpioInfo in xmlParserObj.root: testPassOrFail &= True signal = gpioInfo.attrib['signal'] theDirection = [] theDirection = gpioInfo.attrib['direction'].split(',') expectedDirection = theDirection[0] UtilLogger.verboseLogger.info("%s: running Execute for Signal %s" %(fileName, signal)) execCmds = ['\n'] execCmds.append("gpioutil -n %s\n" %(signal)) # Get GPIO Pin Direction regexPattern = r"DIRECTION: (\w+)" (execPassOrFail, sshOutputs, parsedCmdOutputs) = Ssh.sshExecuteCommand( execCmds, username=Config.bmcUser, password=Config.bmcPassword, expectedOutput = expectedDirection, regExpPattern = regexPattern ) testPassOrFail &= execPassOrFail if (execPassOrFail): actualDirection = parsedCmdOutputs if not actualDirection: UtilLogger.verboseLogger.error("%s: Signal Direction failed: Actual Direction was returned an empty string" %(fileName)) testPassOrFail = False continue # Note: pinDirection may contain several directions, seperated by # a comma (i.e. "in,falling") pinDirections = expectedDirection.split(',') for pinDirection in pinDirections: # Validate GPIO pin direction if pinDirection.strip() == actualDirection: UtilLogger.verboseLogger.info("%s: Signal Direction successful: '%s'; Direction: %s" %(fileName, signal, actualDirection)) break if pinDirection == pinDirections[-1]: UtilLogger.verboseLogger.error("%s: Signal Direction failed : '%s'; Actual Direction: %s; Expected Direction(s): %s" %(fileName, signal, actualDirection, ','.join(pinDirections))) testPassOrFail = False else: UtilLogger.verboseLogger.error("%s: failed to find '%s' in response" %(fileName, signal)) testPassOrFail = False except Exception, e: UtilLogger.verboseLogger.error( fileName + ": Test failed with exception - " + str(e)) testPassOrFail = False
def create_emu(): ''' Create emulation by POSTing xml with required parameters ''' response.set_header('Content-Type', 'application/vnd.bonfire+xml') response.set_header('Accept', '*/*') response.set_header('Allow', 'GET, HEAD, POST') #http://10.55.164.232:8050/emulations xml_stream = request.files.data xml_stream_body = request.body.read() xml_stream_body = urllib.unquote(xml_stream_body).decode('utf8') xml_stream_body = xml_stream_body.replace(unicode("+"), unicode(" ")) searchString = "&runifOverloaded=" searchIndex = xml_stream_body.rfind(searchString) runIfOverloaded = False if (searchIndex > 0): runIfOverloadedChar = xml_stream_body[searchIndex + len(searchString)] xml_stream_body = xml_stream_body[4:searchIndex] if (runIfOverloadedChar.upper() == "Y"): runIfOverloaded = True if xml_stream: #print "File data detected:\n",xml_stream return xml_stream try: (emulationName, emulationType, emulationLog, emulationLogFrequency, resourceTypeEmulation, startTimeEmu, stopTimeEmu, distroList, xmlData, MQproducerValues) = XmlParser.xmlFileParser( xml_stream, runIfOverloaded) if ("Re-send with force (-f)" in distroList[0]): response.status = 500 ET.register_namespace("test", "http://127.0.0.1/cocoma") emuError = ET.Element('Force-Errors') emuError = ET.Element('Force-Errors', { 'xmlns': 'http://127.0.0.1/cocoma', 'href': '/emulations/' }) for forceError in distroList: forceErrorXML = ET.SubElement(emuError, "error") forceErrorXML.text = str(forceError) return prettify(emuError) except Exception, e: print e if str(e).find("no attribute 'getElementsByTagName'" ) > 0: #Return if supplied XML is bad e = "Supplied xml is malformed, check thoroughly for errors" response.status = 500 emuError = ET.Element('error') emuError.text = str(e) return prettify(emuError)
def start_test(): ''' Execute an existing emulation XML from "/tests" folder ''' ET.register_namespace("test", "http://127.0.0.1/cocoma") response.set_header('Content-Type', 'application/vnd.bonfire+xml') response.set_header('Accept', '*/*') response.set_header('Allow', 'GET, HEAD, POST') emulationID = "" fileName_stream = request.files.data fileName_stream_body = request.body.read() if fileName_stream: try: filename = HOMEPATH + "/tests/" + str(fileName_stream_body) #check if file exists maybe? except Exception, e: print e response.status = 400 return "<error>" + str(e) + "</error>" #print "File data detected:\n",fileName_stream #return fileName_stream try: (emulationName, emulationType, emulationLog, emulationLogFrequency, emulationLogLevel, resourceTypeEmulation, startTimeEmu, stopTimeEmu, distroList, xmlData, MQproducerValues) = XmlParser.xmlFileParser(filename, True) if startTimeEmu.lower() == "now": startTimeEmu = Library.emulationNow(2) emulationID = EmulationManager.createEmulation( emulationName, emulationType, emulationLog, emulationLogFrequency, emulationLogLevel, resourceTypeEmulation, startTimeEmu, stopTimeEmu, distroList, xmlData, MQproducerValues) else: emulationID = EmulationManager.createEmulation( emulationName, emulationType, emulationLog, emulationLogFrequency, emulationLogLevel, resourceTypeEmulation, startTimeEmu, stopTimeEmu, distroList, xmlData, MQproducerValues) except Exception, e: print e response.status = 400 return "<error>Cannot parse:" + str(e) + "</error>"
def Setup(interfaceParams): global fileName UtilLogger.verboseLogger.info("%s: running Setup fxn" % (fileName)) # Test Variable sensorListFile = Config.J2010sensorListXmlFile xmlParserObj = XmlParser.XmlParser(sensorListFile) if not xmlParserObj.root: UtilLogger.verboseLogger.error( "SensorReadingStressTest.py - XmlParser: failed to parse sensor list XML file." ) return False return True
def readSMFDConfigFiles(self): smfd_cfg_path = self.configMng.getConfValue("PATH", "SMFD_AFDX_CFG_FOLDER") smfd_cfg_files = self.configMng.getItems("SMFD_AFDX_CFG_FILES") smfd_cfg_path = FileManager.joinPath(FileManager.getCurrentPath(), smfd_cfg_path) self.logMng.infoMesg("Read SMFD config files") for (smfd_id, cfg_file_name) in smfd_cfg_files: self.logMng.infoMesg("Read %s", cfg_file_name) self.smfdAfdxCfgPathDict[smfd_id] = {} self.smfdAfdxCfgPathDict[smfd_id]["path"] = FileManager.joinPath( smfd_cfg_path, cfg_file_name) self.smfdAfdxCfgPathDict[smfd_id]["xml"] = XmlParser.XmlParser() self.smfdAfdxCfgPathDict[smfd_id]["xml"].makeNormalizeXmlFile( self.smfdAfdxCfgPathDict[smfd_id]["path"])
def __init__(self): self.logMng = LoggingManager.LogHandler("CfgGen") self.logMng.logLevel("DEBUG") self.logMng.attachedStreamHandler() self.logMng.attachedFileHandler("CfgGen.log") self.logMng.infoMesg("Initialize AFDXConfigGenerator") self.configMng = ConfigManager.ConfigHandler() self.configMng.loadConfig("afdx_switch.conf") self.xmlParserMng = XmlParser.XmlParser() self.switchPortInfoList = [] self.smfdCfgFileList = [] self.smfdAfdxCfgPathDict = {} self.loadAFDXSwitchInfo()
def Setup(interfaceParams): # Declare global (module-scope) variables. global sensorList # Parse the XML file to get the information regarding the sensors to test. # Validate file containing sensors to monitor. sensorListFile = Config.thresholdSensorListXmlFile # File containing list of threshold sensors to monitor. if (not os.path.isfile(sensorListFile)): UtilLogger.verboseLogger.error("SensorThresholdStressTest.py: File path " + sensorListFile + " is invalid.") return False xmlParserObj = XmlParser.XmlParser(sensorListFile) if not xmlParserObj.root: UtilLogger.verboseLogger.error("SensorThresholdStressTest.py - XmlParser: " + \ "failed to parse sensor list XML file.") return False # Store info regarding all sensors to be monitored in sensorList. for sensorEntry in xmlParserObj.root: sensorName = sensorEntry.attrib["name"] gotSensorIdSuccess, sensorId = IpmiUtil.GetIpmiUtilSensorId(interfaceParams, sensorName) if (not gotSensorIdSuccess): UtilLogger.verboseLogger.error("SensorThresholdStressTest.py - Setup(): " + \ "Failed to get sensor ID for sensor '%s'." % sensorName) return False sensorInfo = IpmiUtil.SdrInfo([ sensorId[2] + sensorId[3], \ sensorId[0] + sensorId[1] ], sensorName, interfaceParams) updatePassOrFail = sensorInfo.UpdateSdrInfo(interfaceParams) # Update SDR Info for sensor if updatePassOrFail: UtilLogger.verboseLogger.info("SensorThresholdStressTest.py - Setup(): " + \ "Successfully received sensor thresholds for sensor '%s'." % sensorName) else: UtilLogger.verboseLogger.error("SensorThresholdStressTest.py - Setup(): " + \ "Failed to get sensor thresholds for sensor '%s'." % sensorName) sensorList.append((sensorName, sensorId, sensorInfo)) return True
def main(argv): opts, args = getopt.getopt(argv, "n:x:") optimal = True path = None for opt, arg in opts: if opt == "-x": path = arg elif opt == "-n": optimal = False problem = XmlParser.xml2problem(path) if not optimal: res = execute_test_multi(problem, optimal) else: res = execute_test_optimal(problem, optimal) if res == None: print 'soluzione non trovata' else: save_result(res)
return "<error>Cannot parse:"+str(e)+"</error>" else: #print "xml_stream_body:\n",fileName_stream_body try: filename=HOMEPATH+"/tests/"+str(fileName_stream_body) #check if file exists maybe? except Exception,e: print e response.status = 400 return "<error>Cannot parse body:"+str(e)+"</error>" #print "Body data detected:\n", filename try: (emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData, MQproducerValues) = XmlParser.xmlFileParser(filename, True) if startTimeEmu.lower() =="now": startTimeEmu = Library.emulationNow(2) emulationID=EmulationManager.createEmulation(emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData, MQproducerValues) else: emulationID=EmulationManager.createEmulation(emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData, MQproducerValues) except Exception,e: print e response.status = 400 return "<error>"+str(e)+"</error>" #Location: http://10.55.164.154:8050/results/2-CPU-dis-1 paramsArray=re.split(r"-",str(emulationID)) if isStr(paramsArray[0]):
def _VerifySelAgainstXmlList(interfaceParams, selListXml): # Validate input parameters. assert selListXml != None assert os.path.isfile(selListXml) # Initialize results. selPassOrFail = False unexpectedSels = None # Get Sel entries cmdPassOrFail, LogFromZipFile = _GetAndUnZip() if cmdPassOrFail: cmdPassOrFail, BMCLogs, BMCLogsNumber = LogParser(LogFromZipFile) else: return selPassOrFail, unexpectedSels if cmdPassOrFail: UtilLogger.verboseLogger.info("%s: Get log data success!" % (fileName)) else: UtilLogger.verboseLogger.error("%s: Parsing log failed!" % (fileName)) return selPassOrFail, unexpectedSels actualSelList = [] for Log in BMCLogs: actualSelList.append(Log['Message']) # Validate the returned SEL log events against list of SEL events # in input selListXml. selReqList = [] # List containing all required SEL events. # Each element in the list is a nested list [Event_Text, duplicate], # where Event_Text is an SEL event as a string, and duplicate # is an integer indicating whether the event is allowed to be # used as a duplicate or not (-1: allow as duplicate, 1: only # use once (no duplicate, hasn't been used yet), 0: can no longer # be used (no duplicate, already used once). selOptList = [] # List containing all optional SEL events. # Each element in the list is a nested list [Event_Text, duplicate], # where Event_Text is an SEL event as a string, and duplicate # is an integer indicating whether the event is allowed to be # used as a duplicate or not (-1: allow as duplicate, 1: only # use once (no duplicate, hasn't been used yet), 0: can no longer # be used (no duplicate, already used once). # Parse the input XML file to get selReqList and selOptList. xmlParserObj = XmlParser.XmlParser(selListXml) if not xmlParserObj.root: UtilLogger.verboseLogger.error("%s: failed to parse input XML file." % (fileName)) return selPassOrFail, unexpectedSels for selEntry in xmlParserObj.root: required = (selEntry.attrib["required"] == "true") selText = selEntry.attrib["contains"] allowDupl = (selEntry.attrib["allowduplicates"] == "true") if required: # Required event log. if allowDupl: selReqList.append([selText, -1]) else: selReqList.append([selText, 1]) else: # Optional event log. if allowDupl: selOptList.append([selText, -1]) else: selOptList.append([selText, 1]) # Ready to do the validation. # Verify whether all required event logs are in the list of actual event logs. AreAllReqIn = True # Indicates wether all required events were found (True) in # list of actual event or not (False). for event in selReqList: IsEventIn = False for actualEvent in actualSelList: if event[0] in actualEvent: IsEventIn = True break if not IsEventIn: AreAllReqIn = False break # Verify whether all actual events are either required or optional and nothing # else. AreAllActualIn = True # Indicates whether all actual events are either required # or optional and nothing else (True) or not (False). unexpectedSels = [] selValidList = selReqList + selOptList for event in actualSelList: IsEventIn = False for validEvent in selValidList: if validEvent[0] in event: if validEvent[1] == 0: break # Event already matched and cannot be duplicate, hence cannot # be matched again. # This SEL record (variable event) is a duplicate. if validEvent[1] == 1: validEvent[ 1] = 0 # Mark event as already matched and no duplicate # is allowed. IsEventIn = True break if not IsEventIn: AreAllActualIn = False unexpectedSels.append(event) # We don't break here in order to find all unexpected SEL events. # Ready to return results. if AreAllReqIn and AreAllActualIn: selPassOrFail = True unexpectedSels = None elif not AreAllActualIn: selPassOrFail = False else: # AreAllActualIn = True, AreAllReqIn = False. selPassOrFail = False unexpectedSels = None return selPassOrFail, unexpectedSels
try: filename = HOMEPATH + "/tests/" + str(fileName_stream_body) #check if file exists maybe? except Exception, e: print e response.status = 400 return "<error>Cannot parse body:" + str(e) + "</error>" #print "Body data detected:\n", filename try: (emulationName, emulationType, emulationLog, emulationLogFrequency, emulationLogLevel, resourceTypeEmulation, startTimeEmu, stopTimeEmu, distroList, xmlData, MQproducerValues) = XmlParser.xmlFileParser(filename, True) if startTimeEmu.lower() == "now": startTimeEmu = Library.emulationNow(2) emulationID = EmulationManager.createEmulation( emulationName, emulationType, emulationLog, emulationLogFrequency, emulationLogLevel, resourceTypeEmulation, startTimeEmu, stopTimeEmu, distroList, xmlData, MQproducerValues) else: emulationID = EmulationManager.createEmulation( emulationName, emulationType, emulationLog, emulationLogFrequency, emulationLogLevel, resourceTypeEmulation, startTimeEmu, stopTimeEmu, distroList, xmlData, MQproducerValues) except Exception, e:
def start_test(): ''' Execute an existing emulation XML from "/tests" folder ''' ET.register_namespace("test", "http://127.0.0.1/cocoma") response.set_header('Content-Type', 'application/vnd.bonfire+xml') response.set_header('Accept', '*/*') response.set_header('Allow', 'GET, HEAD, POST') emulationID="" fileName_stream =request.files.data fileName_stream_body =request.body.read() if fileName_stream: try: filename=HOMEPATH+"/tests/"+str(fileName_stream_body) #check if file exists maybe? except Exception,e: print e response.status = 400 return "<error>"+str(e)+"</error>" #print "File data detected:\n",fileName_stream #return fileName_stream try: (emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData, MQproducerValues) = XmlParser.xmlFileParser(filename, True) if startTimeEmu.lower() =="now": startTimeEmu = Library.emulationNow(2) emulationID=EmulationManager.createEmulation(emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData, MQproducerValues) else: emulationID=EmulationManager.createEmulation(emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData, MQproducerValues) except Exception,e: print e response.status = 400 return "<error>Cannot parse:"+str(e)+"</error>"
def __init__(self): super(self.__class__, self).__init__() self.config = XmlParser.ConfigParse(config_file) self.rob = RobClient.Client(self.config.ip(), self.config.port())
def create_emu(): ''' Create emulation by POSTing xml with required parameters ''' response.set_header('Content-Type', 'application/vnd.bonfire+xml') response.set_header('Accept', '*/*') response.set_header('Allow', 'GET, HEAD, POST') #http://10.55.164.232:8050/emulations xml_stream =request.files.data xml_stream_body =request.body.read() xml_stream_body=urllib.unquote(xml_stream_body).decode('utf8') xml_stream_body = xml_stream_body.replace(unicode("+"), unicode(" ")) searchString = "&runifOverloaded=" searchIndex = xml_stream_body.rfind(searchString) runIfOverloaded = False if (searchIndex > 0): runIfOverloadedChar = xml_stream_body[searchIndex+len(searchString)] xml_stream_body = xml_stream_body [4:searchIndex] if (runIfOverloadedChar.upper() == "Y"): runIfOverloaded = True if xml_stream: #print "File data detected:\n",xml_stream return xml_stream try: (emulationName,emulationType,emulationLog,emulationLogFrequency, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData, MQproducerValues) = XmlParser.xmlFileParser(xml_stream, runIfOverloaded) if ("Re-send with force (-f)" in distroList[0]): response.status = 500 ET.register_namespace("test", "http://127.0.0.1/cocoma") emuError = ET.Element('Force-Errors') emuError = ET.Element('Force-Errors', { 'xmlns':'http://127.0.0.1/cocoma','href':'/emulations/'}) for forceError in distroList: forceErrorXML = ET.SubElement(emuError, "error") forceErrorXML.text = str(forceError) return prettify(emuError) except Exception,e: print e if str(e).find("no attribute 'getElementsByTagName'") > 0: #Return if supplied XML is bad e = "Supplied xml is malformed, check thoroughly for errors" response.status = 500 emuError=ET.Element('error') emuError.text = str(e) return prettify(emuError)
def setAddressBookXml(self, xml): '''modify the structure with a new DynamicItems xml''' contacts = {} for (mail, contact) in self.contactManager.contacts.iteritems(): contacts[mail] = contact self.contactManager.groups = {} self.contactManager.noGroup.users = {} self.contactManager.contacts = {} #doc = minidom.parseString(xml) dinamicItems = XmlParser.DynamicParser(xml) # Retrieve groups for i in dinamicItems.groups: groupId = i['groupId'] name = i['name'] if groupId not in self.contactManager.groups: self.contactManager.setGroup(groupId, ContactData.Group(name, groupId)) self.emit('group-added', name, groupId) # Retrieve contacts for i in dinamicItems.contacts: if 'isMessengerUser' in i and 'passportName' in i and \ i['isMessengerUser'] == 'true': # valid email = i['passportName'].lower() contact = ContactData.Contact(email) else: continue try: contactId = i['contactId'] cid = i['CID'] contact.id = contactId contact.cid = cid groups = [] for guid in i['groupIds']: groups.append(guid) contact.groups = groups for j in i['Annotations']: try: if j['Name'] == 'AB.NickName': alias = j['Value'] contact.alias = urllib.unquote(alias) except: pass displayName = i['displayName'] contact.nick = urllib.unquote(displayName) isMobileIMEnabled = i['isMobileIMEnabled'] contact.mobile = isMobileIMEnabled == 'true' hasSpace = i['hasSpace'] contact.space = hasSpace == 'true' except KeyError: continue if email in contacts: contact.status = contacts[email].status contact.nick = contacts[email].nick contact.personalMessage = contacts[email].personalMessage contact.msnobj = contacts[email].msnobj contact.clientid = contacts[email].clientid # finally adds the contact self.contactManager.addContact(contact) self.emit('contact-added', contact.email, contact.id, contact.nick, contact.personalMessage, contact.status, contact.alias, contact.blocked) for group_id in contact.groups: self.emit('contact-added-to-group', contact.email, self.contactManager.getGroup(group_id).name) self.contactManager.updateMemberships()
''' ################################ createEmu ############################### ''' if options.xml and not options.emuNow: if len(arguments)>0: if Library.daemonCheck()!=False: try: if options.emuForce: noExtraOptions(options, "xml", "emuForce") (emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData,MQproducerValues) = XmlParser.xmlFileParser(arguments[0], True) if (type(distroList[0]) == str): #Print forceErrors for distroItem in distroList: print distroItem + "\n" sys.exit() elif not options.emuForce: noExtraOptions(options, "xml") (emulationName,emulationType,emulationLog,emulationLogFrequency,emulationLogLevel, resourceTypeEmulation, startTimeEmu,stopTimeEmu, distroList,xmlData,MQproducerValues) = XmlParser.xmlFileParser(arguments[0], False) if (type(distroList[0]) == str): for distroItem in distroList: print distroItem + "\n" #Print forceErrors sys.exit() if startTimeEmu.lower() =="now": startTimeEmu1 = Library.emulationNow(2) #producer.sendmsg(myName,"USER REQUEST: "+sys._getframe().f_code.co_name+" create "+arguments[0]) msg = {"Action":"USER REQUEST Create Emulation","File":arguments[0]} producer.sendmsg(myName,msg)
def _Validate(_): # Note: Most of this code was stolen from IpmiUtil.py (VerifySelAgainstXmlList) # Test Variable sensorListFile = Config.J2010sensorListXmlFile xmlParserObj = XmlParser.XmlParser(sensorListFile) selPassOrFail = False unexpectedSels = None if not xmlParserObj.root: UtilLogger.verboseLogger.error( "SensorReadingStressTest.py - XmlParser: failed to parse sensor list XML file." ) return False # Validate the returned SEL log events against list of SEL events # in input selListXml. selReqList = [] # List containing all required SEL events. # Each element in the list is a nested list [Event_Text, duplicate], # where Event_Text is an SEL event as a string, and duplicate # is an integer indicating whether the event is allowed to be # used as a duplicate or not (-1: allow as duplicate, 1: only # use once (no duplicate, hasn't been used yet), 0: can no longer # be used (no duplicate, already used once). selOptList = [] # List containing all optional SEL events. # Each element in the list is a nested list [Event_Text, duplicate], # where Event_Text is an SEL event as a string, and duplicate # is an integer indicating whether the event is allowed to be # used as a duplicate or not (-1: allow as duplicate, 1: only # use once (no duplicate, hasn't been used yet), 0: can no longer # be used (no duplicate, already used once). # Parse the input XML file to get selReqList and selOptList. for selEntry in xmlParserObj.root: required = (selEntry.attrib["required"] == "true") selText = selEntry.attrib["contains"] allowDupl = (selEntry.attrib["allowduplicates"] == "true") if (required): # Required event log. if (allowDupl): selReqList.append([selText, -1]) else: selReqList.append([selText, 1]) else: # Optional event log. if (allowDupl): selOptList.append([selText, -1]) else: selOptList.append([selText, 1]) # Ready to do the validation. # Verify whether all required event logs are in the list of actual event logs. AreAllReqIn = True # Indicates wether all required events were found (True) in # list of actual event or not (False). actualSelList = [] # FIXME for event in selReqList: IsEventIn = False for actualEvent in actualSelList: if event[0] in actualEvent: IsEventIn = True break if not IsEventIn: AreAllReqIn = False break # Verify whether all actual events are either required or optional and nothing # else. AreAllActualIn = True # Indicates whether all actual events are either required # or optional and nothing else (True) or not (False). unexpectedSels = [] selValidList = selReqList + selOptList actualSelList = [] for event in actualSelList: IsEventIn = False for validEvent in selValidList: if validEvent[0] in event: if (validEvent[1] == 0): break # Event already matched and cannot be duplicate, hence cannot # be matched again. # This SEL record (variable event) is a duplicate. if (validEvent[1] == 1): validEvent[ 1] = 0 # Mark event as already matched and no duplicate # is allowed. IsEventIn = True break if not IsEventIn: AreAllActualIn = False unexpectedSels.append(event) # We don't break here in order to find all unexpected SEL events. # Ready to return results. if (AreAllReqIn and AreAllActualIn): selPassOrFail = True unexpectedSels = None elif (not AreAllActualIn): selPassOrFail = False else: # AreAllActualIn = True, AreAllReqIn = False. selPassOrFail = False unexpectedSels = None return selPassOrFail, unexpectedSels
def handle_response(self, request, response): '''handle the response''' if response.status == 200: parser = XmlParser.MembershipParser(response.body) self.session.contacts.pending = {} self.session.contacts.reverse = {} pending = self.session.contacts.pending reverse = self.session.contacts.reverse contacts = self.session.contacts.contacts new_accounts = [] for membership in parser.memberships: role = membership['MemberRole'] for member in membership['Members']: if 'PassportName' in member: email = member['PassportName'].lower() else: continue if email in contacts: contact = contacts[email] else: contact = e3.Contact(email) if role == 'Pending': pending[email] = contact contact.attrs['pending'] = True if 'DisplayName' in member: contact.nick = member['DisplayName'] if role == 'Reverse': reverse[email] = contact contact.attrs['Reverse'] = True if role == 'Allow': new_accounts.append(email) contacts[email] = contact if role == 'Block': contact.blocked = True else: contact.blocked = False if 'CID' in member: contact.cid = member['CID'] all_accounts = set(contacts.keys()) removed_accounts = all_accounts.difference(new_accounts) for email in removed_accounts: # TODO: send some kind of signal to inform to remove the # contact del contacts[email] DynamicItems(self.session, self.command_queue, self.on_login, self.started_from_cache).start() else: log.debug('error requesting membership ' + response.status) log.debug(response.body)
def handle_response(self, request, response): '''handle the response''' if response.status == 200: parser = XmlParser.DynamicParser(response.body) # Retrieve groups for group_dict in parser.groups: group_id = group_dict['groupId'] group_name = group_dict['name'] if group_id in self.session.groups: self.session.groups[group_id].name = group_name else: self.session.groups[group_id] = \ e3.Group(group_name, group_id) # Retrieve contacts for contact_dict in parser.contacts: if 'isMessengerUser' in contact_dict \ and 'passportName' in contact_dict \ and contact_dict['isMessengerUser'] == 'true': # valid email = contact_dict['passportName'].lower() if email in self.session.contacts.contacts: contact = self.session.contacts.contacts[email] else: contact = e3.Contact(email) self.session.contacts.contacts[email] = contact else: continue contact.identifier = contact_dict.get('contactId', '') contact.cid = contact_dict.get('CID', '') contact.groups = [] for guid in contact_dict['groupIds']: contact.groups.append(guid) group = self.session.groups[guid] if contact.account not in group.contacts: group.contacts.append(contact.account) for ann in contact_dict['Annotations']: if ann.get('Name', None) == 'AB.NickName': contact.alias = urllib.unquote(ann['Value']) break if not contact.nick: contact.nick = urllib.unquote(contact_dict.get( 'displayName', contact.account)) contact.attrs['mobile'] = \ contact_dict.get('isMobileIMEnabled', None) == 'true' contact.attrs['space'] = \ contact_dict.get('hasSpace', None) == 'true' log.debug('dynamic finished') self.session.contacts.me.identifier = \ response.body.split('<contactType>Me</contactType>')\ [1].split('</CID>')[0].split('<CID>')[1].strip() # get our nick try: nick = response.body.split('<contactType>Me</contactType>')\ [1].split('</displayName>')[0].split('<displayName>')[1] nick = common.unescape(nick) except IndexError: nick = self.session.contacts.me.account if not self.session.contacts.me.nick or \ self.session.contacts.me != self.session.account.account: self.session.contacts.me.nick = nick if self.on_login: # set our nick self.command_queue.put(Command('PRP', params=('MFN', urllib.quote(nick)))) self.session.add_event(e3.Event.EVENT_NICK_CHANGE_SUCCEED, nick) if not self.started_from_cache: self.command_queue.put(Command('BLP', params=('BL',))) accounts = self.session.contacts.pending.keys() for account in accounts: # account in pending that is already on some other role # (corrupted userlist) if account in self.session.contacts.contacts or account in self.session.contacts.reverse: del self.session.contacts.pending[account] # this line doen't work for accounts on corrupted userlists # RemovePendingContact(self.session, account).start() self.session.add_event(e3.Event.EVENT_CONTACT_LIST_READY) self.session.logger.add_contact_by_group( self.session.contacts.contacts, self.session.groups) if not self.started_from_cache: for adl in self.session.contacts.get_adls(): self.command_queue.put(Command('ADL', payload=adl)) GetProfile(self.session, self.session.contacts.me.identifier).start() else: log.debug('error requestion dynamic items')
def run(self): conf = Config() conf.addFromArg(sys.argv[1:]) self.initConfFromXls(conf) self.initSomeConf(conf) self.tempdir = tempfile.mkdtemp('GoogleTest', 'temp', '/tmp') docmd('mkdir %s/image' % self.tempdir) docmd('mkdir %s/attach' % self.tempdir) docmd('mkdir %s/result' % self.tempdir) conf.getConf('tempdir', 'temp dir', self.tempdir) sendTo = conf.getConf('sendto', 'Send mail to <self|all>') version = conf.getConf('version', 'current version') persoversion = conf.getConf('persoversion', 'Test Type').upper() projectName = conf.getConf('project', 'Project name in check list file name') testtype = conf.getConf('testtype', 'Test Type').upper() resultRootPath = self.getResultRootPath(conf) print resultRootPath resultDirName = conf.getConf('resultdirname', 'test result dir name') xmlpath = '%s%s' % (resultRootPath + 'results/', resultDirName + '/') xmlzip = resultRootPath + 'results/' + resultDirName + '.zip' logs = resultRootPath + 'logs/' + resultDirName if testtype == 'CTS': xmlname = xmlpath + 'testResult.xml' elif testtype == 'GTS': xmlname = xmlpath + 'xtsTestResult.xml' print xmlname print 'Begin to analyse xml, please waiting...' xmlParser = XmlParser(xmlname) result_devices_dic = xmlParser.get_result_devices_dic(xmlname, conf) result_summary_dic = xmlParser.get_result_summary_dic(xmlname) testpackage_result_dic = xmlParser.get_testpackage_result_dic(xmlname) total_fail_num = xmlParser.get_total_fail_num() workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Google_Test_Report') create_testcase_report(worksheet, total_fail_num, result_devices_dic, result_summary_dic, testpackage_result_dic) workbook.save( '%s/attach/Google_%s_TestReport_%s_v%s+%s.xls' % (self.tempdir, testtype, projectName, version, persoversion)) extAttachFileStr = conf.getConf('extattach', 'External attach files', 'none') if extAttachFileStr != 'none': for fileName in extAttachFileStr.split(','): docmd('cp %s %s/attach' % (projBuildRoot + 'v' + version + '/' + fileName.strip(), self.tempdir)) docmd( 'cp %smisc/SuperSpamReleaseMailFootLogoOneTouch.jpg %s/image/ReleaseMailLogo.jpg' % (getToolPath(), self.tempdir)) docmd('cp %s %s/result' % (xmlzip, self.tempdir)) docmd('cp -r %s %s/result' % (logs, self.tempdir)) os.system( 'ssh [email protected] "(rm -rfv /var/www/data/google_CTS_results/%s/%s/v%s+%s;mkdir -p /var/www/data/google_CTS_results/%s/%s/v%s+%s)"' % (projectName, testtype, version, persoversion, projectName, testtype, version, persoversion)) docmd( 'scp -r %s/result/* [email protected]:/var/www/data/google_CTS_results/%s/%s/v%s+%s' % (self.tempdir, projectName, testtype, version, persoversion)) self.__sendMail(conf, result_summary_dic, testpackage_result_dic)
def Execute(interfaceParams): # Define Test variables cmdPassOrFail = True respData = None # Define GetGpio variables cmdName = 'GetGpio' cmdNum = Config.cmdGetGpio netFn = Config.netFnOem30 # Parse Get Gpio List xml file xmlParserObj = XmlParser.XmlParser(Config.C2010getGpioListFilePath) if not xmlParserObj.root: UtilLogger.verboseLogger.error("VerifyGetGpio: failed to parse Xml file." \ + " Will not execute test.") return False # Verify Get GPIO for each GPIO number listed in XML for gpioInfo in xmlParserObj.root: # Define local variables gpioNum = gpioInfo.attrib["number"] gpioDir = gpioInfo.attrib["direction"] gpioDirIdx = 0 gpioVal = gpioInfo.attrib["value"] gpioValIdx = 1 # Define get gpio request raw byte as GPIO pin number rawBytesList = [gpioNum] # Send raw bytes via IpmiUtil gpioPassOrFail, respData = IpmiUtil.SendRawCmd(interfaceParams, \ netFn, cmdNum, rawBytesList) # If completion code not success, # fail GPIO and move to next GPIO if not gpioPassOrFail: UtilLogger.verboseLogger.error(cmdName + \ ": Command failed for GPIO pin number 0x" + gpioNum + \ ". Completion Code: " + str(respData)) cmdPassOrFail = False continue # Validate GPIO pin direction and GPIO pin value # Note: if GPIO pin value is set to 'x', GPIO pin value # will not be validated gpioPassOrFail = gpioDir == respData[gpioDirIdx] and \ ((gpioVal == respData[gpioValIdx]) or (gpioVal == 'x')) if gpioPassOrFail: if gpioVal == 'x': UtilLogger.verboseLogger.info(cmdName + \ ": Command passed for GPIO pin number 0x" + gpioNum + \ ". Pin Direction: 0x" + respData[gpioDirIdx] + \ " Pin Value ignored") else: UtilLogger.verboseLogger.info(cmdName + \ ": Command passed for GPIO pin number 0x" + gpioNum + \ ". Pin Direction: 0x" + respData[gpioDirIdx] + \ " Pin Value: 0x" + respData[gpioValIdx]) else: if gpioVal == 'x': UtilLogger.verboseLogger.info(cmdName + \ ": Command failed for GPIO pin number 0x" + gpioNum + \ ". Expected Pin Direction: 0x" + gpioDir + \ " Actual Pin Direction: 0x" + respData[gpioDirIdx] + \ ". Pin Value ignored") else: UtilLogger.verboseLogger.info(cmdName + \ ": Command failed for GPIO pin number 0x" + gpioNum + \ ". Expected Pin Direction: 0x" + gpioDir + \ " Actual Pin Direction: 0x" + respData[gpioDirIdx] + \ ". Expected Pin Value: 0x" + gpioVal + \ " Actual Pin Value: 0x" + respData[gpioValIdx]) cmdPassOrFail &= gpioPassOrFail # Verify response if cmdPassOrFail: UtilLogger.verboseLogger.info(cmdName + \ ": Command passed.") else: UtilLogger.verboseLogger.error(cmdName + \ ": Command failed.") return cmdPassOrFail
os.system("copy "+ gitIgnoreFile + " C:\Temp\\"+gitDestination) # Grabing the Revision History to use as a guide for cloning each commit credentials = " -host " + vaultHost + " -user " + vaultUser + " -password " + vaultPasswd getRevHistory = "vault VERSIONHISTORY -rowlimit 0 " + credentials beginVersion = " -beginversion 0 " RevHistoryLocation = ' "C:/Temp/temp.xml"' vaultFolder_full = " $/" + vaultFolder getRevHistoryCommand = getRevHistory + " -repository " + vaultRepo + beginVersion + vaultFolder_full + " > " + RevHistoryLocation color_print(getRevHistoryCommand, color='blue') os.system("cd /D " + SourceGearLocation + "&& " + getRevHistoryCommand) #os.system("cd /D"+ vault2git_script_location) XmlParser.init() comments = XmlParser.CommentA() version = XmlParser.VersionA() txid = XmlParser.TxidA() objverid = XmlParser.ObjveridA() date = XmlParser.DateA() user = XmlParser.UserA() gitDestination_full = " C:/Temp/" + gitDestination # if the script fails part way through change startVersion to match the last know vault version to be committed to git. # vault version are recorded at the beginning of the git commit messages startVersion = 0 loopLength = len(version) print('\n\nThere are ', loopLength, ' commits to migrate\n\n')
try: # server = 'http://' + XmlParser.serverIP() # print('Sending to IP:', server) # serverPORT = XmlParser.serverPORT() # print('Sending to PORT:', serverPORT) #payload = {'POST': 'SEND POST DATA FROM AGENT'} # r = requests.post(server, json=payload) r = Adapter.myCon(IP='127.0.0.1', port='80',version=1) print(r.text) except IOError: print(IOError) if cmd[0]=='GET': try: server = 'http://' + XmlParser.serverIP() print('Server ip is:', server) serverPORT = XmlParser.serverPORT() print('Server port is:', serverPORT) payload = {'some': 'data'} r = requests.get(server, json=payload) print(r.text) except IOError: print(IOError) # sends pytest from execution --> need to so how to implement a set of tests # pytest.main(['-x','C:/Users/adamz/PycharmProjects/HttpLesson/venv/pytest_sample.py']) # pytest.cmdline.main(args)