File Coverage

File:script/bi-alert
Coverage:84.0%

linestmtbrancondsubtimecode
1#!/usr/bin/env perl
2# bi-alert -- Digest and threshold CLI for Database::BI
3#
4# Evaluates the measures of one or more saved analyses, prints a digest to
5# STDOUT for each, and exits 1 when a threshold condition is crossed.  It makes
6# no mail or network call: delivery is the caller's job, which is what lets cron
7# (or a wrapper that pipes STDOUT into mail, a webhook or a ticket) decide what
8# an alert is.  Scheduling is likewise cron's.
9#
10# Several checks in one run are the normal case: --analysis may be repeated, and
11# --threshold may be repeated and may name its analysis, so one cron line can
12# watch several measures across several saved analyses.  Every (analysis,
13# threshold) pair is reported, throttled and recovered on its own -- the state
14# file is keyed by both -- and one run is one delivery, with all the
15# announcements in the text.
16#
17# A threshold that stays crossed is not news a second time, so --suppress gives
18# an (analysis, threshold) pair a throttle: the first crossing is announced, and
19# repeats inside the period are not.  The memory for that is one small JSON file
20# in the model directory, written only when --suppress is used (or once such a
21# file exists); with no --suppress the script behaves exactly as it always has
22# and writes nothing.  When the threshold clears, its entry is dropped, so the
23# next crossing alerts straight away rather than staying quiet about it.
24#
25# The end of a crossing is news as well, and --recovery announces it: the run
26# that sees the threshold clear prints THRESHOLD RECOVERED and exits 3, so a
27# wrapper that mails on a non-zero status mails the recovery too.  The state
28# file is what makes this possible, since an entry is the record of a crossing
29# that was announced: finding one is what tells this run that an incident has
30# ended rather than that a threshold was never crossed.  That is also why
31# --recovery keeps that file even with no --suppress to throttle, and why the
32# recovery is said once per crossing rather than on every run after it.
33#
34# Delivery is optional as well: --notify-cmd runs a command when, and only
35# when, something is announced, with the run's own text on STDIN and the
36# verdict in the environment.  That makes a cron line one command instead of a
37# shell wrapper around this one, and it keeps the rule the script has always
38# had -- nothing leaves the machine unless somebody asked it to.
39#
40# Usage:
41#   bi-alert --analysis <id> [--analysis <id> ...]
42#             [--threshold <alias>:<op>:<value>] [--threshold <analysis>:<alias>:<op>:<value> ...]
43#             [--suppress <duration>] [--state-file <path>] [--recovery]
44#             [--notify-cmd <command>]
45#             [--model-dir <dir>] [--data-dir <dir>] [--dry-run]
46#
47# Exit codes:  0 = ok / nothing announced (not crossed, or already announced)
48#              1 = a threshold crossed, and is announced
49#              2 = error (bad args, analysis not found, data unavailable)
50#              3 = a crossing that was announced has ended, and is announced
51#                  as a recovery (--recovery); 1 wins if a run announces both
52
53
59
59
59
75624
27
470
use strict;
54
59
59
59
52
24
978
use warnings;
55
56# Database::BI's own modules from a source folder, as the other scripts do;
57# installed, they are on @INC already.
58
59
59
59
4983
18497
2270
use FindBin qw($Bin);
59
59
59
59
4654
10426
91
use lib "$Bin/../lib";
60
61
59
59
59
12458
174799
86
use Getopt::Long qw(GetOptions :config no_ignore_case);
62
59
59
59
10849
102495
104
use POSIX       qw(_exit);
63
59
59
59
25758
21
398
use File::Spec;
64
59
59
59
15874
284072
1052
use File::Temp qw(tempfile);
65
59
59
59
110
28
557
use File::Path qw(make_path);
66
59
59
59
4849
3131775
1134
use Mojo::JSON qw(decode_json encode_json);
67
59
59
59
7246
300283
787
use Mojo::File;
68
59
59
59
28527
71
349
use Database::BI::I18N ();
69
59
59
59
5933
56
1674382
use Database::BI::Alert ();
70
71# Messages in the language the locale names: LANG=en_US.UTF-8 is American
72# English, anything else British (CGI::Lingua chooses).
73
59
1264095
$Database::BI::I18N::LANGUAGE = Database::BI::I18N::from_locale();
74
75# ---------------------------------------------------------------------------
76# Parse arguments
77# ---------------------------------------------------------------------------
78
79
59
598
my ($opt_analysis, $opt_thresholds, $opt_model_dir, $opt_data_dir, $opt_dry_run,
80        $opt_help, $opt_suppress, $opt_state_file, $opt_recovery, $opt_notify);
81
82GetOptions(
83        'analysis|a=s@'   => \$opt_analysis,
84        'threshold|t=s@'  => \$opt_thresholds,
85        'suppress|s=s'    => \$opt_suppress,
86        'state-file=s'    => \$opt_state_file,
87        'recovery|r'      => \$opt_recovery,
88        'notify-cmd=s'    => \$opt_notify,
89        'model-dir|m=s'   => \$opt_model_dir,
90        'data-dir|d=s'    => \$opt_data_dir,
91        'dry-run|n'       => \$opt_dry_run,
92        'help|h'          => \$opt_help,
93
59
0
0
280
0
0
) or do { usage(); exit 2 };
94
95
59
1
1
32632
2
17
if ($opt_help) { usage(); exit 0 }
96
97# Each --analysis is one saved analysis to check, so repeating it checks several
98# in one run.  A repeated id is one report rather than two, and the first one
99# given is the analysis a threshold without a prefix belongs to.
100
58
67
my @analysis_ids;
101my %listed;
102
58
58
58
106
for my $given (@{ $opt_analysis // [] }) {
103
61
72
        my $id = defined $given ? $given : '';
104
61
61
        $id =~ s/\A\s+//;
105
61
63
        $id =~ s/\s+\z//;
106
61
65
        next unless length $id;
107
61
118
        push @analysis_ids, $id unless $listed{$id}++;
108}
109
110
58
60
unless (@analysis_ids) {
111
1
20
        warn "bi-alert: --analysis <id> is required\n";
112
1
18
        exit 2;
113}
114
115# A delivery command is the one option whose absence is a decision of its own,
116# so an empty one is a mistake rather than a way to say "deliver nowhere".
117
57
22
my $notify_cmd;
118
57
72
if (defined $opt_notify) {
119
16
12
        $notify_cmd = $opt_notify;
120
16
94
        $notify_cmd =~ s/\A\s+|\s+\z//g;
121
16
11
        unless (length $notify_cmd) {
122
1
21
                warn "bi-alert: --notify-cmd must name a command to run\n";
123
1
17
                exit 2;
124        }
125}
126
127# With a delivery command the run's output is collected rather than printed as
128# it is produced, so the command receives exactly what a wrapper would have
129# piped into it -- the digest and the verdict, in order.  The END block is what
130# prints it on a path that exits before delivery, such as a bad threshold.
131
56
34
my $message   = '';
132
56
29
my $buffering = 0;
133
56
28
my $buffer_fh;
134
56
66
start_buffering() if defined $notify_cmd;
135
136
56
56
my $model_dir = $opt_model_dir // '.bi';
137
56
58
my $data_dir  = $opt_data_dir  // 'data';
138
139# The throttle period, in seconds.  Absent or 0 means no throttling, which is
140# also when no state is kept at all.
141
56
32
my $suppress = 0;
142
56
110
if (defined $opt_suppress && length $opt_suppress) {
143
37
74
        $suppress = parse_duration($opt_suppress);
144
37
45
        unless (defined $suppress) {
145
1
21
                warn "bi-alert: --suppress must be a duration such as 30m, 6h or 1d; got '$opt_suppress'\n";
146
1
18
                exit 2;
147        }
148}
149
150# Where the throttle remembers what it has announced.  Model directory by
151# default, beside analyses.json, so a cron job and the web app share one home
152# for state; --state-file points it somewhere else, which is what a second
153# machine or a test wants.
154
55
139
my $state_file = $opt_state_file // File::Spec->catfile($model_dir, 'alerts-state.json');
155
156# ---------------------------------------------------------------------------
157# Load analysis
158# ---------------------------------------------------------------------------
159
160
55
275
my $analyses_path = File::Spec->catfile($model_dir, 'analyses.json');
161
55
311
unless (-f $analyses_path) {
162
0
0
        warn "bi-alert: analyses file not found: $analyses_path\n";
163
0
0
        exit 2;
164}
165
166
55
55
34
318
my $analyses_json = eval { Mojo::File->new($analyses_path)->slurp };
167
55
3581
unless (defined $analyses_json) {
168
0
0
        warn "bi-alert: cannot read $analyses_path: $!\n";
169
0
0
        exit 2;
170}
171
172
55
55
41
145
my $analyses = eval { decode_json($analyses_json) };
173
55
981
if ($@ || !$analyses) {
174
0
0
        warn "bi-alert: cannot parse $analyses_path: $@\n";
175
0
0
        exit 2;
176}
177
178# ---------------------------------------------------------------------------
179# Open each analysis's dataset and compute its measures
180# ---------------------------------------------------------------------------
181
182# A group is one analysis: its digest, its rows, and the checks that name it.
183# Everything below works per group, so several analyses in one run are several
184# independent reports rather than one merged one.
185
55
41
my @groups;
186
187
55
62
for my $id (@analysis_ids) {
188
58
53
        my $a = $analyses->{$id};
189
58
81
        unless (defined $a) {
190
1
20
                warn "bi-alert: analysis '$id' not found\n";
191
1
32
                exit 2;
192        }
193
194
57
57
67
151
        my @datasets = @{ $a->{datasets} // [] };
195
57
73
        unless (@datasets) {
196
0
0
                warn "bi-alert: analysis '$id' has no datasets\n";
197
0
0
                exit 2;
198        }
199
200
57
99
        my $spec = $datasets[0]{spec} // '';
201
57
196
        unless ($spec =~ /\A(?:table|path):/) {
202
0
0
                warn "bi-alert: dataset spec '$spec' is not a local file spec\n";
203
0
0
                exit 2;
204        }
205
206        # table:<name>/<table> and path:<file>#<table> name one table of a file.
207
57
55
        my ($file_path, $internal);
208
57
178
        if ($spec =~ /\Atable:(.+)\z/) {
209
2
2
                my $table = $1;
210
2
2
                ($table, $internal) = ($1, $2) if $table =~ m{\A([^/]+)/(.+)\z};
211
2
6
                for my $ext (qw(csv tsv psv xlsx xml sql sqlite sqlite3 db json jsonl ndjson)) {
212
2
7
                        my $p = File::Spec->catfile($data_dir, "$table.$ext");
213
2
2
2
5
1
1
                        if (-f $p) { $file_path = $p; last }
214                }
215        }
216        elsif ($spec =~ /\Apath:(.+)\z/) {
217
55
15884
                require Database::BI::Model::DataSource;
218
55
159
                ($file_path, $internal) = Database::BI::Model::DataSource::split_path($1);
219        }
220
221
57
197
        unless (defined $file_path && -f $file_path) {
222
0
0
                warn "bi-alert: cannot locate data file for spec '$spec'\n";
223
0
0
                exit 2;
224        }
225
226        # Load records via Database::Abstraction through DataSource if available,
227        # otherwise fall back to a simple CSV parse for the most common case.
228
57
45
        my ($records, $columns);
229
57
115
        eval {
230
57
740
                require Database::BI::Model::DataSource;
231                my $src = Database::BI::Model::DataSource->new(
232                        file   => $file_path,
233
57
57
57
115
116
77
                        table  => do { (my $t = $file_path) =~ s/.*\///; $t =~ s/\.[^.]+\z//; $t },
234
57
57
57
84
101
170
                        directory => do { (my $d = $file_path) =~ s|/[^/]+\z||; $d },
235                        defined $internal ? (internal_table => $internal) : (),
236                );
237
0
0
                $records = $src->fetch_all // [];
238
0
0
0
0
                $columns = $src->columns // [sort keys %{ $records->[0] // {} }];
239        };
240
57
7386
        if ($@) {
241                # Minimal CSV fallback so the script works even without the full stack.
242
57
57
0
46
17814
0
                eval { require Text::CSV_XS } or do { require Text::CSV };
243
57
197346
                my $csv_class = $INC{'Text/CSV_XS.pm'} ? 'Text::CSV_XS' : 'Text::CSV';
244
57
43
                eval {
245
57
145
                        my $csv = $csv_class->new({ binary => 1, auto_diag => 1 });
246
57
3898
                        open(my $fh, '<:utf8', $file_path) or die $!;
247
57
1128
                        $columns = $csv->getline($fh);
248
57
49
                        $records = [];
249
57
193
                        while (my $row = $csv->getline($fh)) {
250
253
143
                                my %h;
251
253
279
                                @h{@$columns} = @$row;
252
253
544
                                push @$records, \%h;
253                        }
254
57
3412
                        close $fh;
255                };
256
57
101
                if ($@) {
257
0
0
                        warn "bi-alert: cannot read data file '$file_path': $@";
258
0
0
                        exit 2;
259                }
260        }
261
262
57
86
        my $row_count = scalar @$records;
263
264        # The measures the analysis defines (sum avg min max count count_distinct).
265
57
157
        my $results = Database::BI::Alert::measure_results([ Database::BI::Alert::measures_of($a) ], $records);
266
267        push @groups, {
268                id      => $id,
269
57
328
                name    => $a->{name} // '',
270                rows    => $row_count,
271                results => $results,
272                checks  => [],
273        };
274}
275
276# ---------------------------------------------------------------------------
277# Pair every threshold with its analysis
278# ---------------------------------------------------------------------------
279
280# One threshold is one (analysis, measure, comparison, value).  The analysis is
281# the prefix when the spec has one, otherwise the first --analysis, which is
282# what keeps a single-analysis command line exactly as it was.
283
54
57
44
89
my %by_id = map { $_->{id} => $_ } @groups;
284
54
50
my $multi = @groups > 1;
285
54
25
my %seen_check;
286
287
54
324
105
803
my %ops = map { $_ => 1 } Database::BI::Alert::operators();
288
289
54
54
84
81
for my $given (@{ $opt_thresholds // [] }) {
290
61
67
        my $text = defined $given ? $given : '';
291
61
62
        $text =~ s/\A\s+//;
292
61
59
        $text =~ s/\s+\z//;
293
61
51
        next unless length $text;
294
295
61
48
        my ($owner, $alias, $op, $tval);
296
297        # The four-field form names its analysis.  An alias that happens to read
298        # like a saved analysis id would be read as a prefix, which is why the
299        # prefix is the documented spelling and ids are not measures.
300
61
247
        if ($text =~ /\A([^:]+):([^:]+):([^:]+):(.+)\z/ && $analyses->{$1}) {
301
4
11
                ($owner, $alias, $op, $tval) = ($1, $2, $3, $4);
302
4
8
                unless ($by_id{$owner}) {
303
1
22
                        warn "bi-alert: threshold '$text' names analysis '$owner', which is not given with --analysis\n";
304
1
29
                        exit 2;
305                }
306        }
307        elsif ($text =~ /\A([^:]+):([^:]+):(.+)\z/) {
308
56
128
                ($owner, $alias, $op, $tval) = ($analysis_ids[0], $1, $2, $3);
309        }
310        else {
311
1
19
                warn "bi-alert: --threshold must be <measure>:<op>:<value> (e.g. count:gt:1000)"
312                        . ", or <analysis>:<measure>:<op>:<value>\n";
313
1
28
                exit 2;
314        }
315
316
59
72
        unless (exists $ops{$op}) {
317
0
0
                warn "bi-alert: unsupported operator '$op'; allowed: gt ge lt le eq ne\n";
318
0
0
                exit 2;
319        }
320
321
59
44
        my $group = $by_id{$owner};
322
59
81
        unless (defined $group->{results}{$alias}) {
323
1
19
                warn "bi-alert: measure alias '$alias' not found in analysis '$owner'\n";
324
1
28
                exit 2;
325        }
326
327        # The same pair written twice is one check, not a request to be told
328        # twice: repeating the option is how a command line grows.
329
58
83
        my $pair = "$owner|$alias:$op:$tval";
330
58
101
        next if $seen_check{$pair}++;
331
332
57
57
28
171
        push @{ $group->{checks} }, { alias => $alias, op => $op, value => $tval };
333}
334
335# ---------------------------------------------------------------------------
336# Report each analysis, then each of its thresholds
337# ---------------------------------------------------------------------------
338
339# BI_ALERT_NOW replaces the clock, so a test can step over a suppression period
340# without sleeping through it; unset, empty or unreadable means now.
341my $now = (defined $ENV{BI_ALERT_NOW} && $ENV{BI_ALERT_NOW} =~ /\A\d+\z/)
342
51
181
        ? $ENV{BI_ALERT_NOW} + 0
343        : time();
344
345# --recovery needs the state file with or without a period: the entry is the
346# record of a crossing that was announced, and so the only thing that can say an
347# incident has ended.
348
51
152
my $in_use  = $suppress > 0 || $opt_recovery || -f $state_file;
349
51
114
my $state   = $in_use ? load_state($state_file) : { version => 1, alerts => {} };
350
51
37
my $changed = 0;
351
51
41
my (@crossings, @recoveries);
352
353
51
51
for my $group (@groups) {
354
54
33
        my $id  = $group->{id};
355
54
75
        my $tag = $multi ? " ($id)" : '';
356
357
54
155
        print "Analysis: $group->{name}$tag\n";
358
54
61
        print "Rows:     $group->{rows}\n";
359
54
54
27
59
        if (%{ $group->{results} }) {
360
54
28
                print "Measures:\n";
361
54
54
36
66
                for my $k (sort keys %{ $group->{results} }) {
362
56
72
                        my $v = defined $group->{results}{$k} ? $group->{results}{$k} : '(null)';
363
56
73
                        print "  $k = $v\n";
364                }
365        }
366        else {
367
0
0
                print "No measures configured.\n";
368        }
369
370        my $outcome = Database::BI::Alert::evaluate(
371                id => $id, results => $group->{results}, checks => $group->{checks},
372
54
151
                state => $state, now => $now, suppress => $suppress, suppress_text => $opt_suppress,
373                recovery => $opt_recovery, multi => $multi, keep => $in_use,
374        );
375
54
54
49
89
        print "$_\n" for @{ $outcome->{lines} };
376
54
54
39
35
        push @crossings,  @{ $outcome->{crossings} };
377
54
54
41
36
        push @recoveries, @{ $outcome->{recoveries} };
378
54
92
        $changed = 1 if $outcome->{changed};
379}
380
381# Delivery is the only thing that leaves the machine, so it runs once the words
382# are final and before the throttle is written: a crossing nobody was told
383# about is not one the throttle may forget.  One run is one delivery, however
384# many checks it announced, so a cron line that checks twenty thresholds does
385# not send twenty mails.
386
51
28
my $delivery_failed = 0;
387
51
47
my @announced       = (@crossings, @recoveries);
388
51
91
if (defined $notify_cmd && @announced) {
389
13
17
        if ($opt_dry_run) {
390
1
1
                print "Notify: would run '$notify_cmd' (--dry-run)\n";
391        }
392        else {
393                # BI_ALERT_EVENT names the more urgent of the two: a crossing means
394                # something is wrong now, a recovery means something stopped being
395                # wrong, and a run that has both is a run with a problem in it.
396
12
26
                my $event = @crossings ? 'crossed' : 'recovery';
397
12
8
                my @parts;
398
12
36
                push @parts, sprintf('%d threshold crossing%s',
399                        scalar @crossings, @crossings == 1 ? '' : 's') if @crossings;
400
12
24
                push @parts, sprintf('%d recover%s',
401                        scalar @recoveries, @recoveries == 1 ? 'y' : 'ies') if @recoveries;
402
12
12
                my $subject = @announced == 1 ? $announced[0] : join(', ', @parts);
403
12
26
                $delivery_failed = 1
404                        unless deliver($notify_cmd, $event, $subject);
405        }
406}
407
408# A dry run reports what would happen and leaves the throttle where it was, so
409# running one cannot use up the alert a later real run depends on.  A delivery
410# that failed is the same case in another form: the alert has not reached
411# anybody yet, so recording it would spend the period on nothing.
412
45
275
save_state($state_file, $state)
413        if $changed && $in_use && !$opt_dry_run && !$delivery_failed;
414
415# A recovery is a third answer, not an error: 3 is what lets a wrapper send the
416# all-clear, which 0 cannot do -- a wrapper keyed on a non-zero status would
417# also fire on every suppressed repeat -- and it leaves 1 meaning exactly "a
418# crossing was announced just now".  When one run announces both, 1 wins: a
419# threshold that is still crossed is not outranked by an all-clear elsewhere.
420
421# Anything still buffered is printed here rather than by the END block, so the
422# output order is the one the run produced.
423
45
98
flush_output();
424
425
45
1754
exit(@crossings ? 1 : @recoveries ? 3 : 0);
426
427# ---------------------------------------------------------------------------
428
429sub usage {
430
1
4
        print <<'USAGE';
431Usage: bi-alert --analysis <id> [--analysis <id> ...] [OPTIONS]
432
433  --analysis, -a <id>           Analysis id; required, and repeatable: each one
434                                is reported in full
435  --threshold, -t <m>:<op>:<v>  Threshold: measure alias, operator (gt|ge|lt|le|eq|ne), value.
436                                Repeatable; prefix it with <analysis>: to check
437                                an analysis other than the first
438  --suppress,  -s <duration>    Announce a threshold at most once per period
439                                (30, 30s, 15m, 6h, 2d, 1w; default: no throttling)
440  --state-file <path>           Where the throttle remembers its last alert
441                                (default: <model-dir>/alerts-state.json)
442  --recovery,  -r               Announce the end of a crossing as well as its
443                                start: THRESHOLD RECOVERED, exit 3
444  --notify-cmd <command>        Run this command when an alert or a recovery is
445                                announced, instead of a shell wrapper around
446                                this script; it gets the run's text on STDIN
447  --model-dir, -m <dir>         Model directory containing analyses.json (default: .bi)
448  --data-dir,  -d <dir>         Data directory (default: data)
449  --dry-run,   -n               Report only: no digest is recorded against the
450                                throttle and --notify-cmd is not run
451  --help,      -h               Show this help
452
453Exit codes:
454  0  OK; nothing announced -- not crossed, or crossed and already announced
455  1  A threshold crossed, and is announced
456  2  Error
457  3  A crossing that was announced has ended, and is announced as a recovery
458
459Both options may be given more than once, so one run can watch several saved
460analyses and several measures.  A threshold with no analysis prefix belongs to
461the first --analysis, and <analysis>:<measure>:<op>:<value> names another one of
462those listed.  Each (analysis, threshold) pair is a check of its own: it gets
463its own line in the report, its own entry in the state file, its own throttle
464period and its own recovery.  One crossing neither silences nor recovers
465another, so a run that watches twenty thresholds reports exactly what each of
466them is doing.
467
468  bi-alert --analysis abc123 --analysis def456 \
469           --threshold count:gt:1000 --threshold def456:sum:lt:50 \
470           --suppress 1h --recovery
471
472A run that announces both a crossing and a recovery exits 1: a threshold that
473is still crossed is the more urgent news, and 3 keeps meaning "an all-clear and
474nothing else".
475
476The digest goes to STDOUT and nothing leaves the machine until you say where.
477Pipe STDOUT into mail, curl or a ticket creator if the alert has to travel, or
478let --notify-cmd run that for you:
479
480  bi-alert --analysis abc123 --threshold count:gt:1000 --suppress 1h \
481           --notify-cmd 'mail -s "$BI_ALERT_SUBJECT" oncall@example.com'
482
483The command runs through the shell, exactly once per run, and only when
484something is announced: a crossing (exit 1), or a recovery with -r (exit 3).  A
485suppressed repeat, a threshold that is not crossed, an error and a --dry-run run
486it not at all, so it never says the same thing twice, and twenty checks still
487send one mail.  The whole run's text arrives on STDIN, and three variables say
488what it is:
489
490  BI_ALERT_EVENT         crossed if any crossing was announced, else recovery
491  BI_ALERT_SUBJECT       the verdict line when one thing was announced, else a
492                         count (2 threshold crossings, 1 recovery)
493  BI_ALERT_MESSAGE_FILE  the same text in a file, for a command that cannot
494                         read STDIN: curl -d @$BI_ALERT_MESSAGE_FILE ...
495
496A delivery that fails is reported on STDERR and the exit status stays what it
497would have been, but the crossing is not written to the state file: the alert
498has not reached anybody, so the next run announces it again rather than losing
499it for the whole period.
500
501Cron every five minutes, mailing only what is announced (exit 1) or an error
502(exit 2), with an hourly ceiling on repeats.  Add -r to that line and the same
503mail carries the recoveries (exit 3) when thresholds clear:
504
505  */5 * * * * cd /path/to/app && ./script/bi-alert --analysis abc123 \
506      --analysis def456 --threshold count:gt:1000 \
507      --threshold def456:sum:lt:50 --suppress 1h --recovery \
508      --notify-cmd 'mail -s "$BI_ALERT_SUBJECT" oncall@example.com'
509
510Without --notify-cmd the same line needs a wrapper to pipe STDOUT into mail:
511
512  */5 * * * * cd /path/to/app && out=$(./script/bi-alert --analysis abc123 \
513      --threshold count:gt:1000 --suppress 1h 2>&1) \
514      || printf '%s\n' "$out" | mail -s 'bi-alert' you
515
516A run inside the period says THRESHOLD SUPPRESSED and exits 0, so a wrapper
517keyed on the exit status stays quiet; THRESHOLD CLEARED, also exit 0, is said
518once when the crossing ends.  The state file is one small JSON object, keyed by
519analysis and threshold; delete it to make every threshold alert again.
520
521With --recovery that ending is announced instead of merely reported: the run
522prints THRESHOLD RECOVERED and exits 3, so the wrapper above -- which mails on
523any non-zero status -- mails the all-clear as well as the alert, and a wrapper
524that should not is a wrapper that does not pass --recovery.  It is said once per
525crossing, and only for a crossing that was announced, because the state file is
526what remembers it; that is also why --recovery keeps the state file even with no
527--suppress.
528USAGE
529}
530
531# start_buffering() -> $bool
532#
533# Sends everything the run prints into $message instead of STDOUT, so the
534# delivery command reads the digest and the verdict as one text.  Nothing is
535# lost when a run exits before delivery: flush_output() is called on the way
536# out, and the END block is there for the paths that exit without reaching it.
537sub start_buffering {
538
15
17
        return 1 if $buffering;
539
15
78
        open(my $fh, '>', \$message) or return 0;
540
15
10
        $buffer_fh = $fh;
541
15
21
        select($buffer_fh);
542
15
14
        $buffering = 1;
543
15
2
        return 1;
544}
545
546# flush_output() -> ()
547#
548# Puts STDOUT back and prints what was collected.  Safe to call when nothing
549# was collected, and safe to call twice, so every exit path can call it.
550sub flush_output {
551
110
201
        return unless $buffering;
552
15
15
        select(STDOUT);
553
15
13
        $buffering = 0;
554        # STDOUT is a pipe under cron, so the buffer has to be pushed out here
555        # rather than at exit: a warning on STDERR must not arrive before the
556        # digest it belongs under, and a delivery command's own output must not
557        # arrive before the text it was handed.
558
15
24
        $| = 1;
559
15
254
        print $message;
560
15
12
        return;
561}
562
563
53
9982
END { flush_output() }
564
565# deliver($command, $event, $verdict) -> $bool
566#
567# Runs the delivery command once, with the run's text as its STDIN (see
568# Database::BI::Alert::deliver), and returns whether it succeeded.  Failure is
569# reported here and turned into "not delivered" by the caller, which then leaves
570# the throttle alone.
571sub deliver {
572
12
10
        my ($command, $event, $verdict) = @_;
573
574        # The announcement is complete by the time this is called.  Printing it
575        # first keeps the run's own output in the order it was produced, and it
576        # means the command's own output cannot land in the message.
577
12
20
        flush_output();
578
579
12
36
        my ($ok, $problem) = Database::BI::Alert::deliver(
580                command => $command, event => $event, subject => $verdict, message => $message,
581        );
582
6
88
        return 1 if $ok;
583
2
17
        if ($problem =~ /\Athe delivery command failed (\(.*\))\z/) {
584
2
56
                warn "bi-alert: --notify-cmd failed $1; the alert is not recorded, so the next run announces it again\n";
585        } else {
586
0
0
                warn "bi-alert: $problem\n";
587        }
588
2
29
        return 0;
589}
590
591# parse_duration($text) -> $seconds | undef; the same rules as the web application.
592
37
93
sub parse_duration { return Database::BI::Alert::parse_duration(@_) }
593
594# load_state($path) -> \%state; a damaged file is reported and treated as empty.
595sub load_state {
596
43
100
        my ($state, $problem) = Database::BI::Alert::load_state(@_);
597
43
73
        warn "bi-alert: $problem\n" if defined $problem;
598
43
32
        return $state;
599}
600
601# save_state($path, \%state) -> $bool; the alert has been announced by then, so a
602# failed write is reported and the next run repeats it rather than losing it.
603sub save_state {
604
23
64
        my ($ok, $problem) = Database::BI::Alert::save_state(@_);
605
23
32
        warn "bi-alert: $problem\n" unless $ok;
606
23
27
        return $ok;
607}
608