attempt to handle mysql hanging on queries, 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   foreach my $torrus_srvderive ( qsearch('torrus_srvderive', {}) ) {
68
69     my $serviceid = $torrus_srvderive->serviceid;
70
71     my @serviceids = $torrus_srvderive->component_serviceids;
72
73     my @in = ();
74     for my $dir ('_IN', '_OUT') {
75       push @in, map dbh->quote("$_$dir"), @serviceids;
76     }
77     my $in = join(',', @in);
78
79     my $ssql = "
80       $sql AND EXISTS (
81                        SELECT 1 FROM srvexport AS other
82                          WHERE other.serviceid IN ($in)
83                            AND srvexport.srv_date = other.srv_date
84                            AND ABS( $_date - $other_date ) <= 60
85                      )
86     ";
87
88     $ssql .= " AND srv_date >= '". $torrus_srvderive->last_srv_date. "' "
89       if $torrus_srvderive->last_srv_date;
90
91     $ssql .= $orderlimit;
92
93     warn "searching for times to add $serviceid\n" if $DEBUG;
94     warn $ssql if $DEBUG > 2;
95     my $sth = dbh->prepare($ssql) or die $DBI::errstr; #better recovery here?
96
97     warn "executing search" if $DEBUG;
98
99     eval {
100       my $timeout = set_sig_handler(
101         'ALRM', sub {
102           dbh->clone()->do("KILL QUERY ". dbh->{"mysql_thread_id"})
103             if driver_name eq 'mysql';
104           die '_timeout';
105         },
106         { mask=>['ALRM'] , safe=>1 }
107       );
108       alarm(5*60); # 15*60);
109       $sth->execute($serviceid, $serviceid) or die $sth->errstr;
110       alarm(0);
111     };
112     alarm(0);
113     if ( $@ =~ /^_timeout/ ) {
114       warn "search timed out; reconnecting and restarting\n";
115       adminsuidsetup($user);
116       next MAIN;
117     } elsif ( $@ ) {
118       die $@;
119     }
120
121     warn "search executed; checking results" if $DEBUG;
122
123     my $prev = 0;
124     while ( my $row = $sth->fetchrow_arrayref ) {
125       last if sigterm() || sigint();
126
127       my( $srv_date, $srv_time ) = @$row;
128       my $cur = str2time( "$srv_date $srv_time" );
129       next if $cur-$prev <= 60;
130       last if time - $cur <= 300;
131
132       warn "no $serviceid for $srv_date $srv_time; adding\n"
133         if $DEBUG;
134       $found++;
135
136       for my $dir ('_IN', '_OUT') {
137
138         my $sin = join(',', map dbh->quote("$_$dir"), @serviceids);
139
140         my $sum = "
141           SELECT COALESCE(SUM(value),0) FROM srvexport AS other
142             WHERE other.serviceid IN ($sin)
143               AND ABS( $cur - $other_date ) <= 60
144         ";
145
146         my $isql = "
147           INSERT INTO srvexport ( srv_date, srv_time, serviceid, value, intvl )
148             VALUES ( ?, ?, ?, ($sum), ? )
149         ";
150         my @param = ( time2str('%Y-%m-%d', $cur), #srv_date
151                       time2str('%X', $cur),       #srv_time
152                       "$serviceid$dir",
153                       300, #intvl ... 
154                     );
155         warn $isql. ' with param '. join(',',@param). "\n"
156           if $DEBUG > 2;
157
158         my $isth = dbh->prepare($isql) or die $DBI::errstr; #better recovery?
159
160         #stupid mysql deadlocks all the time on insert, so we need to recover
161         unless ( $isth->execute(@param) ) {
162           warn "Error inserting data for $serviceid$dir (restarting): ".
163                $isth->errstr;
164           dbh->rollback; #or die dbh->errstr;
165           sleep 5;
166           next MAIN;
167         }
168                         
169       }
170
171       if ( $srv_date ne $torrus_srvderive->last_srv_date ) {
172         warn "updating last_srv_date of $serviceid to $srv_date\n" if $DEBUG;
173         $torrus_srvderive->last_srv_date($srv_date);
174         my $error = $torrus_srvderive->replace;
175         die $error if $error;
176       }
177       dbh->commit or die dbh->errstr;
178
179       $prev = $cur;
180     }
181     warn "done with $serviceid\n" if $DEBUG;
182
183   } #foreach my $torrus_srvderive
184   dbh->commit or die dbh->errstr;
185
186   myexit() if sigterm() || sigint();
187   warn "restarting main loop\n" if $DEBUG > 1;
188   sleep 60 unless $found;
189 }
190
191 sub _shouldrun {
192      $conf->exists('network_monitoring_system')
193   && $conf->config('network_monitoring_system') eq 'Torrus_Internal';
194 }
195
196 sub usage { 
197   die "Usage:\n\n  freeside-cdrrewrited user\n";
198 }
199
200
201 =head1 NAME
202
203 freeside-torrus-srvderive - Freeside's Torrus virtual port daemon.
204
205 =head1 SYNOPSIS
206
207   freeside-torrus-srvderive
208
209 =head1 DESCRIPTION
210
211 Runs continuously, searches for samples in the srvexport table which do not
212 have an entry for combined virtual ports, and adds them.
213
214 =head1 SEE ALSO
215
216 =cut
217
218 1;
219