blib/lib/App/Netdisco/Worker/Plugin/Discover/Neighbors.pm untested

filter: Statementstmt 0.0% 0 / 262 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 95 MC/DCmcdc 0.0% 0 / 55 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 526 CC 40 SCAR 62.3
CC
40
Cov
0%
store_neighbors
930.0
clear_neighbor_columns
56.0
set_manual_topology
30.0
CRAP 508.4
1 package App::Netdisco::Worker::Plugin::Discover::Neighbors;
2  
3 use Dancer ':syntax';
4 use App::Netdisco::Worker::Plugin;
5 use aliased 'App::Netdisco::Worker::Status';
6  
7 use App::Netdisco::Transport::SNMP ();
8 use App::Netdisco::Util::Device qw/get_device is_discoverable match_to_setting/;
9 use App::Netdisco::Util::Permission 'acl_matches';
10 use App::Netdisco::JobQueue 'jq_insert';
11 use Dancer::Plugin::DBIC 'schema';
12 use List::Util 'pairs';
13 use NetAddr::IP::Lite ();
14 use NetAddr::MAC;
15 use App::Netdisco::Util::SNMPText 'decode_snmp_text';
16 use App::Netdisco::Util::SNMP qw/walk_mark incomplete_walks_for incomplete_walk_message
17 incomplete_walk_level/;
18 use Try::Tiny;
19  
20 my @neighbor_walks = qw/has_topo c_if c_port c_id c_ip c_platform c_cap lldp_ipv6 interfaces/;
21  
22 =head2 discover_new_neighbors( )
23  
24 Given a Device database object, and a working SNMP connection, discover and
25 store the device's port neighbors information.
26  
27 Entries in the Topology database table will override any discovered device
28 port relationships.
29  
30 The Device database object can be a fresh L<DBIx::Class::Row> object which is
31 not yet stored to the database.
32  
33 Any discovered neighbor unknown to Netdisco will have a C<discover> job
34 immediately queued (subject to the filtering by the C<discover_*> settings).
35  
36 =cut
37  
38 register_worker({ phase => 'main', driver => 'snmp' }, sub {
39 my ($job, $workerconf) = @_;
40  
41 my $device = $job->device;
42 return unless $device->in_storage;
43  
44 if (acl_matches($device, 'skip_neighbors') or not setting('discover_neighbors')) {
45 clear_neighbor_columns($device, [], include_manual => 1);
46 return Status->info(
47 sprintf ' [%s] neigh - neighbor discovery is disabled on this device',
48 $device->ip);
49 }
50  
51 if (not setting('queue_neighbors')) {
52 config->{'discover_only'} = $device->ip;
53 debug sprintf ' [%s] neigh - neighbors will be discovered but not queued',
54 $device->ip;
55 }
56  
57 # do not remove. not used directly in this worker
58 # but is used in store_neighbors()
59 my $snmp = App::Netdisco::Transport::SNMP->reader_for($device)
60 or return Status->defer("discover failed: could not SNMP connect to $device");
61  
62 # store_neighbors() will update neighbors on ports, in the database
63 # might return empty set if config or other reasons deny neighbor discovery
64 my @incomplete = ();
65 my @to_discover = store_neighbors($device, \@incomplete);
66 my (%seen_id, %seen_ip) = ((), ());
67  
68 # only enqueue if device is not already discovered,
69 # discover_* config permits the discovery
70 foreach my $neighbor (@to_discover) {
71 my ($ip, $remote_id) = @$neighbor;
72 if ($seen_ip{ $ip }++) {
73 debug sprintf
74 ' queue - skip: IP %s is already queued from %s',
75 $ip, $device->ip;
76 next;
77 }
78  
79 if ($remote_id and $seen_id{ $remote_id }++) {
80 debug sprintf
81 ' queue - skip: %s with ID [%s] already queued from %s',
82 $ip, $remote_id, $device->ip;
83 next;
84 }
85  
86 my $newdev = get_device($ip);
87 next if $newdev->in_storage;
88  
89 # risk of things going wrong...?
90 # https://quickview.cloudapps.cisco.com/quickview/bug/CSCur12254
91  
92 jq_insert({
93 device => $ip,
94 action => 'discover',
95 ($remote_id ? (device_key => $remote_id) : ()),
96 });
97  
98 vars->{'queued'}->{$ip} = true;
99 debug sprintf ' [%s] queue - queued %s for discovery (ID: [%s])',
100 $device, $ip, ($remote_id || '');
101 }
102  
103 my $processed = sprintf ' [%s] neigh - processed %s neighbors',
104 $device->ip, scalar @to_discover;
105  
106 if (scalar @incomplete) {
107 my $message = incomplete_walk_message($device, 'neigh', @incomplete);
108 my $level = incomplete_walk_level(@incomplete);
109 warning $message;
110 return Status->$level("$processed; $message");
111 }
112  
113 return Status->info($processed);
114 });
115  
116 =head2 store_neighbors( $device, \@incomplete? )
117  
118 returns: C<@to_discover>
119  
120 Given a Device database object, and a working SNMP connection, discover and
121 store the device's port neighbors information.
122  
123 Entries in the Topology database table will override any discovered device
124 port relationships.
125  
126 The Device database object can be a fresh L<DBIx::Class::Row> object which is
127 not yet stored to the database.
128  
129 A list of discovered neighbors will be returned as [C<$ip>, C<$type>] tuples.
130  
131 Neighbor columns are cleared on the device's other ports, unless a neighbor
132 walk was incomplete. Those walk outcomes are pushed onto C<@incomplete> when
133 it is given.
134  
135 =cut
136  
137 sub store_neighbors {
138 my ($device, $incomplete) = @_;
139 $incomplete ||= [];
140 my @to_discover = ();
141 my %written = ();
142  
143 my $snmp = App::Netdisco::Transport::SNMP->reader_for($device)
144 or return (); # already checked!
145  
146 # first allow any manually configured topology to be set;
147 # this will also bust the cache in vars->{'device_ports'}
148 set_manual_topology($device);
149 my $walk_mark = walk_mark($snmp);
150  
151 if (!defined $snmp->has_topo) {
152 debug sprintf ' [%s] neigh - neighbor protocols are not enabled', $device->ip;
153 push @$incomplete, incomplete_walks_for($device, $snmp, $walk_mark, 'has_topo');
154 clear_neighbor_columns($device, []) if not scalar @$incomplete;
155 return @to_discover;
156 }
157  
158 my $interfaces = $snmp->interfaces;
159 my $c_if = $snmp->c_if;
160 my $c_port = $snmp->c_port;
161 my $c_id = $snmp->c_id;
162 my $c_platform = $snmp->c_platform;
163 my $c_cap = $snmp->c_cap;
164  
165 # cache the device ports to save hitting the database for many single rows
166 my $device_ports = vars->{'device_ports'}
167 || { map {($_->port => $_)} $device->ports->all };
168  
169 # v4 and v6 neighbor tables
170 my $c_ip = ($snmp->c_ip || {});
171 my %c_ipv6 = %{ ($snmp->can('hasLLDP') and $snmp->hasLLDP)
172 ? ($snmp->lldp_ipv6 || {}) : {} };
173  
174 # remove keys with undef values, as c_ip does
175 delete @c_ipv6{ grep { not defined $c_ipv6{$_} } keys %c_ipv6 };
176  
177 # neighbors found by a cut-short walk are still written, but a port missing
178 # from it may only have been missed, so nothing is cleared
179 push @$incomplete, incomplete_walks_for($device, $snmp, $walk_mark, @neighbor_walks);
180  
181 # allow fallback from v6 to try v4
182 my %success_with_index = ();
183  
184 NEIGHBOR: foreach my $pair ((sort { $a->key cmp $b->key } pairs %c_ipv6),
185 (sort { $a->key cmp $b->key } pairs %$c_ip)) {
186  
187 my ($entry, $c_ip_entry) = (@$pair);
188 next unless defined $entry and defined $c_ip_entry;
189  
190 if (!defined $c_if->{$entry} or !defined $interfaces->{ $c_if->{$entry} }) {
191 debug sprintf ' [%s] neigh - port for IID:%s not resolved, skipping',
192 $device->ip, $entry;
193 next NEIGHBOR;
194 }
195  
196 # WRT #475 this is SAFE because we check against known ports below
197 my $port = $interfaces->{ $c_if->{$entry} } or next NEIGHBOR;
198 my $portrow = $device_ports->{$port};
199  
200 if (!defined $portrow) {
201 debug sprintf ' [%s] neigh - local port %s already skipped, ignoring',
202 $device->ip, $port;
203 next NEIGHBOR;
204 }
205  
206 if (ref $c_ip_entry) {
207 debug sprintf ' [%s] neigh - port %s has multiple neighbors - skipping',
208 $device->ip, $port;
209 next NEIGHBOR;
210 }
211  
212 if ($portrow->manual_topo) {
213 debug sprintf ' [%s] neigh - %s has manually defined topology',
214 $device->ip, $port;
215 next NEIGHBOR;
216 }
217  
218 my $remote_ip = $c_ip_entry;
219 my $remote_port = undef;
220 my $remote_type = decode_snmp_text($c_platform->{$entry} || '', $device, "neighbor $port remote_type");
221 my $remote_id = decode_snmp_text($c_id->{$entry}, $device, "neighbor $port remote_id");
222 my $remote_cap = $c_cap->{$entry} || [];
223  
224 next NEIGHBOR unless $remote_ip;
225 my $r_netaddr = NetAddr::IP::Lite->new($remote_ip);
226  
227 if ($r_netaddr and ($r_netaddr->addr ne $remote_ip)) {
228 debug sprintf ' [%s] neigh - IP on %s: using %s as canonical form of %s',
229 $device->ip, $port, $r_netaddr->addr, $remote_ip;
230 $remote_ip = $r_netaddr->addr;
231 }
232  
233 if ($remote_ip and acl_matches($remote_ip, 'group:__LOCAL_ADDRESSES__')) {
234 debug sprintf ' [%s] neigh - %s is a non-unique local address - skipping',
235 $device->ip, $remote_ip;
236 next NEIGHBOR;
237 }
238  
239 if ($remote_type and match_to_setting($remote_type, 'neighbor_no_type')) {
240 debug sprintf ' [%s] neigh - %s has type %s matching neighbor_no_type - skipping',
241 $device->ip, $remote_ip, $remote_type;
242 next NEIGHBOR;
243 }
244  
245 # a bunch of heuristics to search known devices if we do not have a
246 # useable remote IP...
247  
248 if ((! $r_netaddr) or ($remote_ip eq '0.0.0.0') or
249 acl_matches($remote_ip, 'group:__LOOPBACK_ADDRESSES__')) {
250  
251 if ($remote_id) {
252 my $devices = schema('netdisco')->resultset('Device');
253  
254 debug sprintf
255 ' [%s] neigh - bad address %s on port %s, searching for %s instead',
256 $device->ip, $remote_ip, $port, $remote_id;
257 my $neigh_rs = $devices->search_rs({name => $remote_id});
258 my $neigh = ($neigh_rs->count == 1 ? $neigh_rs->first : undef);
259  
260 if (!defined $neigh and $neigh_rs->count) {
261 debug sprintf ' [%s] neigh - multiple devices claim to be %s (port %s) - skipping',
262 $device->ip, $remote_id, $port;
263 next NEIGHBOR;
264 }
265  
266 if (!defined $neigh) {
267 my $mac = NetAddr::MAC->new(mac => ($remote_id || ''));
268 if ($mac and not $mac->errstr) {
269 $neigh = $devices->single({mac => $mac->as_ieee});
270 }
271 }
272  
273 # some HP switches send 127.0.0.1 as remote_ip if no ip address
274 # on default vlan for HP switches remote_ip looks like
275 # "myswitchname(012345-012345)"
276 if (!defined $neigh) {
277 (my $tmpid = $remote_id) =~ s/.*\(([0-9a-f]{6})-([0-9a-f]{6})\).*/$1$2/;
278 my $mac = NetAddr::MAC->new(mac => ($tmpid || ''));
279 if ($mac and not $mac->errstr) {
280 debug sprintf
281 ' [%s] neigh - trying to find neighbor %s by MAC %s',
282 $device->ip, $remote_id, $mac->as_ieee;
283 $neigh = $devices->single({mac => $mac->as_ieee});
284 }
285 }
286  
287 if (!defined $neigh) {
288 (my $shortid = $remote_id) =~ s/\..*//;
289 $neigh = $devices->single({name => { -ilike => "${shortid}%" }});
290 }
291  
292 if ($neigh) {
293 $remote_ip = $neigh->ip;
294 debug sprintf ' [%s] neigh - found %s with IP %s',
295 $device->ip, $remote_id, $remote_ip;
296 }
297 else {
298 debug sprintf ' [%s] neigh - could not find %s, skipping',
299 $device->ip, $remote_id;
300 next NEIGHBOR;
301 }
302 }
303 else {
304 debug sprintf ' [%s] neigh - skipping unuseable address %s on port %s',
305 $device->ip, $remote_ip, $port;
306 next NEIGHBOR;
307 }
308 }
309  
310 if (++$success_with_index{$entry} > 1) {
311 debug sprintf ' [%s] neigh - port for IID:%s already got a neighbor, skipping',
312 $device->ip, $entry;
313 next NEIGHBOR;
314 }
315  
316 # what we came here to do.... discover the neighbor
317 debug sprintf ' [%s] neigh - %s with ID [%s] on %s',
318 $device->ip, $remote_ip, ($remote_id || ''), $port;
319  
320 if (is_discoverable($remote_ip, $remote_type, $remote_cap)) {
321 push @to_discover, [$remote_ip, $remote_id];
322 }
323 else {
324 debug sprintf
325 ' [%s] neigh - skip: %s of type [%s] excluded by discover_* config',
326 $device->ip, $remote_ip, ($remote_type || '');
327 }
328  
329 $remote_port = $c_port->{$entry};
330 if (defined $remote_port) {
331 # clean weird characters
332 $remote_port =~ s/[^\d\s\/\.,"()\w:-]+//gi;
333 }
334 else {
335 debug sprintf ' [%s] neigh - no remote port found for port %s at %s',
336 $device->ip, $port, $remote_ip;
337 }
338  
339 $portrow = $portrow->update({
340 remote_ip => $remote_ip,
341 remote_port => $remote_port,
342 remote_type => $remote_type,
343 remote_id => $remote_id,
344 is_uplink => \"true",
345 manual_topo => \"false",
346 })->discard_changes();
347 $written{$port} = 1;
348  
349 # update master of our aggregate to be a neighbor of
350 # the master on our peer device (a lot of iffs to get there...).
351 # & cannot use ->neighbor prefetch because this is the port insert!
352 if (defined $portrow->slave_of) {
353  
354 my $peer_device = get_device($remote_ip);
355 my $master = schema('netdisco')->resultset('DevicePort')->single({
356 ip => $device->ip,
357 port => $portrow->slave_of
358 });
359  
360 if ($peer_device and $peer_device->in_storage and $master
361 and not ($portrow->is_master or defined $master->slave_of)) {
362  
363 my $peer_port = schema('netdisco')->resultset('DevicePort')->single({
364 ip => $peer_device->ip,
365 port => $portrow->remote_port,
366 });
367  
368 $master->update({
369 remote_ip => ($peer_device->ip || $remote_ip),
370 remote_port => ($peer_port ? $peer_port->slave_of : undef ),
371 remote_type => undef,
372 remote_id => undef,
373 is_uplink => \"true",
374 is_master => \"true",
375 manual_topo => \"false",
376 });
377 $written{ $master->port } = 1;
378 }
379 }
380 }
381  
382 clear_neighbor_columns($device, [keys %written]) if not scalar @$incomplete;
383 return @to_discover;
384 }
385  
386 =head2 clear_neighbor_columns( $device, \@keep_ports, %opt )
387  
388 Clears C<remote_*> and C<is_uplink> on the device's ports not named in
389 C<@keep_ports>, in one statement that writes only rows not already clear.
390 Ports with C<manual_topo> are left alone, unless C<include_manual> is set,
391 when they are cleared too and C<manual_topo> is set false.
392  
393 =cut
394  
395 sub clear_neighbor_columns {
396 my ($device, $keep_ports, %opt) = @_;
397  
398 my %where = (
399 ip => $device->ip,
400 (scalar @$keep_ports ? (port => { -not_in => [sort @$keep_ports] }) : ()),
401 ($opt{include_manual} ? () : (-not_bool => 'manual_topo')),
402 -or => [
403 (map {{ $_ => { '!=' => undef } }} qw/remote_ip remote_port remote_type remote_id/),
404 { is_uplink => \'IS TRUE' },
405 ($opt{include_manual} ? { -bool => 'manual_topo' } : ()),
406 ],
407 );
408  
409 my $cleared = schema('netdisco')->resultset('DevicePort')->search(\%where)->update({
410 remote_ip => undef,
411 remote_port => undef,
412 remote_type => undef,
413 remote_id => undef,
414 is_uplink => undef,
415 ($opt{include_manual} ? (manual_topo => \'false') : ()),
416 });
417  
418 # later workers read remote_ip from the cached rows; store_column leaves
419 # them clean, so no later update writes these columns again
420 my %keep = map {($_ => 1)} @$keep_ports;
421 foreach my $row (values %{ vars->{'device_ports'} || {} }) {
422 next if $keep{ $row->port } or ($row->manual_topo and not $opt{include_manual});
423 $row->store_column($_ => undef) for qw/remote_ip remote_port remote_type remote_id is_uplink/;
424 $row->store_column(manual_topo => 0) if $opt{include_manual};
425 }
426  
427 return $cleared;
428 }
429  
430 # take data from the topology table and update remote_ip and remote_port
431 # in the devices table. only use root_ips and skip any bad topo entries.
432 sub set_manual_topology {
433 my $device = shift;
434 my $snmp = App::Netdisco::Transport::SNMP->reader_for($device) or return;
435  
436 # clear outdated manual topology links
437 my $old_links = schema('netdisco')->resultset('Topology')->search({
438 -or => [
439 { dev1 => $device->ip,
440 port1 => { '-not_in' => $device->ports->get_column('port')->as_query } },
441 { dev2 => $device->ip,
442 port2 => { '-not_in' => $device->ports->get_column('port')->as_query } },
443 ],
444 })->delete;
445 debug sprintf ' [%s] neigh - removed %d outdated manual topology links',
446 $device->ip, $old_links;
447  
448 my $topo_links = schema('netdisco')->resultset('Topology')
449 ->search({-or => [dev1 => $device->ip, dev2 => $device->ip]});
450 debug sprintf ' [%s] neigh - setting manual topology links', $device->ip;
451  
452 my %manual = ();
453 # each link commits on its own: holding one link's port rows while
454 # locking the next could deadlock with that peer's own discover
455 while (my $link = $topo_links->next) {
456 # could fail for broken topo, but we ignore to try the rest
457 try {
458 # recorded only once the link's transaction commits, since a
459 # failed right side rolls the left side back
460 my @own_ports = ();
461 schema('netdisco')->txn_do(sub {
462 # only work on root_ips
463 my $left = get_device($link->dev1);
464 my $right = get_device($link->dev2);
465  
466 # skip bad entries
467 return unless ($left->in_storage and $right->in_storage);
468  
469 $left->ports
470 ->single({port => $link->port1})
471 ->update({
472 remote_ip => $right->ip,
473 remote_port => $link->port2,
474 remote_type => undef,
475 remote_id => undef,
476 is_uplink => \"true",
477 manual_topo => \"true",
478 });
479 push @own_ports, $link->port1 if $left->ip eq $device->ip;
480  
481 $right->ports
482 ->single({port => $link->port2})
483 ->update({
484 remote_ip => $left->ip,
485 remote_port => $link->port1,
486 remote_type => undef,
487 remote_id => undef,
488 is_uplink => \"true",
489 manual_topo => \"true",
490 });
491 push @own_ports, $link->port2 if $right->ip eq $device->ip;
492 });
493 $manual{$_} = 1 for @own_ports;
494 };
495 }
496  
497 # clear manual topology flags left from links that are gone
498 schema('netdisco')->resultset('DevicePort')->search({
499 ip => $device->ip,
500 -bool => 'manual_topo',
501 (scalar keys %manual ? (port => { -not_in => [sort keys %manual] }) : ()),
502 })->update({manual_topo => \'false'});
503  
504 # bust the cache after updating manual topology.
505 vars->{'device_ports'} = { map {($_->port => $_)}
506 $device->ports(undef, {prefetch => 'properties'})->reset->all };
507 }
508  
509 true;