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