2018-02-07 15:25:15 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2022-09-23 10:59:19 +00:00
|
|
|
|
2022-08-22 10:32:33 +00:00
|
|
|
from django.db.models import F
|
2022-12-27 08:53:23 +00:00
|
|
|
from django.db.transaction import atomic
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
from rest_framework import serializers
|
2019-05-21 08:24:01 +00:00
|
|
|
|
2023-02-01 10:45:51 +00:00
|
|
|
from accounts.models import Account
|
2023-01-30 10:59:12 +00:00
|
|
|
from accounts.serializers import AccountSerializerCreateValidateMixin
|
2023-02-15 12:16:01 +00:00
|
|
|
from accounts.serializers import AuthValidateMixin
|
2023-01-16 11:02:09 +00:00
|
|
|
from common.serializers import WritableNestedModelSerializer, SecretReadableMixin, CommonModelSerializer
|
|
|
|
from common.serializers.fields import LabeledChoiceField
|
|
|
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
2022-08-18 09:58:59 +00:00
|
|
|
from ...const import Category, AllTypes
|
2023-01-16 11:02:09 +00:00
|
|
|
from ...models import Asset, Node, Platform, Label, Protocol
|
2018-02-07 15:25:15 +00:00
|
|
|
|
2018-04-24 03:07:09 +00:00
|
|
|
__all__ = [
|
2021-08-27 08:38:23 +00:00
|
|
|
'AssetSerializer', 'AssetSimpleSerializer', 'MiniAssetSerializer',
|
2022-11-16 07:07:35 +00:00
|
|
|
'AssetTaskSerializer', 'AssetsTaskSerializer', 'AssetProtocolsSerializer',
|
2023-01-16 11:02:09 +00:00
|
|
|
'AssetDetailSerializer', 'DetailMixin', 'AssetAccountSerializer',
|
2023-01-31 09:46:56 +00:00
|
|
|
'AccountSecretSerializer', 'SpecSerializer'
|
2018-04-24 03:07:09 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
|
2022-08-05 07:46:36 +00:00
|
|
|
class AssetProtocolsSerializer(serializers.ModelSerializer):
|
2023-02-17 13:11:06 +00:00
|
|
|
port = serializers.IntegerField(required=False, allow_null=True, max_value=65535, min_value=1)
|
|
|
|
|
2023-03-10 07:52:07 +00:00
|
|
|
def to_file_representation(self, data):
|
|
|
|
return '{name}/{port}'.format(**data)
|
|
|
|
|
|
|
|
def to_file_internal_value(self, data):
|
|
|
|
name, port = data.split('/')
|
|
|
|
return {'name': name, 'port': port}
|
|
|
|
|
2022-08-05 07:46:36 +00:00
|
|
|
class Meta:
|
|
|
|
model = Protocol
|
2023-01-16 11:02:09 +00:00
|
|
|
fields = ['name', 'port']
|
2019-07-05 10:07:10 +00:00
|
|
|
|
2019-06-19 11:25:21 +00:00
|
|
|
|
2022-08-05 07:46:36 +00:00
|
|
|
class AssetLabelSerializer(serializers.ModelSerializer):
|
|
|
|
class Meta:
|
|
|
|
model = Label
|
2022-09-28 04:10:39 +00:00
|
|
|
fields = ['id', 'name', 'value']
|
2022-08-08 03:39:55 +00:00
|
|
|
extra_kwargs = {
|
2023-02-07 07:56:59 +00:00
|
|
|
# 取消默认唯一键的校验
|
|
|
|
'id': {'validators': []},
|
2022-08-09 08:53:43 +00:00
|
|
|
'name': {'required': False},
|
2023-02-07 07:56:59 +00:00
|
|
|
'value': {'required': False},
|
2022-08-08 03:39:55 +00:00
|
|
|
}
|
2022-05-05 08:18:05 +00:00
|
|
|
|
2019-06-19 11:25:21 +00:00
|
|
|
|
2022-08-08 03:39:55 +00:00
|
|
|
class AssetPlatformSerializer(serializers.ModelSerializer):
|
|
|
|
class Meta:
|
|
|
|
model = Platform
|
2022-08-09 08:53:43 +00:00
|
|
|
fields = ['id', 'name']
|
2022-08-08 03:39:55 +00:00
|
|
|
extra_kwargs = {
|
|
|
|
'name': {'required': False}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-01-30 10:59:12 +00:00
|
|
|
class AssetAccountSerializer(
|
2023-02-15 12:16:01 +00:00
|
|
|
AuthValidateMixin,
|
|
|
|
AccountSerializerCreateValidateMixin,
|
|
|
|
CommonModelSerializer
|
2023-01-30 10:59:12 +00:00
|
|
|
):
|
2022-09-07 12:24:48 +00:00
|
|
|
add_org_fields = False
|
2023-01-16 11:02:09 +00:00
|
|
|
push_now = serializers.BooleanField(
|
|
|
|
default=False, label=_("Push now"), write_only=True
|
|
|
|
)
|
2023-02-01 06:43:58 +00:00
|
|
|
template = serializers.BooleanField(
|
|
|
|
default=False, label=_("Template"), write_only=True
|
|
|
|
)
|
2023-02-14 03:37:18 +00:00
|
|
|
name = serializers.CharField(max_length=128, required=True, label=_("Name"))
|
2022-09-07 12:24:48 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
class Meta:
|
|
|
|
model = Account
|
2022-09-07 12:24:48 +00:00
|
|
|
fields_mini = [
|
2023-02-17 09:14:53 +00:00
|
|
|
'id', 'name', 'username', 'privileged',
|
|
|
|
'is_active', 'version', 'secret_type',
|
2022-09-13 13:07:20 +00:00
|
|
|
]
|
|
|
|
fields_write_only = [
|
2023-03-10 08:04:48 +00:00
|
|
|
'secret', 'passphrase', 'push_now', 'template'
|
2022-09-07 12:24:48 +00:00
|
|
|
]
|
|
|
|
fields = fields_mini + fields_write_only
|
2023-01-16 11:02:09 +00:00
|
|
|
extra_kwargs = {
|
|
|
|
'secret': {'write_only': True},
|
|
|
|
}
|
|
|
|
|
2023-02-10 03:12:03 +00:00
|
|
|
def validate_push_now(self, value):
|
|
|
|
request = self.context['request']
|
2023-02-21 05:39:28 +00:00
|
|
|
if not request.user.has_perms('accounts.push_account'):
|
2023-02-10 03:12:03 +00:00
|
|
|
return False
|
|
|
|
return value
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
def validate_name(self, value):
|
|
|
|
if not value:
|
|
|
|
value = self.initial_data.get('username')
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
class AccountSecretSerializer(SecretReadableMixin, CommonModelSerializer):
|
|
|
|
class Meta:
|
|
|
|
model = Account
|
|
|
|
fields = [
|
|
|
|
'name', 'username', 'privileged', 'secret_type', 'secret',
|
|
|
|
]
|
|
|
|
extra_kwargs = {
|
|
|
|
'secret': {'write_only': False},
|
|
|
|
}
|
2022-09-07 12:24:48 +00:00
|
|
|
|
|
|
|
|
2023-01-31 09:46:56 +00:00
|
|
|
class SpecSerializer(serializers.Serializer):
|
|
|
|
# 数据库
|
|
|
|
db_name = serializers.CharField(label=_("Database"), max_length=128, required=False)
|
|
|
|
use_ssl = serializers.BooleanField(label=_("Use SSL"), required=False)
|
|
|
|
allow_invalid_cert = serializers.BooleanField(label=_("Allow invalid cert"), required=False)
|
|
|
|
# Web
|
|
|
|
autofill = serializers.CharField(label=_("Auto fill"), required=False)
|
|
|
|
username_selector = serializers.CharField(label=_("Username selector"), required=False)
|
|
|
|
password_selector = serializers.CharField(label=_("Password selector"), required=False)
|
|
|
|
submit_selector = serializers.CharField(label=_("Submit selector"), required=False)
|
|
|
|
script = serializers.JSONField(label=_("Script"), required=False)
|
|
|
|
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
class AssetSerializer(BulkOrgResourceModelSerializer, WritableNestedModelSerializer):
|
2022-09-01 06:46:31 +00:00
|
|
|
category = LabeledChoiceField(choices=Category.choices, read_only=True, label=_('Category'))
|
2022-09-26 10:03:48 +00:00
|
|
|
type = LabeledChoiceField(choices=AllTypes.choices(), read_only=True, label=_('Type'))
|
2023-01-16 11:02:09 +00:00
|
|
|
labels = AssetLabelSerializer(many=True, required=False, label=_('Label'))
|
2023-02-03 11:44:59 +00:00
|
|
|
protocols = AssetProtocolsSerializer(many=True, required=False, label=_('Protocols'), default=())
|
2023-03-10 07:52:07 +00:00
|
|
|
accounts = AssetAccountSerializer(many=True, required=False, allow_null=True, write_only=True, label=_('Account'))
|
|
|
|
nodes_display = serializers.ListField(read_only=True, label=_("Node path"))
|
2022-09-09 03:00:09 +00:00
|
|
|
|
2018-02-07 15:25:15 +00:00
|
|
|
class Meta:
|
|
|
|
model = Asset
|
2022-12-27 08:53:23 +00:00
|
|
|
fields_mini = ['id', 'name', 'address']
|
2022-09-09 03:00:09 +00:00
|
|
|
fields_small = fields_mini + ['is_active', 'comment']
|
2023-01-16 11:02:09 +00:00
|
|
|
fields_fk = ['domain', 'platform']
|
2020-04-23 03:14:02 +00:00
|
|
|
fields_m2m = [
|
2023-01-31 09:46:56 +00:00
|
|
|
'nodes', 'labels', 'protocols',
|
|
|
|
'nodes_display', 'accounts'
|
2019-05-21 08:24:01 +00:00
|
|
|
]
|
2020-04-23 03:14:02 +00:00
|
|
|
read_only_fields = [
|
2023-03-10 07:52:07 +00:00
|
|
|
'category', 'type', 'connectivity', 'auto_info',
|
2023-02-09 12:48:25 +00:00
|
|
|
'date_verified', 'created_by', 'date_created',
|
2021-07-08 06:23:18 +00:00
|
|
|
]
|
2022-04-02 10:35:46 +00:00
|
|
|
fields = fields_small + fields_fk + fields_m2m + read_only_fields
|
2023-03-10 07:52:07 +00:00
|
|
|
fields_unexport = ['auto_info']
|
2021-11-11 03:56:30 +00:00
|
|
|
extra_kwargs = {
|
2023-02-23 11:14:58 +00:00
|
|
|
'auto_info': {'label': _('Auto info')},
|
2022-08-11 07:45:03 +00:00
|
|
|
'name': {'label': _("Name")},
|
2022-09-21 03:17:14 +00:00
|
|
|
'address': {'label': _('Address')},
|
2022-12-27 08:21:32 +00:00
|
|
|
'nodes_display': {'label': _('Node path')},
|
2021-11-11 03:56:30 +00:00
|
|
|
}
|
2018-02-07 15:25:15 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self._init_field_choices()
|
|
|
|
|
2023-02-03 11:44:59 +00:00
|
|
|
def _get_protocols_required_default(self):
|
2023-03-15 06:14:48 +00:00
|
|
|
platform = self._asset_platform
|
2023-02-03 11:44:59 +00:00
|
|
|
platform_protocols = platform.protocols.all()
|
|
|
|
protocols_default = [p for p in platform_protocols if p.default]
|
|
|
|
protocols_required = [p for p in platform_protocols if p.required or p.primary]
|
|
|
|
return protocols_required, protocols_default
|
|
|
|
|
|
|
|
def _set_protocols_default(self):
|
|
|
|
if not hasattr(self, 'initial_data'):
|
|
|
|
return
|
|
|
|
protocols = self.initial_data.get('protocols')
|
|
|
|
if protocols is not None:
|
|
|
|
return
|
|
|
|
|
|
|
|
protocols_required, protocols_default = self._get_protocols_required_default()
|
|
|
|
protocols_data = [
|
|
|
|
{'name': p.name, 'port': p.port}
|
|
|
|
for p in protocols_required + protocols_default
|
|
|
|
]
|
|
|
|
self.initial_data['protocols'] = protocols_data
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
def _init_field_choices(self):
|
|
|
|
request = self.context.get('request')
|
|
|
|
if not request:
|
|
|
|
return
|
|
|
|
category = request.path.strip('/').split('/')[-1].rstrip('s')
|
|
|
|
field_category = self.fields.get('category')
|
2023-02-02 06:37:21 +00:00
|
|
|
field_category.choices = Category.filter_choices(category)
|
2023-01-16 11:02:09 +00:00
|
|
|
field_type = self.fields.get('type')
|
2023-02-02 06:37:21 +00:00
|
|
|
field_type.choices = AllTypes.filter_choices(category)
|
2023-01-16 11:02:09 +00:00
|
|
|
|
2018-12-17 10:20:44 +00:00
|
|
|
@classmethod
|
|
|
|
def setup_eager_loading(cls, queryset):
|
|
|
|
""" Perform necessary eager loading of data. """
|
2023-02-23 08:14:24 +00:00
|
|
|
queryset = queryset.prefetch_related('domain', 'nodes', 'labels', 'protocols') \
|
|
|
|
.prefetch_related('platform', 'platform__automation') \
|
2022-08-24 08:36:42 +00:00
|
|
|
.annotate(category=F("platform__category")) \
|
2022-08-22 10:32:33 +00:00
|
|
|
.annotate(type=F("platform__type"))
|
2018-12-17 10:20:44 +00:00
|
|
|
return queryset
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
@staticmethod
|
|
|
|
def perform_nodes_display_create(instance, nodes_display):
|
2020-10-30 02:16:49 +00:00
|
|
|
if not nodes_display:
|
|
|
|
return
|
|
|
|
nodes_to_set = []
|
|
|
|
for full_value in nodes_display:
|
2022-10-25 11:31:13 +00:00
|
|
|
if not full_value.startswith('/'):
|
|
|
|
full_value = '/' + instance.org.name + '/' + full_value
|
2020-10-30 02:16:49 +00:00
|
|
|
node = Node.objects.filter(full_value=full_value).first()
|
|
|
|
if node:
|
|
|
|
nodes_to_set.append(node)
|
|
|
|
else:
|
|
|
|
node = Node.create_node_by_full_value(full_value)
|
|
|
|
nodes_to_set.append(node)
|
|
|
|
instance.nodes.set(nodes_to_set)
|
|
|
|
|
2023-02-23 09:44:38 +00:00
|
|
|
@property
|
2023-03-15 06:14:48 +00:00
|
|
|
def _asset_platform(self):
|
2023-02-03 11:44:59 +00:00
|
|
|
platform_id = self.initial_data.get('platform')
|
|
|
|
if isinstance(platform_id, dict):
|
|
|
|
platform_id = platform_id.get('id') or platform_id.get('pk')
|
2023-03-15 06:14:48 +00:00
|
|
|
|
|
|
|
if not platform_id and self.instance:
|
|
|
|
platform = self.instance.platform
|
|
|
|
else:
|
|
|
|
platform = Platform.objects.filter(id=platform_id).first()
|
|
|
|
|
2023-02-03 11:44:59 +00:00
|
|
|
if not platform:
|
|
|
|
raise serializers.ValidationError({'platform': _("Platform not exist")})
|
|
|
|
return platform
|
|
|
|
|
|
|
|
def validate_domain(self, value):
|
2023-03-15 06:14:48 +00:00
|
|
|
platform = self._asset_platform
|
2023-02-03 11:44:59 +00:00
|
|
|
if platform.domain_enabled:
|
|
|
|
return value
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2022-09-09 03:00:09 +00:00
|
|
|
def validate_nodes(self, nodes):
|
|
|
|
if nodes:
|
|
|
|
return nodes
|
2023-02-19 07:43:56 +00:00
|
|
|
nodes_display = self.initial_data.get('nodes_display')
|
|
|
|
if nodes_display:
|
|
|
|
return nodes
|
2022-09-09 03:00:09 +00:00
|
|
|
request = self.context.get('request')
|
|
|
|
if not request:
|
|
|
|
return []
|
|
|
|
node_id = request.query_params.get('node_id')
|
|
|
|
if not node_id:
|
|
|
|
return []
|
2023-02-09 12:48:25 +00:00
|
|
|
nodes = Node.objects.filter(id=node_id)
|
|
|
|
return nodes
|
2022-09-09 03:00:09 +00:00
|
|
|
|
2023-02-03 11:44:59 +00:00
|
|
|
def is_valid(self, raise_exception=False):
|
|
|
|
self._set_protocols_default()
|
|
|
|
return super().is_valid(raise_exception)
|
2022-10-18 12:37:17 +00:00
|
|
|
|
2023-02-03 11:44:59 +00:00
|
|
|
def validate_protocols(self, protocols_data):
|
|
|
|
# 目的是去重
|
2022-10-18 12:37:17 +00:00
|
|
|
protocols_data_map = {p['name']: p for p in protocols_data}
|
2023-02-03 08:03:34 +00:00
|
|
|
for p in protocols_data:
|
|
|
|
port = p.get('port', 0)
|
|
|
|
if port < 1 or port > 65535:
|
|
|
|
error = p.get('name') + ': ' + _("port out of range (1-65535)")
|
|
|
|
raise serializers.ValidationError(error)
|
|
|
|
|
2023-02-03 11:44:59 +00:00
|
|
|
protocols_required, protocols_default = self._get_protocols_required_default()
|
2022-10-18 12:37:17 +00:00
|
|
|
protocols_not_found = [p.name for p in protocols_required if p.name not in protocols_data_map]
|
|
|
|
if protocols_not_found:
|
|
|
|
raise serializers.ValidationError({
|
|
|
|
'protocols': _("Protocol is required: {}").format(', '.join(protocols_not_found))
|
|
|
|
})
|
|
|
|
return protocols_data_map.values()
|
|
|
|
|
2023-02-06 03:00:36 +00:00
|
|
|
@staticmethod
|
|
|
|
def accounts_create(accounts_data, asset):
|
2023-03-13 09:57:50 +00:00
|
|
|
if not accounts_data:
|
|
|
|
return
|
2023-02-06 03:00:36 +00:00
|
|
|
for data in accounts_data:
|
|
|
|
data['asset'] = asset
|
|
|
|
AssetAccountSerializer().create(data)
|
|
|
|
|
2022-08-24 08:36:42 +00:00
|
|
|
@atomic
|
2019-07-05 10:07:10 +00:00
|
|
|
def create(self, validated_data):
|
2020-10-31 04:52:24 +00:00
|
|
|
nodes_display = validated_data.pop('nodes_display', '')
|
2023-02-06 03:00:36 +00:00
|
|
|
accounts = validated_data.pop('accounts', [])
|
2019-06-13 10:58:43 +00:00
|
|
|
instance = super().create(validated_data)
|
2023-02-06 03:00:36 +00:00
|
|
|
self.accounts_create(accounts, instance)
|
2020-10-30 02:16:49 +00:00
|
|
|
self.perform_nodes_display_create(instance, nodes_display)
|
2019-06-13 10:58:43 +00:00
|
|
|
return instance
|
|
|
|
|
2022-08-24 08:36:42 +00:00
|
|
|
@atomic
|
2019-06-13 10:58:43 +00:00
|
|
|
def update(self, instance, validated_data):
|
2023-02-22 03:04:29 +00:00
|
|
|
if not validated_data.get('accounts'):
|
|
|
|
validated_data.pop('accounts', None)
|
2020-10-31 04:52:24 +00:00
|
|
|
nodes_display = validated_data.pop('nodes_display', '')
|
2020-10-30 02:16:49 +00:00
|
|
|
instance = super().update(instance, validated_data)
|
|
|
|
self.perform_nodes_display_create(instance, nodes_display)
|
|
|
|
return instance
|
2018-02-07 15:25:15 +00:00
|
|
|
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
class DetailMixin(serializers.Serializer):
|
2022-12-27 08:53:23 +00:00
|
|
|
accounts = AssetAccountSerializer(many=True, required=False, label=_('Accounts'))
|
2023-01-31 09:46:56 +00:00
|
|
|
spec_info = serializers.DictField(label=_('Spec info'), read_only=True)
|
|
|
|
auto_info = serializers.DictField(read_only=True, label=_('Auto info'))
|
2022-12-27 08:53:23 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
def get_field_names(self, declared_fields, info):
|
|
|
|
names = super().get_field_names(declared_fields, info)
|
|
|
|
names.extend([
|
2023-01-31 09:46:56 +00:00
|
|
|
'accounts', 'info', 'spec_info', 'auto_info'
|
2023-01-16 11:02:09 +00:00
|
|
|
])
|
|
|
|
return names
|
|
|
|
|
|
|
|
|
|
|
|
class AssetDetailSerializer(DetailMixin, AssetSerializer):
|
|
|
|
pass
|
2022-12-27 08:53:23 +00:00
|
|
|
|
|
|
|
|
2021-08-27 08:38:23 +00:00
|
|
|
class MiniAssetSerializer(serializers.ModelSerializer):
|
|
|
|
class Meta:
|
|
|
|
model = Asset
|
|
|
|
fields = AssetSerializer.Meta.fields_mini
|
|
|
|
|
|
|
|
|
2018-12-18 09:28:45 +00:00
|
|
|
class AssetSimpleSerializer(serializers.ModelSerializer):
|
|
|
|
class Meta:
|
|
|
|
model = Asset
|
2022-04-29 10:28:12 +00:00
|
|
|
fields = [
|
2022-09-21 03:17:14 +00:00
|
|
|
'id', 'name', 'address', 'port',
|
2022-04-29 10:28:12 +00:00
|
|
|
'connectivity', 'date_verified'
|
|
|
|
]
|
2020-03-12 08:24:38 +00:00
|
|
|
|
|
|
|
|
2021-07-20 06:48:38 +00:00
|
|
|
class AssetsTaskSerializer(serializers.Serializer):
|
2020-03-12 08:24:38 +00:00
|
|
|
ACTION_CHOICES = (
|
|
|
|
('refresh', 'refresh'),
|
|
|
|
('test', 'test'),
|
|
|
|
)
|
|
|
|
task = serializers.CharField(read_only=True)
|
|
|
|
action = serializers.ChoiceField(choices=ACTION_CHOICES, write_only=True)
|
2021-01-06 03:08:35 +00:00
|
|
|
assets = serializers.PrimaryKeyRelatedField(
|
|
|
|
queryset=Asset.objects, required=False, allow_empty=True, many=True
|
|
|
|
)
|
2021-07-20 06:48:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AssetTaskSerializer(AssetsTaskSerializer):
|
|
|
|
ACTION_CHOICES = tuple(list(AssetsTaskSerializer.ACTION_CHOICES) + [
|
|
|
|
('push_system_user', 'push_system_user'),
|
|
|
|
('test_system_user', 'test_system_user')
|
|
|
|
])
|
2021-08-17 06:02:13 +00:00
|
|
|
action = serializers.ChoiceField(choices=ACTION_CHOICES, write_only=True)
|
2021-07-20 06:48:38 +00:00
|
|
|
asset = serializers.PrimaryKeyRelatedField(
|
|
|
|
queryset=Asset.objects, required=False, allow_empty=True, many=False
|
|
|
|
)
|
2022-11-02 09:27:47 +00:00
|
|
|
accounts = serializers.PrimaryKeyRelatedField(
|
|
|
|
queryset=Account.objects, required=False, allow_empty=True, many=True
|
|
|
|
)
|