Example #1
0
class InstanceSerializer(serializers.HyperlinkedModelSerializer):
    identity = IdentitySummarySerializer(source='created_by_identity')
    user = UserSummarySerializer(source='created_by')
    provider = ProviderSummarySerializer(source='created_by_identity.provider')
    status = serializers.CharField(source='esh_status', read_only=True)
    projects = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    size = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()
    uuid = serializers.CharField(source='provider_alias')

    def get_size(self, obj):
        size_alias = obj.esh_size()
        provider_id = obj.created_by_identity.provider_id
        size = Size.objects.get(alias=size_alias, provider=provider_id)
        serializer = SizeSummarySerializer(size, context=self.context)
        return serializer.data

    def get_image(self, obj):
        image_uuid = obj.application_uuid()
        image = Image.objects.get(uuid=image_uuid)
        serializer = ImageSummarySerializer(image, context=self.context)
        return serializer.data

    class Meta:
        model = Instance
        view_name = 'api_v2:instance-detail'
        fields = ('id', 'uuid', 'url', 'name', 'status', 'size', 'ip_address',
                  'shell', 'vnc', 'identity', 'user', 'provider', 'image',
                  'projects', 'start_date', 'end_date')
Example #2
0
class CredentialSerializer(serializers.HyperlinkedModelSerializer):
    url = UUIDHyperlinkedIdentityField(view_name='api:v2:credential-detail', )
    identity = IdentitySummarySerializer()

    class Meta:
        model = Credential
        fields = ('id', 'uuid', 'url', 'identity', 'key', 'value')
Example #3
0
class InstanceSerializer(serializers.HyperlinkedModelSerializer):
    identity = IdentitySummarySerializer(source='created_by_identity')
    user = UserSummarySerializer(source='created_by')
    provider = ProviderSummarySerializer(source='created_by_identity.provider')
    status = serializers.CharField(source='esh_status', read_only=True)
    projects = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    scripts = ModelRelatedField(many=True,
                                required=False,
                                queryset=BootScript.objects.all(),
                                serializer_class=BootScriptSummarySerializer,
                                style={'base_template': 'input.html'})
    size = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()
    version = serializers.SerializerMethodField()
    uuid = serializers.CharField(source='provider_alias')
    url = UUIDHyperlinkedIdentityField(view_name='api:v2:instance-detail',
                                       uuid_field='provider_alias')

    def get_size(self, obj):
        size = obj.get_size()
        serializer = SizeSummarySerializer(size, context=self.context)
        return serializer.data

    def get_image(self, obj):
        image_uuid = obj.application_uuid()
        image = Image.objects.get(uuid=image_uuid)
        serializer = ImageSummarySerializer(image, context=self.context)
        return serializer.data

    def get_version(self, obj):
        version = obj.source.providermachine.application_version
        serializer = ImageVersionSummarySerializer(version,
                                                   context=self.context)
        return serializer.data

    class Meta:
        model = Instance
        fields = (
            'id',
            'uuid',
            'url',
            'name',
            'status',
            'size',
            'ip_address',
            'shell',
            'vnc',
            'identity',
            'user',
            'provider',
            'image',
            'version',  # NOTE:Should replace image?
            'scripts',
            'projects',
            'start_date',
            'end_date',
        )
Example #4
0
class IdentityMembershipSerializer(serializers.HyperlinkedModelSerializer):
    quota = QuotaSummarySerializer()
    allocation = AllocationSummarySerializer()
    identity = IdentitySummarySerializer()
    user = UserSummarySerializer(source='identity.created_by')
    provider = ProviderSummarySerializer(source='identity.provider')
    url = serializers.HyperlinkedIdentityField(
        view_name='api:v2:identitymembership-detail', )

    class Meta:
        model = IdentityMembership
        fields = ('id', 'url', 'quota', 'allocation', 'end_date', 'provider',
                  'identity', 'user')
Example #5
0
class VolumeSerializer(serializers.HyperlinkedModelSerializer):
    provider = ProviderSummarySerializer(source='instance_source.provider')
    identity = IdentitySummarySerializer(
        source='instance_source.created_by_identity')
    user = UserSummarySerializer(source='instance_source.created_by')
    start_date = serializers.DateTimeField(source='instance_source.start_date')
    end_date = serializers.DateTimeField(source='instance_source.end_date')
    projects = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    uuid = serializers.CharField(source='instance_source.identifier')

    class Meta:
        model = Volume
        view_name = 'api_v2:volume-detail'
        fields = ('id', 'uuid', 'url', 'name', 'size', 'user', 'provider',
                  'identity', 'projects', 'start_date', 'end_date')
Example #6
0
class IdentityMembershipSerializer(serializers.HyperlinkedModelSerializer):
    quota = QuotaSummarySerializer()
    identity_key = serializers.SerializerMethodField()
    identity = IdentitySummarySerializer()
    user = UserSummarySerializer(source='identity.created_by')
    provider = ProviderSummarySerializer(source='identity.provider')
    url = serializers.HyperlinkedIdentityField(
        view_name='api:v2:identitymembership-detail', )

    def get_identity_key(self, identity_membership):
        return identity_membership.identity.get_key()

    class Meta:
        model = IdentityMembership
        fields = ('id', 'url', 'quota', 'end_date', 'provider', 'identity',
                  'identity_key', 'user')
Example #7
0
class CredentialSerializer(serializers.HyperlinkedModelSerializer):
    url = UUIDHyperlinkedIdentityField(view_name='api:v2:credential-detail', )
    identity = IdentitySummarySerializer(read_only=True)

    def validate_text(self, key, value):
        """
        """
        return value

    def validate_url(self, key, url_value):
        """
        Ensure keys expecting a URL receive a URL
        """
        parse_result = urlparse(url_value)
        if not parse_result.scheme:
            raise serializers.ValidationError(
                "Key: %s expects Valid URL - Value %s throws Error: Missing scheme (http(s)://)"
                % (key, url_value)
            )
        return url_value

    def validate(self, data):
        # Object-level validation of the key to ensure value 'makes sense' and that only credentials understood by Atmosphere are added.
        if data['key'] in ['admin_url', 'auth_url']:
            self.validate_url(data['key'], data['value'])
        elif data['key'] in [
            'key', 'secret', 'ex_tenant_name', 'ex_project_name', 'router_name'
        ]:
            self.validate_text(data['key'], data['value'])
        else:
            raise serializers.ValidationError(
                "Key %s is not supported as a credential. "
                "Contact a developer for more information." % data['key']
            )
        return data

    class Meta:
        model = Credential
        fields = ('id', 'uuid', 'url', 'identity', 'key', 'value')
Example #8
0
class ImageVersionSerializer(serializers.HyperlinkedModelSerializer):
    """
    Serializer for ApplicationVersion (aka 'image_version')
    """
    # NOTE: Implicitly included via 'fields'
    # id, application
    parent = ImageVersionSummarySerializer()
    # name, change_log, allow_imaging
    licenses = ModelRelatedField(
        many=True,
        queryset=License.objects.all(),
        serializer_class=LicenseSummarySerializer,
        style={'base_template': 'input.html'}
    )
    scripts = ModelRelatedField(
        source='boot_scripts',
        many=True,
        queryset=BootScript.objects.all(),
        serializer_class=BootScriptSummarySerializer,
        style={'base_template': 'input.html'}
    )
    membership = serializers.SlugRelatedField(
        slug_field='name', read_only=True, many=True
    )
    user = UserSummarySerializer(source='created_by')
    identity = IdentitySummarySerializer(source='created_by_identity')
    machines = serializers.SerializerMethodField('get_machines_for_user')
    image = ModelRelatedField(
        source='application',
        queryset=Image.objects.all(),
        serializer_class=ImageSummarySerializer,
        style={'base_template': 'input.html'}
    )
    start_date = serializers.DateTimeField()
    min_mem = serializers.IntegerField(source='threshold.memory_min')
    min_cpu = serializers.IntegerField(source='threshold.cpu_min')
    end_date = serializers.DateTimeField(allow_null=True)
    url = UUIDHyperlinkedIdentityField(
        view_name='api:v2:imageversion-detail', uuid_field='id'
    )

    def get_machines_for_user(self, obj):
        """
        Only show version as available on providers the user has access to
        """
        user = self.context['request'].user

        filtered = obj.machines.filter(
            Q(instance_source__provider__active=True)
        )
        if isinstance(user, AnonymousUser):
            filtered = filtered.filter(
                Q(instance_source__provider__public=True)
            )
        elif not user.is_staff:
            filtered = filtered.filter(
                Q(instance_source__provider_id__in=user.provider_ids())
            )
        serializer = ProviderMachineSummarySerializer(
            filtered, context=self.context, many=True
        )
        return serializer.data

    class Meta:
        model = ImageVersion
        fields = (
            'id', 'url', 'parent', 'name', 'change_log', 'image', 'machines',
            'allow_imaging', 'doc_object_id', 'licenses', 'membership',
            'min_mem', 'min_cpu', 'scripts', 'user', 'identity', 'start_date',
            'end_date'
        )

    def update(self, instance, validated_data):
        if 'min_cpu' in self.initial_data or 'min_mem' in self.initial_data:
            self.update_threshold(instance, validated_data)
        return super(ImageVersionSerializer,
                     self).update(instance, validated_data)

    def validate_min_cpu(self, value):
        if value < 0 or value > 16:
            raise serializers.ValidationError(
                "Value of CPU must be between 1 & 16"
            )
        return value

    def validate_min_mem(self, value):
        if value < 0 or value > 32 * 1024:
            raise serializers.ValidationError(
                "Value of mem must be between 1 & 32 GB"
            )
        return value

    def update_threshold(self, instance, validated_data):
        current_threshold = instance.get_threshold()

        try:
            current_mem_min = current_threshold.memory_min
        except:
            current_mem_min = 0

        try:
            current_cpu_min = current_threshold.cpu_min
        except:
            current_cpu_min = 0

        try:
            new_mem_min = validated_data.get('threshold')['memory_min']
        except:
            new_mem_min = current_mem_min

        try:
            new_cpu_min = validated_data.get('threshold')['cpu_min']
        except:
            new_cpu_min = current_cpu_min

        if not current_threshold:
            new_threshold = ApplicationThreshold.objects.create(
                application_version=instance,
                memory_min=new_mem_min,
                cpu_min=new_cpu_min
            )
        else:
            new_threshold = ApplicationThreshold.objects.get(
                application_version=instance
            )
            new_threshold.memory_min = new_mem_min
            new_threshold.cpu_min = new_cpu_min
            new_threshold.save()

        validated_data['threshold'] = new_threshold
Example #9
0
class InstanceSerializer(serializers.HyperlinkedModelSerializer):
    identity = IdentitySummarySerializer(source='created_by_identity')
    user = UserSummarySerializer(source='created_by')
    provider = ProviderSummarySerializer(source='created_by_identity.provider')
    status = serializers.CharField(source='api_status', read_only=True)
    activity = serializers.CharField(source='api_activity', read_only=True)
    projects = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    scripts = ModelRelatedField(many=True,
                                required=False,
                                queryset=BootScript.objects.all(),
                                serializer_class=BootScriptSummarySerializer,
                                style={'base_template': 'input.html'})
    size = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()
    ip_address = serializers.SerializerMethodField()
    usage = serializers.SerializerMethodField()
    version = serializers.SerializerMethodField()
    allocation_source = serializers.SerializerMethodField()
    uuid = serializers.CharField(source='provider_alias')
    url = UUIDHyperlinkedIdentityField(view_name='api:v2:instance-detail',
                                       lookup_field='uuid',
                                       uuid_field='provider_alias')

    def get_allocation_source(self, instance):
        snapshot = InstanceAllocationSourceSnapshot.objects.filter(
            instance=instance).first()
        if not snapshot:
            return None
        serializer = AllocationSourceSerializer(snapshot.allocation_source,
                                                context=self.context)
        return serializer.data

    def get_usage(self, instance):
        return instance.get_total_hours()

    def get_size(self, obj):
        size = obj.get_size()
        serializer = SizeSummarySerializer(size, context=self.context)
        return serializer.data

    def get_image(self, obj):
        if obj.source.is_volume():
            return {}
        image_uuid = obj.application_uuid()
        image = Image.objects.get(uuid=image_uuid)
        serializer = ImageSummarySerializer(image, context=self.context)
        return serializer.data

    def get_ip_address(self, obj):
        status = obj.esh_status()
        if status in ["suspended", "shutoff", "shelved"]:
            return "0.0.0.0"
        return obj.ip_address

    def get_version(self, obj):
        if obj.source.is_volume():
            return {}
        version = obj.source.providermachine.application_version
        serializer = ImageVersionSummarySerializer(version,
                                                   context=self.context)
        return serializer.data

    class Meta:
        model = Instance
        fields = (
            'id',
            'uuid',
            'url',
            'name',
            'status',
            'activity',
            'size',
            'ip_address',
            'shell',
            'vnc',
            'web_desktop',
            'identity',
            'user',
            'provider',
            'image',
            'version',  # NOTE:Should replace image?
            'usage',
            'scripts',
            'projects',
            'start_date',
            'end_date',
            'allocation_source',
        )
Example #10
0
 def to_representation(self, value):
     identity = Identity.objects.get(pk=value.pk)
     serializer = IdentitySummarySerializer(identity, context=self.context)
     return serializer.data
Example #11
0
 def to_representation(self, identity):
     serializer = IdentitySummarySerializer(identity, context=self.context)
     return serializer.data
Example #12
0
 def to_representation(self, value):
     queryset = self.get_queryset()
     identity = queryset.get(pk=value.pk)
     serializer = IdentitySummarySerializer(identity, context=self.context)
     return serializer.data