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