Exemplo n.º 1
0
    def post(self, request, sessions, *args, **kwargs):
        """Release the given resources one by one."""
        errors = {}
        username = get_username(request)
        session = sessions[request.model.token]
        with transaction.atomic():
            for name in request.model.resources:
                try:
                    resource_data = ResourceData.objects.select_for_update() \
                        .get(name=name)

                except ObjectDoesNotExist:
                    errors[name] = (ResourceDoesNotExistError.ERROR_CODE,
                                    "Resource %r doesn't exist" % name)
                    continue

                resource = get_sub_model(resource_data)

                try:
                    self.release_resource(resource, username)
                    session.resources.remove(resource)

                except ServerError as ex:
                    errors[name] = (ex.ERROR_CODE, ex.get_error_content())

        if len(errors) > 0:
            return Response(
                {
                    "errors": errors,
                    "details": "errors occurred while releasing resource"
                },
                status=httplib.BAD_REQUEST)

        return Response({}, status=httplib.NO_CONTENT)
Exemplo n.º 2
0
    def get(self, request, sessions, *args, **kwargs):
        """Initialize the tests run data."""
        parameters = {"test_name": request.model.test_name}
        if request.model.max_sample_size is not None:
            parameters["max_size"] = request.model.max_sample_size

        test_durations = collect_durations(**parameters)
        if len(test_durations) < 1:
            raise BadRequest("No test history found!")

        parameters = {"durations": test_durations}
        if request.model.min_duration_cut is not None:
            parameters["min_duration_cut"] = request.model.min_duration_cut
        if request.model.max_iterations is not None:
            parameters["max_iterations"] = request.model.max_iterations
        if request.model.acceptable_ratio is not None:
            parameters["acceptable_ratio"] = request.model.acceptable_ratio

        test_durations = clean_data(**parameters)
        if len(test_durations) < 1:
            raise BadRequest("Test history disparity too wide!")

        response = {
            "min": min(test_durations),
            "avg": sum(test_durations) / len(test_durations),
            "max": max(test_durations)
        }

        return Response(response, status=http_client.OK)
Exemplo n.º 3
0
    def get(self, request, sessions, *args, **kwargs):
        """Check if the test passed in the last run according to results DB.

        Args:
            test_id (number): the identifier of the test.
            token (str): token of the session.
        """
        session_token = request.model.token
        try:
            session_data = sessions[session_token]
            test_data = session_data.all_tests[request.model.test_id]

        except KeyError:
            raise BadRequest("Invalid token/test_id provided!")

        run_data = session_data.run_data

        test_should_skip = test_data.should_skip(test_name=test_data.name,
                                                 run_data=run_data,
                                                 exclude_pk=test_data.pk)
        reason = SKIP_DELTA_MESSAGE if test_should_skip else ""

        return Response({
            "should_skip": test_should_skip,
            "reason": reason
        }, status=httplib.OK)
Exemplo n.º 4
0
    def post(self, request, *args, **kwargs):
        """Find and return the resources that answer the client's query.

        Args:
            request (Request): QueryResources request.

        Returns:
            ResourcesReply. a reply containing matching resources.
        """
        try:
            descriptor = ResourceDescriptor.decode(request.model.obj)

        except ResourceTypeError as e:
            raise BadRequest(str(e))

        # query for resources that are usable and match the descriptors
        query = (Q(is_usable=True, **descriptor.properties))
        query_result = []
        with transaction.atomic():
            matches = descriptor.type.objects.select_for_update().filter(query)

            if matches.count() == 0:
                raise BadRequest("No existing resource meets "
                                 "the requirements: {!r}".format(descriptor))

            encoder = JSONParser()
            query_result = [
                encoder.recursive_encode(resource) for resource in matches
            ]

        return Response({"resource_descriptors": query_result},
                        status=http_client.OK)
Exemplo n.º 5
0
    def post(self, request, sessions, *args, **kwargs):
        """Update the resources list for a test data.

        Args:
            test_id (number): the identifier of the test.
            descriptors (list): the resources the test used.
        """
        session_token = request.model.test_details.token
        try:
            session_data = sessions[session_token]
            test_data = \
                session_data.all_tests[request.model.test_details.test_id]

        except KeyError:
            raise BadRequest("Invalid token/test_id provided "
                             "(Test timed out?)")

        test_data.resources.clear()

        for resource_descriptor in request.model.descriptors:
            resource_dict = ResourceDescriptor.decode(resource_descriptor)
            test_data.resources.add(resource_dict.type.objects.get(
                **resource_dict.properties))

        test_data.save()

        return Response({}, status=http_client.NO_CONTENT)
Exemplo n.º 6
0
    def post(self, request, sessions, *args, **kwargs):
        """Lock the given resources one by one.

        Note:
            If one of the resources fails to lock, all the resources that has
            been locked until that resource will be released.
        """
        username = get_username(request)
        session = sessions[request.model.token]
        descriptors = request.model.descriptors

        if not auth_models.User.objects.filter(username=username).exists():
            raise BadRequest(USER_NOT_EXIST.format(username))

        locked_resources = []
        user = auth_models.User.objects.get(username=username)
        groups = list(user.groups.all())
        with transaction.atomic():
            for descriptor_dict in descriptors:
                locked_resources.append(
                    self._try_to_lock_available_resource(
                        username, groups, descriptor_dict))

        for resource in locked_resources:
            session.resources.append(resource)

        encoder = JSONParser()
        response = [
            encoder.encode(_resource) for _resource in locked_resources
        ]
        return Response({"resource_descriptors": response}, status=httplib.OK)
Exemplo n.º 7
0
    def post(self, request, sessions, *args, **kwargs):
        """Initialize the tests run data.

        Args:
            tests_tree (dict): contains the hierarchy of the tests in the run.
            run_data (dict): contains additional data about the run.
        """
        try:
            run_data = RunData.objects.create(**request.model.run_data)

        except TypeError:
            raise BadRequest("Invalid run data provided!")

        all_tests = {}
        tests_tree = request.model.tests
        try:
            main_test = self._create_test_data(tests_tree, run_data, all_tests)

        except KeyError:
            raise BadRequest("Invalid tests tree provided!")

        run_data.main_test = main_test
        run_data.user_name = request.get_host()
        run_data.save()

        session = sessions[request.model.token]
        session.all_tests = all_tests
        session.run_data = run_data
        session.main_test = main_test

        return Response({}, status=httplib.NO_CONTENT)
Exemplo n.º 8
0
    def post(self, request, sessions, *args, **kwargs):
        """Initialize the tests run data."""
        session_token = request.model.token
        try:
            session_data = sessions[session_token]

        except KeyError:
            raise BadRequest("Invalid token provided!")

        run_data = session_data.run_data
        RunData.objects.filter(pk=run_data.pk).update(**request.model.run_data)

        return Response({}, status=http_client.NO_CONTENT)
Exemplo n.º 9
0
    def get(self, request, sessions, *args, **kwargs):
        """Initialize the tests run data.

        Args:
            tests_tree (dict): contains the hierarchy of the tests in the run.
            run_data (dict): contains additional data about the run.
        """
        session_token = str(uuid.uuid4())
        sessions[session_token] = SessionData()
        response = {
            "token": session_token
        }
        return Response(response, status=httplib.OK)
Exemplo n.º 10
0
    def post(self, request, sessions, *args, **kwargs):
        """Clean up user's requests and locked resources.

        Args:
            username (str): the username to cleanup.

        Returns:
            SuccessReply. a reply indicating on a successful operation.
        """
        username = get_username(request)
        session = sessions[request.model.token]
        for resource in session.resources:
            ReleaseResources.release_resource(resource, username=None)

        return Response({
            "details": "User {} was successfully cleaned".format(username)
        }, status=http_client.NO_CONTENT)
Exemplo n.º 11
0
    def post(self, request, sessions, *args, **kwargs):
        """End a test run.

        Args:
            request (Request): StopTest request.
        """
        session_token = request.model.token
        try:
            session_data = sessions[session_token]
            test_data = session_data.all_tests[request.model.test_id]

        except KeyError:
            raise BadRequest("Invalid token/test_id provided!")

        test_data.end()
        test_data.save()

        return Response({}, status=httplib.NO_CONTENT)
Exemplo n.º 12
0
    def post(self, request, sessions, *args, **kwargs):
        """Update the test data to 'in progress' state and set the start time.

        Args:
            test_id (number): the identifier of the test.
        """
        session_token = request.model.token
        try:
            session_data = sessions[session_token]
            test_data = session_data.all_tests[request.model.test_id]

        except KeyError:
            raise BadRequest("Invalid token/test_id provided!")

        test_data.start()
        test_data.save()

        return Response({}, status=httplib.NO_CONTENT)
Exemplo n.º 13
0
    def post(self, request, *args, **kwargs):
        """Get signature data for an error or create a new one."""
        error_message = request.model.error
        # Normalize newline char
        error_message = error_message.replace("\r\n", "\n")

        match = self._match_signatures(error_message)

        is_new = False
        if match is None:
            is_new = True
            pattern = SignatureData.create_pattern(error_message)
            match = SignatureData.objects.create(link="", pattern=pattern)

        return Response({
            "is_new": is_new,
            "id": match.id,
            "link": match.link
        },
                        status=http_client.OK)
Exemplo n.º 14
0
    def post(self, request, sessions, *args, **kwargs):
        """Save the composite test's data.

        Args:
            test_id (number): the identifier of the test.
        """
        session_token = request.model.token
        try:
            session_data = sessions[session_token]
            test_data = session_data.all_tests[request.model.test_id]

        except KeyError:
            raise BadRequest("Invalid token/test_id provided!")

        has_succeeded = all(sub_test.success for sub_test in test_data)
        test_data.success = has_succeeded
        test_data.end()
        test_data.save()

        return Response({}, status=httplib.NO_CONTENT)
Exemplo n.º 15
0
    def put(self, request, *args, **kwargs):
        """Update content in the server's DB.

        Args:
            model (type): Django model to apply changes on.
            filter (dict): arguments to filter by.
            changes (dict): the additional arguments are the changes to
                apply on the filtered instances.
        """
        model = extract_type(request.model.resource_descriptor.type)
        filter_dict = request.model.resource_descriptor.properties
        kwargs_vars = request.model.changes
        with transaction.atomic():
            objects = model.objects.select_for_update()
            if filter_dict is not None and len(filter_dict) > 0:
                objects.filter(**filter_dict).update(**kwargs_vars)

            else:
                objects.all().update(**kwargs_vars)

        return Response({}, status=httplib.NO_CONTENT)
Exemplo n.º 16
0
    def post(self, request, sessions, *args, **kwargs):
        """Add a result to the test.

        Args:
            test_id (number): the identifier of the test.
            result_code (number): code of the result as defined in TestOutcome.
            info (str): additional info (traceback / end reason etc).
        """
        session_token = request.model.test_details.token
        try:
            session_data = sessions[session_token]
            test_data = \
                session_data.all_tests[request.model.test_details.test_id]

        except KeyError:
            raise BadRequest("Invalid token/test_id provided!")

        test_data.update_result(request.model.result.result_code,
                                request.model.result.info)
        test_data.save()

        return Response({}, status=httplib.NO_CONTENT)
Exemplo n.º 17
0
 def get(self, request, sessions, *args, **kwargs):
     """Create a session for the client and return its unique token."""
     session_token = str(uuid.uuid4())
     sessions[session_token] = SessionData()
     response = {"token": session_token}
     return Response(response, status=http_client.OK)