Restore

O Operator
Restore

Restore file to captured state

Every captured change carries its SHA-256-addressed content in BLOB_STORE. Restoring writes that content back to the original path — current file gets backed up to <path>.drift_restore_backup_<epoch> before overwrite.

What will change
Preview -- nothing has been written yet.
Target file/var/www/vhosts/3dshawn.com/site1/_alert_dispatch.pl
SiteDriftSense self-monitor on local
Kindlocal
Captured at2026-07-12 00:02:08
Captured SHA50aef6cbce02f3e212b0302289efed426c35ba295f6c82008a8af3f3a87c9d8b
Current state on disk
Live check just now. If SHAs match, the restore is a no-op.
File presentyes
Size22933 bytes
Current SHAa53566efc691
Same as captured?no -- restore will change it
What restore will change — live diff
Left column shows current on-disk content; right shows what restore will write. +1 additions, -185 deletions, 408 unchanged context lines.
11#!/usr/bin/perl
22#======================================================================
33# DriftSense -- alert dispatcher
44#
55# Cron entry point (NOT a CGI). Walks FILE_CHANGES + SCHEMA_CHANGE rows
66# inserted since the last cursor tick, evaluates every ACTIVE rule
77# against each new row, and POSTs matching payloads to the configured
88# webhook (Slack / Discord / generic HTTP). Every attempt is logged
99# to ALERT_DELIVERIES for the operator's audit trail.
1010#
1111# Config: /etc/drift_sense/drift_sense.conf (via MODS::Config).
1212# Log: /var/log/drift_sense/alert_dispatch.log (via cron redirect).
1313#======================================================================
1414use strict;
1515use warnings;
1616use lib '/var/www/vhosts/3dshawn.com/site1';
1717use POSIX ();
18use Symbol ();
1918use JSON::PP;
2019use MODS::Config;
2120use MODS::DBConnect;
2221use MODS::Webhook;
2322
2423$| = 1;
2524my $ts = POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime);
2625
2726my $cfg = MODS::Config->new;
2827my $db = MODS::DBConnect->new;
2928my $dbh = $db->db_connect or die "[$ts] cannot connect to DriftSense storage DB\n";
3029
3130my $public_url = $cfg->settings('public_url') || 'https://watchtower.3dshawn.com';
3231
3332# ---- Fetch active rules ---------------------------------------------
3433my @rules = $db->db_readwrite_multiple($dbh, q~
3534 SELECT alert_rule_id, rule_name, match_kind, match_path_glob,
3635 match_status_list, exclude_ts_only,
3736 delivery_kind, delivery_url, delivery_email,
3837 rate_limit_per_min, coalesce_window_s,
3938 frequency_threshold, frequency_window_min,
4039 UNIX_TIMESTAMP(last_frequency_fire_at) AS last_freq_fire_epoch
4140 FROM ALERT_RULES
4241 WHERE is_active = 1
4342~, __FILE__, __LINE__);
4443
4544unless (@rules) {
4645 print "[$ts] no active alert rules, exiting\n";
4746 $db->db_disconnect($dbh);
4847 exit 0;
4948}
5049
5150# ---- Fetch cursor ---------------------------------------------------
5251my %cursor;
5352foreach my $r ($db->db_readwrite_multiple($dbh, q~
5453 SELECT source_kind, last_seen_id FROM ALERT_CURSOR
5554~, __FILE__, __LINE__)) {
5655 $cursor{$r->{source_kind}} = $r->{last_seen_id};
5756}
5857$cursor{file} //= 0;
5958$cursor{schema} //= 0;
6059
6160# ---- Pull new FILE_CHANGES since cursor ------------------------------
6261my $file_max = $cursor{file};
6362my @file_new = $db->db_readwrite_multiple($dbh, qq~
6463 SELECT fc.file_changes_id AS id, fc.file_name, fc.status, fc.blob_sha,
6564 fc.is_ts_only, fc.date_time,
6665 UNIX_TIMESTAMP(fc.date_time) AS ts_epoch,
6766 s.server_name
6867 FROM FILE_CHANGES fc
6968 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
7069 WHERE fc.file_changes_id > $cursor{file}
7170 ORDER BY fc.file_changes_id ASC
7271 LIMIT 500
7372~, __FILE__, __LINE__);
7473foreach my $r (@file_new) {
7574 $file_max = $r->{id} if $r->{id} > $file_max;
7675}
7776
7877# ---- Pull new SCHEMA_CHANGE since cursor -----------------------------
7978my $schema_max = $cursor{schema};
8079my @schema_new = $db->db_readwrite_multiple($dbh, qq~
8180 SELECT sc.schema_change_id AS id, sc.database_name, sc.table_name,
8281 sc.changes, sc.is_ts_only, sc.change_datetime,
8382 UNIX_TIMESTAMP(sc.change_datetime) AS ts_epoch,
8483 s.server_name
8584 FROM SCHEMA_CHANGE sc
8685 LEFT JOIN SERVERS s ON s.server_id = sc.server_id
8786 WHERE sc.schema_change_id > $cursor{schema}
8887 ORDER BY sc.schema_change_id ASC
8988 LIMIT 500
9089~, __FILE__, __LINE__);
9190foreach my $r (@schema_new) {
9291 $schema_max = $r->{id} if $r->{id} > $schema_max;
9392}
9493
9594my $total_new = scalar(@file_new) + scalar(@schema_new);
9695if ($total_new == 0) {
9796 print "[$ts] no new changes since cursor (file=$cursor{file} schema=$cursor{schema})\n";
9897 $db->db_disconnect($dbh);
9998 exit 0;
10099}
101100
102101# ---- Evaluate + deliver ---------------------------------------------
103102# HTTP transport is MODS::Webhook (shells out to /usr/bin/curl) so we
104103# don't need LWP::Protocol::https / IO::Socket::SSL as CPAN installs.
105104
106105my $delivered = 0;
107106my $skipped = 0;
108107my $failed = 0;
109108
110109foreach my $row (@file_new) { _process_row($row, 'file'); }
111110foreach my $row (@schema_new) { _process_row($row, 'schema'); }
112111
113112# ---- Frequency-mode rules ------------------------------------------
114113# For any rule where frequency_threshold > 0, we ignore the per-row loop
115114# above and instead: query how many file changes matching the rule's
116115# path glob happened in the last window_min minutes. If it crosses the
117116# threshold and we haven't fired within the same window, fire once with
118117# the top offender.
119118foreach my $rule (@rules) {
120119 next unless ($rule->{frequency_threshold} || 0) > 0;
121120 my $win = int($rule->{frequency_window_min} || 60);
122121 my $thr = int($rule->{frequency_threshold});
123122
124123 # Re-fire cooldown: don't fire more than once per window
125124 my $last = int($rule->{last_freq_fire_epoch} || 0);
126125 if ($last && (time - $last) < $win * 60) {
127126 next;
128127 }
129128
130129 # Find files whose match_path_glob-hit change count > threshold
131130 my $glob = $rule->{match_path_glob} // '';
132131 my $glob_sql = '';
133132 if (length $glob) {
134133 # Approx: SQL LIKE. Convert glob wildcards to SQL % / _.
135134 my $like = $glob;
136135 $like =~ s/\*\*/%/g;
137136 $like =~ s/\*/%/g;
138137 $like =~ s/\?/_/g;
139138 my $q_like = $dbh->quote($like);
140139 $glob_sql = " AND fc.file_name LIKE $q_like";
141140 }
142141 my @hot = $db->db_readwrite_multiple($dbh, qq~
143142 SELECT fc.file_name,
144143 COUNT(*) AS ct,
145144 MAX(fc.file_changes_id) AS latest_id,
146145 s.server_name
147146 FROM FILE_CHANGES fc
148147 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
149148 WHERE fc.date_time >= DATE_SUB(NOW(), INTERVAL $win MINUTE)
150149 $glob_sql
151150 GROUP BY fc.file_name
152151 HAVING ct >= $thr
153152 ORDER BY ct DESC
154153 LIMIT 5
155154 ~, __FILE__, __LINE__);
156155 next unless @hot;
157156
158157 # Fire once with the top offender's info
159158 my $top = $hot[0];
160159 my $fake_row = {
161160 id => $top->{latest_id},
162161 file_name => $top->{file_name},
163162 server_name => $top->{server_name} // 'local',
164163 date_time => POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime),
165164 ts_epoch => time,
166165 status => 'frequency_alert',
167166 };
168167 my $payload = _build_payload($rule, $fake_row, 'file');
169168 # Enrich summary with count + threshold
170169 my $extra = "frequency alert: $top->{file_name} changed $top->{ct} times in the last $win min (threshold: $thr)";
171170 if (ref($payload->{generic_webhook}) eq 'HASH') {
172171 $payload->{generic_webhook}{frequency_summary} = $extra;
173172 $payload->{generic_webhook}{frequency_count} = $top->{ct};
174173 $payload->{generic_webhook}{frequency_window} = $win;
175174 $payload->{generic_webhook}{summary} = $extra;
176175 }
177176 my ($status, $http_code, $body, $err) = _deliver($rule, $payload);
178177 _log_delivery($rule, $fake_row, 'file', $status, $http_code, $body, $err);
179178 if ($status eq 'sent') {
180179 $delivered++;
181180 $db->db_readwrite($dbh, qq~
182181 UPDATE ALERT_RULES
183182 SET fire_count = fire_count + 1,
184183 last_fired_at = NOW(),
185184 last_frequency_fire_at = NOW()
186185 WHERE alert_rule_id = $rule->{alert_rule_id}
187186 ~, __FILE__, __LINE__);
188187 } else {
189188 $failed++;
190189 }
191190}
192191
193192# ---- Advance cursor atomically --------------------------------------
194193if ($file_max > $cursor{file}) {
195194 $db->db_readwrite($dbh,
196195 "UPDATE ALERT_CURSOR SET last_seen_id = $file_max WHERE source_kind = 'file'",
197196 __FILE__, __LINE__);
198197}
199198if ($schema_max > $cursor{schema}) {
200199 $db->db_readwrite($dbh,
201200 "UPDATE ALERT_CURSOR SET last_seen_id = $schema_max WHERE source_kind = 'schema'",
202201 __FILE__, __LINE__);
203}
204
205# ---- Pin-drift alerts (Feature 5 wave 4) ---------------------------
206# For each Named Release with alert_delivery_url set, check whether any
207# pin's current-latest SHA differs from the pinned SHA. Log the drift
208# to PIN_DRIFT_LOG (with notified=0) and, if not yet notified, POST an
209# alert to the release's delivery URL, then set notified=1.
210foreach my $rel ($db->db_readwrite_multiple($dbh, q~
211 SELECT named_release_id, name, alert_delivery_kind, alert_delivery_url
212 FROM NAMED_RELEASES
213 WHERE alert_delivery_kind IS NOT NULL
214 AND alert_delivery_kind != 'none'
215 AND alert_delivery_url IS NOT NULL
216 AND alert_delivery_url != ''
217~, __FILE__, __LINE__)) {
218
219 my $rid = $rel->{named_release_id};
220 my @drifts;
221 foreach my $pin ($db->db_readwrite_multiple($dbh, qq~
222 SELECT p.pin_id, p.file_name, p.blob_sha AS pinned_sha,
223 fc.server_id
224 FROM NAMED_RELEASE_PINS p
225 LEFT JOIN FILE_CHANGES fc ON fc.file_changes_id = p.file_changes_id
226 WHERE p.named_release_id = $rid
227 ~, __FILE__, __LINE__)) {
228 my $q_file = $dbh->quote($pin->{file_name});
229 my $sid = int($pin->{server_id} || 0);
230 my $cur = $db->db_readwrite($dbh, qq~
231 SELECT blob_sha, file_changes_id FROM FILE_CHANGES
232 WHERE server_id = $sid AND file_name = $q_file
233 ORDER BY file_changes_id DESC LIMIT 1
234 ~, __FILE__, __LINE__);
235 my $cur_sha = $cur ? $cur->{blob_sha} : '';
236 next unless $cur_sha && $cur_sha ne $pin->{pinned_sha};
237
238 # Have we already logged + notified this (pin, current_sha) tuple?
239 my $q_pinned = $dbh->quote($pin->{pinned_sha});
240 my $q_current = $dbh->quote($cur_sha);
241 my $seen = $db->db_readwrite($dbh, qq~
242 SELECT drift_id, notified FROM PIN_DRIFT_LOG
243 WHERE pin_id = $pin->{pin_id}
244 AND current_sha = $q_current
245 ORDER BY drift_id DESC LIMIT 1
246 ~, __FILE__, __LINE__);
247 if ($seen && $seen->{notified}) {
248 next; # already notified for this exact drift state
249 }
250
251 # Log the drift
252 my $q_fname = $dbh->quote($pin->{file_name});
253 my $cid = int($cur->{file_changes_id} || 0);
254 $db->db_readwrite($dbh, qq~
255 INSERT INTO PIN_DRIFT_LOG
256 (named_release_id, pin_id, file_name, pinned_sha, current_sha, file_changes_id, notified)
257 VALUES
258 ($rid, $pin->{pin_id}, $q_fname, $q_pinned, $q_current, $cid, 0)
259 ~, __FILE__, __LINE__);
260 push @drifts, {
261 file_name => $pin->{file_name},
262 pinned_sha => $pin->{pinned_sha},
263 current_sha => $cur_sha,
264 change_id => $cid,
265 };
266 }
267
268 next unless @drifts;
269
270 # Build a summary payload
271 my $summary = sprintf('Named release "%s" -- %d pinned file(s) have drifted', $rel->{name}, scalar @drifts);
272 my $public_url = $cfg->settings('public_url') || 'https://watchtower.3dshawn.com';
273 my $files_list = join("\n", map {
274 " * $_->{file_name} (pinned: " . substr($_->{pinned_sha}, 0, 12) .
275 " -> current: " . substr($_->{current_sha}, 0, 12) . ")"
276 } @drifts);
277 my $link = "$public_url/restore_release.cgi?release_id=$rid";
278
279 my $slack_body = {
280 text => "*DriftSense pin drift*: $summary",
281 attachments => [{
282 color => '#f43f5e',
283 fields => [
284 { title => 'Release', value => $rel->{name}, short => 1 },
285 { title => 'Drifted files', value => scalar(@drifts), short => 1 },
286 { title => 'Details', value => $files_list, short => 0 },
287 ],
288 actions => [{ type => 'button', text => 'Restore all pinned', url => $link }],
289 }],
290 };
291 my $discord_body = {
292 content => "**DriftSense pin drift**: $summary",
293 embeds => [{
294 title => $rel->{name},
295 url => $link,
296 color => 16005694,
297 description => $files_list,
298 }],
299 };
300 my $generic_body = {
301 source => 'drift_sense',
302 alert_type => 'pin_drift',
303 release_id => $rid,
304 release_name => $rel->{name},
305 drifted_count=> scalar @drifts,
306 summary => $summary,
307 files => \@drifts,
308 restore_url => $link,
309 };
310
311 my $body_ref = $rel->{alert_delivery_kind} eq 'slack' ? $slack_body
312 : $rel->{alert_delivery_kind} eq 'discord' ? $discord_body
313 : $generic_body;
314
315 my ($code, $rbody, $err) = MODS::Webhook::post_json(
316 $rel->{alert_delivery_url}, $body_ref,
317 timeout => 8,
318 user_agent => 'DriftSense/1.0 (pin-drift)',
319 );
320
321 if (!$err && $code >= 200 && $code < 400) {
322 # Mark all just-logged rows as notified
323 foreach my $d (@drifts) {
324 my $q_current = $dbh->quote($d->{current_sha});
325 $db->db_readwrite($dbh, qq~
326 UPDATE PIN_DRIFT_LOG SET notified = 1
327 WHERE named_release_id = $rid
328 AND file_name = @{[ $dbh->quote($d->{file_name}) ]}
329 AND current_sha = $q_current
330 AND notified = 0
331 ~, __FILE__, __LINE__);
332 }
333 $delivered++;
334 print "[$ts] pin-drift alert delivered for release '$rel->{name}' (" . scalar(@drifts) . " drifted)\n";
335 } else {
336 $failed++;
337 print "[$ts] pin-drift alert FAILED for release '$rel->{name}': " . ($err // "HTTP $code") . "\n";
338 }
339
340 # Bookkeep the check timestamp
341 $db->db_readwrite($dbh, qq~
342 UPDATE NAMED_RELEASES SET last_pin_drift_check_at = NOW()
343 WHERE named_release_id = $rid
344 ~, __FILE__, __LINE__);
345202}
346203
347204$db->db_disconnect($dbh);
348205print "[$ts] processed +$total_new new changes: $delivered delivered, $skipped skipped, $failed failed\n";
349206exit 0;
350207
351208#---------------------------------------------------------------------
352209sub _process_row {
353210 my ($row, $kind) = @_;
354211 foreach my $rule (@rules) {
355212 next unless _rule_matches($rule, $row, $kind);
356213
357214 # Rate limit check
358215 if ($rule->{rate_limit_per_min} > 0) {
359216 my $rlq = $db->db_readwrite($dbh, qq~
360217 SELECT COUNT(*) AS n FROM ALERT_DELIVERIES
361218 WHERE alert_rule_id = $rule->{alert_rule_id}
362219 AND fired_at >= DATE_SUB(NOW(), INTERVAL 1 MINUTE)
363220 AND delivery_status IN ('sent','pending')
364221 ~, __FILE__, __LINE__);
365222 if ($rlq && $rlq->{n} >= $rule->{rate_limit_per_min}) {
366223 _log_delivery($rule, $row, $kind, 'skipped', undef, undef,
367224 "rate limit ($rule->{rate_limit_per_min}/min) reached");
368225 $skipped++;
369226 next;
370227 }
371228 }
372229
373230 # Build payload + POST
374231 my $payload = _build_payload($rule, $row, $kind);
375232 my ($status, $http_code, $body, $err) = _deliver($rule, $payload);
376233 _log_delivery($rule, $row, $kind, $status, $http_code, $body, $err);
377234
378235 if ($status eq 'sent') { $delivered++; }
379236 elsif ($status eq 'skipped') { $skipped++; }
380237 else { $failed++; }
381238
382239 # Bump the rule's fire_count + last_fired_at
383240 if ($status eq 'sent') {
384241 $db->db_readwrite($dbh, qq~
385242 UPDATE ALERT_RULES
386243 SET fire_count = fire_count + 1,
387244 last_fired_at = NOW()
388245 WHERE alert_rule_id = $rule->{alert_rule_id}
389246 ~, __FILE__, __LINE__);
390247 }
391248 }
392249}
393250
394251#---------------------------------------------------------------------
395252sub _rule_matches {
396253 my ($rule, $row, $kind) = @_;
397254
398255 # Kind filter
399256 return 0 if $rule->{match_kind} ne 'either' && $rule->{match_kind} ne $kind;
400257
401258 # ts-only exclusion (files only)
402259 return 0 if $kind eq 'file' && $rule->{exclude_ts_only} && $row->{is_ts_only};
403260
404261 # Path glob
405262 my $glob = $rule->{match_path_glob} // '';
406263 if (length $glob) {
407264 my $target = $kind eq 'file'
408265 ? ($row->{file_name} // '')
409266 : (($row->{database_name} // '') . '.' . ($row->{table_name} // ''));
410267 my $re = _glob_to_regex($glob);
411268 return 0 unless $target =~ $re;
412269 }
413270
414271 # Status filter (files only)
415272 if ($kind eq 'file' && $rule->{match_status_list}) {
416273 my %allowed = map { s/^\s+|\s+$//g; $_ => 1 }
417274 split /,/, $rule->{match_status_list};
418275 return 0 unless $allowed{ $row->{status} // '' };
419276 }
420277
421278 return 1;
422279}
423280
424281sub _glob_to_regex {
425282 my $g = shift;
426283 my $re = quotemeta $g;
427284 # Handle glob patterns: escaped meta chars back to regex meaning
428285 $re =~ s{\\\*\\\*}{.*}g; # ** -> .*
429286 $re =~ s{\\\*}{[^/]*}g; # * -> [^/]*
430287 $re =~ s{\\\?}{.}g; # ? -> .
431288 return qr/^$re$/;
432289}
433290
434291#---------------------------------------------------------------------
435292sub _build_payload {
436293 my ($rule, $row, $kind) = @_;
437294
438295 my $where = $kind eq 'file'
439296 ? ($row->{file_name} // '(unknown file)')
440297 : (($row->{database_name} // '?') . '.' . ($row->{table_name} // '?'));
441298 my $when_utc = $row->{date_time} || $row->{change_datetime} || '';
442299 my $server = $row->{server_name} || 'local';
443300 my $status_h = $kind eq 'file' ? ($row->{status} // '') : 'DDL change';
444301 my $link_id = $row->{id};
445302 my $link = "$public_url/diff.cgi?kind=$kind&id=$link_id";
446303
447304 my $summary = $kind eq 'file'
448305 ? "$status_h: $where on $server"
449306 : "$where changed on $server";
450307
451308 my $slack = {
452309 text => "*DriftSense*: $summary",
453310 attachments => [{
454311 color => $kind eq 'schema' ? '#f59e0b' : '#14b8a6',
455312 fields => [
456313 { title => 'What', value => $where, short => 0 },
457314 { title => 'When', value => $when_utc, short => 1 },
458315 { title => 'Server', value => $server, short => 1 },
459316 ],
460317 actions => [{
461318 type => 'button', text => 'View diff', url => $link,
462319 }],
463320 }],
464321 };
465322 my $discord = {
466323 content => "**DriftSense**: $summary",
467324 embeds => [{
468325 title => $where,
469326 url => $link,
470327 color => $kind eq 'schema' ? 16101915 : 1349286, # amber, teal
471328 fields => [
472329 { name => 'When', value => $when_utc || '?', inline => \1 },
473330 { name => 'Server', value => $server, inline => \1 },
474331 ],
475332 }],
476333 };
477334 my $generic = {
478335 source => 'drift_sense',
479336 rule_id => $rule->{alert_rule_id},
480337 rule_name => $rule->{rule_name},
481338 kind => $kind,
482339 summary => $summary,
483340 target => $where,
484341 server => $server,
485342 when_utc => $when_utc,
486343 ts_epoch => $row->{ts_epoch},
487344 diff_url => $link,
488345 status => $status_h,
489346 };
490347
491348 return {
492349 slack => $slack,
493350 discord => $discord,
494351 generic_webhook => $generic,
495352 summary => $summary,
496353 };
497354}
498355
499356#---------------------------------------------------------------------
500357sub _deliver {
501358 my ($rule, $payload) = @_;
502359 my $kind = $rule->{delivery_kind};
503360 my $url = $rule->{delivery_url};
504361
505362 if ($kind eq 'email') {
506 my $to = $rule->{delivery_email} || '';
507 return ('failed', undef, undef, 'no delivery_email configured') unless length $to;
508 my $summary = $payload->{summary} // 'DriftSense alert';
509 my $target = ($payload->{generic_webhook} && $payload->{generic_webhook}{target}) // '(unknown)';
510 my $server = ($payload->{generic_webhook} && $payload->{generic_webhook}{server}) // 'local';
511 my $link = ($payload->{generic_webhook} && $payload->{generic_webhook}{diff_url}) // '';
512
513 my $mail_body = "DriftSense captured a change matching alert rule: $rule->{rule_name}\n\n"
514 . "Target : $target\n"
515 . "Server : $server\n"
516 . "Summary: $summary\n"
517 . ($link ? "Diff : $link\n" : '')
518 . "\n(Automated notification from DriftSense.)\n";
519
520 my $from = $cfg->settings('alert_from_email') || 'drift_sense@localhost';
521 my $subj = "[DriftSense] " . substr($summary, 0, 120);
522
523 my $sendmail = '/usr/sbin/sendmail';
524 $sendmail = '/usr/lib/sendmail' unless -x $sendmail;
525 return ('failed', undef, undef, "no sendmail binary") unless -x $sendmail;
526
527 require IPC::Open3;
528 my ($wtr, $rdr, $err_fh);
529 $err_fh = Symbol::gensym();
530 my $pid = eval { IPC::Open3::open3($wtr, $rdr, $err_fh, $sendmail, '-t', '-i') };
531 return ('failed', undef, undef, "spawn: $@") if $@ || !$pid;
532 binmode $wtr;
533 print {$wtr} "From: $from\r\n";
534 print {$wtr} "To: $to\r\n";
535 print {$wtr} "Subject: $subj\r\n";
536 print {$wtr} "Content-Type: text/plain; charset=utf-8\r\n";
537 print {$wtr} "\r\n";
538 print {$wtr} $mail_body;
539 close $wtr;
540 do { local $/; <$rdr> // ''; };
541 do { local $/; <$err_fh> // ''; };
542 close $rdr; close $err_fh;
543 waitpid $pid, 0;
544 my $rc = $? >> 8;
545 return $rc == 0
546 ? ('sent', 0, "delivered to $to", undef)
547 : ('failed', $rc, undef, "sendmail exit $rc");
363 return ('skipped', undef, undef, 'email delivery not yet implemented');
548364 }
549365 unless (length($url // '')) {
550366 return ('failed', undef, undef, "no delivery URL configured");
551367 }
552368
553369 my $body_ref = $kind eq 'slack' ? $payload->{slack}
554370 : $kind eq 'discord' ? $payload->{discord}
555371 : $payload->{generic_webhook};
556372
557373 # MODS::Webhook handles JSON encoding + curl transport; returns
558374 # (http_code, response_body, error_message).
559375 my ($code, $rbody, $err) = MODS::Webhook::post_json(
560376 $url, $body_ref,
561377 timeout => 8,
562378 user_agent => 'DriftSense/1.0 (alert-dispatch)',
563379 );
564380 $rbody //= '';
565381 $rbody = substr($rbody, 0, 500) if length($rbody) > 500;
566382
567383 if (!$err && $code >= 200 && $code < 400) {
568384 return ('sent', $code, $rbody, undef);
569385 }
570386 return ('failed', $code, $rbody, $err || "HTTP $code");
571387}
572388
573389#---------------------------------------------------------------------
574390sub _log_delivery {
575391 my ($rule, $row, $kind, $status, $http_code, $body, $err) = @_;
576392 my $summary = substr(($rule->{rule_name} // '') . ' :: ' . ($row->{file_name}
577393 || ($row->{database_name} . '.' . $row->{table_name})
578394 || '?'), 0, 490);
579395 my $q_summary = $dbh->quote($summary);
580396 my $q_status = $dbh->quote($status);
581397 my $q_body = $dbh->quote($body // '');
582398 my $q_err = $dbh->quote($err // '');
583399 my $q_code = defined($http_code) ? int($http_code) : 'NULL';
584400
585401 $db->db_readwrite($dbh, qq~
586402 INSERT INTO ALERT_DELIVERIES
587403 (alert_rule_id, source_kind, source_id, match_summary,
588404 delivery_status, http_status, http_response, error_message)
589405 VALUES
590406 ($rule->{alert_rule_id}, '$kind', $row->{id}, $q_summary,
591407 $q_status, $q_code, $q_body, $q_err)
592408 ~, __FILE__, __LINE__);
593409}
Confirm restore
Backs current content to <target>.drift_restore_backup_<epoch>, writes the captured content, verifies SHA post-write.
Cancel Logged to RESTORE_LOG regardless of outcome.