FixServiceDevies

This commit is contained in:
QuangMinh_123
2026-05-29 11:34:03 +07:00
parent edc4fc44c5
commit 48c5183c12
4 changed files with 84 additions and 27 deletions

View File

@@ -0,0 +1,57 @@
# pyrefly: ignore [missing-import]
from config.database import get_connection, release_connection
# ============================================
# REPOSITORY LAYER: Tương tác trực tiếp với bảng alert_config trong PostgreSQL
# ============================================
def insert_default_alert_config_db(device_id):
"""
Tạo cấu hình cảnh báo mặc định cho thiết bị mới.
Tham số mặc định trong DB/Đặc tả:
- is_enabled = True
- fail_threshold = 3 (lỗi 3 lần liên tiếp thì alert)
- cooldown_minutes = 30 (khoảng thời gian tối thiểu giữa 2 cảnh báo tránh spam)
- notify_web = True (thông báo hiển thị trên giao diện)
- notify_email = False (mặc định chưa bật gửi email)
"""
conn = get_connection()
cur = None
try:
cur = conn.cursor()
cur.execute("""
INSERT INTO alert_config (device_id, is_enabled, fail_threshold, cooldown_minutes, notify_web, notify_email)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id, device_id, is_enabled, fail_threshold, cooldown_minutes, notify_web, notify_email, created, modified
""", (
device_id,
True, # is_enabled
3, # fail_threshold
30, # cooldown_minutes
True, # notify_web
False # notify_email
))
row = cur.fetchone()
conn.commit()
if row:
return {
"id": str(row[0]),
"device_id": str(row[1]),
"is_enabled": row[2],
"fail_threshold": row[3],
"cooldown_minutes": row[4],
"notify_web": row[5],
"notify_email": row[6],
"created": row[7].isoformat() if row[7] else None,
"modified": row[8].isoformat() if row[8] else None
}
return None
except Exception:
conn.rollback()
raise
finally:
if cur:
cur.close()
release_connection(conn)

View File

@@ -0,0 +1,12 @@
# pyrefly: ignore [missing-import]
from modules.alert.repository import insert_default_alert_config_db
# ============================================
# SERVICE LAYER: Xử lý nghiệp vụ cho Module Alert
# ============================================
def create_default_alert_config_service(device_id):
"""
Tạo cấu hình cảnh báo mặc định cho thiết bị mới.
"""
return insert_default_alert_config_db(device_id)

View File

@@ -1,5 +1,4 @@
from config.database import get_connection, release_connection from config.database import get_connection, release_connection
from modules.monitor_config.repository import insert_default_monitor_config_db
def _row_to_dict(row): def _row_to_dict(row):
""" """
@@ -135,9 +134,7 @@ def find_device_by_ip(ip_address):
def insert_device(data): def insert_device(data):
""" """
Tạo mới một thiết bị và cấu hình mặc định (MonitorConfig & AlertConfig) Tạo mới một thiết bị mạng (chỉ ghi nhận vào bảng device).
trong cùng một database transaction.
Trả về: tuple (device_dict, monitor_config_dict)
""" """
conn = get_connection() conn = get_connection()
cur = None cur = None
@@ -165,23 +162,7 @@ def insert_device(data):
device_row = cur.fetchone() device_row = cur.fetchone()
device_id = device_row[0] device_id = device_row[0]
# 2. Thêm cấu hình giám sát mặc định (MonitorConfig) bằng repository chuyên biệt # 2. Lấy lại thiết bị kèm thông tin DeviceType đã JOIN để trả về đầy đủ dữ liệu
monitor_config = insert_default_monitor_config_db(device_id, cursor=cur)
# 3. Thêm cấu hình cảnh báo mặc định (AlertConfig) cho thiết bị vừa tạo
cur.execute("""
INSERT INTO alert_config (device_id, is_enabled, fail_threshold, cooldown_minutes, notify_web, notify_email)
VALUES (%s, %s, %s, %s, %s, %s)
""", (
device_id,
True, # is_enabled
3, # fail_threshold (số lần fail liên tiếp trước khi alert)
30, # cooldown_minutes (thời gian tránh spam alert)
True, # notify_web (hiển thị thông báo trên web)
False # notify_email (mặc định tắt gửi email)
))
# 4. Lấy lại thiết bị kèm thông tin DeviceType đã JOIN để trả về đầy đủ dữ liệu
cur.execute(""" cur.execute("""
SELECT SELECT
d.id, d.device_type_id, d.name, d.description, d.ip_address, d.port, d.id, d.device_type_id, d.name, d.description, d.ip_address, d.port,
@@ -193,10 +174,10 @@ def insert_device(data):
""", (device_id,)) """, (device_id,))
full_row = cur.fetchone() full_row = cur.fetchone()
# Commit toàn bộ transaction # Commit transaction
conn.commit() conn.commit()
return _row_to_dict(full_row), monitor_config return _row_to_dict(full_row)
except Exception: except Exception:
conn.rollback() conn.rollback()

View File

@@ -19,6 +19,8 @@ from scheduler.scheduler import (
remove_device_monitoring_job, remove_device_monitoring_job,
reschedule_device_monitoring_job reschedule_device_monitoring_job
) )
from modules.monitor_config.service import create_default_monitor_config_service
from modules.alert.service import create_default_alert_config_service
def get_devices_service(): def get_devices_service():
@@ -62,11 +64,16 @@ def create_device_service(data):
if existing_ip: if existing_ip:
raise DeviceIPAlreadyExistsException(data["ip_address"]) raise DeviceIPAlreadyExistsException(data["ip_address"])
# 4. Insert DB (trả về thiết bị và cấu hình giám sát mặc định vừa tạo) # 4. Insert DB (Chỉ lưu vào bảng device)
new_device, monitor_config = insert_device(data) new_device = insert_device(data)
# 5. Kích hoạt Job giám sát trên Background Scheduler # 5. Tạo cấu hình giám sát mặc định (thuộc module monitor_config)
# Truyền kèm cấu hình giám sát mặc định thay vì None để Scheduler lập lịch monitor_config = create_default_monitor_config_service(new_device["id"])
# 6. Tạo cấu hình cảnh báo mặc định (thuộc module alert)
create_default_alert_config_service(new_device["id"])
# 7. Kích hoạt Job giám sát trên Background Scheduler
add_device_monitoring_job(new_device["id"], monitor_config) add_device_monitoring_job(new_device["id"], monitor_config)
return new_device return new_device