blib/lib/App/Netdisco/Web/API/Objects.pm untested

filter: Statementstmt 0.0% 0 / 180 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 73 MC/DCmcdc 0.0% 0 / 42 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 350 CC 7 SCAR 19.9
CC
7
Cov
0%
_node_includes
12.0
_node_to_json
12.0
_bool_param
12.0
CRAP 7.3
1 package App::Netdisco::Web::API::Objects;
2  
3 use Dancer ':syntax';
4 use Dancer::Plugin::DBIC;
5 use Dancer::Plugin::Swagger;
6 use Dancer::Plugin::Auth::Extensible;
7  
8 use App::Netdisco::JobQueue 'jq_insert';
9 use Try::Tiny;
10 use URI::Escape 'uri_unescape';
11  
12 sub _port_param { my $s = uri_unescape(shift // ''); $s =~ s/^\s+|\s+$//g; $s }
13  
14 # Node relations a caller may pull in alongside the node rows themselves.
15 # The value says whether the relation yields a list. "oui" is deliberately
16 # absent: Node has both a column and a relation of that name, and the
17 # accessor collision is exactly what the TO_JSON override in
18 # App::Netdisco::DB::Result guards against.
19 my %NODE_INCLUDES = (
20 wireless => 1, # node_wireless - SSID, signal, rates
21 ips => 1, # node_ip
22 netbios => 0, # node_nbt
23 manufacturer => 0, # vendor looked up from the OUI
24 );
25  
26 sub _node_includes {
27 my $val = shift;
28 return () unless defined $val and length $val;
29 my @asked = grep { length } map { s/^\s+|\s+$//gr } split /,/, $val;
30 if (my @bad = grep { ! exists $NODE_INCLUDES{$_} } @asked) {
31 send_error((sprintf 'Bad include "%s". Valid: %s',
32 (join ',', @bad), (join ',', sort keys %NODE_INCLUDES)), 400);
33 }
34 return @asked;
35 }
36  
37 # TO_JSON returns own columns only, so fold in the requested relations here
38 sub _node_to_json {
39 my ($row, @includes) = @_;
40 my $data = $row->TO_JSON;
41 # extra +columns such as those from with_port_context
42 my %cols = $row->get_columns;
43 $data->{$_} = $cols{$_} for grep { not $row->result_source->has_column($_) } keys %cols;
44 foreach my $rel (@includes) {
45 if ($NODE_INCLUDES{$rel}) {
46 $data->{$rel} = [ map { $_->TO_JSON } $row->$rel->all ];
47 }
48 else {
49 my $one = $row->$rel;
50 $data->{$rel} = $one ? $one->TO_JSON : undef;
51 }
52 }
53 return $data;
54 }
55  
56 # query params always arrive as strings, so accept the usual spellings of a
57 # boolean and fall back to the default documented in the swagger_path
58 sub _bool_param {
59 my ($val, $default) = @_;
60 return $default unless defined $val and length $val;
61 return ($val =~ m/^(?:1|y|yes|t|true|on)$/i) ? 1 : 0;
62 }
63  
64 swagger_path {
65 tags => ['Objects'],
66 path => (setting('api_base') || '').'/object/device/{ip}',
67 description => 'Returns a row from the device table',
68 parameters => [
69 ip => {
70 description => 'Canonical IP of the Device. Use Search methods to find this.',
71 required => 1,
72 in => 'path',
73 },
74 ],
75 responses => { default => {} },
76 }, get '/api/v1/object/device/:ip' => require_role api => sub {
77 my $device = try { schema(vars->{'tenant'})->resultset('Device')
78 ->find( params->{ip} ) } or send_error('Bad Device', 404);
79  
80 my $data = $device->TO_JSON;
81  
82 my @modules = try {
83 schema(vars->{'tenant'})->resultset('DevicePower')
84 ->search({ 'me.ip' => $device->ip })->with_poestats->hri->all;
85 } catch { () };
86  
87 if (@modules) {
88 my %totals = (
89 modules => scalar @modules,
90 power_total => 0,
91 poe_capable_ports => 0,
92 poe_powered_ports => 0,
93 poe_disabled_ports => 0,
94 poe_errored_ports => 0,
95 poe_power_committed => 0,
96 poe_power_delivering => 0,
97 );
98 for my $m (@modules) {
99 $totals{power_total} += $m->{power} // 0;
100 $totals{poe_capable_ports} += $m->{poe_capable_ports} // 0;
101 $totals{poe_powered_ports} += $m->{poe_powered_ports} // 0;
102 $totals{poe_disabled_ports} += $m->{poe_disabled_ports} // 0;
103 $totals{poe_errored_ports} += $m->{poe_errored_ports} // 0;
104 $totals{poe_power_committed} += $m->{poe_power_committed} // 0;
105 $totals{poe_power_delivering} += $m->{poe_power_delivering} // 0;
106 }
107 $data->{poe} = \%totals;
108 } else {
109 $data->{poe} = undef;
110 }
111  
112 return to_json $data;
113 };
114  
115 foreach my $rel (qw/device_ips vlans ports modules port_vlans wireless_ports ssids powered_ports/) {
116 swagger_path {
117 tags => ['Objects'],
118 path => (setting('api_base') || '')."/object/device/{ip}/$rel",
119 description => "Returns $rel rows for a given device",
120 parameters => [
121 ip => {
122 description => 'Canonical IP of the Device. Use Search methods to find this.',
123 required => 1,
124 in => 'path',
125 },
126 ],
127 responses => { default => {} },
128 }, get "/api/v1/object/device/:ip/$rel" => require_role api => sub {
129 my $rows = try { schema(vars->{'tenant'})->resultset('Device')
130 ->find( params->{ip} )->$rel } or send_error('Bad Device', 404);
131 return to_json [ map {$_->TO_JSON} $rows->all ];
132 };
133 }
134  
135 swagger_path {
136 tags => ['Objects'],
137 path => (setting('api_base') || '').'/object/device/{ip}/power_modules',
138 description => 'Returns PoE module status and aggregated port statistics for a given device',
139 parameters => [
140 ip => {
141 description => 'Canonical IP of the Device. Use Search methods to find this.',
142 required => 1,
143 in => 'path',
144 },
145 ],
146 responses => { default => {} },
147 }, get '/api/v1/object/device/:ip/power_modules' => require_role api => sub {
148 my $device = try { schema(vars->{'tenant'})->resultset('Device')
149 ->find( params->{ip} ) } or send_error('Bad Device', 404);
150 my @rows = try {
151 schema(vars->{'tenant'})->resultset('DevicePower')
152 ->search({ 'me.ip' => $device->ip })->with_poestats->hri->all;
153 } catch { () };
154 return to_json \@rows;
155 };
156  
157 swagger_path {
158 tags => ['Objects'],
159 path => setting('api_base')."/object/device/{ip}/neighbors",
160 description => 'Returns layer 2 neighbor relation data for a given device',
161 parameters => [
162 ip => {
163 description => 'Canonical IP of the Device. Use Search methods to find this.',
164 required => 1,
165 in => 'path',
166 },
167 scope => {
168 description => 'Scope of results, either "all", "cloud" (LLDP cloud), or "depth" (uses hops)',
169 default => 'depth',
170 in => 'query',
171 },
172 hops => {
173 description => 'When specifying Scope "depth", this is the number of hops',
174 default => '1',
175 in => 'query',
176 },
177 vlan => {
178 description => 'Limit results to devices carrying this numeric VLAN ID',
179 },
180 ],
181 responses => { default => {} },
182 }, get "/api/v1/object/device/:ip/neighbors" => require_role api => sub {
183 forward "/ajax/data/device/netmap", {
184 q => params->{'ip'},
185 depth => params->{'hops'},
186 mapshow => params->{'scope'},
187 };
188 };
189  
190 swagger_path {
191 tags => ['Objects'],
192 path => (setting('api_base') || '').'/object/device/{ip}/jobs',
193 description => 'Delete jobs and clear skiplist for a device, optionally filtered by fields',
194 parameters => [
195 ip => {
196 description => 'Canonical IP of the Device. Use Search methods to find this.',
197 required => 1,
198 in => 'path',
199 },
200 port => {
201 description => 'Port field of the Job',
202 },
203 action => {
204 description => 'Action field of the Job',
205 },
206 status => {
207 description => 'Status field of the Job',
208 },
209 username => {
210 description => 'Username of the Job submitter',
211 },
212 userip => {
213 description => 'IP address of the Job submitter',
214 },
215 backend => {
216 description => 'Backend instance assigned the Job',
217 },
218 ],
219 responses => { default => {} },
220 }, del '/api/v1/object/device/:ip/jobs' => require_role api_admin => sub {
221 my $device = try { schema(vars->{'tenant'})->resultset('Device')
222 ->find( params->{ip} ) } or send_error('Bad Device', 404);
223  
224 my $gone = schema(vars->{'tenant'})->resultset('Admin')->search({
225 device => param('ip'),
226 ( param('port') ? ( port => param('port') ) : () ),
227 ( param('action') ? ( action => param('action') ) : () ),
228 ( param('status') ? ( status => param('status') ) : () ),
229 ( param('username') ? ( username => param('username') ) : () ),
230 ( param('userip') ? ( userip => param('userip') ) : () ),
231 ( param('backend') ? ( backend => param('backend') ) : () ),
232 })->delete;
233  
234 schema(vars->{'tenant'})->resultset('DeviceSkip')->search({
235 device => param('ip'),
236 ( param('action') ? ( actionset => { '&&' => \[ 'ARRAY[?]', param('action') ] } ) : () ),
237 ( param('backend') ? ( backend => param('backend') ) : () ),
238 })->delete;
239  
240 # DBI reports "no rows" as the true string "0E0", which slips past the ||
241 # and reached clients as {"deleted":"0E0"}; numify so it is always a number
242 return to_json { deleted => 0 + ($gone || 0) };
243 };
244  
245 foreach my $rel (qw/nodes active_nodes nodes_with_age active_nodes_with_age port_vlans vlans logs ssid/) {
246 swagger_path {
247 tags => ['Objects'],
248 description => "Returns $rel rows for a given port",
249 path => (setting('api_base') || '')."/object/device/{ip}/port/{port}/$rel",
250 parameters => [
251 ip => {
252 description => 'Canonical IP of the Device. Use Search methods to find this.',
253 required => 1,
254 in => 'path',
255 },
256 port => {
257 description => 'Name of the port. Use the ".../device/{ip}/ports" method to find these.',
258 required => 1,
259 in => 'path',
260 },
261 ],
262 responses => { default => {} },
263 }, get qr{/api/v1/object/device/(?<ip>[^/]+)/port/(?<port>.+)/${rel}$} => require_role api => sub {
264 my $params = captures;
265 my $rows = try { schema(vars->{'tenant'})->resultset('DevicePort')
266 ->find( _port_param($$params{port}), uri_unescape($$params{ip}) )->$rel }
267 or send_error('Bad Device or Port', 404);
268 return to_json [ map {$_->TO_JSON} $rows->all ];
269 };
270 }
271  
272 foreach my $rel (qw/power properties wireless agg_master neighbor last_node/) {
273 swagger_path {
274 tags => ['Objects'],
275 description => "Returns the related $rel table entry for a given port",
276 path => (setting('api_base') || '')."/object/device/{ip}/port/{port}/$rel",
277 parameters => [
278 ip => {
279 description => 'Canonical IP of the Device. Use Search methods to find this.',
280 required => 1,
281 in => 'path',
282 },
283 port => {
284 description => 'Name of the port. Use the ".../device/{ip}/ports" method to find these.',
285 required => 1,
286 in => 'path',
287 },
288 ],
289 responses => { default => {} },
290 }, get qr{/api/v1/object/device/(?<ip>[^/]+)/port/(?<port>.+)/${rel}$} => require_role api => sub {
291 my $params = captures;
292 my $row = try { schema(vars->{'tenant'})->resultset('DevicePort')
293 ->find( _port_param($$params{port}), uri_unescape($$params{ip}) )->$rel }
294 or send_error('Bad Device or Port', 404);
295 return to_json $row->TO_JSON;
296 };
297 }
298  
299 # must come after the port methods above, so the route matches later
300 swagger_path {
301 tags => ['Objects'],
302 description => 'Returns a row from the device_port table',
303 path => (setting('api_base') || '').'/object/device/{ip}/port/{port}',
304 parameters => [
305 ip => {
306 description => 'Canonical IP of the Device. Use Search methods to find this.',
307 required => 1,
308 in => 'path',
309 },
310 port => {
311 description => 'Name of the port. Use the ".../device/{ip}/ports" method to find these.',
312 required => 1,
313 in => 'path',
314 },
315 ],
316 responses => { default => {} },
317 }, get qr{/api/v1/object/device/(?<ip>[^/]+)/port/(?<port>.+)$} => require_role api => sub {
318 my $params = captures;
319 my $port = try { schema(vars->{'tenant'})->resultset('DevicePort')
320 ->find( _port_param($$params{port}), uri_unescape($$params{ip}) ) }
321 or send_error('Bad Device or Port', 404);
322 return to_json $port->TO_JSON;
323 };
324  
325 swagger_path {
326 tags => ['Objects'],
327 path => (setting('api_base') || '').'/object/device/{ip}/nodes',
328 description => "Returns the nodes found on a given Device",
329 parameters => [
330 ip => {
331 description => 'Canonical IP of the Device. Use Search methods to find this.',
332 required => 1,
333 in => 'path',
334 },
335 active_only => {
336 description => 'Restrict results to active Nodes only',
337 type => 'boolean',
338 default => 'true',
339 in => 'query',
340 },
341 include => {
342 description => 'Comma-separated list of related rows to embed in each Node: wireless (node_wireless - SSID, signal, rates), ips (node_ip), netbios (node_nbt), manufacturer (vendor from the OUI). Omitted by default.',
343 type => 'string',
344 in => 'query',
345 },
346 port_context => {
347 description => 'Include topology context of each Node\'s switch port (uplink, neighbor, LAG, node count)',
348 type => 'boolean',
349 default => 'false',
350 in => 'query',
351 },
352 ],
353 responses => { default => {} },
354 }, get '/api/v1/object/device/:ip/nodes' => require_role api => sub {
355 my $active = _bool_param(params->{active_only}, 1);
356 my @includes = _node_includes(params->{include});
357 # qualified, because prefetching ips or netbios joins tables that have
358 # an active column of their own
359 my $rows = try { schema(vars->{'tenant'})->resultset('Node')
360 ->search({ 'me.switch' => params->{ip}, ($active ? (-bool => 'me.active') : ()) },
361 (@includes ? { prefetch => [@includes] } : ())) }
362 or send_error('Bad Device', 404);
363 $rows = $rows->with_port_context if _bool_param(params->{port_context}, 0);
364 return to_json [ map { _node_to_json($_, @includes) } $rows->all ];
365 };
366  
367 swagger_path {
368 tags => ['Objects'],
369 path => (setting('api_base') || '').'/object/device/{ip}/nodes',
370 description => "Queue a job to store the nodes found on a given Device",
371 parameters => [
372 ip => {
373 description => 'Canonical IP of the Device. Use Search methods to find this.',
374 required => 1,
375 in => 'path',
376 },
377 nodes => {
378 description => 'List of node tuples (port, VLAN, MAC)',
379 default => '[]',
380 schema => {
381 type => 'array',
382 items => {
383 type => 'object',
384 properties => {
385 port => {
386 type => 'string'
387 },
388 vlan => {
389 type => 'integer',
390 default => '1'
391 },
392 mac => {
393 type => 'string'
394 }
395 }
396 }
397 },
398 in => 'body',
399 },
400 ],
401 responses => { default => {} },
402 }, put '/api/v1/object/device/:ip/nodes' => require_role setting('defanged_api_admin') => sub {
403  
404 jq_insert([{
405 action => 'macsuck',
406 device => params->{ip},
407 subaction => request->body,
408 username => session('logged_in_user'),
409 userip => request->remote_address,
410 }]);
411  
412 return to_json {};
413 };
414  
415 swagger_path {
416 tags => ['Objects'],
417 path => (setting('api_base') || '').'/object/vlan/{vlan}/nodes',
418 description => "Returns the nodes found in a given VLAN",
419 parameters => [
420 vlan => {
421 description => 'VLAN number',
422 type => 'integer',
423 required => 1,
424 in => 'path',
425 },
426 active_only => {
427 description => 'Restrict results to active Nodes only',
428 type => 'boolean',
429 default => 'true',
430 in => 'query',
431 },
432 include => {
433 description => 'Comma-separated list of related rows to embed in each Node: wireless (node_wireless - SSID, signal, rates), ips (node_ip), netbios (node_nbt), manufacturer (vendor from the OUI). Omitted by default.',
434 type => 'string',
435 in => 'query',
436 },
437 ],
438 responses => { default => {} },
439 }, get '/api/v1/object/vlan/:vlan/nodes' => require_role api => sub {
440 my $active = _bool_param(params->{active_only}, 1);
441 my @includes = _node_includes(params->{include});
442 # qualified, because prefetching ips or netbios joins tables that have
443 # an active column of their own
444 my $rows = try { schema(vars->{'tenant'})->resultset('Node')
445 ->search({ 'me.vlan' => params->{vlan}, ($active ? (-bool => 'me.active') : ()) },
446 (@includes ? { prefetch => [@includes] } : ())) }
447 or send_error('Bad VLAN', 404);
448 return to_json [ map { _node_to_json($_, @includes) } $rows->all ];
449 };
450  
451 swagger_path {
452 tags => ['Objects'],
453 path => (setting('api_base') || '').'/object/device/{ip}/arps',
454 description => "Queue a job to store the ARP entries found on a given Device",
455 parameters => [
456 ip => {
457 description => 'Canonical IP of the Device. Use Search methods to find this.',
458 required => 1,
459 in => 'path',
460 },
461 arps => {
462 description => 'List of arp tuples (MAC, IP, DNS?). IPs will be resolved to FQDN by Netdisco.',
463 default => '[]',
464 schema => {
465 type => 'array',
466 items => {
467 type => 'object',
468 properties => {
469 mac => {
470 type => 'string',
471 required => 1,
472 },
473 ip => {
474 type => 'string',
475 required => 1,
476 },
477 dns => {
478 type => 'string',
479 required => 0,
480 }
481 }
482 }
483 },
484 in => 'body',
485 },
486 ],
487 responses => { default => {} },
488 }, put '/api/v1/object/device/:ip/arps' => require_role setting('defanged_api_admin') => sub {
489  
490 jq_insert([{
491 action => 'arpnip',
492 device => params->{ip},
493 subaction => request->body,
494 username => session('logged_in_user'),
495 userip => request->remote_address,
496 }]);
497  
498 return to_json {};
499 };
500  
501 true;