def send_msg_abort(self):
     """Send an abort message."""
     if self.isSpecConnected():
         self.__send_msg_no_reply(
             SpecMessage.msg_abort(version=self.serverVersion))
     else:
         raise SpecClientNotConnectedError
Example #2
0
    def send_msg_abort(self):
        """Send an abort message."""
        if not self.is_connected():
            raise SpecClientNotConnectedError

        msg = SpecMessage.msg_abort(version=self.server_version)
        self.__send_msg_no_reply(msg)
Example #3
0
    def handle_read(self):
        try:
            received = self.recv(32768)

            self.received_strings.append(received)

            if is_python3():
                s = b''.join(self.received_strings)
                sbuffer = memoryview(s)
            else:
                s = ''.join(self.received_strings)
                sbuffer = buffer(s)

            consumedBytes = 0
            offset = 0
            received_messages = []

            while offset < len(sbuffer):

                if self.message is None:
                    try:
                        self.message = SpecMessage.message(
                            version=self.client_version,
                            order=self.client_order)
                    except:
                        import traceback
                        log.log(2, traceback.format_exc())

                consumedBytes = self.message.readFromStream(sbuffer[offset:])

                if consumedBytes == 0:
                    break

                offset += consumedBytes

                if self.message.isComplete():
                    # dispatch incoming message
                    if self.message.cmd == SpecMessage.HELLO:
                        self.client_order = self.message.packedHeaderDataFormat[
                            0]
                        self.client_version = self.message.vers
                        self.clientName = self.message.name
                        self.send_hello_reply(self.message.sn,
                                              str(self.server.name))
                    else:
                        received_messages.append(self.message)

                    self.message = None

            self.received_strings = [s[offset:]]

            for message in received_messages:
                if not self.dispatch_message(message):
                    self.send_error(
                        message.sn, '',
                        'unsupported command type : %d' % message.cmd)
        except:
            import traceback
            log.log(3, "SpecServer read error. %s" % traceback.format_exc())
            return
Example #4
0
 def send_error(self, replyID, name, data):
     self.sendq.append(
         SpecMessage.error_message(replyID,
                                   name,
                                   data,
                                   version=self.clientVersion,
                                   order=self.clientOrder))
Example #5
0
 def send_msg_event(self, chanName, value, broadcast=True):
     self.sendq.append(
         SpecMessage.msg_event(chanName,
                               value,
                               version=self.clientVersion,
                               order=self.clientOrder))
     if broadcast:
         for client in self.server.clients:
             client.send_msg_event(chanName, value, broadcast=False)
Example #6
0
    def send_msg_cmd(self, cmd):
        """Send a command message to the remote Spec server.

        Arguments:
        cmd -- command string, i.e. 'mv psvo 1.2'
        """
        if self.isSpecConnected():
            self.__send_msg_no_reply(SpecMessage.msg_cmd(cmd, version=self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #7
0
    def send_msg_unregister(self, chanName):
        """Send a channel unregister message.

        Arguments:
        chanName -- a string representing the channel name, i.e. 'var/toto'
        """
        if self.isSpecConnected():
            self.__send_msg_no_reply(SpecMessage.msg_unregister(chanName, version=self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #8
0
    def handle_read(self):
        """Handle 'read' events on socket

        Messages are built from the read calls on the socket.
        """
        self.receivedStrings.append(self.recv(32768)) #read at most all the input buffer
        s = ''.join(self.receivedStrings)
        sbuffer = buffer(s)
        consumedBytes = 0
        offset = 0

        while offset < len(sbuffer):
            if self.message is None:
                self.message = SpecMessage.message(version = self.serverVersion)

            consumedBytes = self.message.readFromStream(sbuffer[offset:])

            if consumedBytes == 0:
                break

            offset += consumedBytes

            if self.message.isComplete():
                # dispatch incoming message
                if self.message.cmd == SpecMessage.REPLY:
                    replyID = self.message.sn

                    if replyID > 0:
                        try:
                            reply = self.registeredReplies[replyID]
                        except:
                            logging.getLogger("SpecClient").exception("Unexpected error while receiving a message from server")
                        else:
                            del self.registeredReplies[replyID]

                            reply.update(self.message.data, self.message.type == SpecMessage.ERROR, self.message.err)

                            #SpecEventsDispatcher.emit(self, 'replyFromSpec', (replyID, reply, ))
                elif self.message.cmd == SpecMessage.EVENT:
                    for name in SpecChannel.SpecChannel.channel_aliases[self.message.name]:
                        self.registeredChannels[name].update(self.message.data, deleted=self.message.flags == SpecMessage.DELETED)
                elif self.message.cmd == SpecMessage.HELLO_REPLY:
                    if self.checkourversion(self.message.name):
                        self.serverVersion = self.message.vers #header version
                        #self.state = CONNECTED
                        self.specConnected()
                    else:
                        self.serverVersion = None
                        self.connected = False
                        self.close()
                        self.state = DISCONNECTED

                self.message = None

        self.receivedStrings = [ s[offset:] ]
Example #9
0
    def send_msg_register(self, chan_name):
        """Send a channel register message.

        Arguments:
        chan_name -- a string representing the channel name, i.e. 'var/toto'
        """
        if not self.is_connected():
            raise SpecClientNotConnectedError

        msg = SpecMessage.msg_register(chan_name, version=self.server_version)
        self.__send_msg_no_reply(msg)
Example #10
0
    def send_msg_cmd(self, cmd):
        """Send a command message to the remote Spec server.

        Arguments:
        cmd -- command string, i.e. 'mv psvo 1.2'
        """
        if self.isSpecConnected():
            self.__send_msg_no_reply(
                SpecMessage.msg_cmd(cmd, version=self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #11
0
    def send_msg_register(self, chanName):
        """Send a channel register message.

        Arguments:
        chanName -- a string representing the channel name, i.e. 'var/toto'
        """
        if self.isSpecConnected():
            self.__send_msg_no_reply(
                SpecMessage.msg_register(chanName, version=self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #12
0
    def send_msg_chan_send(self, chanName, value, wait=False):
        """Send a channel write message.

        Arguments:
        chanName -- a string representing the channel name, i.e. 'var/toto'
        value -- channel value
        """
        if self.isSpecConnected():
            self.__send_msg_no_reply(SpecMessage.msg_chan_send(chanName, value, version=self.serverVersion), wait)
        else:
            raise SpecClientNotConnectedError
Example #13
0
    def send_msg_func(self, cmd):
        """Send a command message to the remote Spec server using the new 'func' feature

        Arguments:
        cmd -- command string
        """
        if self.serverVersion < 3:
            logging.getLogger('SpecClient').error('Cannot execute command in Spec : feature is available since Spec server v3 only')
        else:
            if self.isSpecConnected():
                self.__send_msg_no_reply(SpecMessage.msg_func(cmd, version = self.serverVersion))
            else:
                raise SpecClientNotConnectedError
Example #14
0
    def send_msg_func(self, cmd):
        """Send a command message to the remote Spec server using the new 'func' feature

        Arguments:
        cmd -- command string
        """
        if self.server_version < 3:
            raise SpecClientVersionError("need spec server minimum version 3")

        if not self.is_connected():
            raise SpecClientNotConnectedError

        msg = SpecMessage.msg_func(cmd, version=self.server_version)
        self.__send_msg_no_reply(msg)
Example #15
0
    def send_msg_chan_send(self, chanName, value, wait=False):
        """Send a channel write message.

        Arguments:
        chanName -- a string representing the channel name, i.e. 'var/toto'
        value -- channel value
        """
        if self.isSpecConnected():
            self.__send_msg_no_reply(
                SpecMessage.msg_chan_send(chanName,
                                          value,
                                          version=self.serverVersion), wait)
        else:
            raise SpecClientNotConnectedError
Example #16
0
    def send_msg_chan_read(self, chanName):
        """Send a channel read message, and return the reply id.

        Arguments:
        chanName -- a string representing the channel name, i.e. 'var/toto'
        """
        if self.isSpecConnected():
            try:
                caller = sys._getframe(1).f_locals['self']
            except KeyError:
                caller = None

            return self.__send_msg_with_reply(replyReceiverObject = caller, *SpecMessage.msg_chan_read(chanName, version = self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #17
0
    def send_msg_cmd_with_return(self, cmd):
        """Send a command message to the remote Spec server, and return the reply id.

        Arguments:
        cmd -- command string, i.e. '1+1'
        """
        if self.isSpecConnected():
            try:
                caller = sys._getframe(1).f_locals['self']
            except KeyError:
                caller = None

            return self.__send_msg_with_reply(replyReceiverObject = caller, *SpecMessage.msg_cmd_with_return(cmd, version = self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #18
0
    def send_msg_func(self, cmd):
        """Send a command message to the remote Spec server using the new 'func' feature

        Arguments:
        cmd -- command string
        """
        if self.serverVersion < 3:
            log.error(
                'Cannot execute command in Spec : feature is available since Spec server v3 only'
            )
        else:
            if self.isSpecConnected():
                self.__send_msg_no_reply(
                    SpecMessage.msg_func(cmd, version=self.serverVersion))
            else:
                raise SpecClientNotConnectedError
Example #19
0
    def handle_read(self):
        """Handle 'read' events on socket

        Messages are built from the read calls on the socket.
        """
        _received = self.recv(32768)

        self.received_strings.append(_received)

        if is_python3():
            s = b''.join(self.received_strings)
            sbuffer = memoryview(s)
        else:
            s = ''.join(self.received_strings)
            sbuffer = buffer(s)

        consumedBytes = 0
        offset = 0

        while offset < len(sbuffer):
            if self.message is None:
                self.message = SpecMessage.message(version=self.server_version)

            consumedBytes = self.message.readFromStream(sbuffer[offset:])

            if consumedBytes == 0:
                break

            offset += consumedBytes

            if self.message.isComplete():
                try:
                    # dispatch incoming message
                    if self.message.cmd == SpecMessage.REPLY:
                        self.dispatch_reply_msg(self.message)
                    elif self.message.cmd == SpecMessage.EVENT:
                        self.dispatch_event_msg(self.message)
                    elif self.message.cmd == SpecMessage.HELLO_REPLY:
                        self.dispatch_hello_reply_msg(self.message)
                except Exception as e:
                    self.message = None
                    self.received_strings = [s[offset:]]
                    raise SpecClientProtocolError(str(e))
                else:
                    self.message = None

        self.received_strings = [s[offset:]]
Example #20
0
    def send_msg_chan_read(self, chan_name):
        """Send a channel read message, and return the reply id.

        Arguments:
        chan_name -- a string representing the channel name, i.e. 'var/toto'
        """
        if not self.is_connected():
            raise SpecClientNotConnectedError

        try:
            caller = sys._getframe(1).f_locals['self']
        except KeyError:
            caller = None

        reply, msg = SpecMessage.msg_chan_read(chan_name,
                                               version=self.server_version)
        reply_id = self.__send_msg_with_reply(reply, msg, receiver_obj=caller)
        return reply_id
Example #21
0
    def send_msg_cmd_with_return(self, cmd):
        """Send a command message to the remote Spec server, and return the reply id.

        Arguments:
        cmd -- command string, i.e. '1+1'
        """
        if self.isSpecConnected():
            try:
                caller = sys._getframe(1).f_locals['self']
            except KeyError:
                caller = None

            return self.__send_msg_with_reply(replyReceiverObject=caller,
                                              *SpecMessage.msg_cmd_with_return(
                                                  cmd,
                                                  version=self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #22
0
    def send_msg_chan_read(self, chanName):
        """Send a channel read message, and return the reply id.

        Arguments:
        chanName -- a string representing the channel name, i.e. 'var/toto'
        """
        if self.isSpecConnected():
            try:
                caller = sys._getframe(1).f_locals['self']
            except KeyError:
                caller = None

            return self.__send_msg_with_reply(replyReceiverObject=caller,
                                              *SpecMessage.msg_chan_read(
                                                  chanName,
                                                  version=self.serverVersion))
        else:
            raise SpecClientNotConnectedError
Example #23
0
    def send_msg_func_with_return(self, cmd):
        """Send a command message to the remote Spec server using the new 'func' feature, and return the reply id.

        Arguments:
        cmd -- command string
        """
        if self.serverVersion < 3:
            logging.getLogger('SpecClient').error('Cannot execute command in Spec : feature is available since Spec server v3 only')
        else:
            if self.isSpecConnected():
                try:
                    caller = sys._getframe(1).f_locals['self']
                except KeyError:
                    caller = None

                message = SpecMessage.msg_func_with_return(cmd, version = self.serverVersion)
                return self.__send_msg_with_reply(replyReceiverObject = caller, *message)
            else:
                raise SpecClientNotConnectedError
Example #24
0
    def handle_read(self):
        self.receivedStrings.append(self.recv(32768))
        s = ''.join(self.receivedStrings)
        sbuffer = buffer(s)
        consumedBytes = 0
        offset = 0
        received_messages = []

        while offset < len(sbuffer):
            if self.message is None:
                self.message = SpecMessage.message(version=self.clientVersion,
                                                   order=self.clientOrder)

            consumedBytes = self.message.readFromStream(sbuffer[offset:])

            if consumedBytes == 0:
                break

            offset += consumedBytes

            if self.message.isComplete():
                # dispatch incoming message
                if self.message.cmd == SpecMessage.HELLO:
                    self.clientOrder = self.message.packedHeaderDataFormat[0]
                    print "client byte order: ", self.clientOrder
                    self.clientVersion = self.message.vers
                    self.clientName = self.message.name
                    self.send_hello_reply(self.message.sn,
                                          str(self.server.name))
                else:
                    received_messages.append(self.message)

                self.message = None

        self.receivedStrings = [s[offset:]]

        for message in received_messages:
            if not self.dispatchIncomingMessage(message):
                self.send_error(message.sn, '',
                                'unsupported command type : %d' % message.cmd)
Example #25
0
    def send_msg_chan_send(self, chanName, value):
        """Send a channel write message.

        Arguments:
        chanName -- a string representing the channel name, i.e. 'var/toto'
        value -- channel value
        """
        log.log(
            DEBUG,
            "message channel send channel=%s, value=%s" % (chanName, value))
        if self.isSpecConnected():
            try:
                self.__send_msg_no_reply(
                    SpecMessage.msg_chan_send(chanName,
                                              value,
                                              version=self.serverVersion))
            except:
                import traceback
                log.log(1, traceback.format_exc())
        else:
            log.log(DEBUG, " not connected")
            raise SpecClientNotConnectedError
Example #26
0
    def send_msg_cmd_with_return(self, cmd, caller=None):
        """Send a command message to the remote Spec server, and return the reply id.

        Arguments:
        cmd -- command string, i.e. '1+1'
        """
        if not self.is_connected():
            raise SpecClientNotConnectedError

        if not caller:
            try:
                caller = sys._getframe(1).f_locals['self']
            except KeyError:
                log.log(2, "caller not identified")
                caller = None
        log.log(2,
                "executing command. reply to be informed to %s" % str(caller))

        reply, msg = SpecMessage.msg_cmd_with_return(
            cmd, version=self.server_version)
        reply_id = self.__send_msg_with_reply(reply, msg, receiver_obj=caller)

        return reply_id
Example #27
0
    def send_msg_func_with_return(self, cmd):
        """Send a command message to the remote Spec server using the new 'func' feature, and return the reply id.

        Arguments:
        cmd -- command string
        """
        if self.serverVersion < 3:
            log.error(
                'Cannot execute command in Spec : feature is available since Spec server v3 only'
            )
        else:
            if self.isSpecConnected():
                try:
                    caller = sys._getframe(1).f_locals['self']
                except KeyError:
                    caller = None

                message = SpecMessage.msg_func_with_return(
                    cmd, version=self.serverVersion)
                return self.__send_msg_with_reply(replyReceiverObject=caller,
                                                  *message)
            else:
                raise SpecClientNotConnectedError
Example #28
0
    def handle_read(self):
        self.receivedStrings.append(self.recv(32768))
        s = ''.join(self.receivedStrings)
        sbuffer = buffer(s)
        consumedBytes = 0
        offset = 0
        received_messages = []

        while offset < len(sbuffer):
            if self.message is None:
                self.message = SpecMessage.message(version = self.clientVersion, order=self.clientOrder)

            consumedBytes = self.message.readFromStream(sbuffer[offset:])

            if consumedBytes == 0:
                break

            offset += consumedBytes

            if self.message.isComplete():
                # dispatch incoming message
                if self.message.cmd == SpecMessage.HELLO:
                    self.clientOrder = self.message.packedHeaderDataFormat[0]
                    print "client byte order: ", self.clientOrder
                    self.clientVersion = self.message.vers
                    self.clientName = self.message.name
                    self.send_hello_reply(self.message.sn, str(self.server.name))
                else:
                    received_messages.append(self.message)

                self.message = None

        self.receivedStrings = [ s[offset:] ]

        for message in received_messages:
          if not self.dispatchIncomingMessage(message):
            self.send_error(message.sn, '', 'unsupported command type : %d' % message.cmd)
Example #29
0
    def send_msg_func_with_return(self, cmd, caller=None):
        """Send a command message to the remote Spec server using the new 'func' feature, and return the reply id.

        Arguments:
        cmd -- command string
        """
        if self.server_version < 3:
            raise SpecClientVersionError("need spec server minimum version 3")

        if not self.is_connected():
            raise SpecClientNotConnectedError

        if caller is None:
            try:
                caller = sys._getframe(1).f_locals['self']
            except KeyError:
                caller = None
        log.log(2,
                "executing command. reply to be informed to %s" % str(caller))

        reply, msg = SpecMessage.msg_func_with_return(
            cmd, version=self.server_version)
        reply_id = self.__send_msg_with_reply(reply, msg, receiver_obj=caller)
        return reply_id
Example #30
0
 def send_hello_reply(self, reply_id, serverName):
     self.sendq.append(SpecMessage.msg_hello_reply(reply_id, serverName, \
             version = self.client_version, order=self.client_order))
Example #31
0
 def send_error(self, reply_id, name, data):
     self.sendq.append(SpecMessage.error_message(reply_id, name, data, \
             version = self.client_version, order=self.client_order))
Example #32
0
 def send_msg_event(self, chanName, value, broadcast=True):
     self.sendq.append(SpecMessage.msg_event(chanName, value, version = self.clientVersion, order=self.clientOrder))
     if broadcast:
       for client in self.server.clients:
         client.send_msg_event(chanName, value, broadcast=False)
Example #33
0
 def send_msg_event(self, chanName, value):
     self.sendq.append(SpecMessage.msg_event(chanName, value, version = self.clientVersion, order=self.clientOrder))
Example #34
0
 def send_hello_reply(self, replyID, serverName):
     self.sendq.append(
         SpecMessage.msg_hello_reply(replyID,
                                     serverName,
                                     version=self.clientVersion,
                                     order=self.clientOrder))
Example #35
0
 def send_error(self, replyID, name, data):
     self.sendq.append(SpecMessage.error_message(replyID, name, data, version = self.clientVersion, order=self.clientOrder))
Example #36
0
 def send_msg_hello(self):
     """Send a hello message."""
     self.__send_msg_no_reply(SpecMessage.msg_hello())
Example #37
0
    def handle_read(self):
        """Handle 'read' events on socket

        Messages are built from the read calls on the socket.
        """
        self.receivedStrings.append(
            self.recv(32768))  #read at most all the input buffer
        s = ''.join(self.receivedStrings)
        sbuffer = buffer(s)
        consumedBytes = 0
        offset = 0

        while offset < len(sbuffer):
            if self.message is None:
                self.message = SpecMessage.message(version=self.serverVersion)

            consumedBytes = self.message.readFromStream(sbuffer[offset:])

            if consumedBytes == 0:
                break

            offset += consumedBytes

            if self.message.isComplete():
                try:
                    # dispatch incoming message
                    if self.message.cmd == SpecMessage.REPLY:
                        replyID = self.message.sn

                        if replyID > 0:
                            try:
                                reply = self.registeredReplies[replyID]
                            except:
                                logging.getLogger("SpecClient").exception(
                                    "Unexpected error while receiving a message from server"
                                )
                            else:
                                del self.registeredReplies[replyID]

                                reply.update(
                                    self.message.data,
                                    self.message.type == SpecMessage.ERROR,
                                    self.message.err)
                                #SpecEventsDispatcher.emit(self, 'replyFromSpec', (replyID, reply, ))
                    elif self.message.cmd == SpecMessage.EVENT:
                        try:
                            self.registeredChannels[self.message.name].update(
                                self.message.data,
                                self.message.flags == SpecMessage.DELETED)
                        except KeyError:
                            pass
                    elif self.message.cmd == SpecMessage.HELLO_REPLY:
                        if self.checkourversion(self.message.name):
                            self.serverVersion = self.message.vers  #header version
                            #self.state = CONNECTED
                            self.specConnected()
                        else:
                            self.serverVersion = None
                            self.connected = False
                            self.close()
                            self.state = DISCONNECTED
                except:
                    self.message = None
                    self.receivedStrings = [s[offset:]]
                    raise
                else:
                    self.message = None

        self.receivedStrings = [s[offset:]]
Example #38
0
def connectionHandler(connection_ref, socket_to_spec):
    receivedStrings = []
    message = None
    serverVersion = None
    socket_to_spec.settimeout(None)

    conn = connection_ref()
    if conn is not None:
        conn.connected = True
        conn.state = WAITINGFORHELLO
        conn.socket = socket_to_spec
        conn.send_msg_hello()
        del conn

    while True:
        try:
            receivedStrings.append(socket_to_spec.recv(4096))
        except:
            receivedStrings.append("")

        if receivedStrings[-1] == "":
            conn = connection_ref()
            if conn is None:
                break
            conn.handle_close()
            del conn
            break

        s = ''.join(receivedStrings)
        consumedBytes = 0
        offset = 0

        while offset < len(s):
            if message is None:
                message = SpecMessage.message(version=serverVersion)

            consumedBytes = message.readFromStream(s[offset:])

            if consumedBytes == 0:
                break

            offset += consumedBytes

            if message.isComplete():
                conn = connection_ref()
                if conn is None:
                    break

                try:
                    try:
                        # dispatch incoming message
                        if message.cmd == SpecMessage.REPLY:
                            replyID = message.sn
                            if replyID > 0:
                                try:
                                    reply = conn.registeredReplies[replyID]
                                except:
                                    logging.getLogger("SpecClient").exception(
                                        "Unexpected error while receiving a message from server"
                                    )
                                else:
                                    del conn.registeredReplies[replyID]
                                    #replies_queue.put((reply, message.data, message.type==SpecMessage.ERROR, message.err))
                                    gevent.spawn(
                                        reply.update, message.data,
                                        message.type == SpecMessage.ERROR,
                                        message.err)
                                    time.sleep(1E-6)
                        elif message.cmd == SpecMessage.EVENT:
                            try:
                                channel = conn.registeredChannels[message.name]
                            except KeyError:
                                pass
                            else:
                                #channels_queue.put((channel, message.data, message.flags == SpecMessage.DELETED))
                                gevent.spawn(
                                    channel.update, message.data,
                                    message.flags == SpecMessage.DELETED)
                                time.sleep(1E-6)
                        elif message.cmd == SpecMessage.HELLO_REPLY:
                            if conn.checkourversion(message.name):
                                serverVersion = message.vers  #header version
                                conn.serverVersion = serverVersion
                                gevent.spawn(conn.specConnected)
                                time.sleep(1E-6)
                            else:
                                serverVersion = None
                                conn.serverVersion = None
                                conn.connected = False
                                conn.disconnect()
                                conn.state = DISCONNECTED
                                if conn.scanport:
                                    conn.port += 1
                    except:
                        receivedStrings = [s[offset:]]
                        raise
                finally:
                    del conn
                    message = None

            receivedStrings = [s[offset:]]
Example #39
0
 def send_msg_close(self):
     """Send a close message."""
     if self.isSpecConnected():
         self.__send_msg_no_reply(SpecMessage.msg_close(version=self.serverVersion))
     else:
         raise SpecClientNotConnectedError
Example #40
0
 def send_msg_hello(self):
     """Send a hello message."""
     self.__send_msg_no_reply(SpecMessage.msg_hello())
Example #41
0
 def send_msg_abort(self, wait=False):
     """Send an abort message."""
     if self.isSpecConnected():
         self.__send_msg_no_reply(SpecMessage.msg_abort(version=self.serverVersion), wait)
     else:
         raise SpecClientNotConnectedError
Example #42
0
    def handle_read(self):
        """Handle 'read' events on socket

        Messages are built from the read calls on the socket.
        """
        _received = self.recv(32768)

        #if is_python3():
        #_received = _received.decode('utf-8')

        self.receivedStrings.append(_received)

        log.log(DEBUG, "received new data from spec")

        if is_python3():
            s = b''.join(self.receivedStrings)
            sbuffer = memoryview(s)
            #sbuffer = bytes(sbuffer).decode('utf-8')
        else:
            s = ''.join(self.receivedStrings)
            sbuffer = buffer(s)

        consumedBytes = 0
        offset = 0

        while offset < len(sbuffer):
            if self.message is None:
                log.log(DEBUG, "creating a new message")
                self.message = SpecMessage.message(version=self.serverVersion)
            else:
                log.log(DEBUG, "adding data to existing message")

            consumedBytes = self.message.readFromStream(sbuffer[offset:])
            log.log(DEBUG, "  bytes consumed %s" % consumedBytes)

            log.log(DEBUG, " message complete? %s" % self.message.isComplete())

            if consumedBytes == 0:
                log.log(DEBUG, "  no bytes consumed")
                break

            offset += consumedBytes

            if self.message.isComplete():
                log.log(
                    DEBUG, "new message from spec %s / name %s" %
                    (self.message.cmd, self.message.name))
                try:
                    # dispatch incoming message
                    if self.message.cmd == SpecMessage.REPLY:
                        replyID = self.message.sn

                        if replyID > 0:
                            try:
                                reply = self.registeredReplies[replyID]
                            except:
                                log.exception(
                                    "Unexpected error while receiving a message from server"
                                )
                            else:
                                del self.registeredReplies[replyID]

                                reply.update(
                                    self.message.data,
                                    self.message.type == SpecMessage.ERROR,
                                    self.message.err)
                                #SpecEventsDispatcher.emit(self, 'replyFromSpec', (replyID, reply, ))
                    elif self.message.cmd == SpecMessage.EVENT:
                        log.log(
                            2, "got a new event from spec name=%s, data=%s" %
                            (self.message.name, self.message.data))
                        try:
                            self.registeredChannels[self.message.name].update(
                                self.message.data,
                                self.message.flags == SpecMessage.DELETED)
                        except KeyError:
                            import traceback
                            log.log(2, traceback.format_exc())
                        except:
                            import traceback
                            log.log(2, traceback.format_exc())
                        log.log(
                            DEBUG,
                            "AFTER event: %s" % str(self.registeredChannels))
                    elif self.message.cmd == SpecMessage.HELLO_REPLY:
                        if self.checkourversion(self.message.name):
                            self.serverVersion = self.message.vers  #header version
                            #self.state = CONNECTED
                            log.log(DEBUG, "Hello reply. all right. connected")
                            self.specConnected()
                        else:
                            self.serverVersion = None
                            self.connected = False
                            self.close()
                            self.state = DISCONNECTED
                except:
                    self.message = None
                    self.receivedStrings = [s[offset:]]
                    raise
                else:
                    self.message = None

        self.receivedStrings = [s[offset:]]
Example #43
0
def connectionHandler(connection_ref, socket_to_spec):
    receivedStrings = []
    message = None
    serverVersion = None
    socket_to_spec.settimeout(None)

    conn = connection_ref()
    if conn is not None:
        conn.connected = True
        conn.state = WAITINGFORHELLO
        conn.socket = socket_to_spec
        conn.send_msg_hello()
        del conn

    while True:
        try:
            receivedStrings.append(socket_to_spec.recv(4096))
        except:
            receivedStrings.append("")

        if receivedStrings[-1] == "":
            conn = connection_ref()
            if conn is None:
                break
            conn.handle_close()
            del conn
            break

        s = "".join(receivedStrings)
        consumedBytes = 0
        offset = 0

        while offset < len(s):
            if message is None:
                message = SpecMessage.message(version=serverVersion)

            consumedBytes = message.readFromStream(s[offset:])

            if consumedBytes == 0:
                break

            offset += consumedBytes

            if message.isComplete():
                conn = connection_ref()
                if conn is None:
                    break

                try:
                    try:
                        # dispatch incoming message
                        if message.cmd == SpecMessage.REPLY:
                            replyID = message.sn
                            if replyID > 0:
                                try:
                                    reply = conn.registeredReplies[replyID]
                                except:
                                    logging.getLogger("SpecClient").exception(
                                        "Unexpected error while receiving a message from server"
                                    )
                                else:
                                    del conn.registeredReplies[replyID]
                                    # replies_queue.put((reply, message.data, message.type==SpecMessage.ERROR, message.err))
                                    gevent.spawn(
                                        reply.update, message.data, message.type == SpecMessage.ERROR, message.err
                                    )
                                    time.sleep(1e-6)
                        elif message.cmd == SpecMessage.EVENT:
                            try:
                                channel = conn.registeredChannels[message.name]
                            except KeyError:
                                pass
                            else:
                                # channels_queue.put((channel, message.data, message.flags == SpecMessage.DELETED))
                                gevent.spawn(channel.update, message.data, message.flags == SpecMessage.DELETED)
                                time.sleep(1e-6)
                        elif message.cmd == SpecMessage.HELLO_REPLY:
                            if conn.checkourversion(message.name):
                                serverVersion = message.vers  # header version
                                conn.serverVersion = serverVersion
                                gevent.spawn(conn.specConnected)
                                time.sleep(1e-6)
                            else:
                                serverVersion = None
                                conn.serverVersion = None
                                conn.connected = False
                                conn.disconnect()
                                conn.state = DISCONNECTED
                                if conn.scanport:
                                    conn.port += 1
                    except:
                        receivedStrings = [s[offset:]]
                        raise
                finally:
                    del conn
                    message = None

            receivedStrings = [s[offset:]]
Example #44
0
 def send_hello_reply(self, replyID, serverName):
     self.sendq.append(SpecMessage.msg_hello_reply(replyID, serverName, version = self.clientVersion, order=self.clientOrder))