| 1 | package App::Netdisco::Web::Plugin::Device::Ports; | ||
| 2 | |||
| 3 | use Dancer ':syntax'; | ||
| 4 | use Dancer::Plugin::DBIC; | ||
| 5 | use Dancer::Plugin::Auth::Extensible; | ||
| 6 | |||
| 7 | use App::Netdisco::Util::Permission 'acl_matches'; | ||
| 8 | use App::Netdisco::Util::Port qw/port_acl_service port_acl_pvid port_acl_name/; | ||
| 9 | use App::Netdisco::Web::Plugin; | ||
| 10 | |||
| 11 | use List::MoreUtils 'singleton'; | ||
| 12 | use NetAddr::MAC (); | ||
| 13 | use DBIx::Class::ResultClass::HashRefInflator; | ||
| 14 | use URI::Escape 'uri_escape'; | ||
| 15 | |||
| 16 | register_device_tab({ tag => 'ports', label => 'Ports', provides_csv => 1 }); | ||
| 17 | |||
| 18 | # $nodes_name names a has_many relation, but the source it reads from is a | ||
| 19 | # different name again. | ||
| 20 | my %node_result_class = ( | ||
| 21 | nodes => 'Node', | ||
| 22 | active_nodes => 'Virtual::ActiveNode', | ||
| 23 | nodes_with_age => 'Virtual::NodeWithAge', | ||
| 24 | active_nodes_with_age => 'Virtual::ActiveNodeWithAge', | ||
| 25 | ); | ||
| 26 | |||
| 27 | # Fetches nodes for one device and groups them by port name. Split out from | ||
| 28 | # the route so xt can call it without a session, the route being require_login. | ||
| 29 | # | ||
| 30 | # HashRefInflator returns plain hashrefs, and Template Toolkit's FOREACH over | ||
| 31 | # a bare hashref iterates its key/value pairs instead of treating it as one | ||
| 32 | # item, so manufacturer (belongs_to) and netbios (might_have) are wrapped in | ||
| 33 | # an arrayref to restore the one-row-or-none shape the template expects. | ||
| 34 | # wireless is has_many and arrives as an arrayref already. | ||
| 35 | sub _stitch_nodes { | ||
| 36 | my ($schema, $device_ip, $rows, $nodes_name, $ips_name, $node_order, | ||
| 37 | $extra_prefetch, $only_ports) = @_; | ||
| 38 | |||
| 39 | my %cond = (switch => $device_ip); | ||
| 40 | $cond{port} = { -in => $only_ports } | ||
| 41 | if $only_ports and scalar @$only_ports; | ||
| 42 | |||
| 43 | my $node_rs = $schema->resultset($node_result_class{$nodes_name}) | ||
| 44 | ->search(\%cond, { | ||
| 45 | order_by => $node_order, | ||
| 46 | prefetch => [ $ips_name, @{ $extra_prefetch || [] } ], | ||
| 47 | }); | ||
| 48 | $node_rs->result_class('DBIx::Class::ResultClass::HashRefInflator'); | ||
| 49 | |||
| 50 | my %nodes_by_port = (); | ||
| 51 | for my $node ($node_rs->all) { | ||
| 52 | $node->{stitched_ips} = delete $node->{$ips_name} || []; | ||
| 53 | $node->{net_mac} = NetAddr::MAC->new(mac => ($node->{mac} || '')); | ||
| 54 | $node->{manufacturer} = [ $node->{manufacturer} ] if $node->{manufacturer}; | ||
| 55 | $node->{netbios} = [ $node->{netbios} ] if $node->{netbios}; | ||
| 56 | push @{ $nodes_by_port{ $node->{port} } }, $node; | ||
| 57 | } | ||
| 58 | |||
| 59 | # attached here rather than by the caller, so a test exercises the same | ||
| 60 | # key the template reads. | ||
| 61 | $_->{stitched_nodes} = ($nodes_by_port{ $_->port } || []) for @$rows; | ||
| 62 | return; | ||
| 63 | } | ||
| 64 | |||
| 65 | # Decides whether to fetch nodes for this view, and how widely, as the | ||
| 66 | # $only_ports argument to _stitch_nodes. Kept free of param() so xt can pin | ||
| 67 | # the decision without a session. | ||
| 68 | # | ||
| 69 | # The neighbors-only branch is for a site's own older ports.tt ($legacy), which | ||
| 70 | # finds the neighbor's MAC among the nodes; the shipped one uses _neighbor_macs. | ||
| 71 | # | ||
| 72 | # Returns undef to fetch nothing, or an arrayref for $only_ports: empty means | ||
| 73 | # the whole device, non-empty scopes the fetch to those ports. The c_nodes | ||
| 74 | # branch's empty arrayref only reaches the CSV export as written: the HTML | ||
| 75 | # path narrows it again via _threshold_scope before any fetch runs. | ||
| 76 | sub _node_fetch_scope { | ||
| 77 | my ($want_nodes, $want_neighbors, $rows, $legacy) = @_; | ||
| 78 | |||
| 79 | return [] if $want_nodes; | ||
| 80 | return undef if not ($want_neighbors and $legacy); | ||
| 81 | |||
| 82 | my @neighbor_ports = map { $_->port } grep { $_->remote_ip } @$rows; | ||
| 83 | return undef if not scalar @neighbor_ports; | ||
| 84 | return \@neighbor_ports; | ||
| 85 | } | ||
| 86 | |||
| 87 | # The MAC behind each port's remote_ip, in one query, so c_neighbors alone no | ||
| 88 | # longer stitches nodes. Picks what the stitch picked: the first node in | ||
| 89 | # _node_display_options' order carrying the IP. | ||
| 90 | sub _neighbor_macs { | ||
| 91 | my ($schema, $device_ip, $nodes_name, $ips_name) = @_; | ||
| 92 | |||
| 93 | my $family = ($ips_name eq 'ip4s') ? 'AND family(i.ip) = 4' | ||
| 94 | : ($ips_name eq 'ip6s') ? 'AND family(i.ip) = 6' | ||
| 95 | : ''; | ||
| 96 | |||
| 97 | my $sql = sprintf(q{ | ||
| 98 | SELECT DISTINCT ON (n.port) n.port, n.mac::text | ||
| 99 | FROM device_port p | ||
| 100 | JOIN node n ON n.switch = p.ip AND n.port = p.port | ||
| 101 | JOIN node_ip i ON i.mac = n.mac AND i.active = n.active | ||
| 102 | AND i.ip = p.remote_ip | ||
| 103 | WHERE p.ip = ? AND p.remote_ip IS NOT NULL %s %s | ||
| 104 | ORDER BY n.port, | ||
| 105 | regexp_replace(COALESCE(n.vlan, '0'), '[^0-9]*' ,'0') :: integer, | ||
| 106 | n.mac | ||
| 107 | }, _shadow_active_fragment($nodes_name), $family); | ||
| 108 | |||
| 109 | my $macs = $schema->storage->dbh_do(sub { | ||
| 110 | my (undef, $dbh) = @_; | ||
| 111 | $dbh->selectall_arrayref($sql, undef, $device_ip); | ||
| 112 | }); | ||
| 113 | |||
| 114 | return { map {; $_->[0] => $_->[1] } @$macs }; | ||
| 115 | } | ||
| 116 | |||
| 117 | # PoE, SSIDs and the last comment, one query each keyed by port: prefetched, | ||
| 118 | # power and ssid slowed the port query, and last_comment ran a query per port. | ||
| 119 | # Kept under keys of their own so templates do not call the relation methods. | ||
| 120 | sub _port_power { | ||
| 121 | my ($schema, $device_ip) = @_; | ||
| 122 | my $rows = $schema->storage->dbh_do(sub { | ||
| 123 | my (undef, $dbh) = @_; | ||
| 124 | $dbh->selectall_arrayref(q{ | ||
| 125 | SELECT port, admin, status, class, power | ||
| 126 | FROM device_port_power WHERE ip = ? | ||
| 127 | }, { Slice => {} }, $device_ip); | ||
| 128 | }); | ||
| 129 | return { map {; (delete $_->{port}) => $_ } @$rows }; | ||
| 130 | } | ||
| 131 | |||
| 132 | # sorted; the prefetch gave no order | ||
| 133 | sub _port_ssids { | ||
| 134 | my ($schema, $device_ip) = @_; | ||
| 135 | my $rows = $schema->storage->dbh_do(sub { | ||
| 136 | my (undef, $dbh) = @_; | ||
| 137 | $dbh->selectall_arrayref(q{ | ||
| 138 | SELECT port, ssid FROM device_port_ssid | ||
| 139 | WHERE ip = ? AND ssid IS NOT NULL | ||
| 140 | ORDER BY port, ssid | ||
| 141 | }, undef, $device_ip); | ||
| 142 | }); | ||
| 143 | my %ssids = (); | ||
| 144 | push @{ $ssids{ $_->[0] } }, $_->[1] for @$rows; | ||
| 145 | return \%ssids; | ||
| 146 | } | ||
| 147 | |||
| 148 | # DevicePort's last_comment, for every port at once | ||
| 149 | sub _last_comments { | ||
| 150 | my ($schema, $device_ip) = @_; | ||
| 151 | my $rows = $schema->storage->dbh_do(sub { | ||
| 152 | my (undef, $dbh) = @_; | ||
| 153 | $dbh->selectall_arrayref(q{ | ||
| 154 | SELECT DISTINCT ON (port) port, log | ||
| 155 | FROM device_port_log | ||
| 156 | WHERE ip = ? | ||
| 157 | ORDER BY port, creation DESC | ||
| 158 | }, undef, $device_ip); | ||
| 159 | }); | ||
| 160 | return { map {; $_->[0] => $_->[1] } @$rows }; | ||
| 161 | } | ||
| 162 | |||
| 163 | # n_archived swaps $nodes_name to nodes, which is the whole table rather than | ||
| 164 | # the archived half, so a shadow built with active = 0 there would drop the | ||
| 165 | # active nodes back out and a MAC visible on screen would stop being findable. | ||
| 166 | # Derived from $nodes_name so this and %node_result_class cannot drift apart. | ||
| 167 | sub _shadow_active_fragment { | ||
| 168 | my ($nodes_name) = @_; | ||
| 169 | return $nodes_name =~ m/^active/ ? 'AND n.active' : ''; | ||
| 170 | } | ||
| 171 | |||
| 172 | # Builds the DataTables search shadow: one string per port carrying every | ||
| 173 | # node's mac, ip, dns and vlan text, plus ssid and netbios when asked for, so | ||
| 174 | # the filter can find a node whose markup this response does not render. | ||
| 175 | # Built in one statement rather than by concatenating the fetched rows in | ||
| 176 | # Perl, which costs more than the render it exists to save. | ||
| 177 | # | ||
| 178 | # The node_ip lateral's "active = n.active" mirrors Node's ips relationship, | ||
| 179 | # which joins foreign.active => self.active, so an archived node gets archived | ||
| 180 | # IPs. Get it wrong and the filter matches archived IPs that are not on | ||
| 181 | # screen. node_wireless and node_nbt are keyed on mac alone, with no active | ||
| 182 | # condition, so their laterals match that instead. | ||
| 183 | # | ||
| 184 | # vlan has no n_* guard in the template and is always included. ssid, netbios | ||
| 185 | # and vendor are joined only under their own guards: a field the cell does not | ||
| 186 | # render need not be findable, and each join has a real cost. | ||
| 187 | sub _attach_search_shadow { | ||
| 188 | my ($schema, $device_ip, $rows, $active_fragment, $want_ssid, $want_netbios, | ||
| 189 | $mac_format, $want_vendor) = @_; | ||
| 190 | |||
| 191 | my ($ssid_select, $ssid_join) = ('', ''); | ||
| 192 | if ($want_ssid) { | ||
| 193 | $ssid_select = q{ || ' ' || COALESCE(w.txt, '')}; | ||
| 194 | $ssid_join = q{ | ||
| 195 | LEFT JOIN LATERAL ( | ||
| 196 | SELECT string_agg(ssid, ' ') AS txt | ||
| 197 | FROM node_wireless WHERE mac = n.mac) w ON true}; | ||
| 198 | } | ||
| 199 | |||
| 200 | # nbuser is a logged-in user rather than the machine's own NetBIOS | ||
| 201 | # hostname, so nbname does not cover it, and nbt.ip is not always one of | ||
| 202 | # the node's own IPs, so the node_ip lateral does not either. The | ||
| 203 | # '[No User]' fallback the template renders is left out: it would match | ||
| 204 | # every node that has no NetBIOS user. | ||
| 205 | my ($netbios_select, $netbios_join) = ('', ''); | ||
| 206 | if ($want_netbios) { | ||
| 207 | $netbios_select = q{ || ' ' || COALESCE(b.txt, '')}; | ||
| 208 | $netbios_join = q{ | ||
| 209 | LEFT JOIN LATERAL ( | ||
| 210 | SELECT string_agg(COALESCE(nbname, '') || ' ' || COALESCE(domain, '') | ||
| 211 | || ' ' || COALESCE(nbuser, '') || ' ' || COALESCE(ip::text, ''), ' ') AS txt | ||
| 212 | FROM node_nbt WHERE mac = n.mac) b ON true}; | ||
| 213 | } | ||
| 214 | |||
| 215 | # manufacturer is belongs_to on the node's oui, so at most one row and a | ||
| 216 | # plain LEFT JOIN rather than a lateral. abbrev, not company, because | ||
| 217 | # abbrev is what the cell renders. | ||
| 218 | my ($vendor_select, $vendor_join) = ('', ''); | ||
| 219 | if ($want_vendor) { | ||
| 220 | $vendor_select = q{ || ' ' || COALESCE(m.abbrev, '')}; | ||
| 221 | $vendor_join = q{ | ||
| 222 | LEFT JOIN manufacturer m ON m.base = n.oui}; | ||
| 223 | } | ||
| 224 | |||
| 225 | # The cell renders the MAC through mac_format_call, so on any setting but | ||
| 226 | # IEEE the string on screen is not the one Postgres stores and a filter on | ||
| 227 | # the visible MAC would miss. The displayed form is carried beside the | ||
| 228 | # canonical one rather than instead of it, so a pasted IEEE address keeps | ||
| 229 | # working whatever the setting. IEEE needs no entry here: it is exactly | ||
| 230 | # what mac::text already gives. Kept in step with NetAddr::MAC's as_cisco, | ||
| 231 | # as_microsoft and as_sun, which is what the template calls. | ||
| 232 | my %mac_as = ( | ||
| 233 | cisco => q{regexp_replace(replace(n.mac::text, ':', ''), | ||
| 234 | '(.{4})(.{4})(.{4})', '\1.\2.\3')}, | ||
| 235 | microsoft => q{replace(n.mac::text, ':', '-')}, | ||
| 236 | sun => q{replace(regexp_replace(n.mac::text, | ||
| 237 | '(^|:)0([0-9a-f])', '\1\2', 'g'), ':', '-')}, | ||
| 238 | ); | ||
| 239 | my $mac_select = ''; | ||
| 240 | if ($mac_format and my $expr = $mac_as{ lc $mac_format }) { | ||
| 241 | $mac_select = qq{ || ' ' || $expr}; | ||
| 242 | } | ||
| 243 | |||
| 244 | my $sql = sprintf(q{ | ||
| 245 | SELECT n.port, | ||
| 246 | string_agg(n.mac::text || ' ' || COALESCE(n.vlan, '') || ' ' | ||
| 247 | || COALESCE(i.txt, '')%s%s%s%s, ' ') AS s | ||
| 248 | FROM node n | ||
| 249 | LEFT JOIN LATERAL ( | ||
| 250 | SELECT string_agg(ip::text || ' ' || COALESCE(dns, ''), ' ') AS txt | ||
| 251 | FROM node_ip WHERE mac = n.mac AND active = n.active) i ON true | ||
| 252 | %s%s%s | ||
| 253 | WHERE n.switch = ? %s | ||
| 254 | GROUP BY n.port | ||
| 255 | }, $ssid_select, $netbios_select, $vendor_select, $mac_select, | ||
| 256 | $ssid_join, $netbios_join, $vendor_join, $active_fragment); | ||
| 257 | |||
| 258 | my $shadow = $schema->storage->dbh_do(sub { | ||
| 259 | my (undef, $dbh) = @_; | ||
| 260 | $dbh->selectall_arrayref($sql, undef, $device_ip); | ||
| 261 | }); | ||
| 262 | |||
| 263 | my %shadow_by_port = map {; $_->[0] => ($_->[1] || '') } @$shadow; | ||
| 264 | $_->{nodes_search} = ($shadow_by_port{ $_->port } || '') for @$rows; | ||
| 265 | return; | ||
| 266 | } | ||
| 267 | |||
| 268 | # The nodes cell and the neighbors cell are one <td>, and data-search on a | ||
| 269 | # <td> replaces that cell's whole search text rather than adding to it, so a | ||
| 270 | # port's own neighbor identity has to be appended or it stops being findable | ||
| 271 | # once c_nodes is on. | ||
| 272 | # | ||
| 273 | # remote_ip, remote_port, remote_dns, remote_id and remote_type are | ||
| 274 | # device_port columns (remote_dns via the with_properties join the route | ||
| 275 | # always applies) and are safe to read whatever the params say. neighbor_ip | ||
| 276 | # and neighbor_dns come from a +select added only under c_neighbors, and | ||
| 277 | # get_column dies for a column that was never selected. remote_inventory is a | ||
| 278 | # method, not a column: it reads columns only with_remote_inventory selects, | ||
| 279 | # which the route applies only under n_inventory, so it dies the same way | ||
| 280 | # unless guarded on that flag. | ||
| 281 | sub _augment_neighbor_search { | ||
| 282 | my ($rows, $want_neighbors, $want_inventory) = @_; | ||
| 283 | |||
| 284 | for my $row (@$rows) { | ||
| 285 | my @extra = grep { defined and length } | ||
| 286 | ($row->remote_ip, $row->remote_port, $row->remote_dns, | ||
| 287 | $row->remote_id, $row->remote_type); | ||
| 288 | push @extra, grep { defined and length } | ||
| 289 | ($row->get_column('neighbor_ip'), $row->get_column('neighbor_dns')) | ||
| 290 | if $want_neighbors; | ||
| 291 | if ($want_inventory) { | ||
| 292 | my $inventory = $row->remote_inventory; | ||
| 293 | push @extra, $inventory if defined $inventory and length $inventory; | ||
| 294 | } | ||
| 295 | |||
| 296 | next unless @extra; | ||
| 297 | $row->{nodes_search} = join ' ', grep { length } ($row->{nodes_search}, @extra); | ||
| 298 | } | ||
| 299 | return; | ||
| 300 | } | ||
| 301 | |||
| 302 | # Shared with the one-port route below: the node source and the ordering and | ||
| 303 | # prefetch terms must not drift between the two, or the deferred fetch draws | ||
| 304 | # its rows in a different order than the eager path would have. Kept free of | ||
| 305 | # the c_nodes/c_neighbors gate the main route used to apply to the ordering | ||
| 306 | # and prefetch terms, because the deferred fetch never sends either param and | ||
| 307 | # an empty @node_order would leave it unordered. | ||
| 308 | sub _node_display_options { | ||
| 309 | my $nodes_name = (param('n_archived') ? 'nodes' : 'active_nodes'); | ||
| 310 | $nodes_name .= '_with_age' if param('n_age'); | ||
| 311 | |||
| 312 | my $ips_name = ((param('n_ip4') and param('n_ip6')) ? 'ips' | ||
| 313 | : param('n_ip4') ? 'ip4s' | ||
| 314 | : 'ip6s'); | ||
| 315 | |||
| 316 | my @node_order = ( | ||
| 317 | \qq{regexp_replace(COALESCE(me.vlan, '0'), '[^0-9]*' ,'0') :: integer}, | ||
| 318 | 'me.mac', | ||
| 319 | "${ips_name}.ip", | ||
| 320 | ); | ||
| 321 | |||
| 322 | my @extra_prefetch = (); | ||
| 323 | push @extra_prefetch, 'wireless' if param('n_ssid'); | ||
| 324 | push @extra_prefetch, 'netbios' if param('n_netbios'); | ||
| 325 | push @extra_prefetch, 'manufacturer' if param('n_vendor'); | ||
| 326 | |||
| 327 | return ($nodes_name, $ips_name, \@node_order, \@extra_prefetch); | ||
| 328 | } | ||
| 329 | |||
| 330 | # One query, run once per c_nodes request rather than once per row: reads the | ||
| 331 | # same table _attach_search_shadow does, under the same active fragment, so a | ||
| 332 | # port cannot say "N nodes" here and expand to a different number there. | ||
| 333 | sub _count_nodes_by_port { | ||
| 334 | my ($schema, $device_ip, $rows, $active_fragment) = @_; | ||
| 335 | |||
| 336 | my $sql = sprintf(q{ | ||
| 337 | SELECT n.port, count(*) AS n | ||
| 338 | FROM node n | ||
| 339 | WHERE n.switch = ? %s | ||
| 340 | GROUP BY n.port | ||
| 341 | }, $active_fragment); | ||
| 342 | |||
| 343 | my $counts = $schema->storage->dbh_do(sub { | ||
| 344 | my (undef, $dbh) = @_; | ||
| 345 | $dbh->selectall_arrayref($sql, undef, $device_ip); | ||
| 346 | }); | ||
| 347 | |||
| 348 | my %count_by_port = map {; $_->[0] => $_->[1] } @$counts; | ||
| 349 | $_->{node_count} = ($count_by_port{ $_->port } || 0) for @$rows; | ||
| 350 | return \%count_by_port; | ||
| 351 | } | ||
| 352 | |||
| 353 | # Carries the display options that change how a node row renders, built once | ||
| 354 | # here rather than in the template, so the deferred fetch draws the same | ||
| 355 | # markup the eager path would have. mac_format feeds mac_format_call in | ||
| 356 | # Web.pm, which every node's MAC is rendered through. Kept free of param() | ||
| 357 | # so xt can pin the querystring without a session. | ||
| 358 | sub _deferred_node_params { | ||
| 359 | my ($n_ip4, $n_ip6, $n_dns, $n_age, $n_ssid, $n_vendor, $n_netbios, | ||
| 360 | $n_archived, $mac_format) = @_; | ||
| 361 | |||
| 362 | my $qs = ''; | ||
| 363 | $qs .= '&n_ip4=1' if $n_ip4; | ||
| 364 | $qs .= '&n_ip6=1' if $n_ip6; | ||
| 365 | $qs .= '&n_dns=1' if $n_dns; | ||
| 366 | $qs .= '&n_age=1' if $n_age; | ||
| 367 | $qs .= '&n_ssid=1' if $n_ssid; | ||
| 368 | $qs .= '&n_vendor=1' if $n_vendor; | ||
| 369 | $qs .= '&n_netbios=1' if $n_netbios; | ||
| 370 | $qs .= '&n_archived=1' if $n_archived; | ||
| 371 | $qs .= '&mac_format=' . uri_escape($mac_format) if $mac_format; | ||
| 372 | return $qs; | ||
| 373 | } | ||
| 374 | |||
| 375 | # Ports at or under the threshold get their own row fetched. For a site's own | ||
| 376 | # ports.tt ($want_neighbors is then c_neighbors), a port over it still gets | ||
| 377 | # one when it might carry a neighbor's own MAC, since that template reads | ||
| 378 | # stitched_nodes for it regardless of the node list's own threshold. The | ||
| 379 | # shipped templates read _neighbor_macs instead and pass false, so an | ||
| 380 | # over-threshold trunk port is never stitched just to throw the render away. | ||
| 381 | # Kept free of param() and setting() so xt can pin the decision without a | ||
| 382 | # session. | ||
| 383 | sub _threshold_scope { | ||
| 384 | my ($threshold, $want_neighbors, $count_by_port, $rows) = @_; | ||
| 385 | return [ map { $_->port } | ||
| 386 | grep { ($count_by_port->{ $_->port } || 0) <= $threshold | ||
| 387 | or ($want_neighbors and $_->remote_ip) } @$rows ]; | ||
| 388 | } | ||
| 389 | |||
| 390 | # Everything the Ports tab knows about each port, decorated, filtered and | ||
| 391 | # grouped, for whichever output the caller renders: the HTML table, the CSV | ||
| 392 | # export, or the JSON the browser draws from. Reads param() and setting(), so | ||
| 393 | # it runs inside a route only. Returns undef when the view has no rows, the | ||
| 394 | # caller's "no matching records". | ||
| 395 | # | ||
| 396 | # $opt->{legacy} is set for a site's own copy of an older ports.tt, which | ||
| 397 | # finds the neighbor's MAC by searching stitched_nodes. | ||
| 398 | sub _port_rows { | ||
| 399 | my ($opt) = @_; | ||
| 400 | $opt ||= {}; | ||
| 401 | my $q = param('q'); | ||
| 402 | my $prefer = param('prefer'); | ||
| 403 | $prefer = '' | ||
| 404 | unless defined $prefer and $prefer =~ m/^(?:port|name|vlan)$/; | ||
| 405 | |||
| 406 | my $device = schema(vars->{'tenant'})->resultset('Device') | ||
| 407 | ->search_for_device($q) or send_error('Bad device', 400); | ||
| 408 | my $set = $device->ports->with_properties->with_custom_fields; | ||
| 409 | |||
| 410 | # refine by ports if requested | ||
| 411 | my $f = param('f'); | ||
| 412 | if ($f) { | ||
| 413 | if (($prefer eq 'vlan') or (not $prefer and $f =~ m/^\d+$/)) { | ||
| 414 | return unless $f =~ m/^\d+$/; | ||
| 415 | } | ||
| 416 | else { | ||
| 417 | if (param('partial')) { | ||
| 418 | # change wildcard chars to SQL | ||
| 419 | $f =~ s/\*/%/g; | ||
| 420 | $f =~ s/\?/_/g; | ||
| 421 | # set wildcards at param boundaries | ||
| 422 | if ($f !~ m/[%_]/) { | ||
| 423 | $f =~ s/^\%*/%/; | ||
| 424 | $f =~ s/\%*$/%/; | ||
| 425 | } | ||
| 426 | # enable ILIKE op | ||
| 427 | $f = { (param('invert') ? '-not_ilike' : '-ilike') => $f }; | ||
| 428 | } | ||
| 429 | elsif (param('invert')) { | ||
| 430 | $f = { '!=' => $f }; | ||
| 431 | } | ||
| 432 | |||
| 433 | if (($prefer eq 'port') or not $prefer and | ||
| 434 | $set->search({-or => ['me.port' => $f, 'me.descr' => $f]})->count) { | ||
| 435 | |||
| 436 | $set = $set->search({ | ||
| 437 | -or => [ | ||
| 438 | 'me.port' => $f, | ||
| 439 | 'me.descr' => $f, | ||
| 440 | 'me.slave_of' => $f, | ||
| 441 | ], | ||
| 442 | }); | ||
| 443 | } | ||
| 444 | else { | ||
| 445 | $set = $set->search({'me.name' => $f}); | ||
| 446 | return unless $set->count; | ||
| 447 | } | ||
| 448 | } | ||
| 449 | } | ||
| 450 | |||
| 451 | # filter for port status if asked | ||
| 452 | my %port_state = map {$_ => 1} | ||
| 453 | (ref [] eq ref param('port_state') ? @{param('port_state')} | ||
| 454 | : param('port_state') ? param('port_state') : ()); | ||
| 455 | |||
| 456 | return unless scalar keys %port_state; | ||
| 457 | |||
| 458 | if (exists $port_state{free}) { | ||
| 459 | if (scalar keys %port_state == 1) { | ||
| 460 | $set = $set->only_free_ports({ | ||
| 461 | age_num => (param('age_num') || 3), | ||
| 462 | age_unit => (param('age_unit') || 'months') | ||
| 463 | }); | ||
| 464 | } | ||
| 465 | else { | ||
| 466 | $set = $set->with_is_free({ | ||
| 467 | age_num => (param('age_num') || 3), | ||
| 468 | age_unit => (param('age_unit') || 'months') | ||
| 469 | }); | ||
| 470 | } | ||
| 471 | delete $port_state{free}; | ||
| 472 | # showing free ports requires showing down ports | ||
| 473 | ++$port_state{down}; | ||
| 474 | } | ||
| 475 | |||
| 476 | if (scalar keys %port_state < 3) { | ||
| 477 | my @combi = (); | ||
| 478 | |||
| 479 | push @combi, {'me.up' => 'up'} | ||
| 480 | if exists $port_state{up}; | ||
| 481 | push @combi, {'me.up_admin' => 'up', 'me.up' => { '!=' => 'up'}} | ||
| 482 | if exists $port_state{down}; | ||
| 483 | push @combi, {'me.up_admin' => { '!=' => 'up'}} | ||
| 484 | if exists $port_state{shut}; | ||
| 485 | |||
| 486 | $set = $set->search({-or => \@combi}); | ||
| 487 | } | ||
| 488 | |||
| 489 | # so far only the basic device_port data | ||
| 490 | # now begin to join tables depending on the selected columns/options | ||
| 491 | |||
| 492 | # get vlans on the port | ||
| 493 | # leave this query dormant (lazy) unless c_vmember is set or vlan filtering | ||
| 494 | my $vlans = $set->search( | ||
| 495 | { param('p_hide1002') ? | ||
| 496 | (-or => ['port_vlans.vlan' => {'<', '1002'}, | ||
| 497 | 'port_vlans.vlan' => {'>', '1005'}]) : () | ||
| 498 | }, { | ||
| 499 | select => [ | ||
| 500 | 'port', | ||
| 501 | { count => 'port_vlans.vlan', -as => 'vlan_count' }, | ||
| 502 | { array_agg => \q{port_vlans.vlan ORDER BY port_vlans.vlan}, -as => 'vlan_set' }, | ||
| 503 | { array_agg => \q{COALESCE(NULLIF(vlan_entry.description,''), vlan_entry.vlan::text) ORDER BY vlan_entry.vlan}, -as => 'vlan_name_set' }, | ||
| 504 | ], | ||
| 505 | join => {'port_vlans' => 'vlan_entry'}, | ||
| 506 | group_by => 'me.port', | ||
| 507 | }); | ||
| 508 | |||
| 509 | if (param('c_vmember') or ($prefer eq 'vlan') or (not $prefer and $f =~ m/^\d+$/)) { | ||
| 510 | $vlans = { map {( | ||
| 511 | $_->port => { | ||
| 512 | # DBIC smart enough to work out this should be an arrayref :) | ||
| 513 | vlan_count => $_->get_column('vlan_count'), | ||
| 514 | vlan_set => $_->get_column('vlan_set'), | ||
| 515 | vlan_name_set => $_->get_column('vlan_name_set'), | ||
| 516 | }, | ||
| 517 | )} $vlans->all }; | ||
| 518 | } | ||
| 519 | |||
| 520 | if (param('p_vlan_names')) { | ||
| 521 | $set = $set->search({}, { | ||
| 522 | 'join' => 'native_vlan', | ||
| 523 | '+select' => [qw/native_vlan.description/], | ||
| 524 | '+as' => [qw/native_vlan_name/], | ||
| 525 | }); | ||
| 526 | } | ||
| 527 | |||
| 528 | # get aggregate master status (self join) | ||
| 529 | $set = $set->search({}, { | ||
| 530 | 'join' => 'agg_master', | ||
| 531 | '+select' => [qw/agg_master.up_admin agg_master.up/], | ||
| 532 | '+as' => [qw/agg_master_up_admin agg_master_up/], | ||
| 533 | }); | ||
| 534 | |||
| 535 | # make sure query asks for formatted timestamps when needed | ||
| 536 | $set = $set->with_times if param('c_lastchange'); | ||
| 537 | |||
| 538 | # what kind of nodes are we interested in? node_order is qualified | ||
| 539 | # against the node source, never $set: see DevicePort's | ||
| 540 | # order_by_port_name for why the port key has to lead there. Fetched | ||
| 541 | # separately and joined by port name below, not prefetched: one prefetch | ||
| 542 | # of ports to nodes to IPs returns the product of all three and DBIC | ||
| 543 | # inflates every row of it. _stitch_nodes still prefetches IPs and | ||
| 544 | # wireless together off the node, which reintroduces that product, but | ||
| 545 | # scoped to one node's own rows rather than every port's. | ||
| 546 | my ($nodes_name, $ips_name, $node_order, $extra_prefetch) | ||
| 547 | = _node_display_options(); | ||
| 548 | |||
| 549 | # retrieve neighbor devices, if asked for | ||
| 550 | #$set = $set->search({}, { prefetch => [{neighbor_alias => 'device'}] }) | ||
| 551 | # if param('c_neighbors'); | ||
| 552 | # retrieve neighbor devices, if asked for | ||
| 553 | $set = $set->search({}, { | ||
| 554 | join => 'neighbor_alias', | ||
| 555 | '+select' => ['neighbor_alias.ip', 'neighbor_alias.dns'], | ||
| 556 | '+as' => ['neighbor_ip', 'neighbor_dns'], | ||
| 557 | }) if param('c_neighbors'); | ||
| 558 | |||
| 559 | # also get remote LLDP inventory if asked for | ||
| 560 | $set = $set->with_remote_inventory if param('n_inventory'); | ||
| 561 | |||
| 562 | # Ordered in the database rather than after the fetch. The order is | ||
| 563 | # portsort.js's, which is the one the browser shows, so this replaces a | ||
| 564 | # sort_port pass whose result the browser overwrote anyway. $node_order | ||
| 565 | # must not be added here: $set has its own mac and vlan columns and would | ||
| 566 | # silently order by those instead. | ||
| 567 | $set = $set->order_by_port_name(); | ||
| 568 | |||
| 569 | # run query | ||
| 570 | my @results = $set->all; | ||
| 571 | |||
| 572 | # see _port_power for why these are not prefetched | ||
| 573 | if (param('c_power')) { | ||
| 574 | my $power = _port_power(schema(vars->{'tenant'}), $device->ip); | ||
| 575 | $_->{port_power} = $power->{ $_->port } for @results; | ||
| 576 | } | ||
| 577 | if (param('c_ssid')) { | ||
| 578 | my $ssids = _port_ssids(schema(vars->{'tenant'}), $device->ip); | ||
| 579 | $_->{port_ssids} = ($ssids->{ $_->port } || []) for @results; | ||
| 580 | } | ||
| 581 | if (param('c_comment')) { | ||
| 582 | my $comments = _last_comments(schema(vars->{'tenant'}), $device->ip); | ||
| 583 | $_->{port_comment} = $comments->{ $_->port } for @results; | ||
| 584 | } | ||
| 585 | |||
| 586 | if (param('c_neighbors')) { | ||
| 587 | my $macs = _neighbor_macs(schema(vars->{'tenant'}), $device->ip, | ||
| 588 | $nodes_name, $ips_name); | ||
| 589 | $_->{neighbor_net_mac} = NetAddr::MAC->new(mac => $macs->{ $_->port }) | ||
| 590 | for grep { exists $macs->{ $_->port } } @results; | ||
| 591 | } | ||
| 592 | |||
| 593 | # fetch and attach nodes by port name, rather than prefetching them | ||
| 594 | my $node_fetch_scope = _node_fetch_scope( | ||
| 595 | scalar param('c_nodes'), scalar param('c_neighbors'), \@results, | ||
| 596 | $opt->{legacy}); | ||
| 597 | |||
| 598 | my $deferred_node_params = ''; | ||
| 599 | |||
| 600 | if (defined $node_fetch_scope) { | ||
| 601 | my $only_ports = $node_fetch_scope; | ||
| 602 | my $skip_stitch = 0; | ||
| 603 | |||
| 604 | # ports_csv.tt has no collapse threshold and reads every port's | ||
| 605 | # stitched_nodes unconditionally, so this scoping only applies to | ||
| 606 | # the HTML fragment: a CSV export still gets the whole device. | ||
| 607 | if (param('c_nodes') and request->is_ajax) { | ||
| 608 | my $count_by_port = _count_nodes_by_port(schema(vars->{'tenant'}), | ||
| 609 | $device->ip, \@results, _shadow_active_fragment($nodes_name)); | ||
| 610 | |||
| 611 | # Ports over the threshold render a count and an empty div that | ||
| 612 | # fetches its own rows; fetching them here would build markup | ||
| 613 | # that netdisco.css hides on arrival. | ||
| 614 | $only_ports = _threshold_scope( | ||
| 615 | setting('devport_nodes_collapse_threshold'), | ||
| 616 | (param('c_neighbors') and $opt->{legacy}), | ||
| 617 | $count_by_port, \@results); | ||
| 618 | $skip_stitch = 1 unless scalar @$only_ports; | ||
| 619 | |||
| 620 | $deferred_node_params = _deferred_node_params( | ||
| 621 | scalar param('n_ip4'), scalar param('n_ip6'), | ||
| 622 | scalar param('n_dns'), scalar param('n_age'), | ||
| 623 | scalar param('n_ssid'), scalar param('n_vendor'), | ||
| 624 | scalar param('n_netbios'), scalar param('n_archived'), | ||
| 625 | scalar param('mac_format')); | ||
| 626 | } | ||
| 627 | |||
| 628 | _stitch_nodes(schema(vars->{'tenant'}), $device->ip, \@results, | ||
| 629 | $nodes_name, $ips_name, $node_order, $extra_prefetch, $only_ports) | ||
| 630 | unless $skip_stitch; | ||
| 631 | } | ||
| 632 | |||
| 633 | # Gated on c_nodes alone, not c_neighbors like the stitch above: the | ||
| 634 | # template emits data-search only under c_nodes, so the neighbors-only | ||
| 635 | # view would build this for nothing. | ||
| 636 | if (param('c_nodes')) { | ||
| 637 | _attach_search_shadow(schema(vars->{'tenant'}), $device->ip, \@results, | ||
| 638 | _shadow_active_fragment($nodes_name), | ||
| 639 | scalar param('n_ssid'), scalar param('n_netbios'), | ||
| 640 | scalar param('mac_format'), scalar param('n_vendor')); | ||
| 641 | _augment_neighbor_search(\@results, scalar param('c_neighbors'), | ||
| 642 | scalar param('n_inventory')); | ||
| 643 | } | ||
| 644 | |||
| 645 | # filter for tagged vlan using existing agg query, | ||
| 646 | # which is better than join inflation | ||
| 647 | if (($prefer eq 'vlan') or (not $prefer and $f =~ m/^\d+$/)) { | ||
| 648 | if (param('invert')) { | ||
| 649 | @results = grep { | ||
| 650 | (!defined $_->vlan or $_->vlan ne $f) | ||
| 651 | and | ||
| 652 | (0 == scalar grep {defined and $_ ne $f} @{ $vlans->{$_->port}->{vlan_set} }) | ||
| 653 | } @results; | ||
| 654 | } | ||
| 655 | else { | ||
| 656 | @results = grep { | ||
| 657 | (defined $_->vlan and $_->vlan eq $f) | ||
| 658 | or | ||
| 659 | (scalar grep {defined and $_ eq $f} @{ $vlans->{$_->port}->{vlan_set} }) | ||
| 660 | } @results; | ||
| 661 | } | ||
| 662 | } | ||
| 663 | |||
| 664 | # filter out hidden ones | ||
| 665 | if (not param('p_include_hidden')) { | ||
| 666 | my $port_map = {}; | ||
| 667 | my %to_hide = (); | ||
| 668 | |||
| 669 | map { push @{ $port_map->{$_->port} }, $_ } | ||
| 670 | grep { $_->port } | ||
| 671 | @results; | ||
| 672 | |||
| 673 | map { push @{ $port_map->{$_->port} }, $_ } | ||
| 674 | grep { $_->port } | ||
| 675 | $device->device_ips()->all; | ||
| 676 | |||
| 677 | foreach my $map (@{ setting('hide_deviceports')}) { | ||
| 678 | next unless ref {} eq ref $map; | ||
| 679 | |||
| 680 | foreach my $key (sort keys %$map) { | ||
| 681 | # lhs matches device, rhs matches port | ||
| 682 | next unless $key and $map->{$key}; | ||
| 683 | next unless acl_matches($device, $key); | ||
| 684 | |||
| 685 | foreach my $port (sort keys %$port_map) { | ||
| 686 | next unless acl_matches($port_map->{$port}, $map->{$key}); | ||
| 687 | ++$to_hide{$port}; | ||
| 688 | } | ||
| 689 | } | ||
| 690 | } | ||
| 691 | |||
| 692 | @results = grep { ! exists $to_hide{$_->port} } @results; | ||
| 693 | } | ||
| 694 | |||
| 695 | # empty set would be a 'no records' msg | ||
| 696 | return unless scalar @results; | ||
| 697 | |||
| 698 | # collapsible subinterface groups | ||
| 699 | my %port_has_dot_zero = (); | ||
| 700 | my %port_subinterface_count = (); | ||
| 701 | my $subinterfaces_match = (setting('subinterfaces_match') || qr/(.+)\.\d+/); | ||
| 702 | |||
| 703 | foreach my $port (@results) { | ||
| 704 | if ($port->port =~ m/^${subinterfaces_match}$/) { | ||
| 705 | my $parent = $1; | ||
| 706 | next unless defined $parent; | ||
| 707 | ++$port_subinterface_count{$parent}; | ||
| 708 | ++$port_has_dot_zero{$parent} | ||
| 709 | if $port->port =~ m/\.0$/ | ||
| 710 | and ($port->type and $port->type =~ m/^(?:propVirtual|ieee8023adLag)$/i); | ||
| 711 | $port->{subinterface_group} = $parent; | ||
| 712 | } | ||
| 713 | } | ||
| 714 | |||
| 715 | # one pass to index the rows by port name. the two lookups below used to | ||
| 716 | # grep @results, re-reading every row once per parent, and on a wireless | ||
| 717 | # controller where every port is subinterface-shaped that is the whole | ||
| 718 | # request: 3650 parents each reading all 7300 rows and matching none of | ||
| 719 | # them, because the bare parent port does not exist (see 1479). | ||
| 720 | my %port_row = (); | ||
| 721 | $port_row{ $_->port } = $_ for @results; | ||
| 722 | |||
| 723 | foreach my $parent (keys %port_subinterface_count) { | ||
| 724 | my $parent_port = $port_row{$parent} | ||
| 725 | or next; # 1479 we've seen subinterfaces without parents | ||
| 726 | $parent_port->{has_subinterface_group} = true; | ||
| 727 | $parent_port->{has_only_dot_zero_subinterface} = true | ||
| 728 | if exists $port_has_dot_zero{$parent} | ||
| 729 | and $port_subinterface_count{$parent} == 1 | ||
| 730 | and ($parent_port->type | ||
| 731 | and $parent_port->type =~ m/^(?:ethernetCsmacd|ieee8023adLag)$/i); | ||
| 732 | if ($parent_port->{has_only_dot_zero_subinterface}) { | ||
| 733 | my $dotzero_port = $port_row{"${parent}.0"}; | ||
| 734 | $dotzero_port->{is_dot_zero_subinterface} = true; | ||
| 735 | } | ||
| 736 | } | ||
| 737 | |||
| 738 | # add acl on port config | ||
| 739 | # this has the merged yaml and database config | ||
| 740 | if (param('c_admin') and user_has_role('port_control')) { | ||
| 741 | # for native vlan change | ||
| 742 | map {$_->{port_acl_pvid} = port_acl_pvid($_, $device, logged_in_user)} @results; | ||
| 743 | # for up/down and poe | ||
| 744 | map {$_->{port_acl_service} = port_acl_service($_, $device, logged_in_user)} @results; | ||
| 745 | # for name/descr change | ||
| 746 | map {$_->{port_acl_name} = ($_->{port_acl_service} || # if service true then this is OK | ||
| 747 | port_acl_name($_, $device, logged_in_user))} @results; | ||
| 748 | } | ||
| 749 | |||
| 750 | # filter the tags by hide_tags setting | ||
| 751 | my @hide = @{ setting('hide_tags')->{'device_port'} }; | ||
| 752 | map { $_->{filtered_tags} = [ singleton (@{ $_->tags || [] }, @hide, @hide) ] } @results; | ||
| 753 | |||
| 754 | # pretty print the port running speed | ||
| 755 | use App::Netdisco::Util::Port 'to_speed'; | ||
| 756 | map { $_->{speed_running} = to_speed( $_->speed ) } @results; | ||
| 757 | |||
| 758 | return { | ||
| 759 | results => \@results, | ||
| 760 | vlans => $vlans, | ||
| 761 | device => $device, | ||
| 762 | nodes_name => $nodes_name, | ||
| 763 | ips_name => $ips_name, | ||
| 764 | deferred_node_params => $deferred_node_params, | ||
| 765 | }; | ||
| 766 | } | ||
| 767 | |||
| 768 | # Whether this is a site's ajax/device/ports.tt from before the neighbor's | ||
| 769 | # MAC came as neighbor_net_mac: one that reads stitched_nodes, where it used | ||
| 770 | # to find it, and not neighbor_net_mac. TT comments are left out, so a note | ||
| 771 | # naming either decides nothing. The site-local rule ports-row-keys tells | ||
| 772 | # the admin about such a copy. | ||
| 773 | sub _ports_template_is_legacy { | ||
| 774 | my ($text) = @_; | ||
| 775 | return 0 if not defined $text; | ||
| 776 | (my $code = $text) =~ s/\[%#.*?%\]//gs; | ||
| 777 | return ($code =~ m/\bstitched_nodes\b/ | ||
| 778 | and $code !~ m/\bneighbor_net_mac\b/) ? 1 : 0; | ||
| 779 | } | ||
| 780 | |||
| 781 | # The same for the template that resolves, cached by file and mtime. | ||
| 782 | my %template_legacy = (); | ||
| 783 | sub _legacy_ports_template { | ||
| 784 | my $file = engine('template')->view('ajax/device/ports') or return 0; | ||
| 785 | my $mtime = (stat $file)[9] || 0; | ||
| 786 | my $known = $template_legacy{$file}; | ||
| 787 | if (not $known or $known->{mtime} != $mtime) { | ||
| 788 | open my $fh, '<:encoding(UTF-8)', $file or return 0; | ||
| 789 | my $text = do { local $/; <$fh> }; | ||
| 790 | $known = $template_legacy{$file} | ||
| 791 | = { mtime => $mtime, legacy => _ports_template_is_legacy($text) }; | ||
| 792 | } | ||
| 793 | return $known->{legacy}; | ||
| 794 | } | ||
| 795 | |||
| 796 | # device ports with a description (er, name) matching | ||
| 797 | get '/ajax/content/device/ports' => require_login sub { | ||
| 798 | # the CSV never reads the neighbor's MAC | ||
| 799 | my $data = _port_rows({ | ||
| 800 | legacy => (request->is_ajax ? _legacy_ports_template() : 0) }) or return; | ||
| 801 | |||
| 802 | if (request->is_ajax) { | ||
| 803 | template 'ajax/device/ports.tt', { | ||
| 804 | results => $data->{results}, | ||
| 805 | # kept for site-local template overrides that may still read | ||
| 806 | # row.$nodes or row.$ips: site-local template compatibility is | ||
| 807 | # a project commitment, even though the shipped template no | ||
| 808 | # longer reads them itself | ||
| 809 | nodes => $data->{nodes_name}, | ||
| 810 | ips => $data->{ips_name}, | ||
| 811 | device => $data->{device}, | ||
| 812 | vlans => $data->{vlans}, | ||
| 813 | deferred_node_params => $data->{deferred_node_params}, | ||
| 814 | }, { layout => 'noop' }; | ||
| 815 | } | ||
| 816 | else { | ||
| 817 | header( 'Content-Type' => 'text/comma-separated-values' ); | ||
| 818 | template 'ajax/device/ports_csv.tt', { | ||
| 819 | results => $data->{results}, | ||
| 820 | nodes => $data->{nodes_name}, | ||
| 821 | ips => $data->{ips_name}, | ||
| 822 | device => $data->{device}, | ||
| 823 | vlans => $data->{vlans}, | ||
| 824 | }, { layout => 'noop' }; | ||
| 825 | } | ||
| 826 | }; | ||
| 827 | |||
| 828 | # one collapsed port's node list, fetched only when the caller opens it | ||
| 829 | get '/ajax/content/device/port/nodes' => require_login sub { | ||
| 830 | my $device = schema(vars->{'tenant'})->resultset('Device') | ||
| 831 | ->search_for_device(param('q')) or send_error('Bad device', 400); | ||
| 832 | my $port = param('port') or send_error('Bad port', 400); | ||
| 833 | my $row = $device->ports->find({ port => $port }) | ||
| 834 | or send_error('Bad port', 400); | ||
| 835 | |||
| 836 | my ($nodes_name, $ips_name, $node_order, $extra_prefetch) | ||
| 837 | = _node_display_options(); | ||
| 838 | |||
| 839 | _stitch_nodes(schema(vars->{'tenant'}), $device->ip, [$row], | ||
| 840 | $nodes_name, $ips_name, $node_order, $extra_prefetch, [$port]); | ||
| 841 | |||
| 842 | template 'ajax/device/port_nodes.tt', { | ||
| 843 | row => $row, device => $device, | ||
| 844 | }, { layout => 'noop' }; | ||
| 845 | }; | ||
| 846 | |||
| 847 | true; |