blib/lib/Web/VWF/Display/meta_data.pm untested

filter: Statementstmt 0.0% 0 / 281 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 39 MC/DCmcdc 0.0% 0 / 22 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 456 CC 38 SCAR 37.5
CC
38
Cov
0%
get_slow_endpoints_24h
110.0
html
72.0
get_latency_24h
72.0
CRAP 42.3
1 package Web::VWF::Display::meta_data;
2  
3 # Display the meta-data page - the internal status of the server and VWF system
4  
5 # TODO: Add breakdown by browser name; the chart counts the types of client
6 # (web, mobile, search engine, ...), which is not the same thing
7  
8 use strict;
9 use warnings;
10  
11 use version; our $VERSION = version->declare('0.004.3');
12  
13 use parent 'Web::VWF::Display';
14  
15 # 0.23 and earlier take positional arguments (render_pie_chart_snippet($data,
16 # $opts)) and die "Data must be an array of arrays" on the hashes passed here;
17 # 0.24 was the first to take them, and the charts were built and tested on 0.30.
18 use HTML::D3 0.30;
19  
20 # Filesys::Df refuses to install on Windows, so Makefile.PL does not require it
21 # there. A server without it just has no disk figure: df() then answers as if
22 # the call had failed, which get_server_metrics() already copes with.
23 BEGIN {
24 if(!eval { require Filesys::Df; Filesys::Df->import(); 1 }) {
25 no strict 'refs'; ## no critic (ProhibitNoStrict)
26 *{__PACKAGE__ . '::df'} = sub { return };
27 }
28 }
29  
30 use List::Util qw(max sum0);
31 use Scalar::Util qw(looks_like_number);
32 use POSIX qw(strftime);
33 use Readonly;
34 use System::Info;
35 use Sys::Uptime;
36 use Sys::MemInfo;
37 use Time::Piece;
38 use Time::Seconds;
39  
40 # The browser types counted in the breakdown chart.
41 # Keep this in step with Web::VWF::Display::_types() and CGI::Info::browser_type().
42 Readonly my @BROWSER_TYPES => ('web', 'mobile', 'search', 'robot', 'ai');
43  
44 # A request cannot have taken longer than the window these charts cover, so a
45 # duration beyond one day is not a measurement but a stale row written by the
46 # old timer bug (about 1.8e12 ms). One such row would otherwise dominate the
47 # average, the 95th percentile and the slow-endpoint list for a whole day.
48 Readonly my $MAX_DURATION_MS => ONE_DAY * 1000;
49  
50 # What each panel says when it has nothing to draw. An empty frame looks like
51 # a broken chart, so every chart area explains itself instead - and the page
52 # has one place, not two, where that wording lives.
53 Readonly my $NO_REQUESTS => '<p>No requests logged yet.</p>';
54 Readonly my $NO_RECENT_REQUESTS => '<p>No requests logged in the last 24 hours.</p>';
55 Readonly my $NO_DURATIONS => '<p>No request durations logged in the last 24 hours.</p>';
56 Readonly my $NOT_ENOUGH_SAMPLES => '<p>Not enough data yet to rank endpoints.</p>';
57  
58 sub html {
59 my $self = shift;
60 my %args = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
61  
62 my $vwf_log = $args{'vwf_log'} or die "Missing 'vwf_log' handle";
63 my $domain_name = $self->{'info'}->domain_name();
64  
65 # --- Browser breakdown: one slice per browser type ---
66 my @browser;
67 foreach my $type (@BROWSER_TYPES) {
68 my @entries = $vwf_log->type({ domain_name => $domain_name, type => $type });
69 push @browser, [$type, scalar(@entries)];
70 if($self->{'logger'}) {
71 $self->{'logger'}->debug("$type = " . scalar(@entries));
72 }
73 }
74  
75 # --- Server metrics using CPAN modules ---
76 my $server_metrics = $self->get_server_metrics();
77  
78 # --- Traffic metrics from vwf_log ---
79 my $traffic_metrics = $self->get_traffic_metrics($vwf_log, $domain_name);
80  
81 # --- HTTP status breakdown: one slice per status code ---
82 my %status_count;
83 foreach my $http_code ($vwf_log->http_code({ domain_name => $domain_name })) {
84 $status_count{$http_code}++;
85 }
86 my @status = map { [$_, $status_count{$_}] } sort keys %status_count;
87  
88 my $rate_24h = $self->get_request_rate_24h($vwf_log, $domain_name);
89 my $latency_24h = $self->get_latency_24h($vwf_log, $domain_name);
90 my $slow = $self->get_slow_endpoints_24h($vwf_log, $domain_name);
91  
92 # The charts are built here and the template only places them. HTML::D3
93 # escapes the labels it writes into the page, so nothing from the access log
94 # is trusted as markup. A chart with no data is a placeholder, never an
95 # empty frame.
96 # responsive gives each SVG a viewBox, so that it scales to its panel; without
97 # it the chart is a fixed 800x400 and the panel cuts off the axis labels, the
98 # values and the bottom of the pies.
99 my $charts = HTML::D3->new(width => 800, height => 400, responsive => 1);
100 my $browser_chart = (grep { $_->[1] } @browser)
101 ? _scoped_snippet($charts->render_pie_chart_snippet({ data => \@browser, id => 'browser_chart', donut => 1, sort_slices => 'value' }))
102 : $NO_REQUESTS;
103 my $status_chart = @status
104 ? _scoped_snippet($charts->render_pie_chart_snippet({ data => \@status, id => 'status_chart', donut => 1, sort_slices => 'label' }))
105 : $NO_REQUESTS;
106 # B::Lint reads an array dereference in a conditional as an implicit scalar
107 # context and fails CI over it; scalar() is the count that was wanted anyway.
108 my $rate_chart = scalar(@{$rate_24h->{'total'}})
109 ? _scoped_snippet($charts->render_multi_series_line_chart_snippet({
110 series_data => _series(['Requests', $rate_24h->{'total'}], ['Errors', $rate_24h->{'errors'}]),
111 id => 'rate_chart', x_label => 'Hour', y_label => 'Requests',
112 }))
113 : $NO_RECENT_REQUESTS;
114 my $latency_chart = scalar(@{$latency_24h->{'avg'}})
115 ? _scoped_snippet($charts->render_multi_series_line_chart_snippet({
116 series_data => _series(['Average', $latency_24h->{'avg'}], ['P95', $latency_24h->{'p95'}]),
117 id => 'latency_chart', x_label => 'Hour', y_label => 'Milliseconds',
118 }))
119 : $NO_DURATIONS;
120 my $slow_chart = scalar(@{$slow})
121 ? _scoped_snippet($charts->render_bar_chart_snippet({
122 data => $slow, id => 'slow_chart', orientation => 'horizontal',
123 sort_bars => 'value', show_values => 1, value_label => 'ms',
124 }))
125 # Too few requests to rank anything is normal, not an error
126 : $NOT_ENOUGH_SAMPLES;
127  
128 return $self->SUPER::html({
129 server => $server_metrics,
130 traffic => $traffic_metrics,
131 browser_chart => $browser_chart,
132 status_chart => $status_chart,
133 rate_chart => $rate_chart,
134 latency_chart => $latency_chart,
135 slow_chart => $slow_chart,
136 });
137 }
138  
139 # HTML::D3's multi-series charts take {name, data => [{label, value}, ...]};
140 # the counting methods above return [label, value] pairs.
141 sub _series
142 {
143 my @series = @_;
144  
145 return [ map {
146 my ($name, $points) = @{$_};
147 {
148 name => $name,
149 data => [ map { { label => $_->[0], value => $_->[1] } } @{$points} ],
150 }
151 } @series ];
152 }
153  
154 # The pie snippet writes its script at the top level of the page, while the
155 # line and bar snippets wrap theirs in a function. Two pies on one page would
156 # therefore both declare "const data": the second script dies with
157 # "Identifier 'data' has already been declared" and leaves an empty frame.
158 # Giving every snippet its own function makes them independent; the snippets
159 # that already wrap themselves are simply wrapped twice, which is harmless.
160 sub _scoped_snippet
161 {
162 my ($result) = @_;
163  
164 my $html = $result->{'html'};
165 $html =~ s{(<script\b[^>]*>)(.*?)(</script>)}{$1 . "(function () {\n" . $2 . "\n})();\n" . $3}gse;
166  
167 return $html;
168 }
169  
170 sub get_server_metrics {
171 my $metrics = {};
172  
173 # CPU info
174 my $si = System::Info->new;
175 $metrics->{cpu_count} = $si->ncpu // 0;
176 $metrics->{cpu_type} = $si->cpu_type // '';
177  
178 # Disk usage
179 if(my $df = df('/')) {
180 # prefer 'per' if present
181 # A filesystem reporting no blocks has no meaningful percentage
182 $metrics->{disk_used_pct} = $df->{per}
183 // ($df->{blocks} ? int(100 * ($df->{blocks} - $df->{bfree}) / $df->{blocks}) : undef);
184 } else {
185 $metrics->{disk_used_pct} = undef;
186 }
187  
188 # Memory usage (via Sys::MemInfo)
189 my $total_mem = Sys::MemInfo::totalmem();
190 my $free_mem = Sys::MemInfo::freemem();
191 if (defined $total_mem && defined $free_mem && $total_mem > 0) {
192 $metrics->{memory_used_pct} = int(100 * ($total_mem - $free_mem) / $total_mem);
193 } else {
194 $metrics->{memory_used_pct} = 0;
195 }
196  
197 return $metrics;
198 }
199  
200 # ------------------------------
201 # Traffic metrics from vwf_log
202 # ------------------------------
203  
204 sub get_traffic_metrics {
205 my (undef, $vwf_log, $domain_name) = @_;
206 my $metrics = {};
207  
208 # Current time and one hour ago (local time)
209 my $now = time();
210 my $hour_ago = $now - ONE_HOUR + _utc_offset();
211  
212 # Get all entries as array of hashrefs
213 my @entries = $vwf_log->selectall_array({ domain_name => $domain_name });
214  
215 # Filter entries from last hour
216 my @recent;
217 foreach my $entry (@entries) {
218 next unless ref $entry eq 'HASH' && $entry->{time};
219  
220 my $tp;
221 eval { $tp = Time::Piece->strptime($entry->{time}, '%Y-%m-%d %H:%M:%S') };
222 next unless $tp;
223  
224 my $epoch = $tp->epoch;
225 push @recent, $entry if $epoch > $hour_ago;
226 }
227  
228 # Requests per hour
229 $metrics->{requests_per_hour} = scalar @recent;
230  
231 # Active users (unique IPs)
232 my %ips;
233 foreach my $entry (@recent) {
234 my $ip = $entry->{ip} // 'unknown';
235 $ips{$ip} = 1;
236 }
237 $metrics->{active_users} = scalar keys %ips;
238  
239 # Top 5 endpoints
240 # my %urls;
241 # foreach my $entry (@recent) {
242 # my $url = $entry->{url} // '/';
243 # $urls{$url}++;
244 # }
245 # my @top_urls = sort { $urls{$b} <=> $urls{$a} } keys %urls;
246 # $metrics->{top_urls} = [ @top_urls[0..(4 > $#top_urls ? $#top_urls : 4)] ];
247  
248 # Error count (HTTP code >= 400)
249 my $errors = grep { ($_->{http_code} // 0) >= 400 } @recent;
250 $metrics->{errors_last_hour} = $errors;
251  
252 return $metrics;
253 }
254  
255 sub get_request_rate_24h {
256 my (undef, $vwf_log, $domain_name) = @_;
257  
258 my $now = time();
259 my $start = $now - ONE_DAY + _utc_offset();
260  
261 my %buckets;
262  
263 foreach my $entry ($vwf_log->selectall_array({ domain_name => $domain_name })) {
264 next unless ref $entry eq 'HASH' && $entry->{time};
265  
266 my $tp;
267 eval { $tp = Time::Piece->strptime($entry->{time}, '%Y-%m-%d %H:%M:%S') };
268 next unless $tp;
269  
270 my $epoch = $tp->epoch;
271 next if $epoch < $start;
272  
273 my $bucket = _hour_key($tp);
274 $buckets{$bucket}{label} = _hour_label($tp);
275  
276 $buckets{$bucket}{total}++;
277 if(($entry->{http_code} // 0) >= 400) {
278 $buckets{$bucket}{errors}++;
279 }
280 }
281  
282 # One [label, value] pair per hour, ready for HTML::D3
283 my (@total, @errors, @error_pct);
284  
285 foreach my $key (sort keys %buckets) {
286 my $hour = $buckets{$key}{label};
287 my $total = $buckets{$key}{total} // 0;
288 my $errors = $buckets{$key}{errors} // 0;
289  
290 push @total, [$hour, $total];
291 push @errors, [$hour, $errors];
292 push @error_pct, [$hour, $total ? 0 + sprintf('%.2f', ($errors / $total) * 100) : 0];
293 }
294  
295 return {
296 total => \@total,
297 errors => \@errors,
298 error_pct => \@error_pct,
299 };
300 }
301  
302 sub get_latency_24h {
303 my (undef, $vwf_log, $domain_name) = @_;
304  
305 my $start = time() - ONE_DAY + _utc_offset();
306  
307 my (%buckets, %labels);
308  
309 foreach my $entry ($vwf_log->selectall_array({ domain_name => $domain_name })) {
310 next unless ref $entry eq 'HASH';
311 next unless $entry->{time};
312 # The log is data, not code: only numbers are durations
313 next unless defined($entry->{duration_ms}) && looks_like_number($entry->{duration_ms});
314 next if $entry->{duration_ms} > $MAX_DURATION_MS;
315  
316 my $tp;
317 eval { $tp = Time::Piece->strptime($entry->{time}, '%Y-%m-%d %H:%M:%S') };
318 next unless $tp;
319  
320 my $epoch = $tp->epoch;
321 next if $epoch < $start;
322  
323 my $bucket = _hour_key($tp);
324 $labels{$bucket} = _hour_label($tp);
325  
326 push @{ $buckets{$bucket} }, $entry->{duration_ms};
327 }
328  
329 my (@avg, @p95);
330  
331 foreach my $key (sort keys %buckets) {
332 my $hour = $labels{$key};
333 my @vals = sort { $a <=> $b } @{ $buckets{$key} };
334 next unless @vals;
335  
336 my $count = @vals;
337 # Never eval() log contents: a crafted duration_ms would run as Perl
338 my $avg = int(sum0(@vals) / $count);
339  
340 my $p95_index = int(0.95 * ($count - 1));
341 my $p95 = $vals[$p95_index];
342  
343 push @avg, [$hour, $avg];
344 push @p95, [$hour, $p95];
345 }
346  
347 return {
348 avg => \@avg,
349 p95 => \@p95,
350 };
351 }
352  
353 sub get_slow_endpoints_24h {
354 my (undef, $vwf_log, $domain_name) = @_;
355  
356 my $start = time() - ONE_DAY + _utc_offset();
357  
358 # Step 1: fetch rows filtered only by equality
359 my @rows = $vwf_log->selectall_array({ domain_name => $domain_name });
360  
361 # Step 2: collect durations per template
362 my %durations;
363  
364 foreach my $row (@rows) {
365 next unless ref($row) eq 'HASH';
366 next unless defined $row->{time};
367 next unless defined($row->{duration_ms}) && looks_like_number($row->{duration_ms});
368 next if $row->{duration_ms} <= 0;
369 next if $row->{duration_ms} > $MAX_DURATION_MS;
370  
371 my $tp;
372 eval { $tp = Time::Piece->strptime($row->{time}, '%Y-%m-%d %H:%M:%S') };
373 next unless $tp;
374 next if $tp->epoch < $start;
375  
376 my $tpl = $row->{template} // '';
377 push @{ $durations{$tpl} }, $row->{duration_ms};
378 }
379  
380 # Step 3: compute p95
381 my @ranked;
382  
383 foreach my $tpl (keys %durations) {
384 my @vals = sort { $a <=> $b } @{ $durations{$tpl} };
385 my $count = @vals;
386 next if $count < 5;
387  
388 my $p95_index = int(0.95 * ($count - 1));
389 my $p95 = $vals[$p95_index];
390  
391 push @ranked, {
392 template => $tpl,
393 p95_ms => $p95,
394 };
395 }
396  
397 # Step 4: sort + top 10
398 @ranked = sort { $b->{p95_ms} <=> $a->{p95_ms} } @ranked;
399 splice(@ranked, 10) if @ranked > 10;
400  
401 # Step 5: [label, value] pairs. The labels stay as the log wrote them;
402 # HTML::D3 escapes them when it writes the chart.
403 my @dp;
404 foreach my $row (@ranked) {
405 my $label = $row->{template};
406 $label =~ s/^.+\/templates\///;
407 # The chart has little room for a label and cuts off the start of a long
408 # one, which is the part that tells them apart. Keep the page, and the
409 # language and client type, so that two templates never share a label.
410 $label =~ s{\A(.+?)/Web/VWF/Display/(.+)\.tmpl\z}{$2 ($1)};
411  
412 push @dp, [$label, $row->{p95_ms}];
413 }
414  
415 return \@dp;
416 }
417  
418 # The 24 hours behind us cross midnight, so the hour of the day alone neither
419 # puts the points in order nor tells the end of yesterday's hour from the start
420 # of today's. Buckets are keyed, and so sorted, by date and hour.
421 sub _hour_key
422 {
423 my ($tp) = @_;
424  
425 return $tp->strftime('%Y-%m-%d %H');
426 }
427  
428 # The day of the week is enough to tell two days apart, and is short enough for
429 # the axis of a chart
430 sub _hour_label
431 {
432 my ($tp) = @_;
433  
434 return $tp->strftime('%a %H:00');
435 }
436  
437 sub _utc_offset
438 {
439 my $local_time = time();
440 my @local = localtime($local_time);
441 my @gmt = gmtime($local_time);
442  
443 # Convert both to seconds since midnight
444 my $local_seconds = $local[2] * 3600 + $local[1] * 60 + $local[0];
445 my $gmt_seconds = $gmt[2] * 3600 + $gmt[1] * 60 + $gmt[0];
446  
447 # Account for day boundary crossing
448 my $day_diff = $local[3] - $gmt[3];
449 if ($day_diff > 1) { $day_diff = -1; } # wrapped backwards
450 if ($day_diff < -1) { $day_diff = 1; } # wrapped forwards
451  
452 return $local_seconds - $gmt_seconds + ($day_diff * 86400);
453 }
454  
455 1;
456  
457 =encoding utf8
458  
459 =head1 NAME
460  
461 Web::VWF::Display::meta_data - The status page: the server and its traffic
462  
463 =head1 VERSION
464  
465 Version 0.004.3
466  
467 =head1 DESCRIPTION
468  
469 A dashboard for the site's owner. It reads the access log through the
470 C<vwf_log> handle (see L<Web::VWF::Data::vwf_log>) and shows the server's load,
471 memory, disk and uptime, the counts of requests, and five L<HTML::D3> charts: the
472 browser types, the HTTP status codes, requests and errors per hour, latency per
473 hour, and the slowest endpoints. A chart with nothing to draw is replaced by a
474 sentence saying so. It needs L<HTML::D3> 0.30 or later.
475  
476 An access log with no requests in it, as on a new site or just after the log
477 is rotated, is not an error: the charts say that there is nothing to show.
478  
479 =head1 METHODS
480  
481 =head2 html
482  
483 Needs the C<vwf_log> handle and dies without it. Returns the HTML from
484 F<meta_data.tmpl>.
485  
486 =head3 API SPECIFICATION
487  
488 =head4 INPUT
489  
490 { vwf_log => { type => 'object' } }
491  
492 =head4 OUTPUT
493  
494 { type => 'string' }
495  
496 =head2 get_server_metrics
497  
498 The state of the server as a hash reference: C<cpu_count>, C<cpu_type>,
499 C<disk_used_pct> (undef when L<Filesys::Df> is not installed) and
500 C<memory_used_pct>.
501  
502 =head2 get_traffic_metrics
503  
504 Takes the log handle and the domain name. Returns a hash reference with
505 C<requests_per_hour>, C<active_users> (distinct addresses) and C<errors_last_hour>
506 for the last hour.
507  
508 =head2 get_request_rate_24h
509  
510 Takes the log handle and the domain name. Returns C<{ total, errors, error_pct }>,
511 each a list of C<[ hour, value ]> pairs for the last 24 hours, oldest first. An
512 hour is labelled with its day, such as C<Mon 13:00>.
513  
514 =head2 get_latency_24h
515  
516 Takes the log handle and the domain name. Returns C<{ avg, p95 }>, each a list of
517 C<[ hour, milliseconds ]> pairs for the last 24 hours, ordered and labelled as
518 for L</get_request_rate_24h>. Durations over a day are
519 log rows written by an old bug and are left out.
520  
521 =head2 get_slow_endpoints_24h
522  
523 Takes the log handle and the domain name. Returns up to ten C<[ template,
524 milliseconds ]> pairs, the 95th percentile of the slowest templates in the last
525 24 hours, ignoring any that were asked for fewer than five times.
526  
527 =head1 AUTHOR
528  
529 Nigel Horne, C<< <njh at nigelhorne.com> >>
530  
531 =head1 LICENCE AND COPYRIGHT
532  
533 Copyright 2010-2026 Nigel Horne.
534  
535 Usage is subject to the GPL2 licence terms.
536 If you use it,
537 please let me know.
538  
539 =cut