5 use FS::UID qw(dbh adminsuidsetup);
6 use FS::Record qw( dbh qsearch qsearchs );
14 # could add others here
17 my $interval = 300; # seconds
18 my $timeout = 5.0; # seconds
20 # useful opts: scan interval, timeout, verbose, max forks
21 # maybe useful opts: interface, protocol, packet size, no-fork
24 getopts('vxi:', \%opt);
25 my $user = shift or die usage();
28 daemonize1('freeside-pingd');
38 warn(@_, "\n") if $opt{v};
41 adminsuidsetup($user);
42 $FS::UID::AutoCommit = 1;
47 foreach my $table (@TARGETS) {
48 # find addresses that need to be scanned (haven't been yet, or are
50 my $expired = time - $interval;
51 debug("checking addresses from $table");
53 my $statement = "SELECT ip_addr FROM $table
54 LEFT JOIN addr_status USING (ip_addr)
55 WHERE $table.ip_addr IS NOT NULL
56 AND (addr_status.ip_addr IS NULL OR addr_status._date <= ?)
57 ORDER BY COALESCE(addr_status._date, 0)";
58 my $addrs = dbh->selectcol_arrayref($statement, {}, $expired);
59 die dbh->errstr if !defined $addrs;
60 debug("found ".scalar(@$addrs));
61 push @addrs_to_scan, @$addrs;
64 # fork to handle this since we're going to spend most of our time
65 # waiting for remote machines to respond
66 foreach my $addr (@addrs_to_scan) {
67 daemon_fork( \&scan, $addr );
70 debug("waiting for scan to complete");
74 # sleep until there's more work to do:
75 # the oldest record that still has an expire time in the future
76 # (as opposed to records for dead addresses, which will not be rescanned)
77 my $next_expire = FS::Record->scalar_sql(
78 'SELECT MIN(_date) FROM addr_status WHERE _date + ? > ?',
81 my $delay = $next_expire + $interval - time;
82 # but at least scan every $interval seconds, to pick up new addresses
83 $delay = $interval if $delay > $interval;
86 debug("it is now ".time."; sleeping for $delay");
89 debug("it is now ".time."; continuing");
95 # currently just sends a single ping; it might be more useful to send
96 # several of them and estimate packet loss.
99 my $addr_status = qsearchs('addr_status', { 'ip_addr' => $addr })
100 || FS::addr_status->new({ 'ip_addr' => $addr });
102 $addr_status->select_for_update if $addr_status->addrnum;
103 my $ping = Net::Ping->new;
105 debug "pinging $addr";
106 my ($result, $latency) = $ping->ping($addr, $timeout);
107 debug "status $result, delay $latency";
108 $addr_status->set('up', $result ? 'Y' : '');
109 $addr_status->set('delay', int($latency * 1000));
110 $addr_status->set('_date', time);
111 my $error = $addr_status->addrnum ?
112 $addr_status->replace :
113 $addr_status->insert;
115 die "ERROR: could not update status for $addr\n$error\n";
121 freeside-pingd [ -i INTERVAL ] [ -v ] [ -x ] <username>