Skip to content

Commit

Permalink
#43 DB情報更新時にSlack通知する機能の実装.
Browse files Browse the repository at this point in the history
  • Loading branch information
yoneyan committed Sep 15, 2024
1 parent 8f7986e commit a091b14
Show file tree
Hide file tree
Showing 15 changed files with 302 additions and 44 deletions.
55 changes: 38 additions & 17 deletions custom_auth/signals.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from django.db.models.signals import post_save, pre_delete, pre_save
from django.dispatch import receiver

from custom_auth.models import Group, User
from custom_auth.tool import SignalTool
from dsbd.notify import notify_db_save
from custom_auth.models import Group, User, UserGroup
from dsbd.notify import notify_delete_db, notify_insert_db, notify_update_db


@receiver(pre_save, sender=User)
Expand All @@ -17,26 +16,48 @@ def user_model_pre_save(sender, instance, **kwargs):
@receiver(post_save, sender=User)
def post_user(sender, instance, created, **kwargs):
if created:
text = SignalTool().get_create_user(True, instance)
notify_db_save(table_name="User", type=0, data=text)
else:
text = SignalTool().get_update_user(instance._pre_save_instance, instance)
notify_db_save(table_name="User", type=1, data=text)
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_insert_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=User)
def delete_user(sender, instance, **kwargs):
text = SignalTool().get_create_user(False, instance)
notify_db_save(table_name="User", type=2, data=text)
notify_delete_db(model_name=sender.__name__, instance=instance)


@receiver(post_save, sender=Group)
def update_group(sender, instance, created, **kwargs):
# 審査OKステータス変更時にサービス追加許可にする
if instance.is_pass and not instance.allow_service_add:
def post_group(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return

notify_update_db(model_name=sender.__name__, instance=instance)
# 審査NG => 審査OKの場合にサービス追加とJPNIC追加を出来るようにする
if not instance._pre_save_instance.is_pass and instance.is_pass:
instance.allow_service_add = True
instance.save(update_fields=["allow_service_add"])
# 審査NGステータス変更時にサービス追加拒否設定にする
if not instance.is_pass and instance.allow_service_add:
instance.allow_jpnic_add = True
instance.save(update_fields=["allow_service_add", "allow_jpnic_add"])
# Statusが1以外の場合はサービス追加とJPNIC追加を禁止する
if instance.status != 1:
instance.allow_service_add = False
instance.save(update_fields=["allow_service_add"])
instance.allow_jpnic_add = False
instance.save(update_fields=["allow_service_add", "allow_jpnic_add"])


@receiver(pre_delete, sender=Group)
def delete_group(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)


@receiver(post_save, sender=UserGroup)
def post_user_group(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_insert_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=UserGroup)
def delete_user_group(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)
77 changes: 66 additions & 11 deletions dsbd/notify.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,78 @@
from django.conf import settings
from slack_sdk import WebhookClient

from dsbd.utils import get_admin_history_url, get_admin_url

def notify_db_save(table_name="", type=0, data=""):
event_name = "create"
color = "good"
match type:
case 1:
event_name = "update"
case 2:
event_name = "delete"
color = "danger"

def notify_delete_db(model_name: str, instance):
admin_history_url = get_admin_history_url(instance)

message = f"レコードが削除されました:\n{instance}"
client = WebhookClient(settings.SLACK_WEBHOOK_LOG)
client.send(
attachments=[
{
"color": "danger",
"title": "[%s]" % f"{model_name}",
"text": f"{message}\n管理画面(履歴): {admin_history_url}",
}
],
)


def notify_insert_db(model_name: str, instance):
admin_url = get_admin_url(instance)
admin_history_url = get_admin_history_url(instance)

message = f"新しいレコードが登録されました:\n{instance}"
client = WebhookClient(settings.SLACK_WEBHOOK_LOG)
client.send(
text="[%s(%s)]" % (table_name, event_name),
attachments=[{"color": color, "title": "[%s(%s)]" % (table_name, event_name), "text": "%s" % (data,)}],
attachments=[
{
"color": "good",
"title": "[%s]" % f"{model_name}",
"text": f"{message}\n管理画面: {admin_url}\n管理画面(履歴): {admin_history_url}",
}
],
)


def notify_update_db(model_name: str, instance):
admin_url = get_admin_url(instance)
admin_history_url = get_admin_history_url(instance)

history = instance.history.all()
if history.count() < 2:
return # 履歴が2つ未満の場合は差分がないため、何もしない

latest = history.first() # 最新の履歴
previous = history[1] # 直前の履歴

changes = []

# フィールドごとの差分を確認
for field in instance._meta.fields:
field_name = field.name
old_value = getattr(previous, field_name, None)
new_value = getattr(latest, field_name, None)

if old_value != new_value:
changes.append(f"{field_name}: {old_value} -> {new_value}")

if changes:
message = f"モデル '{instance}' の以下のフィールドが変更されました:\n" + "\n".join(changes)
client = WebhookClient(settings.SLACK_WEBHOOK_LOG)
client.send(
attachments=[
{
"color": "good",
"title": "[%s]" % f"{model_name}",
"text": f"{message}\n管理画面: {admin_url}\n管理画面(履歴): {admin_history_url}",
}
],
)


def notice_payment(metadata_type="", event_type="", data=None):
client = WebhookClient(settings.SLACK_WEBHOOK_LOG)
client.send(
Expand Down
1 change: 1 addition & 0 deletions dsbd/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ def _import_ldap_group_type(group_type_name):
LOGIN_REDIRECT_URL = "/"

DOMAIN_URL = os.environ.get("DOMAIN_URL", "http://localhost:8000")
ADMIN_DOMAIN_URL = os.environ.get("ADMIN_DOMAIN_URL", "http://localhost:8001")

USER_LOGIN_VERIFY_EMAIL_EXPIRED_HOURS = os.environ.get("USER_LOGIN_VERIFY_EMAIL_EXPIRED_HOURS", 1)
USER_LOGIN_VERIFY_EMAIL_EXPIRED_MINUTES = os.environ.get("USER_LOGIN_VERIFY_EMAIL_EXPIRED_MINUTES", 10)
Expand Down
30 changes: 30 additions & 0 deletions dsbd/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from django.conf import settings
from django.urls import reverse


def get_admin_url(instance) -> str:
"""
任意のモデルインスタンスの管理ページURLを生成する。
"""
model_name = instance._meta.model_name
app_label = instance._meta.app_label
admin_url = reverse(f"admin:{app_label}_{model_name}_change", args=[instance.pk])

# フルURLにするために現在のサイトドメインを取得
full_admin_url = f"{settings.ADMIN_DOMAIN_URL}{admin_url}"

return full_admin_url


def get_admin_history_url(instance) -> str:
"""
任意のモデルインスタンスの管理ページURLを生成する。
"""
model_name = instance._meta.model_name
app_label = instance._meta.app_label
admin_url = reverse(f"admin:{app_label}_{model_name}_history", args=[instance.pk])

# フルURLにするために現在のサイトドメインを取得
admin_history_url = f"{settings.ADMIN_DOMAIN_URL}{admin_url}"

return admin_history_url
3 changes: 3 additions & 0 deletions ip/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class CustomAdmin(AppConfig):
name = "ip"
verbose_name = "IP"

def ready(self):
from . import signals # noqa
44 changes: 44 additions & 0 deletions ip/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver

from dsbd.notify import notify_delete_db, notify_insert_db, notify_update_db
from ip.models import IP, IPJPNICUser, JPNICUser


@receiver(post_save, sender=JPNICUser)
def post_jpnic_user(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=JPNICUser)
def delete_jpnic_user(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)


@receiver(post_save, sender=IP)
def post_ip(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=IP)
def delete_ip(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)


@receiver(post_save, sender=IPJPNICUser)
def post_ip_jpnic_user(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=IPJPNICUser)
def delete_ip_jpnic_user(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)
3 changes: 3 additions & 0 deletions noc/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class CustomAdmin(AppConfig):
name = "noc"
verbose_name = "NOC"

def ready(self):
from . import signals # noqa
18 changes: 18 additions & 0 deletions noc/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver

from dsbd.notify import notify_delete_db, notify_insert_db, notify_update_db
from noc.models import NOC


@receiver(post_save, sender=NOC)
def post_noc(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=NOC)
def delete_noc(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)
3 changes: 3 additions & 0 deletions notice/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class Notice(AppConfig):
name = "notice"
verbose_name = "通知"

def ready(self):
from . import signals # noqa
18 changes: 18 additions & 0 deletions notice/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver

from dsbd.notify import notify_delete_db, notify_insert_db, notify_update_db
from notice.models import Notice


@receiver(post_save, sender=Notice)
def post_notice(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=Notice)
def delete_notice(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)
3 changes: 3 additions & 0 deletions router/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class CustomAdmin(AppConfig):
name = "router"
verbose_name = "Router"

def ready(self):
from . import signals # noqa
31 changes: 31 additions & 0 deletions router/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver

from dsbd.notify import notify_delete_db, notify_insert_db, notify_update_db
from router.models import TunnelIP, TunnelRouter


@receiver(post_save, sender=TunnelRouter)
def post_tunnel_router(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=TunnelRouter)
def delete_tunnel_router(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)


@receiver(post_save, sender=TunnelIP)
def post_tunnel_ip(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=TunnelIP)
def delete_tunnel_ip(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)
3 changes: 3 additions & 0 deletions service/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class CustomAdmin(AppConfig):
name = "service"
verbose_name = "Service"

def ready(self):
from . import signals # noqa
31 changes: 31 additions & 0 deletions service/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver

from dsbd.notify import notify_delete_db, notify_insert_db, notify_update_db
from service.models import Connection, Service


@receiver(post_save, sender=Service)
def post_service(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=Service)
def delete_service(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)


@receiver(post_save, sender=Connection)
def post_connection(sender, instance, created, **kwargs):
if created:
notify_insert_db(model_name=sender.__name__, instance=instance)
return
notify_update_db(model_name=sender.__name__, instance=instance)


@receiver(pre_delete, sender=Connection)
def delete_connection(sender, instance, **kwargs):
notify_delete_db(model_name=sender.__name__, instance=instance)
Loading

0 comments on commit a091b14

Please sign in to comment.