avoid deadlocks, RT#10574
[freeside.git] / FS / bin / freeside-torrus-srvderive
1 #!/usr/bin/perl -w
2
3 use strict;
4 use POSIX qw( :sys_wait_h );
5 use Sys::SigAction qw( set_sig_handler );
6 use Date::Parse;
7 use Date::Format;
8 use FS::Daemon ':all'; #daemonize1 drop_root daemonize2 myexit logfile sig*
9 use FS::UID qw( adminsuidsetup forksuidsetup dbh driver_name );
10 use FS::Record qw( qsearch str2time_sql str2time_sql_closing concat_sql );
11 use FS::torrus_srvderive;
12
13 our $DEBUG = 2;
14 our $max_kids = 6;
15 our $search_timeout = 30*60; # 15*60 5*60; #$torrus_srvderive->last_srv_date ? 5*60 : 15*60);
16 our %kids;
17
18 my $user = shift or die &usage;
19 $FS::Daemon::PID_NEWSTYLE = 1;
20 daemonize1('torrus-srvderive');
21
22 drop_root();
23
24 adminsuidsetup($user);
25
26 logfile( "%%%FREESIDE_LOG%%%/torrus-srvderive-log.". $FS::UID::datasrc );
27
28 daemonize2();
29
30 our $conf = new FS::Conf;
31
32 die "not running: network_monitoring_system not Torrus_Internal\n"
33   unless _shouldrun();
34
35 #--
36
37 my $str2time = str2time_sql();
38 my $c = str2time_sql_closing();
39
40 my $_date = concat_sql([ 'srvexport.srv_date', "' '", 'srvexport.srv_time' ]);
41 $_date = "CAST( $_date AS TIMESTAMP )" if driver_name =~ /^Pg/i;
42 $_date = str2time_sql. $_date.  str2time_sql_closing;
43
44 my $other_date = concat_sql([ 'other.srv_date', "' '", 'other.srv_time' ]);
45 $other_date = "CAST( $other_date AS TIMESTAMP )" if driver_name =~ /^Pg/i;
46 $other_date = str2time_sql. $other_date.  str2time_sql_closing;
47
48 my $in  = concat_sql([ '?', "'_IN'" ]);
49 my $out = concat_sql([ '?', "'_OUT'" ]);
50
51 my $sql = "
52   SELECT DISTINCT srv_date, srv_time FROM srvexport
53     WHERE NOT EXISTS (
54                        SELECT 1 FROM srvexport AS other
55                          WHERE other.serviceid IN ( $in, $out )
56                            AND srvexport.srv_date = other.srv_date
57                            AND ABS( $_date - $other_date ) <= 60
58                      )
59 ";
60
61 my $orderlimit = "
62     ORDER BY srv_date, srv_time
63     LIMIT 100
64 "; #50?
65
66 our $kids = 0;
67
68 #MAIN: while (1) {
69 while (1) {
70
71   my $found = 0;
72
73   #SERVICEID: foreach my $torrus_srvderive ( qsearch('torrus_srvderive', {}) ) {
74   foreach my $torrus_srvderive ( qsearch('torrus_srvderive', {}) ) {
75
76     &reap_kids;
77     if ( $kids >= $max_kids ) {
78       sleep 5;
79       myexit() if sigterm() || sigint();
80       redo;
81     }
82
83     defined( my $pid = fork ) or do {
84       #warn "WARNING: can't fork: $!\n";
85       #next; #don't increment the kid counter
86       die "can't fork: $!\n";
87     };
88
89     if ( $pid ) {
90       $kids++;
91       $kids{$pid} = 1;
92     } else { #kid time
93
94       #get new db handle
95       $FS::UID::dbh->{InactiveDestroy} = 1;
96
97       forksuidsetup($user);
98
99       my $serviceid = $torrus_srvderive->serviceid;
100
101       my @serviceids = $torrus_srvderive->component_serviceids;
102       exit unless @serviceids; #don't try to search for empty virtual ports
103
104       #nonlocking select statements; rows in this table never change
105       if ( driver_name eq 'mysql' ) {
106         dbh->do('SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED');
107         dbh->commit or die dbh->errstr;
108       }
109
110       my @in = ();
111       for my $dir ('_IN', '_OUT') {
112         push @in, map dbh->quote("$_$dir"), @serviceids;
113       }
114       my $in = join(',', @in);
115
116       if ( ! $torrus_srvderive->last_srv_date ) {
117         warn "finding initial last_srv_date for $serviceid\n" if $DEBUG;
118         my $dsql = "SELECT srv_date FROM srvexport WHERE serviceid IN ($in)
119                     ORDER BY srv_date LIMIT 1";
120         my $dsth = dbh->prepare($dsql) or die $DBI::errstr;
121         $dsth->execute or die $dsth->errstr;
122         my $date = $dsth->fetchrow_arrayref->[0];
123         if ( $date ) {
124           warn "found initial last_srv_date of $date; updating $serviceid\n"
125             if $DEBUG;
126           $torrus_srvderive->last_srv_date($date);
127           my $error = $torrus_srvderive->replace;
128           die $error if $error;
129         } else {
130           warn "no initial last_srv_date for $serviceid; skipping\n" if $DEBUG;
131           exit;
132         }
133       }
134
135       my $ssql = "
136         $sql AND EXISTS (
137                          SELECT 1 FROM srvexport AS other
138                            WHERE other.serviceid IN ($in)
139                              AND srvexport.srv_date = other.srv_date
140                              AND ABS( $_date - $other_date ) <= 60
141                        )
142       ";
143
144       $ssql .= " AND srv_date >= '". $torrus_srvderive->last_srv_date. "' "
145         if $torrus_srvderive->last_srv_date;
146
147       $ssql .= $orderlimit;
148
149       warn "searching for times to add $serviceid\n" if $DEBUG;
150       warn $ssql if $DEBUG > 2;
151       my $sth = dbh->prepare($ssql) or die $DBI::errstr; #better recovery here?
152
153       eval {
154         my $h = set_sig_handler( 'ALRM', sub { die "_timeout\n"; } );
155         alarm($search_timeout);
156         $sth->execute($serviceid, $serviceid) or die $sth->errstr;
157         alarm(0);
158       };
159       alarm(0);
160       
161       if ( $@ && $@ eq "_timeout\n" ) {
162         #warn "search timed out; reconnecting and restarting\n";
163         warn "search timed out\n";
164         dbh->clone()->do("KILL QUERY ". dbh->{"mysql_thread_id"})
165           if driver_name eq 'mysql';
166         dbh->rollback; #or die dbh->errstr;
167         #adminsuidsetup($user);
168         #next SERVICEID; #MAIN;
169         exit;
170       } elsif ( $@ ) {
171         die $@;
172       }
173
174       warn "search for $serviceid finished; checking results\n" if $DEBUG;
175
176       my $prev = 0;
177       while ( my $row = $sth->fetchrow_arrayref ) {
178         last if sigterm() || sigint();
179
180         my( $srv_date, $srv_time ) = @$row;
181         my $cur = str2time( "$srv_date $srv_time" );
182         next if $cur-$prev <= 60;
183         last if time - $cur <= 300;
184
185         warn "no $serviceid for $srv_date $srv_time; adding\n"
186           if $DEBUG;
187         $found++;
188
189         for my $dir ('_IN', '_OUT') {
190
191           my $sin = join(',', map dbh->quote("$_$dir"), @serviceids);
192
193           my $sum = "
194             SELECT COALESCE(SUM(value),0) FROM srvexport AS other
195               WHERE other.serviceid IN ($sin)
196                 AND ABS( $cur - $other_date ) <= 60
197           ";
198
199           my $isql = "
200             INSERT INTO srvexport ( srv_date, srv_time, serviceid, value, intvl )
201               VALUES ( ?, ?, ?, ($sum), ? )
202           ";
203           my @param = ( time2str('%Y-%m-%d', $cur), #srv_date
204                         time2str('%X', $cur),       #srv_time
205                         "$serviceid$dir",
206                         300, #intvl ... 
207                       );
208           warn $isql. ' with param '. join(',',@param). "\n"
209             if $DEBUG > 2;
210
211           my $isth = dbh->prepare($isql) or die $DBI::errstr; #better recovery?
212
213           #stupid mysql deadlocks all the time on insert, so we need to recover
214           unless ( $isth->execute(@param) ) {
215             #warn "Error inserting data for $serviceid$dir (restarting): ".
216             #     $isth->errstr;
217             warn "Error inserting data for $serviceid$dir: ". $isth->errstr;
218             dbh->rollback; #or die dbh->errstr;
219             #sleep 5;
220             #next SERVICEID; #MAIN;
221             exit;
222           }
223                           
224         }
225
226         if ( $srv_date ne $torrus_srvderive->last_srv_date ) {
227           warn "updating last_srv_date of $serviceid to $srv_date\n" if $DEBUG;
228           $torrus_srvderive->last_srv_date($srv_date);
229           my $error = $torrus_srvderive->replace;
230           die $error if $error;
231         }
232         dbh->commit or die dbh->errstr;
233
234         $prev = $cur;
235       }
236       warn "done with $serviceid\n" if $DEBUG;
237
238       exit;
239       #end-of-kid
240     }
241
242   } #foreach my $torrus_srvderive
243   dbh->commit or die dbh->errstr;
244
245   myexit() if sigterm() || sigint();
246   warn "restarting main loop\n" if $DEBUG > 1;
247   #sleep 60 unless $found;
248 }
249
250 sub _shouldrun {
251      $conf->exists('network_monitoring_system')
252   && $conf->config('network_monitoring_system') eq 'Torrus_Internal';
253 }
254
255 sub usage { 
256   die "Usage:\n\n  freeside-cdrrewrited user\n";
257 }
258
259 sub reap_kids {
260   foreach my $pid ( keys %kids ) {
261     my $kid = waitpid($pid, WNOHANG);
262     if ( $kid > 0 ) {
263       $kids--;
264       delete $kids{$kid};
265     }
266   }
267 }
268
269 =head1 NAME
270
271 freeside-torrus-srvderive - Freeside's Torrus virtual port daemon.
272
273 =head1 SYNOPSIS
274
275   freeside-torrus-srvderive
276
277 =head1 DESCRIPTION
278
279 Runs continuously, searches for samples in the srvexport table which do not
280 have an entry for combined virtual ports, and adds them.
281
282 =head1 SEE ALSO
283
284 =cut
285
286 1;
287