blib/lib/App/Netdisco/Worker/Plugin/Arpnip/Nodes.pm untested

filter: Statementstmt 0.0% 0 / 287 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 115 MC/DCmcdc 0.0% 0 / 67 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 597 CC 32 SCAR 35.1
CC
32
Cov
0%
drop_own_entries
72.0
gather_arps_by_vrf_cli
56.0
merge_vrf_reads
56.0
CRAP 33.5
1 package App::Netdisco::Worker::Plugin::Arpnip::Nodes;
2  
3 use Dancer ':syntax';
4 use Dancer::Plugin::DBIC 'schema';
5  
6 use App::Netdisco::Worker::Plugin;
7 use aliased 'App::Netdisco::Worker::Status';
8  
9 use App::Netdisco::Transport::SSH ();
10 use App::Netdisco::Transport::SNMP ();
11  
12 use App::Netdisco::Util::Node qw/check_mac memoize_arp store_arp retire_unvouched_arps record_cli_vrfs/;
13 use App::Netdisco::Util::VRF
14 qw/vrf_collection_enabled vrf_skip_test netdisco_vrf vrf_instances_for each_vrf_instance/;
15 use App::Netdisco::Util::FastResolver 'hostnames_resolve_async';
16  
17 use NetAddr::IP::Lite ':lower';
18 use Regexp::Common 'net';
19 use NetAddr::MAC ();
20 use Time::HiRes 'gettimeofday';
21 use Try::Tiny;
22  
23 # microseconds must be zero padded or 99999 us outranks 100000 us
24 sub _arpnip_timestamp_sql {
25 my ($seconds, $microseconds) = @_;
26 return sprintf('to_timestamp(%d.%06d)::timestamp', $seconds, $microseconds);
27 }
28  
29 register_worker({ phase => 'early',
30 title => 'prepare common data' }, sub {
31  
32 my ($job, $workerconf) = @_;
33 my $device = $job->device;
34  
35 vars->{'timestamp'} = ($job->is_offline and $job->entered)
36 ? (schema('netdisco')->storage->dbh->quote($job->entered) .'::timestamp')
37 : _arpnip_timestamp_sql(gettimeofday);
38  
39 # initialise the cache
40 vars->{'arps'} = {};
41 # netdisco-do runs every job in one process, so no job sees another's VRF reads
42 delete @{ vars() }{qw/vrf_read vrf_read_families vrf_list_complete cli_vrf_list/};
43 });
44  
45 register_worker({ phase => 'store', title => 'store ARP cache' }, sub {
46 my ($job, $workerconf) = @_;
47 my $device = $job->device;
48  
49 # convert cache to a list, now that we've gathererd all of them
50 # it just makes the rest of the "store" code easier
51 vars->{'arps'} = [ values %{ vars->{'arps'} } ];
52  
53 if (vrf_collection_enabled($device)) {
54 drop_flattened_twins($device);
55 drop_own_entries($device);
56 }
57 delete $_->{flattened} for @{ vars->{'arps'} };
58  
59 vars->{'arps'} = [ grep { check_mac(($_->{node} || $_->{mac}), $device) }
60 @{ vars->{'arps'} } ];
61  
62 debug sprintf ' resolving %d ARP entries with max %d outstanding requests',
63 scalar @{ vars->{'arps'} }, $ENV{'PERL_ANYEVENT_MAX_OUTSTANDING_DNS'};
64 vars->{'arps'} = hostnames_resolve_async( vars->{'arps'} );
65  
66 my ($v4, $v6) = (0, 0);
67 foreach my $a_entry (@{ vars->{'arps'} }) {
68 my $a_ip = NetAddr::IP::Lite->new($a_entry->{ip});
69  
70 if ($a_ip) {
71 ++$v4 if $a_ip->bits == 32;;
72 ++$v6 if $a_ip->bits == 128;;
73 }
74 }
75  
76 my $now = vars->{'timestamp'};
77 store_arp(\%$_, $now, $device->ip) for @{ vars->{'arps'} };
78 if (vars->{'cli_vrf_list'} and vrf_collection_enabled($device)) {
79 # the entries are stored, so a failed write only delays the VRFs' domains
80 try { record_cli_vrfs($device, vars->{'cli_vrf_list'}{read}, vars->{'cli_vrf_list'}{complete}, $now) }
81 catch { warning sprintf ' [%s] arpnip - recording the VRFs read failed, the next arpnip retries: %s',
82 $device->ip, $_ };
83 }
84  
85 debug sprintf ' [%s] arpnip - processed %s ARP Cache entries',
86 $device->ip, $v4;
87 debug sprintf ' [%s] arpnip - processed %s IPv6 Neighbor Cache entries',
88 $device->ip, $v6;
89  
90 my $status = $job->best_status;
91 if (Status->$status->level == Status->done->level) {
92 # the entries are stored, so a failed retire leaves stale rows active
93 # until the next arpnip retries, rather than failing this job
94 try { retire_unvouched_arps($device, $now, vars->{'vrf_read'}, vars->{'vrf_list_complete'}) }
95 catch { warning sprintf ' [%s] arpnip - retiring unreported entries failed, the next arpnip retries: %s',
96 $device->ip, $_ };
97 $device->update({last_arpnip => \$now});
98 }
99  
100 return Status->$status("Ended arpnip for $device");
101 });
102  
103 register_worker({ phase => 'main', driver => 'snmp' }, sub {
104 my ($job, $workerconf) = @_;
105  
106 my $device = $job->device;
107 my $snmp = App::Netdisco::Transport::SNMP->reader_for($device)
108 or return Status->defer("arpnip failed: could not SNMP connect to $device");
109  
110 my $instances = vrf_instances_for($device, $snmp);
111 if ($instances) {
112 gather_arps_per_vrf($device, $snmp, $instances);
113 return Status->done("Gathered arp caches from $device");
114 }
115  
116 # cache v4 arp table, then the v6 neighbor cache; with no VRF support these
117 # tables may hold any VRF's hosts, so they count as flattened
118 cache_arp($_, 1) for get_arps_snmp($device, $snmp->at_paddr, $snmp->at_netaddr);
119 cache_arp($_, 1) for get_arps_snmp($device, $snmp->ipv6_n2p_mac, $snmp->ipv6_n2p_addr);
120  
121 return Status->done("Gathered arp caches from $device");
122 });
123  
124 # a flattening collector, or a default read left partial because other
125 # instances' rows are mixed into it, reports a host with no VRF that a
126 # VRF-aware driver reported under its VRF in the same job; keep only the named
127 # one. An entry from a whole default read is the device's own word, so a host
128 # in both '' and a named VRF there keeps both rows.
129 sub drop_flattened_twins {
130 my ($device) = @_;
131 my $key_of = sub {
132 my $entry = shift;
133 my $mac = NetAddr::MAC->new(mac => ($entry->{node} || $entry->{mac} || ''));
134 my $ip = NetAddr::IP::Lite->new($entry->{ip} || '');
135 return ($mac and $ip) ? join(chr(28), $mac->as_ieee, $ip->addr) : undef;
136 };
137  
138 my %named = map { my $key = $key_of->($_); defined $key ? ($key => 1) : () }
139 grep { length($_->{vrf} // '') } @{ vars->{'arps'} };
140 return unless %named;
141  
142 my @kept = grep { my $key = (($_->{flattened} and not length($_->{vrf} // '')) ? $key_of->($_) : undef);
143 not (defined $key and $named{$key}) } @{ vars->{'arps'} };
144 my $dropped = scalar(@{ vars->{'arps'} }) - scalar(@kept);
145 vars->{'arps'} = \@kept;
146  
147 debug sprintf ' [%s] arpnip - dropped %d flattened ARP entries also reported under a VRF',
148 $device->ip, $dropped if $dropped;
149 }
150  
151 # With store_vrfs on, a router's own rows are not ARP nodes: SNMP::Info's
152 # per-VRF reader drops them but CLI collectors report them. Entries carry no
153 # ifIndex, so SNMP::Info's same-port MAC test cannot be reproduced; instead an
154 # entry goes if its MAC is the device's or that of a port holding one of its
155 # addresses, or if its (vrf, address) is one of the device's device_ip rows
156 # AND its MAC is that of some port of the device (a stale alias must not drop
157 # a real host). Any port's MAC alone is not enough: Aruba lists each AP's
158 # Ethernet MAC as a port. Runs only when this job recorded a VRF read, since
159 # only a whole VRF read retires the own rows stored earlier; a device with no
160 # VRF read keeps its own rows as before. Those earlier rows retire when their
161 # VRF is next read whole.
162 sub drop_own_entries {
163 my ($device) = @_;
164 my $reads = vars->{'vrf_read'};
165 return unless ref {} eq ref $reads and scalar keys %$reads;
166 my ($own_macs, $port_macs, $own_addresses) = own_identity($device);
167  
168 my $mac_of = sub {
169 my $mac = NetAddr::MAC->new(mac => ($_[0]->{node} || $_[0]->{mac} || ''));
170 return ($mac ? $mac->as_ieee : undef);
171 };
172 my $is_own = sub {
173 my $entry = shift;
174 my $mac = $mac_of->($entry);
175 return 0 unless defined $mac;
176 return 1 if $own_macs->{$mac};
177 return 0 unless $port_macs->{$mac};
178 my $ip = NetAddr::IP::Lite->new($entry->{ip} || '');
179 return ($ip and $own_addresses->{ join chr(28), ($entry->{vrf} // ''), $ip->addr }) ? 1 : 0;
180 };
181  
182 my @kept = grep { not $is_own->($_) } @{ vars->{'arps'} };
183 my $dropped = scalar(@{ vars->{'arps'} }) - scalar(@kept);
184 vars->{'arps'} = \@kept;
185  
186 debug sprintf ' [%s] arpnip - dropped %d ARP entries for the device\'s own MACs and addresses',
187 $device->ip, $dropped if $dropped;
188 }
189  
190 # two queries: device_ip rows, then device_port rows
191 sub own_identity {
192 my ($device) = @_;
193 my $normalize_mac = sub {
194 my $mac = NetAddr::MAC->new(mac => ($_[0] || ''));
195 return (($mac and $mac->as_ieee ne '00:00:00:00:00:00') ? $mac->as_ieee : undef);
196 };
197  
198 my @aliases = schema('netdisco')->resultset('DeviceIp')
199 ->search({ ip => $device->ip }, { columns => [qw/alias vrf port/] })->hri->all;
200 my @ports = schema('netdisco')->resultset('DevicePort')
201 ->search({ ip => $device->ip, mac => { '!=' => undef } }, { columns => [qw/port mac/] })->hri->all;
202  
203 my %port_macs = map { my $mac = $normalize_mac->($_->{mac}); defined $mac ? ($mac => 1) : () } @ports;
204 my %mac_of_port = map { ($_->{port} => $normalize_mac->($_->{mac})) } @ports;
205  
206 my (%addresses, %own_macs);
207 foreach my $row (@aliases) {
208 my $mac = $mac_of_port{ $row->{port} // '' };
209 $own_macs{$mac} = 1 if defined $mac;
210 my $ip = NetAddr::IP::Lite->new($row->{alias} || '') or next;
211 $addresses{ join chr(28), ($row->{vrf} // ''), $ip->addr } = 1;
212 }
213 my $device_mac = $normalize_mac->($device->mac);
214 $own_macs{$device_mac} = 1 if defined $device_mac;
215  
216 return (\%own_macs, \%port_macs, \%addresses);
217 }
218  
219 # store_vrfs path: each VRF's ARP and neighbor entries are read in its own
220 # context, and vrf_read says which VRFs were read whole
221 sub gather_arps_per_vrf {
222 my ($device, $snmp, $instances) = @_;
223 # read before any switch, as update() clears SNMP::Info's cache
224 my $list_complete = $snmp->vrf_instances_complete;
225  
226 my $reads = each_vrf_instance($device, $snmp, $instances,
227 sub { return $snmp->vrf_neighbors($_[0]) }, log_as => 'arpnip');
228 # vrf_neighbors reads both the ARP and the IPv6 neighbor rows
229 merge_vrf_reads({ map { ($_ => $reads->{$_}->{complete}) } keys %$reads }, $list_complete, [4, 6]);
230  
231 foreach my $vrf (sort keys %$reads) {
232 my $neighbors = $reads->{$vrf}->{data} || {};
233 # a partial default read may hold rows of instances mixed into it
234 my $flattened = ($vrf eq '' and not $reads->{$vrf}->{complete});
235 foreach my $key (sort keys %$neighbors) {
236 cache_arp({ mac => $neighbors->{$key}->{mac}, ip => $neighbors->{$key}->{ip},
237 dns => undef, vrf => $vrf }, $flattened);
238 }
239 }
240 }
241  
242 # Caches one ARP entry. A flattened entry is tagged for drop_flattened_twins
243 # and never replaces an untagged entry for the same host, whichever driver ran
244 # first.
245 sub cache_arp {
246 my ($arp, $flattened) = @_;
247 my $key = memoize_arp($arp) // return;
248 if ($flattened) {
249 my $cached = vars->{'arps'}->{$key};
250 return if $cached and not $cached->{flattened};
251 $arp->{flattened} = 1;
252 }
253 vars->{'arps'}->{$key} = $arp;
254 }
255  
256 # get an arp table (v4 or v6)
257 sub get_arps_snmp {
258 my ($device, $paddr, $netaddr) = @_;
259 my @arps = ();
260  
261 while (my ($arp, $node) = each %$paddr) {
262 my $ip = $netaddr->{$arp} or next;
263 push @arps, {
264 mac => $node,
265 ip => $ip,
266 dns => undef,
267 };
268 }
269  
270 return @arps;
271 }
272  
273 register_worker({ phase => 'main', driver => 'cli' }, sub {
274 my ($job, $workerconf) = @_;
275  
276 my $device = $job->device;
277 my $cli = App::Netdisco::Transport::SSH->session_for($device)
278 or return Status->defer("arpnip failed: could not SSH connect to $device");
279  
280 if (vrf_collection_enabled($device)) {
281 return gather_arps_by_vrf_cli($device, $cli)
282 if $cli->platform->can('arpnip_by_vrf');
283 debug sprintf ' [%s] arpnip - %s collector flattens VRFs and contributes no VRF reads',
284 $device->ip, ref $cli->platform;
285 }
286  
287 # should be both v4 and v6
288 cache_arp($_, 1) for $cli->arpnip;
289  
290 return Status->done("Gathered arp caches from $device");
291 });
292  
293 # a platform with arpnip_by_vrf returns { entries, vrf_read, vrf_list_complete,
294 # families } with each entry's vrf named as netdisco stores it; families lists
295 # the address families its vrf_read covers, [4], [6] or [4, 6], and absent or
296 # malformed means [4], so a platform that does not say never vouches for IPv6.
297 # A global-table entry carries mixed => 1 when that table also lists VRF hosts
298 # (IOS XR's show ipv6 neighbors), even though the read itself was whole.
299 # A platform subclass that overrides arpnip must also override arpnip_by_vrf,
300 # or with store_vrfs on the inherited arpnip_by_vrf runs instead of its arpnip.
301 sub gather_arps_by_vrf_cli {
302 my ($device, $cli) = @_;
303 my $error = 'returned no ARP data';
304 my $result = try { $cli->arpnip_by_vrf } catch { ($error = "failed: $_") =~ s{\s+\z}{}; undef };
305 return Status->defer("arpnip failed: CLI session to $device $error")
306 unless ref {} eq ref $result;
307  
308 my %vrf_read = ();
309 my $reads = $result->{vrf_read} || {};
310 foreach my $vrf (keys %$reads) {
311 my $name = netdisco_vrf($vrf);
312 # default and '' name one table, so it is whole only if both reads were
313 $vrf_read{$name} = (exists $vrf_read{$name} ? ($vrf_read{$name} && $reads->{$vrf}) : $reads->{$vrf});
314 }
315 # a platform that read no VRF cannot vouch that its list is whole
316 my $list_complete = (scalar keys %vrf_read ? $result->{vrf_list_complete} : 0);
317  
318 my $skipped = vrf_skip_test($device);
319 foreach my $entry (@{ $result->{entries} || [] }) {
320 my $vrf = netdisco_vrf($entry->{vrf}) // '';
321 next if $skipped->($vrf);
322 # entries from a VRF the platform did not report reading prove no read
323 $vrf_read{$vrf} = 0 unless exists $vrf_read{$vrf};
324 my $arp = { %$entry, vrf => $vrf };
325 my $mixed = delete $arp->{mixed};
326 # a whole global read is the device's own word, as on the SNMP path
327 cache_arp($arp, ($vrf eq '' and ($mixed or not $vrf_read{''})));
328 }
329  
330 delete @vrf_read{ grep { $skipped->($_) } keys %vrf_read };
331 # stored in device_vrf by the store phase, so a VRF SNMP does not list gets a domain
332 vars->{'cli_vrf_list'} = { read => { %vrf_read }, complete => $list_complete };
333 my @not_whole = sort grep { not $vrf_read{$_} } keys %vrf_read;
334 info sprintf ' [%s] arpnip (cli) - VRFs not read whole, so their entries are kept: %s',
335 $device->ip, join ', ', map { qq{"$_"} } @not_whole
336 if scalar @not_whole;
337 merge_vrf_reads(\%vrf_read, $list_complete, $result->{families});
338 return Status->done("Gathered arp caches from $device");
339 }
340  
341 # SNMP and CLI may both read a VRF in one job. Per address family, a VRF is
342 # whole only if every source that read that family read it whole; vrf_read is
343 # 1 only when both families were read whole by some source. The list is whole
344 # only if every source's list was. A source that read no VRF leaves vrf_read
345 # absent, so nothing retires on its word.
346 sub merge_vrf_reads {
347 my ($reads, $list_complete, $families) = @_;
348 my @families = (_well_formed_families($families) ? @$families : (4));
349 my $by_family = (vars->{'vrf_read_families'} ||= {});
350  
351 foreach my $vrf (keys %$reads) {
352 my $whole = ($reads->{$vrf} ? 1 : 0);
353 foreach my $family (@families) {
354 my $seen = $by_family->{$vrf}->{$family};
355 $by_family->{$vrf}->{$family} = (defined $seen ? ($seen && $whole) : $whole);
356 }
357 vars->{'vrf_read'}->{$vrf} = ((2 == grep { $by_family->{$vrf}->{$_} } 4, 6) ? 1 : 0);
358 }
359 my $list = ($list_complete ? 1 : 0);
360 vars->{'vrf_list_complete'} = (exists vars->{'vrf_list_complete'}
361 ? (vars->{'vrf_list_complete'} && $list) : $list);
362 }
363  
364 # anything but a non-empty list of 4 and 6 reads as absent, so as IPv4 only
365 sub _well_formed_families {
366 my $families = shift;
367 return 0 unless ref [] eq ref $families and scalar @$families;
368 return not scalar grep { not defined $_ or $_ !~ m/^[46]\z/ } @$families;
369 }
370  
371 register_worker({ phase => 'main', driver => 'direct' }, sub {
372 my ($job, $workerconf) = @_;
373 my $device = $job->device;
374  
375 return Status->info('skip: arp table data supplied by other source')
376 unless $job->is_offline;
377  
378 # load cache from file or copy from job param
379 my $data = $job->extra;
380 my @arps = (length $data ? @{ from_json($data) } : ());
381  
382 return $job->cancel('data provided but 0 arp entries found')
383 unless scalar @arps;
384  
385 debug sprintf ' [%s] arpnip - %s arp table entries provided',
386 $device->ip, scalar @arps;
387  
388 # sanity check
389 foreach my $a_entry (@arps) {
390 my $ip = NetAddr::IP::Lite->new($a_entry->{'ip'} || '');
391 my $mac = NetAddr::MAC->new(mac => ($a_entry->{'mac'} || ''));
392  
393 next unless $ip and $mac;
394 next if (($ip->addr eq '0.0.0.0') or ($ip !~ m{^(?:$RE{net}{IPv4}|$RE{net}{IPv6})(?:/\d+)?$}i));
395 next if (($mac->as_ieee eq '00:00:00:00:00:00') or ($mac->as_ieee !~ m{^$RE{net}{MAC}$}i));
396  
397 vars->{'arps'}->{ memoize_arp($a_entry) } = $a_entry;
398 }
399  
400 return Status->done("Received arp cache for $device");
401 });
402  
403 true;