blib/lib/App/Netdisco/Web/Plugin/Device/Neighbors.pm untested

filter: Statementstmt 0.0% 0 / 236 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 129 MC/DCmcdc 0.0% 0 / 74 Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 551 CC 12 SCAR 33.2
CC
12
Cov
0%
make_node_infostring
72.0
netmap_view_params
20.0
neighbors_within_depth
6.0
CRAP 27.6
1 package App::Netdisco::Web::Plugin::Device::Neighbors;
2  
3 use Dancer ':syntax';
4 use Dancer::Plugin::Ajax;
5 use Dancer::Plugin::DBIC;
6 use Dancer::Plugin::Auth::Extensible;
7  
8 use List::Util 'first';
9 use List::MoreUtils ();
10 use HTML::Entities 'encode_entities';
11 use App::Netdisco::Util::Port 'to_speed';
12 use App::Netdisco::Util::Permission qw/acl_matches acl_matches_only/;
13 use App::Netdisco::Web::Plugin;
14  
15 register_device_tab({ tag => 'netmap', label => 'Neighbors' });
16  
17 ajax '/ajax/content/device/netmap' => require_login sub {
18 content_type('text/html');
19 template 'ajax/device/netmap.tt', {}, { layout => undef };
20 };
21  
22 ajax '/ajax/data/device/netmappositions' => require_login sub {
23 my $q = param('q');
24 my $qdev = schema(vars->{'tenant'})->resultset('Device')
25 ->search_for_device($q) or send_error('Bad device', 400);
26  
27 my $p = param('positions') or send_error('Missing positions', 400);
28 my $positions = from_json($p) or send_error('Bad positions', 400);
29 send_error('Bad positions', 400) unless ref [] eq ref $positions;
30  
31 my $vlan = param('vlan');
32 undef $vlan if (defined $vlan and $vlan !~ m/^\d+$/);
33  
34 my ($mapshow, $depth) = netmap_view_params(
35 param('mapshow'), param('depth'), $qdev->in_storage);
36  
37 # list of groups selected by user and passed in param
38 my $hgroup = (ref [] eq ref param('hgroup') ? param('hgroup') : [param('hgroup')]);
39 # list of groups validated as real host groups and named host groups
40 my @hgrplist = List::MoreUtils::uniq
41 grep { exists setting('host_group_displaynames')->{$_} }
42 grep { exists setting('host_groups')->{$_} }
43 grep { defined } @{ $hgroup };
44  
45 # list of locations selected by user and passed in param
46 my $lgroup = (ref [] eq ref param('lgroup') ? param('lgroup') : [param('lgroup')]);
47 my @lgrplist = List::MoreUtils::uniq grep { defined } @{ $lgroup };
48  
49 my %clean = ();
50 POSITION: foreach my $pos (@$positions) {
51 next unless ref {} eq ref $pos;
52 foreach my $k (qw/ID x y/) {
53 next POSITION unless exists $pos->{$k};
54 next POSITION unless $pos->{$k} =~ m/^[[:word:]\.-]+$/;
55 }
56 $clean{$pos->{ID}} = { x => $pos->{x}, y => $pos->{y} };
57 }
58 # Not a bare return: that answers the plugin's text/xml default with an
59 # empty body, which jQuery reads as a successful save.
60 send_error('Bad positions', 400) unless scalar keys %clean;
61  
62 my $posrow = schema(vars->{'tenant'})->resultset('NetmapPositions')->find({
63 device => ($mapshow ne 'all' ? $qdev->ip : undef),
64 depth => ($mapshow eq 'depth' ? $depth : 0),
65 host_groups => \[ '= ?', [host_groups => [sort @hgrplist]] ],
66 locations => \[ '= ?', [locations => [sort @lgrplist]] ],
67 vlan => ($vlan || 0),
68 });
69  
70 if ($posrow) {
71 $posrow->update({ positions => to_json(\%clean) });
72 }
73 else {
74 schema(vars->{'tenant'})->resultset('NetmapPositions')->create({
75 device => ($mapshow ne 'all' ? $qdev->ip : undef),
76 depth => ($mapshow eq 'depth' ? $depth : 0),
77 host_groups => [sort @hgrplist],
78 locations => [sort @lgrplist],
79 vlan => ($vlan || 0),
80 positions => to_json(\%clean),
81 });
82 }
83  
84 content_type('application/json');
85 return to_json({});
86 };
87  
88 sub make_node_infostring {
89 my $node = shift or return '';
90 my $fmt = ('<b>%s</b> is %s <b>%s %s</b><br>running <b>%s %s</b><br>Serial: <b>%s</b><br>'
91 .'Uptime: <b>%s</b><br>Location: <b>%s</b><br>Contact: <b>%s</b>');
92
93 my @field_values = ();
94 if (ref [] eq ref setting('netmap')->{'custom_fields'}->{device}) {
95 foreach my $field (@{ setting('netmap')->{'custom_fields'}->{device} }) {
96 foreach my $config (@{ setting('custom_fields')->{device} }) {
97 next unless $config->{'name'} and $config->{'name'} eq $field;
98  
99 next if $config->{json_list};
100 next if acl_matches($node->ip, ($config->{no} || []));
101 next unless acl_matches_only($node->ip, ($config->{only} || []));
102 $fmt .= sprintf '<br>%s: <b>%%s</b>', ($config->{label} || ucfirst($config->{name}));
103 push @field_values, ('cf_'. $config->{name});
104 }
105 }
106 }
107  
108 return sprintf $fmt, $node->ip,
109 ((($node->vendor || '') =~ m/^[aeiou]/i) ? 'an' : 'a'),
110 encode_entities(ucfirst($node->vendor || '')),
111 (map {defined $_ ? encode_entities($_) : ''}
112 map {$node->$_}
113 (qw/model os os_ver serial uptime_age location contact/)),
114 map {encode_entities($node->get_column($_) || '')} @field_values;
115 }
116  
117 # The devices within $passes hops of $root, breadth first over the adjacency
118 # map built from the deduplicated links. It replaces a nested rescan of every
119 # linked device once per hop, which cost the cloud size times the linked device
120 # count on each pass rather than being linear in the graph. Pure so that
121 # xt/45-netmap-neighbor-walk.t can check it against what it replaced without a
122 # database.
123 #
124 # An undefined $passes means no limit, which is what Neighbor Cloud asks for.
125 # It is not a synonym for a large number: the walk ends when the frontier
126 # empties, so a component longer than any number one might pick is still
127 # reached whole.
128 sub neighbors_within_depth {
129 my ($adjacency, $root, $passes) = @_;
130  
131 my %cloud = ($root => 1);
132 my @frontier = ($root);
133  
134 while (((not defined $passes) or $passes-- > 0) and scalar @frontier) {
135 my @next = ();
136 foreach my $ip (@frontier) {
137 foreach my $peer (@{ $adjacency->{$ip} || [] }) {
138 next if exists $cloud{$peer};
139 $cloud{$peer} = 1;
140 push @next, $peer;
141 }
142 }
143 @frontier = @next;
144 }
145  
146 return \%cloud;
147 }
148  
149 # Shared so the display and save routes cannot key a netmap_positions row
150 # differently. Pure, so it is checkable without a database.
151 sub netmap_view_params {
152 my ($mapshow, $depth, $in_storage) = @_;
153  
154 $mapshow = 'depth'
155 if !defined $mapshow or $mapshow !~ m/^(?:all|cloud|depth)$/;
156 $mapshow = 'all' unless $in_storage;
157  
158 $depth = 1 if !defined $depth or $depth !~ m/^\d+$/ or $depth < 1;
159  
160 return ($mapshow, $depth);
161 }
162  
163 sub make_link_infostring {
164 my $link = shift or return '';
165  
166 my $domains = setting('domain_suffix');
167 (my $left_name = lc($link->{left_dns} || $link->{left_name} || $link->{left_ip})) =~ s/$domains//;
168 (my $right_name = lc($link->{right_dns} || $link->{right_name} || $link->{right_ip})) =~ s/$domains//;
169  
170 my @zipped = List::MoreUtils::zip6
171 @{$link->{left_port}}, @{$link->{left_descr}},
172 @{$link->{right_port}}, @{$link->{right_descr}};
173  
174 return join '<br><br>', map { sprintf '<b>%s:%s</b> (%s)<br><b>%s:%s</b> (%s)',
175 encode_entities($left_name), encode_entities($_->[0]), encode_entities(($_->[1] || 'no description')),
176 encode_entities($right_name), encode_entities($_->[2]), encode_entities(($_->[3] || 'no description')) } @zipped;
177 }
178  
179 get '/ajax/data/device/netmap' => require_login sub {
180 my $q = param('q');
181 my $qdev = schema(vars->{'tenant'})->resultset('Device')
182 ->search_for_device($q) or send_error('Bad device', 400);
183  
184 my $vlan = param('vlan');
185 undef $vlan if (defined $vlan and $vlan !~ m/^\d+$/);
186  
187 my $colorby = (param('colorby') || 'speed');
188 my ($mapshow, $depth) = netmap_view_params(
189 param('mapshow'), param('depth'), $qdev->in_storage);
190  
191 # list of groups selected by user and passed in param
192 my $hgroup = (ref [] eq ref param('hgroup') ? param('hgroup') : [param('hgroup')]);
193 # list of groups validated as real host groups and named host groups
194 my @hgrplist = List::MoreUtils::uniq
195 grep { exists setting('host_group_displaynames')->{$_} }
196 grep { exists setting('host_groups')->{$_} }
197 grep { defined } @{ $hgroup };
198  
199 # list of locations selected by user and passed in param
200 my $lgroup = (ref [] eq ref param('lgroup') ? param('lgroup') : [param('lgroup')]);
201 my @lgrplist = List::MoreUtils::uniq grep { defined } @{ $lgroup };
202  
203 my %ok_dev = ();
204 my %logvals = ();
205 my %metadata = ();
206 my %data = ( nodes => [], links => [] );
207 my $domains = setting('domain_suffix');
208  
209 # LINKS
210  
211 my %seen_link = ();
212 my %adjacency = ();
213 my $links = schema(vars->{'tenant'})->resultset('Virtual::DeviceLinks')->search({
214 (($mapshow eq 'depth' and $depth == 1) ? ( -or => [
215 { left_ip => $qdev->ip },
216 { right_ip => $qdev->ip },
217 ]) : ())
218 }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' });
219  
220 while (my $link = $links->next) {
221 # query is ordered by aggregate speed desc so we see highest speed
222 # first, which is hopefully the "best" if links are not symmetric
223 next if exists $seen_link{$link->{left_ip} ."\0". $link->{right_ip}}
224 or exists $seen_link{$link->{right_ip} ."\0". $link->{left_ip}};
225  
226 push @{$data{'links'}}, {
227 FROMID => $link->{left_ip},
228 TOID => $link->{right_ip},
229 INFOSTRING => make_link_infostring($link),
230 SPEED => to_speed($link->{aggspeed}),
231 };
232  
233 ++$ok_dev{$link->{left_ip}};
234 ++$ok_dev{$link->{right_ip}};
235 ++$seen_link{$link->{left_ip} ."\0". $link->{right_ip}};
236  
237 # built here rather than in a second pass: the dedup above is what
238 # decides which links exist, so this is the only place that knows
239 push @{ $adjacency{ $link->{left_ip} } }, $link->{right_ip};
240 push @{ $adjacency{ $link->{right_ip} } }, $link->{left_ip};
241 }
242  
243 # filter by lldp cloud or depth
244  
245 my %cloud = ($qdev->ip => 1);
246  
247 if ($mapshow eq 'cloud' or ($mapshow eq 'depth' and $depth > 1)) {
248 %cloud = %{ neighbors_within_depth(\%adjacency, $qdev->ip,
249 ($mapshow eq 'cloud' ? undef : $depth)) };
250 }
251 elsif ($mapshow eq 'depth' and $depth == 1) {
252 # the link query above was already filtered to this device's own links
253 %cloud = %ok_dev;
254 }
255  
256 # DEVICES (NODES)
257  
258 my $posrow = schema(vars->{'tenant'})->resultset('NetmapPositions')->find({
259 device => ($mapshow ne 'all' ? $qdev->ip : undef),
260 depth => ($mapshow eq 'depth' ? $depth : 0),
261 host_groups => \[ '= ?', [host_groups => [sort @hgrplist]] ],
262 locations => \[ '= ?', [locations => [sort @lgrplist]] ],
263 vlan => ($vlan || 0),
264 });
265 my $pos_for = from_json( $posrow ? $posrow->positions : '{}' );
266  
267 my $devices = schema(vars->{'tenant'})->resultset('Device')->search({}, {
268 '+select' => [\'floor(log(throughput.total))'], '+as' => ['log'],
269 join => 'throughput', distinct => 1,
270 })->with_times;
271
272 $devices = $devices->with_custom_fields
273 if scalar @{ setting('netmap')->{'custom_fields'}->{'device'} };
274  
275 # filter by vlan for all or neighbors only
276 if ($vlan) {
277 $devices = $devices->search(
278 { 'port_vlans_filter.vlan' => $vlan },
279 { join => 'port_vlans_filter' }
280 );
281 }
282  
283 DEVICE: while (my $device = $devices->next) {
284 # if in neighbors mode then use %ok_dev to filter
285 next DEVICE if ($device->ip ne $qdev->ip)
286 and ($mapshow ne 'all')
287 and (not $cloud{$device->ip}); # showing only neighbors but no link
288  
289 # if location picked then filter
290 next DEVICE if ((scalar @lgrplist) and ((!defined $device->location)
291 or (0 == scalar grep {$_ eq $device->location} @lgrplist)));
292  
293 # if host groups picked then use ACLs to filter
294 my $first_hgrp =
295 first { acl_matches($device, setting('host_groups')->{$_}) } @hgrplist;
296 next DEVICE if ((scalar @hgrplist) and (not $first_hgrp));
297  
298 # now reset first_hgroup to be the group matching the device, if any
299 $first_hgrp = first { acl_matches($device, setting('host_groups')->{$_}) }
300 keys %{ setting('host_group_displaynames') || {} };
301  
302 ++$logvals{ $device->get_column('log') || 1 };
303 (my $name = lc($device->dns || $device->name || $device->ip)) =~ s/$domains//;
304  
305 my %color_lkp = (
306 speed => (($device->get_column('log') || 1) * 1000),
307 hgroup => ($first_hgrp ?
308 setting('host_group_displaynames')->{$first_hgrp} : 'Other'),
309 lgroup => ($device->location || 'Other'),
310 );
311  
312 my $node = {
313 ID => $device->ip,
314 SIZEVALUE => (param('dynamicsize') ? $color_lkp{speed} : 3000),
315 ((exists $color_lkp{$colorby}) ? (COLORVALUE => $color_lkp{$colorby}) : ()),
316 (($device->ip eq $qdev->ip) ? (COLORVALUE => 'ROOTNODE') : ()),
317 # kept for consumers of the JSON; the map draws ORIG_LABEL and ID
318 LABEL => (param('showips') ? ($device->ip .' '. $name) : $name),
319 ORIG_LABEL => $name,
320 INFOSTRING => make_node_infostring($device),
321 LINK => uri_for('/device', {
322 tab => 'netmap',
323 q => $device->ip,
324 firstsearch => 'on',
325 })->path_query,
326 };
327  
328 if (exists $pos_for->{$device->ip}) {
329 $node->{'fixed'} = 1;
330 $node->{'x'} = $pos_for->{$device->ip}->{'x'};
331 $node->{'y'} = $pos_for->{$device->ip}->{'y'};
332 }
333 else {
334 ++$metadata{'newnodes'};
335 }
336  
337 push @{$data{'nodes'}}, $node;
338 $metadata{'centernode'} = $device->ip
339 if $qdev and $qdev->in_storage and $device->ip eq $qdev->ip;
340 }
341  
342 # to help get a sensible range of node sizes
343 $metadata{'numsizes'} = scalar keys %logvals;
344  
345 content_type('application/json');
346 to_json({ data => \%data, %metadata });
347 };
348  
349 true;