blib/lib/App/Netdisco/Web/Metrics.pm untested

filter: Statementstmt 0.0% 0 / 242 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 32 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 328 CC 2 SCAR 10.6
CC
2
Cov
0%
_sample
6.0
_header
2.0
BEGIN
2.0
CRAP 2.9
1 package App::Netdisco::Web::Metrics;
2  
3 use Dancer ':syntax';
4 use Dancer::Plugin::DBIC;
5  
6 use App::Netdisco::Util::Permission qw/acl_matches_only/;
7 use App::Netdisco::Util::Web
8 qw/trusted_client_address warn_forwarded_address_ignored/;
9 use POSIX 'floor';
10 use Try::Tiny;
11  
12 sub _header {
13 my ($name, $help) = @_;
14 return sprintf("# HELP %s %s\n# TYPE %s gauge\n", $name, $help, $name);
15 }
16  
17 sub _sample {
18 my ($name, $value, %labels) = @_;
19 my $label_str = '';
20 if (%labels) {
21 $label_str = '{'. join(',', map { qq($_="$labels{$_}") } sort keys %labels) .'}';
22 }
23 return sprintf("%s%s %s\n", $name, $label_str, $value // 0);
24 }
25  
26 if (my $metrics_path = setting('metrics_path')) {
27  
28 # Both restrictions below are optional, so this endpoint can be published with
29 # neither. Warns rather than dies: a misconfiguration should not become an
30 # outage.
31 warning 'metrics_path is set with neither metrics_allow nor metrics_token,'
32 . ' so the metrics endpoint is served to anyone who can reach it'
33 unless (setting('metrics_allow') and scalar @{ setting('metrics_allow') })
34 or setting('metrics_token');
35  
36 get $metrics_path => sub {
37 # Optional IP range restriction
38 my $allow = setting('metrics_allow');
39 if ($allow and ref $allow eq ref []) {
40 my $remote = trusted_client_address();
41 unless (acl_matches_only($remote, $allow)) {
42 warn_forwarded_address_ignored('metrics_allow');
43 status 403;
44 return 'Forbidden';
45 }
46 }
47  
48 # Optional bearer token auth
49 my $token = setting('metrics_token');
50 if ($token) {
51 my $auth = request->header('Authorization') // '';
52 unless ($auth eq "Bearer $token") {
53 status 401;
54 header 'WWW-Authenticate' => 'Bearer realm="netdisco metrics"';
55 return 'Unauthorized';
56 }
57 }
58  
59 content_type 'text/plain; version=0.0.4; charset=utf-8';
60  
61 my @tenants = ('netdisco');
62 if (my $tdbs = setting('tenant_databases')) {
63 push @tenants, map { $_->{'tag'} } @$tdbs;
64 }
65  
66 my $output = '';
67  
68 # -- Statistics metrics (one row per tenant) -------------------------------
69 my @stat_metrics = (
70 [ netdisco_devices => 'device_count', 'Total number of discovered devices' ],
71 [ netdisco_device_ips => 'device_ip_count', 'Total number of device IP addresses' ],
72 [ netdisco_device_links => 'device_link_count', 'Total number of layer2 links between devices' ],
73 [ netdisco_device_ports => 'device_port_count', 'Total number of device ports' ],
74 [ netdisco_device_ports_up => 'device_port_up_count','Total number of device ports with up/up status' ],
75 [ netdisco_ip_table => 'ip_table_count', 'Total number of IP table entries' ],
76 [ netdisco_ip_active => 'ip_active_count', 'Total number of active IP entries' ],
77 [ netdisco_nodes => 'node_table_count', 'Total number of node entries' ],
78 [ netdisco_nodes_active => 'node_active_count', 'Total number of active nodes' ],
79 [ netdisco_phones => 'phone_count', 'Total number of discovered VoIP phones' ],
80 [ netdisco_waps => 'wap_count', 'Total number of discovered wireless access points' ],
81 );
82  
83 foreach my $m (@stat_metrics) {
84 my ($metric, $col, $help) = @$m;
85 $output .= _header($metric, $help);
86 foreach my $tenant (@tenants) {
87 my $stats = try {
88 schema($tenant)->resultset('Statistics')
89 ->search(undef, { order_by => { -desc => 'day' }, rows => 1 })->first;
90 };
91 next unless $stats;
92 $output .= _sample($metric, $stats->$col // 0, tenant => $tenant);
93 }
94 $output .= "\n";
95 }
96  
97 # Age of latest statistics row in seconds
98 $output .= _header('netdisco_stats_age_seconds', 'Age of the latest statistics snapshot in seconds');
99 foreach my $tenant (@tenants) {
100 my $age = try {
101 schema($tenant)->resultset('Statistics')->search(undef, {
102 select => [ \"extract(epoch FROM (now() - max(day)::timestamp))" ],
103 as => ['age'],
104 })->first->get_column('age');
105 };
106 next unless defined $age;
107 $output .= _sample('netdisco_stats_age_seconds', floor($age), tenant => $tenant);
108 }
109 $output .= "\n";
110  
111 # -- Backend / worker health -----------------------------------------------
112 $output .= _header('netdisco_backends', 'Number of active backend instances');
113 $output .= _header('netdisco_workers', 'Total number of worker slots across all backends');
114  
115 my $backends_output = '';
116 my $workers_output = '';
117 foreach my $tenant (@tenants) {
118 my @backends = try {
119 schema($tenant)->resultset('DeviceSkip')
120 ->search({ device => '255.255.255.255' })->hri->all;
121 } catch { () };
122 my $tot_workers = 0;
123 $tot_workers += $_->{deferrals} for @backends;
124 $backends_output .= _sample('netdisco_backends', scalar @backends, tenant => $tenant);
125 $workers_output .= _sample('netdisco_workers', $tot_workers, tenant => $tenant);
126 }
127 $output .= $backends_output . "\n";
128 $output .= $workers_output . "\n";
129  
130 # -- Job queue metrics (live, per tenant) ----------------------------------
131  
132 # Counts by status
133 $output .= _header('netdisco_jobs', 'Number of jobs in the queue by status');
134 foreach my $tenant (@tenants) {
135 my $rs = try { schema($tenant)->resultset('Admin') } or next;
136 foreach my $st (qw/queued done error/) {
137 my $count = try { $rs->search({ status => $st })->count } catch { 0 };
138 $output .= _sample('netdisco_jobs', $count, tenant => $tenant, status => $st);
139 }
140 }
141 $output .= "\n";
142  
143 # Running and stale jobs
144 $output .= _header('netdisco_jobs_running', 'Number of jobs currently running');
145 foreach my $tenant (@tenants) {
146 my $rs = try { schema($tenant)->resultset('Admin') } or next;
147 my $running = try {
148 $rs->search({ status => 'queued', backend => { '!=' => undef } })->count;
149 } catch { 0 };
150 $output .= _sample('netdisco_jobs_running', $running, tenant => $tenant);
151 }
152 $output .= "\n";
153  
154 $output .= _header('netdisco_jobs_stale', 'Number of stale jobs (running longer than jobs_stale_after)');
155 foreach my $tenant (@tenants) {
156 my $rs = try { schema($tenant)->resultset('Admin') } or next;
157 my $stale = try {
158 $rs->search({
159 status => 'queued',
160 backend => { '!=' => undef },
161 started => \[ q/<= (LOCALTIMESTAMP - ?::interval)/, setting('jobs_stale_after') ],
162 })->count;
163 } catch { 0 };
164 $output .= _sample('netdisco_jobs_stale', $stale, tenant => $tenant);
165 }
166 $output .= "\n";
167  
168 # Counts by action+status
169 $output .= _header('netdisco_jobs_by_action', 'Number of jobs grouped by action and status');
170 foreach my $tenant (@tenants) {
171 my $rs = try { schema($tenant)->resultset('Admin') } or next;
172 my @by_action = try {
173 $rs->search(undef, {
174 select => ['action', 'status', { count => '*', -as => 'cnt' }],
175 as => [qw/action status cnt/],
176 group_by => [qw/action status/],
177 })->hri->all;
178 } catch { () };
179 foreach my $row (@by_action) {
180 $output .= _sample('netdisco_jobs_by_action', $row->{cnt},
181 tenant => $tenant, action => $row->{action}, status => $row->{status});
182 }
183 }
184 $output .= "\n";
185  
186 # Average duration of completed jobs by action
187 $output .= _header('netdisco_job_duration_seconds', 'Average duration of completed jobs by action in seconds');
188 foreach my $tenant (@tenants) {
189 my $rs = try { schema($tenant)->resultset('Admin') } or next;
190 my @durations = try {
191 $rs->search(
192 { status => 'done', started => { '!=' => undef }, finished => { '!=' => undef } },
193 {
194 select => ['action',
195 { avg => \"extract(epoch FROM (finished - started))", -as => 'avg_duration' }],
196 as => [qw/action avg_duration/],
197 group_by => ['action'],
198 }
199 )->hri->all;
200 } catch { () };
201 foreach my $row (@durations) {
202 next unless defined $row->{avg_duration};
203 $output .= sprintf(qq(netdisco_job_duration_seconds{tenant="%s",action="%s"} %.3f\n),
204 $tenant, $row->{action}, $row->{avg_duration});
205 }
206 }
207 $output .= "\n";
208  
209 # -- Device inventory metrics ----------------------------------------------
210  
211 $output .= _header('netdisco_devices_by_vendor', 'Number of devices grouped by vendor');
212 foreach my $tenant (@tenants) {
213 my @rows = try {
214 schema($tenant)->resultset('Device')->search(undef, {
215 select => [ 'vendor', { count => '*', -as => 'cnt' } ],
216 as => [qw/vendor cnt/],
217 group_by => ['vendor'],
218 })->hri->all;
219 } catch { () };
220 foreach my $row (@rows) {
221 my $vendor = $row->{vendor} // 'unknown';
222 $output .= _sample('netdisco_devices_by_vendor', $row->{cnt},
223 tenant => $tenant, vendor => $vendor);
224 }
225 }
226 $output .= "\n";
227  
228 $output .= _header('netdisco_devices_by_os', 'Number of devices grouped by OS version');
229 foreach my $tenant (@tenants) {
230 my @rows = try {
231 schema($tenant)->resultset('Device')->search(undef, {
232 select => [ 'os', { count => '*', -as => 'cnt' } ],
233 as => [qw/os cnt/],
234 group_by => ['os'],
235 })->hri->all;
236 } catch { () };
237 foreach my $row (@rows) {
238 my $os = $row->{os} // 'unknown';
239 $output .= _sample('netdisco_devices_by_os', $row->{cnt},
240 tenant => $tenant, os => $os);
241 }
242 }
243 $output .= "\n";
244  
245 # -- Stale discovery (devices not polled recently) ------------------------
246 foreach my $action (
247 [ netdisco_devices_discover_stale => 'last_discover' => 'Number of devices not discovered in the last 24 hours' ],
248 [ netdisco_devices_macsuck_stale => 'last_macsuck' => 'Number of devices not macsucked in the last 24 hours' ],
249 [ netdisco_devices_arpnip_stale => 'last_arpnip' => 'Number of devices not arpniped in the last 24 hours' ],
250 ) {
251 my ($metric, $col, $help) = @$action;
252 $output .= _header($metric, $help);
253 foreach my $tenant (@tenants) {
254 my $count = try {
255 schema($tenant)->resultset('Device')->search({
256 -or => [
257 $col => undef,
258 $col => { '<' => \q|(now() - interval '24 hours')| },
259 ],
260 })->count;
261 } catch { 0 };
262 $output .= _sample($metric, $count, tenant => $tenant);
263 }
264 $output .= "\n";
265 }
266  
267 # -- Live MAC and ARP counts -----------------------------------------------
268 $output .= _header('netdisco_mac_entries', 'Live count of MAC address entries in the node table');
269 foreach my $tenant (@tenants) {
270 my $count = try { schema($tenant)->resultset('Node')->count } catch { 0 };
271 $output .= _sample('netdisco_mac_entries', $count, tenant => $tenant);
272 }
273 $output .= "\n";
274  
275 $output .= _header('netdisco_arp_entries', 'Live count of ARP entries in the node_ip table');
276 foreach my $tenant (@tenants) {
277 my $count = try { schema($tenant)->resultset('NodeIp')->count } catch { 0 };
278 $output .= _sample('netdisco_arp_entries', $count, tenant => $tenant);
279 }
280 $output .= "\n";
281  
282 # -- Slow devices (top 20 per tenant, bounded cardinality) -----------------
283 $output .= _header('netdisco_slow_device_duration_seconds',
284 'Duration of last completed job for the 20 slowest devices by action (discover/macsuck/arpnip)');
285 foreach my $tenant (@tenants) {
286 my @rows = try {
287 schema($tenant)->resultset('Virtual::SlowDevices')->search(undef)->hri->all;
288 } catch { () };
289 foreach my $row (@rows) {
290 next unless defined $row->{device} and defined $row->{elapsed};
291 # elapsed is a PG interval string like "00:00:45.2" - convert to seconds
292 my $secs = 0;
293 if ($row->{elapsed} =~ m/(\d+):(\d+):(\d+(?:\.\d+)?)/) {
294 $secs = $1 * 3600 + $2 * 60 + $3;
295 }
296 $output .= sprintf(
297 qq(netdisco_slow_device_duration_seconds{tenant="%s",device="%s",action="%s"} %.3f\n),
298 $tenant, $row->{device}, $row->{action}, $secs);
299 }
300 }
301 $output .= "\n";
302  
303 # -- SNMP connect failures (DeviceSkip table) ------------------------------
304 $output .= _header('netdisco_snmp_failures_devices',
305 'Number of devices with at least one SNMP connect failure');
306 foreach my $tenant (@tenants) {
307 my $count = try {
308 schema($tenant)->resultset('DeviceSkip')->search({
309 deferrals => { '>' => 0 },
310 device => { '!=' => '255.255.255.255' },
311 })->count;
312 } catch { 0 };
313 $output .= _sample('netdisco_snmp_failures_devices', $count, tenant => $tenant);
314 }
315 $output .= "\n";
316  
317 # -- Duplicate devices (same query as the Duplicate Devices admin task) ----
318 $output .= _header('netdisco_duplicate_devices',
319 'Number of devices sharing a serial number with another device');
320 foreach my $tenant (@tenants) {
321 my $count = try {
322 schema($tenant)->resultset('Device')->search({
323 serial => { '-in' => schema($tenant)->resultset('Device')->search({
324 '-and' => [serial => { '!=', undef }, serial => { '!=', '' }],
325 }, {
326 group_by => ['serial'],
327 having => \'count(*) > 1',
328 columns => 'serial',
329 })->as_query
330 },
331 })->count;
332 } catch { 0 };
333 $output .= _sample('netdisco_duplicate_devices', $count, tenant => $tenant);
334 }
335 $output .= "\n";
336  
337 $output .= _header('netdisco_snmp_failures_by_device',
338 'Number of SNMP connect failures per device and backend (top 50 by failure count)');
339 foreach my $tenant (@tenants) {
340 my @rows = try {
341 schema($tenant)->resultset('DeviceSkip')->search({
342 deferrals => { '>' => 0 },
343 device => { '!=' => '255.255.255.255' },
344 }, {
345 order_by => { -desc => 'deferrals' },
346 rows => 50,
347 })->hri->all;
348 } catch { () };
349 foreach my $row (@rows) {
350 $output .= sprintf(
351 qq(netdisco_snmp_failures_by_device{tenant="%s",device="%s",backend="%s"} %s\n),
352 $tenant, $row->{device}, $row->{backend}, $row->{deferrals});
353 }
354 }
355 $output .= "\n";
356  
357 return $output;
358 };
359 }
360  
361 true;