mirror of
https://github.com/jumpserver/jumpserver.git
synced 2026-05-12 17:53:53 +00:00
* Bai reactor tree ( 重构获取完整资产树中节点下资产总数的逻辑) (#5548) * tree: v0.1 * tree: v0.2 * tree: v0.3 * tree: v0.4 * tree: 添加并发锁未请求到时的debug日志 * 以空间换时间的方式优化资产树 * Reactor tree togther v2 (#5576) * Bai reactor tree ( 重构获取完整资产树中节点下资产总数的逻辑) (#5548) * tree: v0.1 * tree: v0.2 * tree: v0.3 * tree: v0.4 * tree: 添加并发锁未请求到时的debug日志 * 以空间换时间的方式优化资产树 * 修改授权适配新方案 * 添加树处理工具 * 完成新的用户授权树计算以及修改一些信号 * 重构了获取资产的一些 api * 重构了一些节点的api * 整理了一些代码 * 完成了api 的重构 * 重构检查节点数量功能 * 完成重构授权树工具类 * api 添加强制刷新参数 * 整理一些信号 * 处理一些信号的问题 * 完成了信号的处理 * 重构了资产树相关的锁机制 * RebuildUserTreeTask 还得添加回来 * 优化下不能在root组织的检查函数 * 优化资产树变化时锁的使用 * 修改一些算法的小工具 * 资产树锁不再校验是否在具体组织里 * 整理了一些信号的位置 * 修复资产与节点关系维护的bug * 去掉一些调试代码 * 修复资产授权过期检查刷新授权树的 bug * 添加了可重入锁 * 添加一些计时,优化一些sql * 增加 union 查询的支持 * 尝试用 sql 解决节点资产数量问题 * 开始优化计算授权树节点资产数量不用冗余表 * 新代码能跑起来了,修复一下bug * 去掉 UserGrantedMappingNode 换成 UserAssetGrantedTreeNodeRelation * 修了些bug,做了些优化 * 优化QuerySetStage 执行逻辑 * 与小白的内存结合了 * 删掉老的表,迁移新的 assets_amount 字段 * 优化用户授权页面资产列表 count 慢 * 修复批量命令数量不对 * 修改获取非直接授权节点的 children 的逻辑 * 获取整棵树的节点 * 回退锁 * 整理迁移脚本 * 改变更新树策略 * perf: 修改一波缩进 * fix: 修改handler名称 * 修复授权树获取资产sql 泛滥 * 修复授权规则有效bug * 修复一些bug * 修复一些bug * 又修了一些小bug * 去掉了老的 get_nodes_all_assets * 修改一些写法 * Reactor tree togther b2 (#5570) * fix: 修改handler名称 * perf: 优化生成树 * perf: 去掉注释 * 优化了一些 * 重新生成迁移脚本 * 去掉周期检查节点资产数量的任务 * Pr@reactor tree togther guang@perf mapping (#5573) * fix: 修改handler名称 * perf: mapping 拆分出来 * 修改名称 * perf: 修改锁名 * perf: 去掉检查节点任务 * perf: 修改一下名称 * perf: 优化一波 Co-authored-by: Jiangjie.Bai <32935519+BaiJiangJie@users.noreply.github.com> Co-authored-by: Bai <bugatti_it@163.com> Co-authored-by: xinwen <coderWen@126.com> Co-authored-by: xinwen <coderWen@126.com> Co-authored-by: 老广 <ibuler@qq.com>
149 lines
4.7 KiB
Python
149 lines
4.7 KiB
Python
# ~*~ coding: utf-8 ~*~
|
|
|
|
import re
|
|
from collections import defaultdict
|
|
|
|
from celery import shared_task
|
|
from django.utils.translation import ugettext as _
|
|
from django.utils import timezone
|
|
|
|
from orgs.utils import tmp_to_org, org_aware_func
|
|
from common.utils import get_logger
|
|
from ..models import GatheredUser, Node
|
|
from .utils import clean_ansible_task_hosts
|
|
from . import const
|
|
|
|
__all__ = ['gather_asset_users', 'gather_nodes_asset_users']
|
|
logger = get_logger(__name__)
|
|
space = re.compile('\s+')
|
|
ignore_login_shell = re.compile(r'nologin$|sync$|shutdown$|halt$')
|
|
|
|
|
|
def parse_linux_result_to_users(result):
|
|
users = defaultdict(dict)
|
|
users_result = result.get('gather host users', {})\
|
|
.get('ansible_facts', {})\
|
|
.get('getent_passwd')
|
|
if not isinstance(users_result, dict):
|
|
users_result = {}
|
|
for username, attr in users_result.items():
|
|
if ignore_login_shell.search(attr[-1]):
|
|
continue
|
|
users[username] = {}
|
|
last_login_result = result.get('get last login', {}).get('stdout_lines', [])
|
|
for line in last_login_result:
|
|
data = line.split('@')
|
|
if len(data) != 3:
|
|
continue
|
|
username, ip, dt = data
|
|
dt += ' +0800'
|
|
date = timezone.datetime.strptime(dt, '%b %d %H:%M:%S %Y %z')
|
|
users[username] = {"ip": ip, "date": date}
|
|
return users
|
|
|
|
|
|
def parse_windows_result_to_users(result):
|
|
task_result = []
|
|
for task_name, raw in result.items():
|
|
res = raw.get('stdout_lines', {})
|
|
if res:
|
|
task_result = res
|
|
break
|
|
if not task_result:
|
|
return []
|
|
|
|
users = {}
|
|
|
|
for i in range(4):
|
|
task_result.pop(0)
|
|
for i in range(2):
|
|
task_result.pop()
|
|
|
|
for line in task_result:
|
|
user = space.split(line)
|
|
if user[0]:
|
|
users[user[0]] = {}
|
|
return users
|
|
|
|
|
|
def add_asset_users(assets, results):
|
|
assets_map = {a.hostname: a for a in assets}
|
|
parser_map = {
|
|
'linux': parse_linux_result_to_users,
|
|
'windows': parse_windows_result_to_users
|
|
}
|
|
|
|
assets_users_map = {}
|
|
|
|
for platform, platform_results in results.items():
|
|
for hostname, res in platform_results.items():
|
|
parse = parser_map.get(platform)
|
|
users = parse(res)
|
|
logger.debug('Gathered host users: {} {}'.format(hostname, users))
|
|
asset = assets_map.get(hostname)
|
|
if not asset:
|
|
continue
|
|
assets_users_map[asset] = users
|
|
|
|
for asset, users in assets_users_map.items():
|
|
with tmp_to_org(asset.org_id):
|
|
GatheredUser.objects.filter(asset=asset, present=True)\
|
|
.update(present=False)
|
|
for username, data in users.items():
|
|
defaults = {'asset': asset, 'username': username, 'present': True}
|
|
if data.get("ip"):
|
|
defaults["ip_last_login"] = data["ip"][:32]
|
|
if data.get("date"):
|
|
defaults["date_last_login"] = data["date"]
|
|
GatheredUser.objects.update_or_create(
|
|
defaults=defaults, asset=asset, username=username,
|
|
)
|
|
|
|
|
|
@shared_task(queue="ansible")
|
|
@org_aware_func("assets")
|
|
def gather_asset_users(assets, task_name=None):
|
|
from ops.utils import update_or_create_ansible_task
|
|
if task_name is None:
|
|
task_name = _("Gather assets users")
|
|
assets = clean_ansible_task_hosts(assets)
|
|
if not assets:
|
|
return
|
|
hosts_category = {
|
|
'linux': {
|
|
'hosts': [],
|
|
'tasks': const.GATHER_ASSET_USERS_TASKS
|
|
},
|
|
'windows': {
|
|
'hosts': [],
|
|
'tasks': const.GATHER_ASSET_USERS_TASKS_WINDOWS
|
|
}
|
|
}
|
|
for asset in assets:
|
|
hosts_list = hosts_category['windows']['hosts'] if asset.is_windows() \
|
|
else hosts_category['linux']['hosts']
|
|
hosts_list.append(asset)
|
|
|
|
results = {'linux': defaultdict(dict), 'windows': defaultdict(dict)}
|
|
for k, value in hosts_category.items():
|
|
if not value['hosts']:
|
|
continue
|
|
_task_name = '{}: {}'.format(task_name, k)
|
|
task, created = update_or_create_ansible_task(
|
|
task_name=_task_name, hosts=value['hosts'], tasks=value['tasks'],
|
|
pattern='all', options=const.TASK_OPTIONS,
|
|
run_as_admin=True,
|
|
)
|
|
raw, summary = task.run()
|
|
results[k].update(raw['ok'])
|
|
add_asset_users(assets, results)
|
|
|
|
|
|
@shared_task(queue="ansible")
|
|
def gather_nodes_asset_users(nodes_key):
|
|
nodes = Node.objects.filter(key__in=nodes_key)
|
|
assets = Node.get_nodes_all_assets(*nodes)
|
|
assets_groups_by_100 = [assets[i:i+100] for i in range(0, len(assets), 100)]
|
|
for _assets in assets_groups_by_100:
|
|
gather_asset_users(_assets)
|