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

filter: Statementstmt 0.0% 0 / 160 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 73 MC/DCmcdc 0.0% 0 / 46 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 347 CC 12 SCAR 28.1
CC
12
Cov
0%
_get_snmp_data
42.0
_snmp_icon
30.0
_snmp_node_stash
12.0
CRAP 16.6
1 package App::Netdisco::Web::Plugin::Device::SNMP;
2  
3 use strict;
4 use warnings;
5  
6 use Dancer qw(:syntax);
7 use Dancer::Plugin::Ajax;
8 use Dancer::Plugin::DBIC;
9 use Dancer::Plugin::Swagger;
10 use Dancer::Plugin::Auth::Extensible;
11  
12 use App::Netdisco::Web::Plugin;
13 use App::Netdisco::Util::SNMP 'decode_and_munge';
14 use HTML::Entities 'encode_entities';
15 use Module::Load ();
16 use Try::Tiny;
17  
18 register_device_tab({ tag => 'snmp', label => 'SNMP' });
19  
20 get '/ajax/content/device/snmp' => require_login sub {
21 my $device = try { schema(vars->{'tenant'})->resultset('Device')
22 ->search_for_device( param('q') ) }
23 or send_error('Bad Device', 404);
24  
25 template 'ajax/device/snmp.tt',
26 { device => $device->ip, tree => _get_snmp_data($device->ip, '.1') },
27 { layout => 'noop' };
28 };
29  
30 # Declared with get rather than the ajax keyword, which matches only a request
31 # carrying X-Requested-With. htmx sends HX-Request instead, and the tab forms in
32 # the page shell compensate with an hx-headers attribute; a tree emits one
33 # fetching element per node, so repeating that string there would be thousands
34 # of copies of a constant.
35 get '/ajax/content/device/:ip/snmptree/:base' => require_login sub {
36 my $device = try { schema(vars->{'tenant'})->resultset('Device')
37 ->find( param('ip') ) }
38 or send_error('Bad Device', 404);
39  
40 my $base = param('base');
41 $base =~ m/^\.1(\.\d+)*$/ or send_error('Bad OID Base', 404);
42  
43 # Dancer::Plugin::Ajax stamps text/xml on anything declared with its
44 # keyword, and htmx will not swap a response typed that way: the request is
45 # made, the answer is discarded, and nothing reports it.
46 content_type 'text/html';
47  
48 return _snmp_placeholder(
49 'No data for this device. Admins can request a snapshot in the Details tab.')
50 unless $device->oids->count;
51  
52 # snapshot should run a loadmibs, but just in case that didn't happen...
53 return _snmp_placeholder('No MIB objects. Please run a loadmibs job.')
54 unless schema(vars->{'tenant'})->resultset('SNMPObject')->count();
55  
56 template 'ajax/device/snmptree.tt',
57 { device => $device->ip, nodes => _get_snmp_data($device->ip, $base) },
58 { layout => 'noop' };
59 };
60  
61 # The two states where there is nothing to browse. One inert row, so the reason
62 # reaches the reader where the tree would have been.
63 # The icon beside the search box, swapped out of band so the three states the
64 # widget this replaced drew in JavaScript survive without any.
65 sub _snmp_state_icon {
66 return sprintf '<i id="nd_snmp_loading_spinner" hx-swap-oob="true" class="%s"></i>',
67 encode_entities(shift);
68 }
69  
70 sub _snmp_placeholder {
71 return sprintf '<li class="nd_snmp-empty">'
72 .'<i class="fas fa-magnifying-glass"></i>%s</li>',
73 encode_entities(shift);
74 }
75  
76 ajax '/ajax/data/snmp/typeahead' => require_login sub {
77 my $term = param('term') or return to_json [];
78  
79 my $device = param('ip');
80 my $deviceonly = param('deviceonly');
81 my ($mib, $leaf) = split m/::/, $term;
82  
83 my @found = schema(vars->{'tenant'})->resultset('SNMPObject')
84 ->search({ -or => [ 'me.oid' => $term,
85 'me.oid' => { -like => ($term .'.%') },
86 -and => [(($mib and $leaf) ? ('me.mib' => $mib, 'me.leaf' => { -ilike => ($leaf .'%') })
87 : ('me.leaf' => { -ilike => ('%'. $term .'%') }))] ],
88 (($device and $deviceonly) ? ('device_browser.ip' => $device, 'device_browser.value' => { -not => undef }) : ()) },
89 { select => [\q{ me.mib || '::' || me.leaf }],
90 as => ['qleaf'],
91 join => 'device_browser',
92 rows => 25, order_by => 'me.oid_parts' })
93 ->get_column('qleaf')->all;
94  
95 return to_json [] unless scalar @found;
96  
97 content_type 'application/json';
98 to_json [ sort @found ];
99 };
100  
101 get '/ajax/content/device/:ip/snmpsearch' => require_login sub {
102 # the search box is named term, which is also what the typeahead beside it
103 # sends; str is what the tree widget this replaced used
104 my $to_match = (param('term') || param('str')) or return '';
105 my $partial = param('partial');
106 my $device = param('ip');
107 my $deviceonly = param('deviceonly');
108  
109 # Dancer::Plugin::Ajax stamps text/xml on anything declared with its
110 # keyword, and htmx will not swap a response typed that way: the request is
111 # made, the answer is discarded, and nothing reports it.
112 content_type 'text/html';
113  
114 my ($mib, $leaf) = split m/::/, $to_match;
115 my $found = undef;
116  
117 if ($partial) {
118 $found = schema(vars->{'tenant'})->resultset('SNMPObject')
119 ->search({ -or => [ 'me.oid' => $to_match,
120 'me.oid' => { -like => ($to_match .'.%') },
121 -and => [(($mib and $leaf) ? ('me.mib' => $mib, 'me.leaf' => { -ilike => ($leaf .'%') })
122 : ('me.leaf' => { -ilike => ($to_match .'%') }))] ],
123 (($device and $deviceonly) ? ('device_browser.ip' => $device, 'device_browser.value' => { -not => undef }) : ()),
124 }, { rows => 1, join => 'device_browser', order_by => 'oid_parts' })->first;
125 }
126 else {
127 $found = schema(vars->{'tenant'})->resultset('SNMPObject')
128 ->search({
129 (($mib and $leaf) ? (-and => ['me.mib' => $mib, 'me.leaf' => $leaf])
130 : (-or => ['me.oid' => $to_match, 'me.leaf' => $to_match])),
131 (($device and $deviceonly) ? ('device_browser.ip' => $device, 'device_browser.value' => { -not => undef }) : ()),
132 },{ rows => 1, join => 'device_browser', order_by => 'oid_parts' })->first;
133 }
134 # Nothing matched, so the tree the reader is looking at is left exactly as
135 # it is and only the state icon changes. htmx swaps nothing when a response
136 # holds only out of band content, but the box aims at the tree, so the
137 # header says so rather than leaving it to that.
138 if (!$found) {
139 header 'HX-Reswap' => 'none';
140 return _snmp_state_icon('fas fa-circle-exclamation fa-lg');
141 }
142  
143 $found = $found->oid;
144 $found =~ s/^\.1\.?//;
145 my @results = ('.1');
146  
147 foreach my $part (split m/\./, $found) {
148 my $last = $results[-1];
149 push @results, "${last}.${part}";
150 }
151  
152 # The whole path in one response. The widget this replaced took this same
153 # list and opened it a level at a time, one request each, and then fetched
154 # the panel twice on top of that.
155 my $tree = template 'ajax/device/snmptree.tt',
156 { device => $device,
157 nodes => _get_snmp_data($device, '.1', \@results) },
158 { layout => 'noop' };
159  
160 # The panel for the hit rides along out of band, so choosing a search result
161 # costs nothing beyond the tree it opened.
162 my $icon = _snmp_state_icon('far fa-circle fa-lg text-success');
163 my $stash = _snmp_node_stash($device, $results[-1]);
164 return $tree . $icon unless $stash;
165  
166 my $detail = template 'ajax/device/snmpnode.tt', $stash, { layout => 'noop' };
167 return $tree .'<div id="node" hx-swap-oob="true">'. $detail .'</div>'. $icon;
168 };
169  
170 get '/ajax/content/device/:ip/snmpnode/:oid' => require_login sub {
171 my $device = try { schema(vars->{'tenant'})->resultset('Device')
172 ->find( param('ip') ) }
173 or send_error('Bad Device', 404);
174  
175 my $oid = param('oid');
176 $oid =~ m/^\.1(\.\d+)*$/ or send_error('Bad OID', 404);
177  
178 my $stash = _snmp_node_stash($device->ip, $oid, param('munge'))
179 or send_error('Bad OID', 404);
180  
181 content_type 'text/html';
182 template 'ajax/device/snmpnode.tt', $stash, { layout => 'noop' };
183 };
184  
185 # Everything the detail panel needs for one node. The search route renders the
186 # same panel for its hit, so this lives apart from the route that serves it.
187 sub _snmp_node_stash {
188 my ($ip, $oid, $munge) = @_;
189  
190 my $object = schema(vars->{'tenant'})->resultset('SNMPObject')
191 ->find({'me.oid' => $oid},
192 {join => ['snmp_filter'], prefetch => ['snmp_filter']})
193 or return undef;
194  
195 $munge ||= ($object->snmp_filter ? $object->snmp_filter->subname : undef);
196  
197 # this is a bit lazy, could be a join on above with some effort
198 my $value = schema(vars->{'tenant'})->resultset('DeviceBrowser')
199 ->search({-and => [-bool => \q{ array_length(oid_parts, 1) IS NOT NULL },
200 -bool => \q{ jsonb_typeof(value) = 'array' }]})
201 ->find({'me.oid' => $oid, 'me.ip' => $ip});
202  
203 my %data = (
204 $object->get_columns,
205 snmp_object => { $object->get_columns },
206 value => ( defined $value ? decode_and_munge( $munge, $value->value ) : undef ),
207 );
208  
209 my @mungers = schema(vars->{'tenant'})->resultset('SNMPFilter')
210 ->search({},{ distinct => 1, order_by => 'subname' })
211 ->get_column('subname')->all;
212  
213 return { node => \%data, munge => $munge, mungers => \@mungers,
214 device => $ip, oid => $oid };
215 }
216  
217 sub _get_snmp_data {
218 my ($ip, $base, $open_to) = @_;
219 my @parts = grep {length} split m/\./, $base;
220 my %open = map {($_ => 1)} @{ $open_to || [] };
221  
222 # Only a search passes a path, and its last step is the node that matched.
223 my $hit = (scalar @{ $open_to || [] }) ? $open_to->[-1] : '';
224  
225 my %meta = map { ('.'. join '.', @{$_->{oid_parts}}) => $_ }
226 schema(vars->{'tenant'})->resultset('Virtual::FilteredSNMPObject')
227 ->search({}, { bind => [
228 $ip,
229 (scalar @parts + 1),
230 (scalar @parts + 1),
231 $base,
232 ] })->hri->all;
233  
234 my @items = map {
235 my $oid = $_;
236 my $row = $meta{$oid};
237 my $has_children = ($row->{num_children} ? 1 : 0);
238  
239 # Open a node the search asked for, and keep the older rule that a node
240 # with data and a single child opens itself so the child is not hidden
241 # behind one more click.
242 my $open = ($has_children and ($open{$oid}
243 or ($row->{browser} and $row->{num_children} == 1))) ? 1 : 0;
244  
245 {
246 oid => $oid,
247 label => ($row->{leaf} .' ('. $row->{oid_parts}->[-1] .')'),
248 icon => _snmp_icon($row),
249 has_children => $has_children,
250 found => (($hit and $oid eq $hit) ? 1 : 0),
251 open => $open,
252 children => ($open ? _get_snmp_data($ip, $oid, $open_to) : []),
253 }
254 } sort {$meta{$a}->{oid_parts}->[-1] <=> $meta{$b}->{oid_parts}->[-1]} keys %meta;
255  
256 return \@items;
257 }
258  
259 # A folder unless the row is a table or a leaf, and muted unless this device
260 # has a value for it.
261 sub _snmp_icon {
262 my $row = shift;
263 my $lit = ($row->{browser} ? ' text-info' : ' text-muted');
264  
265 return 'fas fa-table-cells'. $lit if scalar @{ $row->{index} };
266  
267 return 'fas fa-leaf'. $lit
268 if $row->{num_children} == 0
269 and ($row->{type} or $row->{access} =~ m/^(?:read|write)/
270 or $row->{oid_parts}->[-1] == 0);
271  
272 return $row->{browser} ? 'fas fa-folder text-info' : 'far fa-folder text-muted';
273 }
274  
275 true;