File Coverage

File:blib/lib/Database/BI/Alert.pm
Coverage:69.0%

linestmtbrancondsubtimecode
1package Database::BI::Alert;
2
3
190
190
190
1105791
105
1069
use strict;
4
190
190
190
179
98
5032
use warnings;
5
6our $VERSION = '0.025.0';
7
8
190
190
190
183
82
2203
use Carp qw(croak);
9
190
190
190
187
109
1384
use Exporter qw(import);
10
190
190
190
204
101
2287
use File::Path qw(make_path);
11
190
190
190
206
108
1257
use File::Spec;
12
190
190
190
224
109
2373
use File::Temp qw(tempfile);
13
190
190
190
180
124
2598
use List::Util qw(sum);
14
190
190
190
194
113
1733
use Mojo::File;
15
190
190
190
255
157
1896
use Mojo::JSON qw(decode_json encode_json);
16
190
190
190
223
135
899
use POSIX ();
17
190
190
190
944
7104
1937
use Readonly;
18
190
190
190
202
144
1678
use Scalar::Util qw(looks_like_number);
19
190
190
190
193
117
170987
use Time::HiRes ();
20
21our @EXPORT_OK = qw(
22        measures_of measure_results evaluate parse_duration iso
23        load_state save_state load_log append_log deliver check_for
24);
25
26=encoding utf8
27
28 - 51
=head1 NAME

Database::BI::Alert - the checks behind script/bi-alert and the canvas Alerts panel

=head1 SYNOPSIS

    use Database::BI::Alert qw(measure_results evaluate);
    my $results = measure_results(\@measures, \@rows);
    my $outcome = evaluate(
        id => 'abc123', results => $results,
        checks => [ { alias => 'count', op => 'gt', value => 1000 } ],
        state => $state, now => time, suppress => 3600, recovery => 1,
    );
    print "$_\n" for @{ $outcome->{lines} };

=head1 DESCRIPTION

The rules of an alert, in one place so that the command line and the web
application agree: how a measure is worked out, when a crossed threshold is
announced, throttled and recovered, how the throttle's memory is kept and how an
announcement is delivered.  Nothing here reads a data file or touches a canvas;
the caller supplies the rows and the saved state.

=cut
52
53Readonly my %OPS => (
54        gt => sub { $_[0] >  $_[1] },
55        ge => sub { $_[0] >= $_[1] },
56        lt => sub { $_[0] <  $_[1] },
57        le => sub { $_[0] <= $_[1] },
58        eq => sub { $_[0] == $_[1] },
59        ne => sub { $_[0] != $_[1] },
60);
61Readonly my @FUNCTIONS => qw(count count_distinct sum avg min max);
62Readonly my $LOG_MAX   => 200;
63
64 - 73
=head1 FUNCTIONS

=head2 operators, functions

    my @ops = Database::BI::Alert::operators;    # gt ge lt le eq ne
    my @fns = Database::BI::Alert::functions;    # count count_distinct sum avg min max

The words a threshold's comparison and a measure's function may use.

=cut
74
75
98
275
sub operators { return sort keys %OPS }
76
44
57
sub functions { return @FUNCTIONS }
77
78 - 96
=head2 measures_of

    my @measures = measures_of($canvas);

The measures a saved canvas defines: its own C<measures>, else those of its
visuals, and those its Alerts panel thresholds define themselves.  Each is a hash with C<col>, C<fn> and C<as> (or the longer names
C<column>, C<func>, C<alias>).

=head3 API SPECIFICATION

=head4 INPUT

    $canvas : hashref (a saved canvas)

=head4 OUTPUT

A list of hashrefs, or an arrayref of them in scalar context.

=cut
97
98sub measures_of {
99
118
169
        my ($canvas) = @_;
100
118
231
        $canvas = {} unless ref $canvas eq 'HASH';
101
118
118
235
302
        my @measures = @{ ref $canvas->{measures} eq 'ARRAY' ? $canvas->{measures} : [] };
102
118
188
        unless (@measures) {
103
118
118
153
254
                for my $vis (@{ $canvas->{visuals} // [] }) {
104
63
63
44
157
                        push @measures, @{ $vis->{measures} // [] };
105                }
106        }
107        # A threshold set in the canvas's Alerts panel may define its own measure (a
108        # column and a function); it is worked out too, unless the canvas has one
109        # of that name.
110
118
0
0
245
0
0
        my %have = map { ($_->{as} // $_->{alias} // '') => 1 } grep { ref $_ eq 'HASH' } @measures;
111
118
297
        my $alerts = ref $canvas->{alerts} eq 'HASH' ? $canvas->{alerts} : {};
112
118
109
118
113
127
236
        for my $t (grep { ref $_ eq 'HASH' } @{ ref $alerts->{thresholds} eq 'ARRAY' ? $alerts->{thresholds} : [] }) {
113
109
328
                next unless defined $t->{fn} && defined $t->{measure} && !$have{ $t->{measure} }++;
114
92
198
                push @measures, { col => $t->{col} // '', fn => $t->{fn}, as => $t->{measure} };
115        }
116
118
365
        return wantarray ? @measures : \@measures;
117}
118
119 - 139
=head2 measure_results

    my $results = measure_results(\@measures, \@rows);

Works out each measure over the rows: the C<count> of rows is always there.
C<sum avg min max> read only the numeric cells; C<count_distinct> counts the
different values.

=head3 API SPECIFICATION

=head4 INPUT

    $measures : arrayref of { col, fn, as }
    $rows     : arrayref of hashrefs

=head4 OUTPUT

A hashref of alias to number.  A C<min> or C<max> of a column with no numbers is
left out.

=cut
140
141sub measure_results {
142
97
159
        my ($measures, $records) = @_;
143
97
178
        $measures = [] unless ref $measures eq 'ARRAY';
144
97
121
        $records  = [] unless ref $records  eq 'ARRAY';
145
97
71
        my %results;
146
97
56
161
68
        for my $m (grep { ref $_ eq 'HASH' } @$measures) {
147
56
42
                my $col   = $m->{col}  // $m->{column} // '';
148
56
69
                my $fn    = $m->{fn}   // $m->{func}   // 'count';
149
56
49
                my $alias = $m->{as}   // $m->{alias}  // "${col}_${fn}";
150
56
38
                next unless length $alias;
151
152
56
244
52
173
                my @vals = map { ref $_ eq 'HASH' ? $_->{$col} : undef } @$records;
153
154
56
77
                if ($fn eq 'count') {
155
28
43
                        $results{$alias} = scalar @$records;
156                } elsif ($fn eq 'count_distinct') {
157
0
0
                        my %seen;
158
0
0
0
0
                        $results{$alias} = scalar grep { !$seen{$_ // ''}++ } @vals;
159                } else {
160
28
122
40
170
                        my @nums = grep { defined $_ && looks_like_number($_) } @vals;
161
28
30
                        if ($fn eq 'sum') {
162
28
214
                                $results{$alias} = @nums ? sum(@nums) : 0;
163                        } elsif ($fn eq 'avg') {
164
0
0
                                $results{$alias} = @nums ? sum(@nums) / scalar(@nums) : 0;
165                        } elsif ($fn eq 'min') {
166
0
0
                                if (@nums) {
167
0
0
0
0
                                        my $v = $nums[0]; $v = $_ < $v ? $_ : $v for @nums;
168
0
0
                                        $results{$alias} = $v;
169                                }
170                        } elsif ($fn eq 'max') {
171
0
0
                                if (@nums) {
172
0
0
0
0
                                        my $v = $nums[0]; $v = $_ > $v ? $_ : $v for @nums;
173
0
0
                                        $results{$alias} = $v;
174                                }
175                        }
176                }
177        }
178
97
265
        $results{count} //= scalar @$records;
179
97
106
        return \%results;
180}
181
182 - 210
=head2 evaluate

    my $outcome = evaluate(id => ..., results => {...}, checks => [...], state => {...},
                           now => $epoch, suppress => $seconds, suppress_text => '1h',
                           recovery => 1, multi => 0);

Checks each threshold of one analysis against its measures, deciding what is
news.  One alert is one (analysis, threshold) pair: it has an entry of its own in
C<< $state->{alerts} >>, is throttled by C<suppress> (seconds; 0 = never), and is
recovered once, when it clears after an announced crossing.  C<state> is changed
in place; the caller decides whether to keep it.

=head3 API SPECIFICATION

=head4 INPUT

    id, results, checks ([ { alias, op, value } ]), state, now : required
    suppress, suppress_text, recovery, multi, keep : optional
    keep : true when the state is to be recorded (the entry that makes a
           recovery possible is written only then)

=head4 OUTPUT

    { lines => [ text ... ], crossings => [ text ... ], recoveries => [ text ... ],
      changed => 0|1 }

C<lines> are what the command line prints for the checks, in order.

=cut
211
212sub evaluate {
213
94
358
        my %a = @_;
214
94
173
        my ($id, $results, $state, $now) = @a{qw(id results state now)};
215
94
144
        my $suppress = $a{suppress} // 0;
216
94
129
        my $who = $a{multi} ? "[$id] " : '';
217
94
72
        my (@lines, @crossings, @recoveries);
218
94
74
        my $changed = 0;
219
94
138
        $state->{alerts} //= {};
220
221
94
94
82
140
        for my $check (@{ $a{checks} // [] }) {
222
122
122
88
140
                my ($alias, $op, $tval) = @{$check}{qw(alias op value)};
223
122
258
                croak "unsupported operator '$op'" unless exists $OPS{$op};
224
122
477
                my $actual = $results->{$alias};
225
226                # One alert is one (analysis, threshold) pair, so a second threshold on
227                # the same analysis -- and the same threshold on another one -- is
228                # throttled, recovered and delivered on a schedule of its own.
229
122
221
                my $key   = join('|', $id, "$alias:$op:$tval");
230
122
90
                my $entry = $state->{alerts}{$key};
231
232
122
181
                if ($OPS{$op}->($actual, $tval)) {
233
74
111
                        my $last_alert = $entry ? ($entry->{last_alert} // 0) : 0;
234
235                        # Announced unless this crossing was already announced inside the
236                        # period.  The comparison is on elapsed seconds, so a run a minute
237                        # early is still a repeat and a run after the period is news again.
238
74
207
                        if (!$suppress || !$last_alert || $now - $last_alert >= $suppress) {
239
61
121
                                my $verdict = "THRESHOLD CROSSED: $who$alias ($actual) $op $tval";
240
61
57
                                push @lines, $verdict;
241
61
38
                                push @crossings, $verdict;
242
61
86
                                push @lines, "Repeats of this threshold are suppressed for $a{suppress_text}."
243                                        if $suppress;
244
61
80
                                if ($a{keep}) {
245                                        $state->{alerts}{$key} = {
246
55
184
                                                since      => ($entry && ($entry->{since} // 0)) ? $entry->{since} : $now,
247                                                last_alert => $now,
248                                                value      => $actual,
249                                        };
250
55
81
                                        $changed = 1;
251                                }
252                        }
253                        else {
254                                # Crossed, and already announced: say what is going on and stay
255                                # quiet; nothing is being announced, so no CROSSED line.
256
13
43
                                push @lines, "THRESHOLD SUPPRESSED: $who$alias ($actual) $op $tval; last alert "
257                                        . iso($last_alert) . ', next alert after '
258                                        . iso($last_alert + $suppress);
259                        }
260                }
261                else {
262
48
91
                        push @lines, "Threshold not crossed: $who$alias ($actual) $op $tval";
263
264                        # Cleared.  Finding an entry is what makes this run the end of an
265                        # incident rather than the first sight of a threshold that was never
266                        # crossed, which is why the recovery is said once and only for a
267                        # crossing somebody was told about.  The entry goes either way, so the
268                        # next crossing alerts immediately instead of waiting out a period
269                        # that belongs to an incident that is over.
270
48
69
                        if ($entry) {
271
15
37
                                my $since = $entry->{since} // 0;
272
15
41
                                if ($a{recovery}) {
273
13
29
                                        my $verdict = "THRESHOLD RECOVERED: $who$alias ($actual) $op $tval";
274
13
41
                                        push @lines, "$verdict; crossed since " . iso($since) . ', cleared ' . iso($now);
275
13
24
                                        push @recoveries, $verdict;
276                                }
277                                else {
278
2
6
                                        push @lines, "THRESHOLD CLEARED: $who$alias ($actual) $op $tval; crossed since " . iso($since);
279                                }
280
15
23
                                delete $state->{alerts}{$key};
281
15
31
                                $changed = 1;
282                        }
283                }
284        }
285
94
333
        return { lines => \@lines, crossings => \@crossings, recoveries => \@recoveries, changed => $changed };
286}
287
288 - 305
=head2 parse_duration

    my $seconds = parse_duration('6h');

C<30>, C<30s>, C<15m>, C<6h>, C<2d>, C<1w>; a bare number is seconds.  Anything
else is undef.

=head3 API SPECIFICATION

=head4 INPUT

    $text : string

=head4 OUTPUT

Seconds, or undef.

=cut
306
307sub parse_duration {
308
99
134
        my $text = shift;
309
99
262
        return undef unless defined $text && length $text;
310
94
327
        my ($value, $unit) = $text =~ /\A\s*([0-9]+(?:\.[0-9]+)?)\s*([smhdw]?)\s*\z/i;
311
94
171
        return undef unless defined $value;
312
85
330
        my %seconds = ('' => 1, s => 1, m => 60, h => 3_600, d => 86_400, w => 604_800);
313
85
220
        return $value * $seconds{ lc $unit } + 0;
314}
315
316 - 322
=head2 iso

    iso($epoch)    # 2026-11-24T16:00:00Z

UTC, so a state file written in one zone reads the same in another.

=cut
323
324sub iso {
325
70
158
        my @t = gmtime($_[0] // 0);
326
70
279
        return sprintf '%04d-%02d-%02dT%02d:%02d:%02dZ', $t[5] + 1900, $t[4] + 1, @t[3, 2, 1, 0];
327}
328
329 - 348
=head2 load_state

    my ($state, $problem) = load_state($path);

The throttle's memory.  A file that cannot be read or parsed gives an empty state
and a C<$problem> to report, so a damaged file costs one repeated alert rather
than a run that never alerts again.

=head2 save_state

    my ($ok, $problem) = save_state($path, $state);

Written through a temporary file in the same folder and renamed into place, so
overlapping runs, or one that dies mid-write, never leave half a file.

=head3 SIDE EFFECTS

Writes the state file, creating its directory when it is missing.

=cut
349
350sub load_state {
351
90
93
        my $path = shift;
352
90
220
        local ($@, $!);
353
90
155
        my %empty = (version => 1, alerts => {});
354
90
548
        return (\%empty) unless -f $path;
355
356
41
41
26
189
        my $json = eval { Mojo::File->new($path)->slurp };
357
41
1521
        return (\%empty, "cannot read state file '$path': " . ($@ || $!)) unless defined $json;
358
359
41
41
35
113
        my $state = eval { decode_json($json) };
360
41
421
        unless (ref $state eq 'HASH' && ref $state->{alerts} eq 'HASH') {
361
1
2
                return (\%empty, "state file '$path' is not a throttle state file; starting from nothing");
362        }
363
40
75
        return ($state);
364}
365
366sub save_state {
367
42
99
        my ($path, $state) = @_;
368
42
403
        local ($@, $!);
369
42
134
        return _write_json($path, $state, 'state file');
370}
371
372sub _write_json {
373
56
116
        my ($path, $data, $what) = @_;
374
56
218
        return (0, "cannot write a $what: no path given") unless defined $path && length $path;
375
56
936
        my (undef, $dirs) = File::Spec->splitpath($path);
376
56
129
        my $dir = length $dirs ? $dirs : '.';
377
56
179
        unless (-d $dir) {
378
0
0
0
0
                eval { make_path($dir) };
379
0
0
                return (0, "cannot create $what directory '$dir': " . ($@ || $!)) unless -d $dir;
380        }
381
56
56
68
222
        my ($fh, $tmp) = eval { tempfile(DIR => $dir, UNLINK => 0) };
382
56
9867
        return (0, "cannot write a $what in '$dir': " . ($@ || $!)) unless $fh;
383
384
56
49
        my $ok = eval {
385
56
56
67
217
                print {$fh} encode_json($data);
386
56
1504
                close $fh or croak "close: $!";
387
56
2708
                rename($tmp, $path) or croak "rename $tmp to $path: $!";
388
56
59
                1;
389        };
390
56
100
        unless ($ok) {
391
0
0
                my $why = $@ || $!;
392
0
0
                close $fh if defined $fh;
393
0
0
                unlink $tmp if defined $tmp;
394
0
0
                return (0, "cannot write $what '$path': $why");
395        }
396
56
182
        return (1);
397}
398
399 - 417
=head2 load_log

    my @events = load_log($path);

The recent alerts the application has announced, newest last: each
C<< { time, id, kind, text } >>, where C<kind> is C<crossed> or C<recovered>.
An unreadable file is an empty list.

=head2 append_log

    append_log($path, $now, $id, \@crossings, \@recoveries);

Adds the announcements of one check and keeps the newest 200.

=head3 SIDE EFFECTS

Writes the alert log file, creating its directory when it is missing.

=cut
418
419sub load_log {
420
35
68
        my ($path) = @_;
421
35
157
        local ($@, $!);
422
35
297
        return () unless defined $path && -f $path;
423
17
17
18
103
        my $json = eval { Mojo::File->new($path)->slurp };
424
17
508
        return () unless defined $json;
425
17
17
28
42
        my $data = eval { decode_json($json) };
426
17
217
        return () unless ref $data eq 'HASH' && ref $data->{events} eq 'ARRAY';
427
17
22
17
13
53
23
        return grep { ref $_ eq 'HASH' } @{ $data->{events} };
428}
429
430sub append_log {
431
14
54
        my ($path, $now, $id, $crossings, $recoveries) = @_;
432
14
36
        $crossings  = [] unless ref $crossings  eq 'ARRAY';
433
14
39
        $recoveries = [] unless ref $recoveries eq 'ARRAY';
434
9
82
        my @new = ((map { { time => $now, id => $id, kind => 'crossed',   text => $_ } } @$crossings),
435
14
5
28
60
                   (map { { time => $now, id => $id, kind => 'recovered', text => $_ } } @$recoveries));
436
14
35
        return (1) unless @new;
437
14
31
        my @all = (load_log($path), @new);
438
14
181
        @all = @all[-$LOG_MAX .. -1] if @all > $LOG_MAX;
439
14
139
        return _write_json($path, { version => 1, events => \@all }, 'alert log');
440}
441
442# cmd.exe expands %NAME% before it parses the line, so a subject holding & or |
443# (it names measures and columns) could start a command of its own.
444sub _cmd_safe {
445
3
14871
        my ($text) = @_;
446
3
9
        (my $safe = $text // '') =~ tr/&|<>^%"!\r\n/ /;
447
3
9
        return $safe;
448}
449
450# Start the command with $file as its standard input, without waiting, and
451# return its process id; undef when it cannot be started.
452sub _spawn_windows {
453
0
0
        my ($command, $file) = @_;
454
0
0
        my $kept;
455
0
0
        open($kept, '<&', \*STDIN) or undef $kept;
456
0
0
        close STDIN;
457
0
0
        my $pid;
458
0
0
        if (open(STDIN, '<', $file)) {
459
0
0
                $pid = system(1, $command);     # 1: P_NOWAIT, perl on Windows only
460
0
0
                close STDIN;
461        }
462
0
0
        open(STDIN, '<&', $kept) if $kept;
463
0
0
        return defined $pid && $pid > 0 ? $pid : undef;
464}
465
466 - 475
=head2 deliver

    my ($ok, $problem) = deliver(command => ..., event => 'crossed', subject => ..., message => ..., timeout => 30);

Runs the delivery command once through the shell, with the text as its standard
input and C<BI_ALERT_EVENT>, C<BI_ALERT_SUBJECT> and C<BI_ALERT_MESSAGE_FILE>
(the same text in a file, for a command that posts a body) in its environment.
C<timeout> (seconds, default none) kills a command that does not finish.

=cut
476
477sub deliver {
478
42
3305
        my %a = @_;
479
42
108
        local ($@, $!);
480
42
42
55
954
        my ($fh, $file) = eval { tempfile(DIR => File::Spec->tmpdir, UNLINK => 0) };
481
42
7249
        return (0, 'cannot write a message file: ' . ($@ || $!)) unless $fh;
482
42
42
42
110
        my $written = print {$fh} $a{message};
483
42
710
        close $fh;
484
42
98
        unless ($written) {
485
0
0
                my $why = $!;
486
0
0
                unlink $file;
487
0
0
                return (0, "cannot write the message to '$file': $why");
488        }
489
490        # A process of its own rather than a shell redirect appended to the text: a
491        # redirect written after "cmd1; cmd2" would land on cmd2 alone.
492
42
44
        my $status = -1;
493        {
494
42
42
31
247
                local $ENV{BI_ALERT_EVENT}        = $a{event};
495
42
170
                local $ENV{BI_ALERT_SUBJECT}      = $^O eq 'MSWin32' ? _cmd_safe($a{subject}) : $a{subject};
496
42
150
                local $ENV{BI_ALERT_MESSAGE_FILE} = $file;
497
498                # Windows has no real fork: perl's imitation runs the child as a
499                # thread of this process, which in a running server (or a test) ends
500                # things it should not.  The command is spawned there instead.
501
42
93515
                my $pid = $^O eq 'MSWin32' ? _spawn_windows($a{command}, $file) : fork;
502
42
1750
                if (!defined $pid) {
503
0
0
                        unlink $file;
504
0
0
                        return (0, "cannot start the delivery command: $!");
505                }
506                elsif ($pid == 0) {
507
12
1208
                        open(STDIN, '<', $file) or POSIX::_exit(127);
508
12
0
                        exec('/bin/sh', '-c', $a{command}) or POSIX::_exit(127);
509                }
510                else {
511
30
243
                        if ($a{timeout}) {
512
24
481
                                my $until = Time::HiRes::time() + $a{timeout};
513
24
59
                                my $done;
514
24
165
                                while (!($done = waitpid($pid, POSIX::WNOHANG()))) {
515
1066
6497
                                        if (Time::HiRes::time() > $until) {
516
3
132
                                                kill 'KILL', $pid;
517
3
14835
                                                waitpid($pid, 0);
518
3
201
                                                unlink $file;
519
3
243
                                                return (0, "the delivery command did not finish in $a{timeout} seconds");
520                                        }
521
1063
53260398
                                        Time::HiRes::sleep(0.05);
522                                }
523                        }
524                        else {
525
6
2331151
                                waitpid($pid, 0);
526                        }
527
27
1257
                        $status = $?;
528                }
529        }
530
27
1149
        unlink $file;
531
27
862
        return (1) if $status == 0;
532
533
9
129
        my $why = $status == -1   ? 'cannot run it'
534                : ($status & 127) ? 'killed by signal ' . ($status & 127)
535                : 'exit ' . ($status >> 8);
536
9
348
        return (0, "the delivery command failed ($why)");
537}
538
539 - 546
=head2 check_for

    my $verdict = check_for($threshold);

The part of a stored panel threshold C<evaluate> reads: C<{ alias, op, value }>.
The alias is the threshold's C<measure>.

=cut
547
548sub check_for {
549
66
63
        my ($t) = @_;
550
66
221
        return { alias => $t->{measure}, op => $t->{op}, value => $t->{value} };
551}
552
553 - 563
=head1 AUTHOR

Nigel Horne C<< <njh@nigelhorne.com> >>

=head1 LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to the GPL2 licence terms.

=cut
564
5651;