Netsync.pm

filter: Statementstmt 94.7% 36 / 38 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 13 / 13 Podpod n/a totaltotal 96.0% 49 / 51 CC 1 SCAR 0.2
CC
1
Cov
95%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Netsync/SNMP.pm ↑ Summary
1 package App::Netsync;
2  
3 =head1 NAME
4  
5 App::Netsync - network/database synchronization library
6  
7 =head1 DESCRIPTION
8  
9 This package can discover a network and synchronize it with a database.
10  
11 =head1 SYNOPSIS
12  
13 use App::Netsync;
14  
15 App::Netsync::configure({
16 'Table' => 'assets',
17 'DeviceField' => 'SERIAL_NUMBER',
18 'InterfaceField' => 'PORT',
19 'InfoFields' => ['BLDG','ROOM','JACK'],
20 },{
21 'domain' => 'example.com',
22 },{
23 'Version' => 2,
24 'Community' => 'example',
25 },{
26 'DBMS' => 'pg',
27 'Server' => 'pg.example.com',
28 'Port' => 5432,
29 'Database' => 'example_db',
30 'Username' => 'user',
31 'Password' => 'pass',
32 });
33  
34 my $nodes = App::Netsync::discover ('DNS','host[0-9]+');
35 App::Netsync::identify ($nodes,'DB',1);
36 App::Netsync::update ($nodes);
37  
38 =cut
39  
40  
41 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
44  
45 1 ▶use autodie; #XXX Is autodie adequate?
Subroutine BEGIN: called CC=1 SCAR=0.0
46 1 ▶use feature 'say';
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 1 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 1 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 1 ▶use Net::DNS;
Subroutine BEGIN: called CC=1 SCAR=0.0
51 1 ▶use Text::CSV;
Subroutine BEGIN: called CC=1 SCAR=0.0
52 1 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
53  
54 1 ▶use App::Netsync::Network;
Subroutine BEGIN: called CC=1 SCAR=0.0
55 1 ▶use App::Netsync::Scribe 'note';
Subroutine BEGIN: called CC=1 SCAR=0.0
56 0 ▶use App::Netsync::SNMP;
Subroutine BEGIN: called CC=1 SCAR=2.6
57  
58 our ($SCRIPT,$VERSION);
59 our %config;
60  
61 BEGIN {
62 ($SCRIPT) = fileparse ($0,"\.[^.]*");
63 ($VERSION) = version->declare('v4.0.0');
64  
65 require Exporter;
66 our @ISA = ('Exporter');
67 our @EXPORT_OK = ('device_interfaces');
68 }
69  
70 INIT { # These are described in the "Available Environment Setings" POD below.
71 $config{'Indent'} = 4;
72 $config{'Quiet'} = 0;
73 $config{'Verbose'} = 0;
74  
75 $config{'Table'} = undef;
76 $config{'DeviceField'} = undef;
77 $config{'InterfaceField'} = undef;
78 $config{'InfoFields'} = undef;
79 $config{'SyncOID'} = 'ifAlias';
80  
81 $config{'DeviceOrder'} = 4;
82  
83 $config{'NodeLog'} = '/var/log/'.$SCRIPT.'/nodes.log';
84 $config{'ConflictLog'} = '/var/log/'.$SCRIPT.'/conflicts.log';
85 $config{'UpdateLog'} = '/var/log/'.$SCRIPT.'/updates.log';
86  
87 $config{'DNS'} = undef;
88 $config{'SNMP'} = undef;
89 $config{'DB'} = undef;
90 }
91  
92  
93 =head1 METHODS
94  
95 =head2 configure
96  
97 configure the operating environment
98  
99 B<Arguments>
100  
101 I<( \%Netsync [, \%DNS [, \%SNMP [, \%DB ] ] ] )>
102  
103 =over 3
104  
105 =item Netsync
106  
107 key-value pairs of Netsync environment settings
108  
109 B<Available Environment Settings>
110  
111 I<Note: If a default is not specified, the setting is required.>
112  
113 =over 4
114  
115 =item ConflictLog
116  
117 where to log conflicts
118  
119 default: F</var/log/E<lt>script nameE<gt>/conflicts.log>
120  
121 =item DeviceField
122  
123 the table field to use as a unique ID for devices
124  
125 =item DeviceOrder
126  
127 the width of fields specifying node and device counts
128  
129 default: 4
130  
131 I<Example>
132  
133 =over 5
134  
135 =item DeviceOrder = 3 (i.e. nodes < 1000), 500 nodes
136  
137 > discovering (using DNS)... 500 nodes (50 skipped), 600 devices (50 stacks)
138  
139 =item DeviceOrder = 9 (i.e. nodes < 1000000000), 500 nodes
140  
141 > discovering (using DNS)... 500 nodes (50 skipped), 600 devices (50 stacks)
142  
143 =item DeviceOrder = 1 (i.e. nodes < 10), 20 nodes !
144  
145 > discovering (using DNS)... 111111111120 nodes (2 skipped), 24 devices (2 stacks)
146  
147 =back
148  
149 =item Indent
150  
151 the number of spaces to use when output is indented
152  
153 default: 4
154  
155 =item InfoFields
156  
157 which table fields to synchronize with device interfaces
158  
159 =item InterfaceField
160  
161 which table field to use as a unique ID for device interfaces
162  
163 =item NodeLog
164  
165 where to log all probed nodes
166  
167 default: F</var/log/E<lt>script nameE<gt>/nodes.log>
168  
169 =item Quiet
170  
171 Print nothing.
172  
173 default: 0
174  
175 =item SyncOID
176  
177 which OID to send synchronized information to when updating
178  
179 default: ifAlias
180  
181 =item Table
182  
183 which database table to use
184  
185 =item UpdateLog
186  
187 where to log all modifications made to the network
188  
189 default: F</var/log/E<lt>script nameE<gt>/updates.log>
190  
191 =item Verbose
192  
193 Print everything.
194  
195 Note: Quiet mode overrides Verbose mode.
196  
197 default: 0
198  
199 =back
200  
201 I<Netsync requires the following settings to use a DBMS:>
202  
203 =over 4
204  
205 =item DBMS
206  
207 the database platform to use
208  
209 =item Server
210  
211 the server containing the database to use
212  
213 =item Port
214  
215 the port to contact the database server on
216  
217 =item Database
218  
219 the database to connect to
220  
221 =item Username
222  
223 the user to connect to the database as
224  
225 =item Password
226  
227 the authentication key to use to connect to the database
228  
229 =back
230  
231 I<Netsync requires the following settings to use SNMP:>
232  
233 =over 4
234  
235 =item MIBdir
236  
237 the location of MIBs required by Netsync
238  
239 default: F</usr/share/E<lt>script nameE<gt>/mib>
240  
241 =back
242  
243 =item DNS
244  
245 See Net::DNS documentation for more acceptable settings.
246  
247 =item SNMP
248  
249 See SNMP::Session documentation for more acceptable settings.
250  
251 =item DB
252  
253 See DBI documentation for more acceptable settings.
254  
255 =back
256  
257 =cut
258  
259 sub configure {
260 warn 'too few arguments' if @_ < 1;
261 warn 'too many arguments' if @_ > 4;
262 my ($Netsync,$DNS,$SNMP,$DB) = @_;
263  
264 $config{$_} = $Netsync->{$_} foreach keys %$Netsync;
265  
266 my $success = 1;
267 if ((defined $DB->{'Server'} or defined $DB->{'Port'} or
268 defined $DB->{'DBMS'} or defined $DB->{'Database'} or
269 defined $DB->{'Username'} or defined $DB->{'Password'}) and not
270 (defined $DB->{'Server'} and defined $DB->{'Port'} and
271 defined $DB->{'DBMS'} and defined $DB->{'Database'} and
272 defined $DB->{'Username'} and defined $DB->{'Password'})) {
273 warn 'DBMS configuration is inadequate.';
274 $success = 0;
275 }
276  
277 unless (App::Netsync::SNMP::configure($SNMP,[
278 'IF-MIB','ENTITY-MIB', # standard
279 'CISCO-STACK-MIB', # Cisco
280 'FOUNDRY-SN-AGENT-MIB','FOUNDRY-SN-SWITCH-GROUP-MIB', # Brocade
281 'SEMI-MIB', # 'HP-SN-AGENT-MIB' # HP #XXX Is HP-SN-AGENT-MIB analgous to FOUNDRY-SN-AGENT-MIB?
282 ])) {
283 warn 'App::Netsync::SNMP misconfiguration';
284 $success = 0;
285 }
286 $config{'DB'} = $DB if defined $DB;
287 $config{'DNS'} = $DNS if defined $DNS;
288 return $success;
289 }
290  
291  
292 =head2 device_interfaces
293  
294 discover all the devices and corresponding interfaces of a potentially stacked node
295  
296 B<Arguments>
297  
298 I<( $vendor , $session )>
299  
300 =over 3
301  
302 =item vendor
303  
304 a value returned from SNMP::Info::vendor
305  
306 B<Supported Vendors>
307  
308 =over 4
309  
310 =item brocade/foundry
311  
312 =item cisco
313  
314 =item hp
315  
316 =back
317  
318 =item session
319  
320 an SNMP::Session object
321  
322 =back
323  
324 B<Example>
325  
326 =over 3
327  
328 C<device_interfaces ($node-E<gt>{'info'}-E<gt>vendor,$node-E<gt>{'session'});>
329  
330 {
331 '1A2B3C4D5E6F' => {
332 '1001' => 'ethernet1/1/1',
333 '1002' => 'ethernet1/1/2',
334 ...
335 },
336 '2B3C4D5E6F7G' => {
337 '2001' => 'ethernet2/1/1',
338 '2002' => 'ethernet2/1/2',
339 ...
340 },
341 ...
342 }
343  
344 =back
345  
346 =cut
347  
348 sub device_interfaces {
349 warn 'too few arguments' if @_ < 2;
350 warn 'too many arguments' if @_ > 2;
351 my ($vendor,$session) = @_;
352  
353 my %serial2if2ifName; # This will hold interface IIDs and names for each serial.
354 {
355 my %if2ifName; # This will associate interface IIDs with ifNames or ifDescrs.
356 {
357 my ($types) = App::Netsync::SNMP::get1 ([['.1.3.6.1.2.1.2.2.1.3' => 'ifType']],$session); # IF-MIB
358 my ($ifNames,$ifs) = App::Netsync::SNMP::get1 ([
359 ['.1.3.6.1.2.1.2.2.1.2' => 'ifDescr'], # IF-MIB
360 ['.1.3.6.1.2.1.31.1.1.1.1' => 'ifName'], # IF-MIB
361 ],$session); # IF-MIB
362 foreach my $i (keys @$ifs) { # Make sure interface names are defined.
363 unless (defined $types->[$i] and defined $ifNames->[$i]) {
364 warn 'malformed IF-MIB results';
365 next;
366 }
367 $if2ifName{$ifs->[$i]} = $ifNames->[$i] if $types->[$i] =~ /^(?!1|24|53)[0-9]+$/; # Exclude virtual interfaces.
368 }
369 }
370  
371 my @serials;
372 { # ENTITY-MIB
373 my ($serials) = App::Netsync::SNMP::get1 ([['.1.3.6.1.2.1.47.1.1.1.1.11' => 'entPhysicalSerialNum']],$session);
374 if (defined $serials) {
375 my ($classes) = App::Netsync::SNMP::get1 ([['.1.3.6.1.2.1.47.1.1.1.1.5' => 'entPhysicalClass']],$session);
376 foreach my $i (keys @$classes) {
377 push (@serials,$serials->[$i]) if $classes->[$i] =~ /3/ and $serials->[$i] !~ /[^[:ascii:]]/; # Include only chassis serials.
378 }
379 }
380 }
381 unless (@serials > 0) {
382 my $serials;
383 {
384 my $cisco = sub { # CISCO-STACK-MIB
385 ($serials) = App::Netsync::SNMP::get1 ([
386 ['.1.3.6.1.4.1.9.5.1.3.1.1.3' => 'moduleSerialNumber'],
387 ['.1.3.6.1.4.1.9.5.1.3.1.1.26' => 'moduleSerialNumberString'],
388 ],$session);
389 };
390 my $brocade = sub { # FOUNDRY-SN-AGENT-MIB?
391 ($serials) = App::Netsync::SNMP::get1 ([
392 ['.1.3.6.1.4.1.1991.1.1.1.4.1.1.2' => 'snChasUnitSerNum'],
393 ['.1.3.6.1.4.1.1991.1.1.1.1.2' => 'snChasSerNum'], # stacks not supported
394 ],$session);
395 };
396 my $hp = sub { # SEMI-MIB #XXX HP-SN-AGENT-MIB
397 ($serials) = App::Netsync::SNMP::get1 ([
398 ['.1.3.6.1.4.1.11.2.36.1.1.2.9' => 'hpHttpMgSerialNumber'],
399 #['.1.3.6.1.4.1.11.2.36.1.1.5.1.1.10' => 'hpHttpMgDeviceSerialNumber'],
400 #['.1.3.6.1.4.1.11.2.3.7.11.12.1.1.1.2' => 'snChasSerNum'], #XXX HP-SN-AGENT-MIB stacks not supported?
401 ],$session);
402 };
403 my %vendors = (
404 'cisco' => $cisco,
405 'brocade' => $brocade,
406 'foundry' => $brocade,
407 'hp' => $hp,
408 'unsupported' => sub {
409 warn $vendor.' devices are not supported.';
410 },
411 );
412 ($vendors{$vendor} || $vendors{'unsupported'})->();
413 }
414  
415 foreach my $serial (@$serials) {
416 push (@serials,$serial) if $serial !~ /[^[:ascii:]]/; # ASCII only!
417 }
418 }
419 if (@serials == 0) { return undef; } # No serials found.
420 if (@serials == 1) { # Non-stacked node containing 1 device.
421 $serial2if2ifName{$serials[0]} = \%if2ifName;
422 }
423 else {
424 my %if2serial; # This will associate interface IIDs with the serial of the corresponding chassis.
425 {
426 my $cisco = sub { # CISCO-STACK-MIB
427 my ($port2if) = App::Netsync::SNMP::get1 ([['.1.3.6.1.4.1.9.5.1.4.1.1.11' => 'portIfIndex']],$session);
428 my @port2serial;
429 {
430 my ($port2module) = App::Netsync::SNMP::get1 ([['.1.3.6.1.4.1.9.5.1.4.1.1.1' => 'portModuleIndex']],$session);
431 my %module2serial; # A module is basically a chassis IID.
432 {
433 my ($serials,$modules) = App::Netsync::SNMP::get1 ([
434 ['.1.3.6.1.4.1.9.5.1.3.1.1.3' => 'moduleSerialNumber'],
435 ['.1.3.6.1.4.1.9.5.1.3.1.1.26' => 'moduleSerialNumberString'],
436 ],$session);
437 @module2serial{@$modules} = @$serials;
438 }
439 push (@port2serial,$module2serial{$_}) foreach @$port2module;
440 }
441 @if2serial{@$port2if} = @port2serial;
442 };
443 my $brocade = sub { # FOUNDRY-SN-SWITCH-GROUP-MIB
444 my ($port2if) = App::Netsync::SNMP::get1 ([['.1.3.6.1.4.1.1991.1.1.3.3.1.1.38' => 'snSwPortIfIndex']],$session);
445 my @port2serial;
446 {
447 my ($port2umi) = App::Netsync::SNMP::get1 ([['.1.3.6.1.4.1.1991.1.1.3.3.1.1.39' => 'snSwPortDescr']],$session);
448 my %module2serial;
449 {
450 my ($serials,$modules) = App::Netsync::SNMP::get1 ([['.1.3.6.1.4.1.1991.1.1.1.4.1.1.2' => 'snChasUnitSerNum']],$session); #XXX FOUNDRY-SN-AGENT-MIB?
451 @module2serial{@$modules} = @$serials;
452 }
453 foreach (@$port2umi) {
454 push (@port2serial,$module2serial{$+{'unit'}}) if m{^(?<unit>[0-9]+)(/[0-9]+)+$};
455 }
456 }
457 @if2serial{@$port2if} = @port2serial;
458 };
459 my %stack_vendors = (
460 'cisco' => $cisco,
461 'brocade' => $brocade,
462 'foundry' => $brocade,
463 'unsupported' => sub {
464 warn $vendor.' stacks are not supported.';
465 },
466 );
467 ($stack_vendors{$vendor} || $stack_vendors{'unsupported'})->();
468 }
469  
470 foreach my $if (keys %if2serial) { # Filter out interfaces without an associated serial.
471 $serial2if2ifName{$if2serial{$if}}{$if} = $if2ifName{$if} if defined $if2serial{$if};
472 }
473 }
474 }
475 return \%serial2if2ifName;
476 }
477  
478  
479  
480  
481 ################################################################################
482  
483  
484  
485  
486 sub recognize { # A recognizable node has a serial that netsync can retrieve.
487 my (@nodes) = @_;
488  
489 my $serial_count = 0;
490 foreach my $node (@nodes) {
491  
492 # Establish a connection to the node.
493 my ($session,$info) = App::Netsync::SNMP::Info $node->{'ip'};
494 if (defined $info) {
495 $node->{'session'} = $session;
496 $node->{'info'} = $info;
497 }
498 else { # Otherwise, consider it inactive.
499 note ($config{'NodeLog'},node_string ($node).' inactive');
500 say node_string ($node).' inactive' if $config{'Verbose'};
501 next;
502 }
503  
504 # Retrieve the serials of devices at the node.
505 my $serial2if2ifName = device_interfaces ($node->{'info'}->vendor,$node->{'session'});
506 if (defined $serial2if2ifName) {
507 my @serials = keys %$serial2if2ifName;
508 note ($config{'NodeLog'},node_string ($node).' '.join (' ',@serials));
509 node_initialize ($node,$serial2if2ifName);
510 $serial_count += @serials;
511 }
512 else { # Otherwise, consider the device unrecognized.
513 note ($config{'NodeLog'},node_string ($node).' unrecognized');
514 say node_string ($node).' unrecognized' if $config{'Verbose'};
515 next;
516 }
517  
518 # Show the user what's been found if necessary.
519 node_dump $node if $config{'Verbose'};
520 }
521 return $serial_count;
522 }
523  
524  
525 =head2 discover
526  
527 search the network for active nodes
528  
529 B<Arguments>
530  
531 I<[ ( $node_source [, $host_pattern ] ) ]>
532  
533 =over 3
534  
535 =item node_source
536  
537 where to get nodes from (DNS, STDIN, or a filename)
538  
539 default: DNS
540  
541 =item host_pattern
542  
543 a regular expression to match hostnames from the list of retrieved nodes
544  
545 default: [^.]+
546  
547 =back
548  
549 =cut
550  
551 sub discover {
552 warn 'too many arguments' if @_ > 2;
553 my ($node_source,$host_pattern) = @_;
554 $node_source //= 'DNS';
555 $host_pattern //= '[^.]+';
556  
557 my $nodes = {};
558  
559 unless ($config{'Quiet'}) {
560 print 'discovering';
561 print ' (using '.(($node_source eq 'DNS') ? 'DNS' : 'STDIN').')';
562 print '...';
563 print (($config{'Verbose'}) ? "\n" : (' 'x$config{'DeviceOrder'}).'0');
564 }
565  
566 my @zone;
567 { # Retrieve relevant nodes.
568 my %inputs = (
569 'DNS' => sub {
570 unless (defined $config{'DNS'}) {
571 warn 'DNS has not been configured.';
572 return undef;
573 }
574 if (defined $config{'DNS'}{'nameservers'}) {
575 $config{'DNS'}{'nameservers'} = (ref $config{'DNS'}{'nameservers'}) ?
576 $config{'DNS'}{'nameservers'} :
577 [$config{'DNS'}{'nameservers'}];
578 }
579 if (defined $config{'DNS'}{'searchlist'}) {
580 $config{'DNS'}{'searchlist'} = (ref $config{'DNS'}{'searchlist'}) ?
581 $config{'DNS'}{'searchlist'} :
582 [$config{'DNS'}{'searchlist'}];
583 }
584 my $resolver = Net::DNS::Resolver->new(%{$config{'DNS'}});
585 $resolver->print if $config{'Verbose'};
586 push (@zone,$_->string) foreach $resolver->axfr;
587 },
588 'default' => sub { @zone = split("\n",$node_source); },
589 );
590 ($inputs{$node_source} || $inputs{'default'})->();
591 }
592  
593 my ($skip_count,$device_count,$stack_count) = (0,0,0);
594 foreach (@zone) {
595 if (/^(?<host>$host_pattern)(\.(?:\S+\.)+\s+(?:\d+)\s+(?:\S+)\s+(?:A|AAAA))?\s+(?<ip>.+)$/) { #XXX Upgrade this to support a list of IP addresses (It currently supports dig output).
596 $nodes->{$+{'ip'}}{'ip'} = $+{'ip'};
597 my $node = $nodes->{$+{'ip'}};
598 $node->{'hostname'} = $+{'host'};
599 $node->{'RFC1035'} = $_;
600  
601 # Gather information about the node.
602 my $serial_count = recognize $node;
603 if ($serial_count < 1) { # Otherwise, skip it.
604 ++$skip_count;
605 delete $nodes->{$+{'ip'}};
606 }
607 else {
608 $device_count += $serial_count;
609 ++$stack_count if $serial_count > 1;
610  
611 # Show the user how many nodes have been discovered if necessary.
612 unless ($config{'Quiet'} or $config{'Verbose'}) {
613 print "\b"x$config{'DeviceOrder'};
614 printf ('%'.$config{'DeviceOrder'}.'d',scalar keys %$nodes);
615 }
616 }
617 }
618 }
619  
620 # Show the user what's been found if necessary.
621 unless ($config{'Quiet'}) {
622 my $node_count = scalar keys %$nodes;
623 print $node_count if $config{'Verbose'};
624 print ' node';
625 print 's' if $node_count != 1;
626 print ' ('.$skip_count.' skipped)' if $skip_count > 0;
627 print ', '.$device_count.' device';
628 print 's' if $device_count != 1;
629 if ($stack_count > 0) {
630 print ' ('.$stack_count.' stack';
631 print 's' if $stack_count != 1;
632 print ')';
633 }
634 print "\n";
635 }
636  
637 return $nodes;
638 }
639  
640  
641  
642  
643 ################################################################################
644  
645  
646  
647  
648 sub synchronize { # Use information in the databse to update discovered nodes.
649 warn 'too few arguments' if @_ < 4;
650 warn 'too many arguments' if @_ > 4;
651 my ($nodes,$identified,$auto_match,$rows) = @_;
652  
653 my $conflict_count = 0;
654 foreach my $row (@$rows) {
655 my $serial = uc $row->{$config{'DeviceField'}};
656 my $ifName = $row->{$config{'InterfaceField'}};
657  
658 # Identify the device indicated by the given database entry.
659 my $node = $identified->{$serial};
660 unless (defined $node) {
661 my $device = device_find ($nodes,$serial);
662 next unless defined $device; # Otherwise, skip to the next entry.
663 $identified->{$serial} = $node = $device->{'node'};
664 }
665  
666 # Identify the interface indicated by the given database entry.
667 my $device = $node->{'devices'}{$serial};
668 if ($auto_match and not defined $device->{'interfaces'}{$ifName}) {
669 foreach (sort keys %{$device->{'interfaces'}}) {
670 if (/[^0-9]$ifName$/) {
671 $ifName = $row->{$config{'InterfaceField'}} = $_;
672 last;
673 }
674 }
675 }
676  
677 { # Detect conflicts.
678 my $new_conflict_count = 0;
679 if (defined $device->{'interfaces'}{$ifName}) {
680 my $interface = $device->{'interfaces'}{$ifName};
681 if ($interface->{'identified'}) { # The database has a duplicate interface (only the first is used).
682 ++$new_conflict_count;
683 note ($config{'ConflictLog'},interface_string ($interface).' duplicate');
684 }
685 else {
686 $interface->{'identified'} = 1;
687 foreach my $field (@{$config{'InfoFields'}}) { # Grab data to be pushed to the device.
688 $interface->{'info'}{$field} = $row->{$field};
689 }
690  
691 # Show the user what's been found if necessary.
692 interface_dump $interface if $config{'Verbose'};
693 }
694 }
695 else { # An interface in the database could not be found on the indicated device.
696 ++$new_conflict_count;
697 note ($config{'ConflictLog'},device_string ($device).' '.$ifName.' mismatch');
698 }
699 $conflict_count += $new_conflict_count;
700 }
701 }
702 return $conflict_count;
703 }
704  
705 =head2 identify
706  
707 identify discovered nodes in a database
708  
709 B<Arguments>
710  
711 I<( \%nodes [, $data_source [, $auto_match ] ] )>
712  
713 =over 3
714  
715 =item nodes
716  
717 the discovered nodes to identify
718  
719 =item data_source
720  
721 the location of the database (DB or a filename)
722  
723 default: DB
724  
725 =item auto_match
726  
727 whether to enable interface automatching
728  
729 default: 0
730  
731 =back
732  
733 =cut
734  
735 sub identify {
736 warn 'too few arguments' if @_ < 1;
737 warn 'too many arguments' if @_ > 3;
738 my ($nodes,$data_source,$auto_match) = @_;
739 $data_source //= 'DB';
740 $auto_match //= 0;
741  
742 unless ($config{'Quiet'}) {
743 print 'identifying';
744 print ' (using '.$data_source.')...';
745 print (($config{'Verbose'}) ? "\n" : (' 'x$config{'DeviceOrder'}).'0');
746 }
747  
748 my @data;
749 { # Retrieve database.
750  
751 unless (defined $config{'DeviceField'} and
752 defined $config{'InterfaceField'} and
753 defined $config{'InfoFields'}) {
754 warn 'Database fields have not been configured.';
755 return undef;
756 }
757  
758 # Initialize output table headers.
759 my $fields = $config{'DeviceField'}.','.$config{'InterfaceField'};
760 $fields .= ','.join (',',sort @{$config{'InfoFields'}});
761  
762 my %inputs = (
763 'DB' => sub {
764 my %drivers = DBI->installed_drivers;
765 say $_ foreach values %drivers; exit; #XXX debug
766 unless (defined $config{'DB'}) {
767 warn 'A database has not been configured.';
768 return undef;
769 }
770  
771 # Connect to the database.
772 my $DSN = 'dbi:'.$config{'DBMS'};
773 $DSN .= ':host='.$config{'Server'};
774 $DSN .= ';port='.$config{'Port'};
775 $DSN .= ';database='.$config{'Database'};
776 my $db = DBI->connect($DSN,$config{'Username'},$config{'Password'},$config{'DB'});
777 my $query = $db->prepare('SELECT '.$fields.' FROM '.$config{'Table'});
778 $query->execute;
779 @data = @{$query->fetchall_arrayref({})};
780 $db->disconnect;
781 },
782 'default' => sub { # Read a CSV file specified with the database option (-d).
783 open (my $db,'<',$data_source);
784  
785 my $parser = Text::CSV->new;
786 chomp (my @fields = split (',',<$db>));
787 $parser->column_names(@fields);
788  
789 # Filter out fields that are not needed,
790 # and verify the presence of necessary fields.
791 my $removed_field_count = 0;
792 foreach my $i (keys @fields) {
793 $i -= $removed_field_count;
794 unless ($fields =~ /(^|,)$fields[$i](,|$)/) {
795 ++$removed_field_count;
796 splice (@fields,$i,1);
797 }
798 }
799 die 'incompatible database' unless @fields == scalar split (',',$fields);
800  
801 foreach my $row (@{$parser->getline_hr_all($db)}) {
802 my $entry = {};
803 $entry->{$_} = $row->{$_} foreach @fields;
804 push (@data,$entry);
805 }
806  
807 close $db;
808 },
809 );
810 ($inputs{$data_source} || $inputs{'default'})->();
811 }
812  
813 my $conflict_count = 0;
814 {
815 my %identified; # $identified{$serial} == $node
816  
817 ROW : foreach my $row (@data) {
818 my $valid = [
819 $config{'DeviceField'},
820 $config{'InterfaceField'},
821 ];
822 foreach my $field (@$valid) { # Verify necessary fields aren't empty.
823 next ROW unless defined $row->{$field} and $row->{$field} =~ /\S+/; # Otherwise, skip to the next entry.
824 }
825  
826 # Synchronize the entry with gathered info.
827 $conflict_count += synchronize ($nodes,\%identified,$auto_match,[$row]);
828  
829 # Show the user how many nodes have been identified if necessary.
830 unless ($config{'Quiet'} or $config{'Verbose'}) {
831 print "\b"x$config{'DeviceOrder'};
832 printf ('%'.$config{'DeviceOrder'}.'d',scalar keys %identified);
833 }
834 }
835  
836 # Show the user what's been found if necessary.
837 unless ($config{'Quiet'}) {
838 print scalar keys %identified if $config{'Verbose'};
839 print ' synchronized';
840 print ' ('.$conflict_count.' conflicts)' if $conflict_count > 0;
841 print "\n";
842 }
843 }
844  
845 # Search for network devices and interfaces that were not identified in the database.
846 foreach my $ip (sort keys %$nodes) {
847 my $node = $nodes->{$ip};
848 foreach my $serial (sort keys %{$node->{'devices'}}) {
849 my $device = $node->{'devices'}{$serial};
850 unless ($device->{'identified'}) {
851 note ($config{'ConflictLog'},device_string ($device).' unidentified');
852 next;
853 }
854 foreach my $ifName (sort keys %{$device->{'interfaces'}}) {
855 my $interface = $device->{'interfaces'}{$ifName};
856 unless ($interface->{'identified'}) {
857 note ($config{'ConflictLog'},interface_string ($interface).' unidentified');
858 next;
859 }
860 }
861 }
862 }
863 }
864  
865  
866  
867  
868 ################################################################################
869  
870  
871  
872  
873 =head2 update
874  
875 push information to interfaces
876  
877 B<Arguments>
878  
879 I<( \%nodes )>
880  
881 =over 3
882  
883 =item nodes
884  
885 the nodes to update
886  
887 =back
888  
889 B<Example>
890  
891 C<update $nodes;>
892  
893 Table
894 ---------------------------------------------------------
895 | DeviceField | InterfaceField | InfoFields... |
896 --------------------------------------------------------- =============
897 | (serial) | (ifName) |(interface-specific)| --> || SyncOID ||
898 | ... | =============
899 --------------------------------------------------------- (device)
900  
901 =cut
902  
903 sub update {
904 warn 'too few arguments' if @_ < 1;
905 warn 'too many arguments' if @_ > 1;
906 my ($nodes) = @_;
907  
908 unless ($config{'Quiet'}) {
909 print 'updating';
910 print ' (using '.$config{'SyncOID'}.')...';
911 print (($config{'Verbose'}) ? "\n" : (' 'x$config{'DeviceOrder'}).'0');
912 }
913  
914 my ($successful_update_count,$failed_update_count) = (0,0);
915 foreach my $ip (keys %$nodes) {
916 my $node = $nodes->{$ip};
917 foreach my $serial (keys %{$node->{'devices'}}) {
918 my $device = $node->{'devices'}{$serial};
919 next unless $device->{'identified'}; # Only update identified devices.
920  
921 foreach my $ifName (keys %{$device->{'interfaces'}}) {
922 my $interface = $device->{'interfaces'}{$ifName};
923 next unless $interface->{'identified'}; # Only update identified interfaces.
924  
925 # Format the info to be pushed.
926 my $update = '';
927 my $empty = 1;
928 foreach my $field (sort keys %{$interface->{'info'}}) {
929 $update .= "," unless $update eq '';
930 $update .= $field.':'.$interface->{'info'}{$field};
931 $empty = 0 if defined $interface->{'info'}{$field} and $interface->{'info'}{$field} =~ /[\S]+/;
932 }
933 $update = '' if $empty;
934  
935 my $note = interface_string ($interface).' ('.$interface->{'IID'}.')';
936 my $error = App::Netsync::SNMP::set ($config{'SyncOID'},$interface->{'IID'},$update,$node->{'session'});
937 unless ($error) { # Log a successful update.
938 $update =~ s/\n/,/g;
939 $update =~ s/\s+//g;
940 $update =~ s/:,/:(empty),/g;
941 note ($config{'UpdateLog'},$note.' '.$update);
942 ++$successful_update_count;
943  
944 unless ($config{'Quiet'}) {
945 if ($config{'Verbose'}) {
946 interface_dump $interface;
947 }
948 else {
949 print "\b"x$config{'DeviceOrder'};
950 printf ('%'.$config{'DeviceOrder'}.'d',$successful_update_count);
951 }
952 }
953 }
954 else { # Log a failed update.
955 note ($config{'UpdateLog'},$note.' error: '.$error);
956 ++$failed_update_count;
957  
958 if ($config{'Verbose'}) {
959 say interface_string ($interface).' failed';
960 say ((' 'x$config{'Indent'}).$error);
961 }
962 }
963 }
964 }
965 }
966  
967 # Show the user how many nodes have been updated if necessary.
968 unless ($config{'Quiet'}) {
969 print $successful_update_count if $config{'Verbose'};
970 print ' successful';
971 print ' ('.$failed_update_count.' failed)' if $failed_update_count > 0;
972 print "\n";
973 }
974 }
975  
976  
977 =head1 AUTHOR
978  
979 David Tucker, C<< <dmtucker at ucsc.edu> >>
980  
981 =head1 BUGS
982  
983 Please report any bugs or feature requests to C<bug-netsync at rt.cpan.org>, or through
984 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=App-Netsync>. I will be notified, and then you'll
985 automatically be notified of progress on your bug as I make changes.
986  
987 =head1 SUPPORT
988  
989 You can find documentation for this module with the perldoc command.
990  
991 perldoc App::Netsync
992  
993 You can also look for information at:
994  
995 =over 4
996  
997 =item * RT: CPAN's request tracker (report bugs here)
998  
999 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=App-Netsync>
1000  
1001 =item * AnnoCPAN: Annotated CPAN documentation
1002  
1003 L<http://annocpan.org/dist/App-Netsync>
1004  
1005 =item * CPAN Ratings
1006  
1007 L<http://cpanratings.perl.org/d/App-Netsync>
1008  
1009 =item * Search CPAN
1010  
1011 L<http://search.cpan.org/dist/App-Netsync/>
1012  
1013 =back
1014  
1015 =head1 LICENSE
1016  
1017 Copyright 2013 David Tucker.
1018  
1019 This program is free software; you can redistribute it and/or modify it
1020 under the terms of either: the GNU General Public License as published
1021 by the Free Software Foundation; or the Artistic License.
1022  
1023 See L<http://dev.perl.org/licenses/> for more information.
1024  
1025 =cut
1026  
1027  
1028 1;
« Netsync/SNMP.pm ↑ Summary