2018-02-07 15:25:15 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
|
|
|
|
from rest_framework import serializers
|
2021-01-19 09:29:44 +00:00
|
|
|
|
from django.core.validators import RegexValidator
|
2019-05-21 08:24:01 +00:00
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
from orgs.mixins.serializers import BulkOrgResourceModelSerializer
|
2021-07-08 06:23:18 +00:00
|
|
|
|
from ..models import Asset, Node, Platform, SystemUser
|
2018-02-07 15:25:15 +00:00
|
|
|
|
|
2018-04-24 03:07:09 +00:00
|
|
|
|
__all__ = [
|
2021-07-15 09:57:14 +00:00
|
|
|
|
'AssetSerializer', 'AssetSimpleSerializer',
|
2019-12-16 08:53:29 +00:00
|
|
|
|
'ProtocolsField', 'PlatformSerializer',
|
2021-07-08 06:23:18 +00:00
|
|
|
|
'AssetTaskSerializer',
|
2018-04-24 03:07:09 +00:00
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
2019-07-05 10:07:10 +00:00
|
|
|
|
class ProtocolField(serializers.RegexField):
|
2021-07-08 06:23:18 +00:00
|
|
|
|
protocols = '|'.join(dict(Asset.Protocol.choices).keys())
|
2019-07-05 10:07:10 +00:00
|
|
|
|
default_error_messages = {
|
|
|
|
|
'invalid': _('Protocol format should {}/{}'.format(protocols, '1-65535'))
|
|
|
|
|
}
|
|
|
|
|
regex = r'^(%s)/(\d{1,5})$' % protocols
|
2019-06-13 10:58:43 +00:00
|
|
|
|
|
2019-07-05 10:07:10 +00:00
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(self.regex, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def validate_duplicate_protocols(values):
|
|
|
|
|
errors = []
|
|
|
|
|
names = []
|
|
|
|
|
|
|
|
|
|
for value in values:
|
|
|
|
|
if not value or '/' not in value:
|
|
|
|
|
continue
|
|
|
|
|
name = value.split('/')[0]
|
|
|
|
|
if name in names:
|
|
|
|
|
errors.append(_("Protocol duplicate: {}").format(name))
|
|
|
|
|
names.append(name)
|
|
|
|
|
errors.append('')
|
|
|
|
|
if any(errors):
|
|
|
|
|
raise serializers.ValidationError(errors)
|
2019-06-13 10:58:43 +00:00
|
|
|
|
|
2019-06-19 11:25:21 +00:00
|
|
|
|
|
2019-07-05 10:07:10 +00:00
|
|
|
|
class ProtocolsField(serializers.ListField):
|
|
|
|
|
default_validators = [validate_duplicate_protocols]
|
|
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
kwargs['child'] = ProtocolField()
|
|
|
|
|
kwargs['allow_null'] = True
|
|
|
|
|
kwargs['allow_empty'] = True
|
|
|
|
|
kwargs['min_length'] = 1
|
|
|
|
|
kwargs['max_length'] = 4
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
def to_representation(self, value):
|
|
|
|
|
if not value:
|
|
|
|
|
return []
|
|
|
|
|
return value.split(' ')
|
2019-06-19 11:25:21 +00:00
|
|
|
|
|
|
|
|
|
|
2019-06-19 08:45:14 +00:00
|
|
|
|
class AssetSerializer(BulkOrgResourceModelSerializer):
|
2019-12-16 08:53:29 +00:00
|
|
|
|
platform = serializers.SlugRelatedField(
|
|
|
|
|
slug_field='name', queryset=Platform.objects.all(), label=_("Platform")
|
|
|
|
|
)
|
2021-04-27 10:19:54 +00:00
|
|
|
|
protocols = ProtocolsField(label=_('Protocols'), required=False, default=['ssh/22'])
|
2020-10-30 02:16:49 +00:00
|
|
|
|
domain_display = serializers.ReadOnlyField(source='domain.name', label=_('Domain name'))
|
|
|
|
|
nodes_display = serializers.ListField(child=serializers.CharField(), label=_('Nodes name'), required=False)
|
2020-07-07 03:09:43 +00:00
|
|
|
|
|
2018-02-07 15:25:15 +00:00
|
|
|
|
"""
|
|
|
|
|
资产的数据结构
|
|
|
|
|
"""
|
|
|
|
|
class Meta:
|
|
|
|
|
model = Asset
|
2020-04-23 03:14:02 +00:00
|
|
|
|
fields_mini = ['id', 'hostname', 'ip']
|
|
|
|
|
fields_small = fields_mini + [
|
|
|
|
|
'protocol', 'port', 'protocols', 'is_active', 'public_ip',
|
|
|
|
|
'number', 'vendor', 'model', 'sn', 'cpu_model', 'cpu_count',
|
|
|
|
|
'cpu_cores', 'cpu_vcpus', 'memory', 'disk_total', 'disk_info',
|
|
|
|
|
'os', 'os_version', 'os_arch', 'hostname_raw', 'comment',
|
2021-07-08 06:23:18 +00:00
|
|
|
|
'hardware_info', 'connectivity', 'date_verified'
|
2020-04-23 03:14:02 +00:00
|
|
|
|
]
|
|
|
|
|
fields_fk = [
|
2021-07-15 09:57:14 +00:00
|
|
|
|
'domain', 'domain_display', 'platform', 'admin_user', 'admin_user_display'
|
2020-04-23 03:14:02 +00:00
|
|
|
|
]
|
|
|
|
|
fields_m2m = [
|
2020-10-30 02:16:49 +00:00
|
|
|
|
'nodes', 'nodes_display', 'labels',
|
2019-05-21 08:24:01 +00:00
|
|
|
|
]
|
2020-04-23 03:14:02 +00:00
|
|
|
|
read_only_fields = [
|
2019-05-21 08:24:01 +00:00
|
|
|
|
'created_by', 'date_created',
|
2021-07-08 06:23:18 +00:00
|
|
|
|
]
|
|
|
|
|
fields = fields_small + fields_fk + fields_m2m + read_only_fields
|
2020-04-23 03:14:02 +00:00
|
|
|
|
|
2019-05-21 08:24:01 +00:00
|
|
|
|
extra_kwargs = {
|
2019-06-19 11:25:21 +00:00
|
|
|
|
'protocol': {'write_only': True},
|
|
|
|
|
'port': {'write_only': True},
|
2019-05-21 08:24:01 +00:00
|
|
|
|
'hardware_info': {'label': _('Hardware info')},
|
2021-07-12 12:11:53 +00:00
|
|
|
|
'org_name': {'label': _('Org name')},
|
2019-05-21 08:24:01 +00:00
|
|
|
|
}
|
2018-02-07 15:25:15 +00:00
|
|
|
|
|
2021-07-08 06:23:18 +00:00
|
|
|
|
def get_fields(self):
|
|
|
|
|
fields = super().get_fields()
|
|
|
|
|
|
|
|
|
|
admin_user_field = fields.get('admin_user')
|
|
|
|
|
# 因为 mixin 中对 fields 有处理,可能不需要返回 admin_user
|
|
|
|
|
if admin_user_field:
|
|
|
|
|
admin_user_field.queryset = SystemUser.objects.filter(type=SystemUser.Type.admin)
|
|
|
|
|
return fields
|
|
|
|
|
|
2018-12-17 10:20:44 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def setup_eager_loading(cls, queryset):
|
|
|
|
|
""" Perform necessary eager loading of data. """
|
2021-07-15 09:57:14 +00:00
|
|
|
|
queryset = queryset.prefetch_related('domain', 'platform', 'admin_user')
|
2020-09-27 08:02:44 +00:00
|
|
|
|
queryset = queryset.prefetch_related('nodes', 'labels')
|
2018-12-17 10:20:44 +00:00
|
|
|
|
return queryset
|
|
|
|
|
|
2019-07-05 10:07:10 +00:00
|
|
|
|
def compatible_with_old_protocol(self, validated_data):
|
2019-06-19 11:25:21 +00:00
|
|
|
|
protocols_data = validated_data.pop("protocols", [])
|
2019-06-13 10:58:43 +00:00
|
|
|
|
|
|
|
|
|
# 兼容老的api
|
2019-07-05 10:07:10 +00:00
|
|
|
|
name = validated_data.get("protocol")
|
2019-06-13 10:58:43 +00:00
|
|
|
|
port = validated_data.get("port")
|
2019-07-05 10:07:10 +00:00
|
|
|
|
if not protocols_data and name and port:
|
|
|
|
|
protocols_data.insert(0, '/'.join([name, str(port)]))
|
|
|
|
|
elif not name and not port and protocols_data:
|
|
|
|
|
protocol = protocols_data[0].split('/')
|
|
|
|
|
validated_data["protocol"] = protocol[0]
|
|
|
|
|
validated_data["port"] = int(protocol[1])
|
2019-07-17 04:10:14 +00:00
|
|
|
|
if protocols_data:
|
2019-07-05 10:07:10 +00:00
|
|
|
|
validated_data["protocols"] = ' '.join(protocols_data)
|
2019-06-13 10:58:43 +00:00
|
|
|
|
|
2020-10-30 02:16:49 +00:00
|
|
|
|
def perform_nodes_display_create(self, instance, nodes_display):
|
|
|
|
|
if not nodes_display:
|
|
|
|
|
return
|
|
|
|
|
nodes_to_set = []
|
|
|
|
|
for full_value in nodes_display:
|
|
|
|
|
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)
|
|
|
|
|
|
2019-07-05 10:07:10 +00:00
|
|
|
|
def create(self, validated_data):
|
|
|
|
|
self.compatible_with_old_protocol(validated_data)
|
2020-10-31 04:52:24 +00:00
|
|
|
|
nodes_display = validated_data.pop('nodes_display', '')
|
2019-06-13 10:58:43 +00:00
|
|
|
|
instance = super().create(validated_data)
|
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
|
|
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
2020-10-31 04:52:24 +00:00
|
|
|
|
nodes_display = validated_data.pop('nodes_display', '')
|
2019-07-05 10:07:10 +00:00
|
|
|
|
self.compatible_with_old_protocol(validated_data)
|
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
|
|
|
|
|
|
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
|
class PlatformSerializer(serializers.ModelSerializer):
|
2021-03-11 12:09:23 +00:00
|
|
|
|
meta = serializers.DictField(required=False, allow_null=True, label=_('Meta'))
|
2019-12-16 08:53:29 +00:00
|
|
|
|
|
2021-01-19 09:29:44 +00:00
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
# TODO 修复 drf SlugField RegexValidator bug,之后记得删除
|
|
|
|
|
validators = self.fields['name'].validators
|
|
|
|
|
if isinstance(validators[-1], RegexValidator):
|
|
|
|
|
validators.pop()
|
|
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
|
class Meta:
|
|
|
|
|
model = Platform
|
|
|
|
|
fields = [
|
|
|
|
|
'id', 'name', 'base', 'charset',
|
|
|
|
|
'internal', 'meta', 'comment'
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
2018-12-18 09:28:45 +00:00
|
|
|
|
class AssetSimpleSerializer(serializers.ModelSerializer):
|
2019-06-17 08:46:01 +00:00
|
|
|
|
|
2018-12-18 09:28:45 +00:00
|
|
|
|
class Meta:
|
|
|
|
|
model = Asset
|
2021-07-08 06:23:18 +00:00
|
|
|
|
fields = ['id', 'hostname', 'ip', 'port', 'connectivity', 'date_verified']
|
2020-03-12 08:24:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AssetTaskSerializer(serializers.Serializer):
|
|
|
|
|
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
|
|
|
|
|
)
|