script/file-to-elasticsearch.pl untested

filter: Statementstmt 0.0% 0 / 231 Branchbran 0.0% 0 / 106 Conditioncond 0.0% 0 / 71 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 437 CC 51 SCAR 70.5
CC
51
Cov
0%
got_new_line
1892.0
main_start
42.0
got_error
12.0
CRAP 1150.6
1 #!/usr/local/bin/perl
2 # PODNAME: file-to-elasticsearch.pl
3 # ABSTRACT: A simple utility to tail a file and index each line as a document in ElasticSearch
4 use strict;
5 use warnings;
6  
7 use Getopt::Long::Descriptive qw(describe_options);
8 use Hash::Merge::Simple qw(merge);
9 use JSON::MaybeXS qw(decode_json encode_json);
10 use Log::Log4perl qw(:easy);
11 use Module::Load qw(load);
12 use Module::Loaded qw(is_loaded);
13 use Pod::Usage;
14 use Ref::Util qw(is_arrayref is_hashref);
15 use YAML ();
16  
17 sub POE::Kernel::ASSERT_DEFAULT { 1 }
18 use POE qw(
19 Component::ElasticSearch::Indexer
20 Wheel::FollowTail
21 );
22  
23 my %DEFAULT = (
24 config => '/etc/file-to-elasticsearch.yaml',
25 stats_interval => 60,
26 );
27  
28 my ($opt,$usage) = describe_options('%c %o',
29 ['config|c=s', "Config file, default: $DEFAULT{config}",
30 { default => $DEFAULT{config}, callbacks => { "must be a readable file" => sub { -r $_[0] } } }
31 ],
32 ['log4perl-config|L=s', "Log4perl Configuration to use, defaults to STDERR",
33 { callbacks => { "must be a readable file" => sub { -r $_[0] } } }
34 ],
35 ['stats-interval|s=i', "Seconds between displaying statistics, default: $DEFAULT{stats_interval}",
36 { default => $DEFAULT{stats_interval} },
37 ],
38 ['debug', "Enable most verbose output" ],
39 [],
40 ['help', "Display this help.", { shortcircuit => 1 }],
41 ['manual|pod', "Display the user manaul.", { shortcircuit => 1 }],
42 );
43  
44 if( $opt->help ) {
45 print $usage->text;
46 exit 0;
47 }
48 pod2usage( -verbose => 2, -exitval => 0 ) if $opt->manual;
49  
50 my $config = YAML::LoadFile( $opt->config );
51  
52 # Initialize Logging
53 my $level = $opt->debug ? 'TRACE' : 'DEBUG';
54 my $loggingConfig = $opt->log4perl_config || \qq{
55 log4perl.logger = $level, Screen
56 log4perl.appender.Screen = Log::Log4perl::Appender::ScreenColoredLevels
57 log4perl.appender.Screen.layout = PatternLayout
58 log4perl.appender.Screen.layout.ConversionPattern = %d [%P] %p - %m%n
59 };
60 Log::Log4perl->init($loggingConfig);
61  
62 my $main = POE::Session->create(
63 inline_states => {
64 _start => \&main_start,
65 _stop => \&main_stop,
66 _child => \&main_child,
67 stats => \&main_stats,
68  
69 got_new_line => \&got_new_line,
70 get_error => \&got_error,
71 log4perl_refresh => \&log4perl_refresh,
72 },
73 heap => {
74 config => $config,
75 stats => {},
76 },
77 );
78  
79 POE::Kernel->run();
80 exit 0;
81  
82 sub main_start {
83 my ($kernel,$heap) = @_[KERNEL,HEAP];
84  
85 my $config = $heap->{config};
86 my %defaults = (
87 interval => 5,
88 index => 'files-%Y.%m.%d',
89 type => 'log',
90 );
91  
92 my $files = 0;
93 foreach my $tail ( @{ $config->{tail} } ) {
94 if( -r $tail->{file} ) {
95 my $wheel = POE::Wheel::FollowTail->new(
96 Filename => $tail->{file},
97 InputEvent => 'got_new_line',
98 ErrorEvent => 'got_error',
99 PollInterval => $tail->{interval} || $defaults{interval},
100 );
101 $heap->{wheels}{$wheel->ID} = $wheel;
102 $heap->{instructions}{$wheel->ID} = {
103 %defaults,
104 %{ $tail },
105 };
106 $files++;
107 DEBUG(sprintf "Wheel %d tailing %s", $wheel->ID, $tail->{file});
108 }
109 }
110  
111 die sprintf("No files found to tail in %s", $opt->config) unless $files > 0;
112  
113 my $es = $config->{elasticsearch} || {};
114 $heap->{elasticsearch} = POE::Component::ElasticSearch::Indexer->spawn(
115 Alias => 'es',
116 Protocol => $es->{protocol} || 'http',
117 Servers => $es->{servers} || [qw( localhost:9200 )],
118 Timeout => $es->{timeout} || 5,
119 FlushInterval => $es->{flush_interval} || 10,
120 FlushSize => $es->{flush_size} || 100,
121 LoggingConfig => $loggingConfig,
122 StatsInterval => $opt->stats_interval,
123 StatsHandler => sub {
124 my ($stats) = @_;
125 foreach my $k (keys %{ $stats }) {
126 $heap->{stats}{$k} ||= 0;
127 $heap->{stats}{$k}++;
128 }
129 },
130 exists $es->{index} ? ( DefaultIndex => $es->{index} ) : (),
131 exists $es->{type} ? ( DefaultType => $es->{type} ) : (),
132 );
133  
134 # Watch the Log4perl Config
135 $kernel->delay( log4perl_refresh => 60 ) if $opt->log4perl_config;
136 $kernel->delay( stats => $opt->stats_interval );
137  
138 INFO("Started $0 watching $files files.");
139 }
140  
141 sub main_stop {
142 $poe_kernel->post( es => 'shutdown' );
143 FATAL("Shutting down $0");
144 }
145  
146 sub main_child {
147 my ($kernel,$heap,$reason,$child) = @_[KERNEL,HEAP,ARG0,ARG1];
148 INFO(sprintf "Child [%d] %s event.", $child->ID, $reason);
149 }
150  
151 sub main_stats {
152 my ($kernel,$heap) = @_[KERNEL,HEAP];
153  
154 # Reschedule
155 $kernel->delay( stats => $opt->stats_interval );
156  
157 # Collect our stats
158 my $stats = delete $heap->{stats};
159 $heap->{stats} = {};
160  
161 # Display them
162 my $message = keys %{ $stats } ? join(", ", map {"$_=$stats->{$_}"} sort keys %{ $stats })
163 : "Nothing to report.";
164 INFO("STATS - $message");
165 }
166  
167 sub got_error {
168 my ($kernel,$heap,$op,$errnum,$errstr,$wheel_id) = @_[KERNEL,HEAP,ARG0..ARG3];
169  
170 ERROR("Wheel $wheel_id during $op got $errnum : $errstr");
171  
172 # Remove the Wheel from the polling
173 if( exists $heap->{wheels}{$wheel_id} ) {
174 delete $heap->{wheels}{$wheel_id};
175 $heap->{stats}{wheel_error} ||= 0;
176 $heap->{stats}{wheel_error}++;
177 }
178  
179 # Close the ElasticSearch session if this is the last wheel
180 if( !keys %{ $heap->{wheels} } ) {
181 $kernel->post( es => 'shutdown' );
182 }
183 }
184  
185 sub log4perl_refresh {
186 my $kernel = $_[KERNEL];
187 TRACE("Rescanning Log4perl configuration at" . $opt->log4perl_config);
188 # Reschedule
189 $kernel->delay( log4perl_refresh => 60 );
190 # Rescan the Log4perl configuration
191 Log::Log4perl::Config->watcher->force_next_check();
192 return;
193 }
194  
195 sub got_new_line {
196 my ($kernel,$heap,$line,$wheel_id) = @_[KERNEL,HEAP,ARG0,ARG1];
197  
198 $heap->{stats}{received} ||= 0;
199 $heap->{stats}{received}++;
200  
201 my $instr = $heap->{instructions}{$wheel_id};
202  
203 my $doc;
204 if( $instr->{decode} ) {
205 my $decoders = is_arrayref($instr->{decode}) ? $instr->{decode} : [ $instr->{decode} ];
206 foreach my $decoder ( @{ $decoders } ) {
207 if( $decoder eq 'json' ) {
208 my $start = index('{', $line);
209 my $blob = $start > 0 ? substr($line,$start) : $line;
210 my $new;
211 eval {
212 $new = decode_json($blob);
213 1;
214 } or do {
215 my $err = $@;
216 TRACE("Bad JSON, error: $err\n$blob");
217 next;
218 };
219 $doc = merge( $doc, $new );
220 }
221 elsif( $decoder eq 'syslog' ) {
222 unless( is_loaded('Parse::Syslog::Line') ) {
223 eval {
224 load "Parse::Syslog::Line";
225 1;
226 } or do {
227 my $err = $@;
228 die "To use the 'syslog' decoder, please install Parse::Syslog::Line: $err";
229 };
230 no warnings qw(once);
231 $Parse::Syslog::Line::PruneRaw = 1;
232 }
233 # If we make it here, we're ready to parse
234 $doc = Parse::Syslog::Line::parse_syslog_line($line);
235 }
236 }
237 }
238  
239 # Extractors
240 if( my $extracters = $instr->{extract} ) {
241 foreach my $extract( @{ $extracters } ) {
242 # Only process items with a "by"
243 if( $extract->{by} ) {
244 my $from = $extract->{from} ? ( is_hashref($doc) && exists $doc->{$extract->{from}} ? $doc->{$extract->{from}} : undef )
245 : $line;
246 next unless $from;
247 if( $extract->{when} ) {
248 next unless $from =~ /$extract->{when}/;
249 }
250 if( $extract->{by} eq 'split' ) {
251 next unless $extract->{split_on};
252 my @parts = split /$extract->{split_on}/, $from;
253 if( my $keys = $extract->{split_parts} ) {
254 # Name parts
255 for( my $i = 0; $i < @parts; $i++ ) {
256 next unless $keys->[$i] and length $keys->[$i] and $parts[$i];
257 next if lc $keys->[$i] eq 'null' or lc $keys->[$i] eq 'undef';
258 if( my $into = $extract->{into} ) {
259 # Make sure we have a hash reference
260 $doc ||= {};
261 $doc->{$into} = {} unless is_hashref($doc->{$into});
262 $doc->{$into}{$keys->[$i]} = $parts[$i];
263 }
264 else {
265 $doc ||= {};
266 $doc->{$keys->[$i]} = $parts[$i];
267 }
268 }
269 }
270 else {
271 # This is an array, so it's simple
272 my $target = $extract->{into} ? $extract->{into} : $extract->{from};
273 $doc->{$target} = @parts > 1 ? [ grep { defined and length } @parts ] : $parts[0];
274 }
275 }
276 elsif( $extract->{by} eq 'regex' ) {
277 # Skip unless it's valid
278 next unless $extract->{regex} and $extract->{regex_parts};
279  
280 if( my @parts = ($from =~ /$extract->{regex}/) ) {
281 # Name parts
282 my $keys = $extract->{regex_parts};
283 for( my $i = 0; $i < @parts; $i++ ) {
284 next unless $keys->[$i] and length $keys->[$i] and $parts[$i];
285 next if lc $keys->[$i] eq 'null' or lc $keys->[$i] eq 'undef';
286 if( my $into = $extract->{into} ) {
287 # Make sure we have a hash reference
288 $doc ||= {};
289 $doc->{$into} = {} unless is_hashref($doc->{$into});
290 $doc->{$into}{$keys->[$i]} = $parts[$i];
291 }
292 else {
293 $doc ||= {};
294 $doc->{$keys->[$i]} = $parts[$i];
295 }
296 }
297 }
298 }
299 }
300 }
301 }
302  
303 # Skip if the document isn't put together yet
304 return unless $doc;
305  
306 $heap->{stats}{docs} ||= 0;
307 $heap->{stats}{docs}++;
308  
309 # Store Line in _raw now
310 $doc->{_raw} = $line;
311 $doc->{_path} = $instr->{file};
312  
313 # Mutators
314 if( my $mutate = $instr->{mutate} ) {
315 # Copy
316 if( my $copy = $mutate->{copy} ) {
317 foreach my $k ( keys %{ $copy } ) {
318 my $destinations = is_arrayref($copy->{$k}) ? $copy->{$k} : [ $copy->{$k} ];
319 foreach my $dst ( @{ $destinations } ) {
320 $doc->{$dst} = $doc->{$k};
321 }
322 }
323 }
324 # Rename Keys
325 if( my $rename = $mutate->{rename} ) {
326 foreach my $k ( keys %{ $rename } ) {
327 next unless exists $doc->{$k};
328 $doc->{$rename->{$k}} = delete $doc->{$k};
329 }
330 }
331 # Remove unwanted keys
332 if( $mutate->{remove} ) {
333 foreach my $k ( @{ $mutate->{remove} } ) {
334 delete $doc->{$k} if exists $doc->{$k};
335 }
336 }
337 # Append
338 if( my $append = $mutate->{append} ) {
339 foreach my $k ( keys %{ $append } ) {
340 $doc ||= {};
341 $doc->{$k} = $append->{$k};
342 }
343 }
344 # Prune empty or undefined keys
345 if( $mutate->{prune} ) {
346 foreach my $k (keys %{ $doc }) {
347 delete $doc->{$k} unless defined $doc->{$k} and length $doc->{$k};
348 }
349 }
350 }
351  
352 foreach my $meta (qw(index type)) {
353 $doc->{"_$meta"} = $instr->{$meta} if exists $instr->{$meta};
354 }
355  
356 if( $opt->debug ) {
357 TRACE("Indexing: " . encode_json($doc));
358 }
359  
360 # Send the document to ElasticSearch
361 $kernel->post( es => queue => $doc );
362 }
363  
364 __END__
365  
366 =pod
367  
368 =encoding UTF-8
369  
370 =head1 NAME
371  
372 file-to-elasticsearch.pl - A simple utility to tail a file and index each line as a document in ElasticSearch
373  
374 =head1 VERSION
375  
376 version 0.016
377  
378 =head1 SYNOPSIS
379  
380 To see available options, run:
381  
382 file-to-elasticsearch.pl --help
383  
384 Create a config file and run the utility:
385  
386 file-to-elasticsearch.pl --config config.yaml --log4perl logging.conf --debug
387  
388 This will run a single threaded POE instance that will tail the log files
389 you've requested, performing the requested transformations and sending them to
390 the elasticsearch cluster and index you've specified.
391  
392 =head1 CONFIGURATION
393  
394 =head1 Configuration
395  
396 =head2 ElasticSearch Settings
397  
398 The C<elasticsearch> section of the config controls the settings passed to the
399 L<POE::Component::ElasticSearch::Indexer>.
400  
401 ---
402 elasticsearch:
403 servers: [ "localhost:9200" ]
404 flush_interval: 30
405 flush_size: 1_000
406 index: logstash-%Y.%m.%d
407 type: log
408  
409 The settings available are:
410  
411 =over 4
412  
413 =item B<servers>
414  
415 An array of servers used to send bulk data to ElasticSearch. The default is
416 just localhost on port 9200.
417  
418 =item B<flush_interval>
419  
420 Every C<flush_interval> seconds, the queued documents are send to the Bulk API
421 of the cluster.
422  
423 =item B<flush_size>
424  
425 If this many documents is received, regardless of the time since the last
426 flush, force a flush of the queued documents to the Bulk API.
427  
428 =item B<index>
429  
430 A C<strftime> compatible string to use as the C<DefaultIndex> parameter if a
431 file doesn't pass one along.
432  
433 =item B<type>
434  
435 Mostly useless as Elastic is abandoning "types", but this will be set as the
436 C<DefaultType> for documents being indexed.
437  
438 =back
439  
440 =head2 Tail Section
441  
442 The C<files> section contains the list of files to tail and the rules to use to
443 index them.
444  
445 ---
446 tail:
447 - file: '/var/log/osquery/result.log'
448 index: "osquery-result-%Y.%m.%d"
449 decode: json
450 extract:
451 - by: split
452 from: name
453 when: '^pack'
454 into: 'pack'
455 split_on: '/'
456 split_parts: [ null, "name", "report" ]
457 mutate:
458 prune: true
459 remove: [ "calendarTime", "epoch", "counter", "_raw" ]
460 rename:
461 unixTime: _epoch
462  
463 Each element is a hash containing the following information.
464  
465 =over 4
466  
467 =item B<file>
468  
469 B<Required>: The path to the file on the filesystem.
470  
471 =item B<decode>
472  
473 This may be a single element, or an array, containing one or more of the implemented decoders.
474  
475 =over 4
476  
477 =item json
478  
479 Decode the discovered JSON in the document to a hash reference. This finds the
480 first occurrence of an C<{> in the string and assumes everything to the end of
481 the string is JSON.
482  
483 Decoding is done by L<JSON::MaybeXS>.
484  
485 =item syslog
486  
487 Parses each line as a standard UNIX syslog message. Parsing is provided via
488 L<Parse::Syslog::Line> which isn't a hard requirement of the this package, but
489 will be loaded if available.
490  
491 =back
492  
493 =item B<index>
494  
495 A C<strftime> compatible string to use as the index to put documents created
496 from this file. If not specified, the defaults from the ElasticSearch section
497 will be used, and failing that, the default as specified in
498 L<POE::Component::ElasticSearch::Index>.
499  
500 =item B<type>
501  
502 The type to use for documents sourced from this file.
503  
504 =item B<extract>
505  
506 Extraction of fields from the document by one of the supported methods.
507  
508 =over 4
509  
510 =item by
511  
512 Can be 'split' or 'regex'.
513  
514 B<split> supports:
515  
516 =over 4
517  
518 =item split_on
519  
520 Regex or string to split the string on.
521  
522 =item split_parts
523  
524 Name for each part of the split, C<undef> positions in the split string will be discarded.
525  
526 =back
527  
528 B<regex> supports:
529  
530 =over 4
531  
532 =item regex
533  
534 The regex to use to extract, using capture groups to designate:
535  
536 =item regex_parts
537  
538 Name for reach captured group, C<undef> positions in the list will be discarded.
539  
540 =back
541  
542 =item from
543  
544 Name of the field to apply the extraction to.
545  
546 =item when
547  
548 Limits applying the extraction to values matching the regex.
549  
550 =item into
551  
552 Top level namespace for the collected keys to wind up inside of, ie:
553  
554 extract:
555 - by: split
556 from: name
557 when: '^pack'
558 into: 'pack'
559 split_on: '/'
560 split_parts: [ null, "name", "report" ]
561  
562 Will look at the field B<name> and when it matches C<^pack> it will split the
563 name on C</> and index the second element to C<name> and the third to C<report>, so:
564  
565 name: pack/os/cpu_info
566  
567 Becomes:
568  
569 pack:
570 name: os
571 report: cpu_info
572  
573 =back
574  
575 =back
576  
577 =head1 AUTHOR
578  
579 Brad Lhotsky <brad@divisionbyzero.net>
580  
581 =head1 COPYRIGHT AND LICENSE
582  
583 This software is Copyright (c) 2018 by Brad Lhotsky.
584  
585 This is free software, licensed under:
586  
587 The (three-clause) BSD License
588  
589 =cut