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

filter: Statementstmt 0.0% 0 / 318 Branchbran 0.0% 0 / 142 Conditioncond 0.0% 0 / 90 MC/DCmcdc 0.0% 0 / 54 Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 31 totaltotal 0.0% 0 / 674 CC 72 SCAR 34.0
CC
72
Cov
0%
_rule_is_cheap
72.0
_as_boolean
56.0
_group_with_refused_rule
56.0
CRAP 29.9
1 package App::Netdisco::Util::L3Domain;
2  
3 use strict;
4 use warnings;
5  
6 use Dancer qw/:syntax :script/;
7 use Dancer::Plugin::DBIC 'schema';
8 use App::Netdisco::Util::Permission 'acl_matches_only';
9 use NetAddr::IP::Lite;
10 use Scalar::Util 'blessed';
11  
12 use base 'Exporter';
13 our @EXPORT = ();
14 our @EXPORT_OK = qw/
15 recompute_l3_domains
16 l3_domain_recompute_needed
17 manual_l3_entries
18 manual_l3_members
19 l3_domain_evidence_sql
20 with_l3_domain_lock
21 results_span_domains
22 label_rows_by_domain
23 row_l3_domain
24 /;
25 our %EXPORT_TAGS = (all => \@EXPORT_OK);
26  
27 # 1728 is store_arp's class; the recompute is network-wide, so it takes one
28 # global key
29 my $L3_DOMAIN_LOCK_CLASS = 1729;
30  
31 =head1 NAME
32  
33 App::Netdisco::Util::L3Domain
34  
35 =head1 DESCRIPTION
36  
37 Helper subroutines for grouping VRFs into layer 3 domains.
38  
39 A domain is a set of VRF instances (one per device) that form one routing
40 network. Each VRF is keyed by the first evidence it has, in this order:
41  
42 =over 4
43  
44 =item 1. manual
45  
46 A C<vrf_domains> entry places it. Key C<manual:E<lt>domainE<gt>>.
47  
48 =item 2. L3 I-SID
49  
50 Key C<isid:E<lt>nE<gt>>. VRFs with the same L3 I-SID share a domain.
51  
52 =item 3. route targets
53  
54 Key C<rt:E<lt>importsE<gt>/E<lt>exportsE<gt>>. VRFs join only when their
55 de-duplicated, sorted import and export sets are identical and at least one is
56 non-empty. Hub, shared-services and extranet VRFs have different sets, so they
57 never bridge customers. An identical route distinguisher is not evidence: the
58 VRF Naming Inconsistencies report lists it as a hint.
59  
60 =item 4. name
61  
62 Key C<name:E<lt>vrfE<gt>>. The same name joins only VRFs that have neither an
63 I-SID nor route targets.
64  
65 =back
66  
67 The key is stored in C<l3_domain.inferred_name>. A domain's display C<name> is
68 its most common member VRF name (ties go to the alphabetically first), or the
69 configured name for a manual domain. The default table (C<vrf = ''>) is domain
70 0 and never has a key or member rows.
71  
72 The C<vrf_domains> setting is a flat list of entries, each C<< { domain,
73 device, vrf, join } >>:
74  
75 vrf_domains:
76 - domain: CUSTOMER-A
77 device: 192.0.2.1
78 vrf: blue
79 join: true # brings in every VRF sharing blue's key
80 - domain: CUSTOMER-A
81 device: 192.0.2.10
82 vrf: RED-LITE # a plain entry moves just this VRF
83 - domain: CUSTOMER-A
84 device: group:branch-ces # every router in a host_groups group
85 vrf: RED-LITE
86  
87 When entries place one VRF more than once, the most specific wins: an IP
88 entry, then a C<group:> entry, then a VRF brought in by another entry's
89 C<join: true>. So a VRF can be split out even from inside a joined domain or a
90 group. Within one level the alphabetically first domain name wins, with a
91 warning. A C<join: true> entry still brings in its VRF's partners when another
92 entry takes that VRF itself, so splitting a joined VRF out leaves its partners
93 where they were, unless entries place them too.
94  
95 A C<group:> device is matched live with C<acl_matches_only> at every
96 recompute. A group that holds a hostname or regular expression rule, directly
97 or through another C<group:>, is refused with a warning: the ACL matcher
98 answers such a rule with an uncached DNS lookup per device, and the recompute
99 runs on every discover, so a large group with slow DNS would add minutes to
100 each one. A cron rule is refused too, as it makes membership depend on the time
101 of day. Address, prefix, range, C<prop:>, C<tag:>, C<cf:>, C<group:> and
102 C<op:and> rules are allowed.
103  
104 The entries are read through one function, C<manual_l3_entries>, so a table
105 could supply them later without any other change to the recompute.
106  
107 There are no default exports, however the C<:all> tag will export all
108 subroutines.
109  
110 =head1 EXPORT_OK
111  
112 =head2 l3_domain_evidence_sql()
113  
114 Returns a SQL SELECT over C<device_vrf> (named VRFs only) yielding C<ip>,
115 C<vrf>, C<key>, C<reason> and C<display>. The C<key> is the first evidence the
116 VRF has: C<isid:E<lt>nE<gt>> for an L3 I-SID, then
117 C<rt:E<lt>importsE<gt>/E<lt>exportsE<gt>> when it has any route targets (each
118 set de-duplicated and sorted, ignoring NULL and empty elements, so order and
119 repeats do not matter), then
120 C<name:E<lt>vrfE<gt>>. A route-target key longer than 200 bytes is replaced by
121 C<rt:md5:E<lt>digestE<gt>> of its full text, because the key is in a unique
122 btree index that a few hundred route targets would overflow; equal sets still
123 give equal keys. C<reason> is the text stored on the member and
124 C<display> is the VRF name, for naming the domain.
125  
126 =head2 manual_l3_entries( [$schema] )
127  
128 Returns the entries of the C<vrf_domains> setting that are valid, as an
129 arrayref of C<< { domain, device, vrf, join } >>. Each entry is one future row
130 of a manual-domain table, which is why the setting is a flat list:
131  
132 vrf_domains:
133 - domain: CUSTOMER-A
134 device: 192.0.2.1 # a PE: bring its whole L3VPN domain
135 vrf: blue
136 join: true
137 - domain: CUSTOMER-A
138 device: 192.0.2.10 # the VRF-lite CE: move just this VRF
139 vrf: RED-LITE
140 - domain: CUSTOMER-A
141 device: group:branch-ces # every CE in a named group
142 vrf: RED-LITE
143  
144 C<device> is one full IP address of any interface of a known device (short
145 forms such as C<10.1> are refused), returned as the device's canonical IP (all
146 addresses are resolved in one query, by the rule C<get_device> uses), or exactly
147 one C<group:E<lt>nameE<gt>> from C<host_groups>, returned unchanged. C<join> is false unless set. An entry that
148 is malformed, names an unknown device, or names a group that is not cheap to
149 match is skipped with a warning that says what to change. A group is matched
150 against every candidate device on every recompute, so it (and every group it
151 reaches through C<group:>, negated or not) may hold only these rules: an
152 address, a prefix, a range, C<prop:>, C<tag:>, C<cf:>, C<group:> and
153 C<op:and>. A hostname or regular expression rule would cost a DNS lookup per
154 device, and a cron rule makes membership depend on the time of day, so a group
155 holding one is refused. A group whose C<group:> references form any cycle is
156 refused too. Returns C<[]> without querying when the setting is empty.
157  
158 =head2 manual_l3_members( $schema, \@entries, [$evidence] )
159  
160 Returns the (ip, vrf) pairs the entries place, as an arrayref of
161 C<< { ip, vrf, domain, level, direct } >>. An entry places the VRF on its
162 device (or on each device in its group that has that VRF in C<device_vrf>),
163 and a C<join> entry also places every VRF sharing the evidence key of the VRF
164 it placed, with C<direct> false. C<level> is C<ip>, C<group> or C<join>, the
165 order that decides a pair claimed twice (an IP entry, then a group entry, then
166 a joined VRF); within a level the alphabetically first domain wins, with a
167 warning. An entry whose VRF is not in C<device_vrf> places nothing and logs
168 nothing; it takes effect once the device reports that VRF.
169  
170 =head2 recompute_l3_domains( $schema )
171  
172 Brings the members of C<l3_domain_member> into line with C<device_vrf> and the
173 C<vrf_domains> setting. A VRF placed by a manual entry (see
174 C<manual_l3_members>) is a C<manual> member of the domain keyed
175 C<manual:E<lt>domainE<gt>>, named as configured. Every other VRF other than
176 the default table joins the domain of its evidence key (see
177 C<l3_domain_evidence_sql>), as an C<inferred> member. Domains are matched on
178 C<inferred_name>, which is unique; C<name> is for display and may repeat. An
179 inferred domain is named after its most common member VRF name, ties going to
180 the alphabetically first. The recompute owns the manual rows: it writes them to
181 match the entries, so removing an entry, or its VRF leaving C<device_vrf>,
182 returns the VRF to inference at the next recompute. Domains other than 0 left
183 with no members are deleted. A domain keeps its id across recomputes while its
184 key is in use.
185  
186 The recompute is one SQL statement, so the evidence query, the expensive
187 part, runs once and no temporary table is made. (Placing manual entries runs
188 the same query filtered to the VRF names or keys they name.) Only what changed
189 is written. An unchanged network and setting write nothing.
190  
191 Runs in one transaction under C<with_l3_domain_lock>. Returns the number of
192 member rows inserted plus deleted plus domains renamed or deleted, so 0 means everything
193 was already right. Discover calls it once per device, after the transaction
194 that refreshes C<device_vrf> commits, when C<l3_domain_recompute_needed> says so.
195  
196 =cut
197  
198 # COLLATE "C": byte order decides the key on every server, whatever its
199 # locale or glibc version
200 # NULL and empty elements are dropped so a VRF holding only those has no
201 # route targets, instead of every such VRF keying as 'rt:/'
202 my $_clean_set = sub {
203 my $column = shift;
204 return qq{ARRAY(SELECT DISTINCT x COLLATE "C" FROM unnest($column) x WHERE x IS NOT NULL AND x <> '' ORDER BY x COLLATE "C")};
205 };
206  
207 # A long key would overflow the btree behind the unique index on
208 # l3_domain.inferred_name (about 230 route targets), which would stop every
209 # recompute, so a key over 200 bytes is replaced by a digest of its full text.
210 # Each LATERAL step is fenced with OFFSET 0 so that its arrays are cleaned
211 # once per row, not once per use.
212 sub l3_domain_evidence_sql {
213 my $imports = $_clean_set->('d.rt_import');
214 my $exports = $_clean_set->('d.rt_export');
215  
216 return qq{SELECT d.ip, d.vrf,
217 CASE WHEN d.l3_isid IS NOT NULL THEN 'isid:' || d.l3_isid
218 WHEN t.has_rt THEN CASE WHEN octet_length(k.rtkey) > 200 THEN 'rt:md5:' || md5(k.rtkey) ELSE k.rtkey END
219 ELSE 'name:' || d.vrf END AS key,
220 CASE WHEN d.l3_isid IS NOT NULL THEN 'shared L3 I-SID ' || d.l3_isid
221 WHEN t.has_rt THEN 'same route targets import ' || t.imports || ' export ' || t.exports
222 ELSE 'same name ' || d.vrf END AS reason,
223 d.vrf AS display
224 FROM device_vrf d
225 CROSS JOIN LATERAL (SELECT $imports AS imp, $exports AS exp OFFSET 0) s
226 CROSS JOIN LATERAL (SELECT array_to_string(s.imp, ',') AS imports, array_to_string(s.exp, ',') AS exports,
227 coalesce(array_length(s.imp, 1), 0) + coalesce(array_length(s.exp, 1), 0) > 0 AS has_rt OFFSET 0) t
228 CROSS JOIN LATERAL (SELECT 'rt:' || t.imports || '/' || t.exports AS rtkey OFFSET 0) k
229 WHERE d.vrf <> ''};
230 }
231  
232  
233 sub _plain_text {
234 my $value = shift;
235 return (defined $value and !ref $value and $value ne '') ? $value : undef;
236 }
237  
238 sub _as_boolean {
239 my $value = shift;
240 return 0 if !defined $value or (!ref $value and $value eq '');
241 if (ref $value) {
242 return undef unless blessed $value and $value->isa('JSON::PP::Boolean');
243 return ($value ? 1 : 0);
244 }
245 return 1 if $value =~ m/^(?:1|true)$/i;
246 return 0 if $value =~ m/^(?:0|false)$/i;
247 return undef;
248 }
249  
250 # strict, because PostgreSQL's inet refuses the short forms NetAddr accepts
251 # ('10', '10.1') and one refusal would fail the whole batched lookup
252 sub _is_single_address {
253 my $text = shift;
254 my $octet = qr/(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])/;
255 return 1 if $text =~ m/^$octet(?:\.$octet){3}$/;
256 my ($head, $tail) = $text =~ m/^([0-9A-Fa-f:]+?:)([0-9]+(?:\.[0-9]+)+)$/ ? ($1, $2) : ($text, undef);
257 return 0 if defined $tail and $tail !~ m/^$octet(?:\.$octet){3}$/;
258 return 0 unless $head =~ m/^[0-9A-Fa-f:]+$/ and $text =~ m/:.*:/;
259 my $ip = NetAddr::IP::Lite->new($text) or return 0;
260 return ($ip->version == 6 and $ip->masklen == 128) ? 1 : 0;
261 }
262  
263 sub _describe_entry {
264 my $entry = shift;
265 my @fields = map {
266 my $value = ref $entry eq 'HASH' ? $entry->{$_} : undef;
267 "$_ '" . (!defined $value ? '' : ref $value ? 'a ' . lc ref($value) . ' reference' : $value) . "'";
268 } qw/domain device vrf/;
269 return 'vrf_domains entry (' . join(', ', @fields) . ')';
270 }
271  
272 # Rules a group may hold when vrf_domains uses it. The recompute matches the
273 # group against every candidate device on every discover, so a rule that makes
274 # check_acl resolve DNS (a hostname, or a regex) or read the clock (cron) is
275 # refused. Mirrors the order of tests in Permission.pm's check_acl.
276 sub _rule_is_cheap {
277 my $rule = shift;
278 return 0 if !defined $rule or ref $rule;
279 $rule =~ s/^!//;
280 return 1 if $rule eq 'op:and' or $rule =~ m/^(?:group|tag|cf):./;
281 return 1 if $rule =~ m/^([^:]+):/ and $1 !~ m/^[a-f0-9]+$/i;
282 return 1 if $rule =~ m/^\d{1,3}(?:\.\d{1,3}){3}-\d{1,3}$/;
283 return 1 if $rule =~ m/^[0-9a-f]*:[0-9a-f:]*:[0-9a-f]+-[0-9a-f]+$/i;
284 return 1 if $rule =~ m/^\d{1,3}(?:\.\d{1,3}){0,3}(?:\/\d{1,2})?$/;
285 return 1 if $rule =~ m/^[0-9a-f:.]*:[0-9a-f:.]*(?:\/\d{1,3})?$/i;
286 return 0;
287 }
288  
289 # the first group (named, or reached through group:) holding a refused rule,
290 # as (group, rule)
291 sub _group_with_refused_rule {
292 my ($name, $groups, $seen) = @_;
293 return () if $seen->{$name}++;
294 my $rules = $groups->{$name};
295 for my $rule (ref $rules eq 'ARRAY' ? @$rules : ($rules)) {
296 next unless defined $rule;
297 return ($name, $rule) unless _rule_is_cheap($rule);
298 next unless $rule =~ m/^!?group:(.+)$/;
299 my @found = _group_with_refused_rule($1, $groups, $seen);
300 return @found if @found;
301 }
302 return ();
303 }
304  
305 # returns the normalized entry, or the reason it cannot be used
306 sub _check_entry {
307 my $raw = shift;
308 return (undef, 'it is not a mapping. Write it as domain, device, vrf and an optional join')
309 if ref $raw ne 'HASH';
310  
311 for my $field (qw/domain vrf/) {
312 return (undef, "its $field is missing or empty. Set $field to a name")
313 unless defined _plain_text($raw->{$field});
314 return (undef, "$field 'default' is the default table, which cannot be a manual domain or VRF. Use another $field")
315 if lc $raw->{$field} eq 'default';
316 }
317  
318 my $device = _plain_text($raw->{device});
319 return (undef, 'its device must be one IP address or one group:<name>. Set device to the address of any interface of the device, or to a single group from host_groups')
320 unless defined $device and ($device =~ m/^group:\S+$/ or _is_single_address($device));
321  
322 my $join = _as_boolean($raw->{join});
323 return (undef, "its join must be true or false, not '" . (ref $raw->{join} ? 'a ' . lc ref($raw->{join}) . ' reference' : $raw->{join}) . "'. Set join to true or false, or remove it")
324 unless defined $join;
325  
326 return ({ domain => $raw->{domain}, device => $device, vrf => $raw->{vrf}, join => $join });
327 }
328  
329 # the path of group names that leads back to a group already on it, if any
330 sub _group_cycle {
331 my ($name, $groups, $path) = @_;
332 my ($at) = grep { $path->[$_] eq $name } 0 .. $#$path;
333 return [ @{$path}[$at .. $#$path], $name ] if defined $at;
334 my $rules = $groups->{$name};
335 for my $rule (ref $rules eq 'ARRAY' ? @$rules : ($rules)) {
336 next if !defined $rule or ref $rule or $rule !~ m/^!?group:(.+)$/;
337 my $cycle = _group_cycle($1, $groups, [ @$path, $name ]);
338 return $cycle if $cycle;
339 }
340 return undef;
341 }
342  
343 sub _entry_group_problem {
344 my $entry = shift;
345 return undef unless $entry->{device} =~ m/^group:(.+)$/;
346 my ($name, $groups) = ($1, setting('host_groups') || {});
347 my $cycle = _group_cycle($name, $groups, []);
348 return 'host_groups has a cycle (' . join(' -> ', map { "group:$_" } @$cycle)
349 . '), which would make the ACL matcher recurse until the worker runs out of memory. Remove one of the group: references'
350 if $cycle;
351 my ($holder, $rule) = _group_with_refused_rule($name, $groups, {});
352 return undef unless defined $holder;
353 my $shown = ref $rule ? 'a regular expression' : "'$rule'";
354 return "group:$holder has the rule $shown, which would need a DNS lookup (or the clock) for every device on every recompute. "
355 . "Rebuild that group from addresses, prefixes, ranges, prop:, tag:, cf: or group: rules";
356 }
357  
358 my $_resolve_sql = q{WITH req AS (SELECT r.input, r.input::inet AS addr FROM unnest(?::text[]) AS r(input))
359 SELECT DISTINCT ON (r.input) r.input, host(a.ip) AS ip
360 FROM req r
361 JOIN (
362 SELECT d.ip, d.alias, 0 AS rank FROM device_ip d JOIN req q ON q.addr = d.alias WHERE d.ip = d.alias
363 UNION ALL
364 SELECT d.ip, d.ip AS alias, 0 AS rank FROM device d JOIN req q ON q.addr = d.ip
365 UNION ALL
366 SELECT v.ip, v.alias, 1 AS rank FROM device_ip_resolved v JOIN req q ON q.addr = v.alias
367 ) a ON a.alias = r.addr
368 ORDER BY r.input, a.rank, a.ip};
369  
370 sub _resolve_addresses {
371 my ($schema, $addresses) = @_;
372 my %owner;
373 $schema->storage->dbh_do(sub {
374 my (undef, $dbh) = @_;
375 my $rows = $dbh->selectall_arrayref($_resolve_sql, { Slice => {} }, $addresses);
376 $owner{ $_->{input} } = $_->{ip} for @$rows;
377 });
378 return \%owner;
379 }
380  
381 sub manual_l3_entries {
382 my $schema = shift || schema(vars->{'tenant'});
383 my $setting = setting('vrf_domains');
384 return [] if !defined $setting or (ref $setting eq 'ARRAY' and !@$setting);
385  
386 unless (ref $setting eq 'ARRAY') {
387 warning 'vrf_domains is not a list, so every entry in it is ignored. Write it as a list of entries, each with domain, device, vrf and an optional join';
388 return [];
389 }
390  
391 my @valid;
392 for my $raw (@$setting) {
393 my ($entry, $problem) = _check_entry($raw);
394 $problem = _entry_group_problem($entry) if $entry and !$problem;
395 if ($problem) {
396 warning sprintf '%s is skipped: %s', _describe_entry($raw), $problem;
397 next;
398 }
399 push @valid, $entry;
400 }
401 return _resolve_entry_devices($schema, \@valid);
402 }
403  
404 sub _resolve_entry_devices {
405 my ($schema, $entries) = @_;
406 my %addresses = map { ($_->{device} => 1) } grep { $_->{device} !~ m/^group:/ } @$entries;
407 my $owner = %addresses ? _resolve_addresses($schema, [ sort keys %addresses ]) : {};
408  
409 my @resolved;
410 for my $entry (@$entries) {
411 if ($entry->{device} =~ m/^group:/) { push @resolved, $entry; next }
412 my $ip = $owner->{ $entry->{device} };
413 if (!defined $ip) {
414 warning sprintf '%s is skipped: no discovered device has the address %s. Use the address of an interface of a device Netdisco has discovered',
415 _describe_entry($entry), $entry->{device};
416 next;
417 }
418 push @resolved, { %$entry, device => $ip };
419 }
420 return \@resolved;
421 }
422  
423 my %LEVEL_RANK = (ip => 0, group => 1, join => 2);
424  
425 sub _vrf_rows {
426 my ($dbh, $entries, $evidence) = @_;
427 my %names = map { ($_->{vrf} => 1) } @$entries;
428 my $rows = $dbh->selectall_arrayref(
429 qq{SELECT host(e.ip) AS ip, e.vrf, e.key FROM $evidence e WHERE e.vrf = ANY(?)},
430 { Slice => {} }, [ sort keys %names ]);
431 my %by_vrf;
432 push @{ $by_vrf{ $_->{vrf} } }, $_ for @$rows;
433 return \%by_vrf;
434 }
435  
436 # the group names that exist, each warned about once per entry that cannot use it
437 sub _usable_group_entries {
438 my $entries = shift;
439 my $groups = setting('host_groups') || {};
440 my @usable;
441 for my $entry (grep { $_->{device} =~ m/^group:/ } @$entries) {
442 (my $name = $entry->{device}) =~ s/^group://;
443 my $rules = $groups->{$name};
444 if (ref $rules eq 'ARRAY' ? !@$rules : !defined $rules) {
445 warning sprintf '%s matches nothing: %s is not defined, or is empty, in host_groups. Define it there, or fix the name',
446 _describe_entry($entry), $entry->{device};
447 next;
448 }
449 push @usable, $entry;
450 }
451 return \@usable;
452 }
453  
454 sub _device_rows_by_ip {
455 my ($dbh, $ips) = @_;
456 return {} unless @$ips;
457 my $rows = $dbh->selectall_arrayref(q{SELECT * FROM device WHERE ip = ANY(?::inet[])}, { Slice => {} }, $ips);
458 return { map { ($_->{ip} => $_) } @$rows };
459 }
460  
461 # every (entry, row, level) the entries claim directly
462 sub _direct_claims {
463 my ($dbh, $entries, $by_vrf) = @_;
464 my @claims;
465  
466 for my $entry (grep { $_->{device} !~ m/^group:/ } @$entries) {
467 push @claims, map { { entry => $entry, row => $_, level => 'ip' } }
468 grep { $_->{ip} eq $entry->{device} } @{ $by_vrf->{ $entry->{vrf} } || [] };
469 }
470  
471 my $group_entries = _usable_group_entries($entries);
472 my %candidate_ips = map { ($_->{ip} => 1) } map { @{ $by_vrf->{ $_->{vrf} } || [] } } @$group_entries;
473 my $devices = _device_rows_by_ip($dbh, [ sort keys %candidate_ips ]);
474 for my $entry (@$group_entries) {
475 for my $row (@{ $by_vrf->{ $entry->{vrf} } || [] }) {
476 my $device = $devices->{ $row->{ip} } or next;
477 push @claims, { entry => $entry, row => $row, level => 'group' }
478 if acl_matches_only($device, $entry->{device});
479 }
480 }
481 return \@claims;
482 }
483  
484 sub _join_claims {
485 my ($dbh, $direct_claims, $evidence) = @_;
486 my %keys_for_entry;
487 for my $claim (grep { $_->{entry}{join} } @$direct_claims) {
488 $keys_for_entry{ $claim->{entry}{domain} }{ $claim->{row}{key} } = $claim->{entry};
489 }
490 return [] unless %keys_for_entry;
491  
492 my %keys = map { ($_ => 1) } map { keys %$_ } values %keys_for_entry;
493 my $rows = $dbh->selectall_arrayref(
494 qq{SELECT host(e.ip) AS ip, e.vrf, e.key FROM $evidence e WHERE e.key = ANY(?)},
495 { Slice => {} }, [ sort keys %keys ]);
496  
497 my @claims;
498 for my $row (@$rows) {
499 for my $domain (sort keys %keys_for_entry) {
500 my $entry = $keys_for_entry{$domain}{ $row->{key} } or next;
501 push @claims, { entry => $entry, row => $row, level => 'join' };
502 }
503 }
504 return \@claims;
505 }
506  
507 # one winner per (ip, vrf): the most specific level, then the first domain name
508 sub _pick_winners {
509 my $claims = shift;
510 my %by_pair;
511 push @{ $by_pair{ "$_->{row}{ip}\t$_->{row}{vrf}" } }, $_ for @$claims;
512  
513 my @members;
514 for my $pair (sort keys %by_pair) {
515 my @ranked = sort {
516 $LEVEL_RANK{ $a->{level} } <=> $LEVEL_RANK{ $b->{level} }
517 or $a->{entry}{domain} cmp $b->{entry}{domain}
518 } @{ $by_pair{$pair} };
519 my $winner = $ranked[0];
520 _warn_tied_domains($winner, \@ranked);
521 push @members, {
522 ip => $winner->{row}{ip}, vrf => $winner->{row}{vrf}, domain => $winner->{entry}{domain},
523 level => $winner->{level}, direct => ($winner->{level} eq 'join' ? 0 : 1),
524 };
525 }
526 return \@members;
527 }
528  
529 sub _warn_tied_domains {
530 my ($winner, $ranked) = @_;
531 my %tied = map { ($_->{entry}{domain} => 1) }
532 grep { $_->{level} eq $winner->{level} } @$ranked;
533 return unless keys %tied > 1;
534 warning sprintf 'vrf_domains puts VRF %s on %s in more than one domain at the same level (%s). Using %s, the first by name. Remove the entries for the others',
535 $winner->{row}{vrf}, $winner->{row}{ip}, join(', ', sort keys %tied), $winner->{entry}{domain};
536 }
537  
538 sub manual_l3_members {
539 my ($schema, $entries, $evidence) = @_;
540 return [] unless $entries and @$entries;
541 $evidence ||= '(' . l3_domain_evidence_sql() . ')';
542  
543 my $members = [];
544 $schema->storage->dbh_do(sub {
545 my (undef, $dbh) = @_;
546 my $direct = _direct_claims($dbh, $entries, _vrf_rows($dbh, $entries, $evidence));
547 $members = _pick_winners([ @$direct, @{ _join_claims($dbh, $direct, $evidence) } ]);
548 });
549 return $members;
550 }
551  
552 # One statement, not temporary tables plus separate writes: the temporary
553 # tables cost catalog rows and WAL on every recompute, unchanged ones included.
554 # That version (commit bb754463) was somewhat faster on fresh planner
555 # statistics; revisit it if the time this holds the lock becomes a bottleneck.
556 # Every CTE reads the snapshot taken before any of them writes, so a member is
557 # deleted, moved or added, never two of them, and a domain made here is named
558 # on insert, since no other CTE can see it through l3_domain. desired is read
559 # by several CTEs, so the server computes it, and the evidence, once.
560 # Four placeholders: ip, vrf, key and reason arrays of the manual set.
561 sub _sync_sql {
562 my $evidence = l3_domain_evidence_sql();
563 return qq{WITH man AS (SELECT * FROM unnest(?::inet[], ?::text[], ?::text[], ?::text[]) AS man(ip, vrf, key, reason)),
564 desired AS (
565 SELECT man.ip, man.vrf, man.key, man.reason, substr(man.key, 8) AS display, 'manual'::text AS source FROM man
566 UNION ALL
567 SELECT e.ip, e.vrf, e.key, e.reason, e.display, 'inferred'::text AS source FROM ($evidence) e
568 WHERE NOT EXISTS (SELECT 1 FROM man WHERE man.ip = e.ip AND man.vrf = e.vrf)),
569 named AS (
570 SELECT DISTINCT ON (d.key) d.key, CASE WHEN d.key LIKE 'manual:%' THEN min(d.display) ELSE d.vrf END AS name
571 FROM desired d GROUP BY d.key, d.vrf
572 ORDER BY d.key, count(*) DESC, d.vrf COLLATE "C"),
573 new_dom AS (
574 INSERT INTO l3_domain (name, inferred_name)
575 SELECT n.name, n.key FROM named n WHERE NOT EXISTS (SELECT 1 FROM l3_domain x WHERE x.inferred_name = n.key)
576 RETURNING id, inferred_name),
577 dom AS (
578 SELECT id, inferred_name FROM l3_domain WHERE inferred_name IS NOT NULL
579 UNION ALL SELECT id, inferred_name FROM new_dom),
580 target AS (
581 SELECT d.ip, d.vrf, m.id AS domain_id, d.reason, d.source FROM desired d JOIN dom m ON m.inferred_name = d.key),
582 gone AS (
583 DELETE FROM l3_domain_member m WHERE NOT EXISTS (SELECT 1 FROM desired d WHERE d.ip = m.ip AND d.vrf = m.vrf)
584 RETURNING 1),
585 moved AS (
586 UPDATE l3_domain_member m SET domain_id = t.domain_id, reason = t.reason, source = t.source
587 FROM target t WHERE t.ip = m.ip AND t.vrf = m.vrf
588 AND (t.domain_id <> m.domain_id OR t.reason IS DISTINCT FROM m.reason OR t.source <> m.source)
589 RETURNING 1),
590 added AS (
591 INSERT INTO l3_domain_member (ip, vrf, domain_id, reason, source)
592 SELECT t.ip, t.vrf, t.domain_id, t.reason, t.source FROM target t
593 WHERE NOT EXISTS (SELECT 1 FROM l3_domain_member m WHERE m.ip = t.ip AND m.vrf = t.vrf)
594 RETURNING 1),
595 renamed AS (
596 UPDATE l3_domain l SET name = n.name FROM named n
597 WHERE l.inferred_name = n.key AND l.name IS DISTINCT FROM n.name AND l.inferred_name NOT LIKE 'manual:%'
598 RETURNING 1),
599 emptied AS (
600 DELETE FROM l3_domain l WHERE l.id <> 0 AND NOT EXISTS (SELECT 1 FROM desired d WHERE d.key = l.inferred_name)
601 RETURNING 1)
602 SELECT (SELECT count(*) FROM gone) + 2 * (SELECT count(*) FROM moved)
603 + (SELECT count(*) FROM added) + (SELECT count(*) FROM renamed)
604 + (SELECT count(*) FROM emptied)};
605 }
606  
607 sub _manual_arrays {
608 my $members = shift;
609 my @keys = map { 'manual:' . $_->{domain} } @$members;
610 my @reasons = map { $_->{direct} ? "vrf_domains $_->{domain}" : "joined with $_->{domain} by vrf_domains" } @$members;
611 return ([ map { $_->{ip} } @$members ], [ map { $_->{vrf} } @$members ], \@keys, \@reasons);
612 }
613  
614 # a moved member counts twice, as the delete and insert it replaces
615 sub recompute_l3_domains {
616 my $schema = shift;
617 my $written = 0;
618  
619 with_l3_domain_lock($schema, sub {
620 $schema->storage->dbh_do(sub {
621 my (undef, $dbh) = @_;
622 my $members = manual_l3_members($schema, manual_l3_entries($schema));
623 ($written) = $dbh->selectrow_array(_sync_sql(), undef, _manual_arrays($members));
624 });
625 });
626  
627 return $written;
628 }
629  
630 =head2 l3_domain_recompute_needed( $schema, $device_changed, $by_arpnip? )
631  
632 True when a caller that has just refreshed one device's C<device_vrf> rows
633 should run C<recompute_l3_domains>, false when the recompute would find
634 nothing to change. It is true when any of these holds:
635  
636 =over 4
637  
638 =item 1. C<$device_changed> is true
639  
640 The caller found that the device's evidence changed (VRFs added or removed
641 count). No SQL runs.
642  
643 =item 2. C<vrf_domains> is set (not for arpnip)
644  
645 Any non-empty value, a malformed one included, so that the recompute warns
646 about it. Group membership can change with no device change, so a configured
647 site recomputes every time.
648  
649 =item 3. C<l3_domain_member> holds a C<manual> row (not for arpnip)
650  
651 This covers removing the last C<vrf_domains> entry.
652  
653 =item 4. a domain other than 0 has an C<inferred_name> with none of the key prefixes, or none
654  
655 A key from before the evidence keys, which was the bare VRF name, and a VRF
656 name may hold a C<:>. One cheap query re-keys it.
657  
658 =item 5. a named C<device_vrf> row has no C<l3_domain_member> row
659  
660 =item 6. an C<l3_domain_member> row has no C<device_vrf> row
661  
662 Both are primary-key anti-joins. They make a failed recompute that left rows
663 unplaced be retried by the next discover anywhere.
664  
665 =item 7. a domain other than 0 has no member
666  
667 Deleting a device removes its C<device_vrf> and member rows together, so
668 neither 5 nor 6 fires. The next discover anywhere then deletes the empty
669 domain. It is checked last, as the most expensive.
670  
671 =back
672  
673 Arpnip passes C<$by_arpnip>. It runs hourly, so it leaves 2 and 3 to the
674 device's daily discover, which picks up a C<vrf_domains> or group membership
675 change.
676  
677 An evidence change on another device is recomputed by that device's own
678 discover. A failed recompute after a pure route-target or I-SID change (no VRF
679 added or removed) stays stale until the next change. So does the display name of a domain that
680 lost members to a device delete but still has some (cosmetic).
681  
682 =cut
683  
684 # any non-empty value counts, whatever its type: a malformed one must reach the
685 # recompute, which warns that the setting is ignored
686 sub _vrf_domains_is_set {
687 my $entries = shift;
688 return 0 unless defined $entries;
689 return scalar(@$entries) ? 1 : 0 if ref $entries eq 'ARRAY';
690 return scalar(keys %$entries) ? 1 : 0 if ref $entries eq 'HASH';
691 return length($entries) ? 1 : 0;
692 }
693  
694 sub l3_domain_recompute_needed {
695 my ($schema, $device_changed, $by_arpnip) = @_;
696 return 1 if $device_changed;
697 return 1 if not $by_arpnip and _vrf_domains_is_set(setting('vrf_domains'));
698  
699 return $schema->storage->dbh_do(sub {
700 my (undef, $dbh) = @_;
701 $dbh->selectrow_array($_) and return 1 for _recompute_needed_sql($by_arpnip);
702 return 0;
703 });
704 }
705  
706 # cheapest first, and the caller stops at the first true
707 sub _recompute_needed_sql {
708 my $by_arpnip = shift;
709 return (
710 ($by_arpnip ? () : q{SELECT EXISTS (SELECT 1 FROM l3_domain_member WHERE source = 'manual')}),
711 q{SELECT EXISTS (SELECT 1 FROM l3_domain
712 WHERE id <> 0 AND (inferred_name IS NULL OR inferred_name !~ '^(isid|rt|name|manual):'))},
713 q{SELECT EXISTS (SELECT 1 FROM device_vrf d WHERE d.vrf <> ''
714 AND NOT EXISTS (SELECT 1 FROM l3_domain_member m WHERE m.ip = d.ip AND m.vrf = d.vrf))},
715 q{SELECT EXISTS (SELECT 1 FROM l3_domain_member m WHERE NOT EXISTS
716 (SELECT 1 FROM device_vrf d WHERE d.ip = m.ip AND d.vrf = m.vrf))},
717 q{SELECT EXISTS (SELECT 1 FROM l3_domain d WHERE d.id <> 0
718 AND NOT EXISTS (SELECT 1 FROM l3_domain_member m WHERE m.domain_id = d.id))},
719 );
720 }
721  
722 =head2 with_l3_domain_lock( $schema, \&code )
723  
724 Runs C<$code> inside a transaction (joining the caller's, if one is open)
725 after C<pg_advisory_xact_lock(1729, 0)>, and returns what it returns. Every
726 writer of C<l3_domain> or C<l3_domain_member> goes through this, so that it
727 does not interleave with a recompute.
728  
729 =cut
730  
731 sub with_l3_domain_lock {
732 my ($schema, $code) = @_;
733 return $schema->txn_do(sub {
734 $schema->storage->dbh_do(sub {
735 my (undef, $dbh) = @_;
736 $dbh->do('SELECT pg_advisory_xact_lock(?, ?)', undef, $L3_DOMAIN_LOCK_CLASS, 0);
737 });
738 return $code->();
739 });
740 }
741  
742 =head2 results_span_domains( \@rows )
743  
744 True when any of the report rows, each carrying C<vrf> (its domain's name), is
745 in a named domain; two domains always include one. Reports show a VRF column
746 only then, so that a network using only the default table sees the same report
747 as before.
748  
749 =cut
750  
751 sub results_span_domains {
752 my $rows = shift;
753 return scalar grep { ($_->{vrf} // '') ne '' } @$rows;
754 }
755  
756 =head2 label_rows_by_domain( \@rows, $multi_domain )
757  
758 Returns copies of the report rows shaped for a table rendered in the browser.
759 When C<$multi_domain> is true (any row in a named domain, see
760 C<results_span_domains>), C<vrf> is kept and the default table's empty name
761 reads "default". Otherwise every row is in the default table and C<vrf> is
762 dropped, so the page is the same as before domains.
763  
764 =cut
765  
766 sub label_rows_by_domain {
767 my ($rows, $multi_domain) = @_;
768 return [ map {
769 my %row = %$_;
770 if ($multi_domain) { $row{vrf} = 'default' if ($row{vrf} // '') eq '' }
771 else { delete $row{vrf} }
772 \%row;
773 } @$rows ];
774 }
775  
776 =head2 row_l3_domain( $row, $router )
777  
778 Returns C<< { id =E<gt> ..., name =E<gt> ... } >> for the L3 domain of a result
779 row with a C<vrf> column, or undef when the domain cannot be determined. C<$router>
780 is the address of the device that reported the row (undef when unknown). The
781 default table is domain 0 without a query. The query runs on the row's own
782 schema, so tenants work.
783  
784 =cut
785  
786 sub row_l3_domain {
787 my ($row, $router) = @_;
788 return { id => 0, name => '' } if $row->get_column('vrf') eq '';
789  
790 my $found;
791 $row->result_source->schema->storage->dbh_do(sub {
792 my (undef, $dbh) = @_;
793 $found = $dbh->selectrow_hashref(
794 'SELECT d.id, d.name FROM l3_domain d WHERE d.id = l3_domain_of(?, ?)',
795 undef, $router, $row->get_column('vrf'));
796 });
797 return $found ? { id => $found->{id}, name => $found->{name} } : undef;
798 }
799  
800 1;