lib/POE/Component/ElasticSearch/Indexer.pm

filter: Statementstmt 100% 51 / 51 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 17 / 17 Podpod n/a totaltotal 100% 68 / 68 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« script/file-to-elasticsearch.pl ↑ Summary
1 package POE::Component::ElasticSearch::Indexer;
2 # ABSTRACT: POE session to index data to ElasticSearch
3  
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 our $VERSION = '0.016'; # VERSION
9  
10 1 ▶use Const::Fast;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Digest::MD5 qw(md5_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Digest::SHA1 qw(sha1_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Fcntl qw(:flock);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use List::Util qw(shuffle);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Log::Log4perl qw(:easy);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use Ref::Util qw(is_ref is_arrayref is_blessed_ref is_hashref is_coderef);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 1 use POE qw(
25 Component::SSLify
26 Component::Client::HTTP
27 Component::Client::Keepalive
28 1 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30  
31 sub spawn {
32 my $type = shift;
33 my %params = @_;
34  
35 # Setup Logging
36 my $loggingConfig = exists $params{LoggingConfig} && -f $params{LoggingConfig} ? $params{LoggingConfig}
37 : \q{
38 log4perl.logger = DEBUG, Sync
39 log4perl.appender.File = Log::Log4perl::Appender::File
40 log4perl.appender.File.layout = PatternLayout
41 log4perl.appender.File.layout.ConversionPattern = %d [%P] %p - %m%n
42 log4perl.appender.File.filename = es_indexer.log
43 log4perl.appender.File.mode = truncate
44 log4perl.appender.Sync = Log::Log4perl::Appender::Synchronized
45 log4perl.appender.Sync.appender = File
46 };
47 Log::Log4perl->init($loggingConfig) unless Log::Log4perl->initialized;
48  
49 # Build Configuration
50 my %CONFIG = (
51 Alias => 'es',
52 Servers => [qw(localhost)],
53 Timeout => 5,
54 FlushInterval => 30,
55 FlushSize => 1_000,
56 DefaultIndex => 'logs-%Y.%m.%d',
57 DefaultType => '_doc',
58 BatchDir => '/tmp/es_index_backlog',
59 StatsInterval => 60,
60 BacklogInterval => 60,
61 CleanupInterval => 60,
62 PoolConnections => 1,
63 KeepAliveTimeout => 2,
64 MaxConnsPerServer => 3,
65 MaxPendingRequests => 5,
66 MaxRecoveryBatches => 10,
67 MaxFailedRatio => 0.8,
68 AuthUsername => $ENV{USER},
69 Protocol => 'http',
70 %params,
71 );
72 if( $CONFIG{BatchDiskSpace} ) {
73 # Human Readable to Computer Readable
74 if( my ($size,$unit) = ($CONFIG{BatchDiskSpace} =~ /(\d+(?:\.\d+)?)\s*([kmgt])b?/i) ) {
75 $unit = lc $unit;
76 $CONFIG{BatchDiskSpace} = $unit eq 'k' ? $size * 1_000
77 : $unit eq 'm' ? $size * 1_000_000
78 : $unit eq 'g' ? $size * 1_000_000_000
79 : $unit eq 't' ? $size * 1_000_000_000_000
80 : $size;
81 }
82 else {
83 WARN("Disabling cleanup due to bad argument for BatchDiskSpace: '$CONFIG{BatchDiskSpace}', see try something like: 2gb or see docs");
84 delete $CONFIG{BatchDiskSpace};
85 }
86 }
87 if( $CONFIG{MaxFailedRatio} > 1 ) {
88 WARN("Attempt to set MaxFailedRatio to a number greater than 1, reset to default 0.8");
89 $CONFIG{MaxFailedRatio} = 0.8;
90 }
91  
92 # We need a unique session alias for our http client
93 my $http_session_alias = md5_hex( "elasticsearch http client" . time() );
94 # Management Session
95 my $session = POE::Session->create(
96 inline_states => {
97 _start => \&_start,
98 _child => \&_child,
99 stats => \&_stats,
100 queue => \&es_queue,
101 flush => \&es_flush,
102 batch => \&es_batch,
103 save => \&es_save,
104 backlog => \&es_backlog,
105 cleanup => \&es_cleanup,
106 shutdown => \&es_shutdown,
107 version => \&es_version,
108 #health => \&es_health,
109  
110 # HTTP Responses
111 resp_bulk => \&resp_bulk,
112 resp_version => \&resp_version,
113 #resp_health => \&resp_health,
114 },
115 heap => {
116 cfg => \%CONFIG,
117 stats => {},
118 start => {},
119 batch => {},
120 health => '',
121 es_ready => 0,
122 http_alias => $http_session_alias,
123 # Version Checking
124 _version_checks => 0,
125 max_version_tries => 5,
126 },
127 );
128  
129 # Connection Pooling
130 my $num_servers = scalar( @{ $CONFIG{Servers} } );
131 $CONFIG{MaxConnsTotal} ||= $num_servers * $CONFIG{MaxConnsPerServer};
132 my $pool = $CONFIG{PoolConnections} ? POE::Component::Client::Keepalive->new(
133 keep_alive => $CONFIG{KeepAliveTimeout},
134 max_open => $CONFIG{MaxConnsTotal},
135 max_per_host => $CONFIG{MaxConnsPerServer},
136 timeout => $CONFIG{Timeout},
137 ) : undef;
138  
139 my $http_timeout = $pool ? $CONFIG{Timeout} * $CONFIG{MaxConnsPerServer} : $CONFIG{Timeout};
140 POE::Component::Client::HTTP->spawn(
141 Alias => $http_session_alias,
142 Timeout => $http_timeout,
143 # Are we using Connection Pooling?
144 $pool ? (ConnectionManager => $pool) : (),
145 );
146 DEBUG(sprintf "Spawned an HTTP %s for %d servers, %s.",
147 $CONFIG{PoolConnections} ? 'pool' : 'session',
148 $num_servers,
149 $CONFIG{PoolConnections} ?
150 sprintf("%d max connections, %d max per host", @CONFIG{qw(MaxConnsTotal MaxConnsPerServer)})
151 : 'pooling disabled',
152 );
153 return $session;
154 }
155  
156 #------------------------------------------------------------------------#
157 # ES Functions
158  
159 sub _start {
160 my ($kernel,$heap) = @_[KERNEL,HEAP];
161  
162 # Set our alias
163 $kernel->alias_set($heap->{cfg}{Alias});
164  
165 # Set the interval / maximum
166 my $adjuster = (1 + (int(rand(10))/20));
167 $heap->{cfg}{FlushSize} *= $adjuster;
168 $heap->{cfg}{FlushInterval} *= $adjuster;
169  
170 # Batch directory
171 path($heap->{cfg}{BatchDir})->mkpath;
172  
173 # Check Version
174 $kernel->yield('version');
175  
176 # Run through the backlog
177 $kernel->delay( backlog => 2 );
178 $heap->{backlog_scheduled} = 1;
179  
180 # Schedule Statistics Run
181 $kernel->delay( stats => $heap->{cfg}{StatsInterval} );
182 }
183  
184 sub _child {
185 my ($kernel,$heap,$reason,$child) = @_[KERNEL,HEAP,ARG0,ARG1];
186 DEBUG(sprintf "child(%s) event: %s", $child->ID, $reason);
187 }
188  
189 sub _stats {
190 my ($kernel,$heap) = @_[KERNEL,HEAP,ARG0,ARG1];
191  
192 # Reschedule
193 $kernel->delay( stats => $heap->{cfg}{StatsInterval} )
194 unless $heap->{SHUTDOWN};
195  
196 # Extract the stats from the heap
197 my $stats = delete $heap->{stats};
198 $heap->{stats} = {};
199  
200 # Compute Succes/Fail Ratio
201 my $success = $stats->{bulk_success} || 0;
202 my $failure = $stats->{bulk_failure} || 0;
203  
204 # Fetch the pending request count from the HTTP client
205 $stats->{pending_requests} = $kernel->call( $heap->{http_alias} => 'pending_requests_count' );
206  
207 # We tried stuff this go around
208 if( $success >= 0 && $failure == 0 ) {
209 $heap->{es_ready} = 1;
210 }
211 else {
212 # Calculate how much we failed
213 my $ratio = sprintf "%0.3f", $failure / ($success + $failure);
214 # Check and set readiness
215 $heap->{es_ready} = $stats->{pending_requests} < $heap->{cfg}{MaxPendingRequests}
216 && $ratio < $heap->{cfg}{MaxFailedRatio};
217 }
218  
219 # Display our stats
220 if( is_coderef($heap->{cfg}{StatsHandler}) ) {
221 # Run in an eval and remove the handler if the code dies
222 eval {
223 $heap->{cfg}{StatsHandler}->($stats);
224 1;
225 } or do {
226 my $err = $@;
227 ERROR("Disabling the StatsHandler due to fatal error: $!");
228 $heap->{stats}{StatsHandler} = undef;
229 };
230 }
231 # Also output at TRACE level
232 TRACE( "STATS - " .
233 scalar(keys %$stats) ? join(', ', map { "$_=$stats->{$_}" } sort keys %$stats )
234 : 'Nothing to report.'
235 );
236 }
237  
238  
239 sub es_version {
240 my ($kernel,$heap) = @_[KERNEL,HEAP];
241  
242 # Bail if we've tried too many times
243 die "Unable to guess version after $heap->{max_version_tries}"
244 if $heap->{_version_checks} >= $heap->{max_version_tries};
245  
246 $heap->{_version_checks}++;
247  
248 # Get Server/Port
249 my ($server,$port) = split /\:/, $heap->{cfg}{Servers}[int rand scalar @{$heap->{cfg}{Servers}}];
250 my $uri = URI->new();
251 $uri->scheme($heap->{cfg}{Protocol});
252 $uri->host($server);
253 $uri->port($port || 9200);
254 $uri->path('/');
255  
256 # Build the request
257 my $req = HTTP::Request->new(GET => $uri->as_string);
258  
259 # Use authentication if configured
260 $req->authorization_basic( @{ $heap->{cfg} }{qw(AuthUsername AuthPassword)} )
261 if length $heap->{cfg}{AuthPassword};
262  
263 # Make the request
264 $kernel->post( $heap->{http_alias} => request => resp_version => $req );
265 }
266  
267  
268 sub resp_version {
269 my ($kernel,$heap,$params,$resp) = @_[KERNEL,HEAP,ARG0,ARG1];
270  
271 my $req = $params->[0]; # HTTP::Request Object
272 my $r = $resp->[0]; # HTTP::Response Object
273  
274 # We might need to batch things
275 TRACE(sprintf "es_version() - %s", $r->status_line);
276  
277 if( $r->is_success ) {
278 my $details;
279 eval {
280 $details = decode_json($r->content);
281 } or do {
282 my $error = $@;
283 WARN("es_version() not valid JSON: $error");
284 };
285 if( defined $details && ref $details eq 'HASH' ) {
286 my $v = $details->{version};
287 DEBUG(sprintf "es_version(%s) instance=%s cluster=%s version=%s min=%s",
288 $v->{distribution},
289 $details->{name},
290 $details->{cluster_name},
291 $v->{number},
292 $v->{minimum_wire_compatibility_version},
293 );
294 $heap->{es_version} = version->parse($v->{minimum_wire_compatibility_version});
295 $heap->{es_ready} = 1;
296 }
297 }
298 else {
299 ERROR(sprintf "es_version() FAILED: %s", $r->status_line);
300 }
301 # Retry
302 $kernel->yield('version') unless $heap->{es_ready};
303 }
304  
305  
306 sub es_queue {
307 my ($kernel,$heap,$data) = @_[KERNEL,HEAP,ARG0];
308  
309 return unless $data;
310  
311 my $events = is_arrayref($data) ? $data : [$data];
312 $heap->{queue} ||= [];
313 DOC: foreach my $doc ( @{ $events } ) {
314 my $record;
315 if( is_blessed_ref($doc) ) {
316 eval {
317 $record = $doc->as_bulk();
318 1;
319 } or do {
320 $heap->{stats}{queue_blessed_fail} ||= 0;
321 $heap->{stats}{queue_blessed_fail}++;
322 next DOC;
323 };
324 }
325 elsif( is_hashref($doc) ) {
326 # Assemble Metadata
327 my $epoch = $doc->{_epoch} ? delete $doc->{_epoch} : time;
328 my $index = $doc->{_index} ? delete $doc->{_index} : $heap->{cfg}{DefaultIndex};
329 my %meta = (
330 _index => index($index,'%') >= 0 ? strftime($index,localtime($epoch)) : $index,
331 _type => $doc->{_type} ? delete $doc->{_type} : $heap->{cfg}{DefaultType},
332 $doc->{_id} ? ( _id => delete $doc->{_id} ) : (),
333 );
334 # Remove _type attribute for newer elasticsearch
335 delete $meta{_type} if $heap->{es_version} >= version->declare("v7.0.0");
336 # Construct the bulk request
337 $record = sprintf("%s\n%s\n",
338 encode_json({ index => \%meta }),
339 encode_json($doc),
340 );
341 }
342 elsif( !is_ref($doc) ) {
343 $record = $doc;
344 }
345 else {
346 $heap->{stats}{queue_bad_input} ||= 0;
347 $heap->{stats}{queue_bad_input}++;
348 }
349 # Ensure we wound up with something useful
350 next unless $record;
351 push @{ $heap->{queue} }, $record;
352 }
353  
354 my $queue_size = scalar(@{ $heap->{queue} });
355 if ( exists $heap->{cfg}{FlushSize} && $heap->{cfg}{FlushSize} > 0
356 && $queue_size >= $heap->{cfg}{FlushSize}
357 && !exists $heap->{force_flush}
358 ) {
359 TRACE("Queue size target exceeded, flushing queue ". $heap->{cfg}{FlushSize} . " max, size is $queue_size" );
360 $heap->{force_flush} = 1;
361 $kernel->yield( 'flush' );
362 }
363 elsif( $queue_size ) {
364 $kernel->delay_add( flush => $heap->{cfg}{FlushInterval} );
365 }
366 }
367  
368  
369 sub es_flush {
370 my ($kernel,$heap) = @_[KERNEL,HEAP];
371  
372 # Remove the scheduler bit for this event
373 $kernel->delay('flush');
374  
375 my $count_docs = exists $heap->{queue} && is_arrayref($heap->{queue}) ? scalar(@{ $heap->{queue} }) : 0;
376 my $reason = exists $heap->{force_flush} && delete $heap->{force_flush} ? 'force' : 'schedule';
377  
378 # Record the flush
379 $heap->{stats}{"es_flush_$reason"} ||= 0;
380 $heap->{stats}{"es_flush_$reason"}++;
381  
382 if( $count_docs > 0 ) {
383 # Build the batch
384 my $to = $heap->{es_ready} ? 'batch' : 'save';
385 my $docs = delete $heap->{queue};
386 my $batch = join '', @{ $docs };
387 my $id = sha1_hex($batch);
388 $heap->{batch}{$id} = $batch;
389  
390 DEBUG(sprintf "es_flush(%s) of %d documents to %s, id=%s",
391 $reason,
392 $count_docs,
393 $to,
394 $id,
395 );
396 $kernel->yield( $to => $id );
397 }
398 }
399  
400  
401 sub es_backlog {
402 my ($kernel,$heap) = @_[KERNEL,HEAP];
403  
404 delete $heap->{backlog_scheduled};
405  
406 my $max_batches = $heap->{cfg}{MaxRecoveryBatches};
407 my $batch_dir = path($heap->{cfg}{BatchDir});
408  
409 # randomize
410 my @ids = shuffle map { $_->basename('.batch') }
411 $batch_dir->children( qr/\.batch$/ );
412 $kernel->yield( batch => $_ ) for @ids[0..$max_batches-1];
413  
414 if(@ids > $max_batches) {
415 INFO("Rescheduling backlog run");
416 $kernel->delay( backlog => $heap->{cfg}{BacklogInterval}) unless $heap->{SHUTDOWN};
417 $heap->{backlog_scheduled} = 1;
418 }
419 }
420  
421  
422 sub es_shutdown {
423 $_[HEAP]->{SHUTDOWN} = 1;
424 FATAL("es_shutdown() - Shutting down.");
425 }
426  
427  
428 sub es_batch {
429 my ($kernel,$heap,$id) = @_[KERNEL,HEAP,ARG0];
430  
431 return unless defined $id;
432  
433 # Only process if we're ready
434 if( !$heap->{es_ready} ) {
435 WARN("es_batch() - Connection not ready");
436 # Flush this batch to disk
437 $kernel->yield( save => $id )
438 if exists $heap->{batch}{$id};
439  
440  
441 # Bail and rely on the disk backlog
442 return;
443 }
444  
445 # Get our content
446 my $batch = '';
447 if( exists $heap->{batch}{$id} ) {
448 $batch = delete $heap->{batch}{$id};
449 }
450 else {
451 # Read batch from disk
452 my $batch_file = path($heap->{cfg}{BatchDir})->child($id . '.batch');
453 if( $batch_file->is_file ) {
454 # We need exclusive locking so we can brute force a batch
455 # directory in a batch cleanup mode
456 my $locked = lock_batch_file($batch_file);
457 if( defined $locked && $locked == 1 ) {
458 $batch = $batch_file->slurp_raw;
459 my $lines = $batch =~ tr/\n//;
460 if( $lines > 0 ) {
461 $heap->{stats}{consumed} ||= 0;
462 $heap->{stats}{consumed} += int($lines / 2);
463 }
464 }
465 }
466 else {
467 WARN(sprintf "es_batch(%s) called for an unknown batch.", $id);
468 }
469 }
470 return unless length $batch;
471  
472 # Build the URI
473 my ($server,$port) = split /\:/, $heap->{cfg}{Servers}[int rand scalar @{$heap->{cfg}{Servers}}];
474 my $uri = URI->new();
475 $uri->scheme($heap->{cfg}{Protocol});
476 $uri->host($server);
477 $uri->port($port || 9200);
478 $uri->path('/_bulk');
479  
480 # Build the request
481 my $req = HTTP::Request->new(POST => $uri->as_string);
482 $req->header('Content-Type', 'application/x-ndjson');
483 $req->content($batch);
484  
485 # Use authentication if configured
486 $req->authorization_basic( @{ $heap->{cfg} }{qw(AuthUsername AuthPassword)} )
487 if length $heap->{cfg}{AuthPassword};
488  
489 TRACE(sprintf "Bulk update of %d bytes being attempted to %s as %s.",
490 length($batch),
491 $uri->as_string,
492 $id,
493 );
494 $kernel->post( $heap->{http_alias} => request => resp_bulk => $req => $id );
495 # Record the request
496 $heap->{start}{$id} = time unless exists $heap->{start}{$id};
497 $heap->{stats}{http_req} ||= 0;
498 $heap->{stats}{http_req}++;
499 }
500  
501  
502 sub resp_bulk {
503 my ($kernel,$heap,$params,$resp) = @_[KERNEL,HEAP,ARG0,ARG1];
504  
505 my $req = $params->[0]; # HTTP::Request Object
506 my $id = $params->[1]; # Batch ID
507 my $r = $resp->[0]; # HTTP::Response Object
508 my $duration = exists $heap->{start}{$id} ? time - $heap->{start}{$id} : undef;
509  
510 # We might need to batch things
511 my $batch_file = path($heap->{cfg}{BatchDir})->child($id . '.batch');
512 TRACE(sprintf "bulk_resp(%s) %s", $id, $r->status_line);
513  
514 # Record the responses we receive
515 my $resp_key = "bulk_" . ($r->is_success ? 'success' : 'failure');
516 $heap->{stats}{$resp_key} ||= 0;
517 $heap->{stats}{$resp_key}++;
518  
519 if( $r->is_success ) {
520 my $details;
521 eval {
522 $details = decode_json($r->content);
523 };
524 if( defined $details && ref $details eq 'HASH' ) {
525 DEBUG(sprintf "bulk_resp(%s) size was %d bytes for %d items, took %d ms (elapsed:%0.3fs)%s",
526 $id,
527 length($req->content),
528 scalar(@{$details->{items}}),
529 $details->{took},
530 $duration,
531 $details->{errors} ? ' with errors' : '',
532 );
533 $heap->{stats}{indexed} ||= 0;
534 $heap->{stats}{indexed} += scalar@{ $details->{items} };
535 if( exists $details->{errors} && $details->{errors} ) {
536 $heap->{stats}{errors} ||= 0;
537 $heap->{stats}{errors} += scalar grep { exists $_->{create} && exists $_->{create}{error} } @{ $details->{items} };
538 }
539 }
540 else {
541 WARN(sprintf "bulk_resp(%s) size was %d bytes, (elapsed:%0.3fs) but not valid JSON: %s",
542 $id,
543 length($req->content),
544 $duration,
545 $@,
546 );
547 }
548 # Remove the batch file
549 $batch_file->remove if $batch_file->is_file;
550 # Clear the start time
551 delete $heap->{start}{$id};
552 # This should never happen, but if it does, protect us from memory leaks
553 delete $heap->{batch}{$id} if exists $heap->{batch}{$id};
554 }
555 elsif( !$batch_file->is_file ) {
556 WARN(sprintf "bulk_resp(%s) FAILED in %0.3fs: %s",
557 $id, $duration, $r->status_line,
558 );
559 # Reload the batch into the heap
560 $heap->{batch}{$id} = $req->content;
561 # Write batch to disk
562 $kernel->yield( save => $id );
563 }
564 else {
565 # Make sure we consider running the cleanup
566 $kernel->yield( 'cleanup' ) unless $heap->{cleanup_scheduled};
567 }
568 # Remove the lock
569 unlock_batch_file($batch_file);
570 }
571  
572  
573 sub es_save {
574 my ($kernel,$heap,$id) = @_[KERNEL,HEAP,ARG0];
575  
576 return unless exists $heap->{batch}{$id};
577  
578 my $content = delete $heap->{batch}{$id};
579 my $batch_file = path($heap->{cfg}{BatchDir})->child($id . '.batch');
580 my $duration = exists $heap->{start}{$id} ? time - $heap->{start}{$id} : 0;
581  
582 # Write batch to disk, unless it exists.
583 unless( $batch_file->is_file ) {
584 my $lines = $content =~ tr/\n//;
585 my $items = int( $lines / 2 );
586 DEBUG(sprintf "Storing to File Batch[%s] as %d bytes, %d items. (elapsed:%0.3fs)",
587 $id, length($content), $items, $duration
588 );
589 $batch_file->spew_raw($content);
590 $heap->{stats}{batches} ||= 0;
591 $heap->{stats}{batches}++;
592 $heap->{stats}{backlogged} ||= 0;
593 $heap->{stats}{backlogged} += $items;
594 }
595 unless( $heap->{backlog_scheduled} ) {
596 $kernel->delay( backlog => $heap->{cfg}{BacklogInterval} ) unless $heap->{SHUTDOWN};
597 $heap->{backlog_scheduled} = 1;
598 }
599 }
600  
601  
602 sub es_cleanup {
603 my ($kernel,$heap) = @_[KERNEL,HEAP];
604  
605 # Only run if we need to run
606 return unless $heap->{cfg}{BatchDiskSpace};
607 # Rerun the cleanup
608 delete $heap->{cleanup_scheduled};
609  
610 my $total = 0;
611 my $batch_dir = path($heap->{cfg}{BatchDir});
612 my @files = ();
613  
614 # Check our total size
615 $batch_dir->visit(sub {
616 my $p = shift;
617  
618 # Skip unless it's a batch file
619 return unless $p->basename =~ /\.batch$/;
620  
621 # Figure out the size of our batches
622 # We eval() in case another worker deletes the file
623 eval {
624 my $size = $p->stat->size;
625 my $ctime = $p->stat->ctime;
626 die "Invalid size: $size" unless $size > 0;
627 $total += $size;
628 push @files, {
629 path => $p,
630 size => $size,
631 ctime => $ctime,
632 };
633 1;
634 } or do {
635 my $err = $@;
636 # Yes this is an error, but we don't want it spamming the logs because it's
637 # not that important. We log at DEBUG.
638 DEBUG(sprintf "Error checking status of %s: %s", $p->basename, $err)
639 if $err =~ /Invalid size/;
640 };
641 });
642  
643 # Report words
644 DEBUG("es_cleanup(): BatchDiskSpace is '$heap->{cfg}{BatchDiskSpace}', currently $total bytes");
645  
646 # Delete some stuff
647 if( $total > $heap->{cfg}{BatchDiskSpace} ) {
648 # Sort oldest to newest
649 foreach my $batch ( sort { $a->{ctime} <=> $b->{ctime} } @files ) {
650 # Leave early, leave often
651 last if $total < $heap->{cfg}{BatchDiskSpace};
652 # Handle "we can't get lock"
653 if( ! lock_batch_file($batch->{path}) ) {
654 # If we're not the only worker, maybe someone else removed this
655 $total -= $batch->{size} unless $batch->{path}->is_file;
656 next;
657 }
658 # Otherwise, mop up
659 my $state = 'success';
660 eval {
661 # If we fail, it's because something else delete this file
662 $batch->{path}->remove;
663 1;
664 } or do {
665 my $err = $@;
666 WARN(sprintf "es_cleanup() failed removing %s: %s",
667 $batch->{path}->absolute->stringify,
668 $err,
669 );
670 $state = 'fail';
671 };
672 $heap->{stats}{"cleanup_$state"} ||= 0;
673 $heap->{stats}{"cleanup_$state"}++;
674  
675 unlock_batch_file($batch->{path});
676 $total -= $batch->{size};
677 }
678 }
679 if( $total > 0 ) {
680 $kernel->delay( cleanup => $heap->{cfg}{CleanupInterval} ) unless $heap->{SHUTDOWN};
681 $heap->{cleanup_scheduled} = 1;
682 }
683 }
684  
685 # Closure for Locks
686 {
687 my %_lock = ();
688  
689  
690 sub lock_batch_file {
691 my $batch_file = shift;
692 my $lock_file = path($batch_file->absolute . '.lock');
693 my $id = $lock_file->absolute;
694  
695 my $locked = 0;
696 # We need to try to lock, but Path::Tiny doesn't support exclusive locks on
697 # read operations, so we'll handle that with a lock file.
698 if( !exists $_lock{$id} ) {
699 $locked = eval {
700 open $_lock{$id}, '>', $id or die "Cannot create lock file: $!\n";
701 flock($_lock{$id}, LOCK_EX|LOCK_NB) or die "Unable to attain exclusive lock.";
702 1;
703 };
704 if(!defined $locked) {
705 TRACE(sprintf "lock_batch_file(%s) failed: %s", $id, $@);
706 }
707 }
708 return $locked;
709 }
710  
711  
712 sub unlock_batch_file {
713 my $batch_file = shift;
714 my $lock_file = path($batch_file->absolute . '.lock');
715 my $id = $lock_file->absolute;
716  
717 if(exists $_lock{$id}) {
718 eval {
719 flock($_lock{$id}, LOCK_UN);
720 1;
721 } or do {
722 WARN(sprintf "unlock_batch_file(%s) failed: %s, removing file anyways.", $id, $@);
723 };
724 close( delete $_lock{$id} );
725 $lock_file->remove if $lock_file->is_file;
726 }
727 }
728 }
729  
730 # Return True
731 1;
732  
733 __END__
734  
735 =pod
736  
737 =encoding UTF-8
738  
739 =head1 NAME
740  
741 POE::Component::ElasticSearch::Indexer - POE session to index data to ElasticSearch
742  
743 =head1 VERSION
744  
745 version 0.016
746  
747 =head1 SYNOPSIS
748  
749 This POE Session is used to index data to an ElasticSearch cluster.
750  
751 use POE qw{ Component::ElasticSearch::Indexer };
752  
753 my $es_session = POE::Component::ElasticSearch::Indexer->spawn(
754 Alias => 'es', # Default
755 Protocol => 'http', # Default
756 Servers => [qw(localhost)], # Default
757 Timeout => 5, # Default
758 FlushInterval => 30, # Default
759 FlushSize => 1_000, # Default
760 LoggingConfig => undef, # Default
761 DefaultIndex => 'logs-%Y.%m.%d', # Default
762 DefaultType => '_doc', # Default
763 BatchDir => '/tmp/es_index_backlog', # Default
764 BatchDiskSpace => undef, # Default
765 StatsHandler => undef, # Default
766 StatsInterval => 60, # Default
767 AuthUsername => $ENV{USER}, # Default
768 AuthPassword => undef, # Default
769 );
770  
771 # Index the document using the queue for better performance
772 $poe_kernel->post( es => queue => $json_data );
773  
774 =head1 DESCRIPTION
775  
776 This module exists to provide event-based Perl programs with a simple way to
777 index documents into an ElasticSearch cluster.
778  
779 =head2 spawn()
780  
781 This method spawns the ElasticSearch indexing L<POE::Session>. It accepts the
782 following parameters.
783  
784 =over 4
785  
786 =item B<Alias>
787  
788 The alias this session is available to other sessions as. The default is
789 B<es>.
790  
791 =item B<Protocol>
792  
793 Can be either C<http> or C<https>, defaults to B<http>.
794  
795 =item B<Servers>
796  
797 A list of Elasticsearch hosts for connections. Maybe in the form of
798 C<hostname> or C<hostname:port>.
799  
800 =item B<AuthUsername>
801  
802 Username for HTTP Basic Authorization, defaults to C<$ENV{USER}>.
803  
804 =item B<AuthPassword>
805  
806 Password for HTTP Basic Authorization, set to enable HTTP Basic Authorization.
807  
808 =item B<PoolConnections>
809  
810 Boolean, default true. Enable connection pooling with
811 L<POE::Component::Client::Keepalive>. This is desirable in most cases, but can
812 result in timeouts piling up. You may wish to disable this if you notice that
813 indexing takes a while to recover after timeout events.
814  
815 =item B<KeepAliveTimeout>
816  
817 Requires C<PoolConnections>.
818  
819 Set the keep_alive timeout in seconds for the creation of a
820 L<POE::Component::Client::Keepalive> connection pool.
821  
822 Defaults to B<2>.
823  
824 =item B<MaxConnsPerServer>
825  
826 Requires C<PoolConnections>.
827  
828 Maximum number of simultaneous connections to an Elasticsearch node. Used in
829 the creation of a L<POE::Component::Client::Keepalive> connection pool.
830  
831 Defaults to B<3>.
832  
833 =item B<MaxConnsTotal>
834  
835 Requires C<PoolConnections>.
836  
837 Maximum number of simultaneous connections to all servers. Used in
838 the creation of a L<POE::Component::Client::Keepalive> connection pool.
839  
840 Defaults to B<MaxConnsPerServer * number of Servers>.
841  
842 =item B<MaxPendingRequests>
843  
844 Requires C<PoolConnections>.
845  
846 Maximum number of requests backlogged in the connection pool. Defaults to B<5>.
847  
848 =item B<MaxFailedRatio>
849  
850 A number between 0 and 1 representing a percentage of bulk requests that can
851 fail before we back off the cluster for the B<StatsInterval>. This is
852 calculated every B<StatsInterval>. The default is B<0.8> or 80%.
853  
854 =item B<LoggingConfig>
855  
856 The L<Log::Log4perl> configuration file for the indexer to use. Defaults to
857 writing logs to the current directory into the file C<es_indexing.log>.
858  
859 =item B<Timeout>
860  
861 Number of seconds for the HTTP transport connect and transport timeouts.
862 Defaults to B<5> seconds. The total request timeout, waiting for an open
863 connection slot and then completing the request, will be this multiplied by 2.
864  
865 =item B<FlushInterval>
866  
867 Maximum number of seconds which can pass before a flush of the queue is
868 attempted. Defaults to B<30> seconds.
869  
870 =item B<FlushSize>
871  
872 Once this number of documents is reached, flush the queue regardless of time
873 since the last flush. Defaults to B<1,000>.
874  
875 =item B<DefaultIndex>
876  
877 A C<strftime> aware index pattern to use if the document is missing an
878 C<_index> element. Defaults to B<logs-%Y.%m.%d>.
879  
880 =item B<DefaultType>
881  
882 Use this C<_type> attribute if the document is missing one. Defaults to
883 B<_doc> to be compatible with ES 7.x.
884  
885 The C<_type> attribute will be stripped from documents if the cluster is
886 running greater than 7.0.0.
887  
888 =item B<BatchDir>
889  
890 If the cluster responds with an HTTP failure code, the batch is written to disk
891 in this directory to be indexed when the cluster is available again. Defaults
892 to C</tmp/es_index_backlog>.
893  
894 =item B<BatchDiskSpace>
895  
896 Defaults to undef, which means disk space isn't checked. If set, if the batch
897 size goes over this limit, every new batch saved will delete the oldest batch.
898 Checked every ten batches.
899  
900 You may specify either as absolute bytes or using shortcuts:
901  
902 BatchDiskSpace => 500kb,
903 BatchDiskSpace => 100mb,
904 BatchDiskSpace => 10gb,
905 BatchDiskSpace => 1tb,
906  
907 =item B<MaxRecoveryBatches>
908  
909 The number of batches to process per backlog event. This will only come into
910 play if there are batches on disk to flush. Defaults to B<10>.
911  
912 =item B<StatsHandler>
913  
914 A code reference that will be passed a hash reference containing the keys and
915 values of counters tracked by this component. Defaults to C<undef>, meaning no
916 code is run.
917  
918 =item B<StatsInterval>
919  
920 Run the C<StatsHandler> every C<StatsInterval> seconds. Default to B<60>.
921  
922 =item B<BacklogInterval>
923  
924 Run the backlog processing event every C<BacklogInterval> seconds. Default to B<60>.
925 Will process up to C<MaxRecoveryBatches> batches per C<BacklogInterval>.
926  
927 This event only fires when there are batches on disk. When it's done
928 processing them, it will then stop firing.
929  
930 =item B<CleanupInterval>
931  
932 Run the cleanup event every C<CleanupInterval> seconds. Default to B<60>.
933 This will check to ensure the C<BatchDiskSpace> is honored and delete the
934 oldest batches if that is exceeded.
935  
936 This event only fires when there are batches on disk.
937  
938 =back
939  
940 =head2 EVENTS
941  
942 The events provided by this component.
943  
944 =over 2
945  
946 =item B<version>
947  
948 Runs at start to the get Elasticsearch Version.
949  
950 =for Pod::Coverage es_version
951  
952 =for Pod::Coverage resp_version
953  
954 =item B<queue>
955  
956 Takes an array reference of hash references to be transformed into JSON
957 documents and submitted to the cluster's C<_bulk> API.
958  
959 Each hash reference may pass in the following special keys, which will be used
960 to index the event. These keys will be deleted from the document being indexed
961 as they have special meaning to the C<bulk> API.
962  
963 =over 2
964  
965 =item B<_id>
966  
967 Will be submitted as the document id in the bulk operation, if not specified,
968 Elasticsearch will generate a UUID for each document automatically.
969  
970 =item B<_type>
971  
972 Will be submitted as the document type in the bulk operation, if not specified,
973 we'll use the C<DefaultType> specified in the C<spawn()> method.
974  
975 Deprecated and removed for clusters running Elasticsearch version 7.0 or higher.
976  
977 =item B<_index>
978  
979 Will cause the document to be indexed into that index, if not specified, the
980 C<DefaultIndex> will be used.
981  
982 =item B<_epoch>
983  
984 If the C<DefaultIndex> uses a C<strftime> compatible string, you may specify an
985 C<_epoch> in every document. If not specified, we'll assume the epoch to use
986 for C<strftime> calculations is the current time.
987  
988 =back
989  
990 For more information, see the L<Elasticsearch Bulk API Docs|https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html>.
991  
992 Alternatively, you can provide an array reference containing blessed objects that
993 provide an C<as_bulk()> method. The result of that method will be added to the
994 bulk queue.
995  
996 If you've decided to construct the requisite newline delimited JSON yourself,
997 you may pass in an array reference containing scalars. If you do, the module
998 assumes you know what you're doing and will append that text to the existing
999 bulk queue unchanged.
1000  
1001 Example use case:
1002  
1003 sub syslog_handle_line {
1004 my ($kernel,$heap,$session,$line) = @_[KERNEL,HEAP,SESSION,ARG0];
1005  
1006 # Create a document from syslog data
1007 local $Parse::Syslog::Line::PruneRaw = 1;
1008 local $Parse::Syslog::Line::PruneEmpty = 1;
1009 my $evt = parse_syslog_line($line);
1010  
1011 # Override the type
1012 $evt->{_type} = 'syslog';
1013  
1014 # If we want to collect this event into an auth index:
1015 if( exists $Authentication{$evt->{program}} ) {
1016 $evt->{_index} = strftime('authentication-%Y.%m.%d',
1017 localtime($evt->{epoch} || time)
1018 );
1019 }
1020 else {
1021 # Set an _epoch for the es queue DefaultIndex
1022 $evt->{_epoch} = $evt->{epoch} ? delete $evt->{epoch} : time;
1023 }
1024 # You'll want to batch these in your processor to avoid excess
1025 # overhead creating so many events in the POE loop
1026 push @{ $heap->{batch} }, $evt;
1027  
1028 # Once we hit 10 messages, force the flush
1029 $kernel->call( $session->ID => 'submit_batch') if @{ $heap->{batch} } > 10;
1030 }
1031  
1032 sub submit_batch {
1033 my ($kernel,$heap) = @_[KERNEL,HEAP];
1034  
1035 # Reset the batch scheduler
1036 $kernel->delay( 'submit_batch' => 10 );
1037  
1038 $kernel->post( es => queue => delete $heap->{batch} );
1039 $heap->{batch} = [];
1040 }
1041  
1042 =for Pod::Coverage es_queue
1043  
1044 =item B<flush>
1045  
1046 Schedule a flush of the existing bulk updates to the cluster. It should never
1047 be necessary to call this event unless you'd like to shutdown the event loop
1048 faster.
1049  
1050 =for Pod::Coverage es_flush
1051  
1052 =item B<backlog>
1053  
1054 Request the disk-based backlog be processed. You should never need to call
1055 this event as the session will run it once it starts and if there's data to
1056 process, it will continue rescheduling as needed. When a bulk operation fails
1057 resulting in a batch file, this event is scheduled to run again.
1058  
1059 =for Pod::Coverage es_backlog
1060  
1061 =item B<shutdown>
1062  
1063 Inform this session that you'd like to wrap up operations. This prevents recurring events from being scheduled.
1064  
1065 =for Pod::Coverage es_shutdown
1066  
1067 =for Pod::Coverage es_batch
1068  
1069 =back
1070  
1071 =for Pod::Coverage resp_bulk
1072  
1073 =for Pod::Coverage es_save
1074  
1075 =for Pod::Coverage es_cleanup
1076  
1077 =for Pod::Coverage lock_batch_file
1078  
1079 =for Pod::Coverage unlock_batch_file
1080  
1081 =head1 AUTHOR
1082  
1083 Brad Lhotsky <brad@divisionbyzero.net>
1084  
1085 =head1 COPYRIGHT AND LICENSE
1086  
1087 This software is Copyright (c) 2018 by Brad Lhotsky.
1088  
1089 This is free software, licensed under:
1090  
1091 The (three-clause) BSD License
1092  
1093 =head1 CONTRIBUTOR
1094  
1095 =for stopwords Mohammad S Anwar
1096  
1097 Mohammad S Anwar <mohammad.anwar@yahoo.com>
1098  
1099 =for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
1100  
1101 =head1 SUPPORT
1102  
1103 =head2 Websites
1104  
1105 The following websites have more information about this module, and may be of help to you. As always,
1106 in addition to those websites please use your favorite search engine to discover more resources.
1107  
1108 =over 4
1109  
1110 =item *
1111  
1112 MetaCPAN
1113  
1114 A modern, open-source CPAN search engine, useful to view POD in HTML format.
1115  
1116 L<https://metacpan.org/release/POE-Component-ElasticSearch-Indexer>
1117  
1118 =item *
1119  
1120 RT: CPAN's Bug Tracker
1121  
1122 The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
1123  
1124 L<https://rt.cpan.org/Public/Dist/Display.html?Name=POE-Component-ElasticSearch-Indexer>
1125  
1126 =back
1127  
1128 =head2 Source Code
1129  
1130 This module's source code is available by visiting:
1131 L<https://github.com/reyjrar/POE-Component-ElasticSearch-Indexer>
1132  
1133 =cut
« script/file-to-elasticsearch.pl ↑ Summary