blib/lib/App/Netdisco/Util/FastResolver.pm untested

filter: Statementstmt 0.0% 0 / 51 Branchbran 0.0% 0 / 8 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 85 CC 5 SCAR 26.1
CC
5
Cov
0%
hostnames_resolve_async
30.0
BEGIN
2.0
BEGIN
2.0
CRAP 13.7
1 package App::Netdisco::Util::FastResolver;
2  
3 use strict;
4 use warnings;
5 use Dancer ':script';
6  
7 use AnyEvent::Loop;
8 use AnyEvent::DNS;
9 use App::Netdisco::Util::Permission 'acl_matches';
10  
11 use base 'Exporter';
12 our @EXPORT = ();
13 our @EXPORT_OK = qw/hostnames_resolve_async/;
14 our %EXPORT_TAGS = (all => \@EXPORT_OK);
15  
16 =head1 NAME
17  
18 App::Netdisco::Util::FastResolver
19  
20 =head1 DESCRIPTION
21  
22 A set of helper subroutines to support parts of the Netdisco application.
23  
24 There are no default exports, however the C<:all> tag will export all
25 subroutines.
26  
27 =head1 EXPORT_OK
28  
29 =head2 hostnames_resolve_async( \@ips, \@timeouts? )
30  
31 This method uses a fully asynchronous and high-performance pure-perl stub
32 resolver C<AnyEvent::DNS>.
33  
34 Given a reference to an array of hashes will resolve the C<IPv4> or C<IPv6>
35 address in the C<ip>, C<alias>, or C<device> key of each hash into its
36 hostname which will be inserted in the C<dns> key of the hash.
37  
38 Optionally provide a set of timeout values in seconds which is also the
39 number of resolver attempts. The default is C<< [2,5,5] >>.
40  
41 Returns the supplied reference to an array of hashes with dns values for
42 addresses which resolved.
43  
44 =cut
45  
46 sub hostnames_resolve_async {
47 my ($ips, $timeouts) = @_;
48 return [] unless $ips and ref [] eq ref $ips;
49 $timeouts ||= [2,5,5];
50  
51 my $skip = setting('dns')->{'no'};
52 my $ETCHOSTS = setting('dns')->{'ETCHOSTS'};
53 AnyEvent::DNS::resolver->timeout(@$timeouts);
54 AnyEvent::DNS::resolver->os_config();
55  
56 # Set up the condvar
57 my $done = AE::cv;
58 $done->begin( sub { shift->send } );
59  
60 IP: foreach my $hash_ref (@$ips) {
61 my $ip = $hash_ref->{'ip'} || $hash_ref->{'alias'} || $hash_ref->{'device'};
62 next IP if acl_matches($ip, $skip);
63  
64 # check /etc/hosts file and short-circuit if found
65 foreach my $name (reverse sort keys %$ETCHOSTS) {
66 if ($ETCHOSTS->{$name}->[0]->[0] eq $ip) {
67 $hash_ref->{'dns'} = $name;
68 next IP;
69 }
70 }
71  
72 $done->begin;
73 AnyEvent::DNS::reverse_lookup $ip,
74 sub { $hash_ref->{'dns'} = shift; $done->end; };
75 }
76  
77 # Decrement the cv counter to cancel out the send declaration
78 $done->end;
79  
80 # Wait for the resolver to perform all resolutions
81 $done->recv;
82  
83 # Remove reference to resolver so that we close sockets
84 # and allow return to any instance defaults we have changed
85 undef $AnyEvent::DNS::RESOLVER if $AnyEvent::DNS::RESOLVER;
86  
87 return $ips;
88 }
89  
90 1;