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.017'; # 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(
Subroutine BEGIN: called CC=1 SCAR=0.0
25 Component::SSLify
26 Component::Client::HTTP
27 Component::Client::Keepalive
28 1 );
29  
30  
31 sub spawn {
32 my %params = @_;
33  
34 # Setup Logging
35 my $loggingConfig = exists $params{LoggingConfig} && -f $params{LoggingConfig} ? $params{LoggingConfig}
36 : \q{
37 log4perl.logger = DEBUG, Sync
38 log4perl.appender.File = Log::Log4perl::Appender::File
39 log4perl.appender.File.layout = PatternLayout
40 log4perl.appender.File.layout.ConversionPattern = %d [%P] %p - %m%n
41 log4perl.appender.File.filename = es_indexer.log
42 log4perl.appender.File.mode = truncate
43 log4perl.appender.Sync = Log::Log4perl::Appender::Synchronized
44 log4perl.appender.Sync.appender = File
45 };
46 Log::Log4perl->init($loggingConfig) unless Log::Log4perl->initialized;
47  
48 # Build Configuration
49 my %CONFIG = (
50 Alias => 'es',
51 Servers => [qw(localhost)],
52 Timeout => 5,
53 FlushInterval => 30,
54 FlushSize => 1_000,
55 DefaultIndex => 'logs-%Y.%m.%d',
56 DefaultType => '_doc',
57 BatchDir => '/tmp/es_index_backlog',
58 StatsInterval => 60,
59 BacklogInterval => 60,
60 CleanupInterval => 60,
61 PoolConnections => 1,
62 KeepAliveTimeout => 2,
63 MaxConnsPerServer => 3,
64 MaxPendingRequests => 5,
65 MaxRecoveryBatches => 10,
66 MaxFailedRatio => 0.8,
67 AuthUsername => $ENV{USER},
68 Protocol => 'http',
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 # Display our stats
219 if( is_coderef($heap->{cfg}{StatsHandler}) ) {
220 # Run in an eval and remove the handler if the code dies
221 eval {
222 $heap->{cfg}{StatsHandler}->($stats);
223 1;
224 } or do {
225 my $err = $@;
226 ERROR("Disabling the StatsHandler due to fatal error: $err");
227 $heap->{stats}{StatsHandler} = undef;
228 };
229 }
230 # Also output at TRACE level
231 TRACE( "STATS - " .
232 scalar(keys %$stats) ? join(', ', map { "$_=$stats->{$_}" } sort keys %$stats )
233 : 'Nothing to report.'
234 );
235 }
236  
237  
238 sub es_version {
239 my ($kernel,$heap) = @_[KERNEL,HEAP];
240  
241 # Bail if we've tried too many times
242 die "Unable to guess version after $heap->{max_version_tries}"
243 if $heap->{_version_checks} >= $heap->{max_version_tries};
244  
245 $heap->{_version_checks}++;
246  
247 # Get Server/Port
248 my ($server,$port) = split /\:/, $heap->{cfg}{Servers}[int rand scalar @{$heap->{cfg}{Servers}}];
249 my $uri = URI->new();
250 $uri->scheme($heap->{cfg}{Protocol});
251 $uri->host($server);
252 $uri->port($port || 9200);
253 $uri->path('/');
254  
255 # Build the request
256 my $req = HTTP::Request->new(GET => $uri->as_string);
257  
258 # Use authentication if configured
259 $req->authorization_basic( @{ $heap->{cfg} }{qw(AuthUsername AuthPassword)} )
260 if length $heap->{cfg}{AuthPassword};
261  
262 # Make the request
263 $kernel->post( $heap->{http_alias} => request => resp_version => $req );
264 }
265  
266  
267 sub resp_version {
268 my ($kernel,$heap,$params,$resp) = @_[KERNEL,HEAP,ARG0,ARG1];
269 my $r = $resp->[0]; # HTTP::Response Object
270  
271 # We might need to batch things
272 TRACE(sprintf "es_version() - %s", $r->status_line);
273  
274 if( $r->is_success ) {
275 my $details;
276 eval {
277 $details = decode_json($r->content);
278 } or do {
279 my $error = $@;
280 WARN("es_version() not valid JSON: $error");
281 };
282 if( defined $details && ref $details eq 'HASH' ) {
283 my $v = $details->{version};
284 DEBUG(sprintf "es_version(%s) instance=%s cluster=%s version=%s min=%s",
285 $v->{distribution} || 'native',
286 $details->{name},
287 $details->{cluster_name},
288 $v->{number},
289 $v->{minimum_wire_compatibility_version},
290 );
291 $heap->{es_version} = version->parse($v->{minimum_wire_compatibility_version});
292 $heap->{es_ready} = 1;
293 }
294 }
295 else {
296 ERROR(sprintf "es_version() FAILED: %s", $r->status_line);
297 }
298 # Retry
299 $kernel->yield('version') unless $heap->{es_ready};
300 }
301  
302  
303 sub es_queue {
304 my ($kernel,$heap,$data) = @_[KERNEL,HEAP,ARG0];
305  
306 return unless $data;
307  
308 my $events = is_arrayref($data) ? $data : [$data];
309 $heap->{queue} ||= [];
310 DOC: foreach my $doc ( @{ $events } ) {
311 my $record;
312 if( is_blessed_ref($doc) ) {
313 eval {
314 $record = $doc->as_bulk();
315 1;
316 } or do {
317 $heap->{stats}{queue_blessed_fail} ||= 0;
318 $heap->{stats}{queue_blessed_fail}++;
319 next DOC;
320 };
321 }
322 elsif( is_hashref($doc) ) {
323 # Assemble Metadata
324 my $epoch = $doc->{_epoch} ? delete $doc->{_epoch} : time;
325 my $index = $doc->{_index} ? delete $doc->{_index} : $heap->{cfg}{DefaultIndex};
326 my %meta = (
327 _index => index($index,'%') >= 0 ? strftime($index,localtime($epoch)) : $index,
328 _type => $doc->{_type} ? delete $doc->{_type} : $heap->{cfg}{DefaultType},
329 $doc->{_id} ? ( _id => delete $doc->{_id} ) : (),
330 );
331 # Remove _type attribute for newer elasticsearch
332 delete $meta{_type} if $heap->{es_version} >= version->declare("v7.0.0");
333 # Construct the bulk request
334 $record = sprintf("%s\n%s\n",
335 encode_json({ index => \%meta }),
336 encode_json($doc),
337 );
338 }
339 elsif( !is_ref($doc) ) {
340 $record = $doc;
341 }
342 else {
343 $heap->{stats}{queue_bad_input} ||= 0;
344 $heap->{stats}{queue_bad_input}++;
345 }
346 # Ensure we wound up with something useful
347 next unless $record;
348 push @{ $heap->{queue} }, $record;
349 }
350  
351 my $queue_size = scalar(@{ $heap->{queue} });
352 if ( exists $heap->{cfg}{FlushSize} && $heap->{cfg}{FlushSize} > 0
353 && $queue_size >= $heap->{cfg}{FlushSize}
354 && !exists $heap->{force_flush}
355 ) {
356 TRACE("Queue size target exceeded, flushing queue ". $heap->{cfg}{FlushSize} . " max, size is $queue_size" );
357 $heap->{force_flush} = 1;
358 $kernel->yield( 'flush' );
359 }
360 elsif( $queue_size ) {
361 $kernel->delay_add( flush => $heap->{cfg}{FlushInterval} );
362 }
363 }
364  
365  
366 sub es_flush {
367 my ($kernel,$heap) = @_[KERNEL,HEAP];
368  
369 # Remove the scheduler bit for this event
370 $kernel->delay('flush');
371  
372 my $count_docs = exists $heap->{queue} && is_arrayref($heap->{queue}) ? scalar(@{ $heap->{queue} }) : 0;
373 my $reason = exists $heap->{force_flush} && delete $heap->{force_flush} ? 'force' : 'schedule';
374  
375 # Record the flush
376 $heap->{stats}{"es_flush_$reason"} ||= 0;
377 $heap->{stats}{"es_flush_$reason"}++;
378  
379 if( $count_docs > 0 ) {
380 # Build the batch
381 my $to = $heap->{es_ready} ? 'batch' : 'save';
382 my $docs = delete $heap->{queue};
383 my $batch = join '', @{ $docs };
384 my $id = sha1_hex($batch);
385 $heap->{batch}{$id} = $batch;
386  
387 DEBUG(sprintf "es_flush(%s) of %d documents to %s, id=%s",
388 $reason,
389 $count_docs,
390 $to,
391 $id,
392 );
393 $kernel->yield( $to => $id );
394 }
395 }
396  
397  
398 sub es_backlog {
399 my ($kernel,$heap) = @_[KERNEL,HEAP];
400  
401 delete $heap->{backlog_scheduled};
402  
403 my $max_batches = $heap->{cfg}{MaxRecoveryBatches};
404 my $batch_dir = path($heap->{cfg}{BatchDir});
405  
406 # randomize
407 my @ids = shuffle map { $_->basename('.batch') }
408 $batch_dir->children( qr/\.batch$/ );
409 $kernel->yield( batch => $_ ) for @ids[0..$max_batches-1];
410  
411 if(@ids > $max_batches) {
412 INFO("Rescheduling backlog run");
413 $kernel->delay( backlog => $heap->{cfg}{BacklogInterval}) unless $heap->{SHUTDOWN};
414 $heap->{backlog_scheduled} = 1;
415 }
416 }
417  
418  
419 sub es_shutdown {
420 $_[HEAP]->{SHUTDOWN} = 1;
421 FATAL("es_shutdown() - Shutting down.");
422 }
423  
424  
425 sub es_batch {
426 my ($kernel,$heap,$id) = @_[KERNEL,HEAP,ARG0];
427  
428 return unless defined $id;
429  
430 # Only process if we're ready
431 if( !$heap->{es_ready} ) {
432 WARN("es_batch() - Connection not ready");
433 # Flush this batch to disk
434 $kernel->yield( save => $id )
435 if exists $heap->{batch}{$id};
436  
437  
438 # Bail and rely on the disk backlog
439 return;
440 }
441  
442 # Get our content
443 my $batch = '';
444 if( exists $heap->{batch}{$id} ) {
445 $batch = delete $heap->{batch}{$id};
446 }
447 else {
448 # Read batch from disk
449 my $batch_file = path($heap->{cfg}{BatchDir})->child($id . '.batch');
450 if( $batch_file->is_file ) {
451 # We need exclusive locking so we can brute force a batch
452 # directory in a batch cleanup mode
453 my $locked = lock_batch_file($batch_file);
454 if( defined $locked && $locked == 1 ) {
455 $batch = $batch_file->slurp_raw;
456 my $lines = $batch =~ tr/\n//;
457 if( $lines > 0 ) {
458 $heap->{stats}{consumed} ||= 0;
459 $heap->{stats}{consumed} += int($lines / 2);
460 }
461 }
462 }
463 else {
464 WARN(sprintf "es_batch(%s) called for an unknown batch.", $id);
465 }
466 }
467 return unless length $batch;
468  
469 # Build the URI
470 my ($server,$port) = split /\:/, $heap->{cfg}{Servers}[int rand scalar @{$heap->{cfg}{Servers}}];
471 my $uri = URI->new();
472 $uri->scheme($heap->{cfg}{Protocol});
473 $uri->host($server);
474 $uri->port($port || 9200);
475 $uri->path('/_bulk');
476  
477 # Build the request
478 my $req = HTTP::Request->new(POST => $uri->as_string);
479 $req->header('Content-Type', 'application/x-ndjson');
480 $req->content($batch);
481  
482 # Use authentication if configured
483 $req->authorization_basic( @{ $heap->{cfg} }{qw(AuthUsername AuthPassword)} )
484 if length $heap->{cfg}{AuthPassword};
485  
486 TRACE(sprintf "Bulk update of %d bytes being attempted to %s as %s.",
487 length($batch),
488 $uri->as_string,
489 $id,
490 );
491 $kernel->post( $heap->{http_alias} => request => resp_bulk => $req => $id );
492 # Record the request
493 $heap->{start}{$id} = time unless exists $heap->{start}{$id};
494 $heap->{stats}{http_req} ||= 0;
495 $heap->{stats}{http_req}++;
496 }
497  
498  
499 sub resp_bulk {
500 my ($kernel,$heap,$params,$resp) = @_[KERNEL,HEAP,ARG0,ARG1];
501  
502 my $req = $params->[0]; # HTTP::Request Object
503 my $id = $params->[1]; # Batch ID
504 my $r = $resp->[0]; # HTTP::Response Object
505 my $duration = exists $heap->{start}{$id} ? time - $heap->{start}{$id} : undef;
506  
507 # We might need to batch things
508 my $batch_file = path($heap->{cfg}{BatchDir})->child($id . '.batch');
509 TRACE(sprintf "bulk_resp(%s) %s", $id, $r->status_line);
510  
511 # Record the responses we receive
512 my $resp_key = "bulk_" . ($r->is_success ? 'success' : 'failure');
513 $heap->{stats}{$resp_key} ||= 0;
514 $heap->{stats}{$resp_key}++;
515  
516 if( $r->is_success ) {
517 my $details;
518 eval {
519 $details = decode_json($r->content);
520 };
521 if( defined $details && ref $details eq 'HASH' ) {
522 DEBUG(sprintf "bulk_resp(%s) size was %d bytes for %d items, took %d ms (elapsed:%0.3fs)%s",
523 $id,
524 length($req->content),
525 scalar(@{$details->{items}}),
526 $details->{took},
527 $duration,
528 $details->{errors} ? ' with errors' : '',
529 );
530 $heap->{stats}{indexed} ||= 0;
531 $heap->{stats}{indexed} += scalar@{ $details->{items} };
532 if( exists $details->{errors} && $details->{errors} ) {
533 $heap->{stats}{errors} ||= 0;
534 $heap->{stats}{errors} += scalar grep { exists $_->{create} && exists $_->{create}{error} } @{ $details->{items} };
535 }
536 }
537 else {
538 WARN(sprintf "bulk_resp(%s) size was %d bytes, (elapsed:%0.3fs) but not valid JSON: %s",
539 $id,
540 length($req->content),
541 $duration,
542 $@,
543 );
544 }
545 # Remove the batch file
546 $batch_file->remove if $batch_file->is_file;
547 # Clear the start time
548 delete $heap->{start}{$id};
549 # This should never happen, but if it does, protect us from memory leaks
550 delete $heap->{batch}{$id} if exists $heap->{batch}{$id};
551 }
552 elsif( !$batch_file->is_file ) {
553 WARN(sprintf "bulk_resp(%s) FAILED in %0.3fs: %s",
554 $id, $duration, $r->status_line,
555 );
556 # Reload the batch into the heap
557 $heap->{batch}{$id} = $req->content;
558 # Write batch to disk
559 $kernel->yield( save => $id );
560 }
561 else {
562 # Make sure we consider running the cleanup
563 $kernel->yield( 'cleanup' ) unless $heap->{cleanup_scheduled};
564 }
565 # Remove the lock
566 unlock_batch_file($batch_file);
567 }
568  
569  
570 sub es_save {
571 my ($kernel,$heap,$id) = @_[KERNEL,HEAP,ARG0];
572  
573 return unless exists $heap->{batch}{$id};
574  
575 my $content = delete $heap->{batch}{$id};
576 my $batch_file = path($heap->{cfg}{BatchDir})->child($id . '.batch');
577 my $duration = exists $heap->{start}{$id} ? time - $heap->{start}{$id} : 0;
578  
579 # Write batch to disk, unless it exists.
580 unless( $batch_file->is_file ) {
581 my $lines = $content =~ tr/\n//;
582 my $items = int( $lines / 2 );
583 DEBUG(sprintf "Storing to File Batch[%s] as %d bytes, %d items. (elapsed:%0.3fs)",
584 $id, length($content), $items, $duration
585 );
586 $batch_file->spew_raw($content);
587 $heap->{stats}{batches} ||= 0;
588 $heap->{stats}{batches}++;
589 $heap->{stats}{backlogged} ||= 0;
590 $heap->{stats}{backlogged} += $items;
591 }
592 unless( $heap->{backlog_scheduled} ) {
593 $kernel->delay( backlog => $heap->{cfg}{BacklogInterval} ) unless $heap->{SHUTDOWN};
594 $heap->{backlog_scheduled} = 1;
595 }
596 }
597  
598  
599 sub es_cleanup {
600 my ($kernel,$heap) = @_[KERNEL,HEAP];
601  
602 # Only run if we need to run
603 return unless $heap->{cfg}{BatchDiskSpace};
604 # Rerun the cleanup
605 delete $heap->{cleanup_scheduled};
606  
607 my $total = 0;
608 my $batch_dir = path($heap->{cfg}{BatchDir});
609 my @files = ();
610  
611 # Check our total size
612 $batch_dir->visit(sub {
613 my $p = shift;
614  
615 # Skip unless it's a batch file
616 return unless $p->basename =~ /\.batch$/;
617  
618 # Figure out the size of our batches
619 # We eval() in case another worker deletes the file
620 eval {
621 my $size = $p->stat->size;
622 my $ctime = $p->stat->ctime;
623 die "Invalid size: $size" unless $size > 0;
624 $total += $size;
625 push @files, {
626 path => $p,
627 size => $size,
628 ctime => $ctime,
629 };
630 1;
631 } or do {
632 my $err = $@;
633 # Yes this is an error, but we don't want it spamming the logs because it's
634 # not that important. We log at DEBUG.
635 DEBUG(sprintf "Error checking status of %s: %s", $p->basename, $err)
636 if $err =~ /Invalid size/;
637 };
638 });
639  
640 # Report words
641 DEBUG("es_cleanup(): BatchDiskSpace is '$heap->{cfg}{BatchDiskSpace}', currently $total bytes");
642  
643 # Delete some stuff
644 if( $total > $heap->{cfg}{BatchDiskSpace} ) {
645 # Sort oldest to newest
646 foreach my $batch ( sort { $a->{ctime} <=> $b->{ctime} } @files ) {
647 # Leave early, leave often
648 last if $total < $heap->{cfg}{BatchDiskSpace};
649 # Handle "we can't get lock"
650 if( ! lock_batch_file($batch->{path}) ) {
651 # If we're not the only worker, maybe someone else removed this
652 $total -= $batch->{size} unless $batch->{path}->is_file;
653 next;
654 }
655 # Otherwise, mop up
656 my $state = 'success';
657 eval {
658 # If we fail, it's because something else delete this file
659 $batch->{path}->remove;
660 1;
661 } or do {
662 my $err = $@;
663 WARN(sprintf "es_cleanup() failed removing %s: %s",
664 $batch->{path}->absolute->stringify,
665 $err,
666 );
667 $state = 'fail';
668 };
669 $heap->{stats}{"cleanup_$state"} ||= 0;
670 $heap->{stats}{"cleanup_$state"}++;
671  
672 unlock_batch_file($batch->{path});
673 $total -= $batch->{size};
674 }
675 }
676 if( $total > 0 ) {
677 $kernel->delay( cleanup => $heap->{cfg}{CleanupInterval} ) unless $heap->{SHUTDOWN};
678 $heap->{cleanup_scheduled} = 1;
679 }
680 }
681  
682 # Closure for Locks
683 {
684 my %_lock = ();
685  
686  
687 sub lock_batch_file {
688 my $batch_file = shift;
689 my $lock_file = path($batch_file->absolute . '.lock');
690 my $id = $lock_file->absolute;
691  
692 my $locked = 0;
693 # We need to try to lock, but Path::Tiny doesn't support exclusive locks on
694 # read operations, so we'll handle that with a lock file.
695 if( !exists $_lock{$id} ) {
696 $locked = eval {
697 open $_lock{$id}, '>', $id or die "Cannot create lock file: $!\n";
698 flock($_lock{$id}, LOCK_EX|LOCK_NB) or die "Unable to attain exclusive lock.";
699 1;
700 };
701 if(!defined $locked) {
702 TRACE(sprintf "lock_batch_file(%s) failed: %s", $id, $@);
703 }
704 }
705 return $locked;
706 }
707  
708  
709 sub unlock_batch_file {
710 my $batch_file = shift;
711 my $lock_file = path($batch_file->absolute . '.lock');
712 my $id = $lock_file->absolute;
713  
714 if(exists $_lock{$id}) {
715 eval {
716 flock($_lock{$id}, LOCK_UN);
717 1;
718 } or do {
719 WARN(sprintf "unlock_batch_file(%s) failed: %s, removing file anyways.", $id, $@);
720 };
721 close( delete $_lock{$id} );
722 $lock_file->remove if $lock_file->is_file;
723 }
724 }
725 }
726  
727 # Return True
728 1;
729  
730 __END__
« script/file-to-elasticsearch.pl ↑ Summary