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