| 1 | package App::Netdisco::Util::Node; | ||
| 2 | |||
| 3 | use Dancer qw/:syntax :script/; | ||
| 4 | use Dancer::Plugin::DBIC 'schema'; | ||
| 5 | |||
| 6 | use NetAddr::MAC; | ||
| 7 | use App::Netdisco::Util::Permission qw/acl_matches acl_matches_only/; | ||
| 8 | use App::Netdisco::Util::VRF qw/vrf_collection_enabled vrf_skip_test/; | ||
| 9 | use App::Netdisco::Util::L3Domain qw/recompute_l3_domains l3_domain_recompute_needed/; | ||
| 10 | use Try::Tiny; | ||
| 11 | |||
| 12 | use base 'Exporter'; | ||
| 13 | our @EXPORT = (); | ||
| 14 | our @EXPORT_OK = qw/ | ||
| 15 | check_mac | ||
| 16 | is_nbtstatable | ||
| 17 | memoize_arp | ||
| 18 | store_arp | ||
| 19 | retire_unvouched_arps | ||
| 20 | record_cli_vrfs | ||
| 21 | /; | ||
| 22 | our %EXPORT_TAGS = (all => \@EXPORT_OK); | ||
| 23 | |||
| 24 | # excluding the target row from the retire in store_arp lets two pollers that | ||
| 25 | # report one IP under different MACs deadlock, so each entry first takes this | ||
| 26 | # class keyed by its host IP; retire_unvouched_arps takes it keyed by the router | ||
| 27 | # IP, and a key shared by a host and a router only serializes the two. Class | ||
| 28 | # 1729 (key 0) guards L3 domain writes: see App::Netdisco::Util::L3Domain | ||
| 29 | my $ARP_LOCK_CLASS = 1728; | ||
| 30 | |||
| 31 | =head1 NAME | ||
| 32 | |||
| 33 | App::Netdisco::Util::Node | ||
| 34 | |||
| 35 | =head1 DESCRIPTION | ||
| 36 | |||
| 37 | A set of helper subroutines to support parts of the Netdisco application. | ||
| 38 | |||
| 39 | There are no default exports, however the C<:all> tag will export all | ||
| 40 | subroutines. | ||
| 41 | |||
| 42 | =head1 EXPORT_OK | ||
| 43 | |||
| 44 | =head2 check_mac( $node, $device?, $port_macs? ) | ||
| 45 | |||
| 46 | Given a MAC address, perform various sanity checks which need to be done | ||
| 47 | before writing an ARP/Neighbor entry to the database storage. | ||
| 48 | |||
| 49 | Returns false, and might log a debug level message, if the checks fail. | ||
| 50 | |||
| 51 | Returns a true value (the MAC address in IEEE format) if these checks pass: | ||
| 52 | |||
| 53 | =over 4 | ||
| 54 | |||
| 55 | =item * | ||
| 56 | |||
| 57 | MAC address is well-formed (according to common formats) | ||
| 58 | |||
| 59 | =item * | ||
| 60 | |||
| 61 | MAC address is not all-zero, broadcast, CLIP, VRRP or HSRP | ||
| 62 | |||
| 63 | =back | ||
| 64 | |||
| 65 | Optionally pass a Device instance or IP to use in logging. | ||
| 66 | |||
| 67 | Optionally pass a cached set of Device port MAC addresses as the third | ||
| 68 | argument, in which case an additional check is added: | ||
| 69 | |||
| 70 | =over 4 | ||
| 71 | |||
| 72 | =item * | ||
| 73 | |||
| 74 | MAC address does not belong to an interface on any known Device | ||
| 75 | |||
| 76 | =back | ||
| 77 | |||
| 78 | =cut | ||
| 79 | |||
| 80 | sub check_mac { | ||
| 81 | my ($node, $device, $port_macs) = @_; | ||
| 82 | return 0 if !$node; | ||
| 83 | |||
| 84 | my $mac = NetAddr::MAC->new(mac => ($node || '')); | ||
| 85 | my $devip = ($device ? (ref $device ? $device->ip : $device) : ''); | ||
| 86 | $port_macs ||= {}; | ||
| 87 | |||
| 88 | # incomplete MAC addresses (BayRS frame relay DLCI, etc) | ||
| 89 | if (!defined $mac or $mac->errstr) { | ||
| 90 | debug sprintf ' [%s] check_mac - mac [%s] malformed - skipping', | ||
| 91 | $devip, $node; | ||
| 92 | return 0; | ||
| 93 | } | ||
| 94 | else { | ||
| 95 | # lower case, hex, colon delimited, 8-bit groups | ||
| 96 | $node = lc $mac->as_ieee; | ||
| 97 | } | ||
| 98 | |||
| 99 | # broadcast MAC addresses | ||
| 100 | return 0 if $mac->is_broadcast; | ||
| 101 | |||
| 102 | # all-zero MAC addresses | ||
| 103 | return 0 if $node eq '00:00:00:00:00:00'; | ||
| 104 | |||
| 105 | # CLIP | ||
| 106 | return 0 if $node eq '00:00:00:00:00:01'; | ||
| 107 | |||
| 108 | # multicast | ||
| 109 | if ($mac->is_multicast and not $mac->is_msnlb) { | ||
| 110 | debug sprintf ' [%s] check_mac - multicast mac [%s] - skipping', | ||
| 111 | $devip, $node; | ||
| 112 | return 0; | ||
| 113 | } | ||
| 114 | |||
| 115 | # VRRP | ||
| 116 | if ($mac->is_vrrp) { | ||
| 117 | debug sprintf ' [%s] check_mac - VRRP mac [%s] - skipping', | ||
| 118 | $devip, $node; | ||
| 119 | return 0; | ||
| 120 | } | ||
| 121 | |||
| 122 | # HSRP | ||
| 123 | if ($mac->is_hsrp or $mac->is_hsrp2) { | ||
| 124 | debug sprintf ' [%s] check_mac - HSRP mac [%s] - skipping', | ||
| 125 | $devip, $node; | ||
| 126 | return 0; | ||
| 127 | } | ||
| 128 | |||
| 129 | # device's own MACs | ||
| 130 | if ($port_macs and exists $port_macs->{$node}) { | ||
| 131 | debug sprintf ' [%s] check_mac - mac [%s] is device port - skipping', | ||
| 132 | $devip, $node; | ||
| 133 | return 0; | ||
| 134 | } | ||
| 135 | |||
| 136 | return $node; | ||
| 137 | } | ||
| 138 | |||
| 139 | =head2 is_nbtstatable( $ip ) | ||
| 140 | |||
| 141 | Given an IP address, returns C<true> if Netdisco on this host is permitted by | ||
| 142 | the local configuration to nbtstat the node. | ||
| 143 | |||
| 144 | The configuration items C<nbtstat_no> and C<nbtstat_only> are checked | ||
| 145 | against the given IP. | ||
| 146 | |||
| 147 | Returns false if the host is not permitted to nbtstat the target node. | ||
| 148 | |||
| 149 | =cut | ||
| 150 | |||
| 151 | sub is_nbtstatable { | ||
| 152 | my $ip = shift; | ||
| 153 | |||
| 154 | return if acl_matches($ip, 'nbtstat_no'); | ||
| 155 | |||
| 156 | return unless acl_matches_only($ip, 'nbtstat_only'); | ||
| 157 | |||
| 158 | return 1; | ||
| 159 | } | ||
| 160 | |||
| 161 | =head2 memoize_arp ( \%host ) | ||
| 162 | |||
| 163 | Returns a unique string to memoize the arp entry, using node or mac keys, | ||
| 164 | the ip key and the VRF (an absent VRF reads as the empty string). | ||
| 165 | |||
| 166 | =cut | ||
| 167 | |||
| 168 | sub memoize_arp { | ||
| 169 | my $host = shift or return; | ||
| 170 | no warnings 'uninitialized'; | ||
| 171 | return join chr(28), map {$host->{$_}} | ||
| 172 | (($host->{node} ? 'node' : 'mac'), 'ip', 'vrf'); | ||
| 173 | } | ||
| 174 | |||
| 175 | =head2 store_arp( \%host, $now?, $device_ip ) | ||
| 176 | |||
| 177 | Stores a new entry to the C<node_ip> table with the given MAC, IP (v4 or v6) | ||
| 178 | and DNS host name. Host details are provided in a Hash ref: | ||
| 179 | |||
| 180 | { | ||
| 181 | ip => '192.0.2.1', | ||
| 182 | node => '00:11:22:33:44:55', | ||
| 183 | dns => 'myhost.example.com', | ||
| 184 | } | ||
| 185 | |||
| 186 | The C<dns> entry is optional. The update will mark other active entries for | ||
| 187 | this IP in the same VRF as no longer C<active>. | ||
| 188 | |||
| 189 | Optionally a literal string can be passed in the second argument for the | ||
| 190 | C<time_last> timestamp, otherwise the current timestamp (C<LOCALTIMESTAMP>) is used. | ||
| 191 | |||
| 192 | On which L3 devices an arp entry was found is tracked in the | ||
| 193 | C<seen_on_router_first> and C<seen_on_router_last> fields of the C<node_ip>. | ||
| 194 | They contain a timestamp for the time window each router this entry was ever | ||
| 195 | found on. | ||
| 196 | |||
| 197 | =cut | ||
| 198 | |||
| 199 | sub store_arp { | ||
| 200 | my ($hash_ref, $now, $device_ip) = @_; | ||
| 201 | $now ||= 'LOCALTIMESTAMP'; | ||
| 202 | my $ip = $hash_ref->{'ip'}; | ||
| 203 | my $mac = NetAddr::MAC->new(mac => ($hash_ref->{'node'} || $hash_ref->{'mac'} || '')); | ||
| 204 | my $vrf = $hash_ref->{'vrf'} // ''; | ||
| 205 | my $name = $hash_ref->{'dns'}; | ||
| 206 | |||
| 207 | return if !defined $mac or $mac->errstr; | ||
| 208 | warning sprintf 'store_arp - deprecated usage, should be store_arp($hash_ref, $now, $device_ip)' unless $device_ip; | ||
| 209 | debug sprintf 'store_arp - device %s mac %s ip %s vrf "%s"', $device_ip // "n/a", $mac->as_ieee, $ip, $vrf; | ||
| 210 | |||
| 211 | my @key = ($mac->as_ieee, $ip, $vrf); | ||
| 212 | my ($upsert, @upsert_binds) = _arp_upsert_sql($now, $device_ip); | ||
| 213 | |||
| 214 | schema(vars->{'tenant'})->txn_do(sub { | ||
| 215 | schema(vars->{'tenant'})->storage->dbh_do(sub { | ||
| 216 | my (undef, $dbh) = @_; | ||
| 217 | $dbh->do('SELECT pg_advisory_xact_lock(?, hashtext(host(?::inet)))', | ||
| 218 | undef, $ARP_LOCK_CLASS, $ip); | ||
| 219 | $dbh->do('UPDATE node_ip SET active = false' | ||
| 220 | .' WHERE ip = ? AND vrf = ? AND active AND mac <> ?', undef, $ip, $vrf, $key[0]); | ||
| 221 | $dbh->do($upsert, undef, @key, $name, @upsert_binds); | ||
| 222 | }); | ||
| 223 | }); | ||
| 224 | } | ||
| 225 | |||
| 226 | # time_last never moves back: an older overlapping job of one router must not | ||
| 227 | # lower a row the newer job's retire_unvouched_arps will test | ||
| 228 | # without a router (the deprecated sshcollector call) the maps and router_last | ||
| 229 | # are left alone | ||
| 230 | sub _arp_upsert_sql { | ||
| 231 | my ($now, $device_ip) = @_; | ||
| 232 | my $new_map = ($device_ip ? "jsonb_build_object(?::text, $now)" : q{'{}'::jsonb}); | ||
| 233 | my $router_column = ($device_ip ? ', router_last' : ''); | ||
| 234 | my $router_value = ($device_ip ? ', ?::inet' : ''); | ||
| 235 | my $sql = qq{INSERT INTO node_ip AS n | ||
| 236 | (mac, ip, vrf, dns, active, time_first, time_last, seen_on_router_first, seen_on_router_last$router_column) | ||
| 237 | VALUES (?, ?, ?, ?, true, $now, $now, $new_map, $new_map$router_value) | ||
| 238 | ON CONFLICT (mac, ip, vrf) DO UPDATE | ||
| 239 | SET active = true, dns = EXCLUDED.dns, time_last = GREATEST(n.time_last, EXCLUDED.time_last)}; | ||
| 240 | return $sql unless $device_ip; | ||
| 241 | |||
| 242 | $sql .= qq{, | ||
| 243 | router_last = EXCLUDED.router_last, | ||
| 244 | seen_on_router_last = jsonb_set(n.seen_on_router_last, ?, to_jsonb($now)), | ||
| 245 | seen_on_router_first = CASE WHEN (n.seen_on_router_first -> ?) IS NOT NULL | ||
| 246 | THEN n.seen_on_router_first | ||
| 247 | ELSE jsonb_set(n.seen_on_router_first, ?, to_jsonb($now)) | ||
| 248 | END}; | ||
| 249 | my $path = "{$device_ip}"; | ||
| 250 | return ($sql, $device_ip, $device_ip, $device_ip, $path, $device_ip, $path); | ||
| 251 | } | ||
| 252 | |||
| 253 | =head2 record_cli_vrfs( $device, \%vrf_read, $list_complete, $now ) | ||
| 254 | |||
| 255 | Records in C<device_vrf> each named VRF a CLI collector read (the keys of | ||
| 256 | C<\%vrf_read>, netdisco names, C<''> skipped), so that it gets an L3 domain | ||
| 257 | when SNMP::Info does not list it. Rows are C<listed_by> C<cli> and written | ||
| 258 | only when new, so a row discover wrote keeps its facts. When the collector's | ||
| 259 | list was whole, the device's C<cli> rows for VRFs it no longer read are | ||
| 260 | deleted; other rows never are. Domains are recomputed when anything changed. | ||
| 261 | Returns the number of rows inserted or deleted. | ||
| 262 | |||
| 263 | =cut | ||
| 264 | |||
| 265 | my @cli_vrf_insert_only = qw/kind rd rt_import rt_export l3_isid listed_by complete last_discover/; | ||
| 266 | |||
| 267 | sub record_cli_vrfs { | ||
| 268 | my ($device, $vrf_read, $list_complete, $now) = @_; | ||
| 269 | my @names = sort grep { length } keys %{ $vrf_read || {} }; | ||
| 270 | my $rs = schema(vars->{'tenant'})->resultset('DeviceVrf'); | ||
| 271 | |||
| 272 | my $changed = (not @names) ? 0 : $rs->upsert([ map {{ | ||
| 273 | ip => $device->ip, vrf => $_, kind => 'vrf', rd => undef, rt_import => [], rt_export => [], | ||
| 274 | l3_isid => undef, listed_by => 'cli', complete => ($vrf_read->{$_} ? 1 : 0), | ||
| 275 | last_discover => \$now, | ||
| 276 | }} @names ], { insert_only => [@cli_vrf_insert_only] }); | ||
| 277 | |||
| 278 | if ($list_complete) { | ||
| 279 | my $gone = $rs->search({ ip => $device->ip, listed_by => 'cli', | ||
| 280 | vrf => { -not_in => \@names } })->delete; | ||
| 281 | $changed += ($gone eq '0E0' ? 0 : $gone); | ||
| 282 | } | ||
| 283 | my $schema = schema(vars->{'tenant'}); | ||
| 284 | try { recompute_l3_domains($schema) if l3_domain_recompute_needed($schema, $changed, 'by arpnip') } | ||
| 285 | catch { warning sprintf ' [%s] arpnip - L3 domain recompute failed, the next discover that finds a change retries: %s', | ||
| 286 | $device->ip, $_ }; | ||
| 287 | return $changed; | ||
| 288 | } | ||
| 289 | |||
| 290 | =head2 retire_unvouched_arps( $device, $now, \%vrf_read?, $vrf_list_complete? ) | ||
| 291 | |||
| 292 | After a complete arpnip of C<$device>, deactivates the active C<node_ip> rows | ||
| 293 | this router was the last to report (C<router_last>) and did not report in | ||
| 294 | this run (C<time_last> before C<$now>, the timestamp given to C<store_arp>). | ||
| 295 | Rows another router reported since name that router and stay; rows with no | ||
| 296 | C<router_last> are never matched. | ||
| 297 | |||
| 298 | With VRF collection off for the device (C<vrf_collection_enabled> in | ||
| 299 | L<App::Netdisco::Util::VRF>), only rows in named VRFs are retired, never the | ||
| 300 | default table. With it on and C<%vrf_read> (VRF name to 1 for a complete | ||
| 301 | read, 0 for an incomplete one), the VRFs retired are those read whole, those | ||
| 302 | skipped (C<vrf_no_devicevrfs>), and, only when C<$vrf_list_complete> is 1, those the | ||
| 303 | run did not read at all; a VRF read short is never retired. With it on but no | ||
| 304 | C<%vrf_read> (an SSH or offline job, or a class without VRF support) nothing | ||
| 305 | is retired. | ||
| 306 | |||
| 307 | Returns the number of rows deactivated. | ||
| 308 | |||
| 309 | =cut | ||
| 310 | |||
| 311 | sub retire_unvouched_arps { | ||
| 312 | my ($device, $now, $vrf_read, $vrf_list_complete) = @_; | ||
| 313 | my $router = $device->ip; | ||
| 314 | my $collecting = vrf_collection_enabled($device); | ||
| 315 | |||
| 316 | if ($collecting and not $vrf_read) { | ||
| 317 | debug sprintf ' [%s] arpnip - no VRF reads with store_vrfs on, retired nothing', | ||
| 318 | $router; | ||
| 319 | return 0; | ||
| 320 | } | ||
| 321 | |||
| 322 | my $where = "WHERE active AND router_last = ? AND time_last < $now"; | ||
| 323 | my ($retired, @vrfs) = (0); | ||
| 324 | |||
| 325 | schema(vars->{'tenant'})->txn_do(sub { | ||
| 326 | schema(vars->{'tenant'})->storage->dbh_do(sub { | ||
| 327 | my (undef, $dbh) = @_; | ||
| 328 | $dbh->do('SELECT pg_advisory_xact_lock(?, hashtext(host(?::inet)))', | ||
| 329 | undef, $ARP_LOCK_CLASS, $router); | ||
| 330 | |||
| 331 | if (not $collecting) { | ||
| 332 | $retired = $dbh->do("UPDATE node_ip SET active = false $where AND vrf <> ''", | ||
| 333 | undef, $router); | ||
| 334 | return; | ||
| 335 | } | ||
| 336 | ($retired, @vrfs) = _retire_read_vrfs($dbh, $device, $where, $vrf_read, $vrf_list_complete); | ||
| 337 | }); | ||
| 338 | }); | ||
| 339 | |||
| 340 | $retired = 0 + ($retired || 0); | ||
| 341 | debug sprintf ' [%s] arpnip - retired %d ARP entries no longer reported, in %s', | ||
| 342 | $router, $retired, | ||
| 343 | ($collecting ? ('VRFs ['. (join ', ', map { qq{"$_"} } @vrfs) .']') : 'named VRFs'); | ||
| 344 | return $retired; | ||
| 345 | } | ||
| 346 | |||
| 347 | # idx_node_ip_vrf_named_active covers named-VRF rows only, so those | ||
| 348 | # statements repeat its predicate and the default table gets its own UPDATE | ||
| 349 | sub _retire_read_vrfs { | ||
| 350 | my ($dbh, $device, $where, $vrf_read, $vrf_list_complete) = @_; | ||
| 351 | my ($router, $retired) = ($device->ip, 0); | ||
| 352 | |||
| 353 | my $stored = $dbh->selectcol_arrayref( | ||
| 354 | "SELECT DISTINCT vrf FROM node_ip $where AND vrf <> ''", undef, $router); | ||
| 355 | my $skipped = vrf_skip_test($device); | ||
| 356 | my @named = grep { _vrf_unvouched($skipped, $_, $vrf_read, $vrf_list_complete) } | ||
| 357 | sort @$stored; | ||
| 358 | $retired += $dbh->do("UPDATE node_ip SET active = false $where" | ||
| 359 | ." AND vrf <> '' AND vrf = ANY(?::text[])", undef, $router, \@named) | ||
| 360 | if scalar @named; | ||
| 361 | |||
| 362 | my $default = _vrf_unvouched($skipped, '', $vrf_read, $vrf_list_complete); | ||
| 363 | $retired += $dbh->do("UPDATE node_ip SET active = false $where AND vrf = ''", | ||
| 364 | undef, $router) if $default; | ||
| 365 | |||
| 366 | return ($retired, ($default ? '' : ()), @named); | ||
| 367 | } | ||
| 368 | |||
| 369 | sub _vrf_unvouched { | ||
| 370 | my ($skipped, $vrf, $vrf_read, $vrf_list_complete) = @_; | ||
| 371 | return $vrf_read->{$vrf} if exists $vrf_read->{$vrf}; | ||
| 372 | return 1 if $skipped->($vrf); | ||
| 373 | return ($vrf_list_complete ? 1 : 0); | ||
| 374 | } | ||
| 375 | |||
| 376 | 1; |