blib/lib/Algorithm/Classifier/IsolationForest/App/Command/streamd.pm

filter: Statementstmt 80.1% 310 / 387 Branchbran 57.9% 153 / 264 Conditioncond 31.2% 25 / 80 MC/DCmcdc 13.0% 6 / 46 Subroutinesub 82.0% 32 / 39 Podpod 100% 5 / 5 totaltotal 64.6% 531 / 821 CC 166 SCAR 42.2
CC
166
Cov
67%
execute
169.0
validate
98.4
_daemonize
72.0
CRAP 68.0
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/stream.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/fit.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::streamd;
2  
3 86 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 86 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 86 ▶use Algorithm::Classifier::IsolationForest ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 86 ▶use Algorithm::Classifier::IsolationForest::Online ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 86 ▶use Algorithm::Classifier::IsolationForest::App -command;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 86 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 86 ▶use File::Path qw(make_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 86 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 86 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 86 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 86 ▶use IO::Socket::UNIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 86 ▶use IO::Select ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 86 ▶use POSIX qw(setsid strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 86 ▶use Errno qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 # The daemon is a singleton per process, so its runtime state lives in
19 # file-scoped lexicals rather than being threaded through every helper.
20 86 my $JSON; # JSON::MaybeXS codec (required at runtime, see execute)
21 my $OIF; # the online model
22 86 my %OPT; # resolved options
23 86 my $LOG_FH; # log handle (STDERR in foreground without --log)
24 86 my %CONN; # fileno => { sock, inbuf, outbuf, mode }
25 86 my $DIRTY = 0; # learned anything since the last save?
26 86 my $RUN; # cleared by SIGTERM/SIGINT
27 my $SAVE_NOW; # set by SIGUSR1
28 86 my $REOPEN_LOG; # set by SIGHUP
29  
30 # Sanity caps on per-connection buffers: a client is allowed big batch
31 # messages, but one that streams an endless line (or stops reading its
32 # replies) gets dropped instead of eating the daemon's memory.
33 86 ▶use constant MAX_INBUF => 16 * 1024 * 1024;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 86 ▶use constant MAX_OUTBUF => 16 * 1024 * 1024;
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 10 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
37 return (
38 [
39 10 'set=s',
40 'Named instance. Appended to --model-dir, and the socket/pid become <set>.sock / <set>.pid '
41 . 'under the run dir, so several daemons run side by side with no other flags. '
42 . 'Must match /\A[A-Za-z0-9+\-@_]+\z/.'
43 ],
44 [
45 'socket=s',
46 'Unix domain socket to listen on; default /var/run/iforest_streamd/streamd.sock. With --set '
47 . 'this is instead the base run dir (default /var/run/iforest_streamd) the <set>.sock is created in.',
48 { 'completion' => 'files' }
49 ],
50 [
51 'pid=s',
52 'Where to write the daemon pid; default /var/run/iforest_streamd/streamd.pid. With --set '
53 . 'this is instead the base run dir (default /var/run/iforest_streamd) the <set>.pid is created in.',
54 { 'completion' => 'files' }
55 ],
56 [
57 'model-dir=s',
58 'Directory timestamped model saves land in; the symlink latest.json in it always points '
59 . 'at the newest, and the daemon resumes from it at startup when it exists. With --set '
60 . 'the set name is appended as a subdirectory.',
61 { 'default' => '/var/db/iforest_streamd', 'completion' => 'files' }
62 ],
63 [
64 'save-interval=i',
65 'Seconds between periodic model saves (only when learning happened).',
66 { 'default' => 300 }
67 ],
68 [ 'keep=i', 'Prune all but the newest N timestamped model files after each save.' ],
69 [ 'f|foreground', 'Do not daemonize; log to stderr unless --log is given.' ],
70 [
71 'log=s',
72 'Log file. Defaults to <model-dir>/streamd.log when daemonized; stderr in the foreground.',
73 { 'completion' => 'files' }
74 ],
75 [ 'socket-mode=s', 'Octal permissions to chmod the socket file to (e.g. 0660).' ],
76 [ 'threshold=f', 'Alternative decision threshold to use for the label field. 0 < $val < 1' ],
77  
78 # creation knobs, used only when <model-dir>/latest.json does not exist yet
79 [ 'n=i', 'Number of isolation trees in the ensemble (new models only).' ],
80 [ 'window=i', 'Sliding window size; 0 disables forgetting (new models only).' ],
81 [ 'eta=i', 'max_leaf_samples: points a leaf accumulates before splitting (new models only).' ],
82 [ 'growth=s', "Leaf split-requirement growth, 'adaptive' or 'fixed' (new models only)." ],
83 [ 'subsample=f', 'Per-tree stream subsampling probability, in (0, 1] (new models only).' ],
84 [ 's=i', 'Seed int (new models only).' ],
85 [
86 'c=f',
87 'Contamination. Expected fraction of anomalies, in (0, 0.5]; the decision threshold is '
88 . 'relearned from the window before every save (new models only).'
89 ],
90 [
91 't=s@',
92 'Feature name tag. Pass once per feature; enables the tagged (JSON object) row form '
93 . '(new models only).'
94 ],
95 [
96 'mungers=s',
97 'JSON file of Algorithm::ToNumberMunger specs, keyed by feature tag (new models only; requires -t).',
98 { 'completion' => 'files' }
99 ],
100 [
101 'prototype=s',
102 'JSON prototype file to create the model from (new models only). May not be combined '
103 . 'with -t or --mungers. See PROTOTYPES in the module POD.',
104 { 'completion' => 'files' }
105 ],
106 );
107 } ## end sub opt_spec
108  
109 0 ▶sub abstract { 'Run an Online Isolation Forest scoring daemon on a Unix socket, speaking JSON lines' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
110  
111 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
112 0 'Runs a prequential scoring daemon around an Online Isolation Forest
113 model (Algorithm::Classifier::IsolationForest::Online): clients connect
114 to the Unix domain socket and exchange one JSON document per line.
115  
116 At startup the daemon resumes from <model-dir>/latest.json when it
117 exists; otherwise it creates a new model from the creation knobs (-n,
118 --window, --eta, --growth, --subsample, -s, -c, -t, --mungers,
119 --prototype -- the same set `iforest stream` takes). The model is saved
120 to a timestamped file in --model-dir every --save-interval seconds
121 (only when something was learned), on SIGUSR1, on the save command, and
122 at shutdown; the symlink latest.json is atomically repointed at every
123 save, so a restart resumes the stream losing at most one interval.
124  
125 Requests are JSON objects carrying exactly one of "row", "rows", or
126 "cmd", an optional "mode", and an optional "tag" (any JSON value,
127 echoed back verbatim in the reply -- a correlation tag, not to be
128 confused with feature tags):
129  
130 {"row": [0.1, 0.7]} -> {"score": 0.41, "label": 0}
131 {"row": {"cpu": 0.1, "mem": 0.7}} -> {"score": 0.41, "label": 0}
132 {"rows": [[...], {...}], "tag": "b7"} -> {"scores": [[0.41,0], ...], "tag": "b7"}
133 {"rows": [[...]], "mode": "learn"} -> {"ok": {"learned": 1}}
134 {"cmd": "mode", "mode": "score"} -> {"ok": {"mode": "score"}}
135 {"cmd": "ping"} -> {"ok": "pong"}
136 {"cmd": "stats"} -> {"ok": {"seen": ..., ...}}
137 {"cmd": "save"} -> {"ok": {"saved": "oiforest-....json"}}
138 {"cmd": "relearn-threshold"} -> {"ok": {"threshold": 0.61}}
139 anything invalid -> {"error": "...", "tag": ...}
140  
141 The array row form is positional (scalar mungers applied, like stream
142 CSV input); the object form is a tagged row and runs the full munger
143 plan, including expanding and combining mungers -- and, being JSON, the
144 raw values may safely contain commas, newlines, or any unicode.
145  
146 A worked tagged example. Create the daemon around raw HTTP request
147 data, with mungers turning the raw values into numbers (mungers.json
148 here; a --prototype carrying the same schema works identically):
149  
150 { "method": { "munger": "http_method_enum", "default": -1 },
151 "path_len": { "munger": "length", "from": "path" },
152 "host_entropy": { "munger": "entropy", "from": "host" } }
153  
154 iforest streamd --set web -t method -t path_len -t host_entropy \
155 --mungers mungers.json -c 0.05
156  
157 Clients then send the raw values themselves -- note the input fields
158 are the munger SOURCES (method, path, host), not the feature tags,
159 because the plan derives path_len and host_entropy from them:
160  
161 -> {"row": {"method": "GET", "path": "/index.html",
162 "host": "www.example.com"}, "tag": "r-1"}
163 <- {"score": 0.31, "label": 0, "tag": "r-1"}
164 -> {"row": {"method": "BREW", "path": "/aa,a\"a.php",
165 "host": "kq3xv9z2.biz"}, "tag": "r-2"}
166 <- {"score": 0.74, "label": 1, "tag": "r-2"}
167  
168 The same rows work from the shell via
169 `iforest streamc --set web --jsonl -i rows.jsonl`.
170  
171 Modes are prequential (score each row against the model as it stood, then
172 learn it -- the default), learn (learn only), and score (score only);
173 "mode" on a row/rows message overrides the connection default set by
174 the mode command for that message. A bad row gets an {"error": ...}
175 reply on that message only; the connection and the daemon live on (for
176 a "rows" batch, rows before the failing one were already processed).
177  
178 Multiple concurrent connections are supported; rows are applied to the
179 one shared model in the order their lines arrive, which defines the
180 stream order.
181  
182 --set NAME runs a named instance: the set name is appended to
183 --model-dir (so its saves, latest.json, and default log live under
184 their own subdirectory) and the socket/pid become <set>.sock /
185 <set>.pid under the run dir -- with --set, --socket and --pid name the
186 base run dir instead of the files. Several sets run side by side, each
187 with its own model, resume state, and double-start protection:
188  
189 iforest streamd --set web
190 iforest streamd --set dns --prototype dns-proto.json -c 0.02
191  
192 Set names must match /\A[A-Za-z0-9+\-@_]+\z/; since the class has no
193 "." or "/", a set name can only ever create one new path segment.
194  
195 Everything under --model-dir and the socket/pid directories is created
196 at startup when missing; when that fails (e.g. running unprivileged
197 with the /var defaults) the daemon dies immediately, before forking,
198 naming the directory and the flag to override.
199 ';
200 } ## end sub description
201  
202 10 ▶sub validate {
Subroutine validate: called CC=22 SCAR=45.9
Pod documented
203 10 my ( $self, $opt, $args ) = @_;
204  
205 # Anchored with \A/\z rather than ^/$ ($ tolerates a trailing newline).
206 # The class has no '.' or '/', so a set name can only ever create one
207 # new path segment -- no traversal is expressible.
208 10 ▶ if ( defined( $opt->{'set'} ) && $opt->{'set'} !~ /\A[A-Za-z0-9+\-@_]+\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"set"} and not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/) 3 7 10
Condition100%3/3
defined $opt->{"set"} and not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
!ll&&!rl&&r
433
MC/DC100%2/2
defined $opt->{"set"} and not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
defined $opt->{"set"} not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
Truth table100%3/3
A and not(B)
A= defined $opt->{"set"}B= not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
ABresult
0X0
100
111
209 $self->usage_error( '--set, "'
210 3 . $opt->{'set'}
211 . '", must match /\A[A-Za-z0-9+\-@_]+\z/ (letters, digits, and + - @ _ only)' );
212 }
213  
214 7 ▶ if ( $opt->{'save_interval'} < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"save_interval"} < 1) 0 7 7
215 0 $self->usage_error( '--save-interval, "' . $opt->{'save_interval'} . '", must be >= 1 second' );
216 }
217  
218 7 ▶ if ( defined( $opt->{'keep'} ) && $opt->{'keep'} < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"keep"} and $opt->{"keep"} < 1) 0 7 7
Condition33%1/3
defined $opt->{"keep"} and $opt->{"keep"} < 1
!ll&&!rl&&r
700
MC/DC0%0/2
defined $opt->{"keep"} and $opt->{"keep"} < 1
defined $opt->{"keep"} $opt->{"keep"} < 1
Truth table33%1/3
A and B
A= defined $opt->{"keep"}B= $opt->{"keep"} < 1
ABresult
0X0
100
111
219 0 $self->usage_error( '--keep, "' . $opt->{'keep'} . '", must be >= 1' );
220 }
221  
222 7 ▶ if ( defined( $opt->{'threshold'} ) && ( $opt->{'threshold'} <= 0 || $opt->{'threshold'} >= 1 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"threshold"} and $opt->{"threshold"} <= 0 || $opt->{"threshold"} >= 1) 0 7 7
Condition16%1/6
defined $opt->{"threshold"} and $opt->{"threshold"} <= 0 || $opt->{"threshold"} >= 1
!ll&&!rl&&r
700
$opt->{"threshold"} <= 0 or $opt->{"threshold"} >= 1
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $opt->{"threshold"} and $opt->{"threshold"} <= 0 || $opt->{"threshold"} >= 1
defined $opt->{"threshold"} $opt->{"threshold"} <= 0 $opt->{"threshold"} >= 1
Truth table25%1/4
A and B or C
A= defined $opt->{"threshold"}B= $opt->{"threshold"} <= 0C= $opt->{"threshold"} >= 1
ABCresult
0XX0
1000
11X1
1011
223 0 $self->usage_error( '--threshold, "' . $opt->{'threshold'} . '", needs to be greater than 0 and less than 1' );
224 }
225  
226 7 ▶ if ( defined( $opt->{'growth'} ) && $opt->{'growth'} !~ /\A(?:adaptive|fixed)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"growth"} and not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/) 0 7 7
Condition33%1/3
defined $opt->{"growth"} and not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
!ll&&!rl&&r
700
MC/DC0%0/2
defined $opt->{"growth"} and not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
defined $opt->{"growth"} not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
Truth table33%1/3
A and not(B)
A= defined $opt->{"growth"}B= not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
ABresult
0X0
100
111
227 0 $self->usage_error( '--growth, "' . $opt->{'growth'} . '", must be either adaptive or fixed' );
228 }
229  
230 7 ▶ if ( defined( $opt->{'socket_mode'} ) && $opt->{'socket_mode'} !~ /\A0?[0-7]{3}\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"socket_mode"} and not $opt->{"socket_mode"} =~ /\A0?[0-7]{3}\z/) 0 7 7
Condition33%1/3
defined $opt->{"socket_mode"} and not $opt->{"socket_mode"} =~ /\A0?[0-7]{3}\z/
!ll&&!rl&&r
700
MC/DC0%0/2
defined $opt->{"socket_mode"} and not $opt->{"socket_mode"} =~ /\A0?[0-7]{3}\z/
defined $opt->{"socket_mode"} not $opt->{"socket_mode"} =~ /\A0?[0-7]{3}\z/
Truth table33%1/3
A and not(B)
A= defined $opt->{"socket_mode"}B= not $opt->{"socket_mode"} =~ /\A0?[0-7]{3}\z/
ABresult
0X0
100
111
231 0 $self->usage_error( '--socket-mode, "' . $opt->{'socket_mode'} . '", must be octal like 0660' );
232 }
233  
234 7 ▶ if ( defined( $opt->{'mungers'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"mungers"}) 0 7 7
235 0 ▶ if ( !-f $opt->{'mungers'} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not -f $opt->{'mungers'}) { } 0 0 0
elsif (not -r $opt->{'mungers'}) { } 0 0 0
elsif (not defined $opt->{'t'}) { } 0 0 0
236 0 $self->usage_error( '--mungers, "' . $opt->{'mungers'} . '", is not a file or does not exist' );
237 } elsif ( !-r $opt->{'mungers'} ) {
238 0 $self->usage_error( '--mungers, "' . $opt->{'mungers'} . '", is not readable' );
239 } elsif ( !defined( $opt->{'t'} ) ) {
240 0 $self->usage_error('--mungers requires feature tags (-t) to compile against');
241 }
242 }
243  
244 7 ▶ if ( defined( $opt->{'prototype'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"prototype"}) 1 6 7
245 1 ▶ if ( !-f $opt->{'prototype'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'prototype'}) { } 0 1 1
elsif (not -r $opt->{'prototype'}) { } 0 1 1
246 0 $self->usage_error( '--prototype, "' . $opt->{'prototype'} . '", is not a file or does not exist' );
247 } elsif ( !-r $opt->{'prototype'} ) {
248 0 $self->usage_error( '--prototype, "' . $opt->{'prototype'} . '", is not readable' );
249 }
250 1 ▶ if ( defined( $opt->{'t'} ) || defined( $opt->{'mungers'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"t"} or defined $opt->{"mungers"}) 0 1 1
Condition33%1/3
defined $opt->{"t"} or defined $opt->{"mungers"}
l!l&&r!l&&!r
001
MC/DC0%0/2
defined $opt->{"t"} or defined $opt->{"mungers"}
defined $opt->{"t"} defined $opt->{"mungers"}
Truth table33%1/3
A or B
A= defined $opt->{"t"}B= defined $opt->{"mungers"}
ABresult
1X1
011
000
251 0 $self->usage_error(
252 '--prototype may not be combined with -t or --mungers; the schema comes only from the prototype');
253 }
254 } ## end if ( defined( $opt->{'prototype'} ) )
255  
256 7 return 1;
257 } ## end sub validate
258  
259 7 ▶sub execute {
Subroutine execute: called CC=56 SCAR=51.3
Pod documented
260 7 my ( $self, $opt, $args ) = @_;
261  
262 # JSON::MaybeXS is required lazily so a box without it still has a
263 # working iforest CLI (App::Cmd loads every command module up front).
264 7 ▶ eval { require JSON::MaybeXS; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require JSON::MaybeXS; 1 } } or die 'iforest streamd requires JSON::MaybeXS for its wire protocol; install it: ' . $@ 7 0 7
265 or die( 'iforest streamd requires JSON::MaybeXS for its wire protocol; install it: ' . $@ );
266 7 $JSON = JSON::MaybeXS->new( utf8 => 1, canonical => 1, allow_nonref => 0 );
267  
268 7 %OPT = %$opt;
269  
270 # --set turns --socket/--pid into base run dirs holding <set>.sock /
271 # <set>.pid and appends the set name to --model-dir, so several named
272 # daemons run side by side with no other flags. Without a set the
273 # flags are the socket/pid files themselves, defaulting as documented.
274 7 ▶ if ( defined $OPT{'set'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $OPT{'set'}) { } 3 4 7
275 3 ▶ my $run = defined $OPT{'socket'} ? $OPT{'socket'} : '/var/run/iforest_streamd';
Branch: 1 branch
BranchTrueFalseTotal
defined $OPT{'socket'} ? : 3 0 3
276 3 $OPT{'socket'} = File::Spec->catfile( $run, $OPT{'set'} . '.sock' );
277 3 ▶ my $prun = defined $OPT{'pid'} ? $OPT{'pid'} : '/var/run/iforest_streamd';
Branch: 1 branch
BranchTrueFalseTotal
defined $OPT{'pid'} ? : 3 0 3
278 3 $OPT{'pid'} = File::Spec->catfile( $prun, $OPT{'set'} . '.pid' );
279 3 $OPT{'model_dir'} = File::Spec->catdir( $OPT{'model_dir'}, $OPT{'set'} );
280 } else {
281 4 ▶ $OPT{'socket'} = '/var/run/iforest_streamd/streamd.sock' unless defined $OPT{'socket'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $OPT{"socket"} 1 3 4
282 4 ▶ $OPT{'pid'} = '/var/run/iforest_streamd/streamd.pid' unless defined $OPT{'pid'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $OPT{"pid"} 1 3 4
283 }
284  
285 # Daemonizing chdirs to /, so every path used after that point must be
286 # absolute -- including the socket and pid file, which are unlinked at
287 # shutdown.
288 7 for my $path_opt (qw(socket pid model_dir log)) {
289 $OPT{$path_opt} = File::Spec->rel2abs( $OPT{$path_opt} )
290 28 ▶ if defined $OPT{$path_opt};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{$path_opt} 24 4 28
291 }
292  
293 # sun_path is 104 bytes on the BSDs and 108 on Linux (including the
294 # NUL); Socket.pm just warns and TRUNCATES an over-long path, which
295 # binds a socket nobody will ever find. Refuse loudly instead.
296 die( '--socket, "'
297 . $OPT{'socket'}
298 . '", is '
299 . length( $OPT{'socket'} )
300 . ' bytes; Unix socket paths are limited to ~104 bytes -- use a shorter path'
301 . "\n" )
302 7 ▶ if length( $OPT{'socket'} ) > 100;
Branch: 1 branch
BranchTrueFalseTotal
if length $OPT{"socket"} > 100 0 7 7
303  
304 # --- directories, before anything forks or binds -----------------------
305 7 _ensure_dir( $OPT{'model_dir'}, '--model-dir' );
306 6 _ensure_dir( dirname( $OPT{'socket'} ), '--socket' );
307 6 _ensure_dir( dirname( $OPT{'pid'} ), '--pid' );
308  
309 # --- refuse to double-start ---------------------------------------------
310 6 ▶ if ( -e $OPT{'socket'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $OPT{"socket"}) 0 6 6
311 0 my $probe = IO::Socket::UNIX->new( Peer => $OPT{'socket'} );
312 0 ▶ die( 'another daemon is already listening on "' . $OPT{'socket'} . '"' . "\n" ) if $probe;
Branch: 1 branch
BranchTrueFalseTotal
if $probe 0 0 0
313 0 unlink $OPT{'socket'}; # stale socket from an unclean exit
314 }
315 6 ▶ if ( -f $OPT{'pid'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $OPT{"pid"}) 0 6 6
316 0 my $old = read_file( $OPT{'pid'} );
317 0 ▶ chomp $old if defined $old;
Branch: 1 branch
BranchTrueFalseTotal
if defined $old 0 0 0
318 0 ▶ if ( defined $old && $old =~ /\A\d+\z/ && ( kill( 0, $old ) || $!{EPERM} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $old and $old =~ /\A\d+\z/ and kill(0, $old) || $!{"EPERM"}) 0 0 0
Condition0%0/9
defined $old and $old =~ /\A\d+\z/ and kill(0, $old) || $!{"EPERM"}
!ll&&!rl&&r
000
defined $old and $old =~ /\A\d+\z/
!ll&&!rl&&r
000
kill 0, $old or $!{"EPERM"}
l!l&&r!l&&!r
000
MC/DC0%0/4
defined $old and $old =~ /\A\d+\z/ and kill(0, $old) || $!{"EPERM"}
defined $old $old =~ /\A\d+\z/ kill 0, $old $!{"EPERM"}
Truth table0%0/5
A and B and C or D
A= defined $oldB= $old =~ /\A\d+\z/C= kill 0, $oldD= $!{"EPERM"}
ABCDresult
0XXX0
10XX0
11000
111X1
11011
319 0 die( 'another daemon appears to be running (pid ' . $old . ' from "' . $OPT{'pid'} . '")' . "\n" );
320 }
321 0 unlink $OPT{'pid'}; # stale pid file
322 }
323  
324 # --- resume or create the model ----------------------------------------
325 6 my $latest = File::Spec->catfile( $OPT{'model_dir'}, 'latest.json' );
326 6 ▶ if ( -e $latest ) {
Branch: 2 branches
BranchTrueFalseTotal
if (-e $latest) { } 1 5 6
elsif (defined $OPT{'prototype'}) { } 1 4 5
327 1 $OIF = Algorithm::Classifier::IsolationForest->load($latest);
328 1 ▶ die( '"' . $latest . '" is not an online model; streamd only works on those' . "\n" )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $OIF eq "Algorithm::Classifier::IsolationForest::Online" 0 1 1
329 unless ref $OIF eq 'Algorithm::Classifier::IsolationForest::Online';
330 } elsif ( defined $OPT{'prototype'} ) {
331 1 my $proto = eval {
332 1 Algorithm::Classifier::IsolationForest->validate_prototype( scalar read_file( $OPT{'prototype'} ) );
333 };
334 1 ▶ die( '--prototype, "' . $OPT{'prototype'} . '", is not a valid prototype: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
335 die( '--prototype, "' . $OPT{'prototype'} . '", is for a batch model; streamd needs an online one' . "\n" )
336 1 ▶ unless $proto->{class} eq 'online';
Branch: 1 branch
BranchTrueFalseTotal
unless $proto->{"class"} eq "online" 0 1 1
337  
338 1 my %overrides;
339 1 ▶ $overrides{'n_trees'} = $OPT{'n'} if defined $OPT{'n'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"n"} 0 1 1
340 1 ▶ $overrides{'window_size'} = $OPT{'window'} if defined $OPT{'window'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"window"} 0 1 1
341 1 ▶ $overrides{'max_leaf_samples'} = $OPT{'eta'} if defined $OPT{'eta'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"eta"} 0 1 1
342 1 ▶ $overrides{'growth'} = $OPT{'growth'} if defined $OPT{'growth'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"growth"} 0 1 1
343 1 ▶ $overrides{'subsample'} = $OPT{'subsample'} if defined $OPT{'subsample'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"subsample"} 0 1 1
344 1 ▶ $overrides{'seed'} = $OPT{'s'} if defined $OPT{'s'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"s"} 1 0 1
345 1 ▶ $overrides{'contamination'} = $OPT{'c'} if defined $OPT{'c'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"c"} 0 1 1
346  
347 1 $OIF = eval { Algorithm::Classifier::IsolationForest->new_from_prototype( $proto, %overrides ) };
348 1 ▶ die( '--prototype, "' . $OPT{'prototype'} . '", failed to create a model: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
349 } else {
350 4 my $mungers;
351 4 ▶ if ( defined $OPT{'mungers'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $OPT{"mungers"}) 0 4 4
352 0 $mungers = eval { $JSON->decode( scalar read_file( $OPT{'mungers'} ) ) };
353 0 ▶ die( '--mungers, "' . $OPT{'mungers'} . '", did not parse as JSON: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
354 0 ▶ die( '--mungers, "' . $OPT{'mungers'} . '", must be a JSON object of tag => spec' )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $mungers eq "HASH" 0 0 0
355 unless ref $mungers eq 'HASH';
356 }
357 $OIF = Algorithm::Classifier::IsolationForest::Online->new(
358 'n_trees' => $OPT{'n'},
359 'window_size' => $OPT{'window'},
360 'max_leaf_samples' => $OPT{'eta'},
361 'growth' => $OPT{'growth'},
362 'subsample' => $OPT{'subsample'},
363 'seed' => $OPT{'s'},
364 'contamination' => $OPT{'c'},
365 4 'feature_names' => $OPT{'t'},
366 'mungers' => $mungers,
367 );
368 } ## end else [ if ( -e $latest ) ]
369  
370 # --- bind, then daemonize (the listening fd survives the forks) --------
371 my $listener = IO::Socket::UNIX->new(
372 Local => $OPT{'socket'},
373 Listen => 64,
374 6 ▶ ) or die( 'failed to listen on "' . $OPT{'socket'} . '": ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
my $listener = "IO::Socket::UNIX"->new("Local", $OPT{"socket"}, "Listen", 64) or die 'failed to listen on "' . $OPT{"socket"} . '": ' . $! . "\n" 6 0 6
375 6 $listener->blocking(0);
376 6 ▶ if ( defined $OPT{'socket_mode'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $OPT{"socket_mode"}) 0 6 6
377 chmod( oct( $OPT{'socket_mode'} ), $OPT{'socket'} )
378 0 ▶ or die( 'failed to chmod "' . $OPT{'socket'} . '" to ' . $OPT{'socket_mode'} . ': ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
chmod oct $OPT{"socket_mode"}, $OPT{"socket"} or die 'failed to chmod "' . $OPT{"socket"} . '" to ' . $OPT{"socket_mode"} . ': ' . $! . "\n" 0 0 0
379 }
380  
381 6 ▶ if ( !$OPT{'f'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($OPT{"f"}) 0 6 6
382 $OPT{'log'} = File::Spec->catfile( $OPT{'model_dir'}, 'streamd.log' )
383 0 ▶ unless defined $OPT{'log'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $OPT{"log"} 0 0 0
384 0 _daemonize();
385 }
386 6 _open_log();
387  
388 6 write_file( $OPT{'pid'}, { 'atomic' => 1 }, $$ . "\n" );
389  
390 # --- signals -------------------------------------------------------------
391 6 $RUN = 1;
392 6 $SAVE_NOW = 0;
393 6 $REOPEN_LOG = 0;
394 6 ▶ local $SIG{TERM} = sub { $RUN = 0 };
Subroutine __ANON__: called CC=1 SCAR=0.0
395 0 ▶ local $SIG{INT} = sub { $RUN = 0 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
396 0 ▶ local $SIG{USR1} = sub { $SAVE_NOW = 1 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
397 0 ▶ local $SIG{HUP} = sub { $REOPEN_LOG = 1 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
398 6 local $SIG{PIPE} = 'IGNORE';
399  
400 _log( 'listening on '
401 . $OPT{'socket'}
402 . ( -e $latest ? ' (resumed ' : ' (new model, ' )
403 . ( defined $OPT{'set'} ? 'set=' . $OPT{'set'} . ', ' : '' ) . 'seen='
404 . $OIF->seen
405 . ', save-interval='
406 . $OPT{'save_interval'} . 's'
407 . ', model-dir='
408 6 ▶ . $OPT{'model_dir'}
Branch: 2 branches
BranchTrueFalseTotal
-e $latest ? : 1 5 6
defined $OPT{'set'} ? : 3 3 6
409 . ')' );
410  
411 # --- event loop ----------------------------------------------------------
412 6 my $rsel = IO::Select->new($listener);
413 6 my $wsel = IO::Select->new();
414 6 my $next_save = time + $OPT{'save_interval'};
415  
416 6 ▶ while ($RUN) {
Branch: 1 branch
BranchTrueFalseTotal
if ($RUN) 108 6 114
417 108 my $timeout = $next_save - time;
418 108 ▶ $timeout = 0 if $timeout < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $timeout < 0 0 108 108
419  
420 108 my @ready = $rsel->can_read($timeout);
421 108 for my $s (@ready) {
422 103 ▶ if ( $s == $listener ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s == $listener) 24 79 103
423 24 ▶ while ( my $cl = $listener->accept ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cl = $listener->accept) 24 24 48
424 24 $cl->blocking(0);
425 24 $CONN{ fileno($cl) } = { sock => $cl, inbuf => '', outbuf => '', mode => 'prequential' };
426 24 $rsel->add($cl);
427 }
428 24 next;
429 }
430 79 _read_from( $s, $rsel, $wsel );
431 } ## end for my $s (@ready)
432  
433 # Drain clients whose replies did not fit in one write.
434 108 ▶ if ( $wsel->count ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wsel->count) 0 108 108
435 0 for my $s ( $wsel->can_write(0) ) {
436 0 _flush( $s, $rsel, $wsel );
437 }
438 }
439  
440 108 ▶ if ($REOPEN_LOG) {
Branch: 1 branch
BranchTrueFalseTotal
if ($REOPEN_LOG) 0 108 108
441 0 $REOPEN_LOG = 0;
442 0 _open_log();
443 0 _log('log reopened on SIGHUP');
444 }
445 108 ▶ if ( $SAVE_NOW || time >= $next_save ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($SAVE_NOW or time >= $next_save) 3 105 108
Condition66%2/3
$SAVE_NOW or time >= $next_save
l!l&&r!l&&!r
03105
MC/DC50%1/2
$SAVE_NOW or time >= $next_save
$SAVE_NOW time >= $next_save
Truth table66%2/3
A or B
A= $SAVE_NOWB= time >= $next_save
ABresult
1X1
011
000
446 3 ▶ _save_model( $SAVE_NOW ? 'signal' : 'interval' ) if $DIRTY || $SAVE_NOW;
Branch: 2 branches
BranchTrueFalseTotal
if $DIRTY or $SAVE_NOW 2 1 3
$SAVE_NOW ? : 0 2 2
Condition66%2/3
$DIRTY or $SAVE_NOW
l!l&&r!l&&!r
201
MC/DC50%1/2
$DIRTY or $SAVE_NOW
$DIRTY $SAVE_NOW
Truth table66%2/3
A or B
A= $DIRTYB= $SAVE_NOW
ABresult
1X1
011
000
447 3 $SAVE_NOW = 0;
448 3 $next_save = time + $OPT{'save_interval'};
449 }
450 } ## end while ($RUN)
451  
452 # --- shutdown ------------------------------------------------------------
453 6 _log('shutting down');
454 6 ▶ _save_model('shutdown') if $DIRTY;
Branch: 1 branch
BranchTrueFalseTotal
if $DIRTY 2 4 6
455 6 for my $c ( values %CONN ) {
456 1 close $c->{sock};
457 }
458 6 %CONN = ();
459 6 close $listener;
460 6 unlink $OPT{'socket'};
461 6 unlink $OPT{'pid'};
462 6 _log('bye');
463  
464 6 return 1;
465 } ## end sub execute
466  
467 #-------------------------------------------------------------------------------
468 # startup helpers
469 #-------------------------------------------------------------------------------
470  
471 # Make sure a directory the daemon needs exists and is writable, creating
472 # it when it does not. Run before daemonizing so a permissions problem is
473 # reported to the terminal that started the daemon rather than buried in a
474 # log the user has not found yet.
475 #
476 # Args:
477 # $dir :: the directory to create or check.
478 # $flag :: the option that asked for it, e.g. '--model-dir'. Only used
479 # to name the fix in the error message.
480 #
481 # Returns: 1 when the directory exists and is writable. Dies otherwise,
482 # telling the user to create it, fix its permissions, or point $flag
483 # somewhere else.
484 #
485 # Example:
486 # _ensure_dir( $OPT{'model_dir'}, '--model-dir' );
487 19 ▶sub _ensure_dir {
Subroutine _ensure_dir: called CC=4 SCAR=13.9
488 19 my ( $dir, $flag ) = @_;
489 19 ▶ if ( !-d $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir) 6 13 19
490 6 my $err;
491 6 make_path( $dir, { mode => oct('0755'), error => \$err } );
492 6 ▶ die( 'could not create "'
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 1 5 6
493 . $dir
494 . '" (needed for '
495 . $flag
496 . '); create it, fix permissions, or point '
497 . $flag
498 . ' somewhere writable'
499 . "\n" )
500 if !-d $dir;
501 } ## end if ( !-d $dir )
502 18 ▶ die( '"' . $dir . '" (needed for ' . $flag . ') is not writable; fix permissions or override ' . $flag . "\n" )
Branch: 1 branch
BranchTrueFalseTotal
unless -w $dir 0 18 18
503 unless -w $dir;
504 18 return 1;
505 } ## end sub _ensure_dir
506  
507 # Classic double-fork daemonization. The parents leave via POSIX::_exit
508 # so no END blocks (Inline's, App::Cmd's) run twice. The second fork is
509 # what guarantees the daemon can never reacquire a controlling terminal.
510 #
511 # Args: none. Reads nothing and takes nothing -- the caller decides
512 # whether to daemonize at all (-f keeps the process in the foreground).
513 #
514 # Returns: 1, in the grandchild only. The two parents never return: they
515 # _exit(0) immediately, so the caller either continues as the daemon or
516 # does not continue. Dies on a failed fork, setsid, chdir or STDIN
517 # reopen.
518 #
519 # Example:
520 # _daemonize() unless $OPT{'f'};
521 # # from here on we are the daemon
522 0 ▶sub _daemonize {
Subroutine _daemonize: not called CC=8 SCAR=42.8
523 0 ▶ defined( my $pid = fork() ) or die( 'fork failed: ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
defined(my $pid = fork) or die 'fork failed: ' . $! . "\n" 0 0 0
524 0 ▶ POSIX::_exit(0) if $pid;
Branch: 1 branch
BranchTrueFalseTotal
if $pid 0 0 0
525 0 ▶ setsid() or die( 'setsid failed: ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
setsid() or die 'setsid failed: ' . $! . "\n" 0 0 0
526 0 ▶ defined( $pid = fork() ) or die( 'second fork failed: ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
defined($pid = fork) or die 'second fork failed: ' . $! . "\n" 0 0 0
527 0 ▶ POSIX::_exit(0) if $pid;
Branch: 1 branch
BranchTrueFalseTotal
if $pid 0 0 0
528 0 ▶ chdir '/' or die( 'chdir / failed: ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
chdir "/" or die 'chdir / failed: ' . $! . "\n" 0 0 0
529 0 ▶ open( STDIN, '<', '/dev/null' ) or die( 'reopen STDIN failed: ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<", "/dev/null" or die 'reopen STDIN failed: ' . $! . "\n" 0 0 0
530 0 return 1;
531 } ## end sub _daemonize
532  
533 # Point the daemon's logging at wherever --log said, falling back to
534 # STDERR. When daemonized, STDOUT and STDERR are reopened onto the log
535 # too, so a warn from anywhere in the process still lands somewhere the
536 # operator can read. Everything is unbuffered: a daemon's log is useless
537 # if the interesting line is still sitting in a buffer when it wedges.
538 #
539 # Args: none. Reads $OPT{'log'} and $OPT{'f'}.
540 #
541 # Returns: 1. Sets the package's $LOG_FH as its whole purpose. Dies when
542 # the log file cannot be opened.
543 #
544 # Example:
545 # _open_log();
546 # _log('listening');
547 6 ▶sub _open_log {
Subroutine _open_log: called CC=6 SCAR=22.9
548 6 ▶ if ( defined $OPT{'log'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $OPT{'log'}) { } 3 3 6
549 3 ▶ open( my $fh, '>>', $OPT{'log'} ) or die( 'failed to open log "' . $OPT{'log'} . '": ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">>", $OPT{"log"} or die 'failed to open log "' . $OPT{"log"} . '": ' . $! . "\n" 3 0 3
550 3 $fh->autoflush(1);
551 3 $LOG_FH = $fh;
552 3 ▶ if ( !$OPT{'f'} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($OPT{"f"}) 0 3 3
553 0 ▶ open( STDOUT, '>>', $OPT{'log'} ) or die( 'reopen STDOUT failed: ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">>", $OPT{"log"} or die 'reopen STDOUT failed: ' . $! . "\n" 0 0 0
554 0 ▶ open( STDERR, '>>', $OPT{'log'} ) or die( 'reopen STDERR failed: ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">>", $OPT{"log"} or die 'reopen STDERR failed: ' . $! . "\n" 0 0 0
555 0 STDOUT->autoflush(1);
556 0 STDERR->autoflush(1);
557 }
558 } else {
559 3 $LOG_FH = \*STDERR;
560 }
561 6 return 1;
562 } ## end sub _open_log
563  
564 # Write one timestamped, pid-stamped line to the log. The pid matters
565 # because several named instances (--set) can share one log file.
566 #
567 # Args:
568 # $msg :: the message, without a trailing newline -- one is added.
569 #
570 # Returns: 1.
571 #
572 # Example:
573 # _log( 'saved ' . $name . ' (' . $why . ')' );
574 # # 2026-08-08T14:02:11 [4821] saved oiforest-20260808-140211.json (interval)
575 25 ▶sub _log {
Subroutine _log: called CC=1 SCAR=0.0
576 25 my ($msg) = @_;
577 25 print {$LOG_FH} strftime( '%Y-%m-%dT%H:%M:%S', localtime ) . ' [' . $$ . '] ' . $msg . "\n";
578 25 return 1;
579 }
580  
581 #-------------------------------------------------------------------------------
582 # model persistence
583 #-------------------------------------------------------------------------------
584  
585 # Timestamped save + atomic symlink flip. The symlink stores a relative
586 # name, so the whole model directory can be moved without breaking it.
587 #
588 # Args:
589 # $why :: a short reason recorded in the log line, e.g. 'interval',
590 # 'command', 'SIGUSR1' or 'shutdown'.
591 #
592 # Returns: the file name written, relative to --model-dir. Also clears
593 # the dirty flag, repoints latest.json, and prunes old models when --keep
594 # is set. Dies if the write fails; a failed symlink or rename only warns
595 # to the log, since the model itself is already safely on disk.
596 #
597 # Example:
598 # my $name = _save_model('interval'); # 'oiforest-20260808-140211.json'
599 7 ▶sub _save_model {
Subroutine _save_model: called CC=7 SCAR=20.2
600 7 my ($why) = @_;
601  
602 # Keep the persisted default cutoff tracking the stream, like the
603 # stream command does before its save.
604 7 ▶ if ( defined $OIF->{contamination} && $OIF->window_count ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $OIF->{"contamination"} and $OIF->window_count) 0 7 7
Condition33%1/3
defined $OIF->{"contamination"} and $OIF->window_count
!ll&&!rl&&r
700
MC/DC0%0/2
defined $OIF->{"contamination"} and $OIF->window_count
defined $OIF->{"contamination"} $OIF->window_count
Truth table33%1/3
A and B
A= defined $OIF->{"contamination"}B= $OIF->window_count
ABresult
0X0
100
111
605 0 $OIF->relearn_threshold;
606 }
607  
608 7 my $base = 'oiforest-' . strftime( '%Y%m%d-%H%M%S', localtime );
609 7 my $name = $base . '.json';
610 7 my $n = 0;
611 7 ▶ while ( -e File::Spec->catfile( $OPT{'model_dir'}, $name ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e "File::Spec"->catfile($OPT{"model_dir"}, $name)) 1 7 8
612 1 $n++;
613 1 $name = $base . '-' . $n . '.json';
614 }
615 7 write_file( File::Spec->catfile( $OPT{'model_dir'}, $name ), { 'atomic' => 1 }, $OIF->to_json );
616  
617 7 my $tmp = File::Spec->catfile( $OPT{'model_dir'}, '.latest.tmp.' . $$ );
618 7 unlink $tmp;
619 7 ▶ symlink( $name, $tmp )
Branch: 1 branch
BranchTrueFalseTotal
symlink $name, $tmp or _log('WARNING: symlink for latest.json failed: ' . $!) 7 0 7
620 or _log( 'WARNING: symlink for latest.json failed: ' . $! );
621 7 ▶ rename( $tmp, File::Spec->catfile( $OPT{'model_dir'}, 'latest.json' ) )
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp, "File::Spec"->catfile($OPT{"model_dir"}, "latest.json") or _log('WARNING: renaming latest.json symlink failed: ' . $!) 7 0 7
622 or _log( 'WARNING: renaming latest.json symlink failed: ' . $! );
623  
624 7 $DIRTY = 0;
625 7 _log( 'saved ' . $name . ' (' . $why . ', seen=' . $OIF->seen . ')' );
626 7 ▶ _prune_models() if defined $OPT{'keep'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OPT{"keep"} 0 7 7
627 7 return $name;
628 } ## end sub _save_model
629  
630 # Keep only the newest --keep timestamped models, deleting the rest
631 # oldest-first. Ordered by mtime rather than by the name's timestamp so
632 # a clock stepping backwards cannot strand a file forever. latest.json is
633 # a symlink, not a match for the model pattern, so it is never a
634 # candidate.
635 #
636 # Args: none. Reads $OPT{'model_dir'} and $OPT{'keep'}, and is only
637 # called when --keep is set.
638 #
639 # Returns: 1, or an empty return when the model directory cannot be
640 # opened -- pruning is housekeeping, so it never takes the daemon down.
641 #
642 # Example:
643 # _prune_models() if defined $OPT{'keep'};
644 0 ▶sub _prune_models {
Subroutine _prune_models: not called CC=4 SCAR=30.0
645 0 ▶ opendir( my $dh, $OPT{'model_dir'} ) or return;
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $OPT{"model_dir"} or return 0 0 0
646 0 my @models = sort { ( stat($a) )[9] <=> ( stat($b) )[9] }
647 0 map { File::Spec->catfile( $OPT{'model_dir'}, $_ ) }
648 0 grep { /\Aoiforest-.*\.json\z/ } readdir($dh);
649 0 closedir $dh;
650 0 ▶ while ( scalar @models > $OPT{'keep'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @models > $OPT{"keep"}) 0 0 0
651 0 my $old = shift @models;
652 0 ▶ unlink $old and _log( 'pruned ' . $old );
Branch: 1 branch
BranchTrueFalseTotal
unlink $old and _log('pruned ' . $old) 0 0 0
653 }
654 0 return 1;
655 } ## end sub _prune_models
656  
657 #-------------------------------------------------------------------------------
658 # connection handling
659 #-------------------------------------------------------------------------------
660  
661 # Close one client connection and forget everything about it. The single
662 # teardown path, so a connection can never be left in a selector after its
663 # socket is gone.
664 #
665 # Args:
666 # $s :: the client socket.
667 # $rsel :: the read IO::Select set it may be registered in.
668 # $wsel :: the write IO::Select set it may be registered in.
669 #
670 # Returns: 1. Callers return its value directly, which is why the read
671 # and write loops read as "return _drop(...)".
672 #
673 # Example:
674 # return _drop( $s, $rsel, $wsel ) if $got == 0; # client closed
675 23 ▶sub _drop {
Subroutine _drop: called CC=1 SCAR=0.0
676 23 my ( $s, $rsel, $wsel ) = @_;
677 23 $rsel->remove($s);
678 23 $wsel->remove($s);
679 23 delete $CONN{ fileno($s) };
680 23 close $s;
681 23 return 1;
682 }
683  
684 # Read whatever is available from one client, dispatch every complete
685 # line in it, and push the replies back out. Partial lines stay in the
686 # connection's input buffer for the next readable event, which is what
687 # lets one non-blocking loop serve many clients.
688 #
689 # A client that sends an unterminated line past MAX_INBUF, or backs up
690 # past MAX_OUTBUF of unread replies, is dropped: neither is recoverable,
691 # and both would otherwise let one client exhaust the daemon's memory.
692 #
693 # Args:
694 # $s :: the readable client socket.
695 # $rsel :: the read IO::Select set.
696 # $wsel :: the write IO::Select set, which gains $s when a reply cannot
697 # be written in full.
698 #
699 # Returns: 1 after servicing the client, or the result of _drop when the
700 # connection ended or misbehaved. An empty return on EAGAIN/EINTR, or for
701 # a socket with no connection record, leaves the client untouched.
702 #
703 # Example:
704 # _read_from( $_, $rsel, $wsel ) for $rsel->can_read($timeout);
705 79 ▶sub _read_from {
Subroutine _read_from: called CC=13 SCAR=33.3
706 79 my ( $s, $rsel, $wsel ) = @_;
707 79 ▶ my $c = $CONN{ fileno($s) } or return;
Branch: 1 branch
BranchTrueFalseTotal
my $c = $CONN{fileno $s} or return 79 0 79
708  
709 79 my $got = sysread( $s, my $chunk, 65536 );
710 79 ▶ if ( !defined $got ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $got) 0 79 79
711 0 ▶ return if $!{EAGAIN} || $!{EWOULDBLOCK} || $!{EINTR};
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EAGAIN"} or $!{"EWOULDBLOCK"} or $!{"EINTR"} 0 0 0
Condition0%0/6
$!{"EAGAIN"} or $!{"EWOULDBLOCK"} or $!{"EINTR"}
l!l&&r!l&&!r
000
$!{"EAGAIN"} or $!{"EWOULDBLOCK"}
l!l&&r!l&&!r
000
MC/DC0%0/3
$!{"EAGAIN"} or $!{"EWOULDBLOCK"} or $!{"EINTR"}
$!{"EAGAIN"} $!{"EWOULDBLOCK"} $!{"EINTR"}
Truth table0%0/4
A or B or C
A= $!{"EAGAIN"}B= $!{"EWOULDBLOCK"}C= $!{"EINTR"}
ABCresult
1XX1
01X1
0011
0000
712 0 return _drop( $s, $rsel, $wsel );
713 }
714 79 ▶ return _drop( $s, $rsel, $wsel ) if $got == 0; # client closed
Branch: 1 branch
BranchTrueFalseTotal
if $got == 0 23 56 79
715  
716 56 $c->{inbuf} .= $chunk;
717 56 ▶ if ( length( $c->{inbuf} ) > MAX_INBUF && $c->{inbuf} !~ /\n/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $c->{"inbuf"} > 16777216 and not $c->{"inbuf"} =~ /\n/) 0 56 56
Condition33%1/3
length $c->{"inbuf"} > 16777216 and not $c->{"inbuf"} =~ /\n/
!ll&&!rl&&r
5600
MC/DC0%0/2
length $c->{"inbuf"} > 16777216 and not $c->{"inbuf"} =~ /\n/
length $c->{"inbuf"} > 16777216 not $c->{"inbuf"} =~ /\n/
Truth table33%1/3
A and not(B)
A= length $c->{"inbuf"} > 16777216B= not $c->{"inbuf"} =~ /\n/
ABresult
0X0
100
111
718 0 _log( 'dropping client: unterminated line exceeded ' . MAX_INBUF . ' bytes' );
719 0 return _drop( $s, $rsel, $wsel );
720 }
721  
722 56 ▶ while ( $c->{inbuf} =~ s/\A([^\n]*)\n// ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"inbuf"} =~ s/\A([^\n]*)\n//) 56 56 112
723 56 my $line = $1;
724 56 ▶ next if $line =~ /\A\s*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /\A\s*\z/ 0 56 56
725 56 _handle_line( $c, $line );
726 56 ▶ return _drop( $s, $rsel, $wsel ) if length( $c->{outbuf} ) > MAX_OUTBUF;
Branch: 1 branch
BranchTrueFalseTotal
if length $c->{"outbuf"} > 16777216 0 56 56
727 }
728 56 ▶ _flush( $s, $rsel, $wsel ) if length $c->{outbuf};
Branch: 1 branch
BranchTrueFalseTotal
if length $c->{"outbuf"} 56 0 56
729 56 return 1;
730 } ## end sub _read_from
731  
732 # Push as much of a connection's pending output as the socket will take.
733 # A client that cannot keep up leaves the remainder buffered and the
734 # socket registered for write-readiness, so the daemon never blocks on a
735 # slow reader.
736 #
737 # Args:
738 # $s :: the client socket.
739 # $rsel :: the read IO::Select set, needed only to hand to _drop.
740 # $wsel :: the write IO::Select set. $s is added while output remains
741 # and removed once it has all gone out.
742 #
743 # Returns: 1 when the buffer drained completely, the result of _drop on a
744 # write error, or an empty return when the socket would block with output
745 # still pending.
746 #
747 # Example:
748 # _flush( $s, $rsel, $wsel ) if length $c->{outbuf};
749 56 ▶sub _flush {
Subroutine _flush: called CC=9 SCAR=31.7
750 56 my ( $s, $rsel, $wsel ) = @_;
751 56 ▶ my $c = $CONN{ fileno($s) } or return;
Branch: 1 branch
BranchTrueFalseTotal
my $c = $CONN{fileno $s} or return 56 0 56
752 56 ▶ while ( length $c->{outbuf} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $c->{"outbuf"}) 56 56 112
753 56 my $wrote = syswrite( $s, $c->{outbuf} );
754 56 ▶ if ( !defined $wrote ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $wrote) 0 56 56
755 0 ▶ if ( $!{EAGAIN} || $!{EWOULDBLOCK} || $!{EINTR} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($!{"EAGAIN"} or $!{"EWOULDBLOCK"} or $!{"EINTR"}) 0 0 0
Condition0%0/6
$!{"EAGAIN"} or $!{"EWOULDBLOCK"} or $!{"EINTR"}
l!l&&r!l&&!r
000
$!{"EAGAIN"} or $!{"EWOULDBLOCK"}
l!l&&r!l&&!r
000
MC/DC0%0/3
$!{"EAGAIN"} or $!{"EWOULDBLOCK"} or $!{"EINTR"}
$!{"EAGAIN"} $!{"EWOULDBLOCK"} $!{"EINTR"}
Truth table0%0/4
A or B or C
A= $!{"EAGAIN"}B= $!{"EWOULDBLOCK"}C= $!{"EINTR"}
ABCresult
1XX1
01X1
0011
0000
756 0 ▶ $wsel->add($s) unless $wsel->exists($s);
Branch: 1 branch
BranchTrueFalseTotal
unless $wsel->exists($s) 0 0 0
757 0 return;
758 }
759 0 return _drop( $s, $rsel, $wsel );
760 }
761 56 substr( $c->{outbuf}, 0, $wrote, '' );
762 } ## end while ( length $c->{outbuf} )
763 56 ▶ $wsel->remove($s) if $wsel->exists($s);
Branch: 1 branch
BranchTrueFalseTotal
if $wsel->exists($s) 0 56 56
764 56 return 1;
765 } ## end sub _flush
766  
767 #-------------------------------------------------------------------------------
768 # protocol
769 #-------------------------------------------------------------------------------
770  
771 # One request line -> one reply line, appended to the connection's
772 # output buffer. Any croak from the model becomes an {"error": ...}
773 # reply on this message alone; the connection and daemon live on.
774 #
775 # Args:
776 # $c :: the connection record hashref, holding inbuf, outbuf and the
777 # connection's default mode.
778 # $line :: one request line, without its newline. Must be a JSON object
779 # carrying exactly one of row, rows or cmd, optionally with mode
780 # and tag.
781 #
782 # Returns: whatever _reply returns (1). Every path replies, including
783 # every error path, so a client is never left waiting. A "tag" in the
784 # request is echoed on the reply, errors included.
785 #
786 # Example:
787 # _handle_line( $c, '{"row":[0.2,0.7],"tag":"req-1"}' );
788 # # queues {"score":0.41,"label":0,"tag":"req-1"}
789 56 ▶sub _handle_line {
Subroutine _handle_line: called CC=21 SCAR=30.8
790 56 my ( $c, $line ) = @_;
791  
792 56 my $msg = eval { $JSON->decode($line) };
793 56 ▶ if ( $@ || ref $msg ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or ref $msg ne "HASH") 1 55 56
Condition66%2/3
$@ or ref $msg ne "HASH"
l!l&&r!l&&!r
1055
MC/DC50%1/2
$@ or ref $msg ne "HASH"
$@ ref $msg ne "HASH"
Truth table66%2/3
A or B
A= $@B= ref $msg ne "HASH"
ABresult
1X1
011
000
794 1 ( my $err = $@ ) =~ s/ at \S+ line \d+\.?\s*\z//s;
795 1 ▶ return _reply( $c, { error => 'request is not a JSON object: ' . ( $err || 'wrong type' ) } );
Condition50%1/2
$err || 'wrong type'
l!l
10
MC/DC0%0/1
$err || 'wrong type'
$err
Truth table50%1/2
A
A= $err
Aresult
11
00
796 }
797  
798 55 ▶ my @tag = exists $msg->{tag} ? ( tag => $msg->{tag} ) : ();
Branch: 1 branch
BranchTrueFalseTotal
exists $msg->{'tag'} ? : 18 37 55
799  
800 55 my @kinds = grep { exists $msg->{$_} } qw(row rows cmd);
801 55 ▶ if ( scalar @kinds != 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @kinds != 1) 1 54 55
802 1 return _reply( $c, { error => q{request needs exactly one of "row", "rows", or "cmd"}, @tag } );
803 }
804 54 my $kind = $kinds[0];
805  
806 54 ▶ my $mode = exists $msg->{mode} ? $msg->{mode} : $c->{mode};
Branch: 1 branch
BranchTrueFalseTotal
exists $msg->{'mode'} ? : 21 33 54
807 54 ▶ if ( !defined $mode || ref $mode || $mode !~ /\A(?:prequential|learn|score)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $mode or ref $mode or not $mode =~ /\A(?:prequential|learn|score)\z/) 1 53 54
Condition50%3/6
not defined $mode or ref $mode or not $mode =~ /\A(?:prequential|learn|score)\z/
l!l&&r!l&&!r
0153
not defined $mode or ref $mode
l!l&&r!l&&!r
0054
MC/DC33%1/3
not defined $mode or ref $mode or not $mode =~ /\A(?:prequential|learn|score)\z/
not defined $mode ref $mode not $mode =~ /\A(?:prequential|learn|score)\z/
Truth table50%2/4
not(A) or B or not(C)
A= not defined $modeB= ref $modeC= not $mode =~ /\A(?:prequential|learn|score)\z/
ABCresult
1XX1
01X1
0011
0000
808 1 return _reply( $c, { error => q{mode must be "prequential", "learn", or "score"}, @tag } );
809 }
810  
811 53 ▶ if ( $kind eq 'cmd' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "cmd") 26 27 53
812 26 return _handle_cmd( $c, $msg, \@tag );
813 }
814  
815 27 ▶ my $rows = $kind eq 'row' ? [ $msg->{row} ] : $msg->{rows};
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'row' ? : 11 16 27
816 27 ▶ if ( ref $rows ne 'ARRAY' || !@$rows ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rows ne "ARRAY" or not @$rows) 0 27 27
Condition33%1/3
ref $rows ne "ARRAY" or not @$rows
l!l&&r!l&&!r
0027
MC/DC0%0/2
ref $rows ne "ARRAY" or not @$rows
ref $rows ne "ARRAY" not @$rows
Truth table33%1/3
A or not(B)
A= ref $rows ne "ARRAY"B= not @$rows
ABresult
1X1
011
000
817 0 return _reply( $c, { error => q{"rows" must be a non-empty JSON array of rows}, @tag } );
818 }
819  
820 27 my @scored;
821 27 my $i = 0;
822 27 for my $row (@$rows) {
823 257 my $score = eval { _apply_row( $row, $mode ) };
824 257 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 4 253 257
825 4 ( my $err = $@ ) =~ s/ at \S+ line \d+\.?\s*\z//s;
826 4 chomp $err;
827 4 ▶ my $where = $kind eq 'row' ? '' : 'row ' . $i . ': ';
Branch: 1 branch
BranchTrueFalseTotal
$kind eq 'row' ? : 3 1 4
828 4 return _reply( $c, { error => $where . $err, @tag } );
829 }
830 253 ▶ push @scored, $score if defined $score;
Branch: 1 branch
BranchTrueFalseTotal
if defined $score 37 216 253
831 253 $i++;
832 } ## end for my $row (@$rows)
833  
834 23 ▶ if ( $mode eq 'learn' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "learn") 6 17 23
835 6 return _reply( $c, { ok => { learned => scalar @$rows }, @tag } );
836 }
837  
838 17 my $threshold = _threshold();
839 17 ▶ my @pairs = map { [ 0 + $_, ( $_ >= $threshold ? 1 : 0 ) ] } @scored;
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $threshold ? : 0 36 36
840 17 ▶ if ( $kind eq 'row' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "row") 7 10 17
841 7 return _reply( $c, { score => $pairs[0][0], label => $pairs[0][1], @tag } );
842 }
843 10 return _reply( $c, { scores => \@pairs, @tag } );
844 } ## end sub _handle_line
845  
846 # The control half of the protocol: everything that inspects or steers
847 # the daemon rather than feeding it data. Split out of _handle_line so
848 # the data path stays readable.
849 #
850 # Recognised commands:
851 # - ping :: liveness check, replies "pong".
852 # - mode :: set this connection's default mode for later messages.
853 # - stats :: counters, window fill, effective threshold, connection
854 # count and the instance's --set name.
855 # - save :: save the model now, replying with the file name written.
856 # - relearn-threshold :: recompute the contamination cutoff from the
857 # current window, replying with the new value.
858 #
859 # Args:
860 # $c :: the connection record hashref. The mode command mutates its
861 # default mode.
862 # $msg :: the decoded request hashref.
863 # $tag :: arrayref of the (tag => value) pair to echo, or empty when the
864 # request carried no tag. Flattened into every reply.
865 #
866 # Returns: whatever _reply returns (1). An unknown command gets an error
867 # reply naming it rather than closing the connection.
868 #
869 # Example:
870 # _handle_cmd( $c, { cmd => 'stats' }, [] );
871 # # queues {"ok":{"seen":48210,"window":2048,...}}
872 26 ▶sub _handle_cmd {
Subroutine _handle_cmd: called CC=15 SCAR=29.1
873 26 my ( $c, $msg, $tag ) = @_;
874 26 my $cmd = $msg->{cmd};
875 26 ▶ $cmd = '' if !defined $cmd || ref $cmd;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $cmd or ref $cmd 0 26 26
Condition33%1/3
not defined $cmd or ref $cmd
l!l&&r!l&&!r
0026
MC/DC0%0/2
not defined $cmd or ref $cmd
not defined $cmd ref $cmd
Truth table33%1/3
not(A) or B
A= not defined $cmdB= ref $cmd
ABresult
1X1
011
000
876  
877 26 ▶ if ( $cmd eq 'ping' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "ping") 8 18 26
878 8 return _reply( $c, { ok => 'pong', @$tag } );
879 }
880 18 ▶ if ( $cmd eq 'mode' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "mode") 1 17 18
881 1 my $mode = $msg->{mode};
882 1 ▶ if ( !defined $mode || ref $mode || $mode !~ /\A(?:prequential|learn|score)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $mode or ref $mode or not $mode =~ /\A(?:prequential|learn|score)\z/) 0 1 1
Condition33%2/6
not defined $mode or ref $mode or not $mode =~ /\A(?:prequential|learn|score)\z/
l!l&&r!l&&!r
001
not defined $mode or ref $mode
l!l&&r!l&&!r
001
MC/DC0%0/3
not defined $mode or ref $mode or not $mode =~ /\A(?:prequential|learn|score)\z/
not defined $mode ref $mode not $mode =~ /\A(?:prequential|learn|score)\z/
Truth table25%1/4
not(A) or B or not(C)
A= not defined $modeB= ref $modeC= not $mode =~ /\A(?:prequential|learn|score)\z/
ABCresult
1XX1
01X1
0011
0000
883 0 return _reply( $c, { error => q{mode must be "prequential", "learn", or "score"}, @$tag } );
884 }
885 1 $c->{mode} = $mode;
886 1 return _reply( $c, { ok => { mode => $mode }, @$tag } );
887 }
888 17 ▶ if ( $cmd eq 'stats' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "stats") 12 5 17
889 return _reply(
890 $c,
891 {
892 ok => {
893 seen => 0 + $OIF->seen,
894 window => 0 + $OIF->window_count,
895 n_features => ( defined $OIF->{n_features} ? 0 + $OIF->{n_features} : undef ),
896 threshold => 0 + _threshold(),
897 connections => 0 + scalar( keys %CONN ),
898 dirty => ( $DIRTY ? 1 : 0 ),
899 12 ▶ set => $OPT{'set'},
Branch: 2 branches
BranchTrueFalseTotal
defined $OIF->{'n_features'} ? : 11 1 12
$DIRTY ? : 9 3 12
900 },
901 @$tag
902 }
903 );
904 } ## end if ( $cmd eq 'stats' )
905 5 ▶ if ( $cmd eq 'save' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "save") 3 2 5
906 3 my $name = eval { _save_model('command') };
907 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3 3
908 0 ( my $err = $@ ) =~ s/ at \S+ line \d+\.?\s*\z//s;
909 0 return _reply( $c, { error => $err, @$tag } );
910 }
911 3 return _reply( $c, { ok => { saved => $name }, @$tag } );
912 }
913 2 ▶ if ( $cmd eq 'relearn-threshold' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "relearn-threshold") 1 1 2
914 0 my $ok = eval { $OIF->relearn_threshold; 1 };
915 1 ▶ if ( !$ok ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 1 0 1
916 1 ( my $err = $@ ) =~ s/ at \S+ line \d+\.?\s*\z//s;
917 1 chomp $err;
918 1 return _reply( $c, { error => $err, @$tag } );
919 }
920 0 return _reply( $c, { ok => { threshold => 0 + $OIF->decision_threshold }, @$tag } );
921 }
922 1 return _reply( $c, { error => 'unknown cmd "' . $cmd . '"', @$tag } );
923 } ## end sub _handle_cmd
924  
925 # Queue one reply on a connection. Encoding and the trailing newline
926 # live here alone, so every reply the daemon emits is one JSON document
927 # per line no matter which handler produced it.
928 #
929 # Args:
930 # $c :: the connection record hashref. Its outbuf grows.
931 # $reply :: the reply as a hashref, ready to encode.
932 #
933 # Returns: 1. The bytes are not written here -- _read_from's _flush call
934 # does that once the current batch of lines has been handled.
935 #
936 # Example:
937 # _reply( $c, { ok => 'pong' } );
938 56 ▶sub _reply {
Subroutine _reply: called CC=1 SCAR=0.0
939 56 my ( $c, $reply ) = @_;
940 56 $c->{outbuf} .= $JSON->encode($reply) . "\n";
941 56 return 1;
942 }
943  
944 # The effective label cutoff, resolved per message so relearns and the
945 # contamination refresh at save time take effect immediately.
946 #
947 # Args: none. Reads $OPT{'threshold'} and the model's own learned cutoff.
948 #
949 # Returns: the cutoff as a float -- --threshold when given, else the
950 # model's contamination-learned decision_threshold, else 0.5.
951 #
952 # Example:
953 # my $label = $score >= _threshold() ? 1 : 0;
954 29 ▶sub _threshold {
Subroutine _threshold: called CC=3 SCAR=12.7
955 return
956 29 ▶ defined $OPT{'threshold'} ? $OPT{'threshold'}
Branch: 2 branches
BranchTrueFalseTotal
defined $OPT{'threshold'} ? : 0 29 29
defined $OIF->decision_threshold ? : 0 29 29
957 : defined $OIF->decision_threshold ? $OIF->decision_threshold
958 : 0.5;
959 }
960  
961 # One row through the model. A JSON object is a tagged row (full munger
962 # plan, expanding/combining mungers included); a JSON array is positional
963 # (scalar mungers, like stream CSV input). Either way the final vector
964 # is validated numeric before it touches the model -- JSON delivers
965 # typed values, so anything non-numeric left after munging is a caller
966 # bug worth an explicit error rather than Perl's silent string-to-0.
967 #
968 # Args:
969 # $row :: one row, either a hashref of tagged raw values or an arrayref
970 # of positional ones. undef cells are left alone and defer to
971 # the model's missing policy.
972 # $mode :: 'learn', 'score' or 'prequential' -- learn only, score
973 # without learning, or score then learn.
974 #
975 # Returns: the anomaly score as a float, or undef in learn mode. Sets the
976 # dirty flag whenever the model actually learned, which is what makes the
977 # interval save skip a quiet period. Dies on a row that is neither shape,
978 # on a cell left non-numeric after munging, or on anything the model
979 # itself croaks about.
980 #
981 # Example:
982 # _apply_row( { method => 'GET', host => 'h' }, 'prequential' ); # 0.41
983 # _apply_row( [ 0.2, 0.7 ], 'learn' ); # undef
984 257 ▶sub _apply_row {
Subroutine _apply_row: called CC=10 SCAR=23.9
985 257 my ( $row, $mode ) = @_;
986  
987 257 my $vec;
988 257 ▶ if ( ref $row eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $row eq 'HASH') { } 67 190 257
elsif (ref $row eq 'ARRAY') { } 190 0 190
989 67 $vec = $OIF->tagged_row_to_array( $row, 'streamd' );
990 } elsif ( ref $row eq 'ARRAY' ) {
991 190 $vec = $row;
992 0 ▶ if ( ref $OIF->{mungers} eq 'HASH' && %{ $OIF->{mungers} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $OIF->{"mungers"} eq "HASH" and %{$OIF->{"mungers"};}) 0 190 190
Condition33%1/3
ref $OIF->{"mungers"} eq "HASH" and %{$OIF->{"mungers"};}
!ll&&!rl&&r
19000
MC/DC0%0/2
ref $OIF->{"mungers"} eq "HASH" and %{$OIF->{"mungers"};}
ref $OIF->{"mungers"} eq "HASH" %{$OIF->{"mungers"};}
Truth table33%1/3
A and B
A= ref $OIF->{"mungers"} eq "HASH"B= %{$OIF->{"mungers"};}
ABresult
0X0
100
111
993 0 $vec = $OIF->munge_rows( [$row] )->[0];
994 }
995 } else {
996 0 die 'row must be a JSON array (positional) or object (tagged)' . "\n";
997 }
998  
999 255 for my $col ( 0 .. $#$vec ) {
1000 511 ▶ next if !defined $vec->[$col]; # undef defers to the model's missing policy
Branch: 1 branch
BranchTrueFalseTotal
unless defined $vec->[$col] 0 511 511
1001 511 ▶ die 'column ' . ( $col + 1 ) . ' is not a number after munging' . "\n"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($vec->[$col]) 1 510 511
1002 unless looks_like_number( $vec->[$col] );
1003 }
1004  
1005 254 ▶ if ( $mode eq 'learn' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "learn") 216 38 254
1006 216 $OIF->learn( [$vec] );
1007 216 $DIRTY = 1;
1008 216 return undef;
1009 }
1010 38 ▶ if ( $mode eq 'score' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "score") 28 10 38
1011 28 return $OIF->score_samples( [$vec] )->[0];
1012 }
1013 10 my $score = $OIF->score_learn( [$vec] )->[0];
1014 9 $DIRTY = 1;
1015 9 return $score;
1016 } ## end sub _apply_row
1017  
1018 =head1 NAME
1019  
1020 Algorithm::Classifier::IsolationForest::App::Command::streamd - Run an Online Isolation Forest scoring daemon on a Unix socket, speaking JSON lines
1021  
1022 =head1 DESCRIPTION
1023  
1024 Wraps the prequential loop of C<iforest stream> in a daemon: it listens
1025 on a Unix domain socket, serves many concurrent connections from one
1026 shared model, and exchanges one JSON document per line. Because values
1027 travel as JSON rather than positionally, raw input headed for mungers may
1028 safely contain commas, newlines or any unicode, and object rows run the
1029 full munger plan -- expanding and combining mungers included, which
1030 positional CSV cannot express.
1031  
1032 An optional C<"tag"> on a request is echoed back verbatim. Errors are
1033 always per-message: a bad row gets an C<{"error": ...}> reply and the
1034 connection lives on.
1035  
1036 Models are saved to C<--model-dir> as timestamped files every
1037 C<--save-interval> seconds when learning has happened, plus on the C<save>
1038 command, on SIGUSR1, and at shutdown. The C<latest.json> symlink is
1039 repointed atomically at each save and resumed from at the next startup, so
1040 a crash loses at most one interval of learning.
1041  
1042 Several named instances can run side by side: C<--set> gives each its own
1043 socket, pid file, model subdirectory and resume state.
1044  
1045 C<iforest streamc> is the matching client.
1046  
1047 Run it as C<iforest streamd>; C<iforest help streamd> lists every option.
1048  
1049 =head1 METHODS
1050  
1051 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
1052 should.
1053  
1054 =head2 opt_spec
1055  
1056 Returns this command's option specifications, as the list of arrayrefs
1057 L<Getopt::Long::Descriptive> expects.
1058  
1059 =head2 abstract
1060  
1061 Returns the one-line summary C<iforest commands> prints beside the
1062 command name.
1063  
1064 =head2 description
1065  
1066 Returns the long help text C<iforest help streamd> prints under the option
1067 list.
1068  
1069 =head2 validate
1070  
1071 Checks the parsed options before anything is read or written, so a
1072 mistake costs nothing.
1073  
1074 Checks that C<--set> is a usable instance name, that C<--save-interval>,
1075 C<--keep>, C<--threshold>, C<--growth> and C<--socket-mode> hold sane
1076 values, and that a C<--mungers> spec is readable and accompanied by the
1077 feature tags (C<-t>) it compiles against.
1078  
1079 Takes the parsed options hashref and the arrayref of remaining
1080 arguments. Calls C<usage_error>, which prints the usage and exits, on
1081 the first problem it finds, and returns 1 when everything checks out.
1082  
1083 =head2 execute
1084  
1085 Prepares the runtime and model directories, daemonizes unless C<-f> was
1086 given, and runs the accept/serve loop until it is asked to stop.
1087  
1088 Takes the parsed options hashref and the arrayref of remaining
1089 arguments, and returns 1.
1090  
1091 =cut
1092  
1093 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/stream.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/fit.pm »