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