have torrus-srvderive just use the native torrus srvderive instead of sucking CPU...
[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 IPC::Run qw( run ); #timeout );
9 use FS::Daemon ':all'; #daemonize1 drop_root daemonize2 myexit logfile sig*
10 use FS::UID qw( adminsuidsetup forksuidsetup dbh driver_name );
11 use FS::Record qw( qsearch str2time_sql str2time_sql_closing concat_sql );
12 use FS::torrus_srvderive;
13
14 our $DEBUG = 2;
15 our $max_kids = 4;
16 our $search_timeout = 2*60*60; #60*60; #30*60; # 15*60 5*60; #$torrus_srvderive->last_srv_date ? 5*60 : 15*60);
17 our %kids;
18
19 my $user = shift or die &usage;
20 $FS::Daemon::PID_NEWSTYLE = 1;
21 daemonize1('torrus-srvderive');
22
23 drop_root();
24
25 adminsuidsetup($user);
26
27 logfile( "%%%FREESIDE_LOG%%%/torrus-srvderive-log.". $FS::UID::datasrc );
28
29 daemonize2();
30
31 our $conf = new FS::Conf;
32
33 die "not running: network_monitoring_system not Torrus_Internal\n"
34   unless _shouldrun();
35
36 #--
37
38 my $in  = concat_sql([ '?', "'_IN'" ]);
39 my $out = concat_sql([ '?', "'_OUT'" ]);
40
41 our $kids = 0;
42
43 #MAIN: while (1) {
44 while (1) {
45
46   #SERVICEID: foreach my $torrus_srvderive ( qsearch('torrus_srvderive', {}) ) {
47   foreach my $torrus_srvderive ( qsearch('torrus_srvderive', {}) ) {
48
49     &reap_kids;
50     if ( $kids >= $max_kids ) {
51       sleep 5;
52       myexit() if sigterm() || sigint();
53       redo;
54     }
55
56     defined( my $pid = fork ) or do {
57       #warn "WARNING: can't fork: $!\n";
58       #next; #don't increment the kid counter
59       die "can't fork: $!\n";
60     };
61
62     if ( $pid ) {
63       $kids++;
64       $kids{$pid} = 1;
65     } else { #kid time
66
67       #get new db handle
68       $FS::UID::dbh->{InactiveDestroy} = 1;
69
70       forksuidsetup($user);
71
72       my $serviceid = $torrus_srvderive->serviceid;
73
74       my @serviceids = $torrus_srvderive->component_serviceids;
75       exit unless @serviceids; #don't try to search for empty virtual ports
76
77       my @in = ();
78       for my $dir ('_IN', '_OUT') {
79         push @in, map dbh->quote("$_$dir"), @serviceids;
80       }
81       my $in = join(',', @in);
82
83       if ( ! $torrus_srvderive->last_srv_date ) {
84         warn "finding initial last_srv_date for $serviceid\n" if $DEBUG;
85         my $dsql = "SELECT srv_date FROM srvexport WHERE serviceid IN ($in)
86                     ORDER BY srv_date LIMIT 1";
87         my $dsth = dbh->prepare($dsql) or die $DBI::errstr;
88         $dsth->execute or die $dsth->errstr;
89         my $date = $dsth->fetchrow_arrayref->[0];
90         if ( $date ) {
91           warn "found initial last_srv_date of $date; updating $serviceid\n"
92             if $DEBUG;
93           $torrus_srvderive->last_srv_date($date);
94           my $error = $torrus_srvderive->replace;
95           die $error if $error;
96         } else {
97           warn "no initial last_srv_date for $serviceid; skipping\n" if $DEBUG;
98           exit;
99         }
100       }
101
102       #if we're more than a day behind, call native torrus srvderive
103       my $last_srv_date = $torrus_srvderive->last_srv_date;
104       my $currdate = time2str('%Y-%m-%d', time);
105       if ( $last_srv_date ne $currdate
106            && time - str2time($last_srv_date) > (24)*60*60
107          ) {
108         warn "serviceid $serviceid last_srv_date != $currdate\n" if $DEBUG;
109
110         #delete records from last_srv_date
111         my $dsql =
112           'DELETE FROM srvexport WHERE srv_date = ? AND serviceid IN(?,?)';
113         my $dsth = dbh->prepare($dsql) or die $DBI::errstr;
114         warn "$dsql $last_srv_date ${serviceid}_IN ${serviceid}_OUT\n"
115           if $DEBUG;
116         $dsth->execute($last_srv_date, $serviceid.'_IN', $serviceid.'_OUT')
117           or die $dsth->errstr;
118         dbh->commit or die dbh->errstr;
119
120         foreach my $dir ('_IN','_OUT') {
121
122           #XX TORRUS_PATH
123           my @cmd = ( '/usr/local/bin/torrus', 'srvderive',
124                         "--start=$last_srv_date", "--end=$currdate",
125                         "--out=$serviceid$dir", "--func=SUM",
126                         map "$_$dir", @serviceids
127                     );
128
129           warn "calling native srvderive: ". join(' ', @cmd). "\n" if $DEBUG;
130           my $out_and_err = '';
131           run( \@cmd, '>&', \$out_and_err ) #verbose?  timeout?
132             or die "error calling native srvder: $out_and_err\n";
133
134         }
135         warn "native srvderive done" if $DEBUG;
136
137         $torrus_srvderive->last_srv_date($currdate);
138         my $error = $torrus_srvderive->replace;
139         die $error if $error;
140
141         #don't bother trying today's immediately
142         warn "done with $serviceid for now\n" if $DEBUG;
143
144       } else {
145
146         warn "serviceid $serviceid last_srv_date == $currdate; skipping\n"
147           if $DEBUG;
148
149       }
150
151       exit; #end-of-kid
152
153     }
154
155   } #foreach my $torrus_srvderive
156   dbh->commit or die dbh->errstr;
157
158   myexit() if sigterm() || sigint();
159   warn "sleeping an hour\n" if $DEBUG > 1;
160   sleep 60*60;
161   warn "restarting main loop\n" if $DEBUG > 1;
162 }
163
164 sub _shouldrun {
165      $conf->exists('network_monitoring_system')
166   && $conf->config('network_monitoring_system') eq 'Torrus_Internal';
167 }
168
169 sub usage { 
170   die "Usage:\n\n  freeside-cdrrewrited user\n";
171 }
172
173 sub reap_kids {
174   foreach my $pid ( keys %kids ) {
175     my $kid = waitpid($pid, WNOHANG);
176     if ( $kid > 0 ) {
177       $kids--;
178       delete $kids{$kid};
179     }
180   }
181 }
182
183 =head1 NAME
184
185 freeside-torrus-srvderive - Freeside's Torrus virtual port daemon.
186
187 =head1 SYNOPSIS
188
189   freeside-torrus-srvderive
190
191 =head1 DESCRIPTION
192
193 Runs continuously, searches for samples in the srvexport table which do not
194 have an entry for combined virtual ports, and adds them.
195
196 =head1 SEE ALSO
197
198 =cut
199
200 1;
201