コード例 #1
0
ファイル: xoom.py プロジェクト: pruan/TestDepot
    def open_session(self, name, *args, **kwargs):
        """
        Xoom open_session
        """
        self.name = name;
        try:
            localhost = socket.gethostbyaddr(socket.gethostname())[2][0]
        except socket.gaierror:
            localhost = ""; # I think this will still work.
        # Determine IP and port from name.
        try:
            plimIp = socket.gethostbyaddr(name)[2][0]
        except: #socket.gaierror, msg:
            #print "Failed to determine ip for plim %s: %s." \
            #     %(name, msg)
            plimIp = name # assume it's in the form of ip string
        try:
            # address 192.168.20.123 will translate to message port
            # 50123
            ip_val = int(plimIp.split(".")[3])
            sub_net_digit = plimIp.split(".")[2][-1]  

            prefix = "5" + sub_net_digit
            if ip_val < 10:
                prefix = prefix + "00"
            elif ip_val < 100:
                prefix = prefix + "0"
            else:
                pass
            plimPort = prefix + str(ip_val)
        except IndexError, msg:
            raise RuntimeError, "Plim Ip address invalid %s." %msg
コード例 #2
0
ファイル: ipv4.py プロジェクト: pruan/TestDepot
	def gethost(self):
		"""gethost()
	Resolve this IP address to a canonical name using gethostbyaddr."""
		try:
			hostname, aliases, others = socket.gethostbyaddr(str(self))
		except:
			return ""
		return hostname
コード例 #3
0
def _get_name(addr):
    try:
        return socketlib.gethostbyaddr(str(addr))[0]
    except:
        return ""
コード例 #4
0
ファイル: rcconfig.py プロジェクト: xiangke/pycopia
def _get_name(addr):
    try:
        return socketlib.gethostbyaddr(str(addr))[0]
    except:
        return ""
コード例 #5
0
ファイル: xoom.py プロジェクト: pruan/TestDepot
    def xoomProcessMsg(self, entityList, attrList, msgType=None):
        """
        Method for processing and sending XOOM messages of different types.
        @param entityList:
        @param attrList:
        @param msgType: Valid values are GET, SET or GETNEXT.      
        @rtype: dict
        @return: A dict indexed by entity(s) containing get attributes. 
        """
        if msgType == None:
            msgType = 'GET'
        else:
            msgType = msgType.upper()
        startTime = time.time()
        try: 
            plimIp = socket.gethostbyaddr(self.name)[2][0]  #need to fix
        except:
            plimIp = self.name
        plimPort = "49" + str(plimIp.split(".")[3]);
        
        returnDict = {}
        msg = xoomMsg()
        attrProcList = []
        
        for index, ent in enumerate(entityList):
            if self.log:
                #self.log.write("Entity %s is %s %s\n" %(index, plimPort, ent))
                pass
            if msgType == 'GET':
                msg.addGetRequest(ent)
            elif msgType == 'GETNEXT':
                msg.addGetNextRequest(ent)
            elif msgType == 'SET':
                msg.addSetRequest(ent)
            else:
                if self.log:
                    self.log.write("Message type %s does not exist.\n" %msgType)
 
            # AttrList will be a list of tuple for a set.
            # AttrList will be a list of lists for a get/set of different attrs
            # per entity.  String or unicode attrs mean it is a flat list.

            attrProcList.append([])
            if self.log:
                self.log.write("Type of %s is %s\n" \
                    %(attrList[0], type(attrList[0])))
            
            # The attr list is either a flat string or tuple
            if type(attrList[0]) == types.TupleType:
                match = True
                # This is flat set
                for attr,value in attrList:
                    msg.addAttribute(attr, value)
                    attrProcList[index].append((attr, value))
            elif type(attrList[0]) == types.StringType or \
                 type(attrList[0]) == types.UnicodeType:
                match = True
                for attr in attrList:
                    msg.addAttribute(attr)
                    attrProcList[index].append(attr)
            else:
                match = False
                if self.log:
                    self.log.write("AttrList %s contains unknown type %s.\n" \
                        %(attrList[0], type(attrList[0])))

            # Or the attrList is a list of string or tuples.
            if not match:
                try:
                    attrList[index]
                except:
                    attrList.append(attrList[0])
                if type(attrList[index]) == types.ListType:
                    for a in attrList[index]:
                        if type(a) == types.TupleType:
                            for attr,value in a:
                                msg.addAttribute(attr, value)
                                attrProcList[index].append((attr, value))
                        elif type(a) == types.StringType or \
                             type(a) == types.UnicodeType:
                            msg.addAttribute(a)
                            attrProcList[index].append(a)
                            print "xxxx attribute: %s added to msg: %s" % (a, msg)
                                
                        else:
                            if self.log:
                                self.log.write(\
                                    "AttrList[%s] %s has unknown type %s.\n" \
                                    %(index, a, type(a)))

        try:
            try:
                xmlData = self.sendXoomMsg(self.conn, msg.getMsg())
            except:
                if self.log:
                    self.log.write("Error: %s\n" \
                        %string.join(traceback.format_exception(*sys.exc_info()), ''))
                self.close_session()
                time.sleep(5)
                self.open_session(self.name)
                xmlData = self.sendXoomMsg(self.conn, msg.getMsg())
            if self.returnXml:
                return xmlData.toprettyxml()
            #print xmlData.toprettyxml()
            # This will parse the xml and extract the details into a python dict
            moList = xmlData.getElementsByTagName(msgType)
            for mo in range(len(moList)):
                returnDict[entityList[mo]] = {}
                errorList = moList[mo].getElementsByTagName('Error')
                if len(errorList) > 0:
                    errorType = errorList[0].getAttribute('type')
                    errorReason = errorList[0].getAttribute('reason')
                    if self.log:
                        self.log.write("%s:%s\n" %(errorType, errorReason))
                    retDict['Error'] = {"Error": errorType + ": " + errorReason}
                else:
                    oaList = moList[mo].getElementsByTagName('OA')
                    attrVal = []
                    retDict = {}
      
                    for i in range(len(attrProcList[mo])):
                        if type(attrProcList[mo][0]) == types.TupleType or \
                           type(attrProcList[mo][0]) == types.ListType:
                            attrName = attrProcList[mo][i][0]
                        elif type(attrProcList[mo][0]) == types.StringType or \
                             type(attrProcList[mo][0]) == types.UnicodeType:
                            attrName = attrProcList[mo][i]
                        else:
                            if self.log:
                                self.log.write(\
                                   "Warn:Unable to determine attribute name.\n")
                            attrName = ""
                        
                        oaName = str(oaList[i].getAttribute('name'))
                        if oaName <> attrName:
                            resValue = str(oaList[i].getAttribute('result'))
                            retDict[attrName] = {}
                            retDict[attrName]['result'] = "failed"
                            retDict[attrName]['value'] = resValue;
                        elif oaList[i].getAttribute('result') <> "":
                            if oaList[i].getAttribute('result') <> "Ok":
                                resValue = str(oaList[i].getAttribute('result'))
                                retDict[oaName] = {}
                                retDict[oaName]['result'] = "failed"
                                retDict[oaName]['value'] = resValue;
                            else:
                                retValue = str(oaList[i].getAttribute('value'))
                                retReg = str(oaList[i].getAttribute('register'))
                                retRawVal = str(oaList[i].getAttribute('rawValue'))
                                retDict[oaName] = {}
                                retDict[oaName]['result'] = "ok";
                                retDict[oaName]['rawValue'] = retRawVal;
                                retDict[oaName]['register'] = retReg;
                                retDict[oaName]['value'] = retValue;
                        else:
                            retValue = str(oaList[i].getAttribute('value'))
                            retReg = str(oaList[i].getAttribute('register'))
                            retRawVal = str(oaList[i].getAttribute('rawValue'))
                            if retValue == "LIST":
                                listDict = {}
                                list = oaList[i].\
                                    getElementsByTagName('LIST')[0].attributes
                                for attr in list.keys():
                                    listDict[str(attr)] = {}
                                    listDict[str(attr)]['value'] = str(list[attr].nodeValue)
                                    listDict[str(attr)]['register'] = "N/A"
                                    listDict[str(attr)]['rawValue'] = "N/A"
                                listDict['result'] = "ok"
                                retDict[oaName] = \
                                    listDict
                            else:
                                retDict[oaName] = {}
                                retDict[oaName]['result'] = "ok";
                                retDict[oaName]['rawValue'] = retRawVal;
                                retDict[oaName]['register'] = retReg;
                                retDict[oaName]['value'] = retValue;

                    for key in retDict.keys():
                        returnDict[entityList[mo]][key] = retDict[key]
                
        except:
            if self.log:
                self.log.write("%s\n" \
                    %string.join(traceback.format_exception(*sys.exc_info()), ''))

        try:
            errorList = xmlData.getElementsByTagName('Error')
            if len(errorList) > 0:
                errorType = errorList[0].getAttribute('type')
                errorReason = errorList[0].getAttribute('reason')
            if self.log:
                self.log.write(\
                    "Error detected in response. '%s:%s'\n" %(errorType,errorReason))
        except:
            errorType = "ProcessingFailure"
            errorReason = "Unknown Failure"

        for ent in entityList:
            if not returnDict.has_key(ent):
                returnDict[ent] = {}
                if type(attrList[0]) == types.TupleType or \
                    type(attrList[0]) == types.ListType:
                    for attr,value in attrList: #xxx: attrList
                        returnDict[ent][attr] = \
                            "Error:" + errorType + ":" + errorReason
                elif type(attrList[0]) == types.StringType or \
                    type(attrList[0]) == types.UnicodeType:
                    for attr in attrList:
                        returnDict[ent][attr] = \
                            "Error:" + errorType + ":" + errorReason
        else:
            if len(returnDict) <> len(entityList):
                for ent in entityList:
                    if not returnDict.has_key(ent):
                        returnDict[ent] = {}
                    if len(returnDict[ent]) <> len(attrList):
                        if type(attrList[0]) == types.TupleType or \
                           type(attrList[0]) == types.ListType:
                            for attr,value in attrList:
                                returnDict[ent][attr] = \
                                    "Error:" + 'ProcessingFailure:Unknown Failure'
                        elif type(attrList[0]) == types.StringType or \
                             type(attrList[0]) == types.UnicodeType:
                            for attr in attrList:
                                returnDict[ent][attr] = \
                                    "Error:" + 'ProcessingFailure:Unknown Failure'
        endTime = time.time()
        timeElapsed = endTime - startTime
        if self.log:
            self.log.write("Returning: %s %s\n" %(timeElapsed, returnDict,))

        #if self.log:
        #    self.log.write("Returning: %s\n" %(returnDict,))
        return returnDict