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