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

filter: Statementstmt 0.0% 0 / 180 Branchbran 0.0% 0 / 90 Conditioncond 0.0% 0 / 86 MC/DCmcdc 0.0% 0 / 52 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 451 CC 46 SCAR 33.1
CC
46
Cov
0%
each_vrf_instance
90.0
_complete_default_read
42.0
_read_instance
42.0
CRAP 27.5
1 package App::Netdisco::Util::VRF;
2  
3 use strict;
4 use warnings;
5  
6 use Dancer qw/:syntax :script !pass/;
7 use App::Netdisco::Util::Permission 'acl_matches';
8 use App::Netdisco::Util::SNMP qw/snmp_vrf_context walk_mark incomplete_walks_for/;
9 use Scope::Guard 'guard';
10 use Scalar::Util qw/blessed refaddr/;
11 use App::Netdisco::Transport::SNMP ();
12  
13 use base 'Exporter';
14 our @EXPORT = ();
15 our @EXPORT_OK = qw/
16 vrf_collection_enabled
17 vrf_skip_test
18 netdisco_vrf
19 vrf_instances_for
20 each_vrf_instance
21 /;
22 our %EXPORT_TAGS = (all => \@EXPORT_OK);
23  
24 =head1 NAME
25  
26 App::Netdisco::Util::VRF
27  
28 =head1 DESCRIPTION
29  
30 Helper subroutines for collecting VRF data from devices.
31  
32 There are no default exports, however the C<:all> tag will export all
33 subroutines.
34  
35 =head1 EXPORT_OK
36  
37 =head2 vrf_collection_enabled( $device )
38  
39 True only when the C<store_vrfs> setting is on, the device does not match
40 C<skip_vrf_devices>, and the device is not a pseudo device. A pseudo device may
41 be read from a snapshot, so every worker treats it as if C<store_vrfs> were off,
42 whether it is read from a snapshot or live.
43  
44 =cut
45  
46 sub vrf_collection_enabled {
47 my $device = shift;
48 return 0 unless setting('store_vrfs');
49 # a context switch is an update(), which clears SNMP::Info's cache: for a
50 # snapshot read offline that cache is the snapshot. Transport::SNMP marks a
51 # device pseudo when it loads one, so for a device not yet stored this is
52 # only reliable after reader_for
53 return 0 if $device->is_pseudo;
54 return (not acl_matches($device, 'skip_vrf_devices'));
55 }
56  
57 =head2 vrf_skip_test( $device )
58  
59 Returns a test, C<< $skipped->($local_name) >>, true when C<vrf_no_devicevrfs>
60 skips that VRF on C<$device>. Build it once, before a loop: the device is
61 matched against the setting's keys here, and each name's answer is kept, so
62 the test costs one ACL check per distinct name however often it is asked.
63 Never true for the default table, whichever of C<default> or the empty string
64 names it.
65  
66 C<vrf_no_devicevrfs> is a dictionary, or a list of them, as
67 C<macsuck_no_deviceports>: each key is an ACL matching devices, its value an
68 ACL matching the VRFs to skip on them. A VRF is matched as C<vrf:E<lt>regexE<gt>>,
69 anchored at both ends, so C<.>, C<+> and C<(> are live; C<(?i)> ignores case.
70  
71 vrf_no_devicevrfs:
72 'group:__ANY__': ['vrf:(?i)mgmt', 'vrf:lab-.*']
73 '192.0.2.1': 'vrf:cust:a'
74  
75 A hostname or regex rule in a key costs a DNS lookup each time a test is
76 built, which is a few times per job. A value rule without a property (a bare
77 name) or a regex object never matches a VRF, so each warns once.
78  
79 =cut
80  
81 sub vrf_skip_test {
82 my $device = shift;
83 my @vrf_acls = _vrf_acls_for($device);
84 my %answer;
85  
86 return sub {
87 my $name = shift;
88 return 0 if not defined $name or $name eq '' or $name eq 'default';
89 return 0 unless scalar @vrf_acls;
90 $answer{$name} //= ((scalar grep { acl_matches({ vrf => $name }, $_) } @vrf_acls) ? 1 : 0);
91 return $answer{$name};
92 };
93 }
94  
95 sub _vrf_acls_for {
96 my $device = shift;
97 my @acls;
98 foreach my $map (_skip_maps()) {
99 foreach my $key (sort keys %$map) {
100 next unless $key and $map->{$key};
101 _warn_unmatchable_rules($map->{$key});
102 push @acls, $map->{$key} if acl_matches($device, $key);
103 }
104 }
105 return @acls;
106 }
107  
108 my %warned;
109  
110 sub _skip_maps {
111 my $setting = setting('vrf_no_devicevrfs');
112 return ($setting) if ref {} eq ref $setting;
113 return () unless ref [] eq ref $setting;
114 foreach my $entry (grep { ref {} ne ref $_ } @$setting) {
115 next if $warned{"entry:" . ($entry // '')}++;
116 warning sprintf 'vrf_no_devicevrfs entry "%s" is ignored: each entry maps a device ACL to VRF rules. Write it as \'<device>\': \'vrf:<name>\'', $entry // '';
117 }
118 return grep { ref {} eq ref $_ } @$setting;
119 }
120  
121 # check_acl reads a bare string as an address or hostname, and a regex object
122 # as a pattern for the device's DNS name, so neither can match { vrf => ... }
123 sub _warn_unmatchable_rules {
124 my $rules = shift;
125 foreach my $rule (ref [] eq ref $rules ? @$rules : ($rules)) {
126 next if not defined $rule or $warned{"rule:$rule"};
127 my $plain = ref $rule ? '' : $rule;
128 $plain =~ s/^!//;
129 next if $plain eq 'op:and' or ($plain =~ m/^([^:]+):/ and $1 !~ m/^[a-f0-9]+$/i);
130 $warned{"rule:$rule"}++;
131 warning sprintf 'vrf_no_devicevrfs rule "%s" matches no VRF. Write a VRF as vrf:<name> or vrf:<regex>', $rule;
132 }
133 }
134  
135 =head2 netdisco_vrf( $snmpinfo_name )
136  
137 SNMP::Info names the global routing table C<default>; Netdisco stores it as
138 the empty string. Returns that, or the name unchanged for any other VRF.
139  
140 =cut
141  
142 sub netdisco_vrf {
143 my $name = shift;
144 return (defined $name and $name eq 'default') ? '' : $name;
145 }
146  
147 =head2 vrf_instances_for( $device, $snmp )
148  
149 Returns the hashref from C<< $snmp->vrf_instances >> without the VRFs skipped
150 by L</vrf_skip_test>, or C<undef> when collection is disabled for the device or
151 the SNMP::Info class has no VRF support (C<vrf_instances_complete> is
152 C<undef>). No SNMP method is called when collection is disabled.
153  
154 The instances are read here, in the default context, because C<update()>
155 clears SNMP::Info's cache.
156  
157 =cut
158  
159 sub vrf_instances_for {
160 my ($device, $snmp) = @_;
161 return undef unless vrf_collection_enabled($device);
162 return undef unless defined $snmp->vrf_instances_complete;
163  
164 my $instances = $snmp->vrf_instances || {};
165 my $skipped = vrf_skip_test($device);
166 return { map { ($_ => $instances->{$_}) }
167 grep { not $skipped->($_) } keys %$instances };
168 }
169  
170 =head2 each_vrf_instance( $device, $snmp, $instances, \&reader, %options )
171  
172 Reads every instance of C<$instances> (as from L</vrf_instances_for>) with
173 C<< $reader->($name, $instance, $switched) >>, which returns whatever the
174 caller needs from that instance.
175  
176 C<default> is read first, then the attribution-mode instances (a first
177 context of kind C<none>, or no C<contexts> at all) sorted by name, all in
178 place with no C<update()>. Then each context-mode instance, sorted by name, in
179 its own context; the session is returned to the default context once, after
180 the last of them. An instance whose context this session cannot enter is not
181 read and is reported incomplete. So is one whose C<contexts> is empty, which
182 SNMP::Info gives for a context-mode VRF that no context serves; it costs no
183 SNMP call.
184  
185 A read is complete only when C<< $snmp->vrf_read_complete($name) >> is 1 and
186 no walk since the read began came back short (C<incomplete_walks_for>, with
187 the C<walk_methods> option naming any further methods to check).
188  
189 Where the default read is partial only because other instances leak into it
190 (C<< $snmp->vrf_read_leaked('default') >>, SNMP::Info 3.985001, so far only
191 Juniper's virtual routers), each of those instances' ports are read with
192 C<i_vrf()> in its own context. Once every one of them was read whole, the
193 session returns to the default context, hands the ports to
194 C<vrf_exclude_ports()> and reads C<default> a second time, which replaces the
195 first read. Otherwise the first, partial read stands.
196  
197 Returns a hashref keyed by L</netdisco_vrf> of each name, of
198 C<< { complete => 0|1, data => <reader result or undef> } >>. Read anything
199 needed from the default context before calling this.
200  
201 Option C<log_as> names the worker in log lines (default C<device>).
202  
203 =cut
204  
205 # a record with context kind none, or (defensively) no contexts at all, is read
206 # in place in the default context like default itself, so attribution-mode
207 # classes never reconnect
208 sub _reads_in_default_context {
209 my $contexts = $_[0]->{contexts};
210 return 1 if not $contexts;
211 return (scalar @$contexts and ($contexts->[0]{kind} || '') eq 'none');
212 }
213  
214 sub _has_no_context { my $contexts = $_[0]->{contexts}; return ($contexts and not scalar @$contexts) }
215  
216 sub each_vrf_instance {
217 my ($device, $snmp, $instances, $reader, %options) = @_;
218 my @named = sort grep { $_ ne 'default' } keys %$instances;
219 my @in_place = ('default', grep { _reads_in_default_context($instances->{$_}) } @named);
220 my @unserved = grep { _has_no_context($instances->{$_}) } @named;
221 my @switched = grep { not _reads_in_default_context($instances->{$_})
222 and not _has_no_context($instances->{$_}) } @named;
223 my $log_as = $options{log_as} || 'device';
224  
225 # a partial default read is reported only once it is known not to be
226 # completed below, so a log never says rows are kept that then retire
227 my $default_partial;
228 my %reads = map {
229 (netdisco_vrf($_) => _read_instance($device, $snmp, $_, $instances->{$_}, $reader, 0, \%options,
230 ($_ eq 'default' ? \$default_partial : undef)))
231 } @in_place;
232 my $leaked = _leaked_instances($snmp, $reads{''});
233 debug $default_partial if defined $default_partial and not $leaked;
234 my %leaked_ports;
235  
236 foreach my $name (@unserved) {
237 debug sprintf ' [%s] %s - VRF %s has no context serving its rows', $device->ip, $log_as, $name;
238 $reads{ netdisco_vrf($name) } = { complete => 0, data => undef };
239 }
240  
241 my $guard;
242 foreach my $name (@switched) {
243 # armed before the switch, so an update() that dies partway still restores
244 $guard ||= guard { _return_to_default($device, $snmp, $log_as) };
245 my $switched = snmp_vrf_context($snmp, $device, $instances->{$name});
246 my $unread = (not defined $switched) ? 'has no context this session can reach'
247 : (not $switched) ? 'could not be switched to, update() failed'. _error_suffix($snmp)
248 : (not _context_answers($snmp)) ? 'context did not answer, so it was not read' : undef;
249 if ($unread) {
250 debug sprintf ' [%s] %s - VRF %s %s', $device->ip, $log_as, $name, $unread;
251 $reads{ netdisco_vrf($name) } = { complete => 0, data => undef };
252 next;
253 }
254 $reads{ netdisco_vrf($name) }
255 = _read_instance($device, $snmp, $name, $instances->{$name}, $reader, 1, \%options);
256 $leaked_ports{$name} = _leaked_ports($device, $snmp)
257 if $leaked and $reads{ netdisco_vrf($name) }{complete} and grep { $_ eq $name } @$leaked;
258 }
259 _complete_default_read($device, $snmp, $instances, $reader, \%reads, $leaked,
260 \%leaked_ports, $guard, \%options) if $leaked;
261 return \%reads;
262 }
263  
264 # the instances SNMP::Info names as mixed into a partial default read; asked
265 # in the default context, after its readers, as vrf_read_leaked requires
266 sub _leaked_instances {
267 my ($snmp, $default_read) = @_;
268 return undef if not $default_read or $default_read->{complete};
269 return undef unless $snmp->can('vrf_read_leaked') and $snmp->can('vrf_exclude_ports');
270 my $leaked = $snmp->vrf_read_leaked('default');
271 return (ref [] eq ref $leaked and scalar @$leaked) ? $leaked : undef;
272 }
273  
274 # the whole port set of the instance whose context the session is in, or undef
275 # when the walk was short: a partial set would let its rows back into default
276 sub _leaked_ports {
277 my ($device, $snmp) = @_;
278 my $walk_mark = walk_mark($snmp);
279 my $i_vrf = $snmp->i_vrf;
280 return undef if scalar incomplete_walks_for($device, $snmp, $walk_mark, 'i_vrf');
281 return undef unless ref {} eq ref $i_vrf and scalar keys %$i_vrf;
282 return [ sort { $a <=> $b } keys %$i_vrf ];
283 }
284  
285 # exclusions are recorded after the return to default because update() clears
286 # SNMP::Info's cache, exclusions included
287 sub _complete_default_read {
288 my ($device, $snmp, $instances, $reader, $reads, $leaked, $ports, $guard, $options) = @_;
289 my $log_as = $options->{log_as} || 'device';
290 my @skipped = grep { not $instances->{$_} } @$leaked;
291 if (@skipped) {
292 debug sprintf ' [%s] %s - default read stays partial: %s is not collected (vrf_no_devicevrfs)',
293 $device->ip, $log_as, join(', ', @skipped);
294 return;
295 }
296 my @unread = grep { not $ports->{$_} } @$leaked;
297 if (@unread) {
298 debug sprintf ' [%s] %s - default read stays partial: %s not read whole in their own context',
299 $device->ip, $log_as, join(', ', @unread);
300 return;
301 }
302 return unless snmp_vrf_context($snmp, $device, undef);
303 $guard->dismiss if $guard;
304  
305 foreach my $name (@$leaked) {
306 next if $snmp->vrf_exclude_ports($name, $ports->{$name});
307 debug sprintf ' [%s] %s - default read stays partial: SNMP::Info refused the ports of %s%s',
308 $device->ip, $log_as, $name, _error_suffix($snmp);
309 return;
310 }
311 $reads->{''} = _read_instance($device, $snmp, 'default', $instances->{default}, $reader, 0, $options);
312 }
313  
314 # the reader is cached for the job, so a session stuck in a VRF context would
315 # feed every later worker that VRF's rows as the default table's
316 sub _return_to_default {
317 my ($device, $snmp, $log_as) = @_;
318 return if snmp_vrf_context($snmp, $device, undef);
319 warning sprintf ' [%s] %s - could not return to the default context, so the SNMP session is dropped%s',
320 $device->ip, $log_as, _error_suffix($snmp);
321 my $readers = App::Netdisco::Transport::SNMP->instance->readers;
322 delete $readers->{ $device->ip }
323 if $readers and (refaddr($readers->{ $device->ip }) || 0) == refaddr($snmp);
324 }
325  
326 sub _error_suffix {
327 my $error = $_[0]->error;
328 return (defined $error and length $error) ? ": $error" : '';
329 }
330  
331 # one get before the reader: a reader walks attribute after attribute, and a
332 # context the device does not serve costs each of them the full timeout. Only a
333 # timeout counts; an error or noSuchObject is an answer
334 sub _context_answers {
335 my $session = $_[0]->session;
336 # no session to ask is no evidence of a dead context
337 return 1 unless blessed $session and $session->can('get');
338 $session->get('.1.3.6.1.2.1.1.3.0');
339 return (($session->{ErrorStr} || '') !~ m/timeout/i);
340 }
341  
342 sub _read_instance {
343 my ($device, $snmp, $name, $instance, $reader, $switched, $options, $deferred_log) = @_;
344 my $walk_mark = walk_mark($snmp);
345 # error() returns any error pending since it was last read; discard it, so
346 # the one logged below is one this read set
347 $snmp->error;
348 my $data = $reader->($name, $instance, $switched);
349 my $complete = ($snmp->vrf_read_complete($name) ? 1 : 0);
350 $complete = 0 if scalar incomplete_walks_for($device, $snmp, $walk_mark,
351 @{ $options->{walk_methods} || [] });
352 if (not $complete) {
353 my $error = $snmp->error;
354 my $line = sprintf ' [%s] %s - VRF %s read incomplete, keeping its rows%s',
355 $device->ip, ($options->{log_as} || 'device'), $name, (defined $error ? ": $error" : '');
356 if ($deferred_log) { $$deferred_log = $line } else { debug $line }
357 }
358 return { complete => $complete, data => $data };
359 }
360  
361 =head1 SEE ALSO
362  
363 L<SNMP::Info::VRF>
364  
365 =cut
366  
367 1;