add -s and -n flags to freeside-daily to specify the kinds of jobs to be run, RT...
[freeside.git] / FS / bin / freeside-queued
1 #!/usr/bin/perl -w
2
3 use strict;
4 use vars qw( $DEBUG $kids $max_kids %kids );
5 use POSIX qw(:sys_wait_h);
6 use IO::File;
7 use Getopt::Std;
8 use FS::UID qw(adminsuidsetup forksuidsetup driver_name dbh myconnect);
9 use FS::Daemon qw(daemonize1 drop_root logfile daemonize2 sigint sigterm);
10 use FS::Conf;
11 use FS::Record qw(qsearch);
12 use FS::queue;
13 use FS::queue_depend;
14
15 # no autoloading for non-FS classes...
16 use Net::SSH 0.07;
17
18 $DEBUG = 0;
19
20 $kids = 0;
21
22 &untaint_argv;  #what it sounds like  (eww)
23 use vars qw(%opt);
24 getopts('sn', \%opt );
25
26 my $user = shift or die &usage;
27
28 warn "starting daemonization (forking)\n" if $DEBUG;
29 #daemonize1('freeside-queued',$user); #to keep pid files unique w/multi installs
30 daemonize1('freeside-queued');
31
32 warn "dropping privledges\n" if $DEBUG;
33 drop_root();
34
35 $ENV{HOME} = (getpwuid($>))[7]; #for ssh
36
37 warn "connecting to database\n" if $DEBUG;
38 $@ = 'not connected';
39 while ( $@ ) {
40   eval { adminsuidsetup $user; };
41   if ( $@ ) {
42     warn $@;
43     warn "sleeping for reconnect...\n";
44     sleep 5;
45   }
46 }
47
48 logfile( "%%%FREESIDE_LOG%%%/queuelog.". $FS::UID::datasrc );
49
50 warn "completing daemonization (detaching))\n" if $DEBUG;
51 daemonize2();
52
53 #--
54
55 my $conf = new FS::Conf;
56 $max_kids = $conf->config('queued-max_kids') || 10;
57
58 my $warnkids=0;
59 while (1) {
60
61   &reap_kids;
62   #prevent runaway forking
63   if ( $kids >= $max_kids ) {
64     warn "WARNING: maximum $kids children reached\n" unless $warnkids++;
65     &reap_kids;
66     sleep 1; #waiting for signals is cheap
67     next;
68   }
69   $warnkids=0;
70
71   unless ( dbh && dbh->ping ) {
72     warn "WARNING: connection to database lost, reconnecting...\n";
73
74     eval { $FS::UID::dbh = myconnect; };
75
76     unless ( !$@ && dbh && dbh->ping ) {
77       warn "WARNING: still no connection to database, sleeping for retry...\n";
78       sleep 10;
79       next;
80     } else {
81       warn "WARNING: reconnected to database\n";
82     }
83   }
84
85   #my($job, $ljob);
86   #{
87   #  my $oldAutoCommit = $FS::UID::AutoCommit;
88   #  local $FS::UID::AutoCommit = 0;
89   $FS::UID::AutoCommit = 0;
90
91   my $nodepend = 'AND NOT EXISTS( SELECT 1 FROM queue_depend'.
92                  '           WHERE queue_depend.jobnum = queue.jobnum )';
93
94   #anything with a priority goes after stuff without one
95   my $order_by = ' ORDER BY COALESCE(priority,0) ASC, jobnum ASC ';
96
97   my $limit = $max_kids - $kids;
98
99   $order_by .= ( driver_name eq 'mysql'
100                    ? " LIMIT $limit FOR UPDATE "
101                    : " FOR UPDATE LIMIT $limit " );
102
103   my $hashref = { 'status' => 'new' };
104   if ( $opt{'s'} ) {
105     $hashref->{'status'} = 'Y';
106   } elsif ( $opt{'n'} ) {
107     $hashref->{'status'} = '';
108   }
109
110   my @jobs = qsearch({
111     'table'     => 'queue',
112     'hashref'   => $hashref,
113     'extra_sql' => $nodepend,
114     'order_by'  => $order_by,
115   });
116
117   unless ( @jobs ) {
118     dbh->commit or do {
119       warn "WARNING: database error, closing connection: ". dbh->errstr;
120       undef $FS::UID::dbh;
121       next;
122     };
123     sleep 1;
124     next;
125   }
126
127   foreach my $job ( @jobs ) {
128
129     my %hash = $job->hash;
130     $hash{'status'} = 'locked';
131     my $ljob = new FS::queue ( \%hash );
132     my $error = $ljob->replace($job);
133     if ( $error ) {
134       warn "WARNING: database error locking job, closing connection: ".
135            dbh->errstr;
136       undef $FS::UID::dbh;
137       next;
138     }
139
140     dbh->commit or do {
141       warn "WARNING: database error, closing connection: ". dbh->errstr;
142       undef $FS::UID::dbh;
143       next;
144     };
145
146     $FS::UID::AutoCommit = 1;
147
148     my @args = $ljob->args;
149     splice @args, 0, 1, $ljob if $args[0] eq '_JOB';
150
151     defined( my $pid = fork ) or do {
152       warn "WARNING: can't fork: $!\n";
153       my %hash = $job->hash;
154       $hash{'status'} = 'failed';
155       $hash{'statustext'} = "[freeside-queued] can't fork: $!";
156       my $ljob = new FS::queue ( \%hash );
157       my $error = $ljob->replace($job);
158       die $error if $error;
159       next; #don't increment the kid counter
160     };
161
162     if ( $pid ) {
163       $kids++;
164       $kids{$pid} = 1;
165     } else { #kid time
166
167       #get new db handle
168       $FS::UID::dbh->{InactiveDestroy} = 1;
169
170       forksuidsetup($user);
171
172       dbh->{'private_profile'} = {} if UNIVERSAL::can(dbh, 'sprintProfile');
173
174       #auto-use classes...
175       if (    $ljob->job =~ /(FS::(part_export|cust_main)::\w+)::/
176            || $ljob->job =~ /(FS::\w+)::/
177          )
178       {
179         my $class = $1;
180         eval "use $class;";
181         if ( $@ ) {
182           warn "job use $class failed";
183           my %hash = $ljob->hash;
184           $hash{'status'} = 'failed';
185           $hash{'statustext'} = $@;
186           my $fjob = new FS::queue( \%hash );
187           my $error = $fjob->replace($ljob);
188           die $error if $error;
189           exit; #end-of-kid
190         };
191       }
192
193       my $eval = "&". $ljob->job. '(@args);';
194       warn 'running "&'. $ljob->job. '('. join(', ', @args). ")\n" if $DEBUG;
195       eval $eval; #throw away return value?  suppose so
196       if ( $@ ) {
197         warn "job $eval failed";
198         my %hash = $ljob->hash;
199         $hash{'status'} = 'failed';
200         $hash{'statustext'} = $@;
201         my $fjob = new FS::queue( \%hash );
202         my $error = $fjob->replace($ljob);
203         die $error if $error;
204       } else {
205         $ljob->delete;
206       }
207
208       if ( UNIVERSAL::can(dbh, 'sprintProfile') ) {
209         open(PROFILE,">%%%FREESIDE_LOG%%%/queueprofile.$$.".time)
210           or die "can't open profile file: $!";
211         print PROFILE dbh->sprintProfile();
212         close PROFILE or die "can't close profile file: $!";
213       }
214
215       exit;
216       #end-of-kid
217     }
218
219   } #foreach my $job
220
221 } continue {
222   if ( sigterm() ) {
223     warn "received TERM signal; exiting\n";
224     exit;
225   }
226   if ( sigint() ) {
227     warn "received INT signal; exiting\n";
228     exit;
229   }
230 }
231
232 sub untaint_argv {
233   foreach $_ ( $[ .. $#ARGV ) { #untaint @ARGV
234     #$ARGV[$_] =~ /^([\w\-\/]*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
235     # Date::Parse
236     $ARGV[$_] =~ /^(.*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
237     $ARGV[$_]=$1;
238   }
239 }
240
241 sub usage {
242   die "Usage:\n\n  freeside-queued user\n";
243 }
244
245 sub reap_kids {
246   foreach my $pid ( keys %kids ) {
247     my $kid = waitpid($pid, WNOHANG);
248     if ( $kid > 0 ) {
249       $kids--;
250       delete $kids{$kid};
251     }
252   }
253 }
254
255 =head1 NAME
256
257 freeside-queued - Job queue daemon
258
259 =head1 SYNOPSIS
260
261   freeside-queued [ -s | -n ] user
262
263 =head1 DESCRIPTION
264
265 Job queue daemon.  Should be running at all times.
266
267 -s: "secure" jobs only (queued billing jobs)
268
269 -n: non-"secure" jobs only (other jobs)
270
271 user: from the mapsecrets file - see config.html from the base documentation
272
273 =head1 VERSION
274
275 =head1 BUGS
276
277 =head1 SEE ALSO
278
279 =cut
280