blib/lib/App/Cronjob.pm untested

filter: Statementstmt 0.0% 0 / 156 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 23 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 282 CC 21 SCAR 51.8
CC
21
Cov
0%
run
380.0
send_cronjob_report
12.0
BEGIN
2.0
CRAP 177.9
1 use strict;
2 use warnings;
3 package App::Cronjob 1.200014;
4 # ABSTRACT: wrap up programs to be run as cron jobs
5  
6 use Digest::MD5 qw(md5_hex);
7 use Errno;
8 use Fcntl qw( :DEFAULT :flock );
9 use Getopt::Long::Descriptive;
10 use IPC::Run3 qw(run3);
11 use Log::Dispatchouli;
12 use Process::Status 0.002;
13 use String::Flogger;
14 use Sys::Hostname::Long;
15 use Text::Template;
16 use Time::HiRes ();
17  
18 #pod =head1 SEE INSTEAD
19 #pod
20 #pod This library, App::Cronjob, is not well documented. Its internals may change
21 #pod substantially until such point as it is documented.
22 #pod
23 #pod Instead of using the library, you should run the program F<cronjob> that is
24 #pod installed along with the library.
25 #pod
26 #pod For a full description of the program's behavior, consult L<cronjob>.
27 #pod
28 #pod =cut
29  
30 my $TEMPLATE;
31  
32 my (
33 $opt,
34 $usage,
35 $subject,
36 $rcpts,
37 $host,
38 $sender,
39 );
40  
41 sub run {
42 ($opt, $usage) = describe_options(
43 '%c %o',
44 [ 'command|c=s', 'command to run (passed to ``)', { required => 1 } ],
45 [ 'subject|s=s', 'subject of mail to send (defaults to command)' ],
46 [ 'rcpt|r=s@', 'recipient of mail; may be given many times', ],
47 [ 'errors-only|E', 'do not send mail if exit code 0, even with output', ],
48 [ 'sender|f=s', 'sender for message', ],
49 [ 'jobname|j=s', 'job name; used for locking, if given' ],
50 [ 'timeout=i', "fail if the child isn't completed within n seconds" ],
51 [ 'ignore-errors=s@', 'error types to ignore (like: lock)' ],
52 [ 'email-header|h=s@', 'add header to the report email, if you send one' ],
53 [ 'temp-ignore-lock-errors=i',
54 'failure to lock only signals an error after this long' ],
55 [ 'lock!', 'lock this job (defaults to true; --no-lock for off)',
56 { default => 1 } ],
57 );
58  
59 $subject = $opt->{subject} || $opt->{command};
60 $subject =~ s{\A/\S+/([^/]+)(\s|$)}{$1$2} if $subject eq $opt->{command};
61  
62 if (defined $opt->{temp_ignore_lock_errors}) {
63 if (grep {; $_ eq "lock" } @{$opt->{ignore_errors}}) {
64 die "--temp-ignore-lock-errors and --ignore-errors=lock are incompatible\n";
65 }
66 }
67  
68 my @extra_headers;
69 for my $entry (@{ $opt->email_header || [] }) {
70 my ($h, $v) = split /=/, $entry;
71  
72 lc $h eq $_ && die "You can't replace the $_ header!\n"
73 for qw(to from subject);
74  
75 die "Invalid header name: $h" if $h =~ /\P{ASCII}/;
76 die "Invalid header name: $h" unless $h =~ /\A[A-Za-z][-A-Za-z0-9]*\z/;
77  
78 push @extra_headers, $h, $v;
79 }
80  
81 $rcpts = $opt->{rcpt}
82 || [ split /\s*,\s*/, ($ENV{MAILTO} ? $ENV{MAILTO} : 'root') ];
83  
84 $host = hostname_long;
85 $sender = $opt->{sender} || sprintf '%s@%s', ($ENV{USER}||'cron'), $host;
86  
87 my $got_lock;
88  
89 my $okay = eval {
90 die "illegal job name: $opt->{jobname}\n"
91 if $opt->{jobname} and $opt->{jobname} !~ m{\A[-_A-Za-z0-9]+\z};
92  
93 my $job_id = $opt->{jobname} || md5_hex($subject);
94 my $lockfile = sprintf '%s/cronjob.%s',
95 $ENV{APP_CRONJOB_LOCKDIR} || '/tmp',
96 $job_id;
97  
98 my $logger = Log::Dispatchouli->new({
99 ident => 'cronjob',
100 facility => 'cron',
101 log_pid => 1,
102 prefix => "$job_id: ",
103 });
104  
105 my $lock_fh;
106 if ($opt->lock) {
107 sysopen $lock_fh, $lockfile, O_CREAT|O_WRONLY
108 or die App::Cronjob::Exception->new(
109 lockfile => "couldn't open lockfile $lockfile: $!"
110 );
111  
112 my $lock_flags = LOCK_EX | LOCK_NB;
113  
114 unless (flock $lock_fh, $lock_flags) {
115 my $error = $!;
116 my $mtime = (stat $lock_fh)[9];
117 my $stamp = scalar localtime $mtime;
118 die App::Cronjob::Exception->new(
119 lock => "can't lock; $!; lockfile created $stamp",
120 { locked_since => $mtime },
121 );
122 }
123  
124 printf $lock_fh "pid %s running %s\nstarted at %s\n",
125 $$, $opt->{command}, scalar localtime $^T;
126  
127 $got_lock = 1;
128 }
129  
130 $logger->log([ 'trying to run %s', $opt->{command} ]);
131  
132 my $start = Time::HiRes::time;
133 my $output;
134  
135 my $ok = eval {
136 local $SIG{ALRM} = sub { die "command took too long to run" };
137 alarm($opt->timeout) if $opt->timeout;
138 run3($opt->{command}, \undef, \$output, \$output);
139 alarm(0) if $opt->timeout;
140 1;
141 };
142  
143 unless ($ok) {
144 # XXX: does not throw proper exception
145 $logger->log_fatal([ 'run3 failed to run command: %s', $@ ]);
146 }
147  
148 my $status = Process::Status->new;
149  
150 my $end = Time::HiRes::time;
151  
152 my $send_mail = ($status->exitstatus != 0)
153 || (length $output && ! $opt->{errors_only});
154  
155 my $time_taken = sprintf '%0.4f', $end - $start;
156  
157 $logger->log([
158 'job completed with status %s after %ss',
159 $status->as_struct,
160 $time_taken,
161 ]);
162  
163 if ($send_mail) {
164 send_cronjob_report({
165 is_fail => (!! $status->exitstatus),
166 status => $status,
167 time => \$time_taken,
168 output => \$output,
169 extra_headers => \@extra_headers,
170 });
171 }
172  
173 1;
174 };
175  
176 exit 0 if $okay;
177 my $err = $@;
178  
179 if (eval { $err->isa('App::Cronjob::Exception'); }) {
180 unless (
181 grep { $err->{type} and $_ eq $err->{type} } @{$opt->{ignore_errors}}
182 ) {
183 if ($err->{type} eq "lock" && $opt->{temp_ignore_lock_errors}) {
184 my $age = time() - $err->{extra}{locked_since};
185 exit 0 if $age <= $opt->{temp_ignore_lock_errors};
186 }
187 send_cronjob_report({
188 is_fail => 1,
189 output => \$err->{text},
190 extra_headers => \@extra_headers,
191 });
192 }
193  
194 exit 0;
195 } else {
196 $subject = "ERROR: $subject";
197 send_cronjob_report({
198 is_fail => 1,
199 output => \$err,
200 extra_headers => \@extra_headers,
201 });
202 exit 0;
203 }
204 }
205  
206 # read INI from /etc/cronjob
207 #sub __config {
208 #}
209  
210 sub send_cronjob_report {
211 my ($arg) = @_;
212  
213 require Email::Simple;
214 require Email::Simple::Creator;
215 require Email::Sender::Simple;
216 require Text::Template;
217  
218 my $body = Text::Template->fill_this_in(
219 $TEMPLATE,
220 HASH => {
221 command => \$opt->{command},
222 output => $arg->{output},
223 time => $arg->{time} || \'(n/a)',
224 status => \($arg->{status} ? $arg->{status}->as_string : 'never ran'),
225 },
226 );
227  
228 my $subject = sprintf '%s%s', ($arg->{is_fail} ? 'FAIL: ' : ''), $subject;
229  
230 my $irt = sprintf '<%s@%s>', md5_hex($subject), $host;
231  
232 my $email = Email::Simple->create(
233 body => $body,
234 header => [
235 To => join(', ', @$rcpts),
236 From => qq{"cron/$host" <$sender>},
237 Subject => $subject,
238 'In-Reply-To' => $irt,
239 'Auto-Submitted' => 'auto-generated',
240 @{ $arg->{extra_headers} },
241 ],
242 );
243  
244 Email::Sender::Simple->send(
245 $email,
246 {
247 to => $rcpts,
248 from => $sender,
249 }
250 );
251 }
252  
253 BEGIN {
254 $TEMPLATE = <<'END_TEMPLATE'
255 Command: { $command }
256 Time : { $time }s
257 Status : { $status }
258  
259 Output :
260  
261 { $output || '(no output)' }
262 END_TEMPLATE
263 }
264  
265 {
266 package App::Cronjob::Exception 1.200014;
267  
268 sub new {
269 my ($class, $type, $text, $extra) = @_;
270 bless { type => $type, text => $text, extra => $extra } => $class;
271 }
272 }
273  
274 1;
275  
276 __END__