diff --git a/apps/assets/forms/asset.py b/apps/assets/forms/asset.py index a6f488761..f8f187b4d 100644 --- a/apps/assets/forms/asset.py +++ b/apps/assets/forms/asset.py @@ -27,13 +27,16 @@ class AssetCreateForm(forms.ModelForm): 'class': 'select2', 'data-placeholder': _('Admin user') }), 'labels': forms.SelectMultiple(attrs={ - 'class': 'select2', 'data-placeholder': _('Labels') + 'class': 'select2', 'data-placeholder': _('Label') }), 'port': forms.TextInput(), 'domain': forms.Select(attrs={ 'class': 'select2', 'data-placeholder': _('Domain') }), } + labels = { + 'nodes': _("Node"), + } help_texts = { 'hostname': '* required', 'ip': '* required', @@ -57,19 +60,22 @@ class AssetUpdateForm(forms.ModelForm): ] widgets = { 'nodes': forms.SelectMultiple(attrs={ - 'class': 'select2', 'data-placeholder': _('Nodes') + 'class': 'select2', 'data-placeholder': _('Node') }), 'admin_user': forms.Select(attrs={ 'class': 'select2', 'data-placeholder': _('Admin user') }), 'labels': forms.SelectMultiple(attrs={ - 'class': 'select2', 'data-placeholder': _('Labels') + 'class': 'select2', 'data-placeholder': _('Label') }), 'port': forms.TextInput(), 'domain': forms.Select(attrs={ 'class': 'select2', 'data-placeholder': _('Domain') }), } + labels = { + 'nodes': _("Node"), + } help_texts = { 'hostname': '* required', 'ip': '* required', @@ -116,10 +122,10 @@ class AssetBulkUpdateForm(forms.ModelForm): ] widgets = { 'labels': forms.SelectMultiple( - attrs={'class': 'select2', 'data-placeholder': _('Select labels')} + attrs={'class': 'select2', 'data-placeholder': _('Label')} ), 'nodes': forms.SelectMultiple( - attrs={'class': 'select2', 'data-placeholder': _('Select nodes')} + attrs={'class': 'select2', 'data-placeholder': _('Node')} ), } diff --git a/apps/assets/models/user.py b/apps/assets/models/user.py index 541ef8b6a..2326f1c46 100644 --- a/apps/assets/models/user.py +++ b/apps/assets/models/user.py @@ -3,6 +3,7 @@ # import logging +import uuid from django.core.cache import cache from django.db import models @@ -100,10 +101,11 @@ class SystemUser(AssetUser): ) nodes = models.ManyToManyField('assets.Node', blank=True, verbose_name=_("Nodes")) + assets = models.ManyToManyField('assets.Asset', blank=True, verbose_name=_("Assets")) priority = models.IntegerField(default=10, verbose_name=_("Priority")) protocol = models.CharField(max_length=16, choices=PROTOCOL_CHOICES, default='ssh', verbose_name=_('Protocol')) auto_push = models.BooleanField(default=True, verbose_name=_('Auto push')) - sudo = models.TextField(default='/sbin/ifconfig', verbose_name=_('Sudo')) + sudo = models.TextField(default='/bin/whoami', verbose_name=_('Sudo')) shell = models.CharField(max_length=64, default='/bin/bash', verbose_name=_('Shell')) def __str__(self): @@ -119,9 +121,8 @@ class SystemUser(AssetUser): 'auto_push': self.auto_push, } - @property - def assets(self): - assets = set() + def get_assets(self): + assets = set(self.assets.all()) for node in self.nodes.all(): assets.update(set(node.get_all_assets())) return assets @@ -168,6 +169,3 @@ class SystemUser(AssetUser): except IntegrityError: print('Error continue') continue - - - diff --git a/apps/assets/serializers/system_user.py b/apps/assets/serializers/system_user.py index 1dff79422..7abd09d29 100644 --- a/apps/assets/serializers/system_user.py +++ b/apps/assets/serializers/system_user.py @@ -34,7 +34,7 @@ class SystemUserSerializer(serializers.ModelSerializer): @staticmethod def get_assets_amount(obj): - return len(obj.assets) + return len(obj.get_assets()) class SystemUserAuthSerializer(AuthSerializer): diff --git a/apps/assets/signals_handler.py b/apps/assets/signals_handler.py index b530067a7..06cd9f63e 100644 --- a/apps/assets/signals_handler.py +++ b/apps/assets/signals_handler.py @@ -1,14 +1,13 @@ # -*- coding: utf-8 -*- # - +from collections import defaultdict from django.db.models.signals import post_save, m2m_changed from django.dispatch import receiver from common.utils import get_logger from .models import Asset, SystemUser, Node from .tasks import update_assets_hardware_info_util, \ - test_asset_connectability_util, push_system_user_to_node, \ - push_node_system_users_to_asset + test_asset_connectability_util, push_system_user_to_assets logger = get_logger(__file__) @@ -31,7 +30,6 @@ def set_asset_root_node(asset): @receiver(post_save, sender=Asset, dispatch_uid="my_unique_identifier") def on_asset_created_or_update(sender, instance=None, created=False, **kwargs): - # set_asset_root_node(instance) if created: logger.info("Asset `{}` create signal received".format(instance)) update_asset_hardware_info_on_created(instance) @@ -41,25 +39,39 @@ def on_asset_created_or_update(sender, instance=None, created=False, **kwargs): @receiver(post_save, sender=SystemUser, dispatch_uid="my_unique_identifier") def on_system_user_update(sender, instance=None, created=True, **kwargs): if instance and not created: - for node in instance.nodes.all(): - push_system_user_to_node(instance, node) + logger.info("System user `{}` update signal received".format(instance)) + assets = instance.assets.all() + push_system_user_to_assets.delay(instance, assets) @receiver(m2m_changed, sender=SystemUser.nodes.through) -def on_system_user_node_change(sender, instance=None, **kwargs): +def on_system_user_nodes_change(sender, instance=None, **kwargs): if instance and kwargs["action"] == "post_add": - for pk in kwargs['pk_set']: - node = kwargs['model'].objects.get(pk=pk) - push_system_user_to_node(instance, node) + assets = set() + nodes = kwargs['model'].objects.filter(pk__in=kwargs['pk_set']) + for node in nodes: + assets.update(set(node.get_all_assets())) + instance.assets.add(*tuple(assets)) + + +@receiver(m2m_changed, sender=SystemUser.assets.through) +def on_system_user_assets_change(sender, instance=None, **kwargs): + if instance and kwargs["action"] == "post_add": + assets = kwargs['model'].objects.filter(pk__in=kwargs['pk_set']) + push_system_user_to_assets(instance, assets) @receiver(m2m_changed, sender=Asset.nodes.through) def on_asset_node_changed(sender, instance=None, **kwargs): if isinstance(instance, Asset) and kwargs['action'] == 'post_add': logger.debug("Asset node change signal received") - for pk in kwargs['pk_set']: - node = kwargs['model'].objects.get(pk=pk) - push_node_system_users_to_asset(node, [instance]) + nodes = kwargs['model'].objects.filter(pk__in=kwargs['pk_set']) + system_users_assets = defaultdict(set) + system_users = SystemUser.objects.filter(nodes__in=nodes) + for system_user in system_users: + system_users_assets[system_user].update({instance}) + for system_user, assets in system_users_assets.items(): + system_user.assets.add(*tuple(assets)) @receiver(m2m_changed, sender=Asset.nodes.through) @@ -67,5 +79,6 @@ def on_node_assets_changed(sender, instance=None, **kwargs): if isinstance(instance, Node) and kwargs['action'] == 'post_add': logger.debug("Node assets change signal received") assets = kwargs['model'].objects.filter(pk__in=kwargs['pk_set']) - push_node_system_users_to_asset(instance, assets) - + system_users = SystemUser.objects.filter(nodes=instance) + for system_user in system_users: + system_user.assets.add(*tuple(assets)) diff --git a/apps/assets/tasks.py b/apps/assets/tasks.py index 53a54764d..b51798e3d 100644 --- a/apps/assets/tasks.py +++ b/apps/assets/tasks.py @@ -386,52 +386,17 @@ def push_system_user_util(system_users, assets, task_name): return task.run() -def get_node_push_system_user_task_name(system_user, node): - - # return _("Push system user to node: {} => {}").format( - return _("推送系统用户到节点资产: {} => {}").format( - system_user.name, - node.value - ) - - -@shared_task -def push_system_user_to_node(system_user, node): - logger.info("Start push system user node: {} => {}".format(system_user.name, node.value)) - assets = node.get_all_assets() - task_name = get_node_push_system_user_task_name(system_user, node) - push_system_user_util([system_user], assets, task_name) - - -@shared_task -def push_system_user_related_nodes(system_user): - if not system_user.is_need_push(): - msg = "push system user `{}` passed, may be not auto push or ssh " \ - "protocol is not ssh".format(system_user.name) - logger.info(msg) - return - - nodes = system_user.nodes.all() - for node in nodes: - push_system_user_to_node(system_user, node) - - @shared_task def push_system_user_to_assets_manual(system_user): - push_system_user_related_nodes(system_user) + assets = system_user.get_assets() + task_name = "推送系统用户到入资产: {}".format(system_user.name) + return push_system_user_util([system_user], assets, task_name=task_name) -def push_node_system_users_to_asset(node, assets): - system_users = [] - nodes = node.ancestor_with_node - # 获取该节点所有父节点有的系统用户, 然后推送 - for n in nodes: - system_users.extend(list(n.systemuser_set.all())) - - if system_users: - # task_name = _("Push system users to node: {}").format(node.value) - task_name = _("推送节点系统用户到新加入资产中: {}").format(node.value) - push_system_user_util.delay(system_users, assets, task_name) +@shared_task +def push_system_user_to_assets(system_user, assets): + task_name = _("推送系统用户到入资产: {}").format(system_user.name) + return push_system_user_util.delay([system_user], assets, task_name) # @shared_task diff --git a/apps/assets/templates/assets/asset_create.html b/apps/assets/templates/assets/asset_create.html index 7f01e0530..eca0f6a03 100644 --- a/apps/assets/templates/assets/asset_create.html +++ b/apps/assets/templates/assets/asset_create.html @@ -34,7 +34,7 @@