ETLp/Audit/Browser/Model/Schedule.pm untested

filter: Statementstmt 0.0% 0 / 384 Branchbran 0.0% 0 / 120 Conditioncond 0.0% 0 / 26 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 8 Podpod n/a totaltotal 0.0% 0 / 553 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package ETLp::Audit::Browser::Model::Schedule;
2  
3 use MooseX::Declare;
4  
5 =head1 NAME
6  
7 ETLp::Audit::Browser::Model::Schedule - Model Class for interacting
8 with Runtime Process Audit Schedules
9  
10 =head1 SYNOPSIS
11  
12 use ETLp::Audit::Browser::Model::Schedule;
13
14 my $model = ETLp::Audit::Browser::Model::Schedule->new();
15 my $processes = $model->get_schedules(
16 page => 1,
17 config_name => 'ApacheLogs',
18 section_name => 'NZServers'
19 );
20  
21 =cut
22  
23 class ETLp::Audit::Browser::Model::Schedule with
24 (ETLp::Role::Config, ETLp::Role::Schema, ETLp::Role::Audit,
25 ETLp::Role::Browser) {
26
27 use Data::Dumper;
28 use Try::Tiny;
29 use Text::Wrapper;
30 use Config::General qw(ParseConfig);
31 use File::Copy;
32 use File::Basename;
33 use DateTime;
34
35 =head1 METHODS
36  
37 =head2 get_schedules
38  
39 Returns a resultset on the ep_schedule table, based on the supplied criteria.
40 It will grab 10 rows at a time, and is ordered by date_updated descending
41  
42 =head3 Parameters
43
44 * page. Optional, Integer. The page you wish to return. Defaults
45 to 1.
46 * config_name: Optional. The name of the configuration file
47 * section_name. The name of the fection in the configuration file
48
49 =head3 Returns
50  
51 * A DBIx::Class resultset
52  
53 =cut
54  
55 method get_schedules(HashRef $args) {
56 my $page = $args->{page} || 1;
57 my $criteria = {};
58 my $filter = {
59 join => {'section' => ['config']},
60 prefetch => {'section' => ['config']},
61 order_by => ['config_name', 'section_name'],
62 };
63
64 unless ($args->{no_paging}) {
65 $filter->{page} = $page;
66 $filter->{rows} = 10;
67 }
68
69 # Add the filter if one was supplied
70 if ($args->{config_name}) {
71 $criteria->{'config_name'} = $args->{config_name};
72 }
73
74 if ($args->{section_name}) {
75 $criteria->{'section_name'} = $args->{section_name};
76 }
77
78 if (defined($args->{status}) && ($args->{status} ne '')) {
79 $criteria->{status} = $args->{status};
80 }
81
82 my $schedules = $self->EtlpSchedule->search($criteria, $filter);
83 return $schedules;
84 }
85  
86 =head2 get_schedule_details
87  
88 Returns an array ref consisting of the main schedule and associated
89 time componnets
90  
91 =head3 Parameters
92
93 * page. Optional, Integer. The page you wish to return. Defaults
94 to 1.
95 * config_name: Optional. The name of the configuration file
96 * section_name. The name of the fection in the configuration file
97 * status. Optional. (1 = active, 0 = inactive)
98
99 =head3 Returns
100  
101 An array ref of schedule details:
102  
103 * schedule_id
104 * minutes (cron format)
105 * hours (cron format)
106 * dom - day of month (cron format)
107 * days - days of the week (cron format)
108 * month - 1-12
109 * description - description of the schedule
110 * comment - any comment provided by the suer who edited the schedule
111 * status (1 = active, 0 = inactive)
112 * config_name - name of the configuration tghe schedule is processing
113 * section - the section inside the configuration file
114  
115 =cut
116  
117 method get_schedule_details(HashRef $args) {
118 my $schedule_details;
119 my @schedules;
120 my $schedules = $self->get_schedules($args);
121
122 # Loop through each shedule and add the time components to the returned
123 # records
124 while (my $schedule = $schedules->next) {
125 my $schedule_id = $schedule->schedule_id;
126 my $minutes = $self->get_contracted_minutes($schedule_id);
127 my $hours = $self->get_contracted_hours($schedule_id);
128 my $doms = $self->get_contracted_doms($schedule_id);
129 my $day_ids = $self->get_contracted_cron_dows($schedule_id);
130 my $days = join(', ', @{$self->get_day_names($schedule_id)}) || '';
131 my $month_rec = $self->get_schedule_month($schedule_id) || '';
132 my $month = ($month_rec) ? $month_rec->ep_month->month_name : '';
133 my $month_id = ($month_rec) ? $month_rec->month_id : '';
134
135 push @schedules,
136 {
137 schedule_id => $schedule_id,
138 minutes => $minutes,
139 hours => $hours,
140 doms => $doms,
141 day_ids => $day_ids,
142 days => $days,
143 month => $month,
144 month_id => $month_id,
145 description => $schedule->schedule_description,
146 comment => $schedule->schedule_comment,
147 status => $schedule->status,
148 config_name => $schedule->ep_section->ep_config->config_name,
149 section_name => $schedule->ep_section->section_name,
150 };
151 }
152
153 $self->logger->debug(Dumper(\@schedules));
154 return \@schedules;
155 }
156
157 =head2 get_day_names
158  
159 Get the day names for a schedule
160  
161 =head3 Parameters
162
163 * schedule_id. Optional. The schedule's key
164
165 =head3 Returns
166  
167 * An array ref of day names, in day-of-week order
168  
169 =cut
170  
171 method get_day_names(Int $schedule_id) {
172 my @days;
173
174 foreach my $day (
175 $self->EtlpDayOfWeek->search(
176 {schedule_id => $schedule_id},
177 {
178 join => 'ep_schedule_day_of_weeks',
179 order_by => 'dow_id'
180 }
181 )->all
182 )
183 {
184 ;
185 push @days, $day->day_name;
186 }
187
188 return \@days;
189 }
190  
191 =head2 get_schedule
192  
193 Returns the schedule withe the supplied id
194  
195 =head3 Parameters
196
197 * schedule_id. Optional. 1
198
199 =head3 Returns
200  
201 * A DBIx::Class row object
202  
203 =cut
204  
205 method get_schedule(Maybe[Int] $schedule_id?) {
206 return $self->EtlpSchedule->find($schedule_id);
207 }
208
209 =head2 get_months
210  
211 Returns all of the ep_months records
212  
213 =head3 Parameters
214  
215 None
216
217 =head3 Returns
218  
219 * An Array of DBIx::Class row objects
220  
221 =cut
222  
223 method get_months {
224 my @months = $self->EtlpMonth->search(undef, {order_by => 'month_id'})->all;
225 unshift @months, {month_id => undef, month_name => undef};
226 return \@months;
227 }
228
229 =head2 get_dows
230  
231 Gets all of the ep_days_of_month records
232  
233 =head3 Parameters
234  
235 None
236
237 =head3 Returns
238  
239 * An Array of DBIx::Class row objects
240  
241 =cut
242  
243 method get_dows {
244 return $self->EtlpDayOfWeek->search(undef, {order_by => 'dow_id'});
245 }
246
247 =head2 get_schedule_month
248  
249 Gets the month that the job is scheduled to run for
250  
251 =head3 Parameters
252  
253 * schedule_id. Integer
254
255 =head3 Returns
256  
257 * A EtlpScheduleMonth resultset row
258  
259 =cut
260
261 method get_schedule_month(Maybe[Int] $schedule_id?) {
262 return $self->EtlpScheduleMonth->search({schedule_id => $schedule_id},
263 {order_by => 'month_id'})->first;
264 }
265
266 =head2 get_schedule_dows
267  
268 Gets all of the days of the week that the job is scheduled to run for
269  
270 =head3 Parameters
271  
272 * schedule_id. Integer
273
274 =head3 Returns
275  
276 * A hashref, where the keys are the dow_ids that are scheduled
277  
278 =cut
279
280 method get_schedule_dows(Maybe[Int] $schedule_id?) {
281 my %dow;
282
283 my $dow_rs =
284 $self->EtlpScheduleDayOfWeek->search({schedule_id => $schedule_id},
285 {order_by => 'dow_id'});
286
287 while (my $dow_row = $dow_rs->next) {
288 my $dow_id = $dow_row->dow_id;
289 $dow{$dow_id}++;
290 }
291
292 return \%dow;
293 }
294
295 =head2 get_schedule_cron_dows
296  
297 Gets all of the days of the week that the job is scheduled to run for.
298 The days are indexed by the cron day ids (0-6 = Sun - Sat) not the
299 scheduled day of week surrogate key
300  
301 =head3 Parameters
302  
303 * schedule_id. Integer
304
305 =head3 Returns
306  
307 * A hashref, where the keys are the dow_ids that are scheduled
308  
309 =cut
310  
311 method get_schedule_cron_dows(Maybe[Int] $schedule_id?) {
312 my %dow;
313
314 my $dow_rs = $self->EtlpScheduleDayOfWeek->search(
315 {schedule_id => $schedule_id},
316 {
317 join => 'ep_day_of_week',
318 order_by => 'cron_day_id'
319 }
320 );
321
322 while (my $dow_row = $dow_rs->next) {
323 my $dow_id = $dow_row->ep_day_of_week->cron_day_id;
324 $dow{$dow_id}++;
325 }
326
327 return \%dow;
328 }
329  
330 =head2 get_schedule_doms
331  
332 Gets all of the days of the month that the job is scheduled to run for
333  
334 =head3 Parameters
335  
336 * schedule_id. Integer
337
338 =head3 Returns
339  
340 * A EtlpScheduleDayOfMonth resultset
341  
342 =cut
343  
344 method get_schedule_doms(Maybe[Int] $schedule_id?) {
345 return $self->EtlpScheduleDayOfMonth->search({schedule_id => $schedule_id},
346 {order_by => 'schedule_dom'});
347 }
348
349 =head2 get_schedule_minutes
350  
351 Gets all of the minutes that the job is scheduled to run for
352  
353 =head3 Parameters
354  
355 * schedule_id. Integer
356
357 =head3 Returns
358  
359 * A EtlpScheduleMinute resultset
360  
361 =cut
362  
363 method get_schedule_minutes(Maybe[Int] $schedule_id?) {
364 return $self->EtlpScheduleMinute->search({schedule_id => $schedule_id},
365 {order_by => 'schedule_minute'});
366 }
367
368 =head2 get_schedule_hours
369  
370 Gets all of the hours that the job is scheduled to run for
371  
372 =head3 Parameters
373  
374 * schedule_id. Integer
375
376 =head3 Returns
377  
378 * A EtlpScheduleHour resultset
379  
380 =cut
381  
382 method get_schedule_hours(Maybe[Int] $schedule_id?) {
383 return $self->EtlpScheduleHour->search({schedule_id => $schedule_id},
384 {order_by => 'schedule_hour'});
385 }
386  
387 =head2 expand_entries
388  
389 Takes section of cron entries for a given element (e.g. minutes), and
390 expands the into an array ref. If the section contains a range then
391 these are expanded into indvidual entries.
392  
393 =head3 Example
394  
395 '1-5,16-20,23'
396
397 becomes
398  
399 [1,2,3,4,5,16,17.18.19.20.23]
400  
401 =head3 Parameters
402  
403 * entries. String
404
405 =head3 Returns
406  
407 * An array ref of scheduled times
408  
409 =cut
410  
411 sub expand_entries {
412 my $entries = shift;
413 $entries =~ s/\s+//g;
414 my @entries = split /,/, $entries;
415 my @entry_list;
416
417 foreach my $entry (@entries) {
418 if ($entry =~ /^(\d{1,2})-(\d{1,2})$/) {
419 my ($lower, $upper) = ($1, $2);
420
421 if ($lower < $upper) {
422 for my $counter ($lower .. $upper) {
423 push @entry_list, $counter;
424 }
425 } else {
426 push @entry_list, $entry;
427 }
428 } else {
429 push @entry_list, $entry;
430 }
431 }
432
433 return @entry_list;
434 }
435
436 =head2 expand_days_of_week
437  
438 Similar to C<expand_entries>, Takes section of cron entries for
439 the day of the week. Cron expects entries to run from Sun (0) t0
440 Sat (6). Our input runs from (1-7) so we simply subtact 1 from each
441 entry
442  
443 =head3 Example
444  
445 '1-5,16-20,23'
446
447 becomes
448  
449 [1,2,3,4,5,16,17,18,19,20,23]
450  
451 =head3 Parameters
452  
453 * entries. String
454
455 =head3 Returns
456  
457 * A an arrarey of day elements
458  
459 =cut
460  
461 sub expand_days_of_week {
462 my @entry_list = expand_entries(shift);
463
464 foreach my $entry (@entry_list) {
465 $entry-- if ($entry =~ /^\d+$/);
466 }
467
468 return @entry_list;
469 }
470  
471 =head2 validate_entries
472  
473 Takes a list of entries (Comma-separated values), and makes sure that each
474 element is valid. The rules are
475  
476 * each element must consist of one or two digits
477 * each element must be greater than the previous one
478 * no entry can be greater than the limit for the type of entry
479 (e.g. minutes cannot be greater than 59, and hours can't
480 be greater than 23)
481  
482 =head3 Parameters
483  
484 An array consisting of the following entries:
485  
486 * entries. Mandatory. A string of comma-delimited entries
487 * upper_limit. Mandatory. The maximum value allowed
488 * zero_allowed. Optional. Whether or not 0 is a valid element for
489 this type of entry
490
491 =head3 Returns
492  
493 * 1 (valid) or 0 (invalid)
494  
495 =cut
496  
497 sub validate_entries {
498 my $entries = shift || die 'No entries to validate';
499 my $upper_limit = shift || die 'No upper limit';
500
501 # Can 0 be a valid entry?
502 my $zero_allowed = shift || 0;
503 my $lower_value = -1;
504
505 my @expanded_entries = @$entries;
506 foreach my $entry (@expanded_entries) {
507 if ($entry =~ /^(\d{1,2})$/) {
508 my $entry = $1;
509
510 if (($entry == 0) && (!$zero_allowed)) {
511 return 0;
512 }
513
514 if ($entry > $lower_value) {
515 $lower_value = $entry;
516 } else {
517 return 0;
518 }
519
520 if ($entry > $upper_limit) {
521 return 0;
522 }
523 } else {
524 return 0;
525 }
526 }
527
528 return 1;
529 }
530  
531 =head2 validate_hours
532  
533 Validates the cron entries for hours
534  
535 =head3 Parameters
536  
537 * entries. Mandatory. A string of comma-delimited entries
538
539 =head3 Returns
540  
541 * 1 (valid) or 0 (invalid)
542  
543 =cut
544  
545 method validate_hours(Str $hours) {
546 return validate_entries([expand_entries($hours)], 23, 1);
547 }
548  
549 =head2 validate_minutes
550  
551 Validates the cron entries for minutes
552  
553 =head3 Parameters
554  
555 * entries. Mandatory. A string of comma-delimited entries
556
557 =head3 Returns
558  
559 * 1 (valid) or 0 (invalid)
560  
561 =cut
562  
563 method validate_minutes(Str $minutes) {
564 return validate_entries([expand_entries($minutes)], 59, 1);
565 }
566  
567 =head2 validate_days_of_week
568  
569 Validates the cron entries for days of the week
570  
571 =head3 Parameters
572  
573 * entries. Mandatory. A string of comma-delimited entries
574
575 =head3 Returns
576  
577 * 1 (valid) or 0 (invalid)
578  
579 =cut
580  
581 method validate_days_of_week(Str $dow) {
582 return validate_entries([expand_days_of_week($dow)], 6, 1);
583 }
584  
585 =head2 validate_days_of_month
586  
587 Validates the cron entries for days of the month
588  
589 =head3 Parameters
590  
591 * entries. Mandatory. A string of comma-delimited entries
592
593 =head3 Returns
594  
595 * 1 (valid) or 0 (invalid)
596  
597 =cut
598  
599 method validate_days_of_month(Str $dom) {
600 return validate_entries([expand_entries($dom)], 31);
601 }
602  
603 =head2 validate_months
604  
605 Validates the cron entries for the month entries
606  
607 =head3 Parameters
608  
609 * entries. Mandatory. A string of comma-delimited entries
610
611 =head3 Returns
612  
613 * 1 (valid) or 0 (invalid)
614  
615 =cut
616  
617 method validate_months(Str $months) {
618 return validate_entries([expand_entries($months)], 12);
619 }
620  
621 =head2 contract_entries
622  
623 Takes an array ref of cron entries and turns them back into
624 a cron string. Consectutive values are turned into ranges, i.e.
625  
626 [1,4,5,6,10]
627
628 Becomes
629  
630 '1,4-6,10'
631  
632 =head3 Parameters
633  
634 * entries. Mandatory. A string of comma-delimited entries
635
636 =head3 Returns
637  
638 * 1 (valid) or 0 (invalid)
639  
640 =cut
641  
642 sub contract_entries {
643 my $entries = shift || die "No entries to concatenate";
644 my $low_value;
645 my @new_entries;
646 my $grouping = 0;
647
648 foreach my $idx (0 .. @$entries - 1) {
649 if ($grouping) {
650 if ($entries->[$idx] != ($entries->[$idx - 1] + 1)) {
651 $grouping = 0;
652 push @new_entries, $low_value . '-' . $entries->[$idx - 1];
653 $low_value = undef;
654 }
655 }
656
657 if ($idx <= @$entries - 2) {
658 if (!$grouping) {
659 if (($entries->[$idx] + 1) == $entries->[$idx + 1]) {
660 $grouping = 1;
661 $low_value = $entries->[$idx];
662 } else {
663 push @new_entries, $entries->[$idx] if !$grouping;
664 }
665 }
666 } elsif ($idx == @$entries - 1) {
667 if ($grouping) {
668 push @new_entries, $low_value . '-' . $entries->[$idx];
669 } else {
670 push @new_entries, $entries->[$idx];
671 }
672 }
673 }
674
675 return join(',', @new_entries);
676 }
677  
678 =head2 get_contracted_doms
679  
680 Returns the days of month cron string for a given schedule.
681  
682 =head3 Parameters
683  
684 * schedule_id. Integer. Optional. The primary key of the schedule
685
686 =head3 Returns
687  
688 * cron entry string
689  
690 =cut
691  
692 method get_contracted_doms(Maybe[Int] $schedule_id?) {
693 my $doms_rs = $self->get_schedule_doms($schedule_id);
694 my (@schedule_doms, $dom_ids);
695
696 while (my $dom = $doms_rs->next) {
697 push @schedule_doms, $dom->schedule_dom;
698 }
699
700 $self->logger->debug(Dumper(\@schedule_doms));
701
702 return contract_entries(\@schedule_doms);
703 }
704  
705 =head2 get_contracted_cron_dows
706  
707 Returns the days of the week cron string for a given schedule.
708  
709 =head3 Parameters
710  
711 * schedule_id. Integer. Optional. The primary key of the schedule
712
713 =head3 Returns
714  
715 * cron entry string
716  
717 =cut
718  
719 method get_contracted_cron_dows(Maybe[Int] $schedule_id?) {
720 my $dows = [sort keys %{$self->get_schedule_cron_dows($schedule_id)}];
721 return contract_entries($dows);
722 }
723
724 =head2 get_contracted_hours
725  
726 Returns thehours of execution cron string for a given schedule.
727  
728 =head3 Parameters
729  
730 * schedule_id. Integer. Optional. The primary key of the schedule
731
732 =head3 Returns
733  
734 * cron entry string
735  
736 =cut
737  
738 method get_contracted_hours(Maybe[Int] $schedule_id?) {
739 my $hours_rs = $self->get_schedule_hours($schedule_id);
740 my (@schedule_hours, $hour_ids);
741
742 while (my $hour = $hours_rs->next) {
743 push @schedule_hours, $hour->schedule_hour;
744 }
745
746 $self->logger->debug(Dumper(\@schedule_hours));
747
748 return contract_entries(\@schedule_hours);
749 }
750  
751 =head2 get_contracted_minutes
752  
753 Returns the minutes of execution cron string for a given schedule.
754  
755 =head3 Parameters
756  
757 * schedule_id. Integer. Optional. The primary key of the schedule
758
759 =head3 Returns
760  
761 * cron entry string
762  
763 =cut
764  
765 method get_contracted_minutes(Maybe[Int] $schedule_id?) {
766 my $minutes_rs = $self->get_schedule_minutes($schedule_id);
767 my (@schedule_minutes, $minute_ids);
768
769 while (my $minute = $minutes_rs->next) {
770 push @schedule_minutes, $minute->schedule_minute;
771 }
772
773 $self->logger->debug(Dumper(\@schedule_minutes));
774
775 return contract_entries(\@schedule_minutes);
776 }
777
778 =head2 save
779  
780 Saves the schedule to the database
781  
782 =head3 Parameters
783  
784 * params. A hashref of containing the schedule data
785
786 =head3 Returns
787  
788 * Void
789  
790 =cut
791  
792 method save (HashRef $params) {
793 my $schedule;
794
795 $self->logger->debug(Dumper($params));
796 $params->{status} = 0 unless $params->{status};
797
798 $self->logger->debug("Getting the date");
799 my $date = $self->now;
800 $self->logger->debug("Got the date");
801
802 $self->logger->debug('schema: ' . ref($self->schema));
803
804 try{
805 $self->schema->txn_do(
806 sub {
807 # If we were supplied a schedule id then we update an existing
808 # schedule
809
810 $self->logger->debug('Getting config record');
811
812 my $config = $self->EtlpConfiguration->single(
813 {config_name => $params->{config_file}});
814
815 $self->logger->debug('Got config record or a null');
816
817 unless ($config) {
818 $self->logger->debug('Creating a config record');
819 $config = $self->EtlpConfiguration->create(
820 {
821 config_name => $params->{config_file},
822 date_created => $date,
823 date_updated => $date,
824 }
825 );
826 $self->logger->debug('Created a config record');
827 }
828
829 $self->logger->debug("Config: " . $config->config_id);
830
831 my $section = $self->EtlpSection->single(
832 {
833 section_name => $params->{section},
834 config_id => $config->config_id
835 }
836 );
837
838 unless ($section) {
839 $section = $self->EtlpSection->create(
840 {
841 section_name => $params->{section},
842 config_id => $config->config_id,
843 date_created => $date,
844 date_updated => $date,
845 }
846 );
847 }
848
849 my $section_id = $section->section_id;
850 $self->logger->debug("Section: " . $section_id);
851
852 if ($params->{schedule_id}) {
853 $self->logger->debug(
854 'Updating the schedule ' . $params->{schedule_id});
855 $schedule = $self->EtlpSchedule->single(
856 {schedule_id => $params->{schedule_id}});
857
858 $schedule->update(
859 {
860 'schedule_description' =>
861 $params->{schedule_description},
862 'schedule_comment' => $params->{schedule_comment},
863 'status' => $params->{status},
864 'user_updated' => $params->{user_id},
865 'date_updated' => $date,
866 'section_id' => $section_id,
867 }
868 );
869 $self->logger->debug('Schedule updated');
870 } else {
871 # create a new schedule
872 $self->logger->debug('Creating a new schedule');
873 $schedule = $self->EtlpSchedule->create(
874 {
875 schedule_description => $params->{schedule_description},
876 schedule_comment => $params->{schedule_comment},
877 status => $params->{status},
878 user_created => $params->{'user_id'},
879 user_updated => $params->{'user_id'},
880 date_created => $date,
881 date_updated => $date,
882 section_id => $section->section_id,
883 }
884 );
885 }
886
887 my $schedule_id = $schedule->schedule_id;
888 # Delete old minutes and add new ones
889 my $minutes = $self->EtlpScheduleMinute->search(
890 {schedule_id => $schedule->schedule_id});
891 $minutes->delete_all;
892
893 $self->EtlpScheduleMinute->populate(
894 [
895 [qw/schedule_id schedule_minute/],
896 map { [$schedule_id, $_] }
897 expand_entries($params->{schedule_minutes})
898 ]
899 ) if defined $params->{schedule_minutes};
900
901 # Delete old hours and add new ones
902 my $hours = $self->EtlpScheduleHour->search(
903 {schedule_id => $schedule->schedule_id});
904 $hours->delete_all;
905 $self->EtlpScheduleHour->populate(
906 [
907 [qw/schedule_id schedule_hour/],
908 map { [$schedule_id, $_] }
909 expand_entries($params->{schedule_hours})
910 ]
911 ) if defined $params->{schedule_hours};
912
913 # Delete old days of month and add new ones
914 my $doms = $self->EtlpScheduleDayOfMonth->search(
915 {schedule_id => $schedule->schedule_id});
916 $doms->delete_all;
917 $self->EtlpScheduleDayOfMonth->populate(
918 [
919 [qw/schedule_id schedule_dom/],
920 map { [$schedule_id, $_] }
921 expand_entries($params->{schedule_doms})
922 ]
923 ) if defined $params->{schedule_doms};
924
925 # This relies on the fact that there is only one schedule month
926 # record, although the data model allows for an arbitrary number
927 my $month = $self->EtlpScheduleMonth->search(
928 {schedule_id => $schedule->schedule_id})->first;
929
930 # If we received a month
931 if (defined $params->{month_id}) {
932 # if we have a month record then update it...
933 if (defined $month) {
934 $month->month_id($params->{month_id});
935 $month->update;
936 }
937 # ... else create its
938 else {
939 $month = $self->EtlpScheduleMonth->create(
940 {
941 schedule_id => $schedule_id,
942 month_id => $params->{month_id}
943 }
944 );
945 }
946 }
947 # ... else delete any existing month
948 else {
949 $self->EtlpScheduleMonth->search(
950 {schedule_id => $schedule->schedule_id})->delete_all();
951 }
952
953 if (ref $params->{dow_id} ne 'ARRAY') {
954 $params->{dow_id} = [$params->{dow_id}];
955 }
956
957 $self->logger->debug('dow_id: ', Dumper($params->{dow_id}));
958
959 # Delete old days of the week and add new ones
960 $self->EtlpScheduleDayOfWeek->search(
961 {schedule_id => $schedule->schedule_id})->delete_all();
962
963 if (defined $params->{dow_id}->[0]) {
964 $self->EtlpScheduleDayOfWeek->populate(
965 [
966 [qw/schedule_id dow_id/],
967 map { [$schedule_id, $_] } @{$params->{dow_id}}
968 ]
969 );
970 }
971
972 }
973 );
974 } catch {
975 $self->logger->logdie($_);
976 };
977 return $schedule->schedule_id;
978 }
979
980 =head2 get_scheduler_status
981  
982 Sets the scheduler status
983  
984 =head3 Parameters
985  
986 None
987
988 =head3 Returns
989  
990 * An ep_app_config DBIx::Class row
991  
992 =cut
993  
994 method get_scheduler_status {
995 return $self->EtlpAppConfig->single({'parameter' => 'scheduler status'});
996 }
997
998 =head2 generate_crontab
999  
1000 Generates a crontab from the database schedues
1001  
1002 =head3 Parameters
1003  
1004 * pipeline script. String. Full path to the etl-pipeline script
1005
1006 =head3 Returns
1007  
1008 * crontab as a string
1009  
1010 =cut
1011  
1012 method generate_crontab($pipeline_script) {
1013 my $wrapper = Text::Wrapper->new(columns => 70);
1014
1015 my $schedule_status = $self->get_scheduler_status();
1016
1017 my $crontab = <<EOT;
1018 # WARNING: This file was generated by ETLp. DO not edit by hand
1019 # or your changes will be lost
1020 #
1021 # field allowed values
1022 # ============= =================================
1023 # minute 0-59
1024 # hour 0-23
1025 # day of month 1-31
1026 # month 1-12 (or names, see below)
1027 # day of week 0-7 (0 or 7 is Sun, or use names)
1028 #
1029 EOT
1030
1031 foreach my $schedule (@{$self->get_schedule_details({no_paging => 1})}) {
1032 if ($schedule->{description}) {
1033 # Wrap the description at 60 columns
1034 my @descriptions = split /\n/, $schedule->{description};
1035
1036 foreach my $description (@descriptions) {
1037 $description = $wrapper->wrap($description);
1038 $description =~ s/^/# /mg;
1039 }
1040
1041 $schedule->{description} = join("\n", @descriptions);
1042 $schedule->{description} =~ s/\n+/\n/g;
1043 $crontab .= $schedule->{description};
1044 }
1045
1046 $crontab .= '#' unless ($schedule_status->value() eq 'enabled');
1047 $crontab .= '#' unless $schedule->{status};
1048 $schedule->{minutes} = '*' unless $schedule->{minutes} =~ /\d/;
1049 $schedule->{hours} = '*' unless $schedule->{hours} =~ /\d/;
1050 $schedule->{doms} = '*' unless $schedule->{doms} =~ /\d/;
1051 $schedule->{month_id} = '*' unless $schedule->{month_id} =~ /\d/;
1052 $schedule->{day_ids} = '*' unless $schedule->{day_ids} =~ /\d/;
1053
1054 $crontab .= sprintf(
1055 "%s %s %s %s %s $pipeline_script %s %s\n",
1056 $schedule->{minutes}, $schedule->{hours},
1057 $schedule->{doms}, $schedule->{month_id},
1058 $schedule->{day_ids}, $schedule->{config_name},
1059 $schedule->{section_name}
1060 );
1061 }
1062
1063 return $crontab;
1064
1065 }
1066
1067 =head2 get_config_files
1068  
1069 Get a list of configuration files in the application configuration
1070 directory
1071  
1072 =head3 Parameters
1073  
1074 * config_dir. String. Mandatory. The directory that stores the config files
1075
1076 =head3 Returns
1077  
1078 * An array ref of configuration files
1079  
1080 =cut
1081  
1082 method get_config_files (Maybe[Str] $config_dir?) {
1083 my @configuration_files;
1084
1085 opendir(my $dir, $config_dir)
1086 || $self->logger->logdie("Cannot open $config_dir");
1087
1088 while (defined(my $file = readdir($dir))) {
1089 next unless -f $config_dir . '/' . $file;
1090 next if $file eq 'env.conf';
1091 if ($file =~ /^(.*)\.conf$/) {
1092 push @configuration_files, $1;
1093 }
1094 }
1095
1096 return [sort @configuration_files];
1097 }
1098  
1099 =head2 set_scheduler_status
1100  
1101 Sets the scheduler status
1102  
1103 =head3 Parameters
1104  
1105 A string
1106  
1107 * The scheduler status
1108
1109 =head3 Returns
1110  
1111 * Void
1112  
1113 =cut
1114  
1115 method set_scheduler_status(Str $status) {
1116 my $schedule_status = $self->get_scheduler_status;
1117 $schedule_status->update({value => $status});
1118 }
1119  
1120 =head2 get_sections
1121  
1122 Get all of the sections in a configurations file
1123  
1124 =head3 Parameters
1125  
1126 * configuration file. String. The *full* path to the configuration file
1127
1128 =head3 Returns
1129  
1130 * An array ref of sections
1131  
1132 =cut
1133  
1134 method get_sections(Str $configuration_file) {
1135 $configuration_file .= '.conf';
1136
1137 my %config = ParseConfig(-ConfigFile => $configuration_file,);
1138 return [sort(keys %config)];
1139 }
1140  
1141 =head2 get_job
1142  
1143 Given a schedule (an EPSection record), returns the job (configuration
1144 file name, section name)
1145  
1146 =head3 Parameters
1147  
1148 * configuration file. String. The *full* path to the configuration file
1149
1150 =head3 Returns
1151  
1152 * An array; config name, section name
1153  
1154 =cut
1155  
1156 method get_job($schedule) {
1157 return ($schedule->section->ep_config->config_name,
1158 $schedule->section->section_name);
1159 }
1160  
1161 =head2 get_section_options
1162  
1163 Given a config file, return the list of sections - each element
1164 will apear in HTML option tags
1165  
1166 =head3 Parameters
1167  
1168 * configuration file. String. The configuration file name
1169
1170 =head3 Returns
1171  
1172 * An HTML string
1173  
1174 =cut
1175  
1176 method get_section_options(HashRef $args) {
1177 my $app_conf_dir = $args->{app_conf_dir};
1178 my $config_file = $args->{config_file};
1179 my $show_blank = $args->{show_blank};
1180 my $sections = $self->get_sections($app_conf_dir . '/' . $config_file);
1181 my $options;
1182
1183 my $counter = 1;
1184
1185 if ($show_blank) {
1186 $options = '<option selected="selected"></option>';
1187 }
1188
1189 foreach my $section (@$sections) {
1190 if (($counter++ == 1) && !($show_blank)) {
1191 $options .=
1192 qq{<option value="$section" selected="selected">$section</option>};
1193 } else {
1194 $options .= qq{<option value="$section">$section</option>};
1195 }
1196 }
1197
1198 return $options;
1199 }
1200  
1201 =head2 config_exists
1202  
1203 Determines whether a configuration file exists
1204  
1205 =head3 Parameters
1206  
1207 * configuration file. String. The pull path to the configuration
1208 file name, excluding the .conf extension
1209
1210 =head3 Returns
1211  
1212 * 1 = true, 0 = false
1213  
1214 =cut
1215  
1216 method config_exists(Str $config_file) {
1217 return (-f $config_file . '.conf') ? 1 : 0;
1218 }
1219  
1220 =head2 delete
1221  
1222 Deletes a schedule, and dependent records
1223  
1224 =head3 Parameters
1225  
1226 * schedule_id. Integer. The surrogate key for the schedule
1227
1228 =head3 Returns
1229  
1230 * Void
1231  
1232 =cut
1233  
1234 method delete(Int $schedule_id) {
1235 my $schedule_rs = $self->EtlpSchedule->search(schedule_id => $schedule_id);
1236 my $minutes_rs =
1237 $self->EtlpScheduleMinute->search({schedule_id => $schedule_id});
1238 my $hours_rs = $self->EtlpScheduleHour->search({schedule_id => $schedule_id});
1239 my $dow_rs =
1240 $self->EtlpScheduleDayOfWeek->search({schedule_id => $schedule_id});
1241 my $dom_rs =
1242 $self->EtlpScheduleDayOfMonth->search({schedule_id => $schedule_id});
1243 my $month_rs =
1244 $self->EtlpScheduleMonth->search({schedule_id => $schedule_id});
1245
1246 $self->schema->txn_do(
1247 sub {
1248 $month_rs->delete_all;
1249 $dom_rs->delete_all;
1250 $dow_rs->delete_all;
1251 $hours_rs->delete_all;
1252 $minutes_rs->delete_all;
1253 $schedule_rs->delete_all;
1254 }
1255 );
1256 }
1257  
1258 =head2 get_dependencies
1259  
1260 Returns the last of dependent jobs as specified by the "next" parameter
1261 in the application config.
1262  
1263 =head3 Parameters
1264  
1265 A hashref:
1266  
1267 * config_dir. String. The directory where the configuration files
1268 are found
1269 * config_file. String. The root config file
1270 * section. The section on the config file that we wish to derive
1271 the dependencies from
1272
1273 =head3 Returns
1274  
1275 * dependencies as an array
1276  
1277 =cut
1278  
1279 method get_dependencies(Str :$config_dir, Str :$config_file, Str :$section) {
1280 my @dependencies;
1281
1282 $config_file .= '.conf' unless $config_file =~ /\.conf$/;
1283 $config_file = $config_dir . '/' . $config_file;
1284
1285 my %config = ParseConfig(-ConfigFile => $config_file,);
1286 if ($config{$section}->{config}->{next}) {
1287 my ($new_config_file, $new_section) = split /\s+/,
1288 $config{$section}->{config}->{next};
1289 push @dependencies, $config{$section}->{config}->{next},
1290 $self->get_dependencies(
1291 #{
1292 config_dir => $config_dir,
1293 config_file => $new_config_file,
1294 section => $new_section
1295 #}
1296 );
1297 }
1298
1299 return @dependencies;
1300 }
1301 }
1302