Algorithm-Classifier-IsolationForest
view release on metacpan or search on metacpan
lib/Algorithm/Classifier/IsolationForest/App/Command/streamd.pm view on Meta::CPAN
package Algorithm::Classifier::IsolationForest::App::Command::streamd;
use strict;
use warnings;
use Algorithm::Classifier::IsolationForest ();
use Algorithm::Classifier::IsolationForest::Online ();
use Algorithm::Classifier::IsolationForest::App -command;
use File::Slurp qw(read_file write_file);
use File::Path qw(make_path);
use File::Basename qw(dirname);
use File::Spec ();
use Scalar::Util qw(looks_like_number);
use IO::Socket::UNIX ();
use IO::Select ();
use POSIX qw(setsid strftime);
use Errno qw();
# The daemon is a singleton per process, so its runtime state lives in
# file-scoped lexicals rather than being threaded through every helper.
my $JSON; # JSON::MaybeXS codec (required at runtime, see execute)
my $OIF; # the online model
my %OPT; # resolved options
my $LOG_FH; # log handle (STDERR in foreground without --log)
my %CONN; # fileno => { sock, inbuf, outbuf, mode }
my $DIRTY = 0; # learned anything since the last save?
my $RUN; # cleared by SIGTERM/SIGINT
my $SAVE_NOW; # set by SIGUSR1
my $REOPEN_LOG; # set by SIGHUP
# Sanity caps on per-connection buffers: a client is allowed big batch
# messages, but one that streams an endless line (or stops reading its
# replies) gets dropped instead of eating the daemon's memory.
use constant MAX_INBUF => 16 * 1024 * 1024;
use constant MAX_OUTBUF => 16 * 1024 * 1024;
sub opt_spec {
return (
[
'set=s',
'Named instance. Appended to --model-dir, and the socket/pid become <set>.sock / <set>.pid '
. 'under the run dir, so several daemons run side by side with no other flags. '
. 'Must match /\A[A-Za-z0-9+\-@_]+\z/.'
],
[
'socket=s',
'Unix domain socket to listen on; default /var/run/iforest_streamd/streamd.sock. With --set '
. 'this is instead the base run dir (default /var/run/iforest_streamd) the <set>.sock is created in.',
{ 'completion' => 'files' }
],
[
'pid=s',
'Where to write the daemon pid; default /var/run/iforest_streamd/streamd.pid. With --set '
. 'this is instead the base run dir (default /var/run/iforest_streamd) the <set>.pid is created in.',
{ 'completion' => 'files' }
],
[
'model-dir=s',
'Directory timestamped model saves land in; the symlink latest.json in it always points '
. 'at the newest, and the daemon resumes from it at startup when it exists. With --set '
. 'the set name is appended as a subdirectory.',
{ 'default' => '/var/db/iforest_streamd', 'completion' => 'files' }
],
[
'save-interval=i',
'Seconds between periodic model saves (only when learning happened).',
{ 'default' => 300 }
],
[ 'keep=i', 'Prune all but the newest N timestamped model files after each save.' ],
[ 'f|foreground', 'Do not daemonize; log to stderr unless --log is given.' ],
[
'log=s',
'Log file. Defaults to <model-dir>/streamd.log when daemonized; stderr in the foreground.',
{ 'completion' => 'files' }
],
[ 'socket-mode=s', 'Octal permissions to chmod the socket file to (e.g. 0660).' ],
[ 'threshold=f', 'Alternative decision threshold to use for the label field. 0 < $val < 1' ],
# creation knobs, used only when <model-dir>/latest.json does not exist yet
lib/Algorithm/Classifier/IsolationForest/App/Command/streamd.pm view on Meta::CPAN
At startup the daemon resumes from <model-dir>/latest.json when it
exists; otherwise it creates a new model from the creation knobs (-n,
--window, --eta, --growth, --subsample, -s, -c, -t, --mungers,
--prototype -- the same set `iforest stream` takes). The model is saved
to a timestamped file in --model-dir every --save-interval seconds
(only when something was learned), on SIGUSR1, on the save command, and
at shutdown; the symlink latest.json is atomically repointed at every
save, so a restart resumes the stream losing at most one interval.
Requests are JSON objects carrying exactly one of "row", "rows", or
"cmd", an optional "mode", and an optional "tag" (any JSON value,
echoed back verbatim in the reply -- a correlation tag, not to be
confused with feature tags):
{"row": [0.1, 0.7]} -> {"score": 0.41, "label": 0}
{"row": {"cpu": 0.1, "mem": 0.7}} -> {"score": 0.41, "label": 0}
{"rows": [[...], {...}], "tag": "b7"} -> {"scores": [[0.41,0], ...], "tag": "b7"}
{"rows": [[...]], "mode": "learn"} -> {"ok": {"learned": 1}}
{"cmd": "mode", "mode": "score"} -> {"ok": {"mode": "score"}}
{"cmd": "ping"} -> {"ok": "pong"}
{"cmd": "stats"} -> {"ok": {"seen": ..., ...}}
{"cmd": "save"} -> {"ok": {"saved": "oiforest-....json"}}
{"cmd": "relearn-threshold"} -> {"ok": {"threshold": 0.61}}
anything invalid -> {"error": "...", "tag": ...}
The array row form is positional (scalar mungers applied, like stream
CSV input); the object form is a tagged row and runs the full munger
plan, including expanding and combining mungers -- and, being JSON, the
raw values may safely contain commas, newlines, or any unicode.
A worked tagged example. Create the daemon around raw HTTP request
data, with mungers turning the raw values into numbers (mungers.json
here; a --prototype carrying the same schema works identically):
{ "method": { "munger": "http_method_enum", "default": -1 },
"path_len": { "munger": "length", "from": "path" },
"host_entropy": { "munger": "entropy", "from": "host" } }
iforest streamd --set web -t method -t path_len -t host_entropy \
--mungers mungers.json -c 0.05
Clients then send the raw values themselves -- note the input fields
are the munger SOURCES (method, path, host), not the feature tags,
because the plan derives path_len and host_entropy from them:
-> {"row": {"method": "GET", "path": "/index.html",
"host": "www.example.com"}, "tag": "r-1"}
<- {"score": 0.31, "label": 0, "tag": "r-1"}
-> {"row": {"method": "BREW", "path": "/aa,a\"a.php",
"host": "kq3xv9z2.biz"}, "tag": "r-2"}
<- {"score": 0.74, "label": 1, "tag": "r-2"}
The same rows work from the shell via
`iforest streamc --set web --jsonl -i rows.jsonl`.
Modes are prequential (score each row against the model as it stood, then
learn it -- the default), learn (learn only), and score (score only);
"mode" on a row/rows message overrides the connection default set by
the mode command for that message. A bad row gets an {"error": ...}
reply on that message only; the connection and the daemon live on (for
a "rows" batch, rows before the failing one were already processed).
Multiple concurrent connections are supported; rows are applied to the
one shared model in the order their lines arrive, which defines the
stream order.
--set NAME runs a named instance: the set name is appended to
--model-dir (so its saves, latest.json, and default log live under
their own subdirectory) and the socket/pid become <set>.sock /
<set>.pid under the run dir -- with --set, --socket and --pid name the
base run dir instead of the files. Several sets run side by side, each
with its own model, resume state, and double-start protection:
iforest streamd --set web
iforest streamd --set dns --prototype dns-proto.json -c 0.02
Set names must match /\A[A-Za-z0-9+\-@_]+\z/; since the class has no
"." or "/", a set name can only ever create one new path segment.
Everything under --model-dir and the socket/pid directories is created
at startup when missing; when that fails (e.g. running unprivileged
with the /var defaults) the daemon dies immediately, before forking,
naming the directory and the flag to override.
';
} ## end sub description
sub validate {
my ( $self, $opt, $args ) = @_;
# Anchored with \A/\z rather than ^/$ ($ tolerates a trailing newline).
# The class has no '.' or '/', so a set name can only ever create one
# new path segment -- no traversal is expressible.
if ( defined( $opt->{'set'} ) && $opt->{'set'} !~ /\A[A-Za-z0-9+\-@_]+\z/ ) {
$self->usage_error( '--set, "'
. $opt->{'set'}
. '", must match /\A[A-Za-z0-9+\-@_]+\z/ (letters, digits, and + - @ _ only)' );
}
if ( $opt->{'save_interval'} < 1 ) {
$self->usage_error( '--save-interval, "' . $opt->{'save_interval'} . '", must be >= 1 second' );
}
if ( defined( $opt->{'keep'} ) && $opt->{'keep'} < 1 ) {
$self->usage_error( '--keep, "' . $opt->{'keep'} . '", must be >= 1' );
}
if ( defined( $opt->{'threshold'} ) && ( $opt->{'threshold'} <= 0 || $opt->{'threshold'} >= 1 ) ) {
$self->usage_error( '--threshold, "' . $opt->{'threshold'} . '", needs to be greater than 0 and less than 1' );
}
if ( defined( $opt->{'growth'} ) && $opt->{'growth'} !~ /\A(?:adaptive|fixed)\z/ ) {
$self->usage_error( '--growth, "' . $opt->{'growth'} . '", must be either adaptive or fixed' );
}
if ( defined( $opt->{'socket_mode'} ) && $opt->{'socket_mode'} !~ /\A0?[0-7]{3}\z/ ) {
$self->usage_error( '--socket-mode, "' . $opt->{'socket_mode'} . '", must be octal like 0660' );
}
if ( defined( $opt->{'mungers'} ) ) {
if ( !-f $opt->{'mungers'} ) {
$self->usage_error( '--mungers, "' . $opt->{'mungers'} . '", is not a file or does not exist' );
( run in 0.965 second using v1.01-cache-2.11-cpan-995e09ba956 )