RT#14829: automatic payments triggered by bill now show up as Payment by fs_queue
[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|part_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       # switch user only if a job user is available
222       my $oldCurrentUser = $FS::CurrentUser::CurrentUser;
223       my $jobuser = $ljob->access_user;
224       local $FS::CurrentUser::CurrentUser = $jobuser if $jobuser;
225       local $FS::UID::AutoCommit = 0; # so that we can clean up failures
226       eval $eval; #throw away return value?  suppose so
227       $FS::CurrentUser::CurrentUser = $oldCurrentUser if $jobuser;
228       if ( $@ ) {
229         dbh->rollback;
230         my %hash = $ljob->hash;
231         $hash{'statustext'} = $@;
232         if ( $hash{'statustext'} =~ /\/misc\/queued_report/ ) { #use return?
233           $hash{'status'} = 'done'; 
234         } else {
235           $hash{'status'} = 'failed';
236           warn "job $eval failed";
237         }
238         my $fjob = new FS::queue( \%hash );
239         my $error = $fjob->replace($ljob);
240         die $error if $error;
241         dbh->commit; # for the status change only
242       } else {
243         $ljob->delete;
244         dbh->commit; # for the job itself
245       }
246
247       if ( $ljob->job eq 'FS::cust_main::queued_bill' ) {
248         my $queue_stat = new FS::queue_stat {
249           'jobnum'      => $ljob->jobnum,
250           'job'         => $ljob->job,
251           'custnum'     => $ljob->custnum,
252           'insert_date' => $ljob->_date,
253           'start_date'  => $start_date,
254           'end_date'    => time,
255         };
256         my $error = $queue_stat->insert;
257         die $error if $error;
258         dbh->commit; #for the stat
259       }
260
261       if ( UNIVERSAL::can(dbh, 'sprintProfile') ) {
262         open(PROFILE,">%%%FREESIDE_LOG%%%/queueprofile.$$.".time)
263           or die "can't open profile file: $!";
264         print PROFILE dbh->sprintProfile();
265         close PROFILE or die "can't close profile file: $!";
266       }
267
268       exit;
269       #end-of-kid
270     }
271
272   } #foreach my $job
273
274 } continue {
275   if ( sigterm() ) {
276     warn "received TERM signal; exiting\n";
277     exit;
278   }
279   if ( sigint() ) {
280     warn "received INT signal; exiting\n";
281     exit;
282   }
283 }
284
285 sub untaint_argv {
286   foreach $_ ( $[ .. $#ARGV ) { #untaint @ARGV
287     #$ARGV[$_] =~ /^([\w\-\/]*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
288     # Date::Parse
289     $ARGV[$_] =~ /^(.*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
290     $ARGV[$_]=$1;
291   }
292 }
293
294 sub usage {
295   die "Usage:\n\n  freeside-queued user\n";
296 }
297
298 sub reap_kids {
299   foreach my $pid ( keys %kids ) {
300     my $kid = waitpid($pid, WNOHANG);
301     if ( $kid > 0 ) {
302       $kids--;
303       delete $kids{$kid};
304     }
305   }
306 }
307
308 =head1 NAME
309
310 freeside-queued - Job queue daemon
311
312 =head1 SYNOPSIS
313
314   freeside-queued [ -s | -n ] user
315
316 =head1 DESCRIPTION
317
318 Job queue daemon.  Should be running at all times.
319
320 -s: "secure" jobs only (queued billing jobs)
321
322 -n: non-"secure" jobs only (other jobs)
323
324 user: Typically "fs_queue"
325
326 =head1 VERSION
327
328 =head1 BUGS
329
330 =head1 SEE ALSO
331
332 =cut
333