blib/lib/App/Netdisco/DB/ResultSet/DevicePort.pm untested

filter: Statementstmt 0.0% 0 / 157 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 18 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 254 CC 16 SCAR 23.6
CC
16
Cov
0%
retire_ports
30.0
delete
20.0
_is_port_subset
12.0
CRAP 10.6
1 package App::Netdisco::DB::ResultSet::DevicePort;
2 use base 'App::Netdisco::DB::ResultSet';
3  
4 use strict;
5 use warnings;
6  
7 use Try::Tiny;
8 require Dancer::Logger;
9  
10 __PACKAGE__->load_components(qw/
11 +App::Netdisco::DB::ExplicitLocking
12 /);
13  
14 =head1 ADDITIONAL METHODS
15  
16 =head2 with_times
17  
18 This is a modifier for any C<search()> (including the helpers below) which
19 will add the following additional synthesized columns to the result set:
20  
21 =over 4
22  
23 =item lastchange_stamp
24  
25 =back
26  
27 =cut
28  
29 sub with_times {
30 my ($rs, $cond, $attrs) = @_;
31  
32 return $rs
33 ->search_rs($cond, $attrs)
34 ->search({},
35 {
36 '+columns' => { lastchange_stamp =>
37 \("to_char(device.last_discover - (device.uptime - me.lastchange) / 100 * interval '1 second', "
38 ."'YYYY-MM-DD HH24:MI:SS')") },
39 join => 'device',
40 });
41 }
42  
43 =head2 with_is_free
44  
45 This is a modifier for any C<search()> (including the helpers below) which
46 will add the following additional synthesized columns to the result set:
47  
48 =over 4
49  
50 =item is_free
51  
52 =back
53  
54 In the C<$cond> hash (the first parameter) pass in the C<age_num> which must
55 be an integer, and the C<age_unit> which must be a string of either C<days>,
56 C<weeks>, C<months> or C<years>.
57  
58 =cut
59  
60 sub with_is_free {
61 my ($rs, $cond, $attrs) = @_;
62  
63 my $interval = (delete $cond->{age_num}) .' '. (delete $cond->{age_unit});
64  
65 return $rs
66 ->search_rs($cond, $attrs)
67 ->search({},
68 {
69 '+columns' => { is_free =>
70 # NOTE this query is in `git grep 'THREE PLACES'`
71 \["me.up_admin = 'up' AND me.up != 'up' AND "
72 ."(me.type IS NULL OR me.type !~* '^(53|ieee8023adLag|propVirtual|l2vlan|l3ipvlan|135|136|137)\$') AND "
73 ."((age(LOCALTIMESTAMP, to_timestamp(extract(epoch from device.last_discover) - (device.uptime/100))::timestamp) < ?::interval "
74 ."AND (last_node.time_last IS NULL OR age(LOCALTIMESTAMP, last_node.time_last) > ?::interval)) "
75 ."OR age(LOCALTIMESTAMP, to_timestamp(extract(epoch from device.last_discover) - (device.uptime - me.lastchange)/100)::timestamp) > ?::interval)",
76 [{} => $interval],[ {} => $interval],[ {} => $interval]] },
77 join => [qw/device last_node/],
78 });
79 }
80  
81 =head2 only_free_ports
82  
83 This is a modifier for any C<search()> (including the helpers below) which
84 will restrict results based on whether the port is considered "free".
85  
86 In the C<$cond> hash (the first parameter) pass in the C<age_num> which must
87 be an integer, and the C<age_unit> which must be a string of either C<days>,
88 C<weeks>, C<months> or C<years>.
89  
90 =cut
91  
92 sub only_free_ports {
93 my ($rs, $cond, $attrs) = @_;
94  
95 my $interval = (delete $cond->{age_num}) .' '. (delete $cond->{age_unit});
96  
97 return $rs
98 ->search_rs($cond, $attrs)
99 ->search(
100 {
101 # NOTE this query is in `git grep 'THREE PLACES'`
102 'me.up_admin' => 'up',
103 'me.up' => { '!=' => 'up' },
104 'me.type' => [ '-or' =>
105 { '=' => undef },
106 { '!~*' => '^(53|ieee8023adLag|propVirtual|l2vlan|l3ipvlan|135|136|137)$' },
107 ],
108 -or => [
109 -and => [
110 \["age(LOCALTIMESTAMP, to_timestamp(extract(epoch from device.last_discover) - (device.uptime/100))::timestamp) < ?::interval",
111 [{} => $interval]],
112 -or => [
113 'last_node.time_last' => undef,
114 \["age(LOCALTIMESTAMP, last_node.time_last) > ?::interval", [{} => $interval]],
115 ]
116 ],
117 \["age(LOCALTIMESTAMP, to_timestamp(extract(epoch from device.last_discover) - (device.uptime - me.lastchange)/100)::timestamp) > ?::interval",
118 [{} => $interval]],
119 ],
120 },{ join => [qw/device last_node/] },
121 );
122 }
123  
124 =head2 with_properties
125  
126 This is a modifier for any C<search()> which
127 will add the following additional synthesized columns to the result set:
128  
129 =over 4
130  
131 =item error_disable_cause
132  
133 =item remote_is_discoverable (boolean)
134  
135 =item remote_is_wap (boolean)
136  
137 =item remote_is_phone (boolean)
138  
139 =item remote_dns
140  
141 =item ifindex
142  
143 =back
144  
145 =cut
146  
147 sub with_properties {
148 my ($rs, $cond, $attrs) = @_;
149  
150 return $rs
151 ->search_rs($cond, $attrs)
152 ->search({},
153 {
154 '+select' => [qw/
155 properties.error_disable_cause
156 properties.remote_is_discoverable
157 properties.remote_is_wap
158 properties.remote_is_phone
159 properties.remote_dns
160 properties.ifindex
161 properties.pae_authconfig_port_control
162 properties.pae_authconfig_state
163 properties.pae_authconfig_port_status
164 properties.pae_authsess_user
165 properties.pae_authsess_mab
166 properties.pae_last_eapol_frame_source
167 /],
168 '+as' => [qw/
169 error_disable_cause
170 remote_is_discoverable remote_is_wap remote_is_phone remote_dns
171 ifindex
172 pae_authconfig_port_control
173 pae_authconfig_state
174 pae_authconfig_port_status
175 pae_authsess_user
176 pae_authsess_mab
177 pae_last_eapol_frame_source
178 /],
179 join => 'properties',
180 });
181 }
182  
183 =head2 with_remote_inventory
184  
185 This is a modifier for any C<search()> which
186 will add the following additional synthesized columns to the result set:
187  
188 =over 4
189  
190 =item remote_vendor
191  
192 =item remote_model
193  
194 =item remote_os_ver
195  
196 =item remote_serial
197  
198 =back
199  
200 =cut
201  
202 sub with_remote_inventory {
203 my ($rs, $cond, $attrs) = @_;
204  
205 return $rs
206 ->search_rs($cond, $attrs)
207 ->search({},
208 {
209 '+select' => [qw/
210 properties.remote_vendor
211 properties.remote_model
212 properties.remote_os_ver
213 properties.remote_serial
214 /],
215 '+as' => [qw/
216 remote_vendor remote_model remote_os_ver remote_serial
217 /],
218 join => 'properties',
219 });
220 }
221  
222 =head2 with_vlan_count
223  
224 This is a modifier for any C<search()> (including the helpers below) which
225 will add the following additional synthesized columns to the result set:
226  
227 =over 4
228  
229 =item vlan_count
230  
231 =back
232  
233 =cut
234  
235 sub with_vlan_count {
236 my ($rs, $cond, $attrs) = @_;
237  
238 return $rs
239 ->search_rs($cond, $attrs)
240 ->search({},
241 {
242 '+columns' => { vlan_count =>
243 $rs->result_source->schema->resultset('DevicePortVlan')
244 ->search(
245 {
246 'dpv.ip' => { -ident => 'me.ip' },
247 'dpv.port' => { -ident => 'me.port' },
248 },
249 { alias => 'dpv' }
250 )->count_rs->as_query
251 },
252 });
253 }
254  
255 =head1 SPECIAL METHODS
256  
257 =head2 delete( \%options? )
258  
259 Overrides the built-in L<DBIx::Class> delete method to more efficiently
260 handle the removal or archiving of nodes. Deleting a subset of a device's
261 ports removes per-port rows and nodes only for those ports.
262  
263 =cut
264  
265 sub _plural { (shift || 0) == 1 ? 'entry' : 'entries' };
266  
267 # Equal counts mean $ports is the whole device, which keeps the cheaper SQL.
268 sub _is_port_subset {
269 my ($self, $ports, @switches) = @_;
270 return 0 unless scalar @switches;
271 my $device_ports = $self->result_source->schema->resultset('DevicePort')
272 ->search({ ip => { '-in' => \@switches } });
273 return ($ports->count < $device_ports->count) ? 1 : 0;
274 }
275  
276 sub _node_condition {
277 my ($self, $ports, $is_subset, @switches) = @_;
278  
279 # A whole-device delete keeps the plain switch list: a multi-device delete
280 # would otherwise bind every port name of every device.
281 return { switch => { '-in' => \@switches } } unless $is_subset;
282  
283 my %ports_of;
284 push @{ $ports_of{ $_->{ip} } }, $_->{port}
285 for $ports->search(undef, {
286 columns => [qw/ip port/],
287 result_class => 'DBIx::Class::ResultClass::HashRefInflator',
288 })->all;
289  
290 # counts and rows are separate statements, so a concurrent commit can leave
291 # no rows here. Those ports are gone and own no nodes to delete; an empty
292 # -or would drop the WHERE, and the switch list would take every node
293 # on the switch, which is the whole-device bug this method avoids.
294 return { switch => { '-in' => [] } } unless %ports_of;
295  
296 return { -or => [ map { { switch => $_, port => { '-in' => $ports_of{$_} } } }
297 sort keys %ports_of ] };
298 }
299  
300 sub delete {
301 my $self = shift;
302  
303 my $schema = $self->result_source->schema;
304 my $ports = $self->search(undef, { columns => 'ip' });
305  
306 my $ip = undef;
307 {
308 no autovivification;
309 try { $ip ||= ${ $ports->{attrs}->{where}->{ip}->{'-in'} }->[1]->[1] };
310 try { $ip ||= $ports->{attrs}->{where}->{'me.ip'} };
311 }
312 $ip ||= 'netdisco';
313  
314 # a list, not a subquery: given a subquery, PostgreSQL can merge-join
315 # through node_pkey instead of using the (switch, port, active) index
316 my @switches = $ports->search(undef, { columns => ['ip'], distinct => 1 })
317 ->get_column('ip')->all;
318 my $is_subset = $self->_is_port_subset($ports, @switches);
319  
320 my $per_port = $is_subset
321 ? do {
322 my ($sql, @bind) = @{ ${ $self->search(undef, { columns => [qw/ip port/] })->as_query } };
323 \[ '(ip, port) IN ' . $sql, @bind ];
324 }
325 : { '-in' => $ports->as_query };
326  
327 foreach my $set (qw/
328 DevicePortPower
329 DevicePortProperties
330 DevicePortSsid
331 DevicePortVlan
332 DevicePortWireless
333 /) {
334 my $gone = $schema->resultset($set)->search(
335 ($is_subset ? $per_port : { ip => $per_port }),
336 )->delete;
337  
338 Dancer::Logger::debug( sprintf( ' [%s] db/ports - removed %d port %s from %s',
339 $ip, $gone, _plural($gone), $set ) ) if defined Dancer::Logger::logger();
340 }
341  
342 $schema->resultset('Node')->search(
343 $self->_node_condition($ports, $is_subset, @switches),
344 )->delete(@_);
345  
346 # now let DBIC do its thing
347 return $self->next::method();
348 }
349  
350 =head2 retire_ports( $device_ip, \@port_names, $mode )
351  
352 Removes the named ports of one device and returns the number of C<device_port>
353 rows removed. An empty list returns 0 and sends no SQL. Both modes delete the
354 rows of the five per-port tables, then the C<device_port> rows, in one
355 transaction and with plain statements, bypassing the C<delete> override above.
356 Nodes and C<device_port_log> are always kept. C<$mode> is one of:
357  
358 =over 4
359  
360 =item vanished
361  
362 The ports are no longer reported by the device.
363  
364 =item ignored
365  
366 The ports are excluded by configuration.
367  
368 =back
369  
370 =cut
371  
372 my @PER_PORT_SETS = qw/
373 DevicePortPower
374 DevicePortProperties
375 DevicePortSsid
376 DevicePortVlan
377 DevicePortWireless
378 /;
379  
380 sub retire_ports {
381 my ($self, $device_ip, $port_names, $mode) = @_;
382  
383 die sprintf("retire_ports: mode must be 'vanished' or 'ignored', got '%s'\n",
384 (defined $mode ? $mode : 'undef'))
385 unless defined $mode and $mode =~ m/^(?:vanished|ignored)$/;
386 return 0 unless $port_names and scalar @$port_names;
387  
388 return $mode eq 'vanished'
389 ? $self->_retire_vanished_ports($device_ip, $port_names)
390 : $self->_retire_ignored_ports($device_ip, $port_names);
391 }
392  
393 sub _retire_vanished_ports {
394 my ($self, $device_ip, $port_names) = @_;
395 return $self->_delete_ports_and_properties($device_ip, $port_names);
396 }
397  
398 sub _retire_ignored_ports {
399 my ($self, $device_ip, $port_names) = @_;
400 return $self->_delete_ports_and_properties($device_ip, $port_names);
401 }
402  
403 sub _delete_ports_and_properties {
404 my ($self, $device_ip, $port_names) = @_;
405  
406 my $schema = $self->result_source->schema;
407 my @tables = ((map { $schema->source($_)->name } @PER_PORT_SETS),
408 $self->result_source->name);
409 my $removed = 0;
410  
411 $schema->txn_do(sub {
412 foreach my $table (@tables) {
413 my $gone = $schema->storage->dbh_do(sub {
414 my ($storage, $dbh) = @_;
415 $dbh->do("DELETE FROM $table WHERE ip = ? AND port = ANY(?)",
416 undef, $device_ip, $port_names);
417 });
418 $removed = $gone + 0 if $table eq $tables[-1];
419 }
420 });
421  
422 return $removed;
423 }
424  
425 =head2 order_by_port_name( \@also )
426  
427 Orders the result set the way the device Ports tab shows ports, using the
428 C<port_sortkey()> function schema version 99 installs. Any further ordering
429 terms are passed in C<\@also> and applied after the port name.
430  
431 The port key has to lead, and this method exists so that only one place knows
432 it. When connected nodes are prefetched, DBIC collapses the rows into objects
433 and needs each port's rows contiguous, which a node column sorted ahead of the
434 port name would break. Passing the node terms here rather than chaining a
435 second C<order_by> also avoids the other half of that trap: a chained
436 C<order_by> replaces the previous one rather than appending to it.
437  
438 The tiebreak on the raw port name is not decoration. C<port_sortkey()>
439 deliberately ties equivalent names, C<10GigabitEthernet1/1> against
440 C<GigabitEthernet1/1>, and without a tiebreak the order within a tie is
441 whatever Postgres happens to return, which is what makes paging unsafe.
442  
443 Both comparisons are C<COLLATE "C">, matching the JavaScript, which compares
444 strings by code unit.
445  
446 =cut
447  
448 # Checked once per process rather than per query. Steps 98-99 and 101-102 run
449 # strict, so the function can be missing only if they were forced or replayed
450 # with --redeploy-all, both of which skip failing statements and stamp the
451 # version anyway. Without this the first symptom is every Ports tab request
452 # failing with a bare "function port_sortkey(text) does not exist" from inside
453 # a query. Deliberately no fallback to the Perl sort_port: that would hide a
454 # broken deployment behind an order which is not the same one.
455 my $port_sortkey_present = 0;
456  
457 sub _assert_port_sortkey {
458 my $rs = shift;
459 return if $port_sortkey_present;
460  
461 my $found = $rs->result_source->schema->storage->dbh_do(sub {
462 my (undef, $dbh) = @_;
463 my ($exists) = $dbh->selectrow_array(
464 q{SELECT to_regprocedure('port_sortkey(text)') IS NOT NULL});
465 return $exists;
466 });
467  
468 die "port_sortkey() is missing from the database, so ports cannot be ordered.\n"
469 . "Run netdisco-db-deploy to apply schema version 99. If the database is\n"
470 . "already at 99 or later, a step that creates it (98-99 or 101-102) was\n"
471 . "forced or replayed with --redeploy-all and the function was skipped:\n"
472 . "check the schema_step_forced table and run netdisco-db-deploy --check,\n"
473 . "then apply\n"
474 . "share/schema_versions/App-Netdisco-DB-98-99-PostgreSQL.sql by hand and\n"
475 . "read the error it gives.\n"
476 unless $found;
477  
478 $port_sortkey_present = 1;
479 }
480  
481 sub order_by_port_name {
482 my ($rs, $also) = @_;
483 $rs->_assert_port_sortkey;
484  
485 return $rs->search_rs({}, { order_by => [
486 \'port_sortkey(me.port) COLLATE "C"',
487 \'me.port COLLATE "C"',
488 @{ $also || [] },
489 ] });
490 }
491  
492 1;