bin/tstatd

filter: Statementstmt 62.8% 260 / 414 Branchbran 31.3% 64 / 204 Conditioncond 34.6% 17 / 49 MC/DCmcdc 3.7% 1 / 27 Subroutinesub 64.5% 31 / 48 Podpod n/a totaltotal 50.2% 373 / 742 CC 80 SCAR 38.8
CC
80
Cov
51%
__ANON__
179.3
__ANON__
47.8
__ANON__
25.9
CRAP 48.6
↑ Summary blib/lib/Tail/Stat/Plugin/nginx.pm »
1 #!/usr/bin/env perl
2  
3 =head1 NAME
4  
5 tstatd - Logs real-time accounting daemon
6  
7 SYNOPSIS
8  
9 tstatd [ options ] plugin [zone1:]wildcard1 .. [zoneN:]wildcardN
10  
11 OPTIONS
12  
13 =over
14  
15 =item -a I<zone>, --agregate-zone=I<zone>
16  
17 Agregate data from all anonymous logs (wildcards without explicit
18 zone specified) into I<zone>. Default behavior is to create new
19 zone for each anonymous log from its file name.
20  
21 =item -b I<file>, --database-file=I<file>
22  
23 Use I<file> as persistent storage to keep accumulated data across
24 daemon restarts. Default is auto generated from daemon name,
25 specified identity and '.db' suffix.
26  
27 =item --basename
28  
29 Use only base name (excluding directories and suffix) of anonymous log file
30 for auto-created zones.
31  
32 =item -c I<dir>, --change-dir=I<dir>
33  
34 Change current directory to I<dir> before wildcards expanding.
35  
36 =item -d, --debug
37  
38 Composition of options: C<--foreground> and C<--log-level=debug>.
39  
40 =item -f, --foreground
41  
42 Don't detach daemon from control terminal, logging to C<stderr> instead
43 log file or syslog.
44  
45 =item --log-facility=I<name>
46  
47 Use I<name> as C<facility> for syslog logging (see syslog (3) for list
48 of available values). Default is 'daemon'.
49  
50 =item --log-level=I<level>
51  
52 Set minimal logging level to I<level> (see syslog (3) for list of available
53 values). Default is 'notice'.
54  
55 =item --log-file=I<file>
56  
57 Use logging to I<file> instead of syslog logging (which is default).
58  
59 =item -e I<num>, --expand-period=I<num>
60  
61 Do wildcards re-expanding and checking for new and missed logs
62 every I<num> seconds. Default is '60'.
63  
64 =item -h, --help
65  
66 Print brief help message about available options.
67  
68 =item -i I<string>, --identity=I<string>
69  
70 Just a string used in title of daemon process, syslog ident (see syslog(3)),
71 C<--database-file> and C<--pid-file>. Idea behind this options - multiple
72 C<tstatd> instances running simultaneosly.
73  
74 =item -l [I<address>:]I<port>, --listen=[I<address>:]I<port>
75  
76 Specify I<address> and I<port> for TCP listen socket binding.
77 Default is '127.0.0.1:3638'.
78  
79 =item --multiple
80  
81 With this option specified same log file could be included into several
82 zones (if log name satisifies several wildcards). Default behavior is to
83 include log file only in first satisified zone.
84  
85 =item -n I<num>, --windows-num=I<num>
86  
87 Set number of sliding-windows to I<num>. Default is '60'.
88  
89 =item -o I<string>, --options=I<string>
90  
91 Comma-separated plugin supported options (like a mount (8) options).
92  
93 =item --override-from=I<file>
94  
95 Load content of I<file> into plugin package namespace.
96 This is way to easy customize plugin behavior without creating
97 another plugin.
98  
99 =item -p I<file>, --pid-file=I<file>
100  
101 Use I<file> to keep daemon process id. Default is auto generated
102 from daemon name, specified identity and '.pid' suffix.
103  
104 =item --parse-error=I<level>
105  
106 Do logging with I<level> (see syslog (3) for available values) about
107 all unparsed log lines. Hint: use 'none' for ignoring such lines.
108 Default is defining by plugin and usually is 'debug'.
109  
110 =item -r I<pattern>, --regex=I<pattern>
111  
112 Use I<pattern> instead of plugin default regular expression for
113 matching log lines.
114  
115 =item --regex-from=I<file>
116  
117 Load regular expression from I<file> and use instead of plugin default
118 regular expression for matching log lines.
119  
120 =item -s I<num>, --store-period=I<num>
121  
122 Store accumulated data in a persistent storage every I<num> seconds.
123 Default is '60'.
124  
125 =item --timer=I<zone>:I<timer>:I<num>
126  
127 Create named I<timer> firing every I<num> seconds for I<zone>.
128  
129 =item -u <user>, --user=I<user>
130  
131 Change effective privileges of daemon process to I<user>.
132  
133 =item -v, --version
134  
135 Print version information of C<tstatd> and exit.
136  
137 =item -w I<num>, --window-size=<num>
138  
139 Set size (duration) of sliding window to I<num> seconds.
140 Default is '10'.
141  
142 =back
143  
144  
145 =head1 SEE ALSO
146  
147 L<Tail::Stat>
148  
149  
150 =head1 AUTHOR
151  
152 Oleg A. Mamontov, C<< <oleg@mamontov.net> >>
153  
154  
155 =head1 COPYRIGHT & LICENSE
156  
157 This program is free software; you can redistribute it and/or modify it
158 under the terms of either: the GNU General Public License as published
159 by the Free Software Foundation; or the Artistic License.
160  
161 See http://dev.perl.org/licenses/ for more information.
162  
163  
164 =cut
165  
166 11 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
167 11 ▶use warnings qw(all);
Subroutine BEGIN: called CC=1 SCAR=0.0
168  
169 11 ▶use Cwd qw(getcwd realpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
170 11 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
171 11 ▶use File::Basename qw(fileparse);
Subroutine BEGIN: called CC=1 SCAR=0.0
172 11 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
173 11 ▶use Getopt::Long qw(:config no_auto_abbrev bundling);
Subroutine BEGIN: called CC=1 SCAR=0.0
174 11 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
175 11 ▶use List::Util qw(min);
Subroutine BEGIN: called CC=1 SCAR=0.0
176 11 ▶use Log::Dispatch;
Subroutine BEGIN: called CC=1 SCAR=0.0
177 11 ▶use Log::Dispatch::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
178 11 ▶use Log::Dispatch::Screen;
Subroutine BEGIN: called CC=1 SCAR=0.0
179 11 ▶use Log::Dispatch::Syslog;
Subroutine BEGIN: called CC=1 SCAR=0.0
180 11 ▶use Pid::File::Flock;
Subroutine BEGIN: called CC=1 SCAR=0.0
181 11 ▶use POE qw(Wheel::FollowTail Wheel::ListenAccept Wheel::ReadWrite);
Subroutine BEGIN: called CC=1 SCAR=0.0
182 11 ▶use POSIX qw(setsid setuid strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
183 11 ▶use Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
184 11 ▶use Tail::Stat;
Subroutine BEGIN: called CC=1 SCAR=0.0
185 11 ▶use Tie::Hash::Indexed;
Subroutine BEGIN: called CC=1 SCAR=0.0
186  
187 # parse command line
188 11 my %opts;
189 11 ▶GetOptions(\%opts, qw/
Branch: 1 branch
BranchTrueFalseTotal
&GetOptions(\%opts, ("agregate-zone|a=s", "basename", "database-file|b=s", "change-dir|c=s", "debug|d", "foreground|f", "log-facility=s", "log-file=s", "log-level=s", "expand-period|e=i", "help|h", "identity|i=s", "listen|l=s", "windows-num|n=i", "multiple", "options|o=s", "override-from=s\@", "parse-error=s", "pid-file|p=s", "regex|r=s", "regex-from=s", "timer=s\@", "store-period|s=i", "user|u=s", "version|v", "window-size|w=i")) or die usage() 0 11 11
190 agregate-zone|a=s
191 basename
192 database-file|b=s
193 change-dir|c=s
194 debug|d
195 foreground|f
196 log-facility=s
197 log-file=s
198 log-level=s
199 expand-period|e=i
200 help|h
201 identity|i=s
202 listen|l=s
203 windows-num|n=i
204 multiple
205 options|o=s
206 override-from=s@
207 parse-error=s
208 pid-file|p=s
209 regex|r=s
210 regex-from=s
211 timer=s@
212 store-period|s=i
213 user|u=s
214 version|v
215 window-size|w=i
216 /) or die usage();
217  
218 # explicitly requested help
219 11 ▶die usage() if $opts{help};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"help"} 0 11 11
220  
221 # version requested
222 11 ▶print version() and exit if $opts{version};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"version"} 0 11 11
Condition25%1/4
$opts{'version'} && (print(version()) && exit)
!ll
110
print version() and exit
!ll
00
MC/DC0%0/2
$opts{'version'} && (print(version()) && exit)
$opts{'version'} print version()
Truth table33%1/3
A && B
A= $opts{'version'}B= print version()
ABresult
0X0
100
111
223  
224 # no arguments
225 11 ▶die usage() if @ARGV < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @ARGV < 2 0 11 11
226  
227 # try to load requested plugin
228 11 my $pname = shift @ARGV;
229 11 my $pclass = "Tail::Stat::Plugin::$pname";
230 11 ▶eval "require $pclass" or die "can't load plugin '$pname': $@\n";
Branch: 1 branch
BranchTrueFalseTotal
eval "require $pclass" or die "can't load plugin '${pname}': $@\n" 0 11 11
231  
232  
233 # parameters defaults & validation
234 11 ▶if (exists $opts{'agregate-zone'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"agregate-zone"}) 0 11 11
235 die "invalid zone: '$opts{'agregate-zone'}'\n"
236 0 ▶ if $opts{'agregate-zone'} =~ /[^a-z0-9_-]/;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"agregate-zone"} =~ /[^a-z0-9_-]/ 0 0 0
237 }
238  
239 11 ▶if (exists $opts{identity}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"identity"}) 0 11 11
240 0 ▶ die "invalid identity: '$opts{identity}'\n" if $opts{identity} =~ /[^\w]/;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"identity"} =~ /[^\w]/ 0 0 0
241 }
242  
243 11 ▶$opts{'database-file'} ||= $FindBin::RealScript.($opts{identity} ? '-'.$opts{identity} : '').'.db';
Branch: 1 branch
BranchTrueFalseTotal
$opts{'identity'} ? : 0 0 0
Condition50%1/2
$opts{"database-file"} ||= $FindBin::RealScript . ($opts{"identity"} ? '-' . $opts{"identity"} : "") . '.db'
l!l
110
MC/DC0%0/1
$opts{"database-file"} ||= $FindBin::RealScript . ($opts{"identity"} ? '-' . $opts{"identity"} : "") . '.db'
$opts{"database-file"}
Truth table50%1/2
A
A= $opts{"database-file"}
Aresult
11
00
244 11 $opts{'database-file'} = realpath $opts{'database-file'};
245  
246 11 ▶if (exists $opts{'change-dir'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"change-dir"}) 0 11 11
247 die "no such directory: '$opts{'change-dir'}'\n"
248 0 ▶ unless -d $opts{'change-dir'};
Branch: 1 branch
BranchTrueFalseTotal
unless -d $opts{"change-dir"} 0 0 0
249 }
250  
251 11 ▶$opts{'log-facility'} ||= 'daemon';
Condition50%1/2
$opts{"log-facility"} ||= "daemon"
l!l
011
MC/DC0%0/1
$opts{"log-facility"} ||= "daemon"
$opts{"log-facility"}
Truth table50%1/2
A
A= $opts{"log-facility"}
Aresult
11
00
252 die "invalid log facility: '$opts{'log-facility'}'\n"
253 11 ▶ unless $opts{'log-facility'} =~ /^(auth|authpriv|cron|daemon|kern|local[0-7]|mail|news|syslog|user|uucp)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"log-facility"} =~ /^(auth|authpriv|cron|daemon|kern|local[0-7]|mail|news|syslog|user|uucp)$/ 0 11 11
254  
255 11 ▶$opts{'log-level'} ||= 'notice';
Condition50%1/2
$opts{"log-level"} ||= "notice"
l!l
110
MC/DC0%0/1
$opts{"log-level"} ||= "notice"
$opts{"log-level"}
Truth table50%1/2
A
A= $opts{"log-level"}
Aresult
11
00
256 die "invalid log level: '$opts{'log-level'}'\n"
257 11 ▶ unless $opts{'log-level'} =~ /^(debug|info|notice|warning|error|critical|alert|emergency)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"log-level"} =~ /^(debug|info|notice|warning|error|critical|alert|emergency)$/ 0 11 11
258  
259 11 ▶if ($opts{debug}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"debug"}) 0 11 11
260 0 $opts{'log-level'} = 'debug';
261 0 delete $opts{'log-file'};
262 0 $opts{foreground} = 1;
263 }
264  
265 11 ▶$opts{'log-file'} = realpath $opts{'log-file'} if exists $opts{'log-file'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"log-file"} 0 11 11
266  
267 11 ▶$opts{'expand-period'} = 60 unless exists $opts{'expand-period'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"expand-period"} 11 0 11
268 die "invalid expand period: '$opts{'expand-period'}'\n"
269 11 ▶ if $opts{'expand-period'} =~ /[^\d]/;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"expand-period"} =~ /[^\d]/ 0 11 11
270  
271 11 ▶$opts{'listen'} ||= '127.0.0.1:3638';
Condition50%1/2
$opts{"listen"} ||= "127.0.0.1:3638"
l!l
110
MC/DC0%0/1
$opts{"listen"} ||= "127.0.0.1:3638"
$opts{"listen"}
Truth table50%1/2
A
A= $opts{"listen"}
Aresult
11
00
272  
273 11 ▶$opts{'windows-num'} = 60 unless exists $opts{'windows-num'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"windows-num"} 11 0 11
274 die "invalid windows number: '$opts{'windows-num'}'\n"
275 11 ▶ if $opts{'windows-num'} =~ /[^\d]/;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"windows-num"} =~ /[^\d]/ 0 11 11
276  
277 11 ▶$opts{'store-period'} = 10 unless exists $opts{'store-period'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"store-period"} 11 0 11
278 die "invalid store period: '$opts{'store-period'}'\n"
279 11 ▶ if $opts{'store-period'} =~ /[^\d]/;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"store-period"} =~ /[^\d]/ 0 11 11
280  
281 11 ▶$opts{'window-size'} = 10 unless exists $opts{'window-size'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"window-size"} 1 10 11
282 die "invalid window size: '$opts{'window-size'}'\n"
283 11 ▶ if $opts{'window-size'} =~ /[^\d]/;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"window-size"} =~ /[^\d]/ 0 11 11
284  
285 11 ▶$opts{'parse-error'} ||= $pclass->parse_error;
Condition33%1/3
$opts{"parse-error"} ||= $pclass->parse_error
l!l&&r!l&&!r
0110
MC/DC0%0/2
$opts{"parse-error"} ||= $pclass->parse_error
$opts{"parse-error"} $pclass->parse_error
Truth table33%1/3
A ||= B
A= $opts{"parse-error"}B= $pclass->parse_error
ABresult
1X1
011
000
286 die "invalid parse error: '$opts{'parse-error'}'\n"
287 11 ▶ unless $opts{'parse-error'} =~ /^(debug|info|none|notice|warning|error|critical|alert|emergency)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"parse-error"} =~ /^(debug|info|none|notice|warning|error|critical|alert|emergency)$/ 0 11 11
288  
289 11 ▶$opts{'pid-file'} ||= $FindBin::RealScript.($opts{identity} ? '-'.$opts{identity} : '').'.pid';
Branch: 1 branch
BranchTrueFalseTotal
$opts{'identity'} ? : 0 0 0
Condition50%1/2
$opts{"pid-file"} ||= $FindBin::RealScript . ($opts{"identity"} ? '-' . $opts{"identity"} : "") . '.pid'
l!l
110
MC/DC0%0/1
$opts{"pid-file"} ||= $FindBin::RealScript . ($opts{"identity"} ? '-' . $opts{"identity"} : "") . '.pid'
$opts{"pid-file"}
Truth table50%1/2
A
A= $opts{"pid-file"}
Aresult
11
00
290 11 $opts{'pid-file'} = realpath $opts{'pid-file'};
291  
292 11 ▶if (exists $opts{'regex-from'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"regex-from"}) 0 11 11
293 die "options regex and regex-from are mutually exclusive\n"
294 0 ▶ if exists $opts{regex};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"regex"} 0 0 0
295 0 local $/;
296 0 ▶ open FH, $opts{'regex-from'} or
Branch: 1 branch
BranchTrueFalseTotal
open FH, $opts{"regex-from"} or die "can't read regex: $!\n" 0 0 0
297 die "can't read regex: $!\n";
298 0 $opts{regex} = <FH>;
299 }
300  
301 # loading overrides
302 11 for ( @{ $opts{'override-from'} } ) {
303 0 local $/;
304 0 ▶ open FH, $_ or
Branch: 1 branch
BranchTrueFalseTotal
open FH, $_ or die "can't read override from '${_}': $!\n" 0 0 0
305 die "can't read override from '$_': $!\n";
306 0 eval "package $pclass; use strict; use warnings qw(all); ".<FH>;
307 0 ▶ die "can't apply overrides from '$_': $@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
308 }
309  
310 11 ▶defined (my $uid = $opts{'user'} ? getpwnam($opts{'user'}) : $>) or
Branch: 2 branches
BranchTrueFalseTotal
defined(my $uid = $opts{"user"} ? getpwnam $opts{"user"} : $>) or die qq[unknown user: $opts{"user"}\n] 0 11 11
$opts{'user'} ? : 0 11 11
311 die "unknown user: $opts{'user'}\n";
312  
313 # grouping log files by zones, order does matter
314 # due to support '--multiple' option
315 11 my %zones;
316 11 tie %zones, 'Tie::Hash::Indexed';
317 11 for (@ARGV) {
318 11 ▶ /^([\w\d\_-]+):(.+)/ && do {
Branch: 1 branch
BranchTrueFalseTotal
/^([\w\d\_-]+):(.+)/ and do { push @{$zones{$1};}, $2; next } 11 0 11
319 11 push @{$zones{$1}}, $2;
320 11 next;
321 };
322 0 push @{$zones{
323 $opts{'agregate-zone'} ||
324 0 ▶ ( $opts{basename} ? fileparse($_,qr/\.[^\.]+/) : $_ )
Branch: 1 branch
BranchTrueFalseTotal
$opts{'basename'} ? : 0 0 0
Condition0%0/3
$opts{'agregate-zone'} || ($opts{'basename'} ? fileparse($_, qr/\.[^\.]+/) : $_)
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{'agregate-zone'} || ($opts{'basename'} ? fileparse($_, qr/\.[^\.]+/) : $_)
$opts{'agregate-zone'} ($opts{'basename'} ? fileparse($_, qr/\.[^\.]+/) : $_)
Truth table0%0/3
A || B
A= $opts{'agregate-zone'}B= ($opts{'basename'} ? fileparse($_, qr/\.[^\.]+/) : $_)
ABresult
1X1
011
000
325 }}, $_;
326 }
327  
328 # parsing timers
329 11 my %timers;
330 11 my %units = (
331 w => [ 'week', 7 * 86_400 ],
332 d => [ 'day', 86_400 ],
333 h => [ 'hour', 3_600 ],
334 m => [ 'minute', 60 ],
335 s => [ 'second', 1 ],
336 );
337 11 for (@{ $opts{timer} }) {
338 0 ▶ my ($z,$n,$p,$u) = /^(\S+):(\S+):(\d+)(w|d|h|m|s)?$/ or
Branch: 1 branch
BranchTrueFalseTotal
() = /^(\S+):(\S+):(\d+)(w|d|h|m|s)?$/ or die "invalid timer format: $_\n" 0 0 0
339 die "invalid timer format: $_\n";
340 0 ▶ die "no such zone '$z' for timer '$_'\n" unless exists $zones{$z};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $zones{$z} 0 0 0
341 0 ▶ die "zone '$z' already has timer '$n'\n" if exists $timers{$z}{$n};
Branch: 1 branch
BranchTrueFalseTotal
if exists $timers{$z}{$n} 0 0 0
342  
343 0 ▶ $u ||= 's';
Condition0%0/2
$u ||= "s"
l!l
00
MC/DC0%0/1
$u ||= "s"
$u
Truth table0%0/2
A
A= $u
Aresult
11
00
344 0 $timers{$z}{$n} = [ $p * $units{$u}[1], $units{$u}[0] ];
345 }
346  
347 # listen socket
348 my $sock = IO::Socket::INET->new(
349 (
350 $opts{'listen'} =~ /:/ ?
351 ( LocalAddr => $opts{'listen'} ) :
352 11 ▶ ( LocalPort => $opts{'listen'} )
Branch: 2 branches
BranchTrueFalseTotal
my $sock = "IO::Socket::INET"->new($opts{"listen"} =~ /:/ ? ("LocalAddr", $opts{"listen"}) : ("LocalPort", $opts{"listen"}), "Listen", 4096, "ReuseAddr", 1) or die "can't create listen socket: $!\n" 0 11 11
$opts{'listen'} =~ /:/ ? : 0 11 11
353 ),
354 Listen => SOMAXCONN,
355 ReuseAddr => 1,
356 ) or die "can't create listen socket: $!\n";
357  
358 # set process privileges
359 11 ▶setuid $uid or die "can't setuid to $opts{'user'}: $!\n" unless $uid == $>;
Branch: 1 branch
BranchTrueFalseTotal
unless $uid == $> 0 11 11
Condition25%1/4
$uid == $> || (setuid($uid) || die("can't setuid to $opts{'user'}: $!\n"))
l!l
110
setuid($uid) or die qq[can't setuid to $opts{"user"}: $!\n]
l!l
00
MC/DC0%0/2
$uid == $> || (setuid($uid) || die("can't setuid to $opts{'user'}: $!\n"))
$uid == $> setuid($uid)
Truth table33%1/3
A || B
A= $uid == $>B= setuid($uid)
ABresult
1X1
011
000
360  
361 # set process title
362 11 ▶$0 = $FindBin::RealScript.': '.$pname.($opts{identity} ? ' ['.$opts{identity}.']' : '');
Branch: 1 branch
BranchTrueFalseTotal
$opts{'identity'} ? : 0 11 11
363  
364 # fork
365 11 ▶unless ($opts{foreground}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"foreground"}) 0 11 11
366 0 ▶ defined(my $pid = fork) or die "can't fork: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined(my $pid = fork) or die "can't fork: $!\n" 0 0 0
367 0 ▶ exit if $pid;
Branch: 1 branch
BranchTrueFalseTotal
if $pid 0 0 0
368 }
369  
370 # protecting against second instance running
371 11 ▶Pid::File::Flock->new($opts{'pid-file'}) unless $opts{foreground};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"foreground"} 0 11 11
372  
373 # daemonize
374 11 ▶unless ($opts{foreground}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"foreground"}) 0 11 11
375 0 ▶ chdir '/' or die "can't chdir: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
chdir "/" or die "can't chdir: $!\n" 0 0 0
376 0 ▶ die "can't create new session: $!\n" if setsid == -1;
Branch: 1 branch
BranchTrueFalseTotal
if setsid() == -1 0 0 0
377 0 ▶ open STDIN, '</dev/null' or die "can't close stdin\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "</dev/null" or die "can't close stdin\n" 0 0 0
378 0 ▶ open STDOUT, '>/dev/null' or die "can't close stdout\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">/dev/null" or die "can't close stdout\n" 0 0 0
379 0 ▶ open STDERR, '>/dev/null' or die "can't close stderr\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">/dev/null" or die "can't close stderr\n" 0 0 0
380 }
381  
382 # logger
383 11 (my $log = Log::Dispatch->new)->add(logger());
384 11 $log->notice("starting up");
385  
386 # catch perl warnings
387 11 ▶$SIG{__WARN__} = sub { $log->warning(@_) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
388  
389 # main POE session
390 POE::Session->create(
391 inline_states => {
392  
393 # initializing
394 _start => sub {
395 11 ▶ $log->debug("initializing POE session");
Subroutine __ANON__: called CC=19 SCAR=32.5
396  
397 # talk POE kernel adjust to the new situation
398 11 ▶ $_[KERNEL]->has_forked unless $opts{foreground};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"foreground"} 0 11 11
399  
400 # signals
401 11 $log->debug("setting up signal handlers");
402 11 $_[KERNEL]->sig(HUP => 'hangup');
403 11 $_[KERNEL]->sig(INT => 'interrupt');
404 11 $_[KERNEL]->sig(TERM => 'terminate');
405 11 $_[KERNEL]->sig(USR1 => 'rotate');
406  
407 # statistics server
408 11 $log->debug("creating TCP server");
409 11 $_[HEAP]->{server} = POE::Wheel::ListenAccept->new(
410 Handle => $sock,
411 AcceptEvent => 'server_accept',
412 ErrorEvent => 'server_error',
413 );
414  
415 # serializer
416 11 $log->debug("creating serializer");
417 11 $_[HEAP]->{serial} = JSON::XS->new->pretty;
418  
419 # creating plugin instance
420 11 my %popts;
421 11 ▶ for (split /,/, $opts{options} || '') {
Condition100%2/2
$opts{'options'} || ''
l!l
56
MC/DC100%1/1
$opts{'options'} || ''
$opts{'options'}
Truth table100%2/2
A
A= $opts{'options'}
Aresult
11
00
422 5 my ($k,$v) = split /=/;
423 5 ▶ $popts{$k} = defined $v ? $v : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 0 5 5
424 }
425 11 ▶ $popts{regex} = $opts{regex} if exists $opts{regex};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"regex"} 0 11 11
426 11 $_[HEAP]->{plugin} = $pclass->new(%popts);
427  
428 # setting up zones
429 11 $_[HEAP]->{zones} = \%zones;
430  
431 # load previous data
432 11 ▶ if (-f $opts{'database-file'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $opts{"database-file"}) 0 11 11
433 0 ▶ $_[KERNEL]->call($_[SESSION], 'do_load') or return;
Branch: 1 branch
BranchTrueFalseTotal
$_[2]->call($_[1], "do_load") or return 0 0 0
434 }
435  
436 # create insufficient references
437 11 for (keys %zones) {
438 11 ▶ $_[HEAP]->{data}{$_}{public} ||= {};
Condition50%1/2
$_[3]{"data"}{$_}{"public"} ||= {}
l!l
011
MC/DC0%0/1
$_[3]{"data"}{$_}{"public"} ||= {}
$_[3]{"data"}{$_}{"public"}
Truth table50%1/2
A
A= $_[3]{"data"}{$_}{"public"}
Aresult
11
00
439 11 ▶ $_[HEAP]->{data}{$_}{private} ||= {};
Condition50%1/2
$_[3]{"data"}{$_}{"private"} ||= {}
l!l
011
MC/DC0%0/1
$_[3]{"data"}{$_}{"private"} ||= {}
$_[3]{"data"}{$_}{"private"}
Truth table50%1/2
A
A= $_[3]{"data"}{$_}{"private"}
Aresult
11
00
440 11 ▶ $_[HEAP]->{data}{$_}{windows} ||= [];
Condition50%1/2
$_[3]{"data"}{$_}{"windows"} ||= []
l!l
011
MC/DC0%0/1
$_[3]{"data"}{$_}{"windows"} ||= []
$_[3]{"data"}{$_}{"windows"}
Truth table50%1/2
A
A= $_[3]{"data"}{$_}{"windows"}
Aresult
11
00
441 11 ▶ $_[HEAP]->{data}{$_}{windows}[0] ||= {};
Condition50%1/2
$_[3]{"data"}{$_}{"windows"}[0] ||= {}
l!l
011
MC/DC0%0/1
$_[3]{"data"}{$_}{"windows"}[0] ||= {}
$_[3]{"data"}{$_}{"windows"}[0]
Truth table50%1/2
A
A= $_[3]{"data"}{$_}{"windows"}[0]
Aresult
11
00
442  
443 # call plugin initialization code
444 $_[HEAP]->{plugin}->init_zone(
445 $_,
446 $_[HEAP]->{data}{$_}{public},
447 $_[HEAP]->{data}{$_}{private},
448 11 $_[HEAP]->{data}{$_}{windows}[0],
449 );
450 }
451  
452 # expanding zones wildcards
453 11 $_[KERNEL]->call($_[SESSION], 'do_expand');
454  
455 # creating named timers
456 11 $_[HEAP]->{timers} = \%timers;
457 11 for my $z ( keys %{ $_[HEAP]->{timers} } ) {
458 0 for my $n ( keys %{ $_[HEAP]->{timers}{$z} } ) {
459 0 $_[KERNEL]->call($_[SESSION], 'set_timer', $z, $n);
460 }
461 }
462  
463 # schedule save task
464 11 ▶ if ($opts{'store-period'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"store-period"}) 11 0 11
465 11 $log->debug("scheduling saving heartbeat at $opts{'store-period'} second(s)");
466 11 $_[KERNEL]->delay( save_heartbeat => $opts{'store-period'} );
467 }
468  
469 # schedule expanding wildcards
470 11 ▶ if ($opts{'expand-period'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"expand-period"}) 11 0 11
471 11 $log->debug("scheduling expanding heartbeat at $opts{'expand-period'} second(s)");
472 11 $_[KERNEL]->delay( expand_heartbeat => $opts{'expand-period'} );
473 }
474  
475 # schedule windows heartbeat
476 11 ▶ if ($opts{'window-size'} && $opts{'windows-num'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"window-size"} and $opts{"windows-num"}) 11 0 11
Condition33%1/3
$opts{"window-size"} and $opts{"windows-num"}
!ll&&!rl&&r
0011
MC/DC0%0/2
$opts{"window-size"} and $opts{"windows-num"}
$opts{"window-size"} $opts{"windows-num"}
Truth table33%1/3
A and B
A= $opts{"window-size"}B= $opts{"windows-num"}
ABresult
0X0
100
111
477 11 $log->debug("scheduling windows heartbeat at $opts{'window-size'} second(s)");
478 11 $_[KERNEL]->delay( windows_heartbeat => $opts{'window-size'} );
479 }
480 },
481  
482 # expanding task
483 expand_heartbeat => sub {
484 0 ▶ $log->debug("wildcards expanding heartbeat occurred");
Subroutine __ANON__: not called CC=2 SCAR=17.9
485  
486 # expanding zones wildcards
487 0 $_[KERNEL]->call($_[SESSION], 'do_expand');
488  
489 # schedule next call
490 0 ▶ if ($opts{'expand-period'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"expand-period"}) 0 0 0
491 0 $log->debug("scheduling expanding heartbeat at $opts{'expand-period'} second(s)");
492 0 $_[KERNEL]->delay( expand_heartbeat => $opts{'expand-period'} );
493 }
494 },
495  
496 # setting named timer
497 set_timer => sub {
498 0 ▶ my $t = $_[HEAP]->{timers}{$_[ARG0]}{$_[ARG1]};
Subroutine __ANON__: not called CC=1 SCAR=6.9
499 0 my $next = DateTime->now(
500 time_zone => 'local'
501 )->add(
502 seconds => $t->[0]
503 )->truncate(
504 to => $t->[1]
505 );
506 0 $log->debug("setting named timer '$_[ARG1]' for zone '$_[ARG0] at '".$next->strftime('%Y-%m-%d %H:%M:%S')."'");
507 0 $_[KERNEL]->alarm_set( named_timer => $next->epoch, $_[ARG0], $_[ARG1] );
508 },
509  
510 # named timer handler
511 named_timer => sub {
512 0 ▶ $log->debug("processing named timer '$_[ARG1]' for zone '$_[ARG0]");
Subroutine __ANON__: not called CC=2 SCAR=17.9
513 $_[HEAP]->{plugin}->process_timer(
514 $_[ARG1],
515 $_[HEAP]->{data}{$_[ARG0]}{public},
516 $_[HEAP]->{data}{$_[ARG0]}{private},
517 $_[HEAP]->{data}{$_[ARG0]}{windows}
518 ) ? do {
519 0 $log->debug("renewing timer '$_[ARG1]' for zone '$_[ARG0]");
520 0 $_[KERNEL]->call($_[SESSION], 'set_timer', $_[ARG0], $_[ARG1]);
521 0 ▶ } : do {
Branch: 1 branch
BranchTrueFalseTotal
$_[3]{'plugin'}->process_timer($_[11], $_[3]{'data'}{$_[10]}{'public'}, $_[3]{'data'}{$_[10]}{'private'}, $_[3]{'data'}{$_[10]}{'windows'}) ? : 0 0 0
522 0 $log->debug("clearing timer '$_[ARG1]' for zone '$_[ARG0]'");
523 };
524 },
525  
526 # expanding wildcards
527 do_expand => sub {
528 11 ▶ $log->debug("begin expanding wildcards");
Subroutine __ANON__: called CC=15 SCAR=38.7
529  
530 11 my $cwd = getcwd;
531 11 ▶ if ($opts{'change-dir'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"change-dir"}) 0 11 11
532 0 ▶ chdir $opts{'change-dir'} or
Branch: 1 branch
BranchTrueFalseTotal
chdir $opts{"change-dir"} or $log->warning(qq[can't change directory to '$opts{"change-dir"}']) 0 0 0
533 $log->warning("can't change directory to '$opts{'change-dir'}'");
534 }
535  
536 11 my %exif; # existing files
537 11 for my $zone ( keys %{ $_[HEAP]->{zones} } ) {
538 11 my @files;
539 10 push @files, map { realpath $_ } grep { -f } glob $_
540 11 for @{ $_[HEAP]->{zones}{$zone} };
541 11 $log->debug("found ".scalar(@files)." file(s) in zone '$zone'");
542  
543 # create missing watchers
544 FILE:
545 11 for my $f (@files) {
546 10 $exif{$f}++;
547  
548 # searching for already monitored file
549 10 for my $w ( values %{ $_[HEAP]->{watchers} } ) {
550 0 ▶ next unless $f eq $w->[0];
Branch: 1 branch
BranchTrueFalseTotal
unless $f eq $w->[0] 0 0 0
551  
552 0 ▶ unless ($opts{multiple}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"multiple"}) 0 0 0
553 0 $log->debug("file '$f' already monitored, ignoring for zone '$zone'");
554 0 next FILE;
555 }
556  
557 # searching for already subscribed zone
558 0 for my $z ( @{ $w->[1] } ) {
559 0 ▶ next unless $z eq $zone;
Branch: 1 branch
BranchTrueFalseTotal
unless $z eq $zone 0 0 0
560 0 $log->debug("zone already subscribed for '$f'");
561 0 next FILE;
562 }
563  
564 # subscribe to existing watcher
565 0 push @{ $w->[1] }, $zone;
566 0 $log->debug("zone subscribed for '$f'");
567 0 next FILE;
568 }
569  
570 # create new watcher and subscribe zone
571 10 my $w = POE::Wheel::FollowTail->new(
572 Filename => $f,
573 Filter => POE::Filter::Line->new( InputLiteral => "\n" ),
574 ErrorEvent => 'watcher_err',
575 InputEvent => 'watcher_line',
576 ResetEvent => 'watcher_roll',
577 );
578 10 $log->debug("created new watcher [".$w->ID."] for '$f'");
579 10 $log->debug("zone subscribed for '$f'");
580 10 $_[HEAP]->{watchers}{$w->ID} = [ $f, [ $zone ], $w ];
581 }
582 }
583  
584 # remove excess watchers
585 11 for my $w (values %{ $_[HEAP]->{watchers} } ) {
586 10 ▶ next if $exif{$w->[0]}; # file exists
Branch: 1 branch
BranchTrueFalseTotal
if $exif{$w->[0]} 10 0 10
587  
588 0 delete $_[HEAP]->{watchers}{$w->[2]->ID};
589 0 $log->debug("excess watcher [".$w->[2]->ID."] removed for '".$w->[0]."'");
590 }
591  
592 11 ▶ if ($opts{'change-dir'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"change-dir"}) 0 11 11
593 0 ▶ chdir $cwd or
Branch: 1 branch
BranchTrueFalseTotal
chdir $cwd or $log->warning("can't restore directory to '${cwd}'") 0 0 0
594 $log->warning("can't restore directory to '$cwd'");
595 }
596 },
597  
598 # new log line
599 watcher_line => sub {
600 11684 ▶ my $w = $_[HEAP]->{watchers}{$_[ARG1]};
Subroutine __ANON__: called CC=4 SCAR=13.9
601 11684 ▶ my @data = $_[HEAP]->{plugin}->process_line($_[ARG0]) or do {
Branch: 1 branch
BranchTrueFalseTotal
my(@data) = $_[3]{"plugin"}->process_line($_[10]) or do { return $log->log("level", $opts{"parse-error"}, "message", "can't parse: '$_[10]' from '$w->[0]'") unless $opts{"parse-error"} eq "none" } 5880 5804 11684
602 return $log->log(
603 level => $opts{'parse-error'},
604 message => "can't parse: '$_[ARG0]' from '$w->[0]'"
605 5880 ▶ ) unless $opts{'parse-error'} eq 'none';
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"parse-error"} eq "none" 5880 0 5880
606 };
607 # subscribers loop
608 5804 for my $z ( @{ $w->[1] } ) {
609 $_[HEAP]->{plugin}->process_data(
610 \@data,
611 $_[HEAP]->{data}{$z}{public},
612 $_[HEAP]->{data}{$z}{private},
613 5804 $_[HEAP]->{data}{$z}{windows}[0]
614 );
615 }
616 },
617  
618 # log rotating occurred
619 watcher_roll => sub {
620 0 ▶ my $w = $_[HEAP]->{watchers}{$_[ARG0]};
Subroutine __ANON__: not called CC=2 SCAR=17.9
621 # clear tail fragment
622 0 ▶ $w->[2][ POE::Wheel::FollowTail::SELF_FILTER ][ POE::Filter::Line::FRAMING_BUFFER ] =~ s/[^\n]+\z//
Branch: 1 branch
BranchTrueFalseTotal
if $w->[2][3][0] 0 0 0
623 if $w->[2][ POE::Wheel::FollowTail::SELF_FILTER ][ POE::Filter::Line::FRAMING_BUFFER ];
624 0 $log->info("rolled over '$w->[0]'");
625 },
626  
627 # log tailing error
628 watcher_err => sub {
629 0 ▶ my $w = $_[HEAP]->{watchers}{$_[ARG3]};
Subroutine __ANON__: not called CC=1 SCAR=6.9
630 0 $log->error("$_[ARG0] failed ($_[ARG1] during tail '$w->[0]': $_[ARG2]");
631 },
632  
633 # windows processing
634 windows_heartbeat => sub {
635 30 ▶ $log->debug("windows heartbeat occurred");
Subroutine __ANON__: called CC=2 SCAR=6.9
636  
637 # schedule windows processing
638 30 for ( keys %{ $_[HEAP]->{zones} } ) {
639 30 $_[KERNEL]->yield( do_window => $_ );
640 }
641  
642 # schedule next call
643 30 $log->debug("scheduling windows heartbeat at $opts{'window-size'} second(s)");
644 30 $_[KERNEL]->delay( windows_heartbeat => $opts{'window-size'} );
645 },
646  
647 do_window => sub {
648 # windows ring
649 30 ▶ my $wins = $_[HEAP]->{data}{$_[ARG0]}{windows};
Subroutine __ANON__: called CC=2 SCAR=7.0
650  
651 # call plugin handler with last complete window
652 $_[HEAP]->{plugin}->process_window(
653 $_[HEAP]->{data}{$_[ARG0]}{public},
654 $_[HEAP]->{data}{$_[ARG0]}{private},
655 30 $wins
656 );
657  
658 # slide windows
659 30 unshift @$wins, {};
660 $#$wins = $opts{'windows-num'} - 1
661 30 ▶ if $#$wins > $opts{'windows-num'} - 1;
Branch: 1 branch
BranchTrueFalseTotal
if $wins->$#* > $opts{"windows-num"} - 1 0 30 30
662 },
663  
664 # periodically task
665 save_heartbeat => sub {
666 0 ▶ $log->debug("saving heartbeat occurred");
Subroutine __ANON__: not called CC=1 SCAR=6.9
667  
668 # save accumulated data
669 0 $_[KERNEL]->call($_[SESSION], 'do_save');
670  
671 # schedule next call
672 0 $log->debug("scheduling saving heartbeat at $opts{'store-period'} second(s)");
673 0 $_[KERNEL]->delay( save_heartbeat => $opts{'store-period'} );
674 },
675  
676 # loading stored data
677 do_load => sub {
678 0 ▶ $log->debug("loading stored data");
Subroutine __ANON__: not called CC=4 SCAR=30.0
679 0 ▶ open FH, $opts{'database-file'} or do {
Branch: 1 branch
BranchTrueFalseTotal
open FH, $opts{"database-file"} or do { $log->error("can't open database file: $!"); return $_[2]->call($_[1], "shutdown") } 0 0 0
680 0 $log->error("can't open database file: $!");
681 0 return $_[KERNEL]->call($_[SESSION], 'shutdown');
682 };
683 0 local $/;
684 0 ▶ my $d = $_[HEAP]->{serial}->decode(<FH>) or do {
Branch: 1 branch
BranchTrueFalseTotal
my $d = $_[3]{"serial"}->decode(readline FH) or do { $log->error("can't read database file: $!"); return $_[2]->call($_[1], "shutdown") } 0 0 0
685 0 $log->error("can't read database file: $!");
686 0 return $_[KERNEL]->call($_[SESSION], 'shutdown');
687 };
688  
689 # assign
690 0 ▶ $_[HEAP]->{data} = $d->{zones} || {};
Condition0%0/2
$d->{'zones'} || {}
l!l
00
MC/DC0%0/1
$d->{'zones'} || {}
$d->{'zones'}
Truth table0%0/2
A
A= $d->{'zones'}
Aresult
11
00
691 },
692  
693 # store accumulated data
694 do_save => sub {
695 11 ▶ $log->debug("storing accumulated data");
Subroutine __ANON__: called CC=6 SCAR=22.9
696 11 ▶ open FH, '>', $opts{'database-file'}.'~' or do {
Branch: 1 branch
BranchTrueFalseTotal
open FH, ">", $opts{"database-file"} . '~' or do { return $log->warning("can't write database file: $!") } 0 11 11
697 0 return $log->warning("can't write database file: $!");
698 };
699 11 ▶ my $d = { zones => $_[HEAP]->{data} || {} };
Condition50%1/2
$_[3]{'data'} || {}
l!l
110
MC/DC0%0/1
$_[3]{'data'} || {}
$_[3]{'data'}
Truth table50%1/2
A
A= $_[3]{'data'}
Aresult
11
00
700 11 print FH $_[HEAP]->{serial}->encode($d);
701 11 close FH;
702  
703 11 ▶ if (-f $opts{'database-file'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $opts{"database-file"}) 0 11 11
704 0 ▶ unlink $opts{'database-file'} or do {
Branch: 1 branch
BranchTrueFalseTotal
unlink $opts{"database-file"} or do { return $log->warning("can't remove old database file: $!") } 0 0 0
705 0 return $log->warning("can't remove old database file: $!");
706 };
707 };
708 11 ▶ rename $opts{'database-file'}.'~', $opts{'database-file'} or do {
Branch: 1 branch
BranchTrueFalseTotal
rename $opts{"database-file"} . '~', $opts{"database-file"} or do { return $log->warning("can't rename new database file: $!") } 0 11 11
709 0 return $log->warning("can't rename new database file: $!");
710 };
711 },
712  
713 # new client accepted
714 server_accept => sub {
715 22 ▶ my ($port,$addr) = sockaddr_in $_[ARG1];
Subroutine __ANON__: called CC=1 SCAR=0.0
716 22 $log->debug("client accepted from ".inet_ntoa($addr).":$port");
717 22 my $c = POE::Wheel::ReadWrite->new(
718 Handle => $_[ARG0],
719 InputEvent => 'client_input',
720 ErrorEvent => 'client_error',
721 );
722 22 $_[HEAP]->{clients}{$c->ID} = $c;
723 },
724  
725 # server error occurred
726 server_error => sub {
727 0 ▶ $log->error("$_[ARG0] failed ($_[ARG1] during serving: $_[ARG2]");
Subroutine __ANON__: not called CC=1 SCAR=6.9
728 0 $_[KERNEL]->call($_[SESSION], 'shutdown');
729 },
730  
731 # got client command
732 client_input => sub {
733 31 ▶ $log->debug("got client command: '$_[ARG0]'");
Subroutine __ANON__: called CC=26 SCAR=51.9
734 31 ▶ my $cln = $_[HEAP]->{clients}{$_[ARG1]} or
Branch: 1 branch
BranchTrueFalseTotal
my $cln = $_[3]{"clients"}{$_[11]} or return $log->warning("unknown client #$_[11]") 0 31 31
735 return $log->warning("unknown client #$_[ARG1]");
736  
737 31 for ($_[ARG0]) {
738  
739 # zones list (active & inactive zones)
740 31 ▶ /^\s*zones\s*$/i and do {
Branch: 1 branch
BranchTrueFalseTotal
/^\s*zones\s*$/i and do { $cln->put(map({'a:' . $_;} keys %{$_[3]{"zones"};})); $cln->put(map({'i:' . $_;} grep({not exists $_[3]{"zones"}{$_};} keys %{$_[3]{"data"};}))); last } 11 20 31
741 $cln->put(
742 11 map { 'a:'.$_ }
743 11 keys %{ $_[HEAP]->{zones} },
744 );
745 $cln->put(
746 0 map { 'i:'.$_ }
747 11 grep { ! exists $_[HEAP]->{zones}{$_} }
748 11 keys %{ $_[HEAP]->{data} },
749 );
750 11 last;
751 };
752  
753 # wildcards list (active zones only)
754 20 ▶ /^\s*globs\s+(\S+)\s*$/i and do {
Branch: 1 branch
BranchTrueFalseTotal
/^\s*globs\s+(\S+)\s*$/i and do { my $z = $_[3]{"zones"}{$1} or do { $log->warning("invalid client globs query: '$1'"); $cln->put("no such active zone"); last }; $cln->put(sort(@{$z;})); last } 0 20 20
755 0 ▶ my $z = $_[HEAP]->{zones}{$1} or do {
Branch: 1 branch
BranchTrueFalseTotal
my $z = $_[3]{"zones"}{$1} or do { $log->warning("invalid client globs query: '$1'"); $cln->put("no such active zone"); last } 0 0 0
756 0 $log->warning("invalid client globs query: '$1'");
757 0 $cln->put('no such active zone');
758 0 last;
759 };
760 0 $cln->put( sort @{ $z } );
761 0 last;
762 };
763  
764 # files list (active zones only)
765 20 ▶ /^\s*files\s+(\S+)\s*$/i and do {
Branch: 1 branch
BranchTrueFalseTotal
/^\s*files\s+(\S+)\s*$/i and do { $_[3]{"zones"}{$1} or do { $log->warning("invalid client files query: '$1'"); $cln->put("no such active zone"); last }; my @f; foreach my $w (values %{$_[3]{"watchers"};}) { foreach my $z (@{$$w[1];}) { next unless $z eq $1; push @f, [$w->[0], $w->[2]->tell, -s $w->[0]]; last; } ; } ; foreach $_ (sort {$main::a->[0] cmp $main::b->[0];} @f) { $cln->put(join(":", $_->[1] eq "0 but true" ? 0 : $_->[1], $_->[2], $_->[0])); } ; last } 10 10 20
766 10 ▶ $_[HEAP]->{zones}{$1} or do {
Branch: 1 branch
BranchTrueFalseTotal
$_[3]{"zones"}{$1} or do { $log->warning("invalid client files query: '$1'"); $cln->put("no such active zone"); last } 0 10 10
767 0 $log->warning("invalid client files query: '$1'");
768 0 $cln->put('no such active zone');
769 0 last;
770 };
771  
772 10 my @f;
773 10 for my $w ( values %{ $_[HEAP]->{watchers} } ) {
774 10 for my $z ( @{ $w->[1] } ) {
775 10 ▶ next unless $z eq $1;
Branch: 1 branch
BranchTrueFalseTotal
unless $z eq $1 0 10 10
776 10 push @f, [ $w->[0], $w->[2]->tell, -s $w->[0] ];
777 10 last;
778 }
779 }
780 10 for ( sort { $a->[0] cmp $b->[0] } @f ) {
781 10 ▶ $cln->put( join ':', $_->[1] eq '0 but true' ? 0 : $_->[1], $_->[2], $_->[0] );
Branch: 1 branch
BranchTrueFalseTotal
$_->[1] eq '0 but true' ? : 0 10 10
782 }
783 10 last;
784 };
785  
786 # zone dump (active & inactive zones)
787 10 ▶ /^\s*dump\s+(\S+)\s*$/i and do {
Branch: 1 branch
BranchTrueFalseTotal
/^\s*dump\s+(\S+)\s*$/i and do { $_[3]{"zones"}{$1} or $_[3]{"data"}{$1} or do { $log->warning("invalid client dump query: '$1'"); $cln->put("no such zone"); last }; my $wmax = $#{$_[3]{"data"}{$1}{"windows"};}; $cln->put($_[3]{"plugin"}->dump_zone($1, $_[3]{"data"}{$1}{"public"}, $_[3]{"data"}{$1}{"private"}, [@{$_[3]{"data"}{$1}{"windows"};}[1 .. $wmax]])); last } 0 10 10
788 0 ▶ $_[HEAP]->{zones}{$1} or $_[HEAP]->{data}{$1} or do {
Branch: 1 branch
BranchTrueFalseTotal
$_[3]{"zones"}{$1} or $_[3]{"data"}{$1} or do { $log->warning("invalid client dump query: '$1'"); $cln->put("no such zone"); last } 0 0 0
Condition0%0/3
$_[3]{"zones"}{$1} or $_[3]{"data"}{$1}
l!l&&r!l&&!r
000
MC/DC0%0/2
$_[3]{"zones"}{$1} or $_[3]{"data"}{$1}
$_[3]{"zones"}{$1} $_[3]{"data"}{$1}
Truth table0%0/3
A or B
A= $_[3]{"zones"}{$1}B= $_[3]{"data"}{$1}
ABresult
1X1
011
000
789 0 $log->warning("invalid client dump query: '$1'");
790 0 $cln->put('no such zone');
791 0 last;
792 };
793 0 my $wmax = $#{ $_[HEAP]->{data}{$1}{windows} };
794 $cln->put( $_[HEAP]->{plugin}->dump_zone( $1,
795 $_[HEAP]->{data}{$1}{public},
796 $_[HEAP]->{data}{$1}{private},
797 0 [ @{ $_[HEAP]->{data}{$1}{windows} }[1..$wmax] ],
798 ));
799 0 last;
800 };
801  
802 # zone statistics (active & inactive zones)
803 10 ▶ /^\s*stats\s+(\S+)\s*$/i and do {
Branch: 1 branch
BranchTrueFalseTotal
/^\s*stats\s+(\S+)\s*$/i and do { $_[3]{"zones"}{$1} or $_[3]{"data"}{$1} or do { $log->warning("invalid client stats query: '$1'"); $cln->put("no such zone"); last }; my $wmax = $#{$_[3]{"data"}{$1}{"windows"};}; $cln->put($_[3]{"plugin"}->stats_zone($1, $_[3]{"data"}{$1}{"public"}, $_[3]{"data"}{$1}{"private"}, [@{$_[3]{"data"}{$1}{"windows"};}[1 .. $wmax]])); last } 10 0 10
804 10 ▶ $_[HEAP]->{zones}{$1} or $_[HEAP]->{data}{$1} or do {
Branch: 1 branch
BranchTrueFalseTotal
$_[3]{"zones"}{$1} or $_[3]{"data"}{$1} or do { $log->warning("invalid client stats query: '$1'"); $cln->put("no such zone"); last } 0 10 10
Condition33%1/3
$_[3]{"zones"}{$1} or $_[3]{"data"}{$1}
l!l&&r!l&&!r
1000
MC/DC0%0/2
$_[3]{"zones"}{$1} or $_[3]{"data"}{$1}
$_[3]{"zones"}{$1} $_[3]{"data"}{$1}
Truth table33%1/3
A or B
A= $_[3]{"zones"}{$1}B= $_[3]{"data"}{$1}
ABresult
1X1
011
000
805 0 $log->warning("invalid client stats query: '$1'");
806 0 $cln->put('no such zone');
807 0 last;
808 };
809 10 my $wmax = $#{ $_[HEAP]->{data}{$1}{windows} };
810 $cln->put( $_[HEAP]->{plugin}->stats_zone( $1,
811 $_[HEAP]->{data}{$1}{public},
812 $_[HEAP]->{data}{$1}{private},
813 10 [ @{ $_[HEAP]->{data}{$1}{windows} }[1..$wmax] ],
814 ));
815 10 last;
816 };
817  
818 # remove zone statistics (inactive zones only)
819 0 ▶ /^\s*wipe\s+(\S+)\s*$/i and do {
Branch: 1 branch
BranchTrueFalseTotal
/^\s*wipe\s+(\S+)\s*$/i and do { if ($1 eq "*") { foreach $_ (keys %{$_[3]{"data"};}) { next if exists $_[3]{"zones"}{$_}; delete $_[3]{"data"}{$_}; } ; } else { $_[3]{"data"}{$1} or do { $log->warning("invalid client wipe query: '$1'"); $cln->put("no such inactive zone"); last }; $_[3]{"zones"}{$1} and do { $log->warning("invalid client wipe query: '$1'"); $cln->put("zone is active"); last }; delete $_[3]{"data"}{$1}; } ; $cln->put("ok"); $_[2]->call($_[1], "do_save"); last } 0 0 0
820 0 ▶ if ($1 eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 eq '*') { } 0 0 0
821 0 for ( keys %{ $_[HEAP]->{data} } ) {
822 0 ▶ next if exists $_[HEAP]->{zones}{$_};
Branch: 1 branch
BranchTrueFalseTotal
if exists $_[3]{"zones"}{$_} 0 0 0
823 0 delete $_[HEAP]->{data}{$_};
824 }
825 } else {
826 0 ▶ $_[HEAP]->{data}{$1} or do {
Branch: 1 branch
BranchTrueFalseTotal
$_[3]{"data"}{$1} or do { $log->warning("invalid client wipe query: '$1'"); $cln->put("no such inactive zone"); last } 0 0 0
827 0 $log->warning("invalid client wipe query: '$1'");
828 0 $cln->put('no such inactive zone');
829 0 last;
830 };
831 0 ▶ $_[HEAP]->{zones}{$1} and do {
Branch: 1 branch
BranchTrueFalseTotal
$_[3]{"zones"}{$1} and do { $log->warning("invalid client wipe query: '$1'"); $cln->put("zone is active"); last } 0 0 0
832 0 $log->warning("invalid client wipe query: '$1'");
833 0 $cln->put('zone is active');
834 0 last;
835 };
836 0 delete $_[HEAP]->{data}{$1};
837 }
838 0 $cln->put( 'ok' );
839 0 $_[KERNEL]->call($_[SESSION], 'do_save');
840 0 last;
841 };
842  
843  
844 # disconnect request
845 0 ▶ /^\s*quit\s*$/i and do {
Branch: 1 branch
BranchTrueFalseTotal
/^\s*quit\s*$/i and do { return delete $_[3]{"clients"}{$_[11]} } 0 0 0
846 0 return delete $_[HEAP]->{clients}->{$_[ARG1]};
847 };
848  
849 # invalid command
850 0 $log->warning("invalid client command: '$_[ARG0]'");
851 0 $_[HEAP]->{clients}{$_[ARG1]}->put('error');
852 }
853  
854 # force buffer flush
855 31 $_[HEAP]->{clients}{$_[ARG1]}->flush;
856 31 $log->debug("buffer flushed");
857 },
858  
859 # client errors (disconnect included)
860 client_error => sub {
861 22 ▶ $_[ARG1] ?
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$_[11] ? : 0 22 22
862 $log->error("$_[ARG0] ($_[ARG1] from client: $_[ARG2]") :
863 $log->debug("client disconnected");
864 # drop client connection
865 22 delete $_[HEAP]->{clients}->{$_[ARG3]};
866 },
867  
868 # got SIGHUP
869 hangup => sub {
870 0 ▶ $log->notice("got SIGHUP, re-expanging zones wildcards");
Subroutine __ANON__: not called CC=1 SCAR=6.9
871  
872 # expanding zones wildcards
873 0 $_[KERNEL]->call($_[SESSION], 'do_expand');
874  
875 # keep signal handled
876 0 $_[KERNEL]->sig_handled;
877 },
878  
879 # got SIGINT
880 interrupt => sub {
881 0 ▶ $log->notice("got SIGINT, terminating");
Subroutine __ANON__: not called CC=1 SCAR=6.9
882  
883 # keep signal handled
884 0 $_[KERNEL]->sig_handled;
885  
886 # shutting down
887 0 $_[KERNEL]->call($_[SESSION], 'shutdown');
888 },
889  
890 # got SIGTERM
891 terminate => sub {
892 11 ▶ $log->notice("got SIGTERM, terminating");
Subroutine __ANON__: called CC=1 SCAR=0.0
893  
894 # shutting down
895 11 $_[KERNEL]->call($_[SESSION], 'shutdown');
896  
897 # keep signal handled
898 11 $_[KERNEL]->sig_handled;
899 },
900  
901 # got SIGUSR1
902 rotate => sub {
903 0 ▶ $log->notice("got SIGUSR1, re-opening log file");
Subroutine __ANON__: not called CC=1 SCAR=6.9
904  
905 # drop & create logger
906 0 $log->remove('main');
907 0 $log->add(logger());
908  
909 # keep signal handled
910 0 $_[KERNEL]->sig_handled;
911 },
912  
913 # graceful exit
914 shutdown => sub {
915 11 ▶ $log->debug("gracefully shutting down");
Subroutine __ANON__: called CC=3 SCAR=11.0
916  
917 # store statistics
918 11 $_[KERNEL]->call($_[SESSION], 'do_save');
919  
920 # drop timers
921 11 $log->debug("removing alarms");
922 11 $_[KERNEL]->alarm_remove_all;
923  
924 # drop server
925 11 $log->debug("shutting down server");
926 11 delete $_[HEAP]->{server};
927  
928 # drop clients
929 11 $log->debug("disconnecting clients");
930 11 delete $_[HEAP]->{clients}{$_} for keys %{ $_[HEAP]->{clients} };
931  
932 # drop watchers
933 11 $log->debug("shutting down watchers");
934 11 for (values %{ $_[HEAP]->{watchers} }) {
935 10 delete $_[HEAP]->{watchers}{$_->[2]->ID};
936 10 $log->debug("shutdown watcher [".$_->[2]->ID."] for '$_->[0]'");
937 }
938 },
939 },
940 11 );
941  
942  
943 # go!
944 11 POE::Kernel->run;
945  
946 11 $log->notice("exit");
947  
948 # log object create
949 sub logger {
950 return Log::Dispatch::Screen->new(
951 name => 'main',
952 callbacks => [ \&pfmt, \&lfmt, \&dfmt ],
953 min_level => $opts{'log-level'},
954 stderr => 1
955 11 ▶ ) if $opts{foreground};
Subroutine logger: called CC=4 SCAR=24.4
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"foreground"} 11 0 11
956  
957 return Log::Dispatch::File->new(
958 name => 'main',
959 callbacks => [ \&pfmt, \&lfmt, \&dfmt ],
960 min_level => $opts{'log-level'},
961 filename => $opts{'log-file'},
962 mode => '>>'
963 0 ▶ ) if $opts{'log-file'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"log-file"} 0 0 0
964  
965 return Log::Dispatch::Syslog->new(
966 name => 'main',
967 callbacks => [ \&pfmt, ],
968 min_level => $opts{'log-level'},
969 facility => $opts{'log-facility'},
970 0 ▶ ident => $FindBin::RealScript.($opts{identity} ? '-'.$opts{identity} : '' )
Branch: 1 branch
BranchTrueFalseTotal
$opts{'identity'} ? : 0 0 0
971 );
972 };
973  
974 # log formatting routines
975 sub pfmt {
976 0 ▶ my %m = @_;
Subroutine pfmt: not called CC=1 SCAR=6.9
977 0 sprintf "$$: %s\n", $m{message};
978 }
979 sub lfmt {
980 0 ▶ my %m = @_;
Subroutine lfmt: not called CC=1 SCAR=6.9
981 0 sprintf "[%s] %s", $m{level}, $m{message};
982 }
983 sub dfmt {
984 0 ▶ my %m = @_;
Subroutine dfmt: not called CC=1 SCAR=6.9
985 0 sprintf "%s %s", strftime("%Y/%m/%d %H:%M:%S",localtime), $m{message};
986 }
987  
988 sub usage {
989 0 ▶ <<EOM;
Subroutine usage: not called CC=1 SCAR=6.9
990  
991 Usage: $FindBin::RealScript [ options ] plugin [zone1:]wildcard1 .. [zoneN:]wildcardN
992  
993 More information available under 'Tail::Stat' man page.
994  
995 Options:
996 -a, --agregate-zone=ZONE agregating anonymous logs to zone
997 -b, --database-file=FILE persistent database file
998 --basename create anonymous zones from base name of log files
999 -c, --change-dir=DIR change directory before wildards expanding
1000 -d, --debug implies: --foreground --log-level=debug
1001 -f, --foreground no detach, logging to stderr
1002 --log-facility=NAME set facility for syslog logging
1003 --log-level=LEVEL minimum logging level
1004 --log-file=FILE logging to file instead syslog
1005 -e, --expand-period=SECONDS zones wildcard expand period
1006 -h, --help show this help message
1007 -i, --identity=STRING add string to process title, default pid-file,
1008 default database-file and syslog ident
1009 -l, --listen=[ADDR:]PORT TCP statistic server listen socket
1010 --multiple log includes in all expanded wildcard
1011 -n, --windows-num=NUM number of sliding windows (default 60)
1012 -o, --options=STRING comma-separated plugin supported options
1013 (like a mount (8) options)
1014 --override-from=FILE load overriding methods from file
1015 -p, --pid-file=FILE pid file path
1016 --parse-error=LEVEL logging level for unparsed lines
1017 -r, --regex=PATTERN override plugin regular expression
1018 --regex-from=FILE read regular expression from file
1019 -s, --store-period=SECONDS data store period (default 60)
1020 --timer=ZONE:NAME:PERIOD add named timer with fixed period
1021 -u, --user=LOGIN change effective process uid to
1022 -v, --version print version and exit
1023 -w, --window-size=SECONDS size of one sliding window (default 10)
1024  
1025 EOM
1026 }
1027  
1028 sub version {
1029 0 ▶ <<EOM;
Subroutine version: not called CC=1 SCAR=6.9
1030  
1031 $FindBin::RealScript version $Tail::Stat::VERSION
1032  
1033 Copyright (C) 2010 Oleg A. Mamontov
1034  
1035 This program is free software; you can redistribute it and/or modify it
1036 under the terms of either: the GNU General Public License as published
1037 by the Free Software Foundation; or the Artistic License.
1038  
1039 See http://dev.perl.org/licenses/ for more information.
1040  
1041 EOM
1042 }
1043  
↑ Summary blib/lib/Tail/Stat/Plugin/nginx.pm »