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