Example #1
0
 def test_generate_json_response_with_pulp_encoder(self, mock_json):
     """
     Ensure that the shortcut function uses the specified encoder.
     """
     test_content = {'foo': 'bar'}
     util.generate_json_response_with_pulp_encoder(test_content)
     mock_json.dumps.assert_called_once_with(test_content, default=pulp_json_encoder)
Example #2
0
    def put(self, request, repo_id):
        """
        Update a repository. This call will return synchronously unless a distributor is updated.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: id of repository to be updated
        :type  repo_id: str

        :return: Response containing a serialized dict for the updated repo.
        :rtype : django.http.HttpResponse

        :raises exceptions.OperationPostponed: if a task has been dispatched to update a
                                                    distributor
        """

        delta = request.body_as_json.get('delta', None)
        importer_config = request.body_as_json.get('importer_config', None)
        distributor_configs = request.body_as_json.get('distributor_configs', None)

        repo = model.Repository.objects.get_repo_or_missing_resource(repo_id)
        task_result = repo_controller.update_repo_and_plugins(repo, delta, importer_config,
                                                              distributor_configs)

        # Tasks are spawned if a distributor is updated, raise that as a result
        if task_result.spawned_tasks:
            raise exceptions.OperationPostponed(task_result)

        call_report = task_result.serialize()
        call_report['result'] = serializers.Repository(call_report['result']).data
        return generate_json_response_with_pulp_encoder(call_report)
Example #3
0
    def get(self, request, repo_id):
        """
        Looks for query parameters 'importers' and 'distributors', and will add
        the corresponding fields to the repository returned. Query parameter
        'details' is equivalent to passing both 'importers' and 'distributors'.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: id of requested repository
        :type  repo_id: str

        :return: Response containing a serialized dict for the requested repo.
        :rtype : django.http.HttpResponse
        :raises exceptions.MissingResource: if repo cannot be found
        """
        repo_obj = model.Repository.objects.get_repo_or_missing_resource(repo_id)
        repo = serializers.Repository(repo_obj).data

        # Add importers and distributors to the dicts if requested.
        details = request.GET.get('details', 'false').lower() == 'true'
        if request.GET.get('importers', 'false').lower() == 'true' or details:
            _merge_related_objects('importers', model.Importer, (repo,))
        if request.GET.get('distributors', 'false').lower() == 'true' or details:
            _merge_related_objects('distributors', model.Distributor, (repo,))
        if details:
            repo['total_repository_units'] = sum(repo['content_unit_counts'].itervalues())
            total_missing = repo_controller.missing_unit_count(repo_obj.repo_id)
            repo['locally_stored_units'] = repo['total_repository_units'] - total_missing

        return generate_json_response_with_pulp_encoder(repo)
Example #4
0
    def post(self, request):
        """
        Create a new repo. `id` field in body is required. `display_name` will default to `id`.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a serialized dict for the created repo.
        :rtype : django.http.HttpResponse
        """
        repo_data = request.body_as_json
        repo_id = repo_data.get('id')

        repo_obj = repo_controller.create_repo(
            repo_id,
            display_name=repo_data.get('display_name', repo_id),
            description=repo_data.get('description'),
            notes=repo_data.get('notes'),
            importer_type_id=repo_data.get('importer_type_id'),
            importer_repo_plugin_config=repo_data.get('importer_config'),
            distributor_list=repo_data.get('distributors')
        )

        repo = serializers.Repository(repo_obj).data
        response = generate_json_response_with_pulp_encoder(repo)
        return generate_redirect_response(response, repo['_href'])
Example #5
0
    def get(self, request, repo_id, distributor_id):
        """
        Retrieve publish history for a specified distributor.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: id of the repository
        :type  repo_id: str
        :param repo_id: retrieve the publish history of this distributor
        :type  repo_id: str

        :return: Response containing a list of dicts, one for each publish event
        :rtype : django.http.HttpResponse
        """

        sort = request.GET.get(constants.REPO_HISTORY_FILTER_SORT)
        start_date = request.GET.get(constants.REPO_HISTORY_FILTER_START_DATE)
        end_date = request.GET.get(constants.REPO_HISTORY_FILTER_END_DATE)
        limit = request.GET.get(constants.REPO_HISTORY_FILTER_LIMIT)
        if limit:
            try:
                limit = int(limit)
            except ValueError:
                raise pulp_exceptions.InvalidValue([constants.REPO_HISTORY_FILTER_LIMIT])
        if not sort:
            sort = constants.SORT_DESCENDING

        publish_manager = manager_factory.repo_publish_manager()
        entries = publish_manager.publish_history(repo_id, distributor_id, limit=limit, sort=sort,
                                                  start_date=start_date, end_date=end_date)
        return generate_json_response_with_pulp_encoder(entries)
Example #6
0
    def get(self, request, repo_id):
        """
        Retrieve sync history for a specified repository.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: id of the repository
        :type  repo_id: str

        :return: Response containing a list of dicts, one for each sync event
        :rtype : django.http.HttpResponse
        :raises pulp_exceptions.InvalidValue: if limit is not an integer
        """

        sort = request.GET.get(constants.REPO_HISTORY_FILTER_SORT)
        start_date = request.GET.get(constants.REPO_HISTORY_FILTER_START_DATE)
        end_date = request.GET.get(constants.REPO_HISTORY_FILTER_END_DATE)
        limit = request.GET.get(constants.REPO_HISTORY_FILTER_LIMIT)
        if limit:
            try:
                limit = int(limit)
            except ValueError:
                raise pulp_exceptions.InvalidValue([constants.REPO_HISTORY_FILTER_LIMIT])
        if not sort:
            sort = constants.SORT_DESCENDING

        sync_manager = manager_factory.repo_sync_manager()
        # Error checking is done on these options in the sync manager before the database is queried
        entries = sync_manager.sync_history(repo_id, limit=limit, sort=sort, start_date=start_date,
                                            end_date=end_date)
        return generate_json_response_with_pulp_encoder(entries)
Example #7
0
    def post(self, request, repo_id):
        """
        Associate a distributor with a repository.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: The id of the repository to associate with
        :type  repo_id: str

        :return: Response containing a dict of the associated distributor
        :rtype : django.http.HttpResponse
        """

        # Validation will occur in the manager
        distributor_type = request.body_as_json.get('distributor_type_id', None)
        distributor_config = request.body_as_json.get('distributor_config', None)
        distributor_id = request.body_as_json.get('distributor_id', None)
        auto_publish = request.body_as_json.get('auto_publish', False)

        distributor_manager = manager_factory.repo_distributor_manager()
        distributor = distributor_manager.add_distributor(
            repo_id, distributor_type, distributor_config, auto_publish, distributor_id
        )
        distributor['_href'] = reverse(
            'repo_distributor_resource',
            kwargs={'repo_id': repo_id, 'distributor_id': distributor['id']}
        )
        response = generate_json_response_with_pulp_encoder(distributor)
        return generate_redirect_response(response, distributor['_href'])
Example #8
0
    def post(self, request, repo_id, distributor_id):
        """
        Create a new scheduled publish.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: id of the repository
        :type  repo_id: str
        :param distributor_id: id of the distributor
        :type  distributor_id: str

        :return: Response containing a dict for the new scheduled publish
        :rtype : django.http.HttpResponse
        :raises exceptions.UnsupportedValue: if unsupported fields are included in body
        """

        manager = manager_factory.repo_publish_schedule_manager()
        publish_options = {'override_config': request.body_as_json.pop('override_config', {})}
        schedule = request.body_as_json.pop('schedule', None)
        failure_threshold = request.body_as_json.pop('failure_threshold', None)
        enabled = request.body_as_json.pop('enabled', True)
        if request.body_as_json:
            raise exceptions.UnsupportedValue(request.body_as_json.keys())

        schedule = manager.create(repo_id, distributor_id, publish_options,
                                  schedule, failure_threshold, enabled)
        ret = schedule.for_display()
        ret['_href'] = reverse('repo_publish_schedule_resource', kwargs={
            'repo_id': repo_id, 'distributor_id': distributor_id, 'schedule_id': schedule.id
        })
        response = generate_json_response_with_pulp_encoder(ret)
        return generate_redirect_response(response, ret['_href'])
Example #9
0
    def get(self, request, repo_id):
        """
        Looks for query parameters 'importers' and 'distributors', and will add
        the corresponding fields to the repository returned. Query parameter
        'details' is equivalent to passing both 'importers' and 'distributors'.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: id of requested repository
        :type  repo_id: str

        :return: Response containing a serialized dict for the requested repo.
        :rtype : django.http.HttpResponse
        :raises pulp_exceptions.MissingResource: if repo cannot be found
        """

        query_manager = manager_factory.repo_query_manager()
        repo = query_manager.find_by_id(repo_id)

        if repo is None:
            raise pulp_exceptions.MissingResource(repo=repo_id)

        repo['_href'] = reverse('repo_resource', kwargs={'repo_id': repo_id})
        _convert_repo_dates_to_strings(repo)

        details = request.GET.get('details', 'false').lower() == 'true'
        if request.GET.get('importers', 'false').lower() == 'true' or details:
            repo = _merge_related_objects(
                'importers', manager_factory.repo_importer_manager(), (repo,))[0]
        if request.GET.get('distributors', 'false').lower() == 'true' or details:
            repo = _merge_related_objects(
                'distributors', manager_factory.repo_distributor_manager(), (repo,))[0]

        return generate_json_response_with_pulp_encoder(repo)
Example #10
0
    def post(self, request):
        """
        Create a new repo. 'id' field in body is required.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a serialized dict for the created repo.
        :rtype : django.http.HttpResponse
        """

        # Pull the repo data out of the request body (validation will occur
        # in the manager)
        repo_data = request.body_as_json
        repo_id = repo_data.get('id', None)
        display_name = repo_data.get('display_name', None)
        description = repo_data.get('description', None)
        notes = repo_data.get('notes', None)

        importer_type_id = repo_data.get('importer_type_id', None)
        importer_repo_plugin_config = repo_data.get('importer_config', None)
        distributors = repo_data.get('distributors', None)

        # Creation
        repo_manager = manager_factory.repo_manager()
        args = [repo_id, display_name, description, notes]
        kwargs = {'importer_type_id': importer_type_id,
                  'importer_repo_plugin_config': importer_repo_plugin_config,
                  'distributor_list': distributors}
        repo = repo_manager.create_and_configure_repo(*args, **kwargs)
        repo['_href'] = reverse('repo_resource', kwargs={'repo_id': repo_id})
        response = generate_json_response_with_pulp_encoder(repo)
        return generate_redirect_response(response, repo['_href'])
Example #11
0
File: content.py Project: beav/pulp
    def get(self, request, type_id):
        """
        Return a response containing a dict with info about a content type.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param type_id: type of content unit
        :type  type_id: str

        :return: response containing a dict that contains info about a content type or
                 404 response if the specified content type is not found.
        :rtype : django.http.HttpResponse or HttpResponseNotFound
        """
        cqm = factory.content_query_manager()
        content_type = cqm.get_content_type(type_id)
        if content_type is None:
            msg = _('No content type resource: %(r)s') % {'r': type_id}
            return generate_json_response(msg, response_class=HttpResponseNotFound)
        resource = serialization.content.content_type_obj(content_type)
        # These urls are not valid endpoints but are left here for for semantic versioning.
        # BZ - 1187287
        links = {
            'actions': {'_href': '/'.join([request.get_full_path().rstrip('/'), 'actions/'])},
            'content_units': {'_href': '/'.join([request.get_full_path().rstrip('/'), 'units/'])}
        }
        resource.update(links)
        return generate_json_response_with_pulp_encoder(resource)
Example #12
0
    def get(self, request):
        """
        Retrieve permissions for all resources or for a particular resource.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of permissions for resource/s
        :rtype: django.http.HttpResponse
        """
        query_params = request.GET
        resource = query_params.get('resource', None)

        permissions = []
        if resource is None:
            permissions = factory.permission_query_manager().find_all()
        else:
            permission = factory.permission_query_manager().find_by_resource(resource)
            if permission is not None:
                permissions = [permission]

        for permission in permissions:
            # Isolate the database schema change to behind the api.  This should be transparent
            users = {}
            for item in permission['users']:
                users[item['username']] = item['permissions']
            permission['users'] = users
            permission_manager = factory.permission_manager()
            for user, ops in users.items():
                users[user] = [permission_manager.operation_value_to_name(o) for o in ops]

        return generate_json_response_with_pulp_encoder(permissions)
Example #13
0
    def post(self, request):
        """
        Create a consumer group and return a serialized object containing just created group.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :return: Response containing the consumer group
        :rtype: django.http.HttpResponse
        :raises: MissingValue if group ID is not provided
        :raises: InvalidValue if some parameters are invalid
        """
        params = request.body_as_json
        group_id = params.pop('id', None)
        if group_id is None:
            raise pulp_exceptions.MissingValue(['id'])
        display_name = params.pop('display_name', None)
        description = params.pop('description', None)
        consumer_ids = params.pop('consumer_ids', None)
        notes = params.pop('notes', None)
        if params:
            raise pulp_exceptions.InvalidValue(params.keys())
        manager = factory.consumer_group_manager()
        group = manager.create_consumer_group(group_id, display_name, description, consumer_ids,
                                              notes)
        link = {"_href": reverse('consumer_group_resource',
                kwargs={'consumer_group_id': group['id']})}
        group.update(link)
        response = generate_json_response_with_pulp_encoder(group)
        response_redirect = generate_redirect_response(response, link['_href'])
        return response_redirect
Example #14
0
    def get(self, request, consumer_id):
        """
        List schedules <action>.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: The consumer ID.
        :type consumer_id: str

        :raises MissingResource: if consumer does not exist

        :return: Response containing consumer's schedules <action>
        :rtype: django.http.HttpResponse
        """

        try:
            factory.consumer_manager().get_consumer(consumer_id)
        except MissingResource:
            raise MissingResource(consumer_id=consumer_id)
        schedules = self.manager.get(consumer_id, self.ACTION)

        schedule_objs = []
        for schedule in schedules:
            obj = scheduled_unit_management_obj(schedule.for_display())
            add_link_schedule(obj, self.ACTION, consumer_id)
            schedule_objs.append(obj)

        return generate_json_response_with_pulp_encoder(schedule_objs)
Example #15
0
    def put(self, request, repo_id):
        """
        Update a repository. This call will return synchronously unless a distributor is updated.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: id of repository to be updated
        :type  repo_id: str

        :return: Response containing a serialized dict for the updated repo.
        :rtype : django.http.HttpResponse
        :raises pulp_exceptions.OperationPostponed: if a distributor is updated, dispatch a task
        """

        delta = request.body_as_json.get('delta', None)
        importer_config = request.body_as_json.get('importer_config', None)
        distributor_configs = request.body_as_json.get('distributor_configs', None)
        repo_manager = manager_factory.repo_manager()
        task_result = repo_manager.update_repo_and_plugins(repo_id, delta, importer_config,
                                                           distributor_configs)
        repo = task_result.return_value
        repo['_href'] = reverse('repo_resource', kwargs={'repo_id': repo_id})
        _convert_repo_dates_to_strings(repo)

        # Tasks are spawned if a distributor is updated, raise that as a result
        if task_result.spawned_tasks:
            raise pulp_exceptions.OperationPostponed(task_result)

        result = task_result.serialize()
        return generate_json_response_with_pulp_encoder(result)
Example #16
0
    def post(self, request, repo_id):
        """
        Associate a distributor with a repository.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_id: The id of the repository to associate with
        :type  repo_id: basestring

        :return: Response containing the serialized distributor
        :rtype : django.http.HttpResponse
        """
        distributor_type = request.body_as_json.get('distributor_type_id')
        if distributor_type is None:
            raise exceptions.MissingValue('distributor_type_id')

        distributor_config = request.body_as_json.get('distributor_config')
        distributor_id = request.body_as_json.get('distributor_id')
        auto_publish = request.body_as_json.get('auto_publish', False)

        distributor = dist_controller.add_distributor(repo_id, distributor_type, distributor_config,
                                                      auto_publish, distributor_id)
        serialized = model.Distributor.SERIALIZER(distributor).data
        response = generate_json_response_with_pulp_encoder(serialized)
        return generate_redirect_response(response, serialized['_href'])
Example #17
0
    def _generate_response(cls, query, options, *args, **kwargs):
        """
        Perform the database query using the given search data, and return the resuls as a JSON
        serialized HttpReponse object.

        This overrides the base class so we can validate repo existance and to choose the search
        method depending on how many unit types we are dealing with.

        :param query: The criteria that should be used to search for objects
        :type  query: dict
        :param options: additional options for including extra data
        :type  options: dict

        :return:      The serialized search results in an HttpReponse
        :rtype:       django.http.HttpResponse
        """
        repo_id = kwargs.get('repo_id')
        model.Repository.objects.get_repo_or_missing_resource(repo_id)
        criteria = UnitAssociationCriteria.from_client_input(query)
        manager = manager_factory.repo_unit_association_query_manager()
        if criteria.type_ids is not None and len(criteria.type_ids) == 1:
            type_id = criteria.type_ids[0]
            units = manager.get_units_by_type(repo_id, type_id, criteria=criteria)
        else:
            units = manager.get_units(repo_id, criteria=criteria)
        for unit in units:
            content.remap_fields_with_serializer(unit['metadata'])
        return generate_json_response_with_pulp_encoder(units)
Example #18
0
    def post(self, request, consumer_id):
        """
        Associate a profile with a consumer by content type ID.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: A consumer ID.
        :type consumer_id: str

        :raises MissingValue: if some parameter were not provided

        :return: Response representing the created profile
        :rtype: django.http.HttpResponse
        """

        body = request.body_as_json
        content_type = body.get('content_type')
        profile = body.get('profile')

        manager = factory.consumer_profile_manager()
        new_profile = manager.create(consumer_id, content_type, profile)
        if content_type is None:
            raise MissingValue('content_type')
        link = add_link_profile(new_profile)
        response = generate_json_response_with_pulp_encoder(new_profile)
        redirect_response = generate_redirect_response(response, link['_href'])
        return redirect_response
Example #19
0
    def post(self, request, consumer_id):
        """
        Create a schedule.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: The consumer ID.
        :type consumer_id: str

        :raises UnsupportedValue: if some extra unsupported keys were specified.

        :return: Response containing just created schedule
        :rtype: django.http.HttpResponse
        """

        params = request.body_as_json
        units = params.pop('units', None)
        options = params.pop('options', {})
        schedule = params.pop('schedule', None)
        failure_threshold = params.pop('failure_threshold', None)
        enabled = params.pop('enabled', True)
        if params:
            raise UnsupportedValue(params.keys())
        scheduled_call = self.manager.create_schedule(
            self.ACTION, consumer_id, units, options, schedule, failure_threshold, enabled)

        scheduled_obj = scheduled_unit_management_obj(scheduled_call.for_display())
        link = add_link_schedule(scheduled_obj, self.ACTION, consumer_id)
        response = generate_json_response_with_pulp_encoder(scheduled_obj)
        redirect_response = generate_redirect_response(response, link['_href'])
        return redirect_response
Example #20
0
    def get(self, request, consumer_id, schedule_id):
        """
        List a specific schedule <action>.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: The consumer ID.
        :type consumer_id: str
        :param schedule_id: the schedule id
        :type schedule_id: str

        :raises MissingResource: if consumer/schedule does not exist

        :return: Response containing consumer's schedule <action>
        :rtype: django.http.HttpResponse
        """

        scheduled_call = None
        for call in self.manager.get(consumer_id, self.ACTION):
            if call.id == schedule_id:
                scheduled_call = call
                break
        if scheduled_call is None:
            raise MissingResource(consumer_id=consumer_id, schedule_id=schedule_id)

        scheduled_obj = scheduled_unit_management_obj(scheduled_call.for_display())
        add_link_schedule(scheduled_obj, self.ACTION, consumer_id)
        return generate_json_response_with_pulp_encoder(scheduled_obj)
Example #21
0
    def put(self, request, consumer_id, schedule_id):
        """
        Update a specific schedule <action>.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: The consumer ID.
        :type consumer_id: str
        :param schedule_id: the schedule id
        :type schedule_id: str

        :return: Response containing consumer's updated schedule <action>
        :rtype: django.http.HttpResponse
        """

        schedule_data = request.body_as_json
        options = schedule_data.pop('options', None)
        units = schedule_data.pop('units', None)

        if 'schedule' in schedule_data:
            schedule_data['iso_schedule'] = schedule_data.pop('schedule')

        schedule = self.manager.update_schedule(consumer_id, schedule_id, units,
                                                options, schedule_data)

        scheduled_obj = scheduled_unit_management_obj(schedule.for_display())
        add_link_schedule(scheduled_obj, self.ACTION, consumer_id)
        return generate_json_response_with_pulp_encoder(scheduled_obj)
Example #22
0
    def post(self, request):
        """
        Create a repo group from the data passed in the body.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a serialized dict of the new repo group
        :rtype: django.http.HttpResponse
        :raises pulp_exceptions.MissingValue: if required values are not passed into the body
        :raises pulp_exceptions.InvalidValue: if invalid values are passed into the body
        """
        group_data = request.body_as_json
        group_id = group_data.pop('id', None)
        if group_id is None:
            raise pulp_exceptions.MissingValue(['id'])
        display_name = group_data.pop('display_name', None)
        description = group_data.pop('description', None)
        repo_ids = group_data.pop('repo_ids', None)
        notes = group_data.pop('notes', None)
        distributors = group_data.pop('distributors', None)
        if group_data:
            raise pulp_exceptions.InvalidValue(group_data.keys())
        # Create the repo group
        manager = managers_factory.repo_group_manager()
        args = [group_id, display_name, description, repo_ids, notes]
        kwargs = {'distributor_list': distributors}
        group = manager.create_and_configure_repo_group(*args, **kwargs)
        group = _add_group_link(group)
        group['distributors'] = distributors or []
        response = generate_json_response_with_pulp_encoder(group)
        return generate_redirect_response(response, group['_href'])
Example #23
0
    def get(self, request):
        """
        List all roles.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of roles
        :rtype: django.http.HttpResponse
        """
        role_query_manager = factory.role_query_manager()
        permissions_manager = factory.permission_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            users = [u.login for u in user_controller.find_users_belonging_to_role(role["id"])]
            role["users"] = users

            resource_permission = {}
            # isolate schema change
            if role["permissions"]:
                for item in role["permissions"]:
                    resource = item["resource"]
                    operations = item.get("permission", [])
                    resource_permission[resource] = [permissions_manager.operation_value_to_name(o) for o in operations]

            role["permissions"] = resource_permission

            link = {"_href": reverse("role_resource", kwargs={"role_id": role["id"]})}
            role.update(link)
        return generate_json_response_with_pulp_encoder(roles)
Example #24
0
    def post(self, request, repo_group_id):
        """
        Asssociate a distributor with a repo group.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_group_id: matching distributors will be associated with this repo group
        :type  repo_group_id: str

        :return: response containing a serialized dict of the distributor association
        :rtype: django.http.HttpResponse
        """
        # Params (validation will occur in the manager)
        params = request.body_as_json
        distributor_type_id = params.get(distributor_constants.DISTRIBUTOR_TYPE_ID_KEY, None)
        distributor_config = params.get(distributor_constants.DISTRIBUTOR_CONFIG_KEY, None)
        distributor_id = params.get(distributor_constants.DISTRIBUTOR_ID_KEY, None)
        distributor_manager = managers_factory.repo_group_distributor_manager()
        created = distributor_manager.add_distributor(repo_group_id, distributor_type_id,
                                                      distributor_config, distributor_id)
        created['_href'] = reverse('repo_group_distributor_resource',
                                   kwargs={'repo_group_id': repo_group_id,
                                           'distributor_id': created['id']})
        response = generate_json_response_with_pulp_encoder(created)
        return generate_redirect_response(response, created['_href'])
Example #25
0
    def put(self, request, repo_group_id, distributor_id):
        """
        Change information about a single repo group distributor association.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_group_id: repo group the distributor is associated with
        :type  repo_group_id: str
        :param distributor_id: distributor to update
        :type  distributor_id: str

        :return: response containing a serialized dict of the modified distributor association
        :rtype: django.http.HttpResponse
        :raises pulp_exceptions.MissingValue: if param 'distributor_config' is not in the body
        """
        params = request.body_as_json
        distributor_config = params.get('distributor_config', None)
        if distributor_config is None:
            raise pulp_exceptions.MissingValue(['distributor_config'])
        distributor_manager = managers_factory.repo_group_distributor_manager()
        result = distributor_manager.update_distributor_config(repo_group_id, distributor_id,
                                                               distributor_config)
        result['_href'] = reverse(
            'repo_group_distributor_resource',
            kwargs={'repo_group_id': repo_group_id, 'distributor_id': distributor_id}
        )
        return generate_json_response_with_pulp_encoder(result)
Example #26
0
    def get(self, request, role_id):
        """
        Retrieve a specific role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: Response containing the role
        :rtype: django.http.HttpResponse
        :raises: MissingResource if role ID does not exist
        """
        role = factory.role_query_manager().find_by_id(role_id)
        if role is None:
            raise pulp_exceptions.MissingResource(role_id)
        role["users"] = [u.login for u in user_controller.find_users_belonging_to_role(role["id"])]
        permissions_manager = factory.permission_manager()
        # isolate schema change
        resource_permission = {}
        for item in role["permissions"]:
            resource = item["resource"]
            operations = item.get("permission", [])
            resource_permission[resource] = [permissions_manager.operation_value_to_name(o) for o in operations]
        role["permissions"] = resource_permission

        link = {"_href": reverse("role_resource", kwargs={"role_id": role["id"]})}
        role.update(link)
        return generate_json_response_with_pulp_encoder(role)
Example #27
0
    def get(self, request):
        """
        List all roles.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of roles
        :rtype: django.http.HttpResponse
        """
        role_query_manager = factory.role_query_manager()
        user_query_manager = factory.user_query_manager()
        permissions_manager = factory.permission_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            role['users'] = [u['login'] for u in
                             user_query_manager.find_users_belonging_to_role(role['id'])]

            resource_permission = {}
            # isolate schema change
            if role['permissions']:
                for item in role['permissions']:
                    resource = item['resource']
                    operations = item.get('permission', [])
                    resource_permission[resource] = [permissions_manager.operation_value_to_name(o)
                                                     for o in operations]

            role['permissions'] = resource_permission

            link = {'_href': reverse('role_resource',
                    kwargs={'role_id': role['id']})}
            role.update(link)
        return generate_json_response_with_pulp_encoder(roles)
Example #28
0
    def get(self, request):
        """
        Show current status of pulp server.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response showing surrent server status
        :rtype: django.http.HttpResponse
        """
        pulp_version = status_manager.get_version()
        pulp_db_connection = status_manager.get_mongo_conn_status()
        pulp_messaging_connection = status_manager.get_broker_conn_status()

        # do not ask for the worker list unless we have a DB connection
        if pulp_db_connection['connected']:
            # convert Worker documents to dicts
            pulp_workers = [w.to_mongo().to_dict() for w in status_manager.get_workers()]
        else:
            pulp_workers = []

        # 'api_version' is deprecated and can go away in 3.0, bz #1171763
        status_data = {'api_version': '2',
                       'versions': pulp_version,
                       'database_connection': pulp_db_connection,
                       'messaging_connection': pulp_messaging_connection,
                       'known_workers': pulp_workers}

        return generate_json_response_with_pulp_encoder(status_data)
Example #29
0
File: users.py Project: alanoe/pulp
    def get(self, request):
        """
        List all users.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of users
        :rtype: django.http.HttpResponse
        """
        users = model.User.SERIALIZER(model.User.objects(), multiple=True).data
        return generate_json_response_with_pulp_encoder(users)
Example #30
0
    def get(self, request):
        """
        List the available consumer groups.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :return: Response containing a list of consumer groups
        :rtype: django.http.HttpResponse
        """
        collection = ConsumerGroup.get_collection()
        cursor = collection.find({})
        groups = [serialize(group) for group in cursor]
        return generate_json_response_with_pulp_encoder(groups)
Example #31
0
    def put(self, request, role_id):
        """
        Update a specific role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: Response containing the role
        :rtype: django.http.HttpResponse
        """
        role_data = request.body_as_json
        delta = role_data.get('delta', None)
        manager = factory.role_manager()
        role = manager.update_role(role_id, delta)
        link = {
            '_href': reverse('role_resource', kwargs={'role_id': role['id']})
        }
        role.update(link)
        return generate_json_response_with_pulp_encoder(role)
Example #32
0
    def post(self, request):
        """
        Create a consumer and return a serialized object containing just created consumer.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :raises MissingValue: if ID is not provided

        :return: Response containing the consumer
        :rtype: django.http.HttpResponse
        """

        params = request.body_as_json
        consumer_id = params.get('id')
        if consumer_id is None:
            raise MissingValue(['id'])
        display_name = params.get('display_name')
        description = params.get('description')
        notes = params.get('notes')
        rsa_pub = params.get('rsa_pub')

        manager = factory.consumer_manager()

        consumer, certificate = manager.register(
            consumer_id,
            display_name=display_name,
            description=description,
            notes=notes,
            rsa_pub=rsa_pub)

        link = add_link(consumer)

        document = {
            'consumer': consumer,
            'certificate': certificate
        }
        response = generate_json_response_with_pulp_encoder(document)
        redirect_response = generate_redirect_response(response, link['_href'])
        return redirect_response
Example #33
0
    def delete(self, request, consumer_id, repo_id, distributor_id):
        """
        Delete a bind association between the specified
        consumer and repo-distributor.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: A consumer ID.
        :type consumer_id: str
        :param repo_id: A repo ID.
        :type repo_id: str
        :param distributor_id: A distributor ID.
        :type distributor_id: str

        :raises OperationPostponed: will dispatch a task if 'notify_agent' is set to True
        :raises InvalidValue: if some parameters are invalid

        :return: Response representing the deleted binding(in case 'notify agent' is set to False)
        :rtype: django.http.HttpResponse
        """

        body = request.body_as_json
        forced = body.get('force', False)
        if not isinstance(forced, bool):
            raise InvalidValue(['force'])
        options = body.get('options', {})
        if not isinstance(options, dict):
            raise InvalidValue(['options'])
        if forced:
            call_report = consumer_controller.force_unbind(
                consumer_id, repo_id, distributor_id, options)
        else:
            call_report = consumer_controller.unbind(consumer_id, repo_id,
                                                     distributor_id, options)

        if call_report.spawned_tasks:
            raise OperationPostponed(call_report)
        else:
            return generate_json_response_with_pulp_encoder(
                call_report.serialize())
Example #34
0
    def post(self, request, consumer_id):
        """
        Create a bind association between the specified
        consumer by id included in the URL path and a repo-distributor
        specified in the POST body: {repo_id:<str>, distributor_id:<str>}.
        Designed to be idempotent so only MissingResource is expected to
        be raised by manager.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: consumer to bind.
        :type  consumer_id: str

        :raises OperationPostponed: will dispatch a task if 'notify_agent' is set to True
        :raises InvalidValue: if binding_config is invalid

        :return: Response representing the binding(in case 'notify agent' is set to False)
        :rtype: django.http.HttpResponse
        """

        # get other options and validate them
        body = request.body_as_json
        repo_id = body.get('repo_id')
        distributor_id = body.get('distributor_id')
        binding_config = body.get('binding_config', {})
        options = body.get('options', {})
        notify_agent = body.get('notify_agent', True)

        if not isinstance(binding_config, dict):
            raise InvalidValue(['binding_config'])

        call_report = consumer_controller.bind(consumer_id, repo_id,
                                               distributor_id, notify_agent,
                                               binding_config, options)

        if call_report.spawned_tasks:
            raise OperationPostponed(call_report)
        else:
            return generate_json_response_with_pulp_encoder(
                call_report.serialize())
Example #35
0
    def get(self, request, consumer_id):
        """
        Return a serialized object representing the requested consumer.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: id for the requested consumer
        :type consumer_id: str

        :return: Response containing data for the requested consumer
        :rtype: django.http.HttpResponse
        """

        query_params = request.GET
        details = query_params.get('details', 'false').lower() == 'true'
        bindings = query_params.get('bindings', 'false').lower() == 'true'

        manager = factory.consumer_manager()
        consumer = manager.get_consumer(consumer_id)
        consumer = expand_consumers(details, bindings, [consumer])[0]
        add_link(consumer)
        return generate_json_response_with_pulp_encoder(consumer)
Example #36
0
    def get(self, request, repo_group_id):
        """
        Get a list of all distributors associated with the given repo_group.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_group_id: return distributors associated with this repo group
        :type  repo_group_id: str

        :return: response containing a serialized list of dicts, one for each associated distributor
        :rtype: django.http.HttpResponse
        """
        distributor_manager = managers_factory.repo_group_distributor_manager()
        distributor_list = distributor_manager.find_distributors(repo_group_id)
        for distributor in distributor_list:
            distributor['_href'] = reverse('repo_group_distributor_resource',
                                           kwargs={
                                               'repo_group_id': repo_group_id,
                                               'distributor_id':
                                               distributor['id']
                                           })
        return generate_json_response_with_pulp_encoder(distributor_list)
Example #37
0
    def get(self, request, consumer_id, repo_id, distributor_id):
        """
        Fetch a specific bind object which represents a specific association
        between a consumer and repo-distributor.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: A consumer ID.
        :type consumer_id: str
        :param repo_id: A repo ID.
        :type repo_id: str
        :param distributor_id: A distributor ID.
        :type distributor_id: str

        :return: Response representing the binding
        :rtype: django.http.HttpResponse
        """

        manager = factory.consumer_bind_manager()
        bind = manager.get_bind(consumer_id, repo_id, distributor_id)
        serialized_bind = serial_binding.serialize(bind)
        return generate_json_response_with_pulp_encoder(serialized_bind)
Example #38
0
    def post(self, request):
        """
        Create a new role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing the role
        :rtype: django.http.HttpResponse
        """
        role_data = request.body_as_json
        role_id = role_data.get('role_id', None)
        display_name = role_data.get('display_name', None)
        description = role_data.get('description', None)
        manager = factory.role_manager()
        role = manager.create_role(role_id, display_name, description)
        link = {'_href': reverse('role_resource',
                kwargs={'role_id': role['id']})}
        role.update(link)
        response = generate_json_response_with_pulp_encoder(role)
        redirect_response = generate_redirect_response(response, link['_href'])
        return redirect_response
Example #39
0
    def get(self, request):
        """
        Get all content sources.

        :param request:   WSGI request object, body contains bits to upload
        :type  request:   django.core.handlers.wsgi.WSGIRequest

        :return: list of sources
        :rtype:  django.http.HttpResponse
        """
        container = ContentContainer()
        sources = []
        for source in container.sources.values():
            d = source.dict()
            link = {
                '_href':
                reverse('content_sources_resource',
                        kwargs={'source_id': source.id})
            }
            d.update(link)
            sources.append(d)
        return generate_json_response_with_pulp_encoder(sources)
Example #40
0
    def get(self, request):
        """
        List all roles.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing a list of roles
        :rtype: django.http.HttpResponse
        """
        role_query_manager = factory.role_query_manager()
        permissions_manager = factory.permission_manager()
        roles = role_query_manager.find_all()
        for role in roles:
            users = [
                u.login for u in user_controller.find_users_belonging_to_role(
                    role['id'])
            ]
            role['users'] = users

            resource_permission = {}
            # isolate schema change
            if role['permissions']:
                for item in role['permissions']:
                    resource = item['resource']
                    operations = item.get('permission', [])
                    resource_permission[resource] = [
                        permissions_manager.operation_value_to_name(o)
                        for o in operations
                    ]

            role['permissions'] = resource_permission

            link = {
                '_href': reverse('role_resource',
                                 kwargs={'role_id': role['id']})
            }
            role.update(link)
        return generate_json_response_with_pulp_encoder(roles)
Example #41
0
    def post(self, request):
        """
        Create a new user.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing the user
        :rtype: django.http.HttpResponse

        :raises: MissingValue if login field is missing
        :raises: InvalidValue if some parameters are invalid
        """
        user_data = request.body_as_json
        login = user_data.pop('login', None)
        if login is None:
            raise pulp_exceptions.MissingValue(['login'])
        password = user_data.pop('password', None)

        # name defaults to login
        name = user_data.pop('name', login)

        # Raise if extra data is passed
        if user_data:
            raise pulp_exceptions.InvalidValue(user_data.keys())

        new_user = user_controller.create_user(login, password=password, name=name)
        serialized_user = model.User.serializer(new_user).data

        # For backwards compatability. See https://pulp.plan.io/issues/1125
        serialized_user['id'] = str(serialized_user['_id'])

        # Grant permissions
        permission_manager = factory.permission_manager()
        permission_manager.grant_automatic_permissions_for_resource(serialized_user['_href'])

        response = generate_json_response_with_pulp_encoder(serialized_user)
        return generate_redirect_response(response, serialized_user['_href'])
Example #42
0
    def post(self, request):
        """
        Create a new user.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing the user
        :rtype: django.http.HttpResponse
        :raises: MissingValue if login field is missing
        :raises: InvalidValue if some parameters are invalid
        """
        # Pull all the user data
        user_data = request.body_as_json
        login = user_data.pop('login', None)
        if login is None:
            raise pulp_exceptions.MissingValue(['login'])
        password = user_data.pop('password', None)
        name = user_data.pop('name', None)
        if user_data:
            raise pulp_exceptions.InvalidValue(user_data.keys())
        # Creation
        manager = factory.user_manager()
        args = [login]
        kwargs = {'password': password, 'name': name}

        user = manager.create_user(*args, **kwargs)

        # Add the link to the user
        link = _add_link(user)

        # Grant permissions
        permission_manager = factory.permission_manager()
        permission_manager.grant_automatic_permissions_for_resource(
            link['_href'])

        response = generate_json_response_with_pulp_encoder(user)
        return generate_redirect_response(response, link['_href'])
Example #43
0
    def get(self, request, consumer_id, repo_id=None):
        """
        Fetch all bind objects referencing the specified consumer_id. Optionally,
        specify a repo_id to fetch all bind objects for the consumer_id to the repo_id.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: The specified consumer.
        :type  consumer_id: str
        :param repo_id: The repository to retrieve bindings for (optional)
        :type  repo_id: str

        :raises MissingResource: if some resource is missing

        :return: Response representing the bindings
        :rtype: django.http.HttpResponse
        """

        # Check to make sure the resources exist
        missing_resources = {}
        if repo_id is not None:
            repo = model.Repository.objects(repo_id).first()
            if repo is None:
                missing_resources['repo_id'] = repo_id

        # If get_consumer raises MissingResource we might miss reporting a bad repo_id
        try:
            factory.consumer_manager().get_consumer(consumer_id)
        except MissingResource:
            missing_resources['consumer_id'] = consumer_id

        if missing_resources:
            raise MissingResource(**missing_resources)

        manager = factory.consumer_bind_manager()
        bindings = manager.find_by_consumer(consumer_id, repo_id)
        bindings = [serial_binding.serialize(b) for b in bindings]
        return generate_json_response_with_pulp_encoder(bindings)
Example #44
0
    def get(self, request, consumer_id):
        """
        Retrieve histroy for the specified consumer

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: A consumer ID.
        :type consumer_id: str

        :return: Response representing the binding
        :rtype: django.http.HttpResponse
        """

        # Check that the consumer exists and raise a MissingResource exception, in case it doesn't.
        factory.consumer_manager().get_consumer(consumer_id)

        query_param = request.GET
        filters = _ensure_input_encoding(query_param)
        event_type = filters.get('event_type', None)
        limit = filters.get('limit', None)
        sort = filters.get('sort', 'descending')
        start_date = filters.get('start_date', None)
        end_date = filters.get('end_date', None)

        if limit:
            try:
                limit = int(limit)
            except ValueError:
                raise InvalidValue('limit')

        results = factory.consumer_history_manager().query(
            consumer_id=consumer_id,
            event_type=event_type,
            limit=limit,
            sort=sort,
            start_date=start_date,
            end_date=end_date)
        return generate_json_response_with_pulp_encoder(results)
Example #45
0
    def put(self, request, event_listener_id):
        """
        Update a specific event listener.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param event_listener_id: id for the requested event listener
        :type event_listener_id: str

        :return: Response containing the event listener
        :rtype: django.http.HttpResponse
        """
        params = request.body_as_json

        notifier_config = params.get('notifier_config', None)
        event_types = params.get('event_types', None)

        manager = factory.event_listener_manager()
        event = manager.update(event_listener_id,
                               notifier_config=notifier_config,
                               event_types=event_types)
        add_link(event)
        return generate_json_response_with_pulp_encoder(event)
Example #46
0
    def get(self, request):
        """
        Get all type definitions

        :param request: WSGI Request obect
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :return       : Response containing serialized list data for all available content types
        :rtype        : django.http.HttpResponse
        """
        manager = factory.plugin_manager()
        type_defs = manager.types()

        for type_definition in type_defs:
            href = {
                '_href':
                '/'.join([
                    request.get_full_path().rstrip('/'), type_definition['id'],
                    ''
                ])
            }
            type_definition.update(href)

        return generate_json_response_with_pulp_encoder(type_defs)
Example #47
0
    def get(self, request, task_id):
        """
        Return a response containing a single task.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param task_id: The ID of the task you wish to cancel
        :type  task_id: basestring

        :return: Response containing a serialized dict of the requested task
        :rtype : django.http.HttpResponse
        :raises MissingResource: if task is not found
        """
        try:
            task = dispatch.TaskStatus.objects.get(task_id=task_id)
        except DoesNotExist:
            raise MissingResource(task_id)

        task_dict = task_serializer(task)
        if 'worker_name' in task_dict:
            queue_name = Worker(task_dict['worker_name'], datetime.now()).queue_name
            task_dict.update({'queue': queue_name})
        return generate_json_response_with_pulp_encoder(task_dict)
Example #48
0
    def get(self, request, repo_group_id, distributor_id):
        """
        Get information about a single repo group distributor association.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param repo_group_id: repo group the distributor is associated with
        :type  repo_group_id: str
        :param distributor_id: distributor to get
        :type  distributor_id: str

        :return: response containing a serialized dict of the requested distributor
        :rtype: django.http.HttpResponse
        """
        distributor_manager = managers_factory.repo_group_distributor_manager()
        dist = distributor_manager.get_distributor(repo_group_id,
                                                   distributor_id)
        dist['_href'] = reverse('repo_group_distributor_resource',
                                kwargs={
                                    'repo_group_id': repo_group_id,
                                    'distributor_id': distributor_id
                                })
        return generate_json_response_with_pulp_encoder(dist)
Example #49
0
    def get(self, request, role_id):
        """
        Retrieve a specific role.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param role_id: id for the requested role
        :type role_id: str

        :return: Response containing the role
        :rtype: django.http.HttpResponse
        :raises: MissingResource if role ID does not exist
        """
        role = factory.role_query_manager().find_by_id(role_id)
        if role is None:
            raise pulp_exceptions.MissingResource(role_id)
        role['users'] = [
            u.login
            for u in user_controller.find_users_belonging_to_role(role['id'])
        ]
        permissions_manager = factory.permission_manager()
        # isolate schema change
        resource_permission = {}
        for item in role['permissions']:
            resource = item['resource']
            operations = item.get('permission', [])
            resource_permission[resource] = [
                permissions_manager.operation_value_to_name(o)
                for o in operations
            ]
        role['permissions'] = resource_permission

        link = {
            '_href': reverse('role_resource', kwargs={'role_id': role['id']})
        }
        role.update(link)
        return generate_json_response_with_pulp_encoder(role)
Example #50
0
    def get(self, request, consumer_group_id):
        """
        Return a serialized object representing the requested group.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_group_id: id for the requested group
        :type consumer_group_id: str
        :return: Response containing data for the requested group
        :rtype: django.http.HttpResponse
        :raises: MissingResource if group ID does not exist
        """
        collection = ConsumerGroup.get_collection()
        group = collection.find_one({'id': consumer_group_id})
        if group is None:
            raise pulp_exceptions.MissingResource(
                consumer_group=consumer_group_id)
        link = {
            "_href":
            reverse('consumer_group_resource',
                    kwargs={'consumer_group_id': group['id']})
        }
        group.update(link)
        return generate_json_response_with_pulp_encoder(group)
Example #51
0
    def post(self, request):
        """
        Create a new event listener.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest

        :return: Response containing the event listener
        :rtype: django.http.HttpResponse
        """
        params = request.body_as_json

        notifier_type_id = params.get('notifier_type_id', None)
        notifier_config = params.get('notifier_config', None)
        event_types = params.get('event_types', None)

        manager = factory.event_listener_manager()
        event = manager.create(notifier_type_id, notifier_config, event_types)

        link = add_link(event)

        response = generate_json_response_with_pulp_encoder(event)
        redirect_response = generate_redirect_response(response, link['_href'])
        return redirect_response
Example #52
0
    def get(self, request, group_id):
        """
        Return a response containing a summary of task states for task group.

        :param request: WSGI request object
        :type  request: django.core.handlers.wsgi.WSGIRequest
        :param group_id: The ID of the task group you wish to summarize
        :type  group_id: basestring

        :return: Response containing a serialized dict of the task group summary
        :rtype : django.http.HttpResponse
        :raises MissingResource: if group id is not found
        """
        tasks = TaskStatus.objects(group_id=group_id)
        task_group_total = tasks.count()

        if task_group_total == 0:
            raise MissingResource(group_id)

        summary = {'total': task_group_total}
        for state in CALL_STATES:
            summary[state] = tasks.filter(state=state).count()

        return generate_json_response_with_pulp_encoder(summary)
Example #53
0
    def put(self, request, consumer_id, content_type):
        """
        Update the association of a profile with a consumer by content type ID.

        :param request: WSGI request object
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param consumer_id: A consumer ID.
        :type consumer_id: str
        :param content_type: A content unit type ID.
        :type content_type: str

        :return: Response representing the updated profile
        :rtype: django.http.HttpResponse
        """

        body = request.body_as_json
        profile = body.get('profile')

        manager = factory.consumer_profile_manager()
        consumer = manager.update(consumer_id, content_type, profile)

        add_link_profile(consumer)

        return generate_json_response_with_pulp_encoder(consumer)