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

filter: Statementstmt 0.0% 0 / 182 Branchbran 0.0% 0 / 80 Conditioncond 0.0% 0 / 113 MC/DCmcdc 0.0% 0 / 66 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 484 CC 41 SCAR 39.4
CC
41
Cov
0%
decode_and_munge
156.0
snmp_vrf_context
72.0
get_communities
56.0
CRAP 51.5
1 package App::Netdisco::Util::SNMP;
2  
3 use Dancer qw/:syntax :script/;
4 use App::Netdisco::Util::DeviceAuth 'get_external_credentials';
5  
6 use Path::Class 'dir';
7 use File::Spec::Functions qw/splitdir catdir catfile/;
8 use MIME::Base64 'decode_base64';
9 use SNMP::Info;
10 use JSON::PP ();
11 use Scalar::Util 'refaddr';
12  
13 use base 'Exporter';
14 our @EXPORT = ();
15 our @EXPORT_OK = qw/
16 get_communities
17 snmp_comm_reindex
18 snmp_vrf_reindex
19 snmp_vrf_context
20 get_mibdirs
21 get_mibdirs_shortnames
22 decode_and_munge
23 sortable_oid
24 walk_mark
25 incomplete_walks
26 incomplete_walk_message
27 incomplete_walk_level
28 incomplete_walks_for
29 /;
30 our %EXPORT_TAGS = (all => \@EXPORT_OK);
31  
32 =head1 NAME
33  
34 App::Netdisco::Util::SNMP
35  
36 =head1 DESCRIPTION
37  
38 Helper functions for L<SNMP::Info> instances.
39  
40 There are no default exports, however the C<:all> tag will export all
41 subroutines.
42  
43 =head1 EXPORT_OK
44  
45 =head2 get_communities( $device, $mode )
46  
47 Takes the current C<device_auth> setting and pushes onto the front of the list
48 the last known good SNMP settings used for this mode (C<read> or C<write>).
49  
50 =cut
51  
52 sub get_communities {
53 my ($device, $mode) = @_;
54 $mode ||= 'read';
55  
56 my $seen_tags = {}; # for cleaning community table
57 my $config = (setting('device_auth') || []);
58 my @communities = ();
59  
60 # first of all, use external command if configured
61 push @communities, get_external_credentials($device, $mode);
62  
63 # last known-good by tag
64 my $tag_name = 'snmp_auth_tag_'. $mode;
65 my $stored_tag = eval { $device->community->$tag_name };
66  
67 # A hint for a configured tag other than the stored one goes ahead of the
68 # last known-good credentials, so that a device answering to both can be
69 # moved to the hinted ones, as device_auth_tag_hint is documented to do.
70 # The known-good stanza stays in the list behind it, as does every other.
71 my $hint = setting('device_auth_tag_hint');
72 my $hint_wins = ($hint and $hint ne ($stored_tag // '')
73 and scalar grep { $_->{tag} and $_->{tag} eq $hint } @$config);
74  
75 if ($device->in_storage and $stored_tag) {
76 foreach my $stanza (@$config) {
77 if ($stanza->{tag} and $stored_tag eq $stanza->{tag}) {
78 push @communities, {%$stanza, only => [$device->ip]}
79 unless $hint_wins;
80 ++$seen_tags->{ $stored_tag };
81 last;
82 }
83 }
84 }
85  
86 # try last-known-good v2 read
87 push @communities, {
88 read => 1, write => 0, driver => 'snmp',
89 only => [$device->ip],
90 community => $device->snmp_comm,
91 } if defined $device->snmp_comm and $mode eq 'read' and not $hint_wins;
92  
93 # try last-known-good v2 write
94 my $snmp_comm_rw = eval { $device->community->snmp_comm_rw };
95 push @communities, {
96 write => 1, read => 0, driver => 'snmp',
97 only => [$device->ip],
98 community => $snmp_comm_rw,
99 } if $snmp_comm_rw and $mode eq 'write' and not $hint_wins;
100  
101 # clean the community table of obsolete tags
102 eval { $device->community->update({$tag_name => undef}) }
103 if $device->in_storage
104 and (not $stored_tag or !exists $seen_tags->{ $stored_tag });
105  
106 return return ( @communities, @$config );
107 }
108  
109 =head2 snmp_comm_reindex( $snmp, $device, $vlan )
110  
111 Takes an established L<SNMP::Info> instance and makes a fresh connection using
112 community indexing, with the given C<$vlan> ID. Works for all SNMP versions.
113  
114 Inherits the C<vtp_version> from the previous L<SNMP::Info> instance.
115  
116 Passing VLAN "C<0>" (zero) will reset the indexing to the basic v2 community
117 or v3 empty context.
118  
119 =cut
120  
121 sub snmp_comm_reindex {
122 my ($snmp, $device, $vlan) = @_;
123 return _reindex($snmp, $device, $vlan, 'vlan');
124 }
125  
126 =head2 snmp_vrf_reindex( $snmp, $device, $vrf )
127  
128 As C<snmp_comm_reindex>, but for a VRF's SNMP context: on SNMPv3 the context
129 is the VRF name as given, never the VLAN context prefix.
130  
131 =cut
132  
133 sub snmp_vrf_reindex {
134 my ($snmp, $device, $vrf) = @_;
135 return _reindex($snmp, $device, $vrf, 'vrf');
136 }
137  
138 =head2 snmp_vrf_context( $snmp, $device, $instance )
139  
140 Takes a record from C<vrf_instances()> and puts the session in that VRF's SNMP
141 context, as SNMP::Info describes it in the record's C<contexts>. Returns true
142 when the session can now read the VRF. When it cannot, the session is left
143 where it was and the return is C<undef> if the record names no context for
144 this SNMP version (SNMPv2c on a class that refuses community suffixes), or 0
145 if the C<update()> failed, and C<< $snmp->error >> says why.
146  
147 C<default>, or a record with no context entry (attribution mode), is read in
148 the default context. An undefined C<$instance> restores the default context,
149 and returns false when that C<update()> failed.
150  
151 =cut
152  
153 sub snmp_vrf_context {
154 my ($snmp, $device, $instance) = @_;
155 my $context = ($instance and $instance->{contexts} and $instance->{contexts}[0]);
156  
157 # unconditional, as _reindex with index 0: nothing here can tell from the
158 # object that the session is already in the default context
159 if (not $context or ($context->{kind} || '') eq 'none') {
160 debug sprintf ' [%s] returning to the default context (ver: %s, class: %s)',
161 $device->ip, $snmp->snmp_ver, $snmp->class;
162 my $restored = $snmp->update($snmp->snmp_ver == 3 ? (Context => '')
163 : (Community => $snmp->snmp_comm));
164 return ($restored ? 1 : 0);
165 }
166  
167 my $v3 = ($snmp->snmp_ver == 3);
168 my $name = $v3 ? $context->{v3} : $context->{v2c};
169 return undef unless defined $name;
170  
171 debug sprintf ' [%s] switching to %s context (ver: %s, class: %s)',
172 $device->ip, ($instance->{name} // ''), $snmp->snmp_ver, $snmp->class;
173 # a failed update() keeps the previous session, which is in another context
174 my $switched = $v3 ? $snmp->update(Context => $name)
175 : $snmp->update(Community => sprintf($name, $snmp->snmp_comm));
176 return ($switched ? 1 : 0);
177 }
178  
179 sub _reindex {
180 my ($snmp, $device, $index, $kind) = @_;
181 my $ver = $snmp->snmp_ver;
182 my $vtp = $snmp->vtp_version;
183  
184 if ($ver == 3) {
185 my $prefix = '';
186 my @comms = get_communities($device, 'read');
187 # find a context prefix configured by the user
188 foreach my $c (@comms) {
189 next unless $c->{tag}
190 and $c->{tag} eq (eval { $device->community->snmp_auth_tag_read } || '');
191 $prefix = $c->{context_prefix} and last;
192 }
193 $prefix ||= 'vlan-';
194  
195 # snmp_comm_reindex has been passed VRF names too, so for a VLAN only
196 # a number takes the prefix
197 if ($kind eq 'vlan' && $index =~ /^[0-9]+$/ && $index) {
198 debug sprintf ' [%s] reindexing to "%s%s" (ver: %s, class: %s)',
199 $device->ip, $prefix, $index, $ver, $snmp->class;
200 $snmp->update(Context => ($prefix . $index));
201 } elsif ($index =~ /^\S+$/ && $index) {
202 debug sprintf ' [%s] reindexing to "%s" (ver: %s, class: %s)',
203 $device->ip, $index, $ver, $snmp->class;
204 $snmp->update(Context => ($index));
205 } else {
206 debug sprintf ' [%s] reindexing without context (ver: %s, class: %s)',
207 $device->ip, $ver, $snmp->class;
208 $snmp->update(Context => '');
209 }
210 }
211 else {
212 my $comm = $snmp->snmp_comm;
213  
214 debug sprintf ' [%s] reindexing to %s %s (ver: %s, class: %s)',
215 $device->ip, $kind, $index, $ver, $snmp->class;
216 $index ? $snmp->update(Community => $comm . '@' . $index)
217 : $snmp->update(Community => $comm);
218 }
219  
220 $snmp->cache({ _vtp_version => $vtp });
221 return $snmp;
222 }
223  
224 =head2 get_mibdirs
225  
226 Return a list of directories in the `netdisco-mibs` folder.
227  
228 =cut
229  
230 sub get_mibdirs {
231 my $home = (setting('mibhome') || dir(($ENV{NETDISCO_HOME} || $ENV{HOME}), 'netdisco-mibs'));
232 return map { dir($home, $_)->stringify }
233 @{ setting('mibdirs') || get_mibdirs_shortnames() };
234 }
235  
236 sub get_mibdirs_shortnames {
237 my $home = (setting('mibhome') || dir(($ENV{NETDISCO_HOME} || $ENV{HOME}), 'netdisco-mibs'));
238 my @list = map {s|$home/||; $_} grep { m|/[a-z0-9-]+$| } grep {-d} glob("$home/*");
239 return \@list;
240 }
241  
242 =head2 decode_and_munge( $method, $data )
243  
244 Takes some data from snmpwalk cache that has been Base64 encoded,
245 decodes it and then munge to handle data format, before finally pretty
246 render in JSON format.
247  
248 =cut
249  
250 sub get_code_info { return ($_[0]) =~ m/^(.+)::(.*?)$/ }
251 sub sub_name { return (get_code_info $_[0])[1] }
252 sub class_name { return (get_code_info $_[0])[0] }
253  
254 sub decode_and_munge {
255 my ($munger, $encoded) = @_;
256 return undef unless defined $encoded and length $encoded;
257  
258 my $json = JSON::PP->new->utf8->pretty->allow_nonref->allow_unknown->canonical;
259 $json->sort_by( sub { sortable_oid($JSON::PP::a) cmp sortable_oid($JSON::PP::b) } );
260  
261 return undef if $encoded !~ m/^\[/; # legacy format double protection for web crash
262 my $data = (@{ from_json($encoded) })[0];
263  
264 $data = (ref {} eq ref $data)
265 ? { map {($_ => (defined $data->{$_} ? decode_base64($data->{$_}) : undef))}
266 keys %$data }
267 : (defined $data ? decode_base64($data) : undef);
268  
269 return $json->encode( $data ) if not $munger;
270  
271 # this names a class to load and a sub to call, and reaches here from the
272 # request, so only SNMP::Info's own namespace is accepted
273 return $json->encode( $data )
274 unless $munger =~ m/^SNMP::Info(?:::[A-Za-z0-9_]+)*::[A-Za-z0-9_]+$/;
275  
276 my $sub = sub_name($munger);
277 my $class = class_name($munger);
278 Module::Load::load $class;
279  
280 # munge_e_type seems broken, noop it
281 return $json->encode( $data ) if $sub eq 'munge_e_type' and $class eq 'SNMP::Info';
282  
283 $data = (ref {} eq ref $data)
284 ? { map {($_ => (defined $data->{$_} ? $class->can($sub)->($data->{$_}) : undef))}
285 keys %$data }
286 : (defined $data ? $class->can($sub)->($data) : undef);
287  
288 return $json->encode( $data );
289 }
290  
291 =head2 sortable_oid( $oid, $seglen? )
292  
293 Take an OID and return a version of it which is sortable using C<cmp>
294 operator. Works by zero-padding the numeric parts all to be length
295 C<< $seglen >>, which defaults to 6.
296  
297 =cut
298  
299 # take oid and make comparable
300 sub sortable_oid {
301 my ($oid, $seglen) = @_;
302 $seglen ||= 6;
303 return $oid if $oid !~ m/^[0-9.]+$/;
304 $oid =~ s/^(\.)//; my $leading = $1;
305 $oid = join '.', map { sprintf("\%0${seglen}d", $_) } (split m/\./, $oid);
306 return (($leading || '') . $oid);
307 }
308  
309 =head2 walk_mark( $snmp )
310  
311 Returns the number of incomplete walks the L<SNMP::Info> instance has
312 recorded so far, for use with C<incomplete_walks>. Returns 0 when the
313 instance keeps no record.
314  
315 =cut
316  
317 sub walk_mark {
318 my $snmp = shift;
319 return 0 unless $snmp->can('walk_failures');
320 return scalar @{ $snmp->walk_failures };
321 }
322  
323 =head2 incomplete_walks( $snmp, $mark )
324  
325 Returns the incomplete walk outcomes recorded since C<walk_mark> returned
326 C<$mark>, in order. Returns an empty list when the instance keeps no record.
327  
328 =cut
329  
330 sub incomplete_walks {
331 my ($snmp, $mark) = @_;
332 return () unless $snmp->can('walk_failures');
333 my $failures = $snmp->walk_failures;
334 return @{$failures}[ $mark .. $#{$failures} ];
335 }
336  
337 =head2 incomplete_walk_message( $device, $what, @outcomes )
338  
339 Returns a log message for C<$what> on C<$device> naming each incomplete
340 walk outcome: its method, table, reason, rows read and walk method, with
341 the repeaters and SNMP context when there are any. When an outcome is
342 C<absent>, the message says to check the MIBs the poller loads.
343  
344 =cut
345  
346 sub incomplete_walk_message {
347 my ($device, $what, @outcomes) = @_;
348 my @walks = map {
349 sprintf('%s (%s) %s after %d rows by %s',
350 @{$_}{qw/method leaf reason rows walk/})
351 . (defined $_->{repeaters} ? " with $_->{repeaters} repeaters" : '')
352 . ((defined $_->{context} and length $_->{context})
353 ? " in context $_->{context}" : '')
354 } @outcomes;
355 my $hint = (incomplete_walk_level(@outcomes) eq 'error')
356 ? '; the poller could not translate an SNMP object, so check the netdisco-mibs'
357 . ' install and the mibhome and mibdirs settings'
358 : '';
359 return sprintf '[%s] %s - kept existing rows, incomplete SNMP walk: %s%s',
360 $device->ip, $what, (join '; ', @walks), $hint;
361 }
362  
363 =head2 incomplete_walk_level( @outcomes )
364  
365 Returns the L<App::Netdisco::Worker::Status> a worker returns after keeping
366 its stored rows for C<@outcomes>: C<error> when any outcome is C<absent>,
367 otherwise C<info>. An C<absent> walk means the poller's MIBs are broken,
368 which must show on the job, while a cut-short walk leaves the job's status
369 as it was before the guard. An C<error> job queues no discover hooks, so a
370 device first discovered while the MIBs are broken never sends its
371 C<new_device> hook.
372  
373 This is not full broken-MIB detection. It sees only the walks a guarded
374 worker names, and only while C<enable_incomplete_walk_protection> is on.
375 Leaves read behind a composite method, such as C<i_vlan_membership>, go
376 unseen, and there a broken install behaves as it did before the guard.
377  
378 =cut
379  
380 sub incomplete_walk_level {
381 return (grep { ($_->{reason} // '') eq 'absent' } @_) ? 'error' : 'info';
382 }
383  
384 =head2 incomplete_walks_for( $device, $snmp, $mark, @methods )
385  
386 Returns the incomplete walk outcomes that could have cut short a table a
387 worker is about to write: those recorded since C<walk_mark> returned C<$mark>,
388 then the latest C<walk_status> of each named C<@methods> when it is not
389 complete, then the job's record of the early C<interfaces> read when
390 C<interfaces> is among the C<@methods>. Each outcome is returned once.
391  
392 C<walk_status> is read because a table walked by an earlier worker is cached,
393 and reading it again records nothing, so the failure lies before C<$mark>. It
394 holds the latest outcome, so a method that failed and then succeeded on a
395 re-walk is not returned. An C<absent> reason counts as incomplete although
396 L<SNMP::Info> marks it complete, because it means the poller could not
397 translate the object locally, such as a broken MIB checkout.
398  
399 Returns an empty list when C<enable_incomplete_walk_protection> is false, or
400 when the instance keeps no walk record.
401  
402 =cut
403  
404 sub incomplete_walks_for {
405 my ($device, $snmp, $mark, @methods) = @_;
406 return () unless setting('enable_incomplete_walk_protection')
407 and $snmp->can('walk_failures');
408  
409 my @outcomes = incomplete_walks($snmp, $mark);
410 if ($snmp->can('walk_status')) {
411 foreach my $method (@methods) {
412 my $latest = $snmp->walk_status($method);
413 push @outcomes, $latest if $latest
414 and (not $latest->{complete} or ($latest->{reason} // '') eq 'absent');
415 }
416 }
417 push @outcomes, @{ vars->{'incomplete_walks'}{ $device->ip }{'interfaces'} || [] }
418 if grep { $_ eq 'interfaces' } @methods;
419  
420 my %seen;
421 return grep { not $seen{ refaddr $_ }++ } @outcomes;
422 }
423  
424 true;