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