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