Debian Codegraph @

lib/App/Yath/Plugin/Notify.pm

raw
1 package App::Yath::Plugin::Notify;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Test2::Harness::Util::JSON qw/encode_json/;
8 use Test2::Harness::Util qw/mod2file/;
9
10 use Sys::Hostname qw/hostname/;
11
12 use Carp qw/croak confess/;
13
14 use App::Yath::Options;
15
16 use parent 'App::Yath::Plugin';
17 use Test2::Harness::Util::HashBase qw/-final -tries -problems -problem_cids +text_mod +text_mod_handles_events +text_mod_fail/;
18
19 # Notifications only apply to commands which build a run.
20 sub applicable {
21 my ($option, $options) = @_;
22
23 return 1 if $options->included->{'App::Yath::Options::Run'};
24 return 0;
25 }
26
27 option_group {prefix => 'notify', category => "Notification Options", applicable => \&applicable} => sub {
28 option slack => (
29 type => 'm',
30 description => "Send results to a slack channel and/or user",
31 long_examples => [" '#foo'", " '\@bar'"],
32 );
33
34 option slack_fail => (
35 type => 'm',
36 description => "Send failing results to a slack channel and/or user",
37 long_examples => [" '#foo'", " '\@bar'"],
38 );
39
40 option slack_url => (
41 type => 's',
42 description => "Specify an API endpoint for slack webhook integrations",
43 long_examples => [" https://hooks.slack.com/..."],
44 );
45
46 option slack_owner => (
47 type => 'b',
48 description => "Send slack notifications to the slack channels/users listed in test meta-data when tests fail.",
49 default => 0,
50 );
51
52 option no_batch_slack => (
53 type => 'b',
54 default => 0,
55 description => 'Usually owner failures are sent as a single batch at the end of testing. Toggle this to send failures as they happen.',
56 );
57
58 option email_from => (
59 type => 's',
60 long_examples => [' [email protected]'],
61 description => "If any email is sent, this is who it will be from",
62 default => sub {
63 my $user = getlogin() || scalar(getpwuid($<)) || $ENV{USER} || 'unknown';
64 my $host = hostname() || 'unknown';
65 return "${user}\@${host}";
66 },
67 );
68
69 option email => (
70 type => 'm',
71 long_examples => [' [email protected]'],
72 description => "Email the test results to the specified email address(es)",
73 );
74
75 option email_fail => (
76 type => 'm',
77 long_examples => [' [email protected]'],
78 description => "Email failing results to the specified email address(es)",
79 );
80
81 option email_owner => (
82 type => 'b',
83 description => 'Email the owner of broken tests files upon failure. Add `# HARNESS-META-OWNER [email protected]` to the top of a test file to give it an owner',
84 default => 0,
85 );
86
87 option no_batch_email => (
88 type => 'b',
89 default => 0,
90 description => 'Usually owner failures are sent as a single batch at the end of testing. Toggle this to send failures as they happen.',
91 );
92
93 option text => (
94 type => 's',
95 alt => ['message', 'msg'],
96 description => "Add a custom text snippet to email/slack notifications",
97 );
98
99 option text_module => (
100 type => 's',
101 alt => ['message_module'],
102 description => "Use the specified module to generate messages for emails and/or slack.",
103 );
104
105 post sub {
106 my %params = @_;
107
108 my $settings = $params{settings};
109 my $options = $params{options};
110
111 my $set_by_cli = $options->set_by_cli->{notify};
112
113 # Should we use email?
114 if (@{$settings->notify->email} || $settings->notify->email_owner) {
115 $settings->notify->field(email_owner => 1) unless $set_by_cli->{email_owner};
116
117 # Do we have Email::Stuffer?
118 eval { require Email::Stuffer; 1 } or die "Cannot use --email-owner without Email::Stuffer, which is not installed.\n";
119
120 push @{$settings->harness->plugins} => __PACKAGE__->new() unless grep { $_->isa(__PACKAGE__) } @{$settings->harness->plugins};
121 }
122
123 my $use_slack = grep { $settings->notify->$_ } qw/slack_url slack_owner/;
124 $use_slack ||= grep { @{$settings->notify->$_} } qw/slack slack_fail/;
125 if ($use_slack) {
126 die "slack url must be provided in order to use slack" unless $settings->notify->slack_url;
127
128 eval { require HTTP::Tiny; 1 } or die "Cannot use slack without HTTP::Tiny which is not installed.\n";
129
130 die "HTTP::Tiny reports that it does not support SSL, cannot use slack without ssl."
131 unless HTTP::Tiny::can_ssl();
132
133 $settings->notify->field(slack_owner => 1) unless $set_by_cli->{slack_owner};
134
135 push @{$settings->harness->plugins} => __PACKAGE__->new() unless grep { $_->isa(__PACKAGE__) } @{$settings->harness->plugins};
136 }
137 };
138 };
139
140 sub text_mod {
141 my $self = shift;
142 my ($settings) = @_;
143
144 croak 'settings is a required argument' unless $settings;
145
146 return $self->{+TEXT_MOD} if exists $self->{+TEXT_MOD};
147
148 if (my $tm = $settings->notify->text_module) {
149 my $file = mod2file($tm);
150 if (eval { require $file; 1 }) {
151 my $inst = $tm->can('new') ? $tm->new() : $tm;
152 $self->{+TEXT_MOD_HANDLES_EVENTS} = $inst->can('handle_event') ? 1 : 0;
153 return $self->{+TEXT_MOD} = $inst;
154 }
155 else {
156 my $err = $@;
157 warn "Cannot use module '$tm' for notification text generation: $err";
158 chomp($self->{+TEXT_MOD_FAIL} = $err);
159 }
160 }
161
162 $self->{+TEXT_MOD_HANDLES_EVENTS} = 0;
163 return $self->{+TEXT_MOD} = undef;
164 }
165
166 sub handle_event {
167 my $self = shift;
168 my ($e, $settings) = @_;
169
170 my $f = $e->facet_data;
171
172 $self->record_problem($f);
173
174 my $tm = $self->text_mod($settings);
175 if ($tm && $self->{+TEXT_MOD_HANDLES_EVENTS}) {
176 $tm->handle_event($e, $f, settings => $settings, notify => $self);
177 }
178
179 return $self->handle_job_end($e, $f, $settings) if $f->{harness_job_end};
180 return $self->handle_final($e, $f, $settings) if $f->{harness_final};
181
182 return;
183 }
184
185 sub record_problem {
186 my $self = shift;
187 my ($f) = @_;
188
189 return unless $self->has_fail_or_error($f);
190
191 my $job_id = $f->{harness}->{job_id};
192 my $job_try = $f->{harness}->{job_try} // 0;
193
194 push @{$self->{+PROBLEMS}->{$job_id}->{$job_try}} => $self->prune_subtests($f);
195 }
196
197 sub has_fail_or_error {
198 my $self = shift;
199 my ($f, %params) = @_;
200
201 return 0 if $f->{trace}->{nested} && !$params{allow_nested};
202 return 0 if $f->{amnesty} && @{$f->{amnesty}};
203
204 my $out = 0;
205
206 my $cid = $f->{trace}->{cid};
207 $out = 1 if $cid && $self->{+PROBLEM_CIDS}->{$cid} && $f->{info} && @{$f->{info}};
208 $out = 1 if $f->{errors} && @{$f->{errors}};
209 $out = 1 if $f->{assert} && !$f->{assert}->{pass};
210
211 $self->{+PROBLEM_CIDS}->{$cid} = 1 if $cid && $out;
212
213 return $out;
214 }
215
216 sub prune_subtests {
217 my $self = shift;
218 my ($f) = @_;
219
220 my $p = $f->{parent} // return $f;
221 my $c = $p->{children} // return $f;
222
223 return $f unless @$c;
224
225 my $out = {};
226 $out->{$_} = $f->{$_} for grep { $f->{$_} } qw/assert about trace errors info harness control/;
227 $out->{parent} = {%$p, children => [map { $self->prune_subtests($_) } grep { $self->has_fail_or_error($_, allow_nested => 1) } @$c]};
228
229 return $out;
230 }
231
232 sub handle_final {
233 my $self = shift;
234 my ($e, $f, $settings) = @_;
235
236 $self->{+FINAL} = $e;
237 }
238
239 sub handle_job_end {
240 my $self = shift;
241 my ($e, $f, $settings) = @_;
242
243 return unless $f->{harness_job_end}->{fail};
244
245 my $job_id = $f->{harness}->{job_id};
246
247 if ($f->{harness_job_end}->{retry}) {
248 $self->{+TRIES}->{$job_id}++;
249 return;
250 }
251
252 my @args = ($e, $f, $self->{+TRIES}->{$job_id}, $settings);
253
254 $self->send_job_notification_slack(@args);
255 $self->send_job_notification_email(@args);
256 }
257
258 sub send_job_notification_slack {
259 my $self = shift;
260
261 my ($e, $f, $tries, $settings) = @_;
262
263 return unless $settings->notify->no_batch_slack;
264
265 my $tf = Test2::Harness::TestFile->new(file => $f->{harness_job_end}->{abs_file});
266
267 my @slack;
268 push @slack => $tf->meta('slack') if $settings->notify->slack_owner;
269 push @slack => @{$settings->notify->slack_fail};
270
271 return unless @slack;
272
273 my $text = $self->gen_text(scope => 'job', service => 'slack', settings => $settings, file => $tf, tries => $tries);
274
275 $self->_send_slack($text, $settings, @slack);
276 }
277
278 sub gen_slack_job_text {
279 my $self = shift;
280 my %params = @_;
281
282 my $settings = $params{settings} // croak "'settings' is required";
283 my $tf = $params{file} // croak "'file' is required";
284 my $tries = $params{tries} // 0;
285
286 my $host = hostname();
287 my $file = $tf->relative;
288
289 return join "\n\n" => grep { $_ }
290 $settings->notify->text,
291 "Failed test on $host: '$file'.",
292 $tries ? ("Test was run " . (1 + $tries) . " time(s).") : (),
293 join "\n" => map {"> <$_|$_>"} @{$settings->run->links};
294 }
295
296 sub _send_slack {
297 my $self = shift;
298 my ($text, $settings, @to) = @_;
299
300 require HTTP::Tiny;
301 my $ht = HTTP::Tiny->new();
302
303 for my $dest (@to) {
304 my $r = $ht->post(
305 $settings->notify->slack_url,
306 {
307 headers => {'content-type' => 'application/json'},
308 content => encode_json({channel => $dest, text => $text}),
309 },
310 );
311 warn "Failed to send slack message to '$dest'" unless $r->{success};
312 }
313 }
314
315 sub send_job_notification_email {
316 my $self = shift;
317
318 my ($e, $f, $tries, $settings) = @_;
319
320 return unless $settings->notify->no_batch_email;
321
322 my $tf = Test2::Harness::TestFile->new(file => $f->{harness_job_end}->{abs_file});
323
324 my @to;
325 push @to => $tf->meta('owner') if $settings->notify->email_owner;
326 push @to => @{$settings->notify->email_fail};
327 return unless @to;
328
329 my $text = $self->gen_text(scope => 'job', service => 'email', settings => $settings, file => $tf, tries => $tries);
330 my $subject = "Failed test on " . hostname() . ": '" . $tf->relative . "'.";
331
332 $self->_send_email($subject, $text, $settings, @to);
333 }
334
335 sub gen_email_job_text {
336 my $self = shift;
337 my %params = @_;
338
339 my $settings = $params{settings} // croak "'settings' is required";
340 my $tf = $params{file} // croak "'file' is required";
341 my $tries = $params{tries} // 0;
342
343 my $host = hostname();
344 my $file = $tf->relative;
345
346 return join "\n\n" => grep { $_ }
347 $settings->notify->text,
348 "Failed test on $host: '$file'.",
349 $tries ? ("Test was run " . (1 + $tries) . " time(s).") : (),
350 join "\n" => @{$settings->run->links};
351 }
352
353 sub _send_email {
354 my $self = shift;
355 my ($subject, $text, $settings, @to) = @_;
356
357 my $mail = Email::Stuffer->to(@to);
358 $mail->from($settings->notify->email_from);
359 $mail->subject($subject);
360
361 my $rtype = ref($text) // '';
362
363 if (!$rtype) {
364 $mail->text_body($text);
365 }
366 elsif ($rtype eq 'HASH') {
367 $mail->text_body($text->{text}) if $text->{text};
368 $mail->html_body($text->{html}) if $text->{html};
369 }
370 else {
371 warn "Invalid text type: '$rtype'";
372 }
373
374 eval { $mail->send_or_die; 1 } or warn $@;
375 }
376
377 sub finish {
378 my $self = shift;
379 my %params = @_;
380 my $settings = $params{settings};
381
382 my $e = $self->{+FINAL} or return;
383 my $f = $e->facet_data or return;
384 my $final = $f->{harness_final} or return;
385
386 $self->send_run_notification_slack($final, $settings);
387 $self->send_run_notification_email($final, $settings);
388 }
389
390 sub send_run_notification_slack {
391 my $self = shift;
392 my ($final, $settings) = @_;
393
394 return if $settings->notify->no_batch_slack;
395
396 my @to = @{$settings->notify->slack};
397 push @to => @{$settings->notify->slack_fail} unless $final->{pass};
398
399 my $files = "";
400 if ($final->{failed}) {
401 for my $set (@{$final->{failed}}) {
402 my $file = $set->[1];
403
404 $files = $files ? "$files\n$file" : $file;
405
406 next unless $settings->notify->slack_owner;
407 my $tf = Test2::Harness::TestFile->new(file => $file);
408 push @to => $tf->meta('slack');
409 }
410 }
411
412 return unless @to;
413
414 my $text = $self->gen_text(
415 scope => 'run',
416 service => 'slack',
417 settings => $settings,
418 final => $final,
419 files => $files,
420 );
421
422 $self->_send_slack($text, $settings, @to);
423 }
424
425 sub gen_slack_run_text {
426 my $self = shift;
427 my %params = @_;
428
429 my $settings = $params{settings} // croak "'settings' is required";
430 my $final = $params{final} // croak "'final' is required";
431 my $files = $params{files} // '';
432
433 my $host = hostname();
434
435 return join "\n\n" => grep { $_ } (
436 $settings->notify->text,
437 ($final->{pass} ? "Tests passed on $host" : "Tests failed on $host"),
438 ($files ? $files : ()),
439 join("\n" => map {"> <$_|$_>"} @{$settings->run->links}),
440 );
441 }
442
443 sub send_run_notification_email {
444 my $self = shift;
445 my ($final, $settings) = @_;
446
447 return if $settings->notify->no_batch_email;
448
449 my @to = @{$settings->notify->email};
450 push @to => @{$settings->notify->email_fail} unless $final->{pass};
451
452 my $files = "";
453 if ($final->{failed}) {
454 for my $set (@{$final->{failed}}) {
455 my $file = $set->[1];
456
457 $files = $files ? "$files\n$file" : $file;
458
459 next unless $settings->notify->email_owner;
460 my $tf = Test2::Harness::TestFile->new(file => $file);
461 push @to => $tf->meta('owner');
462 }
463 }
464
465 return unless @to;
466
467 my $subject = $self->gen_text(
468 scope => 'run',
469 service => 'email_subject',
470 settings => $settings,
471 final => $final,
472 files => $files,
473 );
474
475 my $text = $self->gen_text(
476 scope => 'run',
477 service => 'email',
478 settings => $settings,
479 final => $final,
480 files => $files,
481 subject => $subject,
482 );
483
484 $self->_send_email($subject, $text, $settings, @to);
485 }
486
487 sub gen_email_subject_run_text {
488 my $self = shift;
489 my %params = @_;
490
491 my $final = $params{final} // croak "'final' is required";
492 my $host = hostname();
493
494 return $final->{pass} ? "Tests passed on $host" : "Tests failed on $host";
495 }
496
497 sub gen_email_run_text {
498 my $self = shift;
499 my %params = @_;
500
501 my $subject = $params{subject} // $self->gen_text(%params, service => 'email_subject');
502 my $settings = $params{settings} // croak "'settings' is required";
503 my $final = $params{final} // croak "'final' is required";
504 my $files = $params{files} // '';
505
506 return join "\n\n" => grep { $_ } (
507 $settings->notify->text,
508 $subject,
509 ($files ? $files : ()),
510 join("\n" => @{$settings->run->links}),
511 );
512 }
513
514 sub gen_text {
515 my $self = shift;
516 my %params = @_;
517
518 my $scope = $params{scope} or croak "'scope' is required";
519 my $service = $params{service} or croak "'service' is required";
520 my $settings = $params{settings} or croak "'settings' is required";
521
522 my $meth = "gen_${service}_${scope}_text";
523
524 if (my $tm = $self->text_mod($settings)) {
525 return $tm->$meth(%params, notify => $self)
526 if $tm->can($meth);
527 }
528
529 if ($self->can($meth)) {
530 my $text = $self->$meth(%params);
531
532 my $mod = $settings->notify->text_module;
533 $text = <<" EOT" if $self->{+TEXT_MOD_FAIL} && $service !~ m/subject/i;
534 *******************************************************************************
535 There was an error loading the text generation module '$mod'.
536 Because of this error the default notification text has been used.
537
538 The error encountered was:
539 $self->{+TEXT_MOD_FAIL}
540 *******************************************************************************
541
542 $text
543 EOT
544
545 return $text;
546 }
547
548 confess "No notification text method '$meth'";
549 }
550
551 1;
552
553 __END__
554
555 =pod
556
557 =encoding UTF-8
558
559 =head1 NAME
560
561 App::Yath::Plugin::Notify - Plugin to send email and/or slack notifications
562
563 =head1 DESCRIPTION
564
565 This plugin is used for sending email and/or slack notifications from yath.
566
567 =head1 SYNOPSIS
568
569 =head2 IN A TEST
570
571 #!/usr/bin/perl
572 use Test2::V0;
573 # HARNESS-META owner [email protected]
574 # HARNESS-META slack #slack_channel
575 # HARNESS-META slack #slack_user
576
577 You can use the C<# HARNESS-META owner EMAIL_ADDRESS> to specify an "owner"
578 email address. You can use the C<# HARNESS-META slack USER/CHANNEL> to specify
579 a slack user or channel that owns the test.
580
581 =head2 RUNNING WITH NOTIFICATIONS ENABLED
582
583 $ yath test -pNotify ...
584
585 Also of note, most of the time you can just specify the notification options
586 you want and the plugin will load as needed as long as C<--no-scan-plugins> was
587 not specified.
588
589 =head3 EMAIL
590
591 $ yath test --notify-email-owner --notify-email-from [email protected] --notify-email-fail [email protected]
592
593 =head3 SLACK
594
595 A slack hooks url is always needed for slack to work.
596
597 $ yath test --notify-slack-url https://hooks.slack.com/... --notify-slack-fail '#foo' --notify-slack-owner
598
599 =head1 PROVIDED OPTIONS
600
601 =head2 COMMAND OPTIONS
602
603 =head3 Notification Options
604
605 =over 4
606
607 =item --notify-email [email protected]
608
609 =item --no-notify-email
610
611 Email the test results to the specified email address(es)
612
613 Can be specified multiple times
614
615
616 =item --notify-email-fail [email protected]
617
618 =item --no-notify-email-fail
619
620 Email failing results to the specified email address(es)
621
622 Can be specified multiple times
623
624
625 =item --notify-email-from [email protected]
626
627 =item --no-notify-email-from
628
629 If any email is sent, this is who it will be from
630
631
632 =item --notify-email-owner
633
634 =item --no-notify-email-owner
635
636 Email the owner of broken tests files upon failure. Add `# HARNESS-META-OWNER [email protected]` to the top of a test file to give it an owner
637
638
639 =item --notify-no-batch-email
640
641 =item --no-notify-no-batch-email
642
643 Usually owner failures are sent as a single batch at the end of testing. Toggle this to send failures as they happen.
644
645
646 =item --notify-no-batch-slack
647
648 =item --no-notify-no-batch-slack
649
650 Usually owner failures are sent as a single batch at the end of testing. Toggle this to send failures as they happen.
651
652
653 =item --notify-slack '#foo'
654
655 =item --notify-slack '@bar'
656
657 =item --no-notify-slack
658
659 Send results to a slack channel and/or user
660
661 Can be specified multiple times
662
663
664 =item --notify-slack-fail '#foo'
665
666 =item --notify-slack-fail '@bar'
667
668 =item --no-notify-slack-fail
669
670 Send failing results to a slack channel and/or user
671
672 Can be specified multiple times
673
674
675 =item --notify-slack-owner
676
677 =item --no-notify-slack-owner
678
679 Send slack notifications to the slack channels/users listed in test meta-data when tests fail.
680
681
682 =item --notify-slack-url https://hooks.slack.com/...
683
684 =item --no-notify-slack-url
685
686 Specify an API endpoint for slack webhook integrations
687
688
689 =item --notify-text ARG
690
691 =item --notify-text=ARG
692
693 =item --message ARG
694
695 =item --message=ARG
696
697 =item --msg ARG
698
699 =item --msg=ARG
700
701 =item --no-notify-text
702
703 Add a custom text snippet to email/slack notifications
704
705
706 =item --notify-text-module ARG
707
708 =item --notify-text-module=ARG
709
710 =item --message_module ARG
711
712 =item --message_module=ARG
713
714 =item --no-notify-text-module
715
716 Use the specified module to generate messages for emails and/or slack.
717
718
719 =back
720
721 =head1 SOURCE
722
723 The source code repository for Test2-Harness can be found at
724 F<http://github.com/Test-More/Test2-Harness/>.
725
726 =head1 MAINTAINERS
727
728 =over 4
729
730 =item Chad Granum E<lt>[email protected]<gt>
731
732 =back
733
734 =head1 AUTHORS
735
736 =over 4
737
738 =item Chad Granum E<lt>[email protected]<gt>
739
740 =back
741
742 =head1 COPYRIGHT
743
744 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
745
746 This program is free software; you can redistribute it and/or
747 modify it under the same terms as Perl itself.
748
749 See F<http://dev.perl.org/licenses/>
750
751 =cut