Scheduler 0.05, fixed bug with @monthly
[catagits/Catalyst-Plugin-Scheduler.git] / lib / Catalyst / Plugin / Scheduler.pm
CommitLineData
74e31b02 1package Catalyst::Plugin::Scheduler;
2
3use strict;
4use warnings;
f9d8e3cf 5use base qw/Class::Accessor::Fast Class::Data::Inheritable/;
cbf1ecfe 6use DateTime;
7use DateTime::Event::Cron;
8use DateTime::TimeZone;
68f800bd 9use File::stat;
74e31b02 10use NEXT;
d2c7c91a 11use Set::Scalar;
f9d8e3cf 12use Storable qw/lock_store lock_retrieve/;
13use YAML;
74e31b02 14
4796c217 15our $VERSION = '0.05';
74e31b02 16
cbf1ecfe 17__PACKAGE__->mk_classdata( '_events' => [] );
68f800bd 18__PACKAGE__->mk_accessors('_event_state');
cbf1ecfe 19
20sub schedule {
21 my ( $class, %args ) = @_;
68f800bd 22
f9d8e3cf 23 unless ( $args{event} ) {
68f800bd 24 Catalyst::Exception->throw(
25 message => 'The schedule method requires an event parameter' );
f9d8e3cf 26 }
68f800bd 27
f9d8e3cf 28 my $conf = $class->config->{scheduler};
4796c217 29
cbf1ecfe 30 my $event = {
cbf1ecfe 31 trigger => $args{trigger},
f9d8e3cf 32 event => $args{event},
cbf1ecfe 33 auto_run => ( defined $args{auto_run} ) ? $args{auto_run} : 1,
34 };
68f800bd 35
cbf1ecfe 36 if ( $args{at} ) {
68f800bd 37
cbf1ecfe 38 # replace keywords that Set::Crontab doesn't support
39 $args{at} = _prepare_cron( $args{at} );
4796c217 40
cbf1ecfe 41 # parse the cron entry into a DateTime::Set
42 my $set;
43 eval { $set = DateTime::Event::Cron->from_cron( $args{at} ) };
68f800bd 44 if ($@) {
45 Catalyst::Exception->throw(
46 "Scheduler: Unable to parse 'at' value "
47 . $args{at} . ': '
48 . $@ );
cbf1ecfe 49 }
50 else {
ea66b1c7 51 $event->{at} = $args{at};
cbf1ecfe 52 $event->{set} = $set;
53 }
54 }
68f800bd 55
cbf1ecfe 56 push @{ $class->_events }, $event;
57}
58
59sub dispatch {
60 my $c = shift;
68f800bd 61
cbf1ecfe 62 $c->NEXT::dispatch(@_);
68f800bd 63
f9d8e3cf 64 $c->_get_event_state();
68f800bd 65
66 $c->_check_yaml();
67
cbf1ecfe 68 # check if a minute has passed since our last check
f9d8e3cf 69 # This check is not run if the user is manually triggering an event
70 if ( time - $c->_event_state->{last_check} < 60 ) {
71 return unless $c->req->params->{schedule_trigger};
cbf1ecfe 72 }
f9d8e3cf 73 my $last_check = $c->_event_state->{last_check};
74 $c->_event_state->{last_check} = time;
75 $c->_save_event_state();
68f800bd 76
77 my $conf = $c->config->{scheduler};
f9d8e3cf 78 my $last_check_dt = DateTime->from_epoch(
79 epoch => $last_check,
cbf1ecfe 80 time_zone => $conf->{time_zone}
81 );
82 my $now = DateTime->now( time_zone => $conf->{time_zone} );
68f800bd 83
48390e8e 84 EVENT:
cbf1ecfe 85 for my $event ( @{ $c->_events } ) {
f9d8e3cf 86 my $next_run;
68f800bd 87
88 if ( $event->{trigger}
89 && $event->{trigger} eq $c->req->params->{schedule_trigger} )
90 {
91
f9d8e3cf 92 # manual trigger, run it now
93 next EVENT unless $c->_event_authorized;
94 $next_run = $now;
95 }
96 else {
97 next EVENT unless $event->{set};
68f800bd 98 $next_run = $event->{set}->next($last_check_dt);
f9d8e3cf 99 }
68f800bd 100
cbf1ecfe 101 if ( $next_run <= $now ) {
68f800bd 102
cbf1ecfe 103 # do some security checking for non-auto-run events
104 if ( !$event->{auto_run} ) {
105 next EVENT unless $c->_event_authorized;
106 }
68f800bd 107
f9d8e3cf 108 # make sure we're the only process running this event
68f800bd 109 next EVENT unless $c->_mark_running($event);
110
cbf1ecfe 111 my $event_name = $event->{trigger} || $event->{event};
68f800bd 112 $c->log->debug("Scheduler: Executing $event_name")
f9d8e3cf 113 if $c->config->{scheduler}->{logging};
68f800bd 114
cbf1ecfe 115 # trap errors
116 local $c->{error} = [];
68f800bd 117
cbf1ecfe 118 # run event
119 eval {
68f800bd 120
cbf1ecfe 121 # do not allow the event to modify the response
122 local $c->res->{body};
123 local $c->res->{cookies};
124 local $c->res->{headers};
125 local $c->res->{location};
126 local $c->res->{status};
68f800bd 127
cbf1ecfe 128 if ( ref $event->{event} eq 'CODE' ) {
68f800bd 129 $event->{event}->($c);
cbf1ecfe 130 }
131 else {
132 $c->forward( $event->{event} );
133 }
134 };
135 my @errors = @{ $c->{error} };
136 push @errors, $@ if $@;
68f800bd 137 if (@errors) {
138 $c->log->error(
139 'Scheduler: Error executing ' . "$event_name: $_" )
140 for @errors;
cbf1ecfe 141 }
68f800bd 142
143 $c->_mark_finished($event);
cbf1ecfe 144 }
145 }
146}
147
148sub setup {
149 my $c = shift;
68f800bd 150
cbf1ecfe 151 # initial configuration
48390e8e 152 $c->config->{scheduler}->{logging} ||= ( $c->debug ) ? 1 : 0;
68f800bd 153 $c->config->{scheduler}->{time_zone} ||= $c->_detect_timezone();
cbf1ecfe 154 $c->config->{scheduler}->{state_file} ||= $c->path_to('scheduler.state');
155 $c->config->{scheduler}->{hosts_allow} ||= '127.0.0.1';
8c698cac 156 $c->config->{scheduler}->{yaml_file} ||= $c->path_to('scheduler.yml');
68f800bd 157
f9d8e3cf 158 $c->NEXT::setup(@_);
cbf1ecfe 159}
160
ea66b1c7 161sub dump_these {
162 my $c = shift;
163
164 return ( $c->NEXT::dump_these(@_) ) unless @{ $c->_events };
165
166 # for debugging, we dump out a list of all events with their next
167 # scheduled run time
168
169 my $conf = $c->config->{scheduler};
170 my $now = DateTime->now( time_zone => $conf->{time_zone} );
171
172 my $last_check = $c->_event_state->{last_check};
173 my $last_check_dt = DateTime->from_epoch(
174 epoch => $last_check,
175 time_zone => $conf->{time_zone}
176 );
177
178 my $event_dump = [];
179 for my $event ( @{ $c->_events } ) {
180 my $dump = {};
181 for my $key ( qw/at trigger event auto_run/ ) {
182 $dump->{$key} = $event->{$key} if $event->{$key};
183 }
184
185 if ( $event->{set} ) {
186 my $next_run = $event->{set}->next($last_check_dt);
187 $dump->{next_run}
188 = $next_run->ymd
189 . q{ } . $next_run->hms
190 . q{ } . $next_run->time_zone_short_name;
191 }
192
193 push @{$event_dump}, $dump;
194 }
195
196 return (
197 $c->NEXT::dump_these(@_),
198 [ 'Scheduled Events', $event_dump ],
199 );
200}
201
68f800bd 202# check and reload the YAML file with schedule data
203sub _check_yaml {
204 my ($c) = @_;
205
206 # each process needs to load the YAML file independently
207 if ( $c->_event_state->{yaml_mtime}->{$$} ||= 0 ) {
208 return if ( time - $c->_event_state->{last_check} < 60 );
209 }
210
8c698cac 211 return unless -e $c->config->{scheduler}->{yaml_file};
68f800bd 212
213 eval {
8c698cac 214 my $mtime = ( stat $c->config->{scheduler}->{yaml_file} )->mtime;
68f800bd 215 if ( $mtime > $c->_event_state->{yaml_mtime}->{$$} ) {
216 $c->_event_state->{yaml_mtime}->{$$} = $mtime;
217 $c->_save_event_state();
218
219 # wipe out all current events and reload from YAML
220 $c->_events( [] );
221
8c698cac 222 my $yaml = YAML::LoadFile( $c->config->{scheduler}->{yaml_file} );
4796c217 223
68f800bd 224 foreach my $event ( @{$yaml} ) {
225 $c->schedule( %{$event} );
226 }
227
228 $c->log->info( "Scheduler: PID $$ loaded "
229 . scalar @{$yaml}
230 . ' events from YAML file' )
231 if $c->config->{scheduler}->{logging};
232 }
233 };
234 if ($@) {
235 $c->log->error("Error reading YAML file: $@");
236 }
237}
238
cbf1ecfe 239# Detect the current time zone
240sub _detect_timezone {
241 my $c = shift;
68f800bd 242
cbf1ecfe 243 my $tz;
244 eval { $tz = DateTime::TimeZone->new( name => 'local' ) };
245 if ($@) {
68f800bd 246 $c->log->warn(
07305803 247 'Scheduler: Unable to autodetect local time zone, using UTC')
248 if $c->config->{scheduler}->{logging};
cbf1ecfe 249 return 'UTC';
250 }
251 else {
f9d8e3cf 252 $c->log->debug(
68f800bd 253 'Scheduler: Using autodetected time zone: ' . $tz->name )
254 if $c->config->{scheduler}->{logging};
cbf1ecfe 255 return $tz->name;
256 }
257}
258
259# Check for authorized users on non-auto events
cbf1ecfe 260sub _event_authorized {
261 my $c = shift;
68f800bd 262
f9d8e3cf 263 # this should never happen, but just in case...
68f800bd 264 return unless $c->req->address;
265
f9d8e3cf 266 my $hosts_allow = $c->config->{scheduler}->{hosts_allow};
68f800bd 267 $hosts_allow = [$hosts_allow] unless ref($hosts_allow) eq 'ARRAY';
d2c7c91a 268 my $allowed = Set::Scalar->new( @{$hosts_allow} );
269 return $allowed->contains( $c->req->address );
f9d8e3cf 270}
271
272# get the state from the state file
273sub _get_event_state {
274 my $c = shift;
68f800bd 275
f9d8e3cf 276 if ( -e $c->config->{scheduler}->{state_file} ) {
68f800bd 277 $c->_event_state(
278 lock_retrieve $c->config->{scheduler}->{state_file} );
f9d8e3cf 279 }
280 else {
68f800bd 281
f9d8e3cf 282 # initialize the state file
68f800bd 283 $c->_event_state(
284 { last_check => time,
285 yaml_mtime => {},
286 }
287 );
f9d8e3cf 288 $c->_save_event_state();
289 }
290}
291
292# Check the state file to ensure we are the only process running an event
293sub _mark_running {
294 my ( $c, $event ) = @_;
68f800bd 295
f9d8e3cf 296 $c->_get_event_state();
68f800bd 297
f9d8e3cf 298 return if $c->_event_state->{ $event->{event} };
68f800bd 299
f9d8e3cf 300 # this is a 2-step process to prevent race conditions
301 # 1. write the state file with our PID
302 $c->_event_state->{ $event->{event} } = $$;
303 $c->_save_event_state();
68f800bd 304
f9d8e3cf 305 # 2. re-read the state file and make sure it's got the same PID
306 $c->_get_event_state();
307 if ( $c->_event_state->{ $event->{event} } == $$ ) {
308 return 1;
309 }
68f800bd 310
f9d8e3cf 311 return;
312}
313
314# Mark an event as finished
315sub _mark_finished {
316 my ( $c, $event ) = @_;
68f800bd 317
f9d8e3cf 318 $c->_event_state->{ $event->{event} } = 0;
319 $c->_save_event_state();
cbf1ecfe 320}
321
f9d8e3cf 322# update the state file on disk
323sub _save_event_state {
324 my $c = shift;
68f800bd 325
f9d8e3cf 326 lock_store $c->_event_state, $c->config->{scheduler}->{state_file};
cbf1ecfe 327}
328
329# Set::Crontab does not support day names, or '@' shortcuts
330sub _prepare_cron {
331 my $cron = shift;
68f800bd 332
cbf1ecfe 333 return $cron unless $cron =~ /\w/;
68f800bd 334
cbf1ecfe 335 my %replace = (
336 jan => 1,
337 feb => 2,
338 mar => 3,
339 apr => 4,
340 may => 5,
341 jun => 6,
342 jul => 7,
343 aug => 8,
344 sep => 9,
345 'oct' => 10,
346 nov => 11,
347 dec => 12,
68f800bd 348
cbf1ecfe 349 sun => 0,
350 mon => 1,
351 tue => 2,
352 wed => 3,
353 thu => 4,
354 fri => 5,
355 sat => 6,
4796c217 356 );
357
358 my %replace_at = (
cbf1ecfe 359 'yearly' => '0 0 1 1 *',
360 'annually' => '0 0 1 1 *',
361 'monthly' => '0 0 1 * *',
362 'weekly' => '0 0 * * 0',
363 'daily' => '0 0 * * *',
364 'midnight' => '0 0 * * *',
365 'hourly' => '0 * * * *',
366 );
4796c217 367
368 if ( $cron =~ /^\@/ ) {
369 $cron =~ s/^\@//;
370 return $replace_at{ $cron };
371 }
68f800bd 372
cbf1ecfe 373 for my $name ( keys %replace ) {
374 my $value = $replace{$name};
4796c217 375 $cron =~ s/$name/$value/i;
376 last unless $cron =~ /\w/;
cbf1ecfe 377 }
cbf1ecfe 378 return $cron;
379}
380
74e31b02 3811;
382__END__
383
384=pod
385
386=head1 NAME
387
388Catalyst::Plugin::Scheduler - Schedule events to run in a cron-like fashion
389
390=head1 SYNOPSIS
391
392 use Catalyst qw/Scheduler/;
393
394 # run remove_sessions in the Cron controller every hour
395 __PACKAGE__->schedule(
396 at => '0 * * * *',
397 event => '/cron/remove_sessions'
398 );
399
400 # Run a subroutine at 4:05am every Sunday
401 __PACKAGE__->schedule(
402 at => '5 4 * * sun',
403 event => \&do_stuff,
404 );
405
68f800bd 406 # A long-running scheduled event that must be triggered
407 # manually by an authorized user
408 __PACKAGE__->schedule(
409 trigger => 'rebuild_search_index',
410 event => '/cron/rebuild_search_index',
411 );
412 $ wget -q http://www.myapp.com/?schedule_trigger=rebuild_search_index
f9d8e3cf 413
74e31b02 414=head1 DESCRIPTION
415
416This plugin allows you to schedule events to run at recurring intervals.
417Events will run during the first request which meets or exceeds the specified
418time. Depending on the level of traffic to the application, events may or may
419not run at exactly the correct time, but it should be enough to satisfy many
420basic scheduling needs.
421
422=head1 CONFIGURATION
423
424Configuration is optional and is specified in MyApp->config->{scheduler}.
425
426=head2 logging
427
428Set to 1 to enable logging of events as they are executed. This option is
429enabled by default when running under -Debug mode. Errors are always logged
430regardless of the value of this option.
431
cbf1ecfe 432=head2 time_zone
433
434The time zone of your system. This will be autodetected where possible, or
435will default to UTC (GMT). You can override the detection by providing a
436valid L<DateTime> time zone string, such as 'America/New_York'.
437
74e31b02 438=head2 state_file
439
440The current state of every event is stored in a file. By default this is
f9d8e3cf 441$APP_HOME/scheduler.state. This file is created on the first request if it
442does not already exist.
74e31b02 443
68f800bd 444=head2 yaml_file
445
446The location of the optional YAML event configuration file. By default this
447is $APP_HOME/scheduler.yml.
448
74e31b02 449=head2 hosts_allow
450
451This option specifies IP addresses for trusted users. This option defaults
452to 127.0.0.1. Multiple addresses can be specified by using an array
453reference. This option is used for both events where auto_run is set to 0
454and for manually-triggered events.
455
456 __PACKAGE__->config->{scheduler}->{hosts_allow} = '192.168.1.1';
457 __PACKAGE__->config->{scheduler}->{hosts_allow} = [
458 '127.0.0.1',
459 '192.168.1.1'
460 ];
461
462=head1 SCHEDULING
463
464=head2 AUTOMATED EVENTS
465
466Events are scheduled by calling the class method C<schedule>.
467
468 MyApp->schedule(
469 at => '0 * * * *',
470 event => '/cron/remove_sessions',
471 );
472
473 package MyApp::Controller::Cron;
474
475 sub remove_sessions : Private {
476 my ( $self, $c ) = @_;
477
478 $c->delete_expired_sessions;
479 }
480
481=head3 at
482
483The time to run an event is specified using L<crontab(5)>-style syntax.
484
485 5 0 * * * # 5 minutes after midnight, every day
486 15 14 1 * * # run at 2:15pm on the first of every month
487 0 22 * * 1-5 # run at 10 pm on weekdays
488 5 4 * * sun # run at 4:05am every Sunday
489
490From crontab(5):
491
492 field allowed values
493 ----- --------------
494 minute 0-59
495 hour 0-23
496 day of month 1-31
497 month 0-12 (or names, see below)
498 day of week 0-7 (0 or 7 is Sun, or use names)
499
500Instead of the first five fields, one of seven special strings may appear:
501
502 string meaning
503 ------ -------
504 @yearly Run once a year, "0 0 1 1 *".
505 @annually (same as @yearly)
506 @monthly Run once a month, "0 0 1 * *".
507 @weekly Run once a week, "0 0 * * 0".
508 @daily Run once a day, "0 0 * * *".
509 @midnight (same as @daily)
510 @hourly Run once an hour, "0 * * * *".
511
512=head3 event
513
514The event to run at the specified time can be either a Catalyst private
515action path or a coderef. Both types of event methods will receive the $c
516object from the current request, but you must not rely on any request-specific
517information present in $c as it will be from a random user request at or near
518the event's specified run time.
519
520Important: Methods used for events should be marked C<Private> so that
521they can not be executed via the browser.
522
523=head3 auto_run
524
525The auto_run parameter specifies when the event is allowed to be executed.
526By default this option is set to 1, so the event will be executed during the
527first request that matches the specified time in C<at>.
528
529If set to 0, the event will only run when a request is made by a user from
530an authorized address. The purpose of this option is to allow long-running
531tasks to execute only for certain users.
532
533 MyApp->schedule(
534 at => '0 0 * * *',
535 event => '/cron/rebuild_search_index',
536 auto_run => 0,
537 );
538
539 package MyApp::Controller::Cron;
540
541 sub rebuild_search_index : Private {
542 my ( $self, $c ) = @_;
543
544 # rebuild the search index, this may take a long time
545 }
546
547Now, the search index will only be rebuilt when a request is made from a user
548whose IP address matches the list in the C<hosts_allow> config option. To
549run this event, you probably want to ping the app from a cron job.
550
f9d8e3cf 551 0 0 * * * wget -q http://www.myapp.com/
74e31b02 552
553=head2 MANUAL EVENTS
554
555To create an event that does not run on a set schedule and must be manually
556triggered, you can specify the C<trigger> option instead of C<at>.
557
558 __PACKAGE__->schedule(
559 trigger => 'send_email',
560 event => '/events/send_email',
561 );
562
563The event may then be triggered by a standard web request from an authorized
564user. The trigger to run is specified by using a special GET parameter,
565'schedule_trigger'; the path requested does not matter.
566
567 http://www.myapp.com/?schedule_trigger=send_email
568
569By default, manual events may only be triggered by requests made from
570localhost (127.0.0.1). To allow other addresses to run events, use the
68f800bd 571configuration option L</hosts_allow>.
572
573=head1 SCHEDULING USING A YAML FILE
574
575As an alternative to using the schedule() method, you may define scheduled
576events in an external YAML file. By default, the plugin looks for the
577existence of a file called C<schedule.yml> in your application's home
578directory. You can change the filename using the configuration option
579L</yaml_file>.
580
581Modifications to this file will be re-read once per minute during the normal
582event checking process.
583
584Here's an example YAML configuration file with 4 events. Each event is
585denoted with a '-' character, followed by the same parameters used by the
586C<schedule> method. Note that coderef events are not supported by the YAML
587file.
588
589 ---
590 - at: '* * * * *'
591 event: /cron/delete_sessions
592 - event: /cron/send_email
593 trigger: send_email
594 - at: '@hourly'
595 event: /cron/hourly
596 - at: 0 0 * * *
597 auto_run: 0
598 event: /cron/rebuild_search_index
74e31b02 599
600=head1 SECURITY
601
602All events are run inside of an eval container. This protects the user from
603receiving any error messages or page crashes if an event fails to run
604properly. All event errors are logged, even if logging is disabled.
605
74e31b02 606=head1 PLUGIN SUPPORT
607
608Other plugins may register scheduled events if they need to perform periodic
609maintenance. Plugin authors, B<be sure to inform your users> if you do this!
610Events should be registered from a plugin's C<setup> method.
611
612 sub setup {
613 my $c = shift;
614 $c->NEXT::setup(@_);
615
616 if ( $c->can('schedule') ) {
617 $c->schedule(
618 at => '0 * * * *',
619 event => \&cleanup,
620 );
621 }
622 }
f9d8e3cf 623
624=head1 CAVEATS
625
626The time at which an event will run is determined completely by the requests
627made to the application. Apps with heavy traffic may have events run at very
628close to the correct time, whereas apps with low levels of traffic may see
629events running much later than scheduled. If this is a problem, you can use
630a real cron entry that simply hits your application at the desired time.
631
632 0 * * * * wget -q http://www.myapp.com/
633
634Events which consume a lot of time will slow the request processing for the
635user who triggers the event. For these types of events, you should use
636auto_run => 0 or manual event triggering.
637
638=head1 PERFORMANCE
639
640The plugin only checks once per minute if any events need to be run, so the
641overhead on each request is minimal. On my test server, the difference
642between running with Scheduler and without was only around 0.02% (0.004
643seconds).
644
68f800bd 645Of course, when a scheduled event runs, performance will depend on what's
646being run in the event.
07305803 647
648=head1 METHODS
649
650=head2 schedule
651
652Schedule is a class method for adding scheduled events. See the
8c698cac 653L<"/SCHEDULING"> section for more information.
07305803 654
655=head1 INTERNAL METHODS
656
657The following methods are extended by this plugin.
658
659=over 4
660
661=item dispatch
662
663The main scheduling logic takes place during the dispatch phase.
664
ea66b1c7 665=item dump_these
666
667On the Catalyst debug screen, all scheduled events are displayed along with
668the next time they will be executed.
669
07305803 670=item setup
671
672=back
74e31b02 673
674=head1 SEE ALSO
675
676L<crontab(5)>
677
678=head1 AUTHOR
679
680Andy Grundman, <andy@hybridized.org>
681
682=head1 COPYRIGHT
683
684This program is free software, you can redistribute it and/or modify it
685under the same terms as Perl itself.
686
687=cut