Runnable/Timeout/Alarm.pm

filter: Statementstmt 92.3% 24 / 26 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 85.7% 6 / 7 Podpod n/a totaltotal 90.9% 30 / 33 CC 1 SCAR 1.3
CC
1
Cov
92%
__ANON__
2.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Runnable/DenyUsers.pm ↑ Summary Runner/Command.pm »
1 package Beam::Runnable::Timeout::Alarm;
2 2 our $VERSION = '0.016';
3 # ABSTRACT: Use `alarm` to set a timeout for a command
4  
5 #pod =head1 SYNOPSIS
6 #pod
7 #pod ### In a Runnable module
8 #pod package My::Runnable::Script;
9 #pod use Moo;
10 #pod with 'Beam::Runnable', 'Beam::Runnable::Timeout::Alarm';
11 #pod has '+timeout' => ( default => 60 ); # Set timeout: 60s
12 #pod sub run { }
13 #pod
14 #pod ### In a container config file
15 #pod runnable:
16 #pod $class: My::Runnable::Script
17 #pod $with:
18 #pod - 'Beam::Runnable::Timeout::Alarm'
19 #pod timeout: 60
20 #pod
21 #pod =head1 DESCRIPTION
22 #pod
23 #pod This role adds a timeout for a runnable module using Perl's L<alarm()|perlfunc/alarm>
24 #pod function. When the timeout is reached, a warning will be printed to C<STDERR> and the
25 #pod program will exit with code C<255>.
26 #pod
27 #pod =head1 SEE ALSO
28 #pod
29 #pod L<Beam::Runnable>, L<perlfunc/alarm>, L<Time::HiRes>
30 #pod
31 #pod =cut
32  
33 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 2 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 2 ▶use Types::Standard qw( Num CodeRef );
Subroutine BEGIN: called CC=1 SCAR=0.0
37 2 ▶use Time::HiRes qw( alarm );
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 #pod =attr timeout
40 #pod
41 #pod The time in seconds this program is allowed to run. This can include
42 #pod a decimal (like C<6.5> seconds).
43 #pod
44 #pod =cut
45  
46 2 has timeout => (
47 is => 'ro',
48 isa => Num,
49 required => 1,
50 );
51  
52 #pod =attr _timeout_cb
53 #pod
54 #pod A callback to be run when the timeout is reached. Override this to change
55 #pod what warning is printed to C<STDERR> and what exit code is used (or whether
56 #pod the process exits at all).
57 #pod
58 #pod =cut
59  
60 has _timeout_cb => (
61 is => 'ro',
62 isa => CodeRef,
63 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
64 0 warn "Timeout reached!\n";
65 0 exit 255;
66 },
67 2 );
68  
69 #pod =method run
70 #pod
71 #pod This role wraps the C<run> method of your runnable class to add the timeout.
72 #pod
73 #pod =cut
74  
75 1 ▶around run => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
76 1 my ( $orig, $self, @args ) = @_;
77 1 local $SIG{ALRM} = $self->_timeout_cb;
78 1 alarm $self->timeout;
79 1 return $self->$orig( @args );
80 2 };
81  
82 2 1;
83  
84 __END__
« Runnable/DenyUsers.pm ↑ Summary Runner/Command.pm »