blib/lib/PAGI/Server/Runner.pm

filter: Statementstmt 76.8% 245 / 319 Branchbran 56.2% 108 / 192 Conditioncond 65.2% 47 / 72 MC/DCmcdc 41.4% 17 / 41 Subroutinesub 89.1% 33 / 37 Podpod 100% 7 / 7 totaltotal 68.4% 457 / 668 CC 131 SCAR 28.7
CC
131
Cov
69%
_daemonize
56.0
_drop_privileges
51.1
_redirect_std_handles
30.0
CRAP 17.6
« blib/lib/PAGI/Server/Protocol/HTTP1.pm ↑ Summary blib/lib/PAGI/Server/Protocol/HTTP2.pm »
1 package PAGI::Server::Runner;
2  
3 17 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 17 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 17 our $VERSION = '0.002013';
7  
8 17 ▶use Getopt::Long qw(GetOptionsFromArray :config pass_through no_auto_abbrev no_ignore_case);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 17 ▶use Pod::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 17 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 17 ▶use POSIX qw(setsid);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 17 ▶use FindBin ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 17 ▶use IO::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 17 ▶use PAGI::Server::AppNormalizer ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 =head1 NAME
18  
19 PAGI::Server::Runner - PAGI application loader and server runner
20  
21 =head1 SYNOPSIS
22  
23 # Command line usage via pagi-server
24 pagi-server PAGI::App::Directory root=/var/www
25 pagi-server ./app.pl -p 8080
26 pagi-server # serves current directory
27  
28 # With environment modes
29 pagi-server -E development app.pl # enable Lint middleware
30 pagi-server -E production app.pl # no auto-middleware
31 PAGI_ENV=production pagi-server app.pl
32  
33 # Programmatic usage
34 use PAGI::Server::Runner;
35  
36 PAGI::Server::Runner->run(@ARGV);
37  
38 =head1 DESCRIPTION
39  
40 PAGI::Server::Runner is a loader and runner for PAGI applications, similar to
41 L<Plack::Runner> for PSGI. It handles CLI argument parsing, app loading
42 (from files or modules), environment modes, and server orchestration.
43  
44 The runner is designed to be server-agnostic. Common options like host,
45 port, and daemonize are handled by the runner, while server-specific
46 options are passed through to the server backend.
47  
48 =head1 ENVIRONMENT MODES
49  
50 PAGI::Server::Runner supports environment modes similar to Plack's C<-E> flag:
51  
52 =over 4
53  
54 =item development
55  
56 Auto-enables L<PAGI::Middleware::Lint> with strict mode to catch
57 specification violations early (when PAGI-Tools is installed). This is
58 the default when running interactively (TTY detected).
59  
60 =item production
61  
62 No middleware is auto-enabled. This is the default when running
63 non-interactively (no TTY, e.g., systemd, docker, cron).
64  
65 =item none
66  
67 Explicit opt-out of all auto-middleware, regardless of TTY detection.
68  
69 =back
70  
71 Mode is determined by (in order of precedence):
72  
73 1. -E / --env command line flag
74 2. PAGI_ENV environment variable
75 3. Auto-detection: TTY = development, no TTY = production
76  
77 After determining the mode, the runner sets C<PAGI_ENV> to the resolved
78 value. This allows your application to check C<$ENV{PAGI_ENV}> to know
79 what mode it's running in, similar to Plack's C<PLACK_ENV>.
80  
81 Use C<--no-default-middleware> to disable auto-middleware while keeping
82 the mode for other purposes.
83  
84 =head1 APP LOADING
85  
86 The runner supports three ways to specify an application:
87  
88 =head2 Module Name
89  
90 If the app specifier contains C<::>, it's treated as a module name:
91  
92 pagi-server PAGI::App::Directory root=/var/www show_hidden=1
93  
94 The module is loaded and C<new> is called with the provided key=value
95 arguments. The constructed value may be a native PAGI coderef or an
96 instantiated application-provider object. A provider is normalized by calling
97 C<to_app> exactly once; C<to_app> is never invoked as a class method.
98  
99 =head2 File Path
100  
101 If the app specifier contains C</> or ends with C<.pl> or C<.psgi>,
102 it's treated as a file path:
103  
104 pagi-server ./app.pl
105 pagi-server /path/to/myapp.psgi
106  
107 The file is loaded via C<do> and must return either a native PAGI coderef or an
108 instantiated application-provider object. A provider is normalized through
109 C<to_app> exactly once before the server is constructed.
110  
111 For compatibility with Plack's C<plackup>, the runner localizes C<$0> to the
112 app file before loading it. This ensures C<FindBin::Bin> resolves to the app
113 file directory inside the app. If C<FindBin> was already loaded, the runner
114 also calls C<FindBin::again()> to refresh its cached path.
115  
116 =head2 Default
117  
118 If no app is specified, defaults to serving the current directory:
119  
120 pagi-server # same as: PAGI::App::Directory root=.
121  
122 =head1 METHODS
123  
124 =head2 run
125  
126 PAGI::Server::Runner->run(@ARGV);
127  
128 Class method that creates a runner, parses options, loads the app,
129 and runs the server. This is the main entry point for CLI usage.
130  
131 =head2 new
132  
133 my $runner = PAGI::Server::Runner->new(%options);
134  
135 Creates a new runner instance. Most users should use C<run()> instead.
136  
137 =cut
138  
139 88 ▶sub new {
Subroutine new: called CC=7 SCAR=20.1
Pod documented
140 88 my ($class, %args) = @_;
141  
142 return bless {
143 # Runner options (common to all servers)
144 host => $args{host},
145 port => $args{port},
146 server => $args{server},
147 env => $args{env},
148 quiet => $args{quiet} // 0,
149 loop => $args{loop},
150 access_log => $args{access_log},
151 no_access_log => $args{no_access_log} // 0,
152 error_log => $args{error_log},
153 daemonize => $args{daemonize} // 0,
154 pid_file => $args{pid_file},
155 user => $args{user},
156 group => $args{group},
157 libs => $args{libs} // [],
158 modules => $args{modules} // [],
159 eval => $args{eval},
160 default_middleware => $args{default_middleware},
161  
162 # Internal state
163 app => undef,
164 app_spec => undef,
165 app_args => {},
166 server_options => $args{server_options} // {},
167 88 ▶ argv => [],
Condition75%9/12
$args{"quiet"} // 0
l!l
1969
$args{"no_access_log"} // 0
l!l
088
$args{"daemonize"} // 0
l!l
187
$args{"libs"} // []
l!l
088
$args{"modules"} // []
l!l
088
$args{"server_options"} // {}
l!l
1078
MC/DC100%1/1
$args{"quiet"} // 0
$args{"quiet"}
MC/DC0%0/1
$args{"no_access_log"} // 0
$args{"no_access_log"}
MC/DC100%1/1
$args{"daemonize"} // 0
$args{"daemonize"}
MC/DC0%0/1
$args{"libs"} // []
$args{"libs"}
MC/DC0%0/1
$args{"modules"} // []
$args{"modules"}
MC/DC100%1/1
$args{"server_options"} // {}
$args{"server_options"}
Truth table100%2/2
A
A= $args{"quiet"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"no_access_log"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"daemonize"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"libs"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"modules"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"server_options"}
Aresult
11
00
168 }, $class;
169 }
170  
171 =head2 parse_options
172  
173 $runner->parse_options(@args);
174  
175 Parses CLI options from the argument list. Common options are stored
176 in the runner object. Server-specific options are passed separately
177 via the C<server_options> hashref (see L</load_server>).
178  
179 =head3 Common Options (handled by Runner)
180  
181 -a, --app FILE Load app from file (legacy option)
182 -e CODE Inline app code (like perl -e)
183 -M MODULE Load MODULE before -e (repeatable, like perl -M)
184 -o, --host HOST Bind address (default: 127.0.0.1)
185 -p, --port PORT Bind port (default: 5000)
186 -s, --server CLASS Server class (default: PAGI::Server)
187 -E, --env MODE Environment mode (development, production, none)
188 -I, --lib PATH Add PATH to @INC (repeatable)
189 -l, --loop BACKEND Event loop backend (EV, Epoll, UV, Poll)
190 -D, --daemonize Run as background daemon
191 --access-log FILE Access log file (default: STDERR)
192 --no-access-log Disable access logging
193 --error-log FILE Diagnostic log file (default: STDERR)
194 --pid FILE Write PID to file
195 --user USER Run as specified user (after binding)
196 --group GROUP Run as specified group (after binding)
197 -q, --quiet Report errors only (shorthand for --log-level error)
198 --default-middleware Toggle mode middleware (default: on)
199 -v, --version Show version info
200 --help Show help
201  
202 Example with C<-e> and C<-M>:
203  
204 pagi-server -MPAGI::App::File -e 'PAGI::App::File->new(root => ".")'
205  
206 =head3 Diagnostic Output
207  
208 Diagnostics -- the server's own log messages, and the warnings emitted by
209 application and middleware code -- go to C<STDERR> by default.
210  
211 C<--error-log FILE> sends them to a file instead. It is opened immediately
212 after the command line is parsed -- before the application is loaded and
213 before any listener is bound -- so it captures app-loading failures and bind
214 errors as well as everything the server says once it is running. The
215 descriptor is inherited across both C<--daemonize> forks, so the destination
216 survives daemonizing; without it, daemonizing reopens C<STDERR> on
217 F</dev/null> and every diagnostic in the process is discarded.
218  
219 Note that C<--access-log> is a separate destination covering request records
220 only, and that it is disabled by default in production mode, so a daemonized
221 production server with neither option configured writes no log output at all.
222  
223 How much is said is governed by one threshold. C<-q> / C<--quiet> is
224 shorthand for the C<error> level. Where the server being run offers a
225 C<--log-level> option, the runner's own messages answer to it as well, so a
226 single flag covers both; an explicit level wins over C<-q>. A server that
227 has no such option simply leaves the runner on its default.
228  
229 =head3 Server-Specific Options
230  
231 Server-specific options should be parsed by the server's CLI wrapper
232 (e.g., C<bin/pagi-server>) and passed to Runner via the C<server_options>
233 hashref parameter. This keeps Runner server-agnostic.
234  
235 See L<PAGI::Server> for available options when using pagi-server.
236  
237 =cut
238  
239 33 ▶sub parse_options {
Subroutine parse_options: called CC=26 SCAR=32.7
Pod documented
240 33 my ($self, @args) = @_;
241  
242 # Check for server_options hashref passed from bin/pagi-server
243 33 for my $i (0 .. $#args) {
244 122 ▶ if ($args[$i] eq 'server_options' && ref($args[$i + 1]) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($args[$i] eq "server_options" and ref $args[$i + 1] eq "HASH") 10 112 122
Condition66%2/3
$args[$i] eq "server_options" and ref $args[$i + 1] eq "HASH"
!ll&&!rl&&r
112010
MC/DC50%1/2
$args[$i] eq "server_options" and ref $args[$i + 1] eq "HASH"
$args[$i] eq "server_options" ref $args[$i + 1] eq "HASH"
Truth table66%2/3
A and B
A= $args[$i] eq "server_options"B= ref $args[$i + 1] eq "HASH"
ABresult
0X0
100
111
245 10 $self->{server_options} = $args[$i + 1];
246 10 splice @args, $i, 2;
247 10 last;
248 }
249 }
250  
251 # Pre-process cuddled options like -MModule or -e"code" → -M Module, -e "code"
252 # This matches Plack::Runner behavior for perl-like flags
253 33 ▶ @args = map { /^(-[IMMe])(.+)/ ? ($1, $2) : $_ } @args;
Branch: 1 branch
BranchTrueFalseTotal
/^(-[IMMe])(.+)/ ? : 1 112 113
254  
255 33 my %opts;
256 my @libs;
257 33 my @modules;
258  
259 # Parse runner options, pass through unknown for server
260 GetOptionsFromArray(
261 \@args,
262 # App loading
263 'a|app=s' => \$opts{app},
264 'e=s' => \$opts{eval},
265 'I|lib=s' => \@libs,
266 'M=s' => \@modules,
267  
268 # Network
269 'o|host=s' => \$opts{host},
270 'p|port=i' => \$opts{port},
271  
272 # Server selection (future: pluggable servers)
273 's|server=s' => \$opts{server},
274  
275 # Environment/mode
276 'E|env=s' => \$opts{env},
277  
278 # Event loop
279 'l|loop=s' => \$opts{loop},
280  
281 # Logging
282 'access-log=s' => \$opts{access_log},
283 'no-access-log' => \$opts{no_access_log},
284 'error-log=s' => \$opts{error_log},
285  
286 # Daemon/process
287 'D|daemonize' => \$opts{daemonize},
288 'pid=s' => \$opts{pid_file},
289 'user=s' => \$opts{user},
290 'group=s' => \$opts{group},
291  
292 # Output
293 'q|quiet' => \$opts{quiet},
294 'default-middleware!' => \$opts{default_middleware},
295  
296 # Help/version
297 'help' => \$opts{help},
298 'v|version' => \$opts{version},
299 33 ▶ ) or die "Error parsing options\n";
Branch: 1 branch
BranchTrueFalseTotal
&GetOptionsFromArray(\@args, "a|app=s", \$opts{"app"}, "e=s", \$opts{"eval"}, "I|lib=s", \@libs, "M=s", \@modules, "o|host=s", \$opts{"host"}, "p|port=i", \$opts{"port"}, "s|server=s", \$opts{"server"}, "E|env=s", \$opts{"env"}, "l|loop=s", \$opts{"loop"}, "access-log=s", \$opts{"access_log"}, "no-access-log", \$opts{"no_access_log"}, "error-log=s", \$opts{"error_log"}, "D|daemonize", \$opts{"daemonize"}, "pid=s", \$opts{"pid_file"}, "user=s", \$opts{"user"}, "group=s", \$opts{"group"}, "q|quiet", \$opts{"quiet"}, "default-middleware!", \$opts{"default_middleware"}, "help", \$opts{"help"}, "v|version", \$opts{"version"}) or die "Error parsing options\n" 33 0 33
300  
301 # Store the selected server class before the version/help early-return
302 # so --version can report the configured server (see _show_version).
303 33 ▶ $self->{server} = $opts{server} if defined $opts{server};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"server"} 6 27 33
304  
305 # Handle help/version flags
306 33 ▶ if ($opts{version}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"version"}) 1 32 33
307 1 $self->{show_version} = 1;
308 1 return;
309 }
310 32 ▶ if ($opts{help}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"help"}) 1 31 32
311 1 $self->{show_help} = 1;
312 1 return;
313 }
314  
315 # Apply parsed options
316 31 ▶ $self->{host} = $opts{host} if defined $opts{host};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"host"} 2 29 31
317 31 ▶ $self->{port} = $opts{port} if defined $opts{port};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"port"} 11 20 31
318 31 ▶ $self->{env} = $opts{env} if defined $opts{env};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"env"} 2 29 31
319 31 ▶ $self->{loop} = $opts{loop} if defined $opts{loop};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"loop"} 1 30 31
320 31 ▶ $self->{access_log} = $opts{access_log} if defined $opts{access_log};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"access_log"} 0 31 31
321 31 ▶ $self->{no_access_log} = $opts{no_access_log} if $opts{no_access_log};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"no_access_log"} 0 31 31
322 31 ▶ $self->{error_log} = $opts{error_log} if defined $opts{error_log};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"error_log"} 1 30 31
323 31 ▶ $self->{daemonize} = $opts{daemonize} if $opts{daemonize};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"daemonize"} 4 27 31
324 31 ▶ $self->{pid_file} = $opts{pid_file} if defined $opts{pid_file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"pid_file"} 3 28 31
325 31 ▶ $self->{user} = $opts{user} if defined $opts{user};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"user"} 3 28 31
326 31 ▶ $self->{group} = $opts{group} if defined $opts{group};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"group"} 3 28 31
327 31 ▶ $self->{quiet} = $opts{quiet} if $opts{quiet};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"quiet"} 2 29 31
328 $self->{default_middleware} = $opts{default_middleware}
329 31 ▶ if defined $opts{default_middleware};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"default_middleware"} 1 30 31
330  
331 # Add library paths
332 0 ▶ push @{$self->{libs}}, @libs if @libs;
Branch: 1 branch
BranchTrueFalseTotal
if @libs 0 31 31
333  
334 # Store -M modules for loading
335 31 ▶ push @{$self->{modules}}, @modules if @modules;
Branch: 1 branch
BranchTrueFalseTotal
if @modules 2 29 31
336  
337 # Store -e eval code
338 31 ▶ $self->{eval} = $opts{eval} if defined $opts{eval};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"eval"} 6 25 31
339  
340 # Legacy --app flag
341 31 ▶ if (defined $opts{app}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"app"}) 4 27 31
342 4 $self->{app_spec} = $opts{app};
343 }
344  
345 # Remaining args go to argv (app spec and app args)
346 31 push @{$self->{argv}}, @args;
347 }
348  
349 =head2 mode
350  
351 my $mode = $runner->mode;
352  
353 Returns the current environment mode. Determines mode by checking
354 (in order): explicit C<-E> flag, C<PAGI_ENV> environment variable,
355 or auto-detection based on TTY.
356  
357 =cut
358  
359 63 ▶sub mode {
Subroutine mode: called CC=1 SCAR=0.0
Pod documented
360 63 my ($self) = @_;
361 63 return ($self->_resolve_mode)[0];
362 }
363  
364 # The mode and what decided it, from one precedence chain so the two cannot
365 # disagree. The source matters because the last rule -- whether STDIN is a
366 # terminal -- silently makes production of anything without one: systemd,
367 # docker, cron, CI, a backgrounded shell.
368 75 ▶sub _resolve_mode {
Subroutine _resolve_mode: called CC=4 SCAR=13.9
369 75 my ($self) = @_;
370  
371 75 ▶ return ($self->{env}, '--env') if defined $self->{env};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"env"} 13 62 75
372 62 ▶ return ($ENV{PAGI_ENV}, 'PAGI_ENV') if defined $ENV{PAGI_ENV};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"PAGI_ENV"} 45 17 62
373 17 ▶ return -t STDIN ? ('development', 'tty') : ('production', 'no tty');
Branch: 1 branch
BranchTrueFalseTotal
-t STDIN ? : 0 17 17
374 }
375  
376 # One line saying what is running, in which mode, and why that mode. Emitted in
377 # production as well as development: confirming that a host did NOT come up in
378 # development, wrapping every request in Lint, is worth more than confirming
379 # that it did.
380 # Facts only the runner knows. They are handed to the server rather than printed
381 # here, so startup reads as one aligned block instead of ragged lines from two
382 # layers. Runner is not server-agnostic in this iteration; this is the trade.
383 0 ▶sub _startup_note {
Subroutine _startup_note: not called CC=2 SCAR=17.9
384 0 my ($self, $label, $text) = @_;
385 0 ▶ push @{ $self->{_startup_notes} ||= [] }, [$label, $text];
Condition0%0/2
$self->{"_startup_notes"} ||= []
l!l
00
MC/DC0%0/1
$self->{"_startup_notes"} ||= []
$self->{"_startup_notes"}
Truth table0%0/2
A
A= $self->{"_startup_notes"}
Aresult
11
00
386 0 return;
387 }
388  
389 17 ▶sub _record_startup_summary {
Subroutine _record_startup_summary: called CC=5 SCAR=16.2
390 17 my ($self, $middleware_note) = @_;
391  
392 17 my $mode = $self->mode;
393 17 ▶ $mode .= " ($self->{_mode_source})" if defined $self->{_mode_source};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_mode_source"} 15 2 17
394 17 ▶ $mode .= ", $middleware_note" if defined $middleware_note;
Branch: 1 branch
BranchTrueFalseTotal
if defined $middleware_note 2 15 17
395  
396 17 ▶ unshift @{ $self->{_startup_notes} ||= [] },
Condition50%2/4
$self->{"_startup_notes"} ||= []
l!l
017
$self->{"app_spec"} // "unknown"
l!l
170
MC/DC0%0/1
$self->{"_startup_notes"} ||= []
$self->{"_startup_notes"}
MC/DC0%0/1
$self->{"app_spec"} // "unknown"
$self->{"app_spec"}
Truth table50%1/2
A
A= $self->{"_startup_notes"}
Aresult
11
00
Truth table50%1/2
A
A= $self->{"app_spec"}
Aresult
11
00
397 17 [serving => $self->{app_spec} // 'unknown'],
398 [mode => $mode];
399 17 return;
400 }
401  
402 =head2 load_app
403  
404 my $app = $runner->load_app;
405  
406 Loads the PAGI application based on the app specifier from command
407 line arguments. Every accepted loading form is normalized to and returns the
408 native PAGI app coderef used by the server.
409  
410 =cut
411  
412 23 ▶sub load_app {
Subroutine load_app: called CC=14 SCAR=29.8
Pod documented
413 23 my ($self) = @_;
414  
415 # Add library paths to @INC before loading
416 23 ▶ if (@{$self->{libs}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"libs"};}) 0 23 23
417 0 unshift @INC, @{$self->{libs}};
418 }
419  
420 # Load -M modules before evaluating -e code
421 23 for my $module (@{$self->{modules}}) {
422 # Handle Module=import,args syntax like perl -M
423 0 my ($mod, $imports) = split /=/, $module, 2;
424 0 eval "require $mod";
425 0 ▶ die "Cannot load module $mod: $@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
426 0 ▶ if (defined $imports) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $imports) { } 0 0 0
427 0 my @imports = split /,/, $imports;
428 0 $mod->import(@imports);
429 } else {
430 0 $mod->import;
431 }
432 }
433  
434 # Handle -e inline code
435 23 ▶ if (defined $self->{eval}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"eval"}) 4 19 23
436 4 my $code = $self->{eval};
437 4 my $app = eval $code;
438 4 ▶ die "Error evaluating -e code: $@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
439 4 $app = PAGI::Server::AppNormalizer::normalize_app($app, '-e code');
440 3 $self->{app_spec} = '-e';
441 3 $self->{app} = $app;
442 3 return $app;
443 }
444  
445 # Get app spec from argv if not set via --app
446 19 my @argv = @{$self->{argv}};
447 19 ▶ if (!$self->{app_spec} && @argv) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"app_spec"} and @argv) 8 11 19
Condition66%2/3
not $self->{"app_spec"} and @argv
!ll&&!rl&&r
1108
MC/DC50%1/2
not $self->{"app_spec"} and @argv
not $self->{"app_spec"} @argv
Truth table66%2/3
not(A) and B
A= not $self->{"app_spec"}B= @argv
ABresult
0X0
100
111
448 8 my $first = $argv[0];
449 # Check if first arg looks like an app spec (not a key=value)
450 8 ▶ if ($first !~ /=/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($first =~ /=/) 8 0 8
451 8 $self->{app_spec} = shift @argv;
452 8 $self->{argv} = \@argv;
453 }
454 }
455  
456 19 my $app_spec = $self->{app_spec};
457  
458 # Default: serve current directory
459 19 my %app_args;
460 19 ▶ if (!defined $app_spec) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $app_spec) { } 0 19 19
461 0 $app_spec = 'PAGI::App::Directory';
462 0 %app_args = (root => '.');
463 } else {
464 # Parse constructor args (key=value pairs) from remaining argv
465 19 %app_args = $self->_parse_app_args(@{$self->{argv}});
466 }
467  
468 19 $self->{app_spec} = $app_spec;
469 19 $self->{app_args} = \%app_args;
470  
471 19 my $app;
472 19 ▶ if ($self->_is_module_name($app_spec)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_is_module_name($app_spec)) { } 1 18 19
elsif ($self->_is_file_path($app_spec)) { } 16 2 18
473 1 $app = $self->_load_module($app_spec, %app_args);
474 }
475 elsif ($self->_is_file_path($app_spec)) {
476 16 $app = $self->_load_file($app_spec);
477 }
478 else {
479 # Ambiguous - try as file first, then module
480 2 ▶ if (-f $app_spec) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $app_spec) { } 0 2 2
481 0 $app = $self->_load_file($app_spec);
482 }
483 else {
484 2 $app = $self->_load_module($app_spec, %app_args);
485 }
486 }
487  
488 16 $self->{app} = $app;
489 16 return $app;
490 }
491  
492 =head2 prepare_app
493  
494 my $app = $runner->prepare_app;
495  
496 Loads the app and wraps it with mode-appropriate middleware.
497 In development mode (with default_middleware enabled), wraps
498 with L<PAGI::Middleware::Lint> if available (requires PAGI-Tools).
499  
500 =cut
501  
502 11 ▶sub prepare_app {
Subroutine prepare_app: called CC=5 SCAR=21.5
Pod documented
503 11 my ($self) = @_;
504  
505 11 my $app = $self->load_app;
506  
507 # Wrap with mode middleware unless disabled
508 11 ▶ my $use_middleware = $self->{default_middleware} // 1;
Condition100%2/2
$self->{"default_middleware"} // 1
l!l
110
MC/DC100%1/1
$self->{"default_middleware"} // 1
$self->{"default_middleware"}
Truth table100%2/2
A
A= $self->{"default_middleware"}
Aresult
11
00
509  
510 11 my $middleware_note;
511 11 ▶ if ($self->mode eq 'development') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mode eq "development") 0 11 11
512 0 ▶ if (!$use_middleware) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $use_middleware) { } 0 0 0
elsif (eval { do { require PAGI::Middleware::Lint; 1 } }) { } 0 0 0
513 # Worth saying: otherwise Lint's absence looks like a fault.
514 0 $middleware_note = 'default middleware disabled';
515 }
516 0 elsif (eval { require PAGI::Middleware::Lint; 1 }) {
517 0 $app = PAGI::Middleware::Lint->new(strict => 1)->wrap($app);
518 0 $middleware_note = 'Lint enabled';
519 }
520 else {
521 0 $middleware_note = 'Lint unavailable -- install PAGI-Tools';
522 }
523 }
524  
525 11 $self->_record_startup_summary($middleware_note);
526  
527 11 $self->{app} = $app;
528 11 return $app;
529 }
530  
531 =head2 load_server
532  
533 my $server = $runner->load_server;
534  
535 Constructs the configured server class (C<-s CLASS>, default
536 L<PAGI::Server>) according to this runner's backend convention:
537 C<< $class->new(%options) >> followed by C<< $server->run >>. This is a
538 PAGI::Server::Runner plugin interface, not a construction API required by
539 L<PAGI::Spec::Server>.
540  
541 Creates the server instance with the prepared app and configuration.
542 Parses server-specific options and passes them to the server constructor.
543  
544 =cut
545  
546 16 ▶sub load_server {
Subroutine load_server: called CC=17 SCAR=32.0
Pod documented
547 16 my ($self) = @_;
548  
549 16 ▶ my $server_class = $self->{server} // 'PAGI::Server';
Condition100%2/2
$self->{"server"} // "PAGI::Server"
l!l
106
MC/DC100%1/1
$self->{"server"} // "PAGI::Server"
$self->{"server"}
Truth table100%2/2
A
A= $self->{"server"}
Aresult
11
00
550  
551 # Load server class
552 16 my $server_file = $server_class;
553 16 $server_file =~ s{::}{/}g;
554 16 $server_file .= '.pm';
555  
556 16 eval { require $server_file };
557 16 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 16 16
558 0 die "Cannot load server '$server_class': $@\n";
559 }
560  
561 # Get server-specific options (passed from bin/pagi-server or similar)
562 16 ▶ my %server_opts = %{$self->{server_options} // {}};
Condition50%1/2
$self->{"server_options"} // {}
l!l
160
MC/DC0%0/1
$self->{"server_options"} // {}
$self->{"server_options"}
Truth table50%1/2
A
A= $self->{"server_options"}
Aresult
11
00
563  
564 # Hand over what only the runner knows, for the startup block.
565 16 ▶ $server_opts{startup_notes} = $self->{_startup_notes} || [];
Condition100%2/2
$self->{'_startup_notes'} || []
l!l
106
MC/DC100%1/1
$self->{'_startup_notes'} || []
$self->{'_startup_notes'}
Truth table100%2/2
A
A= $self->{'_startup_notes'}
Aresult
11
00
566  
567 # Handle access log
568 # Production mode disables logging by default for performance
569 # Use --access-log to explicitly enable in production
570 16 my $access_log;
571 16 my $disable_log = 0;
572  
573 16 ▶ if ($self->{no_access_log}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($self->{'no_access_log'}) { } 0 16 16
elsif ($self->{'access_log'}) { } 0 16 16
elsif ($self->mode eq 'production') { } 16 0 16
574 # Explicit --no-access-log
575 0 $disable_log = 1;
576 }
577 elsif ($self->{access_log}) {
578 # Explicit --access-log FILE
579 open $access_log, '>>', $self->{access_log}
580 0 ▶ or die "Cannot open access log $self->{access_log}: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open $access_log, ">>", $self->{"access_log"} or die qq[Cannot open access log $self->{"access_log"}: $!\n] 0 0 0
581 }
582 elsif ($self->mode eq 'production') {
583 # Production mode: disable logging by default
584 16 $disable_log = 1;
585 }
586 # else: development mode uses server default (STDERR)
587  
588 # Build server
589 # Omit host/port when socket or listen is provided (mutually exclusive)
590 16 ▶ my $has_socket_or_listen = exists $server_opts{socket} || exists $server_opts{listen};
Condition100%3/3
exists $server_opts{'socket'} || exists $server_opts{'listen'}
l!l&&r!l&&!r
1114
MC/DC100%2/2
exists $server_opts{'socket'} || exists $server_opts{'listen'}
exists $server_opts{'socket'} exists $server_opts{'listen'}
Truth table100%3/3
A || B
A= exists $server_opts{'socket'}B= exists $server_opts{'listen'}
ABresult
1X1
011
000
591 return $server_class->new(
592 app => $self->{app},
593 ($has_socket_or_listen ? () : (
594 host => $self->{host} // '127.0.0.1',
595 port => $self->{port} // 5000,
596 )),
597 quiet => $self->{quiet} // 0,
598 16 ▶ ($self->{loop} ? (loop_type => $self->{loop}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$has_socket_or_listen ? : 2 14 16
$self->{'loop'} ? : 0 16 16
defined $access_log || $disable_log ? : 16 0 16
Condition55%5/9
$self->{"host"} // "127.0.0.1"
l!l
014
$self->{"port"} // 5000
l!l
77
$self->{"quiet"} // 0
l!l
160
defined $access_log or $disable_log
l!l&&r!l&&!r
0160
MC/DC0%0/1
$self->{"host"} // "127.0.0.1"
$self->{"host"}
MC/DC100%1/1
$self->{"port"} // 5000
$self->{"port"}
MC/DC0%0/1
$self->{"quiet"} // 0
$self->{"quiet"}
MC/DC0%0/2
defined $access_log or $disable_log
defined $access_log $disable_log
Truth table50%1/2
A
A= $self->{"host"}
Aresult
11
00
Truth table100%2/2
A
A= $self->{"port"}
Aresult
11
00
Truth table50%1/2
A
A= $self->{"quiet"}
Aresult
11
00
Truth table33%1/3
A or B
A= defined $access_logB= $disable_log
ABresult
1X1
011
000
599 (defined $access_log || $disable_log
600 ? (access_log => $access_log) : ()),
601 %server_opts,
602 );
603 }
604  
605  
606 =head2 run
607  
608 PAGI::Server::Runner->run(@ARGV);
609 $runner->run(@ARGV);
610  
611 Main entry point. Parses options, loads the app, creates the server,
612 and delegates to C<< $server->run() >> which manages the event loop.
613  
614 =cut
615  
616 # Package variable for END block cleanup
617 17 our $_current_runner;
618  
619 10 ▶sub run {
Subroutine run: called CC=9 SCAR=26.4
Pod documented
620 10 my $self = shift;
621  
622 # Support both class and instance method
623 10 ▶ unless (ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 10 0 10
624 10 $self = $self->new;
625 }
626  
627 # Parse options
628 10 $self->parse_options(@_);
629  
630 # Open the error log and point STDERR at it before anything can report a
631 # problem. Future::IO configuration, app loading and listener binding all
632 # diagnose through STDERR, and every distribution in the ecosystem warns
633 # there; opening later would lose whatever was said in the meantime.
634 10 $self->_open_error_log;
635 10 $self->_redirect_stderr_to_error_log;
636  
637 # Export resolved mode to environment so apps can check it
638 # (similar to Plack's PLACK_ENV). Note what decided the mode first: after
639 # this assignment PAGI_ENV is always set, and would claim the credit.
640 10 (my $resolved_mode, $self->{_mode_source}) = $self->_resolve_mode;
641 10 $ENV{PAGI_ENV} = $resolved_mode;
642  
643 # Configure Future::IO for IO::Async if available
644 # This enables Future::IO-based libraries (Async::Redis, etc.) and
645 # PAGI::SSE->every() to work seamlessly under pagi-server
646 10 $self->_configure_future_io;
647  
648 # Handle --version
649 10 ▶ if ($self->{show_version}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"show_version"}) 0 10 10
650 0 $self->_show_version;
651 0 return;
652 }
653  
654 # Handle --help
655 10 ▶ if ($self->{show_help}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"show_help"}) 0 10 10
656 0 $self->_show_help;
657 0 return;
658 }
659  
660 # Prepare app (load + wrap with middleware)
661 10 $self->prepare_app;
662  
663 # Create server
664 9 my $server = $self->load_server;
665  
666 # Daemonize before running. The error log's descriptor was opened above and
667 # is inherited across both forks, so --error-log keeps bind errors and
668 # everything after them; without it, daemonizing still discards STDERR.
669 8 ▶ if ($self->{daemonize}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"daemonize"}) 0 8 8
670 0 $self->_daemonize;
671 }
672  
673 # Write PID file (after daemonizing so we record the daemon's PID)
674 8 ▶ if ($self->{pid_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pid_file"}) 0 8 8
675 0 $self->_write_pid_file($self->{pid_file});
676 # Store for END block cleanup
677 0 $_current_runner = $self;
678 }
679  
680 # Drop privileges
681 8 ▶ if ($self->{user} || $self->{group}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"user"} or $self->{"group"}) 0 8 8
Condition33%1/3
$self->{"user"} or $self->{"group"}
l!l&&r!l&&!r
008
MC/DC0%0/2
$self->{"user"} or $self->{"group"}
$self->{"user"} $self->{"group"}
Truth table33%1/3
A or B
A= $self->{"user"}B= $self->{"group"}
ABresult
1X1
011
000
682 0 $self->_drop_privileges;
683 }
684  
685 # Run server (server owns the event loop)
686 8 $server->run;
687  
688 # Cleanup PID file on normal exit
689 5 ▶ $self->_remove_pid_file if $self->{_pid_file_path};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_pid_file_path"} 0 5 5
690 }
691  
692 # END block for PID file cleanup on abnormal exit
693 16 ▶END {
Subroutine END: called CC=3 SCAR=15.4
694 16 ▶ if ($_current_runner && $_current_runner->{_pid_file_path}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($PAGI::Server::Runner::_current_runner and $PAGI::Server::Runner::_current_runner->{"_pid_file_path"}) 0 16 16
Condition33%1/3
$PAGI::Server::Runner::_current_runner and $PAGI::Server::Runner::_current_runner->{"_pid_file_path"}
!ll&&!rl&&r
1600
MC/DC0%0/2
$PAGI::Server::Runner::_current_runner and $PAGI::Server::Runner::_current_runner->{"_pid_file_path"}
$PAGI::Server::Runner::_current_runner $PAGI::Server::Runner::_current_runner->{"_pid_file_path"}
Truth table33%1/3
A and B
A= $PAGI::Server::Runner::_current_runnerB= $PAGI::Server::Runner::_current_runner->{"_pid_file_path"}
ABresult
0X0
100
111
695 0 $_current_runner->_remove_pid_file;
696 }
697 }
698  
699 # Internal methods
700  
701 10 ▶sub _configure_future_io {
Subroutine _configure_future_io: called CC=3 SCAR=11.6
702 10 my ($self) = @_;
703  
704 # Try to configure Future::IO for IO::Async
705 # This enables seamless use of Future::IO-based libraries under pagi-server
706 10 my $configured = eval {
707 10 require Future::IO::Impl::IOAsync;
708 10 1;
709 };
710  
711 10 ▶ if ($configured) {
Branch: 1 branch
BranchTrueFalseTotal
if ($configured) 10 0 10
712 # Report in non-production mode
713 10 ▶ if ($self->mode ne 'production') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mode ne "production") 0 10 10
714 0 $self->_startup_note('future.io' => 'configured for IO::Async');
715 }
716 }
717 # If Future::IO::Impl::IOAsync not installed, that's fine - user just
718 # won't have Future::IO integration. Apps that need it will get a
719 # helpful error message from PAGI::SSE->every() or similar.
720 }
721  
722 23 ▶sub _is_module_name {
Subroutine _is_module_name: called CC=1 SCAR=0.0
723 23 my ($self, $spec) = @_;
724 23 return $spec =~ /::/;
725 }
726  
727 23 ▶sub _is_file_path {
Subroutine _is_file_path: called CC=2 SCAR=6.9
728 23 my ($self, $spec) = @_;
729 23 ▶ return $spec =~ m{/} || $spec =~ /\.(?:pl|psgi)$/i;
Condition100%3/3
$spec =~ m[/] || $spec =~ /\.(?:pl|psgi)$/i
l!l&&r!l&&!r
1733
MC/DC100%2/2
$spec =~ m[/] || $spec =~ /\.(?:pl|psgi)$/i
$spec =~ m[/] $spec =~ /\.(?:pl|psgi)$/i
Truth table100%3/3
A || B
A= $spec =~ m[/]B= $spec =~ /\.(?:pl|psgi)$/i
ABresult
1X1
011
000
730 }
731  
732 3 ▶sub _load_module {
Subroutine _load_module: called CC=5 SCAR=16.2
733 3 my ($self, $module, %args) = @_;
734  
735 # Validate module name (basic security check)
736 3 ▶ die "Invalid module name: $module\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $module =~ /^[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*$/ 0 3 3
737 unless $module =~ /^[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*$/;
738  
739 # Try to load the module
740 3 my $file = $module;
741 3 $file =~ s{::}{/}g;
742 3 $file .= '.pm';
743  
744 3 eval { require $file };
745 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 2 3
746 1 die "Cannot find module '$module': $@\n";
747 }
748  
749 2 ▶ die "Module '$module' does not have a new() method\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $module->can("new") 0 2 2
750 unless $module->can('new');
751  
752 # Get the module's actual file path for correct home directory detection
753 2 my $module_file = $INC{$file};
754  
755 # Instantiate, then normalize the resulting value. Discovery may produce
756 # either a native PAGI coderef or an application-provider object.
757 2 my $instance = eval { $module->new(%args, _caller_file => $module_file) };
758 2 ▶ die "Error constructing module '$module': $@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
759  
760 2 return PAGI::Server::AppNormalizer::normalize_app(
761 $instance,
762 "Module '$module' constructor",
763 );
764 }
765  
766 16 ▶sub _load_file {
Subroutine _load_file: called CC=6 SCAR=19.3
767 16 my ($self, $file) = @_;
768  
769 # Convert to absolute path
770 16 $file = File::Spec->rel2abs($file);
771  
772 16 ▶ die "App file not found: $file\n" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 15 16
773  
774 # Match plackup behavior so FindBin::Bin resolves to the app file directory
775 15 local $0 = $file;
776 15 local @ARGV = ($file);
777 15 ▶ if (exists $INC{'FindBin.pm'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $INC{"FindBin.pm"}) 15 0 15
778 15 FindBin::again();
779 }
780  
781 15 my $app = do $file;
782  
783 15 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 15 15
784 0 die "Error loading $file: $@\n";
785 }
786 15 ▶ if (!defined $app && $!) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $app and $!) 0 15 15
Condition33%1/3
not defined $app and $!
!ll&&!rl&&r
1500
MC/DC0%0/2
not defined $app and $!
not defined $app $!
Truth table33%1/3
not(A) and B
A= not defined $appB= $!
ABresult
0X0
100
111
787 0 die "Error reading $file: $!\n";
788 }
789 15 return PAGI::Server::AppNormalizer::normalize_app($app, 'App file');
790 }
791  
792 21 ▶sub _parse_app_args {
Subroutine _parse_app_args: called CC=3 SCAR=11.0
793 21 my ($self, @args) = @_;
794  
795 21 my %result;
796 21 for my $arg (@args) {
797 5 ▶ if ($arg =~ /^([^=]+)=(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg =~ /^([^=]+)=(.*)$/) { } 4 1 5
798 4 $result{$1} = $2;
799 }
800 else {
801 1 $self->_log(warn => "Ignoring argument without '=': $arg");
802 }
803 }
804 21 return %result;
805 }
806  
807 0 ▶sub _show_help {
Subroutine _show_help: not called CC=1 SCAR=6.9
808 0 my ($self) = @_;
809  
810 0 print <<'HELP';
811 Usage: pagi-server [options] [app] [key=value ...]
812  
813 Common Options (handled by Runner):
814 -I, --lib PATH Add PATH to @INC (repeatable, like perl -I)
815 -a, --app FILE Load app from file (legacy option)
816 -o, --host HOST Bind address (default: 127.0.0.1)
817 -p, --port PORT Bind port (default: 5000)
818 -s, --server CLASS Server class (default: PAGI::Server)
819 -E, --env MODE Environment mode (development, production, none)
820 -l, --loop BACKEND Event loop backend (EV, Epoll, UV, Poll)
821 --access-log FILE Access log file (default: STDERR)
822 --no-access-log Disable access logging
823 --error-log FILE Diagnostic log file (default: STDERR)
824 -D, --daemonize Run as background daemon
825 --pid FILE Write PID to file
826 --user USER Run as specified user (after binding)
827 --group GROUP Run as specified group (after binding)
828 -q, --quiet Report errors only (shorthand for --log-level error)
829 --no-default-middleware Disable mode-based middleware
830 -v, --version Show version info
831 --help Show this help
832  
833 Environment Modes:
834 development Auto-enable Lint middleware if PAGI-Tools installed (default if TTY)
835 production No auto-middleware (default if no TTY)
836 none Explicit opt-out of all auto-middleware
837  
838 App can be:
839 Module name: pagi-server PAGI::App::Directory root=/var/www
840 File path: pagi-server ./app.pl
841 Default: pagi-server (serves current directory)
842  
843 Server-specific options are handled by the server CLI (e.g., pagi-server).
844 See: perldoc pagi-server
845  
846 HELP
847 }
848  
849 3 ▶sub _show_version {
Subroutine _show_version: called CC=4 SCAR=14.0
850 3 my ($self) = @_;
851  
852 3 ▶ my $server_class = $self->{server} // 'PAGI::Server';
Condition50%1/2
$self->{"server"} // "PAGI::Server"
l!l
30
MC/DC0%0/1
$self->{"server"} // "PAGI::Server"
$self->{"server"}
Truth table50%1/2
A
A= $self->{"server"}
Aresult
11
00
853 3 (my $server_file = $server_class) =~ s{::}{/}g;
854 3 eval { require "$server_file.pm" };
855  
856 3 require File::Basename;
857 3 my $prog = File::Basename::basename($0);
858 0 ▶ my $pagi_version = eval { require PAGI; PAGI->VERSION } // 'unknown';
Condition50%1/2
eval { do { require PAGI; "PAGI"->VERSION } } // "unknown"
l!l
03
MC/DC0%0/1
eval { do { require PAGI; "PAGI"->VERSION } } // "unknown"
eval { do { require PAGI; "PAGI"->VERSION } }
Truth table50%1/2
A
A= eval { do { require PAGI; "PAGI"->VERSION } }
Aresult
11
00
859 3 ▶ my $server_version = $server_class->VERSION // 'unknown';
Condition100%2/2
$server_class->VERSION // "unknown"
l!l
21
MC/DC100%1/1
$server_class->VERSION // "unknown"
$server_class->VERSION
Truth table100%2/2
A
A= $server_class->VERSION
Aresult
11
00
860  
861 3 print "$prog (PAGI $pagi_version, $server_class $server_version)\n";
862 }
863  
864 0 ▶sub _daemonize {
Subroutine _daemonize: not called CC=7 SCAR=40.3
865 0 my ($self) = @_;
866  
867 # First fork - parent exits, child continues
868 0 my $pid = fork();
869 0 ▶ die "Cannot fork: $!" unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 0 0
870 0 ▶ exit(0) if $pid; # Parent exits
Branch: 1 branch
BranchTrueFalseTotal
if $pid 0 0 0
871  
872 # Child becomes session leader
873 0 ▶ setsid() or die "Cannot create new session: $!";
Branch: 1 branch
BranchTrueFalseTotal
setsid() or die "Cannot create new session: $!" 0 0 0
874  
875 # Second fork - prevent acquiring a controlling terminal
876 0 $pid = fork();
877 0 ▶ die "Cannot fork: $!" unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 0 0
878 0 ▶ exit(0) if $pid; # First child exits
Branch: 1 branch
BranchTrueFalseTotal
if $pid 0 0 0
879  
880 # Grandchild continues as daemon
881 # Change to root directory to avoid blocking unmounts
882 0 ▶ chdir('/') or die "Cannot chdir to /: $!";
Branch: 1 branch
BranchTrueFalseTotal
chdir "/" or die "Cannot chdir to /: $!" 0 0 0
883  
884 # Clear umask
885 0 umask(0);
886  
887 0 $self->_redirect_std_handles;
888  
889 0 return $$; # Return daemon PID
890 }
891  
892 # Opens the error log named by --error-log and keeps the handle on the runner.
893 # Called before any fork so the descriptor survives daemonizing, exactly as the
894 # access log's handle does.
895 # Runner keeps its own threshold rather than borrowing the server's logger,
896 # which would tie it to one server class. It reads log_level out of
897 # server_options when the operator asked for one -- read-only, optional, and
898 # nothing new is passed down, so a server that has no such option is
899 # unaffected and Runner simply keeps its default.
900 17 my %_LOG_LEVELS = (debug => 1, info => 2, warn => 3, error => 4, fatal => 5);
901  
902 14 ▶sub _log_level_num {
Subroutine _log_level_num: called CC=4 SCAR=14.2
903 14 my ($self) = @_;
904  
905 my $level = $self->{server_options}{log_level}
906 14 ▶ // ($self->{quiet} ? 'error' : 'info');
Branch: 1 branch
BranchTrueFalseTotal
$self->{'quiet'} ? : 3 4 7
Condition100%2/2
$self->{"server_options"}{"log_level"} // ($self->{"quiet"} ? "error" : "info")
l!l
77
MC/DC100%1/1
$self->{"server_options"}{"log_level"} // ($self->{"quiet"} ? "error" : "info")
$self->{"server_options"}{"log_level"}
Truth table100%2/2
A
A= $self->{"server_options"}{"log_level"}
Aresult
11
00
907  
908 14 ▶ return $_LOG_LEVELS{$level} // $_LOG_LEVELS{info};
Condition33%1/3
$_LOG_LEVELS{$level} // $_LOG_LEVELS{"info"}
l!l&&r!l&&!r
1400
MC/DC0%0/2
$_LOG_LEVELS{$level} // $_LOG_LEVELS{"info"}
$_LOG_LEVELS{$level} $_LOG_LEVELS{"info"}
Truth table33%1/3
A // B
A= $_LOG_LEVELS{$level}B= $_LOG_LEVELS{"info"}
ABresult
1X1
011
000
909 }
910  
911 14 ▶sub _log {
Subroutine _log: called CC=3 SCAR=11.1
912 14 my ($self, $level, $msg) = @_;
913  
914 14 ▶ return if ($_LOG_LEVELS{$level} // 2) < $self->_log_level_num;
Branch: 1 branch
BranchTrueFalseTotal
if ($_LOG_LEVELS{$level} // 2) < $self->_log_level_num 6 8 14
Condition50%1/2
$_LOG_LEVELS{$level} // 2
l!l
140
MC/DC0%0/1
$_LOG_LEVELS{$level} // 2
$_LOG_LEVELS{$level}
Truth table50%1/2
A
A= $_LOG_LEVELS{$level}
Aresult
11
00
915 8 warn "$msg\n";
916 }
917  
918 11 ▶sub _open_error_log {
Subroutine _open_error_log: called CC=3 SCAR=11.0
919 11 my ($self) = @_;
920  
921 11 ▶ return unless $self->{error_log};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"error_log"} 10 1 11
922  
923 open my $fh, '>>', $self->{error_log}
924 1 ▶ or die "Cannot open error log $self->{error_log}: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">>", $self->{"error_log"} or die qq[Cannot open error log $self->{"error_log"}: $!\n] 1 0 1
925 1 $fh->autoflush(1);
926  
927 1 return $self->{_error_log_fh} = $fh;
928 }
929  
930 # Points STDERR at an already-opened error log. Returns false when no error log
931 # was configured, leaving the caller to decide what STDERR should become.
932 10 ▶sub _redirect_stderr_to_error_log {
Subroutine _redirect_stderr_to_error_log: called CC=3 SCAR=17.3
933 10 my ($self) = @_;
934  
935 10 ▶ my $fh = $self->{_error_log_fh} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $fh = $self->{"_error_log_fh"} or return 0 0 10 10
936  
937 0 ▶ open(STDERR, '>&', $fh) or die "Cannot redirect STDERR to error log: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&", $fh or die "Cannot redirect STDERR to error log: $!\n" 0 0 0
938 0 STDERR->autoflush(1);
939  
940 0 return 1;
941 }
942  
943 0 ▶sub _redirect_std_handles {
Subroutine _redirect_std_handles: not called CC=5 SCAR=34.0
944 0 my ($self) = @_;
945  
946 0 ▶ open(STDIN, '<', '/dev/null') or die "Cannot redirect STDIN: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<", "/dev/null" or die "Cannot redirect STDIN: $!" 0 0 0
947 0 ▶ open(STDOUT, '>', '/dev/null') or die "Cannot redirect STDOUT: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">", "/dev/null" or die "Cannot redirect STDOUT: $!" 0 0 0
948  
949 # Diagnostics reach STDERR from every PAGI distribution, most of them as a
950 # bare warn that never passes through the server's own logger. Discarding
951 # it is only correct when the operator has named nowhere else to put it.
952 0 ▶ return if $self->_redirect_stderr_to_error_log;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_redirect_stderr_to_error_log 0 0 0
953  
954 0 ▶ open(STDERR, '>', '/dev/null') or die "Cannot redirect STDERR: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">", "/dev/null" or die "Cannot redirect STDERR: $!" 0 0 0
955 }
956  
957 2 ▶sub _write_pid_file {
Subroutine _write_pid_file: called CC=2 SCAR=7.0
958 2 my ($self, $pid_file) = @_;
959  
960 2 ▶ open(my $fh, '>', $pid_file)
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $pid_file or die "Cannot write PID file ${pid_file}: $!\n" 2 0 2
961 or die "Cannot write PID file $pid_file: $!\n";
962 2 print $fh "$$\n";
963 2 close($fh);
964  
965 # Store for cleanup
966 2 $self->{_pid_file_path} = $pid_file;
967 }
968  
969 3 ▶sub _remove_pid_file {
Subroutine _remove_pid_file: called CC=2 SCAR=7.1
970 3 my ($self) = @_;
971  
972 3 ▶ return unless $self->{_pid_file_path};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_pid_file_path"} 0 3 3
973 3 unlink($self->{_pid_file_path});
974 }
975  
976 5 ▶sub _drop_privileges {
Subroutine _drop_privileges: called CC=11 SCAR=39.3
977 5 my ($self) = @_;
978  
979 5 my $user = $self->{user};
980 5 my $group = $self->{group};
981  
982 5 ▶ return unless $user || $group;
Branch: 1 branch
BranchTrueFalseTotal
unless $user or $group 1 4 5
Condition100%3/3
$user or $group
l!l&&r!l&&!r
221
MC/DC100%2/2
$user or $group
$user $group
Truth table100%3/3
A or B
A= $userB= $group
ABresult
1X1
011
000
983  
984 # Must be root to change user/group
985 4 ▶ if ($> != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($> != 0) 4 0 4
986 4 die "Must run as root to use --user/--group\n";
987 }
988  
989 # Change group first (while still root)
990 0 ▶ if ($group) {
Branch: 1 branch
BranchTrueFalseTotal
if ($group) 0 0 0
991 0 my $gid = getgrnam($group);
992 0 ▶ die "Unknown group: $group\n" unless defined $gid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gid 0 0 0
993  
994 # Set both real and effective GID
995 0 $( = $) = $gid;
996 0 ▶ die "Cannot change to group $group: $!\n" if $) != $gid;
Branch: 1 branch
BranchTrueFalseTotal
if $) != $gid 0 0 0
997 }
998  
999 # Then change user
1000 0 ▶ if ($user) {
Branch: 1 branch
BranchTrueFalseTotal
if ($user) 0 0 0
1001 0 my ($uid, $gid) = (getpwnam($user))[2, 3];
1002 0 ▶ die "Unknown user: $user\n" unless defined $uid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $uid 0 0 0
1003  
1004 # If no group specified, use user's primary group
1005 0 ▶ unless ($group) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($group) 0 0 0
1006 0 $( = $) = $gid;
1007 }
1008  
1009 # Set both real and effective UID
1010 0 $< = $> = $uid;
1011 0 ▶ die "Cannot change to user $user: $!\n" if $> != $uid;
Branch: 1 branch
BranchTrueFalseTotal
if $> != $uid 0 0 0
1012 }
1013 }
1014  
1015 17 1;
1016  
1017 __END__
« blib/lib/PAGI/Server/Protocol/HTTP1.pm ↑ Summary blib/lib/PAGI/Server/Protocol/HTTP2.pm »