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