Beispiel #1
0
class ClusterListSerializer(serializers.ModelSerializer):
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)
    display_status = serializers.SerializerMethodField(read_only=True)
    under_task = serializers.SerializerMethodField(read_only=True)
    cluster_template = ClusterTemplateBriefSerializer(read_only=True)

    class Meta:
        model = models.Cluster
        fields = (
            'client',
            'id',
            'name',
            'status',
            'health_status',
            'display_status',
            'under_task',
            'cluster_template',
        )

    @staticmethod
    def get_display_status(model):
        return ClusterStatus.choices.get(model.status)

    @staticmethod
    def get_under_task(model):
        if model.status in ClusterStatus.under_progress_statuses:
            return True
        return False
Beispiel #2
0
class StaffFloatingIpSerializer(FloatingIpSerializer):
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)
    floating_network = FloatingNetworkMinSerializer(read_only=True)
    port = PortMinSerializer(read_only=True)
    router = RouterMinSerializer(read_only=True)
Beispiel #3
0
class StaffInvoiceDetailSerializer(serializers.ModelSerializer):
    client = ClientMinSerializer()
    items = StaffInvoiceItemSerializer(many=True)
    journal = StaffJournalDetailsSerializer(many=True)
    fleio_info = serializers.ReadOnlyField(source='get_company_info')
    balance = serializers.DecimalField(read_only=True, max_digits=14, decimal_places=2)
    taxes = serializers.JSONField(read_only=True)
    transactions = StaffTransactionSerializer(many=True)
    statuses = serializers.SerializerMethodField()
    is_add_credit = serializers.SerializerMethodField()

    class Meta:
        model = Invoice
        fields = ('id', 'status', 'issue_date', 'due_date', 'subtotal', 'total', 'currency', 'first_name', 'last_name',
                  'company', 'address1', 'city', 'country', 'state', 'zip_code', 'phone', 'fax', 'email', 'items',
                  'fleio_info', 'journal', 'balance', 'client', 'taxes', 'transactions', 'statuses', 'display_number',
                  'is_add_credit', 'is_fiscal', 'fiscal_date', 'fiscal_due_date', 'name')
        read_only_fields = ('statuses', 'is_add_credit')

    @staticmethod
    def get_statuses(model):
        del model  # unused
        return InvoiceStatus.STATUSES_LIST

    @staticmethod
    def get_is_add_credit(model):
        return model.is_credit_invoice()
Beispiel #4
0
class StaffInvoiceBriefSerializer(serializers.ModelSerializer):
    """Serializer used for read operations."""
    client = ClientMinSerializer()

    class Meta:
        model = Invoice
        fields = ('id', 'status', 'client', 'issue_date', 'due_date', 'total', 'currency', 'display_number')
Beispiel #5
0
    def create_options(self, request):
        client_id = self.request.query_params.get('client_id', None)
        if not client_id:
            return Response({'client': {}, 'networks': []})
        try:
            client = Client.objects.get(id=client_id)
        except Client.DoesNotExist:
            return Response({'client': {}, 'networks': []})

        try:
            project_id = client.first_project.project_id
        except (Exception, AttributeError):
            # NOTE: most likely code won't reach this branch because clients with project are filtered on frontend
            raise APIBadRequest(_('Client has no project'))

        networks = Network.objects.get_external_networks(project_id=project_id,
                                                         subnet_count=True)
        fnets = [{
            'id': network.id,
            'name': network.name,
            'description': network.description,
            'region': network.region
        } for network in networks.filter(subnet_count__gt=0)]

        return Response({
            'client': ClientMinSerializer(client).data,
            'networks': fnets
        })
Beispiel #6
0
class AdminInstanceDetailSerializer(InstanceDetailSerializer):
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)

    class Meta(InstanceDetailSerializer.Meta):
        fields = InstanceDetailSerializer.Meta.fields + (
            'client',
            'hostId',
            'host_name',
        )

    def allowed(self):
        allowed = copy.deepcopy(INSTANCE_ALLOWED_ACTIONS)
        if staff_active_features.is_enabled('openstack.floatingips'):
            allowed[InstanceStatus.ACTIVE] += ['associate_ip', 'dissociate_ip']
            allowed[InstanceStatus.STOPPED] += [
                'associate_ip', 'dissociate_ip'
            ]
        if staff_active_features.is_enabled(
                'openstack.instances.allow_changing_password'):
            allowed[InstanceStatus.ACTIVE] += [
                'change_password',
            ]
        return allowed

    def get_net_details(self, obj):
        ports_objects = openstack_models.Port.objects.filter(device_id=obj.id)
        floating_ips = openstack_models.FloatingIp.objects.filter(
            port__in=ports_objects).values('id', 'floating_ip_address')
        ports = list()
        for port in ports_objects:
            ipv4s = list()
            ipv6s = list()
            for fixed_ip in port.fixed_ips:
                try:
                    ip_obj = ipaddress.ip_address(fixed_ip['ip_address'])
                except ValueError:
                    continue
                if isinstance(ip_obj, ipaddress.IPv4Address):
                    ipv4s.append({
                        'ip_address': fixed_ip['ip_address'],
                        'subnet_id': fixed_ip['subnet_id']
                    })
                elif isinstance(ip_obj, ipaddress.IPv6Address):
                    ipv6s.append({
                        'ip_address': fixed_ip['ip_address'],
                        'subnet_id': fixed_ip['subnet_id']
                    })
                else:
                    continue
            ports.append({
                'id': port.id,
                'name': port.name or port.id,
                'ipv4s': ipv4s,
                'ipv6s': ipv6s,
                'floating_ips': floating_ips,
            })
        return {'ports': ports}
Beispiel #7
0
class ClusterTemplateSerializer(serializers.ModelSerializer):
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)

    class Meta:
        model = models.ClusterTemplate
        exclude = ('sync_version', )
Beispiel #8
0
class StaffOrderSerializer(serializers.ModelSerializer):
    # cart = StaffOrderItemSerializer(read_only=True, many=True)  #  NOTE(tomo): remove this field
    user = UserMinSerializer(read_only=True)
    client = ClientMinSerializer(read_only=True)
    invoice = StaffInvoiceBriefSerializer(read_only=True)
    fraud_check_result = serializers.JSONField(read_only=True)
    items = StaffOrderItemSerializer(read_only=True, many=True)
    total = serializers.DecimalField(read_only=True, decimal_places=2, max_digits=12)

    class Meta:
        model = Order
        fields = '__all__'
Beispiel #9
0
class ClusterTemplateListSerializer(serializers.ModelSerializer):
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)

    class Meta:
        model = models.ClusterTemplate
        fields = (
            'client',
            'name',
            'id',
            'created_at',
            'image_id',
            'coe',
        )
Beispiel #10
0
class StaffVolumeBackupSerializer(serializers.ModelSerializer):
    related_volume_name = serializers.SerializerMethodField(read_only=True)
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)

    class Meta:
        model = VolumeBackup
        fields = '__all__'

    @staticmethod
    def get_related_volume_name(model):
        try:
            related_volume = model.volume
        except Volume.DoesNotExist:
            return None
        if related_volume:
            return related_volume.name
        return None
Beispiel #11
0
class StaffUserProfileSerializer(serializers.ModelSerializer):
    clients = ClientMinSerializer(many=True, required=False)

    class Meta:
        model = get_user_model()
        fields = (
            'id',
            'username',
            'email',
            'first_name',
            'last_name',
            'date_joined',
            'last_login',
            'is_active',
            'is_staff',
            'language',
            'clients',
            'mobile_phone_number',
        )
class ResellerUserSerializer(serializers.ModelSerializer):
    full_name = serializers.CharField(source='get_full_name', read_only=True)
    clients = ClientMinSerializer(many=True, required=False, read_only=True)
    user_groups = UserGroupBriefSerializer(many=True, required=False)

    class Meta:
        model = get_user_model()
        fields = (
            'id', 'username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login', 'is_active',
            'clients', 'external_billing_id', 'full_name', 'password',
            'permissions', 'user_groups', 'language', 'email_verified'
        )
        read_only_fields = ('id', 'date_joined', 'last_login', 'full_name', 'permissions')
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate(self, attrs):
        validated_data = super().validate(attrs)

        request = self.context.get('request', None)
        if not request:
            raise ValidationError({'detail': _('Internal error when creating user.')})
        else:
            # user created by reseller should be assigned to creating reseller
            validated_data['reseller_resources'] = user_reseller_resources(user=request.user)
            validated_data['is_reseller'] = False

        validated_data['is_staff'] = False
        validated_data['is_superuser'] = False

        return validated_data

    def create(self, validated_data):
        # user is not associated in any group by default
        if 'user_groups' in validated_data:
            validated_data.pop('user_groups', None)
        if 'language' not in validated_data:
            validated_data['language'] = getattr(settings, 'DEFAULT_USER_LANGUAGE', 'en')

        return self.Meta.model.objects.create_user(**validated_data)
Beispiel #13
0
class UserSerializer(ComponentDataModelSerializer):
    clients = ClientMinSerializer(many=True, required=False)

    class Meta:
        model = get_user_model()
        fields = (
            'id',
            'username',
            'email',
            'first_name',
            'last_name',
            'date_joined',
            'last_login',
            'is_active',
            'language',
            'clients',
            'email_verified',
            'mobile_phone_number',
        )
        component_name = 'UserSettings'
        plugin_config_type = PluginConfigTypes.enduser
Beispiel #14
0
class AdminInstanceSerializer(InstanceSerializer):
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)
    host_name = serializers.CharField()

    class Meta(InstanceSerializer.Meta):
        fields = InstanceSerializer.Meta.fields + ('client', 'host_name')

    def allowed(self):
        allowed = copy.deepcopy(INSTANCE_ALLOWED_ACTIONS)
        if staff_active_features.is_enabled('openstack.floatingips'):
            allowed[InstanceStatus.ACTIVE] += ['associate_ip', 'dissociate_ip']
            allowed[InstanceStatus.STOPPED] += [
                'associate_ip', 'dissociate_ip'
            ]
        if staff_active_features.is_enabled(
                'openstack.instances.allow_changing_password'):
            allowed[InstanceStatus.ACTIVE] += [
                'change_password',
            ]
        return allowed
Beispiel #15
0
class VolumeSnapshotSerializer(serializers.ModelSerializer):
    related_volume_name = serializers.SerializerMethodField(read_only=True)
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)

    class Meta:
        model = models.VolumeSnapshot
        exclude = (
            'project',
            'sync_version',
        )

    @staticmethod
    def get_related_volume_name(model):
        try:
            related_volume = model.volume
        except models.Volume.DoesNotExist:
            return None
        if related_volume:
            return related_volume.name
        return None
Beispiel #16
0
class StaffVolumeSerializer(serializers.ModelSerializer):
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)
    display_name = serializers.ReadOnlyField()
    size_increment = serializers.SerializerMethodField()
    number_of_snapshots = serializers.SerializerMethodField(read_only=True)
    related_instance_uuid = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Volume
        exclude = (
            'extra',
            'sync_version',
        )

    @staticmethod
    def get_related_instance_uuid(volume):
        volume_attachment = VolumeAttachments.objects.filter(
            volume_id=volume.id).first()
        return volume_attachment.server_id if volume_attachment else None

    @staticmethod
    def get_number_of_snapshots(volume):
        return VolumeSnapshot.objects.filter(volume=volume).count()

    @staticmethod
    def get_size_increment(volume):
        conf = OSConfig()
        volume_size_increments = conf.volume_size_increments
        if volume_size_increments:
            size_increment = volume_size_increments.get(volume.region, {}).get(
                volume.type, 1)
        else:
            size_increment = 1
        return size_increment
Beispiel #17
0
class StaffUserSerializer(serializers.ModelSerializer):
    full_name = serializers.CharField(source='get_full_name', read_only=True)
    clients = ClientMinSerializer(many=True, required=False, read_only=True)
    user_groups = UserGroupBriefSerializer(many=True, required=False)
    latest_agreed_tos = serializers.SerializerMethodField(read_only=True,
                                                          required=False)
    reseller_client = serializers.SerializerMethodField(read_only=True,
                                                        required=False)
    reseller_client_details = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = get_user_model()
        fields = (
            'id',
            'username',
            'email',
            'first_name',
            'last_name',
            'date_joined',
            'last_login',
            'is_active',
            'is_reseller',
            'clients',
            'external_billing_id',
            'full_name',
            'is_staff',
            'is_superuser',
            'password',
            'permissions',
            'user_groups',
            'language',
            'email_verified',
            'reseller_client',
            'latest_agreed_tos',
            'reseller_client_details',
        )
        read_only_fields = (
            'id',
            'date_joined',
            'last_login',
            'full_name',
            'permissions',
            'reseller_client_details',
        )
        extra_kwargs = {'password': {'write_only': True}}

    @staticmethod
    def get_reseller_client(user):
        if user.reseller_resources:
            return user.reseller_resources.service.client.id
        else:
            return None

    @staticmethod
    def get_reseller_client_details(user: AppUser):
        if user.reseller_resources:
            return {
                'name': user.reseller_resources.service.client.name,
                'id': user.reseller_resources.service.client.id,
            }
        else:
            return None

    @staticmethod
    def get_latest_agreed_tos(user):
        tos_agreement = TermsOfServiceAgreement.objects.filter(
            user=user,
            agreed=True).order_by('-terms_of_service__version').first(
            )  # take the latest version
        if not tos_agreement:
            return None
        return dict(
            id=tos_agreement.id,
            version=tos_agreement.terms_of_service.version,
            agreed_at=tos_agreement.agreed_at,
            ip=tos_agreement.ip,
        )

    def create(self, validated_data):
        # user is not associated in any group by default
        if 'user_groups' in validated_data:
            validated_data.pop('user_groups', None)
        if 'language' not in validated_data:
            validated_data['language'] = getattr(settings,
                                                 'DEFAULT_USER_LANGUAGE', 'en')
        return self.Meta.model.objects.create_user(**validated_data)

    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)
        user = super(StaffUserSerializer, self).update(instance,
                                                       validated_data)
        if password:
            user.set_password(password)
            user.save()
        return user
Beispiel #18
0
class ImageSerializer(serializers.ModelSerializer):
    tags = serializers.JSONField(default=list())
    client = ClientMinSerializer(source='project.service.client',
                                 read_only=True,
                                 default=None)
    properties = serializers.JSONField(default=dict())
    is_iso = serializers.SerializerMethodField()
    display_name = serializers.SerializerMethodField()
    cleanup_date = serializers.SerializerMethodField()
    assigned_to_flavor = serializers.BooleanField(default=True, read_only=True)

    class Meta:
        model = Image
        exclude = ('project', 'owner', 'sync_version', 'virtual_size',
                   'flavors', 'flavor_groups')
        read_only_fields = (
            'id',
            'type',
            'region',
            'status',
            'size',
            'os_distro',
            'os_version',
            'architecture',
            'instance_uuid',
            'is_iso',
            'display_name',
            'cleanup_date',
            'assigned_to_flavor',
            'properties',
        )

    def to_representation(self, instance):
        if isinstance(instance.properties, dict):
            # we treat these items as field not as properties
            instance.properties.pop('os_distro', None)
            instance.properties.pop('hypervisor_type', None)
            instance.properties.pop('os_version', None)
            instance.properties.pop('architecture', None)
        else:
            instance.properties = {}
        return super(ImageSerializer,
                     self).to_representation(instance=instance)

    @staticmethod
    def get_is_iso(image: Image) -> bool:
        return image.disk_format == 'iso'

    @staticmethod
    def get_display_name(image: Image) -> str:
        if image.disk_format == 'iso':
            return '[ISO] {}'.format(image.name)

        return image.name

    @staticmethod
    def get_cleanup_date(image: Image):
        cleanup_date = None
        try:
            project = image.project
        except Project.DoesNotExist:
            return cleanup_date

        if project and project.service and project.service.client:
            openstack_settings = OpenstackSettings.for_client(
                project.service.client)

            if openstack_settings.auto_cleanup_image_types:
                if image.disk_format in openstack_settings.auto_cleanup_image_types:
                    cleanup_date = image.created_at + timedelta(
                        days=openstack_settings.auto_cleanup_number_of_days)

        return cleanup_date