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

filter: Statementstmt 0.0% 0 / 179 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 110 MC/DCmcdc 0.0% 0 / 64 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 470 CC 38 SCAR 39.6
CC
38
Cov
0%
decode_and_munge
156.0
snmp_vrf_context
72.0
get_communities
56.0
CRAP 52.6
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 3.985002; # Netdisco's minimum: Build.PL reads it from here
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>.
313  
314 =cut
315  
316 sub walk_mark {
317 my $snmp = shift;
318 return scalar @{ $snmp->walk_failures };
319 }
320  
321 =head2 incomplete_walks( $snmp, $mark )
322  
323 Returns the incomplete walk outcomes recorded since C<walk_mark> returned
324 C<$mark>, in order.
325  
326 =cut
327  
328 sub incomplete_walks {
329 my ($snmp, $mark) = @_;
330 my $failures = $snmp->walk_failures;
331 return @{$failures}[ $mark .. $#{$failures} ];
332 }
333  
334 =head2 incomplete_walk_message( $device, $what, @outcomes )
335  
336 Returns a log message for C<$what> on C<$device> naming each incomplete
337 walk outcome: its method, table, reason, rows read and walk method, with
338 the repeaters and SNMP context when there are any. When an outcome is
339 C<absent>, the message says to check the MIBs the poller loads.
340  
341 =cut
342  
343 sub incomplete_walk_message {
344 my ($device, $what, @outcomes) = @_;
345 my @walks = map {
346 sprintf('%s (%s) %s after %d rows by %s',
347 @{$_}{qw/method leaf reason rows walk/})
348 . (defined $_->{repeaters} ? " with $_->{repeaters} repeaters" : '')
349 . ((defined $_->{context} and length $_->{context})
350 ? " in context $_->{context}" : '')
351 } @outcomes;
352 my $hint = (incomplete_walk_level(@outcomes) eq 'error')
353 ? '; the poller could not translate an SNMP object, so check the netdisco-mibs'
354 . ' install and the mibhome and mibdirs settings'
355 : '';
356 return sprintf '[%s] %s - kept existing rows, incomplete SNMP walk: %s%s',
357 $device->ip, $what, (join '; ', @walks), $hint;
358 }
359  
360 =head2 incomplete_walk_level( @outcomes )
361  
362 Returns the L<App::Netdisco::Worker::Status> a worker returns after keeping
363 its stored rows for C<@outcomes>: C<error> when any outcome is C<absent>,
364 otherwise C<info>. An C<absent> walk means the poller's MIBs are broken,
365 which must show on the job, while a cut-short walk leaves the job's status
366 as it was before the guard. An C<error> job queues no discover hooks, so a
367 device first discovered while the MIBs are broken never sends its
368 C<new_device> hook.
369  
370 This is not full broken-MIB detection. It sees only the walks a guarded
371 worker names, and only while C<enable_incomplete_walk_protection> is on.
372 Leaves read behind a composite method, such as C<i_vlan_membership>, go
373 unseen, and there a broken install behaves as it did before the guard.
374  
375 =cut
376  
377 sub incomplete_walk_level {
378 return (grep { ($_->{reason} // '') eq 'absent' } @_) ? 'error' : 'info';
379 }
380  
381 =head2 incomplete_walks_for( $device, $snmp, $mark, @methods )
382  
383 Returns the incomplete walk outcomes that could have cut short a table a
384 worker is about to write: those recorded since C<walk_mark> returned C<$mark>,
385 then the latest C<walk_status> of each named C<@methods> when it is not
386 complete, then the job's record of the early C<interfaces> read when
387 C<interfaces> is among the C<@methods>. Each outcome is returned once.
388  
389 C<walk_status> is read because a table walked by an earlier worker is cached,
390 and reading it again records nothing, so the failure lies before C<$mark>. It
391 holds the latest outcome, so a method that failed and then succeeded on a
392 re-walk is not returned. An C<absent> reason counts as incomplete although
393 L<SNMP::Info> marks it complete, because it means the poller could not
394 translate the object locally, such as a broken MIB checkout.
395  
396 Returns an empty list when C<enable_incomplete_walk_protection> is false.
397  
398 =cut
399  
400 sub incomplete_walks_for {
401 my ($device, $snmp, $mark, @methods) = @_;
402 return () unless setting('enable_incomplete_walk_protection');
403  
404 my @outcomes = incomplete_walks($snmp, $mark);
405 foreach my $method (@methods) {
406 my $latest = $snmp->walk_status($method);
407 push @outcomes, $latest if $latest
408 and (not $latest->{complete} or ($latest->{reason} // '') eq 'absent');
409 }
410 push @outcomes, @{ vars->{'incomplete_walks'}{ $device->ip }{'interfaces'} || [] }
411 if grep { $_ eq 'interfaces' } @methods;
412  
413 my %seen;
414 return grep { not $seen{ refaddr $_ }++ } @outcomes;
415 }
416  
417 true;