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

filter: Statementstmt 0.0% 0 / 243 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 58 MC/DCmcdc 0.0% 0 / 36 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 444 CC 42 SCAR 43.1
CC
42
Cov
0%
add_snmpinfo_aliases
182.0
load_cache_for_device
90.0
collapse_snmp_tables
72.0
CRAP 74.7
1 package App::Netdisco::Util::Snapshot;
2  
3 use Dancer qw/:syntax :script/;
4 use Dancer::Plugin::DBIC 'schema';
5  
6 use App::Netdisco::Util::SNMP qw/get_mibdirs sortable_oid/;
7  
8 use File::Spec::Functions qw/catdir catfile/;
9 use MIME::Base64 qw/encode_base64 decode_base64/;
10 use File::Slurper 'read_lines';
11 use Storable 'dclone';
12 use Scalar::Util 'blessed';
13 use String::Util 'trim';
14 use SNMP::Info;
15  
16 use base 'Exporter';
17 our @EXPORT = ();
18 our @EXPORT_OK = qw/
19 load_cache_for_device
20 add_snmpinfo_aliases
21 make_snmpwalk_browsable
22 fixup_browser_from_aliases
23 /;
24 our %EXPORT_TAGS = (all => \@EXPORT_OK);
25  
26 =head1 NAME
27  
28 App::Netdisco::Util::Snapshot
29  
30 =head1 DESCRIPTION
31  
32 Helper functions for L<SNMP::Info> instances.
33  
34 There are no default exports, however the C<:all> tag will export all
35 subroutines.
36  
37 =head1 EXPORT_OK
38  
39 =head2 load_cache_for_device( $device )
40  
41 Tries to find a device cache in database or on disk, or build one from
42 a net-snmp snmpwalk on disk. Returns a cache.
43  
44 =cut
45  
46 sub load_cache_for_device {
47 my $device = shift;
48 return {} unless ($device->is_pseudo or not $device->in_storage);
49  
50 my $pseudo_cache = catfile( catdir(($ENV{NETDISCO_HOME} || $ENV{HOME}), 'logs', 'snapshots'), $device->ip );
51 my $loadmibs = schema('netdisco')->resultset('SNMPObject')->count;
52  
53 if (-f $pseudo_cache and not $loadmibs) {
54 warning "device snapshot exists ($pseudo_cache) but no MIB data available.";
55 warning 'skipping offline cache load - run a "loadmibs" job if you want this!';
56 return {};
57 }
58  
59 my %oids = ();
60  
61 # ideally we have a cache in the db
62 if ($device->is_pseudo
63 and not $device->oids->search({ -or => [
64 -bool => \q{ array_length(oid_parts, 1) IS NULL },
65 -bool => \q{ jsonb_typeof(value) != 'array' }, ] })->count) {
66  
67 my @rows = $device->oids->search({},{
68 join => 'oid_fields',
69 columns => [qw/oid value/],
70 select => [qw/oid_fields.mib oid_fields.leaf/], as => [qw/mib leaf/],
71 })->hri->all;
72  
73 $oids{$_->{oid}} = {
74 %{ $_ },
75 value => (@{ from_json($_->{value}) })[0],
76 } for @rows;
77 }
78 # or we have an snmpwalk file on disk
79 elsif (-f $pseudo_cache and not $device->in_storage) {
80 debug sprintf "importing snmpwalk from disk ($pseudo_cache)";
81  
82 my @lines = read_lines($pseudo_cache);
83 my %store = ();
84  
85 # sometimes we're given a snapshot with iso. instead of .1.
86 if ($lines[0] !~ m/^.\d/) {
87 warning 'snapshot file rejected - has translated names/values instead of numeric';
88 return {};
89 }
90  
91 # parse the snmpwalk output which looks like
92 # .1.0.8802.1.1.2.1.1.1.0 = INTEGER: 30
93 foreach my $line (@lines) {
94 my ($oid, $type, $value) = $line =~ m/^(\S+)\s+=\s+(?:([^:]+):\s+)?(.+)$/;
95 next unless $oid and $value;
96  
97 # empty string makes the capture go wonky
98 $value = '' if $value =~ m/^[^:]+: ?$/;
99  
100 # remove quotes from strings
101 $value =~ s/^"//;
102 $value =~ s/"$//;
103  
104 $store{$oid} = {
105 oid => $oid,
106 oid_parts => [], # not needed temporarily
107 value => to_json([ ((defined $type and $type eq 'BASE64') ? $value
108 : encode_base64(trim($value), '')) ]),
109 };
110 }
111  
112 # put into the database (temporarily)
113 # this MUST happen here and not be refactored into make_snmpwalk_browsable
114 # because make_snmpwalk_browsable is also called from snapshot job.
115 # it will all be cleaned up after
116 schema('netdisco')->txn_do(sub {
117 $device->oids->delete;
118 $device->oids->populate([values %store]);
119 });
120  
121 # get back out of the database as tables with related snmp_object (for the enum)
122 %oids = make_snmpwalk_browsable($device);
123 $oids{$_}->{value} = (@{ from_json( $oids{$_}->{value} ) })[0]
124 for keys %oids;
125 }
126  
127 # inflate the cache to an SNMP::Info cache instance
128 return snmpwalk_to_snmpinfo_cache(%oids);
129 }
130  
131 =head2 make_snmpwalk_browsable( $device )
132  
133 Takes the device_browser rows for a device and rewrites them to convert
134 table rows to hashref, enum values translated, and oid_parts filled.
135  
136 =cut
137  
138 sub make_snmpwalk_browsable {
139 my $device = shift;
140 my %oids = ();
141  
142 # to get relation from device_browser to snmp_object working for tables
143 # we need to temporarily populate device_browser with potential table oids.
144 # it will all be cleaned up after
145 my %value_oids = map {($_ => 1)} $device->oids->get_column('oid')->all;
146 my %table_oids = ();
147  
148 foreach my $orig_oid (keys %value_oids) {
149 (my $oid = $orig_oid) =~ s/\.\d+$//;
150 my $new_oid = '';
151  
152 while (length($oid)) {
153 $oid =~ s/^(\.\d+)//;
154 $new_oid .= $1;
155 $table_oids{$new_oid} = {oid => $new_oid, oid_parts => []}
156 unless exists $value_oids{$new_oid};
157 }
158 }
159  
160 $device->oids->populate([values %table_oids]);
161 my @rows = $device->oids->search({},{
162 join => 'oid_fields',
163 columns => [qw/oid value/],
164 select => [qw/oid_fields.mib oid_fields.leaf oid_fields.enum/], as => [qw/mib leaf enum/],
165 })->hri->all;
166  
167 $oids{$_->{oid}} = {
168 %{ $_ },
169 value => (defined $_->{value} ? decode_base64( (@{ from_json($_->{value}) })[0] ) : q{}),
170 } for grep {$_->{leaf} or length( (@{ from_json($_->{value}) })[0] )}
171 @rows;
172  
173 %oids = collapse_snmp_tables(%oids);
174 %oids = resolve_enums(%oids);
175
176 # walk leaves and table leaves to b64 encode again
177 # build the oid_parts list
178 foreach my $k (keys %oids) {
179 my $value = (defined $oids{$k}->{value} ? $oids{$k}->{value} : q{});
180  
181 # always a JSON array of single element
182 if (ref {} eq ref $value) {
183 $oids{$k}->{value} = to_json([{ map {($_ => encode_base64(trim($value->{$_}), ''))} keys %{ $value } }]);
184 }
185 else {
186 $oids{$k}->{value} = to_json([encode_base64(trim($value), '')]);
187 }
188  
189 $oids{$k}->{oid_parts} = [ grep {length} (split m/\./, $oids{$k}->{oid}) ];
190 }
191  
192 # store the device cache for real, now
193 schema('netdisco')->txn_do(sub {
194 $device->oids->delete;
195 $device->oids->populate([map {
196 { oid => $_->{oid}, oid_parts => $_->{oid_parts}, value => $_->{value} }
197 } values %oids]);
198 debug sprintf 'replaced %d browsable oids in db', scalar keys %oids;
199 });
200  
201 return %oids;
202 }
203  
204 =head2 collapse_snmp_tables ( %oids )
205  
206 In an snmpwalk where table rows are individual entries, gather them
207 up into a hashref. Returns %oids hash similar to what's passed in.
208  
209 =cut
210  
211 sub collapse_snmp_tables {
212 my %oids = @_;
213 return () unless scalar keys %oids;
214  
215 OID: foreach my $orig_oid (sort {sortable_oid($a) cmp sortable_oid($b)} keys %oids) {
216 my $oid = $orig_oid;
217 my $idx = '';
218  
219 # walk down the oid until we hit a known leaf
220 while (length($oid) and !defined $oids{$oid}->{leaf}) {
221 $oid =~ s/\.(\d+)$//;
222 $idx = (length $idx ? "${1}.${idx}" : $1);
223 }
224  
225 if (0 == length($oid)) {
226 # we never found a leaf, delete it and move on
227 delete $oids{$orig_oid};
228 next OID;
229 }
230  
231 $idx ||= '.0';
232 $idx =~ s/^\.//;
233  
234 if ($idx eq '0') {
235 if ($oid eq $orig_oid and $oid =~ m/\.0$/) {
236 # generally considered to be a bad idea, sometimes the OID
237 # is standardised with .0 e.g. .1.3.6.1.2.1.1.3.0 sysUpTimeInstance
238 # - do nothing as the value is already OK
239 }
240 else {
241 $oids{$oid}->{value} = $oids{$orig_oid}->{value};
242 }
243 }
244 else {
245 # on rare occasions a vendor returns .0 and .something
246 # this will overwrite the .0 (requires the sorting above)
247 $oids{$oid}->{value} = {} if ref {} ne ref $oids{$oid}->{value};
248 $oids{$oid}->{value}->{$idx} = $oids{$orig_oid}->{value};
249 }
250  
251 delete $oids{$orig_oid} if $orig_oid ne $oid;
252 }
253  
254 # remove temporary entries added to resolve table names
255 delete $oids{$_}
256 for grep {!defined $oids{$_}->{value}
257 or (ref q{} eq ref $oids{$_}->{value} and $oids{$_}->{value} eq '')}
258 keys %oids;
259  
260 return %oids;
261 }
262  
263 =head2 resolve_enums ( %oids )
264  
265 In an snmpwalk where the values are untranslated but enumerated types,
266 convert the values. Returns %oids hash similar to what's passed in.
267  
268 =cut
269  
270 sub resolve_enums {
271 my %oids = @_;
272 return () unless scalar keys %oids;
273  
274 foreach my $oid (keys %oids) {
275 next unless $oids{$oid}->{enum};
276  
277 my $value = $oids{$oid}->{value};
278 my %emap = map { reverse split m/\(/ }
279 map { s/\)//; $_ }
280 @{ $oids{$oid}->{enum} };
281  
282 if (ref q{} eq ref $value) {
283 $oids{$oid}->{value} = $emap{$value} if exists $emap{$value};
284 }
285 elsif (ref {} eq ref $value) {
286 foreach my $k (keys %$value) {
287 $oids{$oid}->{value}->{$k} = $emap{ $value->{$k} }
288 if exists $emap{ $value->{$k} };
289 }
290 }
291 }
292  
293 return %oids;
294 }
295  
296 =head2 snmpwalk_to_snmpinfo_cache( %oids )
297  
298 Takes an snmpwalk with collapsed tables and returns an SNMP::Info
299 instance using that as the cache.
300  
301 =cut
302  
303 sub snmpwalk_to_snmpinfo_cache {
304 my %walk = @_;
305 return () unless scalar keys %walk;
306  
307 # unpack the values
308 foreach my $oid (keys %walk) {
309 my $value = $walk{$oid}->{value};
310  
311 if (ref q{} eq ref $value) {
312 $walk{$oid}->{value} = decode_base64($walk{$oid}->{value});
313 }
314 elsif (ref {} eq ref $value) {
315 foreach my $k (keys %$value) {
316 $walk{$oid}->{value}->{$k}
317 = decode_base64($walk{$oid}->{value}->{$k});
318 }
319 }
320 }
321  
322 my $info = SNMP::Info->new({
323 Offline => 1,
324 Cache => {},
325 Session => {},
326 MibDirs => [ get_mibdirs() ],
327 AutoSpecify => 0,
328 IgnoreNetSNMPConf => 1,
329 Debug => ($ENV{INFO_TRACE} || 0),
330 DebugSNMP => ($ENV{SNMP_TRACE} || 0),
331 });
332  
333 foreach my $oid (keys %walk) {
334 my $qleaf = $walk{$oid}->{mib} . '::' . $walk{$oid}->{leaf};
335 (my $snmpqleaf = $qleaf) =~ s/[-:]/_/g;
336  
337 $info->_cache($walk{$oid}->{leaf}, $walk{$oid}->{value});
338 $info->_cache($snmpqleaf, $walk{$oid}->{value});
339 }
340  
341 # debug sprintf "snmpwalk_to_snmpinfo: cache size: %d", scalar keys %{ $info->cache };
342 return add_snmpinfo_aliases($info);
343 }
344  
345 =head2 add_snmpinfo_aliases( $snmp_info_instance | $snmp_info_cache )
346  
347 Add in any GLOBALS and FUNCS aliases from the SNMP::Info device class
348 or else a set of defaults that allow device discovery. Returns the cache.
349  
350 =cut
351  
352 sub add_snmpinfo_aliases {
353 my $info = shift or return {};
354  
355 if (not blessed $info) {
356 $info = SNMP::Info->new({
357 Offline => 1,
358 Cache => $info,
359 Session => {},
360 MibDirs => [ get_mibdirs() ],
361 AutoSpecify => 0,
362 IgnoreNetSNMPConf => 1,
363 Debug => ($ENV{INFO_TRACE} || 0),
364 DebugSNMP => ($ENV{SNMP_TRACE} || 0),
365 });
366 }
367  
368 my %globals = %{ $info->globals };
369 my %funcs = %{ $info->funcs };
370  
371 while (my ($alias, $leaf) = each %globals) {
372 next if $leaf =~ m/\.\d+$/;
373 $info->_cache($alias, $info->$leaf) if $info->$leaf;
374 }
375  
376 while (my ($alias, $leaf) = each %funcs) {
377 $info->_cache($alias, dclone $info->$leaf) if ref q{} ne ref $info->$leaf;
378 }
379  
380 # SNMP::Info::Layer3 has some weird structures we can try to fix here
381  
382 my %propfix = (
383 chassisId => 'serial1',
384 ospfRouterId => 'router_ip',
385 bgpIdentifier => 'bgp_id',
386 bgpLocalAs => 'bgp_local_as',
387 ifPhysAddress => 'mac',
388 qw(
389 model model
390 serial serial
391 os_ver os_ver
392 os os
393 ),
394 );
395  
396 foreach my $prop (keys %propfix) {
397 my $val = $info->$prop;
398 $val = [values %$val]->[0] if ref $val eq 'HASH';
399 $info->_cache($propfix{$prop}, $val);
400 }
401  
402 # netdisco will try uptime or hrSystemUptime or sysUptime (but not sysUptimeInstance)
403 if (defined $info->sysUpTimeInstance) {
404 my $uptime = (ref {} eq ref $info->sysUpTimeInstance)
405 ? ($info->sysUpTimeInstance->{0} || $info->sysUpTimeInstance->{''})
406 : $info->sysUpTimeInstance;
407
408 if (!defined $info->uptime) {
409 $info->_cache('uptime', $uptime);
410 }
411 if (!defined $info->sysUpTime) {
412 $info->_cache('sysUpTime', $uptime);
413 }
414 }
415  
416 # now for any other SNMP::Info method in GLOBALS or FUNCS which Netdisco
417 # might call, but will not have data, we fake a cache entry to avoid
418 # throwing errors
419  
420 while (my $method = <DATA>) {
421 $method =~ s/\s//g;
422 next unless length $method and not $info->$method;
423  
424 $info->_cache($method, '') if exists $globals{$method};
425 $info->_cache($method, {}) if exists $funcs{$method};
426 }
427  
428 # debug sprintf "add_snmpinfo_aliases: cache size: %d", scalar keys %{ $info->cache };
429 return $info->cache;
430 }
431  
432 =head2 fixup_browser_from_aliases( $device_instance, $snmp_info_instance )
433  
434 Now we have a solid SNMP::Info cache, if there are any fixups of browser
435 data they can happen here.
436  
437 =cut
438  
439 sub fixup_browser_from_aliases {
440 my $device = shift or return;
441 my $info = shift or return;
442  
443 my $e_type = $info->e_type;
444 if (scalar keys %$e_type) {
445 my $row = $device->oids->find({ oid => '.1.3.6.1.2.1.47.1.1.1.1.3' });
446 $row->update({ value =>
447 to_json([{ map {($_ => encode_base64(trim($e_type->{$_}), ''))} keys %{ $e_type } }]) });
448 }
449 }
450  
451 true;
452  
453 __DATA__