2018-02-06 10:32:02 +00:00
|
|
|
|
# ~*~ coding: utf-8 ~*~
|
2020-08-16 15:08:58 +00:00
|
|
|
|
from functools import partial
|
|
|
|
|
from collections import namedtuple, defaultdict
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
2019-10-18 07:05:45 +00:00
|
|
|
|
from rest_framework import status
|
2018-05-11 03:27:48 +00:00
|
|
|
|
from rest_framework.serializers import ValidationError
|
2018-02-06 10:32:02 +00:00
|
|
|
|
from rest_framework.response import Response
|
2020-12-10 09:12:39 +00:00
|
|
|
|
from rest_framework.decorators import action
|
2018-02-06 10:32:02 +00:00
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2020-03-12 08:24:38 +00:00
|
|
|
|
from django.shortcuts import get_object_or_404, Http404
|
2020-08-16 15:08:58 +00:00
|
|
|
|
from django.db.models.signals import m2m_changed
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
2020-12-10 09:12:39 +00:00
|
|
|
|
from common.const.http import POST
|
2020-08-16 15:08:58 +00:00
|
|
|
|
from common.exceptions import SomeoneIsDoingThis
|
|
|
|
|
from common.const.signals import PRE_REMOVE, POST_REMOVE
|
|
|
|
|
from assets.models import Asset
|
2018-03-01 04:40:41 +00:00
|
|
|
|
from common.utils import get_logger, get_object_or_none
|
2018-12-17 10:20:44 +00:00
|
|
|
|
from common.tree import TreeNodeSerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
|
from orgs.mixins.api import OrgModelViewSet
|
2019-10-18 07:05:45 +00:00
|
|
|
|
from orgs.mixins import generics
|
2020-12-10 09:47:35 +00:00
|
|
|
|
from orgs.utils import current_org
|
2018-07-23 04:55:13 +00:00
|
|
|
|
from ..hands import IsOrgAdmin
|
2018-12-17 10:20:44 +00:00
|
|
|
|
from ..models import Node
|
2019-10-18 07:05:45 +00:00
|
|
|
|
from ..tasks import (
|
2020-03-12 08:24:38 +00:00
|
|
|
|
update_node_assets_hardware_info_manual,
|
|
|
|
|
test_node_assets_connectivity_manual,
|
2021-02-08 06:59:20 +00:00
|
|
|
|
check_node_assets_amount_task
|
2019-10-18 07:05:45 +00:00
|
|
|
|
)
|
2018-02-06 10:32:02 +00:00
|
|
|
|
from .. import serializers
|
2020-08-16 15:08:58 +00:00
|
|
|
|
from .mixin import SerializeToTreeNodeMixin
|
2021-04-06 11:37:45 +00:00
|
|
|
|
from assets.locks import NodeAddChildrenLock
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
logger = get_logger(__file__)
|
2018-02-07 05:39:45 +00:00
|
|
|
|
__all__ = [
|
2018-07-16 06:47:06 +00:00
|
|
|
|
'NodeViewSet', 'NodeChildrenApi', 'NodeAssetsApi',
|
2020-08-16 15:08:58 +00:00
|
|
|
|
'NodeAddAssetsApi', 'NodeRemoveAssetsApi', 'MoveAssetsToNodeApi',
|
2020-03-12 08:24:38 +00:00
|
|
|
|
'NodeAddChildrenApi', 'NodeListAsTreeApi',
|
|
|
|
|
'NodeChildrenAsTreeApi',
|
|
|
|
|
'NodeTaskCreateApi',
|
2018-02-07 05:39:45 +00:00
|
|
|
|
]
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
class NodeViewSet(OrgModelViewSet):
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Node
|
2021-01-07 02:53:10 +00:00
|
|
|
|
filterset_fields = ('value', 'key', 'id')
|
2019-08-21 12:27:21 +00:00
|
|
|
|
search_fields = ('value', )
|
2018-07-23 04:55:13 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
2018-05-29 03:50:09 +00:00
|
|
|
|
serializer_class = serializers.NodeSerializer
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
# 仅支持根节点指直接创建,子节点下的节点需要通过children接口创建
|
2019-01-22 04:44:01 +00:00
|
|
|
|
def perform_create(self, serializer):
|
2019-08-23 10:23:07 +00:00
|
|
|
|
child_key = Node.org_root().get_next_child_key()
|
2019-01-22 04:44:01 +00:00
|
|
|
|
serializer.validated_data["key"] = child_key
|
|
|
|
|
serializer.save()
|
|
|
|
|
|
2021-02-08 06:59:20 +00:00
|
|
|
|
@action(methods=[POST], detail=False, url_path='check_assets_amount_task')
|
|
|
|
|
def check_assets_amount_task(self, request):
|
|
|
|
|
task = check_node_assets_amount_task.delay(current_org.id)
|
|
|
|
|
return Response(data={'task': task.id})
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
def perform_update(self, serializer):
|
2019-01-22 04:44:01 +00:00
|
|
|
|
node = self.get_object()
|
2019-08-23 10:23:07 +00:00
|
|
|
|
if node.is_org_root() and node.value != serializer.validated_data['value']:
|
2019-08-21 12:27:21 +00:00
|
|
|
|
msg = _("You can't update the root node name")
|
|
|
|
|
raise ValidationError({"error": msg})
|
|
|
|
|
return super().perform_update(serializer)
|
2019-01-22 04:44:01 +00:00
|
|
|
|
|
2019-10-10 08:18:29 +00:00
|
|
|
|
def destroy(self, request, *args, **kwargs):
|
|
|
|
|
node = self.get_object()
|
2020-11-27 09:29:00 +00:00
|
|
|
|
if node.is_org_root():
|
|
|
|
|
error = _("You can't delete the root node ({})".format(node.value))
|
|
|
|
|
return Response(data={'error': error}, status=status.HTTP_403_FORBIDDEN)
|
2021-04-29 03:30:01 +00:00
|
|
|
|
if node.has_offspring_assets():
|
|
|
|
|
error = _("Deletion failed and the node contains assets")
|
2020-03-12 08:24:38 +00:00
|
|
|
|
return Response(data={'error': error}, status=status.HTTP_403_FORBIDDEN)
|
2019-10-10 08:18:29 +00:00
|
|
|
|
return super().destroy(request, *args, **kwargs)
|
|
|
|
|
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
2018-12-17 10:20:44 +00:00
|
|
|
|
class NodeListAsTreeApi(generics.ListAPIView):
|
|
|
|
|
"""
|
|
|
|
|
获取节点列表树
|
|
|
|
|
[
|
|
|
|
|
{
|
|
|
|
|
"id": "",
|
|
|
|
|
"name": "",
|
|
|
|
|
"pId": "",
|
|
|
|
|
"meta": ""
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
"""
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Node
|
2018-12-17 10:20:44 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
|
|
|
|
serializer_class = TreeNodeSerializer
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def to_tree_queryset(queryset):
|
|
|
|
|
queryset = [node.as_tree_node() for node in queryset]
|
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
|
|
def filter_queryset(self, queryset):
|
|
|
|
|
queryset = super().filter_queryset(queryset)
|
|
|
|
|
queryset = self.to_tree_queryset(queryset)
|
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class NodeChildrenApi(generics.ListCreateAPIView):
|
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
|
|
|
|
serializer_class = serializers.NodeSerializer
|
|
|
|
|
instance = None
|
2019-08-23 10:23:07 +00:00
|
|
|
|
is_initial = False
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
|
|
def initial(self, request, *args, **kwargs):
|
|
|
|
|
self.instance = self.get_object()
|
|
|
|
|
return super().initial(request, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
2021-04-06 11:37:45 +00:00
|
|
|
|
with NodeAddChildrenLock(self.instance):
|
|
|
|
|
data = serializer.validated_data
|
|
|
|
|
_id = data.get("id")
|
|
|
|
|
value = data.get("value")
|
|
|
|
|
if not value:
|
|
|
|
|
value = self.instance.get_next_child_preset_name()
|
|
|
|
|
node = self.instance.create_child(value=value, _id=_id)
|
|
|
|
|
# 避免查询 full value
|
|
|
|
|
node._full_value = node.value
|
|
|
|
|
serializer.instance = node
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
|
|
def get_object(self):
|
|
|
|
|
pk = self.kwargs.get('pk') or self.request.query_params.get('id')
|
|
|
|
|
key = self.request.query_params.get("key")
|
2021-03-02 06:57:48 +00:00
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
if not pk and not key:
|
2019-08-23 10:23:07 +00:00
|
|
|
|
self.is_initial = True
|
2021-03-02 06:57:48 +00:00
|
|
|
|
if current_org.is_root():
|
|
|
|
|
node = None
|
|
|
|
|
else:
|
|
|
|
|
node = Node.org_root()
|
2019-08-21 12:27:21 +00:00
|
|
|
|
return node
|
|
|
|
|
if pk:
|
|
|
|
|
node = get_object_or_404(Node, pk=pk)
|
|
|
|
|
else:
|
|
|
|
|
node = get_object_or_404(Node, key=key)
|
|
|
|
|
return node
|
|
|
|
|
|
2021-03-02 06:57:48 +00:00
|
|
|
|
def get_org_root_queryset(self, query_all):
|
|
|
|
|
if query_all:
|
|
|
|
|
return Node.objects.all()
|
|
|
|
|
else:
|
|
|
|
|
return Node.org_root_nodes()
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
def get_queryset(self):
|
|
|
|
|
query_all = self.request.query_params.get("all", "0") == "all"
|
2021-03-02 06:57:48 +00:00
|
|
|
|
|
|
|
|
|
if self.is_initial and current_org.is_root():
|
|
|
|
|
return self.get_org_root_queryset(query_all)
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
2019-08-23 10:23:07 +00:00
|
|
|
|
if self.is_initial:
|
2019-08-21 12:27:21 +00:00
|
|
|
|
with_self = True
|
|
|
|
|
else:
|
|
|
|
|
with_self = False
|
|
|
|
|
|
2021-03-02 06:57:48 +00:00
|
|
|
|
if not self.instance:
|
|
|
|
|
return Node.objects.none()
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
if query_all:
|
|
|
|
|
queryset = self.instance.get_all_children(with_self=with_self)
|
|
|
|
|
else:
|
|
|
|
|
queryset = self.instance.get_children(with_self=with_self)
|
2018-12-17 10:20:44 +00:00
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
|
|
|
2020-08-16 15:08:58 +00:00
|
|
|
|
class NodeChildrenAsTreeApi(SerializeToTreeNodeMixin, NodeChildrenApi):
|
2018-12-17 10:20:44 +00:00
|
|
|
|
"""
|
|
|
|
|
节点子节点作为树返回,
|
|
|
|
|
[
|
|
|
|
|
{
|
|
|
|
|
"id": "",
|
|
|
|
|
"name": "",
|
|
|
|
|
"pId": "",
|
|
|
|
|
"meta": ""
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
"""
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Node
|
2018-12-17 10:20:44 +00:00
|
|
|
|
|
2020-08-16 15:08:58 +00:00
|
|
|
|
def list(self, request, *args, **kwargs):
|
|
|
|
|
nodes = self.get_queryset().order_by('value')
|
|
|
|
|
nodes = self.serialize_nodes(nodes, with_asset_amount=True)
|
|
|
|
|
assets = self.get_assets()
|
|
|
|
|
data = [*nodes, *assets]
|
|
|
|
|
return Response(data=data)
|
2018-12-17 10:20:44 +00:00
|
|
|
|
|
2020-08-16 15:08:58 +00:00
|
|
|
|
def get_assets(self):
|
2018-12-17 10:20:44 +00:00
|
|
|
|
include_assets = self.request.query_params.get('assets', '0') == '1'
|
2021-03-02 06:57:48 +00:00
|
|
|
|
if not self.instance or not include_assets:
|
2020-08-16 15:08:58 +00:00
|
|
|
|
return []
|
2019-08-21 12:27:21 +00:00
|
|
|
|
assets = self.instance.get_assets().only(
|
2021-02-05 05:29:29 +00:00
|
|
|
|
"id", "hostname", "ip", "os", "platform_id",
|
|
|
|
|
"org_id", "protocols", "is_active",
|
|
|
|
|
).prefetch_related('platform')
|
2020-08-16 15:08:58 +00:00
|
|
|
|
return self.serialize_assets(assets, self.instance.key)
|
2018-08-10 08:11:40 +00:00
|
|
|
|
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
2018-04-10 12:29:06 +00:00
|
|
|
|
class NodeAssetsApi(generics.ListAPIView):
|
2018-07-23 04:55:13 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
2018-04-10 12:29:06 +00:00
|
|
|
|
serializer_class = serializers.AssetSerializer
|
|
|
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
|
node_id = self.kwargs.get('pk')
|
|
|
|
|
query_all = self.request.query_params.get('all')
|
|
|
|
|
instance = get_object_or_404(Node, pk=node_id)
|
|
|
|
|
if query_all:
|
|
|
|
|
return instance.get_all_assets()
|
2018-02-06 10:32:02 +00:00
|
|
|
|
else:
|
2018-04-10 12:29:06 +00:00
|
|
|
|
return instance.get_assets()
|
2018-02-06 10:32:02 +00:00
|
|
|
|
|
2018-02-07 05:39:45 +00:00
|
|
|
|
|
2018-03-01 04:40:41 +00:00
|
|
|
|
class NodeAddChildrenApi(generics.UpdateAPIView):
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Node
|
2018-07-23 04:55:13 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
2018-03-01 04:40:41 +00:00
|
|
|
|
serializer_class = serializers.NodeAddChildrenSerializer
|
|
|
|
|
instance = None
|
|
|
|
|
|
2021-04-01 02:36:18 +00:00
|
|
|
|
def update(self, request, *args, **kwargs):
|
|
|
|
|
""" 同时支持 put 和 patch 方法"""
|
2018-03-01 04:40:41 +00:00
|
|
|
|
instance = self.get_object()
|
2021-03-08 02:08:51 +00:00
|
|
|
|
node_ids = request.data.get("nodes")
|
|
|
|
|
children = Node.objects.filter(id__in=node_ids)
|
2018-03-01 04:40:41 +00:00
|
|
|
|
for node in children:
|
2018-05-29 11:19:35 +00:00
|
|
|
|
node.parent = instance
|
2018-03-01 04:40:41 +00:00
|
|
|
|
return Response("OK")
|
|
|
|
|
|
|
|
|
|
|
2018-02-07 05:39:45 +00:00
|
|
|
|
class NodeAddAssetsApi(generics.UpdateAPIView):
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Node
|
2018-02-07 05:39:45 +00:00
|
|
|
|
serializer_class = serializers.NodeAssetsSerializer
|
2018-07-23 04:55:13 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
2018-02-07 05:39:45 +00:00
|
|
|
|
instance = None
|
|
|
|
|
|
|
|
|
|
def perform_update(self, serializer):
|
|
|
|
|
assets = serializer.validated_data.get('assets')
|
|
|
|
|
instance = self.get_object()
|
|
|
|
|
instance.assets.add(*tuple(assets))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class NodeRemoveAssetsApi(generics.UpdateAPIView):
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Node
|
2018-02-07 05:39:45 +00:00
|
|
|
|
serializer_class = serializers.NodeAssetsSerializer
|
2018-07-23 04:55:13 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
2018-02-07 05:39:45 +00:00
|
|
|
|
instance = None
|
|
|
|
|
|
|
|
|
|
def perform_update(self, serializer):
|
|
|
|
|
assets = serializer.validated_data.get('assets')
|
2020-08-16 15:08:58 +00:00
|
|
|
|
node = self.get_object()
|
|
|
|
|
node.assets.remove(*assets)
|
2018-03-12 03:41:12 +00:00
|
|
|
|
|
2020-08-16 15:08:58 +00:00
|
|
|
|
# 把孤儿资产添加到 root 节点
|
2021-03-02 06:57:48 +00:00
|
|
|
|
orphan_assets = Asset.objects.filter(
|
|
|
|
|
id__in=[a.id for a in assets],
|
|
|
|
|
nodes__isnull=True
|
|
|
|
|
).distinct()
|
2020-08-16 15:08:58 +00:00
|
|
|
|
Node.org_root().assets.add(*orphan_assets)
|
2018-03-12 03:41:12 +00:00
|
|
|
|
|
2020-08-16 15:08:58 +00:00
|
|
|
|
|
|
|
|
|
class MoveAssetsToNodeApi(generics.UpdateAPIView):
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Node
|
2018-04-13 07:48:10 +00:00
|
|
|
|
serializer_class = serializers.NodeAssetsSerializer
|
2018-07-23 04:55:13 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
2018-04-13 07:48:10 +00:00
|
|
|
|
instance = None
|
|
|
|
|
|
|
|
|
|
def perform_update(self, serializer):
|
|
|
|
|
assets = serializer.validated_data.get('assets')
|
2020-08-16 15:08:58 +00:00
|
|
|
|
node = self.get_object()
|
|
|
|
|
self.remove_old_nodes(assets)
|
|
|
|
|
node.assets.add(*assets)
|
|
|
|
|
|
|
|
|
|
def remove_old_nodes(self, assets):
|
|
|
|
|
m2m_model = Asset.nodes.through
|
|
|
|
|
|
|
|
|
|
# 查询资产与节点关系表,查出要移动资产与节点的所有关系
|
|
|
|
|
relates = m2m_model.objects.filter(asset__in=assets).values_list('asset_id', 'node_id')
|
|
|
|
|
if relates:
|
|
|
|
|
# 对关系以资产进行分组,用来发 `reverse=False` 信号
|
|
|
|
|
asset_nodes_mapper = defaultdict(set)
|
|
|
|
|
for asset_id, node_id in relates:
|
|
|
|
|
asset_nodes_mapper[asset_id].add(node_id)
|
|
|
|
|
|
|
|
|
|
# 组建一个资产 id -> Asset 的 mapper
|
|
|
|
|
asset_mapper = {asset.id: asset for asset in assets}
|
|
|
|
|
|
|
|
|
|
# 创建删除关系信号发送函数
|
|
|
|
|
senders = []
|
|
|
|
|
for asset_id, node_id_set in asset_nodes_mapper.items():
|
|
|
|
|
senders.append(partial(m2m_changed.send, sender=m2m_model, instance=asset_mapper[asset_id],
|
|
|
|
|
reverse=False, model=Node, pk_set=node_id_set))
|
|
|
|
|
# 发送 pre 信号
|
|
|
|
|
[sender(action=PRE_REMOVE) for sender in senders]
|
|
|
|
|
num = len(relates)
|
|
|
|
|
asset_ids, node_ids = zip(*relates)
|
|
|
|
|
# 删除之前的关系
|
|
|
|
|
rows, _i = m2m_model.objects.filter(asset_id__in=asset_ids, node_id__in=node_ids).delete()
|
|
|
|
|
if rows != num:
|
|
|
|
|
raise SomeoneIsDoingThis
|
|
|
|
|
# 发送 post 信号
|
|
|
|
|
[sender(action=POST_REMOVE) for sender in senders]
|
2018-04-13 07:48:10 +00:00
|
|
|
|
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
class NodeTaskCreateApi(generics.CreateAPIView):
|
2018-03-12 03:41:12 +00:00
|
|
|
|
model = Node
|
2020-03-12 08:24:38 +00:00
|
|
|
|
serializer_class = serializers.NodeTaskSerializer
|
2019-10-18 07:05:45 +00:00
|
|
|
|
permission_classes = (IsOrgAdmin,)
|
2018-03-12 03:41:12 +00:00
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
def get_object(self):
|
|
|
|
|
node_id = self.kwargs.get('pk')
|
|
|
|
|
node = get_object_or_none(self.model, id=node_id)
|
|
|
|
|
return node
|
2018-12-26 05:54:42 +00:00
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def set_serializer_data(s, task):
|
|
|
|
|
data = getattr(s, '_data', {})
|
|
|
|
|
data["task"] = task.id
|
|
|
|
|
setattr(s, '_data', data)
|
2018-12-26 05:54:42 +00:00
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def refresh_nodes_cache():
|
|
|
|
|
Task = namedtuple('Task', ['id'])
|
|
|
|
|
task = Task(id="0")
|
|
|
|
|
return task
|
|
|
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
|
action = serializer.validated_data["action"]
|
|
|
|
|
node = self.get_object()
|
|
|
|
|
if action == "refresh_cache" and node is None:
|
|
|
|
|
task = self.refresh_nodes_cache()
|
|
|
|
|
self.set_serializer_data(serializer, task)
|
|
|
|
|
return
|
|
|
|
|
if node is None:
|
|
|
|
|
raise Http404()
|
|
|
|
|
if action == "refresh":
|
|
|
|
|
task = update_node_assets_hardware_info_manual.delay(node)
|
|
|
|
|
else:
|
|
|
|
|
task = test_node_assets_connectivity_manual.delay(node)
|
|
|
|
|
self.set_serializer_data(serializer, task)
|
2019-09-11 13:22:25 +00:00
|
|
|
|
|