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

filter: Statementstmt 0.0% 0 / 197 Branchbran 0.0% 0 / 136 Conditioncond 0.0% 0 / 155 MC/DCmcdc 0.0% 0 / 88 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 607 CC 69 SCAR 63.4
CC
69
Cov
0%
_snmp_connect_generic
1332.0
_try_connect
156.0
_try_read
72.0
CRAP 567.3
1 package App::Netdisco::Transport::SNMP;
2  
3 use Dancer qw/:syntax :script/;
4 use Dancer::Plugin::DBIC 'schema';
5  
6 use App::Netdisco::Util::SNMP qw/get_communities get_mibdirs/;
7 use App::Netdisco::Util::Device 'get_device';
8 use App::Netdisco::Util::Permission 'acl_matches';
9 use App::Netdisco::Util::Snapshot qw/load_cache_for_device add_snmpinfo_aliases fixup_browser_from_aliases/;
10  
11 use SNMP::Info;
12 use Try::Tiny;
13 use Module::Load ();
14 use NetAddr::IP::Lite ':lower';
15 use List::Util qw/pairkeys pairfirst/;
16 use Scalar::Util 'blessed';
17  
18 use base 'Dancer::Object::Singleton';
19  
20 =head1 NAME
21  
22 App::Netdisco::Transport::SNMP
23  
24 =head1 DESCRIPTION
25  
26 Singleton for SNMP connections. Returns cached L<SNMP::Info> instance for a
27 given device IP, or else undef. All methods are class methods, for example:
28  
29 my $snmp = App::Netdisco::Transport::SNMP->reader_for( ... );
30  
31 =cut
32  
33 __PACKAGE__->attributes(qw/ readers writers /);
34  
35 sub init {
36 my ( $class, $self ) = @_;
37 $self->readers( {} );
38 $self->writers( {} );
39 return $self;
40 }
41  
42 =head1 reader_for( $ip, $useclass? )
43  
44 Given an IP address, returns an L<SNMP::Info> instance configured for and
45 connected to that device. The IP can be any on the device, and the management
46 interface will be connected to.
47  
48 If the device is known to Netdisco and there is a cached SNMP community
49 string, that community will be tried first, and then other community strings
50 from the application configuration will be tried.
51  
52 If C<$useclass> is provided, it will be used as the L<SNMP::Info> device
53 class instead of the class in the Netdisco database.
54  
55 Returns C<undef> if the connection fails.
56  
57 =cut
58  
59 sub reader_for {
60 my ($class, $ip, $useclass) = @_;
61 my $device = get_device($ip) or return undef;
62  
63 my $readers = $class->instance->readers or return undef;
64 return $readers->{$device->ip} if exists $readers->{$device->ip};
65  
66 debug sprintf 'snmp reader cache warm: [%s]', $device->ip;
67 return ($readers->{$device->ip}
68 = _snmp_connect_generic('read', $device, $useclass));
69 }
70  
71 =head1 test_connection( $ip )
72  
73 Similar to C<reader_for> but will use the literal IP address passed, and does
74 not support specifying the device class. The purpose is to test the SNMP
75 connectivity to the device before a renumber.
76  
77 Attempts to have no side effect, however there will be a stored SNMP
78 authentication hint (tag) in the database if the connection is successful.
79  
80 Returns C<undef> if the connection fails.
81  
82 =cut
83  
84 sub test_connection {
85 my ($class, $ip) = @_;
86 my $addr = NetAddr::IP::Lite->new($ip) or return undef;
87  
88 # avoid renumbering to localhost loopbacks
89 return undef if $addr->addr eq '0.0.0.0'
90 or acl_matches($addr->addr, 'group:__LOOPBACK_ADDRESSES__');
91  
92 my $device = schema(vars->{'tenant'})->resultset('Device')
93 ->new_result({ ip => $addr->addr }) or return undef;
94  
95 my $readers = $class->instance->readers or return undef;
96 return $readers->{$device->ip} if exists $readers->{$device->ip};
97  
98 debug sprintf 'snmp reader cache warm: [%s]', $device->ip;
99 return ($readers->{$device->ip} = _snmp_connect_generic('read', $device));
100 }
101  
102 =head1 writer_for( $ip, $useclass? )
103  
104 Same as C<reader_for> but uses the read-write community strings from the
105 application configuration file.
106  
107 Returns C<undef> if the connection fails.
108  
109 =cut
110  
111 sub writer_for {
112 my ($class, $ip, $useclass) = @_;
113 my $device = get_device($ip) or return undef;
114  
115 return undef if $device->in_storage and $device->is_pseudo;
116  
117 my $writers = $class->instance->writers or return undef;
118 return $writers->{$device->ip} if exists $writers->{$device->ip};
119  
120 debug sprintf 'snmp writer cache warm: [%s]', $device->ip;
121 return ($writers->{$device->ip}
122 = _snmp_connect_generic('write', $device, $useclass));
123 }
124  
125 sub _snmp_connect_generic {
126 my ($mode, $device, $useclass) = @_;
127 $mode ||= 'read';
128  
129 my %snmp_args = (
130 AutoSpecify => 0,
131 DestHost => $device->ip,
132 # the defined() allows 0 to be a settable value
133 Retries => defined(setting('snmpretries')) ? setting('snmpretries') : 2,
134 Timeout => (setting('snmptimeout') || 1000000),
135 NonIncreasing => (setting('nonincreasing') || 0),
136 BulkWalk => ((defined setting('bulkwalk_off') && setting('bulkwalk_off'))
137 ? 0 : 1),
138 BulkRepeaters => (setting('bulkwalk_repeaters') || 20),
139 # pinned so a change of SNMP::Info's default cannot change what is stored
140 IncompleteWalk => 'partial',
141 MibDirs => [ get_mibdirs() ],
142 IgnoreNetSNMPConf => 1,
143 Debug => ($ENV{INFO_TRACE} || 0),
144 DebugSNMP => ($ENV{SNMP_TRACE} || 0),
145 );
146 my $snmp_fast_connect_timeout = defined(setting('snmp_fast_connect_timeout'))
147 ? setting('snmp_fast_connect_timeout') : 200000;
148  
149 # an override for RemotePort
150 ($snmp_args{RemotePort}) =
151 (pairkeys pairfirst { acl_matches($device, $b) }
152 %{setting('snmp_remoteport') || {}}) || 161;
153  
154 # an override for bulkwalk
155 $snmp_args{BulkWalk} = 0 if acl_matches($device, 'bulkwalk_no');
156  
157 # further protect against buggy Net-SNMP, and disable bulkwalk
158 if ($snmp_args{BulkWalk}
159 and ($SNMP::VERSION eq '5.0203' || $SNMP::VERSION eq '5.0301')) {
160  
161 warning sprintf
162 "[%s] turning off BulkWalk due to buggy Net-SNMP - please upgrade!",
163 $device->ip;
164 $snmp_args{BulkWalk} = 0;
165 }
166  
167 # support for offline cache
168 my $cache = load_cache_for_device($device);
169 if (scalar keys %$cache) {
170 $snmp_args{Cache} = $cache;
171 $snmp_args{Offline} = 1;
172 # support pseudo/offline device renumber and also pseudo device autovivification
173 $device->set_column(is_pseudo => \'true') if not $device->is_pseudo;
174 debug sprintf 'snmp transport running in offline mode for: [%s]', $device->ip;
175 }
176  
177 # any net-snmp options to add or override
178 foreach my $k (keys %{ setting('net_snmp_options') }) {
179 $snmp_args{ $k } = setting('net_snmp_options')->{ $k };
180 }
181  
182 if (scalar keys %{ setting('net_snmp_options') }
183 or not $snmp_args{BulkWalk}) {
184 foreach my $k (sort keys %snmp_args) {
185 next if $k eq 'MibDirs';
186 debug sprintf 'snmp transport conf: %s => %s', $k, $snmp_args{ $k };
187 }
188 }
189  
190 # get the community string(s)
191 my @communities = $snmp_args{Offline}
192 ? ({read => 1, write => 0, only => $device->ip, community => 'public'})
193 : get_communities($device, $mode);
194  
195 # which SNMP versions to try and in what order
196 my @versions =
197 ( acl_matches($device->ip, 'snmpforce_v3') ? (3)
198 : acl_matches($device->ip, 'snmpforce_v2') ? (2)
199 : acl_matches($device->ip, 'snmpforce_v1') ? (1)
200 : (reverse (1 .. (setting('snmpver') || 3))) );
201  
202 # use existing or new device class
203 my @classes = ($useclass || 'SNMP::Info');
204 if ($device->snmp_class and not $useclass) {
205 unshift @classes, $device->snmp_class;
206 }
207  
208 # try last known-good by tag if it's stored
209 # this gets in the way of SNMP version upgrade (2 to 3)
210 # but can use only/no or snmpforce_v* to get around that
211  
212 my $tag_name = 'snmp_auth_tag_'. $mode;
213 my $stored_tag = eval { $device->community->$tag_name };
214  
215 if ($device->in_storage and $stored_tag) {
216 debug sprintf '[%s:%s] try_connect with cached tag %s',
217 $snmp_args{DestHost}, $snmp_args{RemotePort}, $stored_tag;
218  
219 my $comm = $communities[0];
220 my $ver = (exists $comm->{community} ? 2 : 3);
221 my %local_args = (%snmp_args,
222 Version => $ver, Retries => 0, Timeout => $snmp_fast_connect_timeout);
223
224 my $info = _try_connect($device, $classes[0], $comm, $mode, \%local_args,
225 ($useclass ? 0 : 1) );
226 # if successful, restore the default/user timeouts and return
227 if ($info) {
228 my $class = ($useclass ? $classes[0] : $info->device_type) // $classes[0];
229 Module::Load::load $class;
230 return $class->new(
231 %snmp_args, Version => $ver,
232 ($info->offline ? (Cache => $info->cache) : ()),
233 _mk_info_commargs($comm),
234 );
235 }
236 }
237  
238 # try the communities in a fast pass using best version
239  
240 VERSION: foreach my $ver (3, 2) {
241 my %local_args = (%snmp_args,
242 Version => $ver, Retries => 0, Timeout => $snmp_fast_connect_timeout);
243  
244 COMMUNITY: foreach my $comm (@communities) {
245 next unless $comm;
246  
247 next if $ver eq 3 and exists $comm->{community};
248 next if $ver ne 3 and !exists $comm->{community};
249  
250 my $info = _try_connect($device, $classes[0], $comm, $mode, \%local_args,
251 ($useclass ? 0 : 1) );
252  
253 # if successful, restore the default/user timeouts and return
254 if ($info) {
255 my $class = ($useclass ? $classes[0] : $info->device_type) // $classes[0];
256 Module::Load::load $class;
257 return $class->new(
258 %snmp_args, Version => $ver,
259 ($info->offline ? (Cache => $info->cache) : ()),
260 _mk_info_commargs($comm),
261 );
262 }
263 }
264 }
265  
266 # then revert to conservative settings and repeat with all versions
267  
268 # unless user wants just the fast connections for bulk discovery
269 # or we are on the first discovery attempt of a new device
270 return if setting('snmp_try_slow_connect') == false;
271  
272 CLASS: foreach my $class (@classes) {
273 next unless $class;
274  
275 VERSION: foreach my $ver (@versions) {
276 next unless $ver;
277 my %local_args = (%snmp_args, Version => $ver);
278  
279 COMMUNITY: foreach my $comm (@communities) {
280 next unless $comm;
281  
282 next if $ver eq 3 and exists $comm->{community};
283 next if $ver ne 3 and !exists $comm->{community};
284  
285 my $info = _try_connect($device, $class, $comm, $mode, \%local_args,
286 ($useclass ? 0 : 1) );
287 return $info if $info;
288 }
289 }
290 }
291  
292 return undef;
293 }
294  
295 sub _try_connect {
296 my ($device, $class, $comm, $mode, $snmp_args, $reclass) = @_;
297 my %comm_args = _mk_info_commargs($comm);
298 my $debug_comm = '<hidden>';
299 if ($ENV{ND2_SHOW_COMMUNITY} || $ENV{SHOW_COMMUNITY}) {
300 $debug_comm = ($comm->{community} ||
301 (sprintf 'v3:%s:%s/%s', ($comm->{user},
302 ($comm->{auth}->{proto} || 'noAuth'),
303 ($comm->{priv}->{proto} || 'noPriv'))) );
304 }
305 my $info = undef;
306  
307 try {
308 $snmp_args->{Offline} || debug
309 sprintf '[%s:%s] try_connect with v: %s, t: %s, r: %s, class: %s%s, comm: %s',
310 $snmp_args->{DestHost}, $snmp_args->{RemotePort},
311 $snmp_args->{Version}, ($snmp_args->{Timeout} / 1000000), $snmp_args->{Retries},
312 $class,
313 ($comm->{tag} ? ', tag: '. $comm->{tag} : ''), $debug_comm;
314 Module::Load::load $class;
315  
316 $info = $class->new(%$snmp_args, %comm_args) or return;
317 $info = ($mode eq 'read' ? _try_read($info, $device, $comm)
318 : _try_write($info, $device, $comm));
319  
320 # first time a device is discovered, re-instantiate into specific class
321 if ($reclass and $info and ($info->device_type // '') ne $class) {
322 $class = $info->device_type // $class;
323 $info->offline || debug
324 sprintf '[%s:%s] try_connect with v: %s, new class: %s, comm: %s',
325 $snmp_args->{DestHost}, $snmp_args->{RemotePort},
326 $snmp_args->{Version}, $class, $debug_comm;
327  
328 Module::Load::load $class;
329 $info = $class->new(%$snmp_args, %comm_args);
330  
331 if ($info->offline) {
332 add_snmpinfo_aliases($info);
333 fixup_browser_from_aliases($device, $info);
334 }
335 }
336 else {
337 add_snmpinfo_aliases($info) if $info and $info->offline;
338 }
339 }
340 catch {
341 my $ex = $_;
342 my $err = !defined $ex ? '(undef)'
343 : !ref $ex ? do { (my $e = "$ex") =~ s/ at \S+ line \d+.*//s; $e }
344 : (blessed $ex && $ex->can('message')) ? $ex->message
345 : (ref $ex eq 'HASH') ? ($ex->{message} || $ex->{error} || join('; ', map { "$_: $ex->{$_}" } sort keys %$ex) || '(empty hashref - MCE worker killed or timed out)')
346 : "$ex";
347 $err = ref($ex) || '(empty)' unless length $err;
348 debug sprintf 'caught error in try_connect: %s', $err;
349 undef $info;
350 die "exception in SNMP - could be job timeout or crash: $err\n";
351 # use DDP; debug p $_;
352 };
353  
354 return $info;
355 }
356  
357 sub _try_read {
358 my ($info, $device, $comm) = @_;
359  
360 return undef unless (
361 (not defined $info->error)
362 and (defined $info->uptime or defined $info->hrSystemUptime or defined $info->sysUpTime)
363 and ($info->layers or $info->description)
364 and $info->class
365 );
366  
367 return $info if $info->offline;
368
369 $device->in_storage
370 ? $device->update({snmp_ver => $info->snmp_ver})
371 : $device->set_column(snmp_ver => $info->snmp_ver);
372  
373 if ($comm->{community}) {
374 my $new_comm = (($info->snmp_ver and ($info->snmp_ver == 3))
375 ? undef : $comm->{community});
376 $device->in_storage
377 ? $device->update({snmp_comm => $new_comm})
378 : $device->set_column(snmp_comm => $new_comm);
379 }
380  
381 # regardless of device in storage, save the hint
382 $device->update_or_create_related('community',
383 {snmp_auth_tag_read => $comm->{tag}}) if $comm->{tag};
384  
385 return $info;
386 }
387  
388 sub _try_write {
389 my ($info, $device, $comm) = @_;
390  
391 my $loc = $info->load_location;
392 $info->set_location($loc) or return undef;
393 return undef unless ($loc eq $info->load_location);
394  
395 $device->in_storage
396 ? $device->update({snmp_ver => $info->snmp_ver})
397 : $device->set_column(snmp_ver => $info->snmp_ver);
398  
399 # one of these two cols must be set
400 $device->update_or_create_related('community', {
401 ($comm->{tag} ? (snmp_auth_tag_write => $comm->{tag}) : ()),
402 ($comm->{community} ? (snmp_comm_rw => $comm->{community}) : ()),
403 });
404  
405 return $info;
406 }
407  
408 sub _mk_info_commargs {
409 my $comm = shift;
410 return () unless ref {} eq ref $comm and scalar keys %$comm;
411  
412 return (Community => $comm->{community})
413 if exists $comm->{community};
414  
415 my $seclevel =
416 (exists $comm->{auth} ?
417 (exists $comm->{priv} ? 'authPriv' : 'authNoPriv' )
418 : 'noAuthNoPriv');
419  
420 return (
421 SecName => $comm->{user},
422 SecLevel => $seclevel,
423 ( exists $comm->{auth} ? (
424 AuthProto => uc ($comm->{auth}->{proto} || 'MD5'),
425 AuthPass => ($comm->{auth}->{pass} || ''),
426 ( exists $comm->{priv} ? (
427 PrivProto => uc ($comm->{priv}->{proto} || 'DES'),
428 PrivPass => ($comm->{priv}->{pass} || ''),
429 ) : ()),
430 ) : ()),
431 );
432 }
433  
434 true;