Mojolicious/Plugin/Status.pm

filter: Statementstmt 94.3% 168 / 178 Branchbran 59.6% 31 / 52 Conditioncond 44.4% 4 / 9 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 92.6% 38 / 41 Podpod 100% 1 / 1 totaltotal 84.6% 242 / 286 CC 35 SCAR 14.3
CC
35
Cov
85%
__ANON__
11.3
_activity
10.6
register
4.1
CRAP 4.2
↑ Summary Mojo/MemoryMap/Writer.pm »
1 package Mojolicious::Plugin::Status;
2 1 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 1 ▶use BSD::Resource qw(getrusage);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Mojo::File qw(path);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Mojo::MemoryMap;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Mojo::Util qw(humanize_bytes);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 ▶use constant MACOS => $^O eq 'darwin';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 our $VERSION = '1.17';
14  
15 1 ▶sub register {
Subroutine register: called CC=4 SCAR=14.1
Pod documented
16 1 my ($self, $app, $config) = @_;
17  
18 # Config
19 1 ▶ my $prefix = $config->{route} // $app->routes->any('/mojo-status');
Condition33%1/3
$config->{"route"} // $app->routes->any("/mojo-status")
l!l&&r!l&&!r
100
MC/DC0%0/2
$config->{"route"} // $app->routes->any("/mojo-status")
$config->{"route"} $app->routes->any("/mojo-status")
Truth table33%1/3
A // B
A= $config->{"route"}B= $app->routes->any("/mojo-status")
ABresult
1X1
011
000
20 1 ▶ $prefix->to(return_to => $config->{return_to} // '/');
Condition50%1/2
$config->{"return_to"} // "/"
l!l
10
MC/DC0%0/1
$config->{"return_to"} // "/"
$config->{"return_to"}
Truth table50%1/2
A
A= $config->{"return_to"}
Aresult
11
00
21 1 ▶ $self->{slowest} = $config->{slowest} // 10;
Condition50%1/2
$config->{"slowest"} // 10
l!l
10
MC/DC0%0/1
$config->{"slowest"} // 10
$config->{"slowest"}
Truth table50%1/2
A
A= $config->{"slowest"}
Aresult
11
00
22  
23 # Initialize cache
24 1 my $map = $self->{map} = Mojo::MemoryMap->new($config->{size});
25 1 $map->writer->store({processed => 0, started => time, stats => _stats(), slowest => []});
26  
27 # Only the two built-in servers are supported for now
28 1 ▶ $app->hook(before_server_start => sub { $self->_start(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
29  
30 # Static files
31 1 my $resources = path(__FILE__)->sibling('resources');
32 1 push @{$app->static->paths}, $resources->child('public')->to_string;
33  
34 # Templates
35 1 push @{$app->renderer->paths}, $resources->child('templates')->to_string;
36  
37 # Routes
38 1 $prefix->get('/' => => [format => ['json']] => {format => undef, mojo_status => $self} => \&_dashboard)
39 ->name('mojo_status');
40 }
41  
42 2 ▶sub _activity {
Subroutine _activity: called CC=10 SCAR=23.6
43 2 my $all = shift;
44  
45 # Workers
46 2 my @table;
47 2 for my $pid (sort keys %{$all->{workers}}) {
48 2 my $worker = $all->{workers}{$pid};
49 2 my $cpu = sprintf '%.2f', $worker->{utime} + $worker->{stime};
50 2 my @worker = ($pid, $cpu, humanize_bytes($worker->{maxrss}));
51  
52 # Connections
53 2 my $connections = $worker->{connections};
54 2 ▶ if (keys %$connections) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$connections) { } 2 0 2
55 2 my $repeat;
56 2 for my $cid (sort keys %$connections) {
57 2 my $conn = $connections->{$cid};
58 2 ▶ @worker = ('', '', '') if $repeat++;
Branch: 1 branch
BranchTrueFalseTotal
if $repeat++ 0 2 2
59 2 my $bytes_read = humanize_bytes $conn->{bytes_read};
60 2 my $bytes_written = humanize_bytes $conn->{bytes_written};
61 2 my $rw = "$bytes_read/$bytes_written";
62 2 my @conn = ($conn->{client}, $rw, $conn->{processed});
63  
64 # Request
65 2 ▶ if (my $req = $conn->{request}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $req = $conn->{'request'}) { } 2 0 2
66 2 ▶ my $active = $req->{finished} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$req->{'finished'} ? : 0 2 2
67 2 my ($rid, $proto) = @{$req}{qw(request_id protocol)};
68  
69 2 my $str = "$req->{method} $req->{path}";
70 2 ▶ $str .= "?$req->{query}" if $req->{query};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"query"} 1 1 2
71 2 ▶ $str .= " → $req->{status}" if $req->{status};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"status"} 0 2 2
72  
73 2 ▶ my $finished = $active ? time : $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
$active ? : 2 0 2
74 2 my $time = sprintf '%.2f', $finished - $req->{started};
75 2 push @table, [@worker, @conn, $rid, $active, $time, $proto, $str];
76 }
77 0 else { push @table, [@worker, @conn] }
78 }
79 }
80 0 else { push @table, \@worker }
81 }
82  
83 2 return \@table;
84 }
85  
86 9 ▶sub _dashboard {
Subroutine _dashboard: called CC=2 SCAR=6.9
87 9 my $c = shift;
88  
89 9 my $map = $c->stash('mojo_status')->{map};
90 9 ▶ if ($c->param('reset')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->param("reset")) 1 8 9
91 1 ▶ $map->writer->change(sub { @{$_}{qw(slowest stats)} = ([], _stats()) });
Subroutine __ANON__: called CC=1 SCAR=0.0
92 1 return $c->redirect_to('mojo_status');
93 }
94  
95 8 my $all = $map->writer->fetch;
96 $c->respond_to(
97 2 ▶ html => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
98 2 $c->render(
99 'mojo-status/dashboard',
100 now => time,
101 usage => humanize_bytes($map->usage),
102 size => humanize_bytes($map->size),
103 activity => _activity($all),
104 slowest => _slowest($all),
105 all => $all
106 );
107 },
108 8 json => {json => $all}
109 );
110 }
111  
112 64 ▶sub _read_write {
Subroutine _read_write: called CC=2 SCAR=7.0
113 64 my ($all, $id) = @_;
114 64 ▶ return unless my $stream = Mojo::IOLoop->stream($id);
Branch: 1 branch
BranchTrueFalseTotal
unless my $stream = "Mojo::IOLoop"->stream($id) 0 64 64
115 64 @{$all->{workers}{$$}{connections}{$id}}{qw(bytes_read bytes_written)}
116 = ($stream->bytes_read, $stream->bytes_written);
117 }
118  
119 64 ▶sub _request {
Subroutine _request: called CC=3 SCAR=11.5
120 64 my ($self, $c) = @_;
121  
122 # Request start
123 64 my $tx = $c->tx;
124 64 my $id = $tx->connection;
125 64 my $req = $tx->req;
126 64 my $url = $req->url->to_abs;
127 64 ▶ my $proto = $tx->is_websocket ? 'ws' : 'http';
Branch: 1 branch
BranchTrueFalseTotal
$tx->is_websocket ? : 0 64 64
128 64 ▶ $proto .= 's' if $req->is_secure;
Branch: 1 branch
BranchTrueFalseTotal
if $req->is_secure 0 64 64
129 64 ▶ $self->{map}->writer->change(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
130 $_->{workers}{$$}{connections}{$id}{request} = {
131 64 request_id => $req->request_id,
132 method => $req->method,
133 protocol => $proto,
134 path => $url->path->to_abs_string,
135 query => $url->query->to_string,
136 started => time
137 };
138 64 _read_write($_, $id);
139 64 $_->{workers}{$$}{connections}{$id}{client} = $tx->remote_address;
140 64 });
141  
142 # Request end
143 $tx->on(
144 64 ▶ finish => sub {
Subroutine __ANON__: called CC=1 SCAR=0.4
145 64 my $tx = shift;
146 64 ▶ $self->{map}->writer->change(sub {
Subroutine __ANON__: called CC=8 SCAR=24.2
147 64 ▶ return unless my $worker = $_->{workers}{$$};
Branch: 1 branch
BranchTrueFalseTotal
unless my $worker = $_->{"workers"}{$$} 0 64 64
148  
149 64 ▶ my $code = $tx->res->code || 0;
Condition50%1/2
$tx->res->code || 0
l!l
640
MC/DC0%0/1
$tx->res->code || 0
$tx->res->code
Truth table50%1/2
A
A= $tx->res->code
Aresult
11
00
150 0 ▶ if ($code > 499) { $_->{stats}{server_error}++ }
Branch: 5 branches
BranchTrueFalseTotal
if ($code > 499) { } 0 64 64
elsif ($code > 399) { } 0 64 64
elsif ($code > 299) { } 2 62 64
elsif ($code > 199) { } 62 0 62
elsif ($code) { } 0 0 0
151 0 elsif ($code > 399) { $_->{stats}{client_error}++ }
152 2 elsif ($code > 299) { $_->{stats}{redirect}++ }
153 62 elsif ($code > 199) { $_->{stats}{success}++ }
154 0 elsif ($code) { $_->{stats}{info}++ }
155  
156 64 @{$worker->{connections}{$id}{request}}{qw(finished status)} = (time, $code);
157 64 $worker->{connections}{$id}{processed}++;
158 64 $worker->{processed}++;
159 64 $_->{processed}++;
160 64 });
161 }
162 64 );
163 }
164  
165 64 ▶sub _rendered {
Subroutine _rendered: called CC=1 SCAR=0.0
166 64 my ($self, $c) = @_;
167  
168 64 my $id = $c->tx->connection;
169 64 ▶ $self->{map}->writer->change(sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
170 64 ▶ return unless my $conn = $_->{workers}{$$}{connections}{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless my $conn = $_->{"workers"}{$$}{"connections"}{$id} 0 64 64
171 64 ▶ return unless my $req = $conn->{request};
Branch: 1 branch
BranchTrueFalseTotal
unless my $req = $conn->{"request"} 0 64 64
172 64 $req->{time} = time - $req->{started};
173 64 @{$req}{qw(client status worker)} = ($conn->{client}, $c->res->code, $$);
174  
175 64 my $slowest = $_->{slowest};
176 64 @$slowest = sort { $b->{time} <=> $a->{time} } @$slowest, $req;
177 64 my %seen;
178 64 @$slowest = grep { !$seen{"$_->{method} $_->{path}"}++ } @$slowest;
179 64 ▶ pop @$slowest while @$slowest > $self->{slowest};
Branch: 1 branch
BranchTrueFalseTotal
@$slowest > $self->{"slowest"} and do { pop @$slowest } 32 64 96
180 64 });
181 }
182  
183 2 ▶sub _resources {
Subroutine _resources: called CC=1 SCAR=0.0
184 2 my $self = shift;
185  
186 2 ▶ $self->{map}->writer->change(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
187 2 @{$_->{workers}{$$}}{qw(utime stime maxrss)} = (getrusage)[0, 1, 2];
188  
189 # macOS actually returns bytes instead of kilobytes
190 2 $_->{workers}{$$}{maxrss} = $_->{workers}{$$}{maxrss} * 1000 unless MACOS;
191  
192 0 for my $id (keys %{$_->{workers}{$$}{connections}}) { _read_write($_, $id) }
193 2 });
194 }
195  
196 2 ▶sub _slowest {
Subroutine _slowest: called CC=4 SCAR=13.9
197 2 my $all = shift;
198  
199 2 my @table;
200 2 for my $req (@{$all->{slowest}}) {
201 8 my $str = "$req->{method} $req->{path}";
202 8 ▶ $str .= "?$req->{query}" if $req->{query};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"query"} 1 7 8
203 8 ▶ $str .= " → $req->{status}" if $req->{status};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"status"} 8 0 8
204 8 my $time = sprintf '%.2f', $req->{time};
205 8 push @table, [$time, $str, @{$req}{qw(request_id worker client started)}];
206 }
207  
208 2 return \@table;
209 }
210  
211 2 ▶sub _start {
Subroutine _start: called CC=3 SCAR=11.5
212 2 my ($self, $server, $app) = @_;
213  
214 2 ▶ return $app->log->warn('Server not suported by Mojolicious::Plugin::Status')
Branch: 1 branch
BranchTrueFalseTotal
unless $server->isa("Mojo::Server::Daemon") 0 2 2
215 unless $server->isa('Mojo::Server::Daemon');
216  
217 # Register started workers
218 2 ▶ Mojo::IOLoop->next_tick(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
219 2 ▶ $self->{map}->writer->change(sub { $_->{workers}{$$} = {started => time, processed => 0} });
Subroutine __ANON__: called CC=1 SCAR=0.0
220 2 });
221  
222 # Remove stopped workers
223 $server->on(
224 0 ▶ reap => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
225 0 my ($server, $pid) = @_;
226 0 ▶ $self->{map}->writer->change(sub { delete $_->{workers}{$pid} });
Subroutine __ANON__: not called CC=1 SCAR=6.9
227 }
228 2 ▶ ) if $server->isa('Mojo::Server::Prefork');
Branch: 1 branch
BranchTrueFalseTotal
if $server->isa("Mojo::Server::Prefork") 0 2 2
229  
230 # Collect stats
231 2 ▶ $app->hook(after_build_tx => sub { $self->_tx(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
232 2 ▶ $app->hook(before_dispatch => sub { $self->_request(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
233 2 ▶ $app->hook(after_dispatch => sub { $self->_rendered(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
234 2 ▶ Mojo::IOLoop->next_tick(sub { $self->_resources });
Subroutine __ANON__: called CC=1 SCAR=0.0
235 0 ▶ Mojo::IOLoop->recurring(5 => sub { $self->_resources });
Subroutine __ANON__: not called CC=1 SCAR=1.2
236 }
237  
238 2 ▶sub _stats { {started => time, info => 0, success => 0, redirect => 0, client_error => 0, server_error => 0} }
Subroutine _stats: called CC=1 SCAR=0.0
239  
240 1 ▶sub _stream {
Subroutine _stream: called CC=1 SCAR=0.0
241 1 my ($self, $id) = @_;
242  
243 1 my $stream = Mojo::IOLoop->stream($id);
244 $stream->on(
245 1 ▶ close => sub {
Subroutine __ANON__: called CC=1 SCAR=0.2
246 1 ▶ $self->{map}->writer->change(sub { delete $_->{workers}{$$}{connections}{$id} if $_->{workers}{$$} });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
if $_->{"workers"}{$$} 1 0 1
247 }
248 1 );
249 }
250  
251 64 ▶sub _tx {
Subroutine _tx: called CC=1 SCAR=0.0
252 64 my ($self, $tx, $app) = @_;
253  
254 $tx->on(
255 64 ▶ connection => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
256 64 my ($tx, $id) = @_;
257  
258 64 my $map = $self->{map};
259 64 ▶ return if $map->writer->fetch->{workers}{$$}{connections}{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $map->writer->fetch->{"workers"}{$$}{"connections"}{$id} 63 1 64
260  
261 1 ▶ $map->writer->change(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
262 1 $_->{workers}{$$}{connections}{$id} = {started => time, processed => 0, bytes_read => 0, bytes_written => 0};
263 1 });
264 1 $self->_stream($id);
265 }
266 64 );
267 }
268  
269 1 1;
270  
271 =encoding utf8
272  
273 =head1 NAME
274  
275 Mojolicious::Plugin::Status - Mojolicious server status
276  
277 =head1 SYNOPSIS
278  
279 # Mojolicious
280 $self->plugin('Status');
281  
282 # Mojolicious::Lite
283 plugin 'Status';
284  
285 # Secure access to the server status ui with Basic authentication
286 my $under = $self->routes->under('/status' => sub ($c) {
287 return 1 if $c->req->url->to_abs->userinfo eq 'Bender:rocks';
288 $c->res->headers->www_authenticate('Basic');
289 $c->render(text => 'Authentication required!', status => 401);
290 return undef;
291 });
292 $self->plugin('Status' => {route => $under});
293  
294 =head1 DESCRIPTION
295  
296 =begin html
297  
298 <p>
299 <img alt="Screenshot" src="https://raw.github.com/mojolicious/mojo-status/master/examples/status.png?raw=true"
300 width="600px">
301 </p>
302  
303 =end html
304  
305 L<Mojolicious::Plugin::Status> is a L<Mojolicious> plugin providing a server status ui for L<Mojo::Server::Daemon> and
306 L<Mojo::Server::Prefork>. Note that this module is B<EXPERIMENTAL> and should therefore only be used for debugging
307 purposes.
308  
309 =head1 OPTIONS
310  
311 L<Mojolicious::Plugin::Status> supports the following options.
312  
313 =head2 return_to
314  
315 # Mojolicious::Lite
316 plugin Status => {return_to => 'some_route'};
317  
318 Name of route or path to return to when leaving the server status ui, defaults to C</>.
319  
320 =head2 route
321  
322 # Mojolicious::Lite
323 plugin Status => {route => app->routes->any('/status')};
324  
325 L<Mojolicious::Routes::Route> object to attach the server status ui to, defaults to generating a new one with the
326 prefix C</mojo-status>.
327  
328 =head2 size
329  
330 # Mojolicious::Lite
331 plugin Status => {size => 1234};
332  
333 Size of anonymous mapped memory to use for storing statistics, defaults to C<52428800> (50 MiB).
334  
335 =head2 slowest
336  
337 # Mojolicious::Lite
338 plugin Status => {slowest => 5};
339  
340 Number of slowest requests to track, defaults to C<10>.
341  
342 =head1 METHODS
343  
344 L<Mojolicious::Plugin::Status> inherits all methods from L<Mojolicious::Plugin> and implements the following new ones.
345  
346 =head2 register
347  
348 my $route = $plugin->register(Mojolicious->new);
349  
350 Register renderer and helper in L<Mojolicious> application.
351  
352 =head1 BUNDLED FILES
353  
354 The L<Mojolicious::Plugin::Status> distribution includes a few files with different licenses that have been bundled for
355 internal use.
356  
357 =head2 Artwork
358  
359 Copyright (C) 2018, Sebastian Riedel.
360  
361 Licensed under the CC-SA License, Version 4.0 L<http://creativecommons.org/licenses/by-sa/4.0>.
362  
363 =head2 Bootstrap
364  
365 Copyright (C) 2011-2018 The Bootstrap Authors.
366  
367 Licensed under the MIT License, L<http://creativecommons.org/licenses/MIT>.
368  
369 =head2 Font Awesome
370  
371 Copyright (C) Dave Gandy.
372  
373 Licensed under the MIT License, L<http://creativecommons.org/licenses/MIT>, and the SIL OFL 1.1,
374 L<http://scripts.sil.org/OFL>.
375  
376 =head1 AUTHOR
377  
378 Sebastian Riedel, C<sri@cpan.org>.
379  
380 =head1 COPYRIGHT AND LICENSE
381  
382 Copyright (C) 2018-2021, Sebastian Riedel and others.
383  
384 This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version
385 2.0.
386  
387 =head1 SEE ALSO
388  
389 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
390  
391 =cut
↑ Summary Mojo/MemoryMap/Writer.pm »