Compare commits
4 Commits
v1.7.3
...
9cd50d1257
| Author | SHA1 | Date | |
|---|---|---|---|
| 9cd50d1257 | |||
| 646d61f72e | |||
| 5f7a98f21c | |||
| 19ed231a31 |
@@ -23,6 +23,7 @@ def setup_indexes(max_retries: int = 5, delay: float = 2.0):
|
||||
events_collection.create_index([("service", ASCENDING), ("timestamp", DESCENDING)])
|
||||
events_collection.create_index("id")
|
||||
saved_searches_collection.create_index([("created_by", ASCENDING), ("created_at", DESCENDING)])
|
||||
db["alert_rules"].create_index("name", unique=True)
|
||||
events_collection.create_index(
|
||||
[("actor_display", TEXT), ("raw_text", TEXT), ("operation", TEXT)],
|
||||
name="text_search_index",
|
||||
|
||||
@@ -12,6 +12,7 @@ from datetime import UTC, datetime, timedelta
|
||||
import structlog
|
||||
from config import ALERT_DEDUPE_MINUTES, ALERT_WEBHOOK_FORMAT, ALERT_WEBHOOK_URL
|
||||
from database import db
|
||||
from pymongo import ASCENDING
|
||||
|
||||
logger = structlog.get_logger("aoc.rules")
|
||||
rules_collection = db["alert_rules"]
|
||||
@@ -136,9 +137,15 @@ def _create_alert(rule: dict, event: dict):
|
||||
|
||||
|
||||
def seed_default_rules():
|
||||
"""Insert pre-built admin-ops rule templates if the collection is empty."""
|
||||
if rules_collection.count_documents({}) > 0:
|
||||
return
|
||||
"""Upsert pre-built admin-ops rule templates. Safe for concurrent startup."""
|
||||
# One-time cleanup: remove duplicates by name, keep the oldest (_id ascending)
|
||||
pipeline = [
|
||||
{"$sort": {"_id": ASCENDING}},
|
||||
{"$group": {"_id": "$name", "first_id": {"$first": "$_id"}}},
|
||||
]
|
||||
seen = {doc["_id"]: doc["first_id"] for doc in rules_collection.aggregate(pipeline)}
|
||||
for name, keep_id in seen.items():
|
||||
rules_collection.delete_many({"name": name, "_id": {"$ne": keep_id}})
|
||||
|
||||
defaults = [
|
||||
{
|
||||
@@ -261,8 +268,17 @@ def seed_default_rules():
|
||||
},
|
||||
]
|
||||
|
||||
try:
|
||||
rules_collection.insert_many(defaults)
|
||||
logger.info("Default admin-ops rules seeded", count=len(defaults))
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to seed default rules", error=str(exc))
|
||||
inserted = 0
|
||||
for rule in defaults:
|
||||
try:
|
||||
result = rules_collection.replace_one(
|
||||
{"name": rule["name"]},
|
||||
rule,
|
||||
upsert=True,
|
||||
)
|
||||
if result.upserted_id:
|
||||
inserted += 1
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to seed rule", rule=rule["name"], error=str(exc))
|
||||
if inserted:
|
||||
logger.info("Default admin-ops rules seeded", inserted=inserted, total=len(defaults))
|
||||
|
||||
Reference in New Issue
Block a user