Exemplo n.º 1
0
    def ConnectToServer(self, func_id):
        """This function creates a connection to TCP server and sends/receives
            message.

        Args:
            func_id: This is the unique key corresponding to a function and
                also the id field of the request_message that we send to the
                server.

        Returns:
            response_message: The object that the TCP host returns.

        Raises:
            TcpServerConnectionError: Exception occurred while stopping server.
        """
        # This object is sent to the TCP host
        request_message = SysMsg_pb2.AndroidSystemCallbackRequestMessage()
        request_message.id = func_id

        #  The response in string format that we receive from host
        received_message = ""

        # The final object that this function returns
        response_message = SysMsg_pb2.AndroidSystemCallbackResponseMessage()

        # Create a socket (SOCK_STREAM means a TCP socket)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        host = self._callback_server.ip
        port = self._callback_server.port
        logging.debug('Sending Request to host %s using port %s', host, port)

        try:
            # Connect to server and send request_message
            sock.connect((host, port))

            message = request_message.SerializeToString()
            sock.sendall(str(len(message)) + "\n" + message)
            logging.debug("Sent: %s", message)

            # Receive request_message from the server and shut down
            received_message = sock.recv(1024)
            response_message.ParseFromString(received_message)
            logging.debug('Received: %s', received_message)
        except socket_error as e:
            logging.error(e)
            raise errors.TcpServerConnectionError('Exception occurred.')
        finally:
            sock.close()

        return response_message
Exemplo n.º 2
0
    def RecvResponse(self, retries=0):
        """Receives and parses the response, and returns the relevant ResponseMessage.

        Args:
            retries: an integer indicating the max number of retries in case of
                     session timeout error.
        """
        for index in xrange(1 + retries):
            try:
                if index != 0:
                    logging.info("retrying...")
                header = self.channel.readline().strip("\n")
                length = int(header) if header else 0
                logging.debug("resp %d bytes", length)
                data = self.channel.read(length)
                response_msg = SysMsg_pb2.AndroidSystemControlResponseMessage()
                response_msg.ParseFromString(data)
                logging.debug(
                    "Response %s", "success"
                    if response_msg.response_code == SysMsg_pb2.SUCCESS else
                    "fail")
                return response_msg
            except socket.timeout as e:
                logging.exception(e)
        return None
Exemplo n.º 3
0
    def handle(self):
        """Receives requests from clients.

        When a callback happens on the target side, a request message is posted
        to the host side and is handled here. The message is parsed and the
        appropriate callback function on the host side is called.
        """
        header = self.rfile.readline().strip()
        try:
            len = int(header)
        except ValueError:
            if header:
                logging.exception(
                    "Unable to convert '%s' into an integer, which "
                    "is required for reading the next message." % header)
                raise
            else:
                logging.error(
                    'CallbackRequestHandler received empty message header. Skipping...'
                )
                return
        # Read the request message.
        received_data = self.rfile.read(len)
        logging.debug("Received callback message: %s", received_data)
        request_message = SysMsg.AndroidSystemCallbackRequestMessage()
        request_message.ParseFromString(received_data)
        logging.debug('Handling callback ID: %s', request_message.id)
        response_message = SysMsg.AndroidSystemCallbackResponseMessage()
        # Call the appropriate callback function and construct the response
        # message.
        if request_message.id in _functions:
            callback_args = []
            for arg in request_message.arg:
                callback_args.append(pb2py.Convert(arg))
            args = tuple(callback_args)
            _functions[request_message.id](*args)
            response_message.response_code = SysMsg.SUCCESS
        else:
            logging.error("Callback function ID %s is not registered!",
                          request_message.id)
            response_message.response_code = SysMsg.FAIL

        # send the response back to client
        message = response_message.SerializeToString()
        # self.request is the TCP socket connected to the client
        self.request.sendall(message)
Exemplo n.º 4
0
    def SendCommand(self,
                    command_type,
                    paths=None,
                    file_path=None,
                    bits=None,
                    target_class=None,
                    target_type=None,
                    target_version_major=None,
                    target_version_minor=None,
                    target_package=None,
                    target_component_name=None,
                    hw_binder_service_name=None,
                    is_test_hal=None,
                    module_name=None,
                    service_name=None,
                    callback_port=None,
                    driver_type=None,
                    shell_command=None,
                    caller_uid=None,
                    arg=None,
                    fmq_request=None,
                    hidl_memory_request=None,
                    hidl_handle_request=None):
        """Sends a command.

        Args:
            command_type: integer, the command type.
            each of the other args are to fill in a field in
            AndroidSystemControlCommandMessage.
        """
        if not self.channel:
            raise errors.VtsTcpCommunicationError(
                "channel is None, unable to send command.")

        command_msg = SysMsg_pb2.AndroidSystemControlCommandMessage()
        command_msg.command_type = command_type
        logging.debug("sending a command (type %s)",
                      COMMAND_TYPE_NAME[command_type])
        if command_type == 202:
            logging.debug("target API: %s", arg)

        if target_class is not None:
            command_msg.target_class = target_class

        if target_type is not None:
            command_msg.target_type = target_type

        if target_version_major is not None:
            command_msg.target_version_major = target_version_major

        if target_version_minor is not None:
            command_msg.target_version_minor = target_version_minor

        if target_package is not None:
            command_msg.target_package = target_package

        if target_component_name is not None:
            command_msg.target_component_name = target_component_name

        if hw_binder_service_name is not None:
            command_msg.hw_binder_service_name = hw_binder_service_name

        if is_test_hal is not None:
            command_msg.is_test_hal = is_test_hal

        if module_name is not None:
            command_msg.module_name = module_name

        if service_name is not None:
            command_msg.service_name = service_name

        if driver_type is not None:
            command_msg.driver_type = driver_type

        if paths is not None:
            command_msg.paths.extend(paths)

        if file_path is not None:
            command_msg.file_path = file_path

        if bits is not None:
            command_msg.bits = bits

        if callback_port is not None:
            command_msg.callback_port = callback_port

        if caller_uid is not None:
            command_msg.driver_caller_uid = caller_uid

        if arg is not None:
            command_msg.arg = arg

        if shell_command is not None:
            if isinstance(shell_command, (list, tuple)):
                command_msg.shell_command.extend(shell_command)
            else:
                command_msg.shell_command.append(shell_command)

        if fmq_request is not None:
            command_msg.fmq_request.CopyFrom(fmq_request)

        if hidl_memory_request is not None:
            command_msg.hidl_memory_request.CopyFrom(hidl_memory_request)

        if hidl_handle_request is not None:
            command_msg.hidl_handle_request.CopyFrom(hidl_handle_request)

        logging.debug("command %s" % command_msg)
        message = command_msg.SerializeToString()
        message_len = len(message)
        logging.debug("sending %d bytes", message_len)
        self.channel.write(str(message_len) + b'\n')
        self.channel.write(message)
        self.channel.flush()