Esempio n. 1
0
class CopySerializer(serializers.Serializer):
    """
    Serializer for copying units from a source repository to a destination repository.
    """

    source_repository = serializers.HyperlinkedRelatedField(
        help_text=_('A URI of the repository to copy content from.'),
        queryset=Repository.objects.all(),
        view_name='repositories-detail',
        label=_('Repository'),
        write_only=True,
        required=False,
    )
    source_repository_version = NestedRelatedField(
        help_text=_('A URI of the repository version to copy content from.'),
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
        queryset=models.RepositoryVersion.objects.all(),
        write_only=True,
        required=False,
    )
    destination_repository = serializers.HyperlinkedRelatedField(
        required=True,
        help_text=_('A URI of the repository to copy content to.'),
        queryset=Repository.objects.all(),
        view_name='repositories-detail',
        label=_('Repository'),
        error_messages={
            'required': _('Destination repository URI must be specified.')
        }
    )

    def validate(self, data):
        """Ensure that source_repository or source_rpository_version is pass, but not both."""
        if hasattr(self, 'initial_data'):
            validate_unknown_fields(self.initial_data, self.fields)

        repository = data.pop('source_repository', None)
        repository_version = data.get('source_repository_version')
        if not repository and not repository_version:
            raise serializers.ValidationError(
                _("Either the 'repository' or 'repository_version' need to be specified"))
        elif not repository and repository_version:
            return data
        elif repository and not repository_version:
            version = models.RepositoryVersion.latest(repository)
            if version:
                new_data = {'source_repository_version': version}
                new_data.update(data)
                return new_data
            else:
                raise serializers.ValidationError(
                    detail=_('Source repository has no version available to copy content from'))
        raise serializers.ValidationError(
            _("Either the 'repository' or 'repository_version' need to be specified "
              "but not both.")
        )
Esempio n. 2
0
class CopySerializer(serializers.Serializer):
    """
    Serializer for copying units from a source repository to a destination repository.
    """

    source_repository = serializers.HyperlinkedRelatedField(
        help_text=_("A URI of the repository to copy content from."),
        queryset=models.ContainerRepository.objects.all(),
        view_name="repositories-container/container-detail",
        label=_("Repository"),
        required=False,
    )
    source_repository_version = NestedRelatedField(
        help_text=_("A URI of the repository version to copy content from."),
        view_name="versions-detail",
        lookup_field="number",
        parent_lookup_kwargs={"repository_pk": "repository__pk"},
        queryset=RepositoryVersion.objects.all(),
        required=False,
    )

    def validate(self, data):
        """Ensure that source_repository or source_rpository_version is pass, but not both."""
        if hasattr(self, "initial_data"):
            validate_unknown_fields(self.initial_data, self.fields)

        repository = data.pop("source_repository", None)
        repository_version = data.get("source_repository_version")
        if not repository and not repository_version:
            raise serializers.ValidationError(
                _("Either the 'repository' or 'repository_version' need to be specified")
            )
        elif not repository and repository_version:
            return data
        elif repository and not repository_version:
            version = repository.latest_version()
            if version:
                new_data = {"source_repository_version": version}
                new_data.update(data)
                return new_data
            else:
                raise serializers.ValidationError(
                    detail=_("Source repository has no version available to copy content from")
                )
        raise serializers.ValidationError(
            _(
                "Either the 'repository' or 'repository_version' need to be specified "
                "but not both."
            )
        )
class Pulp2RepositoriesSerializer(ModelSerializer):
    """
    A serializer for the Pulp2Repositories
    """
    pulp_href = IdentityField(view_name='pulp2repositories-detail')
    pulp2_object_id = serializers.CharField(max_length=255)
    pulp2_repo_id = serializers.CharField()
    is_migrated = serializers.BooleanField(default=False)

    pulp3_repository_version = NestedRelatedField(
        view_name='versions-detail',
        lookup_field='number',
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
        queryset=RepositoryVersion.objects.all(),
        required=False,
    )

    pulp3_remote_href = serializers.SerializerMethodField(read_only=True)
    pulp3_publisher_href = serializers.SerializerMethodField(read_only=True)
    pulp3_publication_href = serializers.SerializerMethodField(read_only=True)
    pulp3_distribution_hrefs = serializers.SerializerMethodField(
        read_only=True)

    def get_pulp3_remote_href(self, obj):
        """
        Get pulp3_remote_href from Pulp2Importer
        """
        importer = Pulp2Importer.objects.filter(pulp2_repository=obj).first()
        return get_pulp_href(importer.pulp3_remote)

    def get_pulp3_publisher_href(self, obj):
        """
        Get pulp3_publisher_href from Pulp2Distributor
        """
        distributors = getattr(self, "_distributors", None)
        if not distributors:
            self._distributors = Pulp2Distributor.objects.filter(
                pulp2_repository=obj).all()
            distributors = self._distributors

        return [
            get_pulp_href(d.pulp3_publisher) for d in distributors
            if d.pulp3_publisher
        ]

    def get_pulp3_publication_href(self, obj):
        """
        Get pulp3_publication_href from Pulp2Distributor
        """
        distributors = getattr(self, "_distributors", None)
        if not distributors:
            self._distributors = Pulp2Distributor.objects.filter(
                pulp2_repository=obj).all()
            distributors = self._distributors

        return [
            get_pulp_href(d.pulp3_publication) for d in distributors
            if d.pulp3_publication
        ]

    def get_pulp3_distribution_hrefs(self, obj):
        """
        Get pulp3_distribution_hrefs from Pulp2Distributor
        """
        distributors = getattr(self, "_distributors", None)
        if not distributors:
            self._distributors = Pulp2Distributor.objects.filter(
                pulp2_repository=obj).all()
            distributors = self._distributors

        return [
            get_pulp_href(d.pulp3_distribution) for d in distributors
            if d.pulp3_distribution
        ]

    class Meta:
        fields = ModelSerializer.Meta.fields + (
            "pulp2_object_id",
            "pulp2_repo_id",
            "is_migrated",
            "pulp3_repository_version",
            "pulp3_remote_href",
            "pulp3_publisher_href",
            "pulp3_publication_href",
            "pulp3_distribution_hrefs",
        )
        model = Pulp2Repository
Esempio n. 4
0
class CopySerializer(serializers.Serializer):
    """
    A serializer for Content Copy API.
    """

    source_repo = serializers.HyperlinkedRelatedField(
        help_text=_('A URI of the repository.'),
        required=False,
        queryset=RpmRepository.objects.all(),
        view_name='repositories-rpm/rpm-detail',
    )
    source_repo_version = NestedRelatedField(
        help_text=_('A URI of the repository version'),
        required=False,
        queryset=RepositoryVersion.objects.all(),
        parent_lookup_kwargs={'repository_pk': 'repository__pk'},
        lookup_field='number',
        view_name='versions-detail',
    )
    dest_repo = serializers.HyperlinkedRelatedField(
        help_text=_('A URI of the repository.'),
        required=True,
        queryset=RpmRepository.objects.all(),
        view_name='repositories-rpm/rpm-detail',
    )
    types = serializers.ListField(
        help_text=_('A list of types to copy ["package", "advisory"]'),
        write_only=True,
        default=['package', 'advisory'])

    def validate(self, data):
        """
        Validate that the Serializer contains valid data.

        Set the RpmRepository based on the RepositoryVersion if only the latter is provided.
        Set the RepositoryVersion based on the RpmRepository if only the latter is provided.
        Convert the human-friendly names of the content types into what Pulp needs to query on.

        """
        super().validate(data)
        if hasattr(self, 'initial_data'):
            validate_unknown_fields(self.initial_data, self.fields)

        new_data = {}
        new_data.update(data)

        source_repo = data.get('source_repo')
        source_repo_version = data.get('source_repo_version')

        if not source_repo and not source_repo_version:
            raise serializers.ValidationError(
                _("Either the 'source_repo' or 'source_repo_version' need to be specified"
                  ))

        if source_repo and source_repo_version:
            raise serializers.ValidationError(
                _("Either the 'source_repo' or 'source_repo_version' need to be specified "
                  "but not both."))

        if not source_repo and source_repo_version:
            repo = {'source_repo': source_repo_version.repository}
            new_data.update(repo)

        if source_repo and not source_repo_version:
            version = RepositoryVersion.latest(source_repo)
            if version:
                repo_version = {'source_repo_version': version}
                new_data.update(repo_version)
            else:
                raise serializers.ValidationError(
                    detail=_('Repository has no version available to copy'))

        types = data.get('types')
        final_types = []

        if types:
            for t in types:
                substitution = RPM_PLUGIN_TYPE_CHOICE_MAP.get(t)
                if not substitution:
                    raise serializers.ValidationError(
                        _("'{type}' is an invalid type, please use one of {choices}"
                          .format(type=t,
                                  choices=list(
                                      RPM_PLUGIN_TYPE_CHOICE_MAP.keys()))))
                final_types.append(substitution)
            new_data.update({'types': final_types})

        return new_data