add start of torrus srvderive daemon, RT#10574
[freeside.git] / FS / bin / freeside-torrus-srvderive
1 #!/usr/bin/perl -w
2
3 use strict;
4 use Date::Parse;
5 use FS::Daemon ':all'; #daemonize1 drop_root daemonize2 myexit logfile sig*
6 use FS::UID qw( adminsuidsetup dbh driver_name );
7 use FS::Record qw( qsearch str2time_sql str2time_sql_closing );
8 use FS::torrus_srvderive;
9
10 our $DEBUG = 1;
11
12 my $user = shift or die &usage;
13 $FS::Daemon::PID_NEWSTYLE = 1;
14 daemonize1('freeside-torrus-srvderive');
15
16 drop_root();
17
18 adminsuidsetup($user);
19
20 logfile( "%%%FREESIDE_LOG%%%/torrus-srvderive-log.". $FS::UID::datasrc );
21
22 daemonize2();
23
24 our $conf = new FS::Conf;
25
26 die "not running: network_monitoring_system not Torrus_Internal\n"
27   unless _shouldrun();
28
29 #--
30
31 my $str2time = str2time_sql();
32 my $c = str2time_sql_closing();
33
34 my $_date = concat_sql([ 'srvexport.srv_date', "' '", 'srvexport.srv_time' ]);
35 $_date = "CAST( $_date AS TIMESTAMP )" if driver_name =~ /^Pg/i;
36 $_date = str2time_sql. $_date.  str2time_sql_closing;
37
38 my $other_date = concat_sql([ 'other.srv_date', "' '", 'other.srv_time' ]);
39 $other_date = "CAST( $other_date AS TIMESTAMP )" if driver_name =~ /^Pg/i;
40 $other_date = str2time_sql. $other_date.  str2time_sql_closing;
41
42 my $sql = "
43   SELECT DISTINCT srv_date, srv_time FROM srvexport
44     WHERE NOT EXISTS (
45                        SELECT 1 FROM srvexport AS other
46                          WHERE other.serviceid IN ( ?||'_IN', ?||'_OUT')
47                            AND ABS( $_date - $other_date ) <= 60
48                      )
49     ORDER BY id
50 ";
51
52 while (1) {
53
54   #my $found = 0;
55
56   foreach my $torrus_srvderive ( qsearch('torrus_srvderive', {}) ) {
57
58     my $serviceid = $torrus_srvderive->serviceid;
59
60     my $sth = dbh->prepare($sql) or die $DBI::errstr; #better recovery?
61     $sth->execute($serviceid, $serviceid) or die $sth->errstr;
62     my $prev = 0;
63     while ( my $row = $sth->fetchrow_arrayref ) {
64       my( $srv_date, $srv_time ) = @$row;
65       my $cur = str2time( "$srv_date $srv_time" );
66       next if $cur-$prev <= 60;
67       
68       warn "no $serviceid for $srv_date $srv_time; adding\n"
69         if $DEBUG;
70
71     }
72
73   }
74
75
76   myexit() if sigterm() || sigint();
77   sleep 60; #unless $found
78 }
79
80 sub _shouldrun {
81      $conf->exists('network_monitoring_system')
82   && $conf->config('network_monitoring_system') eq 'Torrus_Internal';
83 }
84
85 sub usage { 
86   die "Usage:\n\n  freeside-cdrrewrited user\n";
87 }
88
89
90 =head1 NAME
91
92 freeside-torrus-srvderive - Freeside's Torrus virtual port daemon.
93
94 =head1 SYNOPSIS
95
96   freeside-torrus-srvderive
97
98 =head1 DESCRIPTION
99
100 Runs continuously, searches for samples in the srvexport table which do not
101 have an entry for combined virtual ports, and adds them.
102
103 =head1 SEE ALSO
104
105 =cut
106
107 1;
108