You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
jumpserver/apps/assets/signals_handler.py

204 lines
7.1 KiB

# -*- coding: utf-8 -*-
#
from collections import defaultdict
from django.db.models.signals import (
post_save, m2m_changed, post_delete
)
from django.db.models.aggregates import Count
from django.dispatch import receiver
from common.utils import get_logger, timeit
from common.decorator import on_transaction_commit
from .models import Asset, SystemUser, Node, AuthBook
from .utils import TreeService
[Feature] 添加资产用户管理器 (#2489) * [Feature] 1. 资产用户管理器 * [Feature] 2. 资产用户管理器: 更新AuthBook * [Feature] 3. 资产用户管理器: 添加 AssetUser API * [Feature] 4. AssetUser Model: 添加方法 load_related_asset_auth * [Feature] 5. AdminUser: 更新管理用户获取认证信息时,先加载相关资产的认证 * [Feature] 6. SystemUser: 更新系统用户获取认证信息时,先加载相关资产的认证 * [Feature] 前端页面: 添加资产用户列表页面 * [Feature] 前端页面: 管理用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 前端页面: 系统用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 优化: 从管理用户和系统用户的backend中获取相关资产用户的逻辑 * [Update] Fix 1 * [Feature] 优化: SystemUserBackend之filter功能 * [Feature] 优化: AdminUserBackend之filter功能 * [Feature] 优化: AdminUserBackend和SystemUserBackend功能 * [Feature] 更新翻译: 资产用户管理器 * [Update] 更新资产用户列表页名称为: asset_asset_user_list.html * [Bugfix] 修改bug: SystemUserBackend 根据用户名过滤系统用户 * [Feature] 添加: 资产用户列表中可测试资产用户的连接性 * [Update] 修改: AdHoc model的run_as字段从SystemUser外键修改为username字符串 * [Feature] 添加: 获取系统用户认证信息(对应某个资产)API * [Update] 更新: API获取asset user时进行排序 * [Bugfix] 修改: 资产用户可连接性CACHE_KEY * [Update] 更新翻译信息 * [Update] 修改获取资产用户认证信息API的返回响应(200/400) * [Update] 修改BaseUser获取特定资产的方法名 * [Update] 修改logger输出,AuthBook set_version_and_latest * [Update] 修改日志输出添加exc_info参数 * [Update] 移除AuthBook迁移文件0026 * [Bugfix] 修复AdminUserBackend获取instances为空的bug
6 years ago
from .tasks import (
update_assets_hardware_info_util,
test_asset_connectivity_util,
push_system_user_to_assets,
add_nodes_assets_to_system_users
[Feature] 添加资产用户管理器 (#2489) * [Feature] 1. 资产用户管理器 * [Feature] 2. 资产用户管理器: 更新AuthBook * [Feature] 3. 资产用户管理器: 添加 AssetUser API * [Feature] 4. AssetUser Model: 添加方法 load_related_asset_auth * [Feature] 5. AdminUser: 更新管理用户获取认证信息时,先加载相关资产的认证 * [Feature] 6. SystemUser: 更新系统用户获取认证信息时,先加载相关资产的认证 * [Feature] 前端页面: 添加资产用户列表页面 * [Feature] 前端页面: 管理用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 前端页面: 系统用户的资产管理页面添加按钮: 修改资产用户认证信息 * [Feature] 优化: 从管理用户和系统用户的backend中获取相关资产用户的逻辑 * [Update] Fix 1 * [Feature] 优化: SystemUserBackend之filter功能 * [Feature] 优化: AdminUserBackend之filter功能 * [Feature] 优化: AdminUserBackend和SystemUserBackend功能 * [Feature] 更新翻译: 资产用户管理器 * [Update] 更新资产用户列表页名称为: asset_asset_user_list.html * [Bugfix] 修改bug: SystemUserBackend 根据用户名过滤系统用户 * [Feature] 添加: 资产用户列表中可测试资产用户的连接性 * [Update] 修改: AdHoc model的run_as字段从SystemUser外键修改为username字符串 * [Feature] 添加: 获取系统用户认证信息(对应某个资产)API * [Update] 更新: API获取asset user时进行排序 * [Bugfix] 修改: 资产用户可连接性CACHE_KEY * [Update] 更新翻译信息 * [Update] 修改获取资产用户认证信息API的返回响应(200/400) * [Update] 修改BaseUser获取特定资产的方法名 * [Update] 修改logger输出,AuthBook set_version_and_latest * [Update] 修改日志输出添加exc_info参数 * [Update] 移除AuthBook迁移文件0026 * [Bugfix] 修复AdminUserBackend获取instances为空的bug
6 years ago
)
logger = get_logger(__file__)
def update_asset_hardware_info_on_created(asset):
logger.debug("Update asset `{}` hardware info".format(asset))
update_assets_hardware_info_util.delay([asset])
def test_asset_conn_on_created(asset):
logger.debug("Test asset `{}` connectivity".format(asset))
test_asset_connectivity_util.delay([asset])
@receiver(post_save, sender=Asset)
@on_transaction_commit
def on_asset_created_or_update(sender, instance=None, created=False, **kwargs):
"""
当资产创建时更新硬件信息更新可连接性
确保资产必须属于一个节点
"""
if created:
logger.info("Asset create signal recv: {}".format(instance))
# 获取资产硬件信息
update_asset_hardware_info_on_created(instance)
test_asset_conn_on_created(instance)
# 确保资产存在一个节点
has_node = instance.nodes.all().exists()
if not has_node:
instance.nodes.add(Node.org_root())
@receiver(post_delete, sender=Asset)
def on_asset_delete(sender, instance=None, **kwargs):
"""
当资产删除时刷新节点节点中存在节点和资产的关系
"""
logger.debug("Asset delete signal recv: {}".format(instance))
Node.refresh_assets()
@receiver(post_save, sender=SystemUser, dispatch_uid="jms")
def on_system_user_update(sender, instance=None, created=True, **kwargs):
"""
当系统用户更新时可能更新了秘钥用户名等这时要自动推送系统用户到资产上,
其实应该当 用户名密码秘钥 sudo等更新时再推送这里偷个懒,
这里直接取了 instance.assets 因为nodes和系统用户发生变化时会自动将nodes下的资产
关联到上面
"""
if instance and not created:
logger.info("System user update signal recv: {}".format(instance))
assets = instance.assets.all().valid()
push_system_user_to_assets.delay(instance, assets)
@receiver(m2m_changed, sender=SystemUser.assets.through)
def on_system_user_assets_change(sender, instance=None, action='', model=None, pk_set=None, **kwargs):
"""
当系统用户和资产关系发生变化时应该重新推送系统用户到新添加的资产中
"""
if action != "post_add":
return
logger.debug("System user assets change signal recv: {}".format(instance))
queryset = model.objects.filter(pk__in=pk_set)
if model == Asset:
system_users = [instance]
assets = queryset
else:
system_users = queryset
assets = [instance]
for system_user in system_users:
push_system_user_to_assets.delay(system_user, assets)
@receiver(m2m_changed, sender=SystemUser.nodes.through)
def on_system_user_nodes_change(sender, instance=None, action=None, model=None, pk_set=None, **kwargs):
"""
当系统用户和节点关系发生变化时应该将节点下资产关联到新的系统用户上
"""
if action != "post_add":
return
logger.info("System user nodes update signal recv: {}".format(instance))
queryset = model.objects.filter(pk__in=pk_set)
if model == Node:
nodes_keys = queryset.values_list('key', flat=True)
system_users = [instance]
else:
nodes_keys = [instance.key]
system_users = queryset
add_nodes_assets_to_system_users.delay(nodes_keys, system_users)
@receiver(m2m_changed, sender=Asset.nodes.through)
def on_asset_nodes_change(sender, instance=None, action='', **kwargs):
"""
资产节点发生变化时刷新节点
"""
if action.startswith('post'):
logger.debug("Asset nodes change signal recv: {}".format(instance))
Node.refresh_assets()
@receiver(m2m_changed, sender=Asset.nodes.through)
def on_asset_nodes_add(sender, instance=None, action='', model=None, pk_set=None, **kwargs):
"""
当资产的节点发生变化时或者 当节点的资产关系发生变化时
节点下新增的资产添加到节点关联的系统用户中
"""
if action != "post_add":
return
logger.debug("Assets node add signal recv: {}".format(action))
if model == Node:
nodes = model.objects.filter(pk__in=pk_set).values_list('key', flat=True)
assets = [instance.id]
else:
nodes = [instance.key]
assets = model.objects.filter(pk__in=pk_set).values_list('id', flat=True)
# 节点资产发生变化时,将资产关联到节点及祖先节点关联的系统用户, 只关注新增的
nodes_ancestors_keys = set()
node_tree = TreeService.new()
for node in nodes:
ancestors_keys = node_tree.ancestors_ids(nid=node)
nodes_ancestors_keys.update(ancestors_keys)
system_users = SystemUser.objects.filter(nodes__key__in=nodes_ancestors_keys)
system_users_assets = defaultdict(set)
for system_user in system_users:
system_users_assets[system_user].update(set(assets))
for system_user, _assets in system_users_assets.items():
system_user.assets.add(*tuple(_assets))
@receiver(m2m_changed, sender=Asset.nodes.through)
def on_asset_nodes_remove(sender, instance=None, action='', model=None,
pk_set=None, **kwargs):
"""
监控资产删除节点关系, 或节点删除资产避免产生游离资产
"""
if action not in ["post_remove", "pre_clear", "post_clear"]:
return
if action == "pre_clear":
if model == Node:
instance._nodes = list(instance.nodes.all())
else:
instance._assets = list(instance.assets.all())
return
logger.debug("Assets node remove signal recv: {}".format(action))
if action == "post_remove":
queryset = model.objects.filter(pk__in=pk_set)
else:
if model == Node:
queryset = instance._nodes
else:
queryset = instance._assets
if model == Node:
assets = [instance]
else:
assets = queryset
if isinstance(assets, list):
assets_not_has_node = []
for asset in assets:
if asset.nodes.all().count() == 0:
assets_not_has_node.append(asset.id)
else:
assets_not_has_node = assets.annotate(nodes_count=Count('nodes'))\
.filter(nodes_count=0).values_list('id', flat=True)
Node.org_root().assets.add(*tuple(assets_not_has_node))
@receiver([post_save, post_delete], sender=Node)
def on_node_update_or_created(sender, **kwargs):
# 刷新节点
Node.refresh_nodes()
@receiver(post_save, sender=AuthBook)
def on_authbook_created(sender, instance=None, created=True, **kwargs):
if created and instance:
instance.set_version()