Diff -- /var/www/vhosts/3dshawn.com/site1/_alert_dispatch.pl
Diff
/var/www/vhosts/3dshawn.com/site1/_alert_dispatch.pl
modified on local at 2026-07-12 00:19:42
Added
+142
lines
Removed
-0
lines
Context
409
unchanged
Blobs
from 50aef6cbce02
to 6bb32e8ab07d
to 6bb32e8ab07d
Unified diff
Naive LCS-based line diff. Additions in emerald, deletions in rose. Both sides decompressed live from BLOB_STORE.| 1 | 1 | #!/usr/bin/perl |
| 2 | 2 | #====================================================================== |
| 3 | 3 | # DriftSense -- alert dispatcher |
| 4 | 4 | # |
| 5 | 5 | # Cron entry point (NOT a CGI). Walks FILE_CHANGES + SCHEMA_CHANGE rows |
| 6 | 6 | # inserted since the last cursor tick, evaluates every ACTIVE rule |
| 7 | 7 | # against each new row, and POSTs matching payloads to the configured |
| 8 | 8 | # webhook (Slack / Discord / generic HTTP). Every attempt is logged |
| 9 | 9 | # to ALERT_DELIVERIES for the operator's audit trail. |
| 10 | 10 | # |
| 11 | 11 | # Config: /etc/drift_sense/drift_sense.conf (via MODS::Config). |
| 12 | 12 | # Log: /var/log/drift_sense/alert_dispatch.log (via cron redirect). |
| 13 | 13 | #====================================================================== |
| 14 | 14 | use strict; |
| 15 | 15 | use warnings; |
| 16 | 16 | use lib '/var/www/vhosts/3dshawn.com/site1'; |
| 17 | 17 | use POSIX (); |
| 18 | 18 | use JSON::PP; |
| 19 | 19 | use MODS::Config; |
| 20 | 20 | use MODS::DBConnect; |
| 21 | 21 | use MODS::Webhook; |
| 22 | 22 | |
| 23 | 23 | $| = 1; |
| 24 | 24 | my $ts = POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime); |
| 25 | 25 | |
| 26 | 26 | my $cfg = MODS::Config->new; |
| 27 | 27 | my $db = MODS::DBConnect->new; |
| 28 | 28 | my $dbh = $db->db_connect or die "[$ts] cannot connect to DriftSense storage DB\n"; |
| 29 | 29 | |
| 30 | 30 | my $public_url = $cfg->settings('public_url') || 'https://watchtower.3dshawn.com'; |
| 31 | 31 | |
| 32 | 32 | # ---- Fetch active rules --------------------------------------------- |
| 33 | 33 | my @rules = $db->db_readwrite_multiple($dbh, q~ |
| 34 | 34 | SELECT alert_rule_id, rule_name, match_kind, match_path_glob, |
| 35 | 35 | match_status_list, exclude_ts_only, |
| 36 | 36 | delivery_kind, delivery_url, delivery_email, |
| 37 | 37 | rate_limit_per_min, coalesce_window_s, |
| 38 | 38 | frequency_threshold, frequency_window_min, |
| 39 | 39 | UNIX_TIMESTAMP(last_frequency_fire_at) AS last_freq_fire_epoch |
| 40 | 40 | FROM ALERT_RULES |
| 41 | 41 | WHERE is_active = 1 |
| 42 | 42 | ~, __FILE__, __LINE__); |
| 43 | 43 | |
| 44 | 44 | unless (@rules) { |
| 45 | 45 | print "[$ts] no active alert rules, exiting\n"; |
| 46 | 46 | $db->db_disconnect($dbh); |
| 47 | 47 | exit 0; |
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | # ---- Fetch cursor --------------------------------------------------- |
| 51 | 51 | my %cursor; |
| 52 | 52 | foreach my $r ($db->db_readwrite_multiple($dbh, q~ |
| 53 | 53 | SELECT source_kind, last_seen_id FROM ALERT_CURSOR |
| 54 | 54 | ~, __FILE__, __LINE__)) { |
| 55 | 55 | $cursor{$r->{source_kind}} = $r->{last_seen_id}; |
| 56 | 56 | } |
| 57 | 57 | $cursor{file} //= 0; |
| 58 | 58 | $cursor{schema} //= 0; |
| 59 | 59 | |
| 60 | 60 | # ---- Pull new FILE_CHANGES since cursor ------------------------------ |
| 61 | 61 | my $file_max = $cursor{file}; |
| 62 | 62 | my @file_new = $db->db_readwrite_multiple($dbh, qq~ |
| 63 | 63 | SELECT fc.file_changes_id AS id, fc.file_name, fc.status, fc.blob_sha, |
| 64 | 64 | fc.is_ts_only, fc.date_time, |
| 65 | 65 | UNIX_TIMESTAMP(fc.date_time) AS ts_epoch, |
| 66 | 66 | s.server_name |
| 67 | 67 | FROM FILE_CHANGES fc |
| 68 | 68 | LEFT JOIN SERVERS s ON s.server_id = fc.server_id |
| 69 | 69 | WHERE fc.file_changes_id > $cursor{file} |
| 70 | 70 | ORDER BY fc.file_changes_id ASC |
| 71 | 71 | LIMIT 500 |
| 72 | 72 | ~, __FILE__, __LINE__); |
| 73 | 73 | foreach my $r (@file_new) { |
| 74 | 74 | $file_max = $r->{id} if $r->{id} > $file_max; |
| 75 | 75 | } |
| 76 | 76 | |
| 77 | 77 | # ---- Pull new SCHEMA_CHANGE since cursor ----------------------------- |
| 78 | 78 | my $schema_max = $cursor{schema}; |
| 79 | 79 | my @schema_new = $db->db_readwrite_multiple($dbh, qq~ |
| 80 | 80 | SELECT sc.schema_change_id AS id, sc.database_name, sc.table_name, |
| 81 | 81 | sc.changes, sc.is_ts_only, sc.change_datetime, |
| 82 | 82 | UNIX_TIMESTAMP(sc.change_datetime) AS ts_epoch, |
| 83 | 83 | s.server_name |
| 84 | 84 | FROM SCHEMA_CHANGE sc |
| 85 | 85 | LEFT JOIN SERVERS s ON s.server_id = sc.server_id |
| 86 | 86 | WHERE sc.schema_change_id > $cursor{schema} |
| 87 | 87 | ORDER BY sc.schema_change_id ASC |
| 88 | 88 | LIMIT 500 |
| 89 | 89 | ~, __FILE__, __LINE__); |
| 90 | 90 | foreach my $r (@schema_new) { |
| 91 | 91 | $schema_max = $r->{id} if $r->{id} > $schema_max; |
| 92 | 92 | } |
| 93 | 93 | |
| 94 | 94 | my $total_new = scalar(@file_new) + scalar(@schema_new); |
| 95 | 95 | if ($total_new == 0) { |
| 96 | 96 | print "[$ts] no new changes since cursor (file=$cursor{file} schema=$cursor{schema})\n"; |
| 97 | 97 | $db->db_disconnect($dbh); |
| 98 | 98 | exit 0; |
| 99 | 99 | } |
| 100 | 100 | |
| 101 | 101 | # ---- Evaluate + deliver --------------------------------------------- |
| 102 | 102 | # HTTP transport is MODS::Webhook (shells out to /usr/bin/curl) so we |
| 103 | 103 | # don't need LWP::Protocol::https / IO::Socket::SSL as CPAN installs. |
| 104 | 104 | |
| 105 | 105 | my $delivered = 0; |
| 106 | 106 | my $skipped = 0; |
| 107 | 107 | my $failed = 0; |
| 108 | 108 | |
| 109 | 109 | foreach my $row (@file_new) { _process_row($row, 'file'); } |
| 110 | 110 | foreach my $row (@schema_new) { _process_row($row, 'schema'); } |
| 111 | 111 | |
| 112 | 112 | # ---- Frequency-mode rules ------------------------------------------ |
| 113 | 113 | # For any rule where frequency_threshold > 0, we ignore the per-row loop |
| 114 | 114 | # above and instead: query how many file changes matching the rule's |
| 115 | 115 | # path glob happened in the last window_min minutes. If it crosses the |
| 116 | 116 | # threshold and we haven't fired within the same window, fire once with |
| 117 | 117 | # the top offender. |
| 118 | 118 | foreach my $rule (@rules) { |
| 119 | 119 | next unless ($rule->{frequency_threshold} || 0) > 0; |
| 120 | 120 | my $win = int($rule->{frequency_window_min} || 60); |
| 121 | 121 | my $thr = int($rule->{frequency_threshold}); |
| 122 | 122 | |
| 123 | 123 | # Re-fire cooldown: don't fire more than once per window |
| 124 | 124 | my $last = int($rule->{last_freq_fire_epoch} || 0); |
| 125 | 125 | if ($last && (time - $last) < $win * 60) { |
| 126 | 126 | next; |
| 127 | 127 | } |
| 128 | 128 | |
| 129 | 129 | # Find files whose match_path_glob-hit change count > threshold |
| 130 | 130 | my $glob = $rule->{match_path_glob} // ''; |
| 131 | 131 | my $glob_sql = ''; |
| 132 | 132 | if (length $glob) { |
| 133 | 133 | # Approx: SQL LIKE. Convert glob wildcards to SQL % / _. |
| 134 | 134 | my $like = $glob; |
| 135 | 135 | $like =~ s/\*\*/%/g; |
| 136 | 136 | $like =~ s/\*/%/g; |
| 137 | 137 | $like =~ s/\?/_/g; |
| 138 | 138 | my $q_like = $dbh->quote($like); |
| 139 | 139 | $glob_sql = " AND fc.file_name LIKE $q_like"; |
| 140 | 140 | } |
| 141 | 141 | my @hot = $db->db_readwrite_multiple($dbh, qq~ |
| 142 | 142 | SELECT fc.file_name, |
| 143 | 143 | COUNT(*) AS ct, |
| 144 | 144 | MAX(fc.file_changes_id) AS latest_id, |
| 145 | 145 | s.server_name |
| 146 | 146 | FROM FILE_CHANGES fc |
| 147 | 147 | LEFT JOIN SERVERS s ON s.server_id = fc.server_id |
| 148 | 148 | WHERE fc.date_time >= DATE_SUB(NOW(), INTERVAL $win MINUTE) |
| 149 | 149 | $glob_sql |
| 150 | 150 | GROUP BY fc.file_name |
| 151 | 151 | HAVING ct >= $thr |
| 152 | 152 | ORDER BY ct DESC |
| 153 | 153 | LIMIT 5 |
| 154 | 154 | ~, __FILE__, __LINE__); |
| 155 | 155 | next unless @hot; |
| 156 | 156 | |
| 157 | 157 | # Fire once with the top offender's info |
| 158 | 158 | my $top = $hot[0]; |
| 159 | 159 | my $fake_row = { |
| 160 | 160 | id => $top->{latest_id}, |
| 161 | 161 | file_name => $top->{file_name}, |
| 162 | 162 | server_name => $top->{server_name} // 'local', |
| 163 | 163 | date_time => POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime), |
| 164 | 164 | ts_epoch => time, |
| 165 | 165 | status => 'frequency_alert', |
| 166 | 166 | }; |
| 167 | 167 | my $payload = _build_payload($rule, $fake_row, 'file'); |
| 168 | 168 | # Enrich summary with count + threshold |
| 169 | 169 | my $extra = "frequency alert: $top->{file_name} changed $top->{ct} times in the last $win min (threshold: $thr)"; |
| 170 | 170 | if (ref($payload->{generic_webhook}) eq 'HASH') { |
| 171 | 171 | $payload->{generic_webhook}{frequency_summary} = $extra; |
| 172 | 172 | $payload->{generic_webhook}{frequency_count} = $top->{ct}; |
| 173 | 173 | $payload->{generic_webhook}{frequency_window} = $win; |
| 174 | 174 | $payload->{generic_webhook}{summary} = $extra; |
| 175 | 175 | } |
| 176 | 176 | my ($status, $http_code, $body, $err) = _deliver($rule, $payload); |
| 177 | 177 | _log_delivery($rule, $fake_row, 'file', $status, $http_code, $body, $err); |
| 178 | 178 | if ($status eq 'sent') { |
| 179 | 179 | $delivered++; |
| 180 | 180 | $db->db_readwrite($dbh, qq~ |
| 181 | 181 | UPDATE ALERT_RULES |
| 182 | 182 | SET fire_count = fire_count + 1, |
| 183 | 183 | last_fired_at = NOW(), |
| 184 | 184 | last_frequency_fire_at = NOW() |
| 185 | 185 | WHERE alert_rule_id = $rule->{alert_rule_id} |
| 186 | 186 | ~, __FILE__, __LINE__); |
| 187 | 187 | } else { |
| 188 | 188 | $failed++; |
| 189 | 189 | } |
| 190 | 190 | } |
| 191 | 191 | |
| 192 | 192 | # ---- Advance cursor atomically -------------------------------------- |
| 193 | 193 | if ($file_max > $cursor{file}) { |
| 194 | 194 | $db->db_readwrite($dbh, |
| 195 | 195 | "UPDATE ALERT_CURSOR SET last_seen_id = $file_max WHERE source_kind = 'file'", |
| 196 | 196 | __FILE__, __LINE__); |
| 197 | 197 | } |
| 198 | 198 | if ($schema_max > $cursor{schema}) { |
| 199 | 199 | $db->db_readwrite($dbh, |
| 200 | 200 | "UPDATE ALERT_CURSOR SET last_seen_id = $schema_max WHERE source_kind = 'schema'", |
| 201 | 201 | __FILE__, __LINE__); |
| 202 | } | |
| 203 | ||
| 204 | # ---- Pin-drift alerts (Feature 5 wave 4) --------------------------- | |
| 205 | # For each Named Release with alert_delivery_url set, check whether any | |
| 206 | # pin's current-latest SHA differs from the pinned SHA. Log the drift | |
| 207 | # to PIN_DRIFT_LOG (with notified=0) and, if not yet notified, POST an | |
| 208 | # alert to the release's delivery URL, then set notified=1. | |
| 209 | foreach my $rel ($db->db_readwrite_multiple($dbh, q~ | |
| 210 | SELECT named_release_id, name, alert_delivery_kind, alert_delivery_url | |
| 211 | FROM NAMED_RELEASES | |
| 212 | WHERE alert_delivery_kind IS NOT NULL | |
| 213 | AND alert_delivery_kind != 'none' | |
| 214 | AND alert_delivery_url IS NOT NULL | |
| 215 | AND alert_delivery_url != '' | |
| 216 | ~, __FILE__, __LINE__)) { | |
| 217 | ||
| 218 | my $rid = $rel->{named_release_id}; | |
| 219 | my @drifts; | |
| 220 | foreach my $pin ($db->db_readwrite_multiple($dbh, qq~ | |
| 221 | SELECT p.pin_id, p.file_name, p.blob_sha AS pinned_sha, | |
| 222 | fc.server_id | |
| 223 | FROM NAMED_RELEASE_PINS p | |
| 224 | LEFT JOIN FILE_CHANGES fc ON fc.file_changes_id = p.file_changes_id | |
| 225 | WHERE p.named_release_id = $rid | |
| 226 | ~, __FILE__, __LINE__)) { | |
| 227 | my $q_file = $dbh->quote($pin->{file_name}); | |
| 228 | my $sid = int($pin->{server_id} || 0); | |
| 229 | my $cur = $db->db_readwrite($dbh, qq~ | |
| 230 | SELECT blob_sha, file_changes_id FROM FILE_CHANGES | |
| 231 | WHERE server_id = $sid AND file_name = $q_file | |
| 232 | ORDER BY file_changes_id DESC LIMIT 1 | |
| 233 | ~, __FILE__, __LINE__); | |
| 234 | my $cur_sha = $cur ? $cur->{blob_sha} : ''; | |
| 235 | next unless $cur_sha && $cur_sha ne $pin->{pinned_sha}; | |
| 236 | ||
| 237 | # Have we already logged + notified this (pin, current_sha) tuple? | |
| 238 | my $q_pinned = $dbh->quote($pin->{pinned_sha}); | |
| 239 | my $q_current = $dbh->quote($cur_sha); | |
| 240 | my $seen = $db->db_readwrite($dbh, qq~ | |
| 241 | SELECT drift_id, notified FROM PIN_DRIFT_LOG | |
| 242 | WHERE pin_id = $pin->{pin_id} | |
| 243 | AND current_sha = $q_current | |
| 244 | ORDER BY drift_id DESC LIMIT 1 | |
| 245 | ~, __FILE__, __LINE__); | |
| 246 | if ($seen && $seen->{notified}) { | |
| 247 | next; # already notified for this exact drift state | |
| 248 | } | |
| 249 | ||
| 250 | # Log the drift | |
| 251 | my $q_fname = $dbh->quote($pin->{file_name}); | |
| 252 | my $cid = int($cur->{file_changes_id} || 0); | |
| 253 | $db->db_readwrite($dbh, qq~ | |
| 254 | INSERT INTO PIN_DRIFT_LOG | |
| 255 | (named_release_id, pin_id, file_name, pinned_sha, current_sha, file_changes_id, notified) | |
| 256 | VALUES | |
| 257 | ($rid, $pin->{pin_id}, $q_fname, $q_pinned, $q_current, $cid, 0) | |
| 258 | ~, __FILE__, __LINE__); | |
| 259 | push @drifts, { | |
| 260 | file_name => $pin->{file_name}, | |
| 261 | pinned_sha => $pin->{pinned_sha}, | |
| 262 | current_sha => $cur_sha, | |
| 263 | change_id => $cid, | |
| 264 | }; | |
| 265 | } | |
| 266 | ||
| 267 | next unless @drifts; | |
| 268 | ||
| 269 | # Build a summary payload | |
| 270 | my $summary = sprintf('Named release "%s" -- %d pinned file(s) have drifted', $rel->{name}, scalar @drifts); | |
| 271 | my $public_url = $cfg->settings('public_url') || 'https://watchtower.3dshawn.com'; | |
| 272 | my $files_list = join("\n", map { | |
| 273 | " * $_->{file_name} (pinned: " . substr($_->{pinned_sha}, 0, 12) . | |
| 274 | " -> current: " . substr($_->{current_sha}, 0, 12) . ")" | |
| 275 | } @drifts); | |
| 276 | my $link = "$public_url/restore_release.cgi?release_id=$rid"; | |
| 277 | ||
| 278 | my $slack_body = { | |
| 279 | text => "*DriftSense pin drift*: $summary", | |
| 280 | attachments => [{ | |
| 281 | color => '#f43f5e', | |
| 282 | fields => [ | |
| 283 | { title => 'Release', value => $rel->{name}, short => 1 }, | |
| 284 | { title => 'Drifted files', value => scalar(@drifts), short => 1 }, | |
| 285 | { title => 'Details', value => $files_list, short => 0 }, | |
| 286 | ], | |
| 287 | actions => [{ type => 'button', text => 'Restore all pinned', url => $link }], | |
| 288 | }], | |
| 289 | }; | |
| 290 | my $discord_body = { | |
| 291 | content => "**DriftSense pin drift**: $summary", | |
| 292 | embeds => [{ | |
| 293 | title => $rel->{name}, | |
| 294 | url => $link, | |
| 295 | color => 16005694, | |
| 296 | description => $files_list, | |
| 297 | }], | |
| 298 | }; | |
| 299 | my $generic_body = { | |
| 300 | source => 'drift_sense', | |
| 301 | alert_type => 'pin_drift', | |
| 302 | release_id => $rid, | |
| 303 | release_name => $rel->{name}, | |
| 304 | drifted_count=> scalar @drifts, | |
| 305 | summary => $summary, | |
| 306 | files => \@drifts, | |
| 307 | restore_url => $link, | |
| 308 | }; | |
| 309 | ||
| 310 | my $body_ref = $rel->{alert_delivery_kind} eq 'slack' ? $slack_body | |
| 311 | : $rel->{alert_delivery_kind} eq 'discord' ? $discord_body | |
| 312 | : $generic_body; | |
| 313 | ||
| 314 | my ($code, $rbody, $err) = MODS::Webhook::post_json( | |
| 315 | $rel->{alert_delivery_url}, $body_ref, | |
| 316 | timeout => 8, | |
| 317 | user_agent => 'DriftSense/1.0 (pin-drift)', | |
| 318 | ); | |
| 319 | ||
| 320 | if (!$err && $code >= 200 && $code < 400) { | |
| 321 | # Mark all just-logged rows as notified | |
| 322 | foreach my $d (@drifts) { | |
| 323 | my $q_current = $dbh->quote($d->{current_sha}); | |
| 324 | $db->db_readwrite($dbh, qq~ | |
| 325 | UPDATE PIN_DRIFT_LOG SET notified = 1 | |
| 326 | WHERE named_release_id = $rid | |
| 327 | AND file_name = @{[ $dbh->quote($d->{file_name}) ]} | |
| 328 | AND current_sha = $q_current | |
| 329 | AND notified = 0 | |
| 330 | ~, __FILE__, __LINE__); | |
| 331 | } | |
| 332 | $delivered++; | |
| 333 | print "[$ts] pin-drift alert delivered for release '$rel->{name}' (" . scalar(@drifts) . " drifted)\n"; | |
| 334 | } else { | |
| 335 | $failed++; | |
| 336 | print "[$ts] pin-drift alert FAILED for release '$rel->{name}': " . ($err // "HTTP $code") . "\n"; | |
| 337 | } | |
| 338 | ||
| 339 | # Bookkeep the check timestamp | |
| 340 | $db->db_readwrite($dbh, qq~ | |
| 341 | UPDATE NAMED_RELEASES SET last_pin_drift_check_at = NOW() | |
| 342 | WHERE named_release_id = $rid | |
| 343 | ~, __FILE__, __LINE__); | |
| 202 | 344 | } |
| 203 | 345 | |
| 204 | 346 | $db->db_disconnect($dbh); |
| 205 | 347 | print "[$ts] processed +$total_new new changes: $delivered delivered, $skipped skipped, $failed failed\n"; |
| 206 | 348 | exit 0; |
| 207 | 349 | |
| 208 | 350 | #--------------------------------------------------------------------- |
| 209 | 351 | sub _process_row { |
| 210 | 352 | my ($row, $kind) = @_; |
| 211 | 353 | foreach my $rule (@rules) { |
| 212 | 354 | next unless _rule_matches($rule, $row, $kind); |
| 213 | 355 | |
| 214 | 356 | # Rate limit check |
| 215 | 357 | if ($rule->{rate_limit_per_min} > 0) { |
| 216 | 358 | my $rlq = $db->db_readwrite($dbh, qq~ |
| 217 | 359 | SELECT COUNT(*) AS n FROM ALERT_DELIVERIES |
| 218 | 360 | WHERE alert_rule_id = $rule->{alert_rule_id} |
| 219 | 361 | AND fired_at >= DATE_SUB(NOW(), INTERVAL 1 MINUTE) |
| 220 | 362 | AND delivery_status IN ('sent','pending') |
| 221 | 363 | ~, __FILE__, __LINE__); |
| 222 | 364 | if ($rlq && $rlq->{n} >= $rule->{rate_limit_per_min}) { |
| 223 | 365 | _log_delivery($rule, $row, $kind, 'skipped', undef, undef, |
| 224 | 366 | "rate limit ($rule->{rate_limit_per_min}/min) reached"); |
| 225 | 367 | $skipped++; |
| 226 | 368 | next; |
| 227 | 369 | } |
| 228 | 370 | } |
| 229 | 371 | |
| 230 | 372 | # Build payload + POST |
| 231 | 373 | my $payload = _build_payload($rule, $row, $kind); |
| 232 | 374 | my ($status, $http_code, $body, $err) = _deliver($rule, $payload); |
| 233 | 375 | _log_delivery($rule, $row, $kind, $status, $http_code, $body, $err); |
| 234 | 376 | |
| 235 | 377 | if ($status eq 'sent') { $delivered++; } |
| 236 | 378 | elsif ($status eq 'skipped') { $skipped++; } |
| 237 | 379 | else { $failed++; } |
| 238 | 380 | |
| 239 | 381 | # Bump the rule's fire_count + last_fired_at |
| 240 | 382 | if ($status eq 'sent') { |
| 241 | 383 | $db->db_readwrite($dbh, qq~ |
| 242 | 384 | UPDATE ALERT_RULES |
| 243 | 385 | SET fire_count = fire_count + 1, |
| 244 | 386 | last_fired_at = NOW() |
| 245 | 387 | WHERE alert_rule_id = $rule->{alert_rule_id} |
| 246 | 388 | ~, __FILE__, __LINE__); |
| 247 | 389 | } |
| 248 | 390 | } |
| 249 | 391 | } |
| 250 | 392 | |
| 251 | 393 | #--------------------------------------------------------------------- |
| 252 | 394 | sub _rule_matches { |
| 253 | 395 | my ($rule, $row, $kind) = @_; |
| 254 | 396 | |
| 255 | 397 | # Kind filter |
| 256 | 398 | return 0 if $rule->{match_kind} ne 'either' && $rule->{match_kind} ne $kind; |
| 257 | 399 | |
| 258 | 400 | # ts-only exclusion (files only) |
| 259 | 401 | return 0 if $kind eq 'file' && $rule->{exclude_ts_only} && $row->{is_ts_only}; |
| 260 | 402 | |
| 261 | 403 | # Path glob |
| 262 | 404 | my $glob = $rule->{match_path_glob} // ''; |
| 263 | 405 | if (length $glob) { |
| 264 | 406 | my $target = $kind eq 'file' |
| 265 | 407 | ? ($row->{file_name} // '') |
| 266 | 408 | : (($row->{database_name} // '') . '.' . ($row->{table_name} // '')); |
| 267 | 409 | my $re = _glob_to_regex($glob); |
| 268 | 410 | return 0 unless $target =~ $re; |
| 269 | 411 | } |
| 270 | 412 | |
| 271 | 413 | # Status filter (files only) |
| 272 | 414 | if ($kind eq 'file' && $rule->{match_status_list}) { |
| 273 | 415 | my %allowed = map { s/^\s+|\s+$//g; $_ => 1 } |
| 274 | 416 | split /,/, $rule->{match_status_list}; |
| 275 | 417 | return 0 unless $allowed{ $row->{status} // '' }; |
| 276 | 418 | } |
| 277 | 419 | |
| 278 | 420 | return 1; |
| 279 | 421 | } |
| 280 | 422 | |
| 281 | 423 | sub _glob_to_regex { |
| 282 | 424 | my $g = shift; |
| 283 | 425 | my $re = quotemeta $g; |
| 284 | 426 | # Handle glob patterns: escaped meta chars back to regex meaning |
| 285 | 427 | $re =~ s{\\\*\\\*}{.*}g; # ** -> .* |
| 286 | 428 | $re =~ s{\\\*}{[^/]*}g; # * -> [^/]* |
| 287 | 429 | $re =~ s{\\\?}{.}g; # ? -> . |
| 288 | 430 | return qr/^$re$/; |
| 289 | 431 | } |
| 290 | 432 | |
| 291 | 433 | #--------------------------------------------------------------------- |
| 292 | 434 | sub _build_payload { |
| 293 | 435 | my ($rule, $row, $kind) = @_; |
| 294 | 436 | |
| 295 | 437 | my $where = $kind eq 'file' |
| 296 | 438 | ? ($row->{file_name} // '(unknown file)') |
| 297 | 439 | : (($row->{database_name} // '?') . '.' . ($row->{table_name} // '?')); |
| 298 | 440 | my $when_utc = $row->{date_time} || $row->{change_datetime} || ''; |
| 299 | 441 | my $server = $row->{server_name} || 'local'; |
| 300 | 442 | my $status_h = $kind eq 'file' ? ($row->{status} // '') : 'DDL change'; |
| 301 | 443 | my $link_id = $row->{id}; |
| 302 | 444 | my $link = "$public_url/diff.cgi?kind=$kind&id=$link_id"; |
| 303 | 445 | |
| 304 | 446 | my $summary = $kind eq 'file' |
| 305 | 447 | ? "$status_h: $where on $server" |
| 306 | 448 | : "$where changed on $server"; |
| 307 | 449 | |
| 308 | 450 | my $slack = { |
| 309 | 451 | text => "*DriftSense*: $summary", |
| 310 | 452 | attachments => [{ |
| 311 | 453 | color => $kind eq 'schema' ? '#f59e0b' : '#14b8a6', |
| 312 | 454 | fields => [ |
| 313 | 455 | { title => 'What', value => $where, short => 0 }, |
| 314 | 456 | { title => 'When', value => $when_utc, short => 1 }, |
| 315 | 457 | { title => 'Server', value => $server, short => 1 }, |
| 316 | 458 | ], |
| 317 | 459 | actions => [{ |
| 318 | 460 | type => 'button', text => 'View diff', url => $link, |
| 319 | 461 | }], |
| 320 | 462 | }], |
| 321 | 463 | }; |
| 322 | 464 | my $discord = { |
| 323 | 465 | content => "**DriftSense**: $summary", |
| 324 | 466 | embeds => [{ |
| 325 | 467 | title => $where, |
| 326 | 468 | url => $link, |
| 327 | 469 | color => $kind eq 'schema' ? 16101915 : 1349286, # amber, teal |
| 328 | 470 | fields => [ |
| 329 | 471 | { name => 'When', value => $when_utc || '?', inline => \1 }, |
| 330 | 472 | { name => 'Server', value => $server, inline => \1 }, |
| 331 | 473 | ], |
| 332 | 474 | }], |
| 333 | 475 | }; |
| 334 | 476 | my $generic = { |
| 335 | 477 | source => 'drift_sense', |
| 336 | 478 | rule_id => $rule->{alert_rule_id}, |
| 337 | 479 | rule_name => $rule->{rule_name}, |
| 338 | 480 | kind => $kind, |
| 339 | 481 | summary => $summary, |
| 340 | 482 | target => $where, |
| 341 | 483 | server => $server, |
| 342 | 484 | when_utc => $when_utc, |
| 343 | 485 | ts_epoch => $row->{ts_epoch}, |
| 344 | 486 | diff_url => $link, |
| 345 | 487 | status => $status_h, |
| 346 | 488 | }; |
| 347 | 489 | |
| 348 | 490 | return { |
| 349 | 491 | slack => $slack, |
| 350 | 492 | discord => $discord, |
| 351 | 493 | generic_webhook => $generic, |
| 352 | 494 | summary => $summary, |
| 353 | 495 | }; |
| 354 | 496 | } |
| 355 | 497 | |
| 356 | 498 | #--------------------------------------------------------------------- |
| 357 | 499 | sub _deliver { |
| 358 | 500 | my ($rule, $payload) = @_; |
| 359 | 501 | my $kind = $rule->{delivery_kind}; |
| 360 | 502 | my $url = $rule->{delivery_url}; |
| 361 | 503 | |
| 362 | 504 | if ($kind eq 'email') { |
| 363 | 505 | return ('skipped', undef, undef, 'email delivery not yet implemented'); |
| 364 | 506 | } |
| 365 | 507 | unless (length($url // '')) { |
| 366 | 508 | return ('failed', undef, undef, "no delivery URL configured"); |
| 367 | 509 | } |
| 368 | 510 | |
| 369 | 511 | my $body_ref = $kind eq 'slack' ? $payload->{slack} |
| 370 | 512 | : $kind eq 'discord' ? $payload->{discord} |
| 371 | 513 | : $payload->{generic_webhook}; |
| 372 | 514 | |
| 373 | 515 | # MODS::Webhook handles JSON encoding + curl transport; returns |
| 374 | 516 | # (http_code, response_body, error_message). |
| 375 | 517 | my ($code, $rbody, $err) = MODS::Webhook::post_json( |
| 376 | 518 | $url, $body_ref, |
| 377 | 519 | timeout => 8, |
| 378 | 520 | user_agent => 'DriftSense/1.0 (alert-dispatch)', |
| 379 | 521 | ); |
| 380 | 522 | $rbody //= ''; |
| 381 | 523 | $rbody = substr($rbody, 0, 500) if length($rbody) > 500; |
| 382 | 524 | |
| 383 | 525 | if (!$err && $code >= 200 && $code < 400) { |
| 384 | 526 | return ('sent', $code, $rbody, undef); |
| 385 | 527 | } |
| 386 | 528 | return ('failed', $code, $rbody, $err || "HTTP $code"); |
| 387 | 529 | } |
| 388 | 530 | |
| 389 | 531 | #--------------------------------------------------------------------- |
| 390 | 532 | sub _log_delivery { |
| 391 | 533 | my ($rule, $row, $kind, $status, $http_code, $body, $err) = @_; |
| 392 | 534 | my $summary = substr(($rule->{rule_name} // '') . ' :: ' . ($row->{file_name} |
| 393 | 535 | || ($row->{database_name} . '.' . $row->{table_name}) |
| 394 | 536 | || '?'), 0, 490); |
| 395 | 537 | my $q_summary = $dbh->quote($summary); |
| 396 | 538 | my $q_status = $dbh->quote($status); |
| 397 | 539 | my $q_body = $dbh->quote($body // ''); |
| 398 | 540 | my $q_err = $dbh->quote($err // ''); |
| 399 | 541 | my $q_code = defined($http_code) ? int($http_code) : 'NULL'; |
| 400 | 542 | |
| 401 | 543 | $db->db_readwrite($dbh, qq~ |
| 402 | 544 | INSERT INTO ALERT_DELIVERIES |
| 403 | 545 | (alert_rule_id, source_kind, source_id, match_summary, |
| 404 | 546 | delivery_status, http_status, http_response, error_message) |
| 405 | 547 | VALUES |
| 406 | 548 | ($rule->{alert_rule_id}, '$kind', $row->{id}, $q_summary, |
| 407 | 549 | $q_status, $q_code, $q_body, $q_err) |
| 408 | 550 | ~, __FILE__, __LINE__); |
| 409 | 551 | } |