blib/lib/Mojolicious/Plugin/Cron.pm

filter: Statementstmt 100% 68 / 68 Branchbran 80.0% 16 / 20 Conditioncond 68.1% 15 / 22 MC/DCmcdc 36.3% 4 / 11 Subroutinesub 100% 13 / 13 Podpod 100% 1 / 1 totaltotal 86.6% 117 / 135 CC 21 SCAR 16.2
CC
21
Cov
90%
__ANON__
9.0
_cron
6.0
register
5.7
CRAP 5.0
↑ Summary
1 package Mojolicious::Plugin::Cron;
2 3 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Fcntl ':flock';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use Mojo::File 'path';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Algorithm::Cron;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 3 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 3 our $VERSION = "0.035";
12 3 ▶use constant CRON_DIR => 'mojo_cron_';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 my $crondir;
14  
15 2 ▶sub register {
Subroutine register: called CC=5 SCAR=17.4
Pod documented
16 2 my ($self, $app, $cronhashes) = @_;
17 2 ▶ croak "No schedules found" unless ref $cronhashes eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cronhashes eq "HASH" 0 2 2
18  
19 # for *nix systems, getpwuid takes precedence
20 # for win systems or wherever getpwuid is not implemented,
21 # eval returns undef so getlogin takes precedence
22 $crondir
23 = path($app->config->{cron}{dir} // File::Spec->tmpdir)
24 2 ▶ ->child(CRON_DIR . (eval { scalar getpwuid($<) } || getlogin || 'nobody'),
Condition37%3/8
$app->config->{"cron"}{"dir"} // "File::Spec"->tmpdir
l!l&&r!l&&!r
020
eval { do { scalar getpwuid $< } } || getlogin || 'nobody'
l!l
20
eval { do { scalar getpwuid $< } } or getlogin
l!l&&r!l&&!r
200
MC/DC0%0/2
$app->config->{"cron"}{"dir"} // "File::Spec"->tmpdir
$app->config->{"cron"}{"dir"} "File::Spec"->tmpdir
MC/DC0%0/2
eval { do { scalar getpwuid $< } } || getlogin || 'nobody'
eval { do { scalar getpwuid $< } } getlogin
Truth table33%1/3
A // B
A= $app->config->{"cron"}{"dir"}B= "File::Spec"->tmpdir
ABresult
1X1
011
000
Truth table33%1/3
A or B
A= eval { do { scalar getpwuid $< } }B= getlogin
ABresult
1X1
011
000
25 $app->mode);
26 2 ▶ Mojo::IOLoop->next_tick(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
27 2 ▶ if (ref((values %$cronhashes)[0]) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref((values %$cronhashes)[0]) eq 'CODE') { } 1 1 2
28  
29 # special case, plugin => 'mm hh dd ...' => sub {}
30 1 $self->_cron($app->moniker,
31 {crontab => (keys %$cronhashes)[0], code => (values %$cronhashes)[0]},
32 $app);
33 }
34 else {
35 1 $self->_cron($_, $cronhashes->{$_}, $app) for keys %$cronhashes;
36 }
37 2 });
38 }
39  
40 7 ▶sub _cron {
Subroutine _cron: called CC=6 SCAR=17.9
41 7 my ($self, $sckey, $cronhash, $app) = @_;
42 7 my $code = delete $cronhash->{code};
43 7 ▶ my $all_proc = delete $cronhash->{all_proc} // '';
Condition100%2/2
delete $cronhash->{"all_proc"} // ""
l!l
25
MC/DC100%1/1
delete $cronhash->{"all_proc"} // ""
delete $cronhash->{"all_proc"}
Truth table100%2/2
A
A= delete $cronhash->{"all_proc"}
Aresult
11
00
44 my $test_key
45 7 = delete $cronhash->{__test_key}; # __test_key is for test case only
46 7 ▶ $sckey = $test_key // $sckey;
Condition66%2/3
$test_key // $sckey
l!l&&r!l&&!r
250
MC/DC0%0/2
$test_key // $sckey
$test_key $sckey
Truth table66%2/3
A // B
A= $test_keyB= $sckey
ABresult
1X1
011
000
47  
48 7 ▶ $cronhash->{base} //= 'local';
Condition100%2/2
$cronhash->{"base"} //= "local"
l!l
61
MC/DC100%1/1
$cronhash->{"base"} //= "local"
$cronhash->{"base"}
Truth table100%2/2
A
A= $cronhash->{"base"}
Aresult
11
00
49  
50 7 ▶ ref $cronhash->{crontab} eq ''
Branch: 1 branch
BranchTrueFalseTotal
ref $cronhash->{"crontab"} eq "" or croak("crontab parameter for schedule $sckey not a string") 7 0 7
51 or croak "crontab parameter for schedule $sckey not a string";
52 7 ▶ ref $code eq 'CODE' or croak "code parameter for schedule $sckey is not CODE";
Branch: 1 branch
BranchTrueFalseTotal
ref $code eq "CODE" or croak("code parameter for schedule $sckey is not CODE") 7 0 7
53  
54 7 my $cron = Algorithm::Cron->new(%$cronhash);
55 7 my $time = time;
56  
57 # $all_proc, $code, $cron, $sckey and $time will be part of the $task clojure
58 7 my $task;
59 28 ▶ $task = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
60 28 $time = $cron->next_time($time);
61 28 ▶ if (!$all_proc) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($all_proc) 24 4 28
62 }
63 Mojo::IOLoop->timer(
64 21 ▶ ($time - time) => sub {
Subroutine __ANON__: called CC=9 SCAR=22.0
65 21 my $fire;
66 21 ▶ if ($all_proc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($all_proc) { } 2 19 21
67 2 $fire = 1;
68 }
69 else {
70 19 my $dat = $crondir->child("$sckey.time");
71 19 my $sem = $crondir->child("$sckey.time.lock");
72 19 $crondir->make_path; # ensure path exists
73 19 ▶ my $handle_sem = $sem->open('>')
Branch: 1 branch
BranchTrueFalseTotal
my $handle_sem = $sem->open(">") or croak("Cannot open semaphore file $!") 19 0 19
74 or croak "Cannot open semaphore file $!";
75 19 flock($handle_sem, LOCK_EX);
76 19 ▶ my $rtime = $1
Branch: 1 branch
BranchTrueFalseTotal
if (-e $dat && $dat->slurp // "") =~ /(\d+)/u 15 4 19
Condition80%4/5
-e $dat && $dat->slurp // ""
l!l
154
-e $dat and $dat->slurp
!ll&&!rl&&r
4015
MC/DC50%1/2
-e $dat && $dat->slurp // ""
-e $dat $dat->slurp
Truth table66%2/3
A and B
A= -e $datB= $dat->slurp
ABresult
111
0X0
100
77 if (-e $dat && $dat->slurp // '') =~ /(\d+)/; # do some untainting
78 19 ▶ $rtime //= '0';
Condition100%2/2
$rtime //= 0
l!l
154
MC/DC100%1/1
$rtime //= 0
$rtime
Truth table100%2/2
A
A= $rtime
Aresult
11
00
79 19 ▶ if ($rtime != $time) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rtime != $time) 18 1 19
80 18 $dat->spew($time);
81 18 $fire = 1;
82 }
83 19 undef $dat;
84 19 undef $sem; # unlock
85 }
86 21 ▶ $code->($time, $app) if $fire;
Branch: 1 branch
BranchTrueFalseTotal
if $fire 20 1 21
87 21 $task->();
88 }
89 28 );
90 7 };
91 7 $task->();
92 }
93  
94 3 1;
95  
96 =encoding utf8
97  
98 =head1 NAME
99  
100 Mojolicious::Plugin::Cron - a Cron-like helper for Mojolicious and Mojolicious::Lite projects
101  
102 =head1 SYNOPSIS
103  
104 # Execute some job every 5 minutes, from 9 to 5 (4:55 actually)
105  
106 # Mojolicious::Lite
107  
108 plugin Cron => ( '*/5 9-16 * * *' => sub {
109 my $target_epoch = shift;
110 # do something non-blocking but useful
111 });
112  
113 # Mojolicious
114  
115 $self->plugin(Cron => '*/5 9-16 * * *' => sub {
116 # same here
117 });
118  
119 # More than one schedule, or more options requires extended syntax
120  
121 plugin Cron => (
122 sched1 => {
123 base => 'utc', # not needed for local time
124 crontab => '*/10 15 * * *', # at every 10th minute past hour 15 (3:00 pm to 3:50 pm)
125 code => sub {
126 # job 1 here
127 }
128 },
129 sched2 => {
130 crontab => '*/15 15 * * *', # at every 15th minute past hour 15 (3:00 pm to 3:45 pm)
131 code => sub {
132 # job 2 here
133 }
134 });
135  
136 =head1 DESCRIPTION
137  
138 L<Mojolicious::Plugin::Cron> is a L<Mojolicious> plugin that allows to schedule tasks
139 directly from inside a Mojolicious application.
140  
141 The plugin mimics *nix "crontab" format to schedule tasks (see L<cron|https://en.wikipedia.org/wiki/Cron>) .
142  
143 As an extension to regular cron, seconds are supported in the form of a sixth space
144 separated field (For more information on cron syntax please see L<Algorithm::Cron>).
145  
146 The plugin can help in development and testing phases, as it is very easy to configure and
147 doesn't require a schedule utility with proper permissions at operating system level.
148  
149 For testing, it may be helpful to use Test::Mock::Time ability to "fast-forward"
150 time calling all the timers in the interval. This way, you can actually test events programmed
151 far away in the future.
152  
153 For deployment phase, it will help avoiding the installation steps normally asociated with
154 scheduling periodic tasks.
155  
156 =head1 BASICS
157  
158 When using preforked servers (as applications running with hypnotoad), some coordination
159 is needed so jobs are not executed several times.
160  
161 L<Mojolicious::Plugin::Cron> uses standard Fcntl functions for that coordination, to assure
162 a platform-independent behavior.
163  
164 Please take a look in the examples section, for a simple Mojo Application that you can
165 run on a preforked server, try hot restarts, adding / removing workers, etc, and
166 check that scheduled jobs execute without interruptions or duplications.
167  
168 =head1 EXTENDEND SYNTAX HASH
169  
170 When using extended syntax, you can define more than one crontab line, and have access
171 to more options
172  
173 plugin Cron => {key1 => {crontab line 1}, key2 => {crontab line 2}, ...};
174  
175 =head2 Keys
176  
177 Keys are the names that identify each crontab line. They are used to form a locking
178 semaphore file to avoid multiple processes starting the same job.
179  
180 You can use the same name in different Mojolicious applications that will run
181 at the same time. This will ensure that not more that one instance of the cron job
182 will take place at a specific scheduled time.
183  
184 =head2 Crontab lines
185  
186 Each crontab line consists of a hash with the following keys:
187  
188 =over 8
189
190 =item base => STRING
191
192 Gives the time base used for scheduling. Either C<utc> or C<local> (default C<local>).
193
194 =item crontab => STRING
195
196 Gives the crontab schedule in 5 or 6 space-separated fields.
197
198 =item sec => STRING, min => STRING, ... mon => STRING
199
200 Optional. Gives the schedule in a set of individual fields, if the C<crontab>
201 field is not specified.
202  
203 For more information on base, crontab and other time related keys,
204 please refer to L<Algorithm::Cron> Constructor Attributes.
205  
206 =item code => sub {...}
207  
208 Mandatory. Is the code that will be executed whenever the crontab rule fires.
209 Note that this code B<MUST> be non-blocking. For tasks that are naturally
210 blocking, the recommended solution would be to enqueue tasks in a job
211 queue (like the L<Minion> queue, that will play nicelly with any Mojo project).
212  
213 =back
214  
215 =head1 METHODS
216  
217 L<Mojolicious::Plugin::Cron> inherits all methods from
218 L<Mojolicious::Plugin> and implements the following new ones.
219  
220 =head2 register
221  
222 $plugin->register(Mojolicious->new, {Cron => '* * * * *' => sub {}});
223  
224 Register plugin in L<Mojolicious> application.
225  
226 =head1 MULTIHOST LOCKING
227  
228 The epoch corresponding to the scheduled time (i.e. the perl "time" function
229 corresponding to the current task) is available as the first parameter for the
230 callback sub. This can be used as a higher level "lock" to limit the amount
231 of simultaneous scheduled tasks to just one on a multi-host environment.
232  
233 (You will need some kind of db service accessible from all hosts).
234  
235 # Execute some job every 5 minutes, only on one of the existing hosts
236  
237 plugin Cron => ( '*/5 * * * *' => sub {
238 my ($target_epoch, $app) = @_;
239 my $last_epoch = some_kind_of_atomic_swap_function(
240 key => "some id key for this crontab",
241 value => $target_epoch
242 );
243 if ($target_epoch != $last_epoc) { # Only first host will get here!
244 # do something non-blocking
245 } else {
246 # following hosts will get here. Do not call the task
247 }
248 });
249  
250 That "atomic_swap" function B<needs to be non-blocking>. As this is unlikely the
251 case because it will normally imply a remote call, you can just enqueue a job to a L<Minion> queue
252 and then inside the task filter out already executed (by other host) tasks by this lock.
253 You can see a working proof of concept L<here|https://github.com/dmanto/clustered-cron-example>, using
254 an L<etcd|https://etcd.io> db as a resilient backend to handle the atomic swap functionality.
255  
256 =head1 WINDOWS INSTALLATION
257  
258 To install in windows environments, you need to force-install module
259 Test::Mock::Time, or installation tests will fail.
260  
261 =head1 AUTHOR
262  
263 Daniel Mantovani, C<dmanto@cpan.org>
264  
265 =head1 COPYRIGHT AND LICENCE
266  
267 Copyright (C) 2018-2024, Daniel Mantovani.
268  
269 This library is free software; you may redistribute it and/or modify it under
270 the terms of the Artistic License version 2.0.
271  
272 =head1 SEE ALSO
273  
274 L<Mojolicious>, L<Mojolicious::Guides>, L<Mojolicious::Plugins>, L<Algorithm::Cron>, L<Minion>
275  
276 =cut
↑ Summary