コード例 #1
0
ファイル: agent.py プロジェクト: rhettg/JoeAgent
    def __init__(self, config):
        from timer import TimerCollection
        from event import EventQueue
        self.state = STOPPED
        self.config = config
        self._info = None
        self.connections = []
        self.event_queue = EventQueue()
        self.timers = TimerCollection()
        EventSource.__init__(self)
        EventListener.__init__(self)

        # Yes we are a listener to ourselves
        self.addListener(self)

        self.setState(STARTING)
        if self.config.getBindAddress() != None and \
           self.config.getPort() != None:
            log.debug("Initializing server on %s:%d" % 
                    (self.config.getBindAddress(), self.config.getPort()))
            srv_sock = create_server_socket(self.config.getBindAddress(),
                                            self.config.getPort())
            self.addConnection(ServerConnection(srv_sock))
            log.debug("Server initialized")

        else:
            log.debug("Initialized non-server agent")
コード例 #2
0
ファイル: agent.py プロジェクト: rhettg/JoeAgent
class Agent(EventSource, EventListener):
    def __init__(self, config):
        from timer import TimerCollection
        from event import EventQueue
        self.state = STOPPED
        self.config = config
        self._info = None
        self.connections = []
        self.event_queue = EventQueue()
        self.timers = TimerCollection()
        EventSource.__init__(self)
        EventListener.__init__(self)

        # Yes we are a listener to ourselves
        self.addListener(self)

        self.setState(STARTING)
        if self.config.getBindAddress() != None and \
           self.config.getPort() != None:
            log.debug("Initializing server on %s:%d" % 
                    (self.config.getBindAddress(), self.config.getPort()))
            srv_sock = create_server_socket(self.config.getBindAddress(),
                                            self.config.getPort())
            self.addConnection(ServerConnection(srv_sock))
            log.debug("Server initialized")

        else:
            log.debug("Initialized non-server agent")

    def getConnections(self):
        return self.connections
    def getConnection(self, name):
        for c in self.connections:
            if c.getName() == name:
                return c
        return None
    def getConnectionByInfo(self, info):
        for c in self.connections:
            if isinstance(c, AgentConnection):
                if c.getAgentInfo() == info:
                    return c
        return None
    def addConnection(self, conn):
        self.connections.append(conn)
        log.debug("Connection Added (%d)" % (len(self.connections)))
    def dropConnection(self, conn):
        self.connections.remove(conn)
        log.debug("Connection Dropped (%d)" % (len(self.connections)))
    
    def addEvent(self, event):
        self.event_queue.push(event)
        log.debug("Event Added (%d)" % (len(self.event_queue)))
    def addTimer(self, timer):
        self.timers.add(timer)
        log.debug("Timer Added (%d)" % (len(self.timers)))
    def dropTimer(self, timer):
        self.timers.remove(timer)
        log.debug("Timer Removed (%d)" % (len(self.timers)))

    def getConfig(self):
        return self.config

    def getInfo(self):
        if self._info is None:
            self._info = AgentInfo(self.getConfig())
        return self._info

    def getState(self):
        return self.state
    def setState(self, state):
        self.addEvent(StateChangeEvent(self, self.state, state))
        if self.state != state:
            self.state = state
    def isRunning(self):
        return isinstance(self.state, RunningState)

    # Event Handlers
    def handleConnectionReadEvent(self, event):
        log.debug("Handling Read Event")
        obj = event.getSource().read()
        if obj != None:
            self.addEvent(obj)

    def handleConnectionWriteEvent(self, event):
        log.debug("Handling Write Event")
        event.getSource().write()

    def handleConnectionExceptionEvent(self, event):
        log.debug("Handling Connection Exception Event")
        event.getSource().disconnect()
        self.dropConnection(event.getSource())

    def handleConnectEvent(self, event):
        log.debug("Handling connect event")
        self.addConnection(event.getNewConnection())

    def handleMessageRecievedEvent(self, event):
        # All we will do a receive event is log it.
        # Its up to one of our listeners to care about it.
        log.debug("Received a message of type %s" 
                   % str(event.getMessage().__class__))
        if isinstance(event.getMessage(), Request):
            log.debug("Request: %s" % str(event.getMessage()))
        if isinstance(event.getMessage(), Response):
            log.debug("Response: %s" % str(event.getMessage()))

    def handleMessageSendEvent(self, event):
        log.debug("Sending a message of type %s" 
                   % str(event.getMessage().__class__))
        if isinstance(event.getMessage(), Request):
            log.debug("Request: %s" % event.getMessage().getKey())
        if isinstance(event.getMessage(), Response):
            log.debug("Response: %s" % str(event.getMessage()))

        if isinstance(event.getTarget(), Connection):
            event.getTarget().write(str(event.getMessage()))


    _handlers = {
                 ConnectionReadEvent:       handleConnectionReadEvent,
                 ConnectionWriteEvent:      handleConnectionWriteEvent,
                 ConnectionExceptionEvent:  handleConnectionExceptionEvent,
                 MessageSendEvent:          handleMessageSendEvent,
                 MessageReceivedEvent:      handleMessageRecievedEvent,
                 ConnectEvent:              handleConnectEvent
               }

    def getHandlers(self):
        return Agent._handlers

    def notify(self, evt):
        found = 0
        hndlrs = self.getHandlers()
        for h in hndlrs.keys():
            if isinstance(evt, h):
                hndlrs[h](self, evt)
                found = 1

    def processEvent(self):
        """Process a single event from the event_queue"""
        log.debug("Going to handle an event")
        event = self.event_queue.pop()
        if event != None:
            try:
                log.debug("Handling event %s" % str(event))
                self.notifyListeners(event)
            except Exception, e:
                log.exception("Error handling event")