jumpserver/apps/terminal/signal_handlers.py

86 lines
2.2 KiB
Python
Raw Normal View History

2017-12-29 18:29:29 +00:00
# -*- coding: utf-8 -*-
#
2022-11-01 10:40:42 +00:00
from django.db.models.signals import post_save, post_delete
from django.db.utils import ProgrammingError
2022-11-01 10:40:42 +00:00
from django.dispatch import receiver
2022-12-07 07:09:01 +00:00
from django.utils.functional import LazyObject
2022-12-07 07:09:01 +00:00
from assets.models import Asset
from common.signals import django_ready
from common.utils import get_logger
2022-12-07 07:09:01 +00:00
from common.utils.connection import RedisPubSub
2022-11-08 02:41:06 +00:00
from orgs.utils import tmp_to_builtin_org
2022-11-01 10:40:42 +00:00
from .models import Applet, AppletHost
2022-12-07 07:09:01 +00:00
from .utils import db_port_manager, DBPortManager
db_port_manager: DBPortManager
logger = get_logger(__file__)
2022-11-01 10:40:42 +00:00
@receiver(post_save, sender=AppletHost)
def on_applet_host_create(sender, instance, created=False, **kwargs):
2022-11-01 12:37:04 +00:00
if not created:
return
applets = Applet.objects.all()
instance.applets.set(applets)
2022-11-08 02:41:06 +00:00
with tmp_to_builtin_org(system=1):
instance.generate_accounts()
2022-11-01 10:40:42 +00:00
2022-12-07 07:09:01 +00:00
applet_host_change_pub_sub.publish(True)
2022-11-01 10:40:42 +00:00
@receiver(post_save, sender=Applet)
def on_applet_create(sender, instance, created=False, **kwargs):
2022-11-01 12:37:04 +00:00
if not created:
return
hosts = AppletHost.objects.all()
instance.hosts.set(hosts)
2022-12-05 07:03:21 +00:00
2022-12-07 07:09:01 +00:00
applet_host_change_pub_sub.publish(True)
2022-12-05 07:03:21 +00:00
@receiver(django_ready)
def init_db_port_mapper(sender, **kwargs):
logger.info('Init db port mapper')
try:
db_port_manager.init()
except (ProgrammingError,) as e:
pass
2022-12-05 07:03:21 +00:00
@receiver(post_save, sender=Asset)
def on_db_app_created(sender, instance: Asset, created, **kwargs):
if not instance.category != 'database':
return
if not created:
return
db_port_manager.add(instance)
2022-12-05 07:03:21 +00:00
@receiver(post_delete, sender=Asset)
def on_db_app_delete(sender, instance, **kwargs):
2022-12-05 07:03:21 +00:00
if not instance.category != 'database':
return
db_port_manager.pop(instance)
2022-12-07 07:09:01 +00:00
class AppletHostPubSub(LazyObject):
def _setup(self):
self._wrapped = RedisPubSub('fm.applet_host_change')
@receiver(django_ready)
def subscribe_applet_host_change(sender, **kwargs):
logger.debug("Start subscribe for expire node assets id mapping from memory")
def on_change(message):
from terminal.connect_methods import ConnectMethodUtil
ConnectMethodUtil.refresh_methods()
applet_host_change_pub_sub.subscribe(on_change)
applet_host_change_pub_sub = AppletHostPubSub()