Exemplo n.º 1
0
    def __set_material(self, visual_path, material):
        """
        Sets the material of a particular visual

        :param visual_path: The visual path in the world description,
                            e.g., 'left_screen::body::screen_glass',
                            i.e., model_name::link_name::visual_name.
        :param material: The material
        :return: The response
        """
        try:
            rospy.wait_for_service('/gazebo/set_visual_properties', 3)
        except rospy.ROSException as exc:
            raise NRPServicesUnavailableROSService(str(exc))
        set_visual_properties = rospy.ServiceProxy(
            '/gazebo/set_visual_properties', SetVisualProperties)
        names = visual_path.split('::')
        if len(names) < 3:
            raise NRPServicesClientErrorException(
                "Invalid visual path: " + visual_path +
                ".\n Expected: model_name::link_name::visual_name",
                error_code=404)
        assert (material is not None)
        try:
            set_visual_properties(model_name=names[0],
                                  link_name="::".join(names[1:-1]),
                                  visual_name=names[-1],
                                  property_name='material:script:name',
                                  property_value=material)
        except rospy.ServiceException as exc:
            raise NRPServicesGeneralException(
                "Service did not process request: " + str(exc),
                "rospy service exception")
        return {'message': 'Material changed successfully'}, 200
Exemplo n.º 2
0
    def get(self, sim_id, command):
        """
        Queries the simulation recorder for a value/status. See parameter description for
        supported query commands.

        :param sim_id: The simulation ID to command.
        :param command: The command to query, supported: [is-recording]

        :status 500: {0}
        :status 404: {1}
        :status 200: Success. The query was issued and value returned.
        """

        # validate simulation id, allow any users/viewers to query recorder
        sim = _get_simulation_or_abort(sim_id)

        # validate the command type
        if command not in ['is-recording']:
            raise NRPServicesClientErrorException('Invalid recorder query: %s' % command,
                                                  error_code=404)

        # command the recorder, return boolean state as a string
        try:
            state = str(sim.cle.command_simulation_recorder(SimulationRecorderRequest.STATE).value)
            return state, 200

        # internal CLE ROS error if service call fails, notify frontend
        except ROSCLEClientException as e:
            raise NRPServicesGeneralException(str(e), 'CLE error', 500)
Exemplo n.º 3
0
    def delete(self, sim_id, state_machine_name):
        """
        Delete a state machine

        :param sim_id: The simulation ID
        :param state_machine_name: The name of the state machine to be deleted

        :status 500: {0}
        :status 404: {1}
        :status 401: {2}
        :status 200: The delete operation was successfully called. This does not imply that the
                     state machine function was correctly deleted though.
        """
        simulation = _get_simulation_or_abort(sim_id)
        if not UserAuthentication.matches_x_user_name_header(request, simulation.owner):
            raise NRPServicesWrongUserException()

        failure_message = "State machine destruction failed: "
        try:
            ok, response_message = simulation.delete_state_machine(state_machine_name)
            if ok:
                return "Success. The state machine was successfully deleted.", 200
        except Exception as e:
            info = exc_info()
            raise NRPServicesGeneralException(
                failure_message +
                " {0}: {1}".format(e.__class__.__name__, e.message),
                "State machine error",
            ), None, info[2]
        raise NRPServicesStateMachineException(failure_message + "\n" + response_message, 404)
Exemplo n.º 4
0
    def put(self, sim_id, state_machine_name):
        """
        Applies user changes to state machine code.
        If the simulation is paused or started, it will be paused.
        A stopped, created or failed simulation will fail the request with error code 403

        :param sim_id: The simulation ID
        :param state_machine_name: The name of the state machine to be modified

        :< json string data: The source code of the state machine

        :status 404: {0}
        :status 401: {1}
        :status 400: {2}
        :status 200: Success. The code was successfully patched
        """
        simulation = _get_simulation_or_abort(sim_id)
        assert simulation, Simulation
        if not UserAuthentication.matches_x_user_name_header(request, simulation.owner):
            raise NRPServicesWrongUserException()

        state_machine_source = request.data
        try:
            simulation.set_state_machine_code(
                state_machine_name,
                state_machine_source
            )
            return "Success. The code was successfully patched.", 200
        except (AttributeError, NameError) as e:
            info = exc_info()
            raise NRPServicesStateMachineException(e.message, 400), None, info[2]

        except SyntaxError as e:
            info = exc_info()
            args_txt = ""
            for text in e.args:
                args_txt += " {0}".format(text)
            raise NRPServicesStateMachineException(
                "The source code is invalid: "
                "SyntaxError in line {0}{1}.".format(e.lineno, args_txt),
                400
            ), None, info[2]

        except Exception as e:
            info = exc_info()
            raise NRPServicesGeneralException(
                "Update of state machine code failed. "
                "{0}: {1}".format(
                    e.__class__.__name__,
                    e.message
                ), "State machine error"
            ), None, info[2]
Exemplo n.º 5
0
 def parse_and_check_file_is_valid(filepath, create_obj_function,
                                   instance_type):
     """
     Parses a file and checks if it corresponds to its instance type and
     can be created into its object
     :param filepath: The path of the file
     :param create_obj_function: The function to create the object
     :param instance_type: The required instance type of the file
     :return: An object containing the file content
     """
     with open(filepath) as file_content:
         try:
             file_obj = create_obj_function(file_content.read())
             if not isinstance(file_obj, instance_type):
                 raise NRPServicesGeneralException(
                     "%s configuration file content is not valid." %
                     (filepath), "File not valid")
         except (ValidationError, SAXParseException) as ve:
             raise NRPServicesGeneralException(
                 "Could not parse file %s due to validation error: %s" %
                 (filepath, str(ve)), "File not valid")
     return file_obj
Exemplo n.º 6
0
    def test_storage_experiment_get_not_ok(self, storage_mock, mock_bp0):
        client_mock = MagicMock()
        client_mock.clone_file.side_effect = NRPServicesGeneralException(
            ErrorMessages.EXPERIMENT_CONF_FILE_NOT_FOUND_404,
            "Experiment xml not found in the storage"
        )

        storage_mock.return_value = client_mock
        mock_bp0.return_value = PATH

        response = self.client.get('/experiment/test_context')
        assert(isinstance(response, Response))
        self.assertEqual(response.status_code, 500)
        self.assertEqual(json.loads(response.get_data())['message'], ErrorMessages.EXPERIMENT_CONF_FILE_NOT_FOUND_404)
Exemplo n.º 7
0
    def put(self, sim_id):
        """
        Calls the CLE for resetting a given simulation.

        :param sim_id: The simulation ID.

        :> json resetType: the reset type the user wants to be performed, details about possible
            values are given in GazeboRosPackages/src/cle_ros_msgs/srv/ResetSimulation.srv

        :status 500: {0}
        :status 404: {1}
        :status 401: {2}
        :status 400: Invalid request, the JSON parameters are incorrect
        :status 200: The requested reset was performed successfully
        """

        sim = _get_simulation_or_abort(sim_id)

        if not UserAuthentication.matches_x_user_name_header(
                request, sim.owner):
            raise NRPServicesWrongUserException()

        body = request.get_json(force=True)

        for par in SimulationReset.ResetRequest.required:
            if par not in body:
                raise NRPServicesClientErrorException('Missing parameter %s' %
                                                      (par, ))

        for par in body:
            if par not in SimulationReset.ResetRequest.resource_fields:
                raise NRPServicesClientErrorException('Invalid parameter %s' %
                                                      (par, ))

        try:
            reset_type = body.get('resetType')
            if reset_type == ResetSimulationRequest.RESET_FULL:
                SimulationReset.reset_brain(sim)
                SimulationReset.reset_transfer_functions(sim)
                SimulationReset.reset_state_machines(sim)
                sim.cle.reset(reset_type)
            elif reset_type == ResetSimulationRequest.RESET_BRAIN:
                SimulationReset.reset_brain(sim)
            else:
                sim.cle.reset(reset_type)

        except ROSCLEClientException as e:
            raise NRPServicesGeneralException(str(e), 'CLE error', 500)

        return {}, 200
Exemplo n.º 8
0
 def test_nrp_services_general_exception(self):
     simulations[0]._Simulation__lifecycle = mock.MagicMock()
     simulations[0]._Simulation__lifecycle.accept_command = \
         mock.Mock(side_effect=NRPServicesGeneralException(\
             "I am a NRPServicesGeneralException message",
             "I am a NRPServicesGeneralException type"))
     response = self.client.put('/simulation/0/state',
                                data='{"state": "started"}')
     self.assertEqual(response.status_code, 500)
     response_object = json.loads(response.data)
     self.assertEqual(u"I am a NRPServicesGeneralException message",
                      response_object['message'])
     self.assertEqual(u"I am a NRPServicesGeneralException type",
                      response_object['type'])
Exemplo n.º 9
0
def pause_simulation_or_raise(simulation):
    """
    Pauses the simulation and raise an exception in case of failure.
    This is needed before an update of a state machine code

    :param simulation: The simulation to be reset
    """
    state = simulation.state
    if state == 'paused' or state == 'started':
        state = simulation.state = 'paused'

    if state != 'paused':
        raise NRPServicesGeneralException(
            "Simulation in state {0}. Can't update the state machine".format(state),
            "Server error", error_code=403
        )
Exemplo n.º 10
0
    def post(self, sim_id, command):
        """
        Issue user commands to the simulator recorder. See parameter description for
        supported query commands.

        :param sim_id: The simulation ID to command.
        :param command: The command to issue, supported: [start, stop, cancel, reset]

        :status 500: {0}
        :status 404: {1}
        :status 400: The command is invalid/refused by recorder - see message returned.
        :status 200: Success. The command was issued.
        """

        # validate simulation id
        sim = _get_simulation_or_abort(sim_id)

        # only the simulation owner can command the recorder
        if not UserAuthentication.matches_x_user_name_header(request, sim.owner):
            raise NRPServicesWrongUserException()

        # validate the command type
        valid_commands = {'start': SimulationRecorderRequest.START,
                          'stop': SimulationRecorderRequest.STOP,
                          'cancel': SimulationRecorderRequest.CANCEL,
                          'reset': SimulationRecorderRequest.RESET}
        if command not in valid_commands:
            raise NRPServicesClientErrorException('Invalid recorder command: %s' % command,
                                                  error_code=404)

        # command the recorder, if unsuccessful return the error message
        try:
            resp = sim.cle.command_simulation_recorder(valid_commands[command])

            # check the command success, on failure return status 400 + error
            if not resp.value:
                raise NRPServicesClientErrorException(resp.message)

            # successful, return status 200
            return 'success', 200

        # internal CLE ROS error if service call fails, notify frontend
        except ROSCLEClientException as e:
            raise NRPServicesGeneralException(str(e), 'CLE error', 500)
Exemplo n.º 11
0
 def test_nrp_services_general_exception(self):
     """
     This method tests the class hbp_nrp_backend.rest_server.NRPServicesGeneralException
     """
     nsge = NRPServicesGeneralException("StringA", "StringB")
     self.assertEqual(nsge.__str__(), "'StringA' (StringB)")