d5d84cced44442b32c6ade32810c69cccd589b1b
[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->{'secure'} = 'Y';
106   } elsif ( $opt{'n'} ) {
107     $hashref->{'secure'} = '';
108   }
109
110   #qsearch dies when the db goes away
111   my @jobs = eval {
112     qsearch({
113       'table'     => 'queue',
114       'hashref'   => $hashref,
115       'extra_sql' => $nodepend,
116       'order_by'  => $order_by,
117     });
118   };
119   if ( $@ ) {
120     warn "WARNING: error searching for jobs, closing connection: $@";
121     undef $FS::UID::dbh;
122     next;
123   }
124
125   unless ( @jobs ) {
126     dbh->commit or do {
127       warn "WARNING: database error, closing connection: ". dbh->errstr;
128       undef $FS::UID::dbh;
129       next;
130     };
131     sleep 1;
132     next;
133   }
134
135   foreach my $job ( @jobs ) {
136
137     my %hash = $job->hash;
138     $hash{'status'} = 'locked';
139     my $ljob = new FS::queue ( \%hash );
140     my $error = $ljob->replace($job);
141     if ( $error ) {
142       warn "WARNING: database error locking job, closing connection: ".
143            dbh->errstr;
144       undef $FS::UID::dbh;
145       next;
146     }
147
148     dbh->commit or do {
149       warn "WARNING: database error, closing connection: ". dbh->errstr;
150       undef $FS::UID::dbh;
151       next;
152     };
153
154     $FS::UID::AutoCommit = 1;
155
156     my @args = eval { $ljob->args; };
157     if ( $@ ) {
158       warn "WARNING: error retrieving job arguments, closing connection: $@";
159       undef $FS::UID::dbh;
160       next;
161     }
162     splice @args, 0, 1, $ljob if $args[0] eq '_JOB';
163
164     defined( my $pid = fork ) or do {
165       warn "WARNING: can't fork: $!\n";
166       my %hash = $job->hash;
167       $hash{'status'} = 'failed';
168       $hash{'statustext'} = "[freeside-queued] can't fork: $!";
169       my $ljob = new FS::queue ( \%hash );
170       my $error = $ljob->replace($job);
171       die $error if $error; #XXX still dying if we can't fork AND we can't connect to the db
172       next; #don't increment the kid counter
173     };
174
175     if ( $pid ) {
176       $kids++;
177       $kids{$pid} = 1;
178     } else { #kid time
179
180       #get new db handle
181       $FS::UID::dbh->{InactiveDestroy} = 1;
182
183       forksuidsetup($user);
184
185       dbh->{'private_profile'} = {} if UNIVERSAL::can(dbh, 'sprintProfile');
186
187       #auto-use classes...
188       if (    $ljob->job =~ /(FS::(part_export|cust_main)::\w+)::/
189            || $ljob->job =~ /(FS::\w+)::/
190          )
191       {
192         my $class = $1;
193         eval "use $class;";
194         if ( $@ ) {
195           warn "job use $class failed";
196           my %hash = $ljob->hash;
197           $hash{'status'} = 'failed';
198           $hash{'statustext'} = $@;
199           my $fjob = new FS::queue( \%hash );
200           my $error = $fjob->replace($ljob);
201           die $error if $error;
202           exit; #end-of-kid
203         };
204       }
205
206       my $eval = "&". $ljob->job. '(@args);';
207       warn 'running "&'. $ljob->job. '('. join(', ', @args). ")\n" if $DEBUG;
208       eval $eval; #throw away return value?  suppose so
209       if ( $@ ) {
210         warn "job $eval failed";
211         my %hash = $ljob->hash;
212         $hash{'status'} = 'failed';
213         $hash{'statustext'} = $@;
214         my $fjob = new FS::queue( \%hash );
215         my $error = $fjob->replace($ljob);
216         die $error if $error;
217       } else {
218         $ljob->delete;
219       }
220
221       if ( UNIVERSAL::can(dbh, 'sprintProfile') ) {
222         open(PROFILE,">%%%FREESIDE_LOG%%%/queueprofile.$$.".time)
223           or die "can't open profile file: $!";
224         print PROFILE dbh->sprintProfile();
225         close PROFILE or die "can't close profile file: $!";
226       }
227
228       exit;
229       #end-of-kid
230     }
231
232   } #foreach my $job
233
234 } continue {
235   if ( sigterm() ) {
236     warn "received TERM signal; exiting\n";
237     exit;
238   }
239   if ( sigint() ) {
240     warn "received INT signal; exiting\n";
241     exit;
242   }
243 }
244
245 sub untaint_argv {
246   foreach $_ ( $[ .. $#ARGV ) { #untaint @ARGV
247     #$ARGV[$_] =~ /^([\w\-\/]*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
248     # Date::Parse
249     $ARGV[$_] =~ /^(.*)$/ || die "Illegal arguement \"$ARGV[$_]\"";
250     $ARGV[$_]=$1;
251   }
252 }
253
254 sub usage {
255   die "Usage:\n\n  freeside-queued user\n";
256 }
257
258 sub reap_kids {
259   foreach my $pid ( keys %kids ) {
260     my $kid = waitpid($pid, WNOHANG);
261     if ( $kid > 0 ) {
262       $kids--;
263       delete $kids{$kid};
264     }
265   }
266 }
267
268 =head1 NAME
269
270 freeside-queued - Job queue daemon
271
272 =head1 SYNOPSIS
273
274   freeside-queued [ -s | -n ] user
275
276 =head1 DESCRIPTION
277
278 Job queue daemon.  Should be running at all times.
279
280 -s: "secure" jobs only (queued billing jobs)
281
282 -n: non-"secure" jobs only (other jobs)
283
284 user: from the mapsecrets file - see config.html from the base documentation
285
286 =head1 VERSION
287
288 =head1 BUGS
289
290 =head1 SEE ALSO
291
292 =cut
293