| 1 | #!/usr/local/bin/perl | ||
| 2 | # PODNAME: file-to-elasticsearch.pl | ||
| 3 | # ABSTRACT: A simple utility to tail a file and index each line as a document in ElasticSearch | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | |||
| 7 | use Getopt::Long::Descriptive qw(describe_options); | ||
| 8 | use Hash::Merge::Simple qw(merge); | ||
| 9 | use JSON::MaybeXS qw(decode_json encode_json); | ||
| 10 | use Log::Log4perl qw(:easy); | ||
| 11 | use Module::Load qw(load); | ||
| 12 | use Module::Loaded qw(is_loaded); | ||
| 13 | use Pod::Usage; | ||
| 14 | use Ref::Util qw(is_arrayref is_hashref); | ||
| 15 | use YAML (); | ||
| 16 | |||
| 17 | sub POE::Kernel::ASSERT_DEFAULT { 1 } | ||
| 18 | use POE qw( | ||
| 19 | Component::ElasticSearch::Indexer | ||
| 20 | Wheel::FollowTail | ||
| 21 | ); | ||
| 22 | |||
| 23 | my %DEFAULT = ( | ||
| 24 | config => '/etc/file-to-elasticsearch.yaml', | ||
| 25 | stats_interval => 60, | ||
| 26 | ); | ||
| 27 | |||
| 28 | my ($opt,$usage) = describe_options('%c %o', | ||
| 29 | ['config|c=s', "Config file, default: $DEFAULT{config}", | ||
| 30 | { default => $DEFAULT{config}, callbacks => { "must be a readable file" => sub { -r $_[0] } } } | ||
| 31 | ], | ||
| 32 | ['log4perl-config|L=s', "Log4perl Configuration to use, defaults to STDERR", | ||
| 33 | { callbacks => { "must be a readable file" => sub { -r $_[0] } } } | ||
| 34 | ], | ||
| 35 | ['stats-interval|s=i', "Seconds between displaying statistics, default: $DEFAULT{stats_interval}", | ||
| 36 | { default => $DEFAULT{stats_interval} }, | ||
| 37 | ], | ||
| 38 | ['debug', "Enable most verbose output" ], | ||
| 39 | [], | ||
| 40 | ['help', "Display this help.", { shortcircuit => 1 }], | ||
| 41 | ['manual|pod', "Display the user manaul.", { shortcircuit => 1 }], | ||
| 42 | ); | ||
| 43 | |||
| 44 | if( $opt->help ) { | ||
| 45 | print $usage->text; | ||
| 46 | exit 0; | ||
| 47 | } | ||
| 48 | pod2usage( -verbose => 2, -exitval => 0 ) if $opt->manual; | ||
| 49 | |||
| 50 | my $config = YAML::LoadFile( $opt->config ); | ||
| 51 | |||
| 52 | # Initialize Logging | ||
| 53 | my $level = $opt->debug ? 'TRACE' : 'DEBUG'; | ||
| 54 | my $loggingConfig = $opt->log4perl_config || \qq{ | ||
| 55 | log4perl.logger = $level, Screen | ||
| 56 | log4perl.appender.Screen = Log::Log4perl::Appender::ScreenColoredLevels | ||
| 57 | log4perl.appender.Screen.layout = PatternLayout | ||
| 58 | log4perl.appender.Screen.layout.ConversionPattern = %d [%P] %p - %m%n | ||
| 59 | }; | ||
| 60 | Log::Log4perl->init($loggingConfig); | ||
| 61 | |||
| 62 | my $main = POE::Session->create( | ||
| 63 | inline_states => { | ||
| 64 | _start => \&main_start, | ||
| 65 | _stop => \&main_stop, | ||
| 66 | _child => \&main_child, | ||
| 67 | stats => \&main_stats, | ||
| 68 | |||
| 69 | got_new_line => \&got_new_line, | ||
| 70 | get_error => \&got_error, | ||
| 71 | log4perl_refresh => \&log4perl_refresh, | ||
| 72 | }, | ||
| 73 | heap => { | ||
| 74 | config => $config, | ||
| 75 | stats => {}, | ||
| 76 | }, | ||
| 77 | ); | ||
| 78 | |||
| 79 | POE::Kernel->run(); | ||
| 80 | exit 0; | ||
| 81 | |||
| 82 | sub main_start { | ||
| 83 | my ($kernel,$heap) = @_[KERNEL,HEAP]; | ||
| 84 | |||
| 85 | my $config = $heap->{config}; | ||
| 86 | my %defaults = ( | ||
| 87 | interval => 5, | ||
| 88 | index => 'files-%Y.%m.%d', | ||
| 89 | type => 'log', | ||
| 90 | ); | ||
| 91 | |||
| 92 | my $files = 0; | ||
| 93 | foreach my $tail ( @{ $config->{tail} } ) { | ||
| 94 | if( -r $tail->{file} ) { | ||
| 95 | my $wheel = POE::Wheel::FollowTail->new( | ||
| 96 | Filename => $tail->{file}, | ||
| 97 | InputEvent => 'got_new_line', | ||
| 98 | ErrorEvent => 'got_error', | ||
| 99 | PollInterval => $tail->{interval} || $defaults{interval}, | ||
| 100 | ); | ||
| 101 | $heap->{wheels}{$wheel->ID} = $wheel; | ||
| 102 | $heap->{instructions}{$wheel->ID} = { | ||
| 103 | %defaults, | ||
| 104 | %{ $tail }, | ||
| 105 | }; | ||
| 106 | $files++; | ||
| 107 | DEBUG(sprintf "Wheel %d tailing %s", $wheel->ID, $tail->{file}); | ||
| 108 | } | ||
| 109 | } | ||
| 110 | |||
| 111 | die sprintf("No files found to tail in %s", $opt->config) unless $files > 0; | ||
| 112 | |||
| 113 | my $es = $config->{elasticsearch} || {}; | ||
| 114 | $heap->{elasticsearch} = POE::Component::ElasticSearch::Indexer->spawn( | ||
| 115 | Alias => 'es', | ||
| 116 | Protocol => $es->{protocol} || 'http', | ||
| 117 | Servers => $es->{servers} || [qw( localhost:9200 )], | ||
| 118 | Timeout => $es->{timeout} || 5, | ||
| 119 | FlushInterval => $es->{flush_interval} || 10, | ||
| 120 | FlushSize => $es->{flush_size} || 100, | ||
| 121 | LoggingConfig => $loggingConfig, | ||
| 122 | StatsInterval => $opt->stats_interval, | ||
| 123 | StatsHandler => sub { | ||
| 124 | my ($stats) = @_; | ||
| 125 | foreach my $k (keys %{ $stats }) { | ||
| 126 | $heap->{stats}{$k} ||= 0; | ||
| 127 | $heap->{stats}{$k}++; | ||
| 128 | } | ||
| 129 | }, | ||
| 130 | exists $es->{index} ? ( DefaultIndex => $es->{index} ) : (), | ||
| 131 | exists $es->{type} ? ( DefaultType => $es->{type} ) : (), | ||
| 132 | ); | ||
| 133 | |||
| 134 | # Watch the Log4perl Config | ||
| 135 | $kernel->delay( log4perl_refresh => 60 ) if $opt->log4perl_config; | ||
| 136 | $kernel->delay( stats => $opt->stats_interval ); | ||
| 137 | |||
| 138 | INFO("Started $0 watching $files files."); | ||
| 139 | } | ||
| 140 | |||
| 141 | sub main_stop { | ||
| 142 | $poe_kernel->post( es => 'shutdown' ); | ||
| 143 | FATAL("Shutting down $0"); | ||
| 144 | } | ||
| 145 | |||
| 146 | sub main_child { | ||
| 147 | my ($kernel,$heap,$reason,$child) = @_[KERNEL,HEAP,ARG0,ARG1]; | ||
| 148 | INFO(sprintf "Child [%d] %s event.", $child->ID, $reason); | ||
| 149 | } | ||
| 150 | |||
| 151 | sub main_stats { | ||
| 152 | my ($kernel,$heap) = @_[KERNEL,HEAP]; | ||
| 153 | |||
| 154 | # Reschedule | ||
| 155 | $kernel->delay( stats => $opt->stats_interval ); | ||
| 156 | |||
| 157 | # Collect our stats | ||
| 158 | my $stats = delete $heap->{stats}; | ||
| 159 | $heap->{stats} = {}; | ||
| 160 | |||
| 161 | # Display them | ||
| 162 | my $message = keys %{ $stats } ? join(", ", map {"$_=$stats->{$_}"} sort keys %{ $stats }) | ||
| 163 | : "Nothing to report."; | ||
| 164 | INFO("STATS - $message"); | ||
| 165 | } | ||
| 166 | |||
| 167 | sub got_error { | ||
| 168 | my ($kernel,$heap,$op,$errnum,$errstr,$wheel_id) = @_[KERNEL,HEAP,ARG0..ARG3]; | ||
| 169 | |||
| 170 | ERROR("Wheel $wheel_id during $op got $errnum : $errstr"); | ||
| 171 | |||
| 172 | # Remove the Wheel from the polling | ||
| 173 | if( exists $heap->{wheels}{$wheel_id} ) { | ||
| 174 | delete $heap->{wheels}{$wheel_id}; | ||
| 175 | $heap->{stats}{wheel_error} ||= 0; | ||
| 176 | $heap->{stats}{wheel_error}++; | ||
| 177 | } | ||
| 178 | |||
| 179 | # Close the ElasticSearch session if this is the last wheel | ||
| 180 | if( !keys %{ $heap->{wheels} } ) { | ||
| 181 | $kernel->post( es => 'shutdown' ); | ||
| 182 | } | ||
| 183 | } | ||
| 184 | |||
| 185 | sub log4perl_refresh { | ||
| 186 | my $kernel = $_[KERNEL]; | ||
| 187 | TRACE("Rescanning Log4perl configuration at" . $opt->log4perl_config); | ||
| 188 | # Reschedule | ||
| 189 | $kernel->delay( log4perl_refresh => 60 ); | ||
| 190 | # Rescan the Log4perl configuration | ||
| 191 | Log::Log4perl::Config->watcher->force_next_check(); | ||
| 192 | return; | ||
| 193 | } | ||
| 194 | |||
| 195 | sub got_new_line { | ||
| 196 | my ($kernel,$heap,$line,$wheel_id) = @_[KERNEL,HEAP,ARG0,ARG1]; | ||
| 197 | |||
| 198 | $heap->{stats}{received} ||= 0; | ||
| 199 | $heap->{stats}{received}++; | ||
| 200 | |||
| 201 | my $instr = $heap->{instructions}{$wheel_id}; | ||
| 202 | |||
| 203 | my $doc; | ||
| 204 | if( $instr->{decode} ) { | ||
| 205 | my $decoders = is_arrayref($instr->{decode}) ? $instr->{decode} : [ $instr->{decode} ]; | ||
| 206 | foreach my $decoder ( @{ $decoders } ) { | ||
| 207 | if( $decoder eq 'json' ) { | ||
| 208 | my $start = index('{', $line); | ||
| 209 | my $blob = $start > 0 ? substr($line,$start) : $line; | ||
| 210 | my $new; | ||
| 211 | eval { | ||
| 212 | $new = decode_json($blob); | ||
| 213 | 1; | ||
| 214 | } or do { | ||
| 215 | my $err = $@; | ||
| 216 | TRACE("Bad JSON, error: $err\n$blob"); | ||
| 217 | next; | ||
| 218 | }; | ||
| 219 | $doc = merge( $doc, $new ); | ||
| 220 | } | ||
| 221 | elsif( $decoder eq 'syslog' ) { | ||
| 222 | unless( is_loaded('Parse::Syslog::Line') ) { | ||
| 223 | eval { | ||
| 224 | load "Parse::Syslog::Line"; | ||
| 225 | 1; | ||
| 226 | } or do { | ||
| 227 | my $err = $@; | ||
| 228 | die "To use the 'syslog' decoder, please install Parse::Syslog::Line: $err"; | ||
| 229 | }; | ||
| 230 | no warnings qw(once); | ||
| 231 | $Parse::Syslog::Line::PruneRaw = 1; | ||
| 232 | } | ||
| 233 | # If we make it here, we're ready to parse | ||
| 234 | $doc = Parse::Syslog::Line::parse_syslog_line($line); | ||
| 235 | } | ||
| 236 | } | ||
| 237 | } | ||
| 238 | |||
| 239 | # Extractors | ||
| 240 | if( my $extracters = $instr->{extract} ) { | ||
| 241 | foreach my $extract( @{ $extracters } ) { | ||
| 242 | # Only process items with a "by" | ||
| 243 | if( $extract->{by} ) { | ||
| 244 | my $from = $extract->{from} ? ( is_hashref($doc) && exists $doc->{$extract->{from}} ? $doc->{$extract->{from}} : undef ) | ||
| 245 | : $line; | ||
| 246 | next unless $from; | ||
| 247 | if( $extract->{when} ) { | ||
| 248 | next unless $from =~ /$extract->{when}/; | ||
| 249 | } | ||
| 250 | if( $extract->{by} eq 'split' ) { | ||
| 251 | next unless $extract->{split_on}; | ||
| 252 | my @parts = split /$extract->{split_on}/, $from; | ||
| 253 | if( my $keys = $extract->{split_parts} ) { | ||
| 254 | # Name parts | ||
| 255 | for( my $i = 0; $i < @parts; $i++ ) { | ||
| 256 | next unless $keys->[$i] and length $keys->[$i] and $parts[$i]; | ||
| 257 | next if lc $keys->[$i] eq 'null' or lc $keys->[$i] eq 'undef'; | ||
| 258 | if( my $into = $extract->{into} ) { | ||
| 259 | # Make sure we have a hash reference | ||
| 260 | $doc ||= {}; | ||
| 261 | $doc->{$into} = {} unless is_hashref($doc->{$into}); | ||
| 262 | $doc->{$into}{$keys->[$i]} = $parts[$i]; | ||
| 263 | } | ||
| 264 | else { | ||
| 265 | $doc ||= {}; | ||
| 266 | $doc->{$keys->[$i]} = $parts[$i]; | ||
| 267 | } | ||
| 268 | } | ||
| 269 | } | ||
| 270 | else { | ||
| 271 | # This is an array, so it's simple | ||
| 272 | my $target = $extract->{into} ? $extract->{into} : $extract->{from}; | ||
| 273 | $doc->{$target} = @parts > 1 ? [ grep { defined and length } @parts ] : $parts[0]; | ||
| 274 | } | ||
| 275 | } | ||
| 276 | elsif( $extract->{by} eq 'regex' ) { | ||
| 277 | # Skip unless it's valid | ||
| 278 | next unless $extract->{regex} and $extract->{regex_parts}; | ||
| 279 | |||
| 280 | if( my @parts = ($from =~ /$extract->{regex}/) ) { | ||
| 281 | # Name parts | ||
| 282 | my $keys = $extract->{regex_parts}; | ||
| 283 | for( my $i = 0; $i < @parts; $i++ ) { | ||
| 284 | next unless $keys->[$i] and length $keys->[$i] and $parts[$i]; | ||
| 285 | next if lc $keys->[$i] eq 'null' or lc $keys->[$i] eq 'undef'; | ||
| 286 | if( my $into = $extract->{into} ) { | ||
| 287 | # Make sure we have a hash reference | ||
| 288 | $doc ||= {}; | ||
| 289 | $doc->{$into} = {} unless is_hashref($doc->{$into}); | ||
| 290 | $doc->{$into}{$keys->[$i]} = $parts[$i]; | ||
| 291 | } | ||
| 292 | else { | ||
| 293 | $doc ||= {}; | ||
| 294 | $doc->{$keys->[$i]} = $parts[$i]; | ||
| 295 | } | ||
| 296 | } | ||
| 297 | } | ||
| 298 | } | ||
| 299 | } | ||
| 300 | } | ||
| 301 | } | ||
| 302 | |||
| 303 | # Skip if the document isn't put together yet | ||
| 304 | return unless $doc; | ||
| 305 | |||
| 306 | $heap->{stats}{docs} ||= 0; | ||
| 307 | $heap->{stats}{docs}++; | ||
| 308 | |||
| 309 | # Store Line in _raw now | ||
| 310 | $doc->{_raw} = $line; | ||
| 311 | $doc->{_path} = $instr->{file}; | ||
| 312 | |||
| 313 | # Mutators | ||
| 314 | if( my $mutate = $instr->{mutate} ) { | ||
| 315 | # Copy | ||
| 316 | if( my $copy = $mutate->{copy} ) { | ||
| 317 | foreach my $k ( keys %{ $copy } ) { | ||
| 318 | my $destinations = is_arrayref($copy->{$k}) ? $copy->{$k} : [ $copy->{$k} ]; | ||
| 319 | foreach my $dst ( @{ $destinations } ) { | ||
| 320 | $doc->{$dst} = $doc->{$k}; | ||
| 321 | } | ||
| 322 | } | ||
| 323 | } | ||
| 324 | # Rename Keys | ||
| 325 | if( my $rename = $mutate->{rename} ) { | ||
| 326 | foreach my $k ( keys %{ $rename } ) { | ||
| 327 | next unless exists $doc->{$k}; | ||
| 328 | $doc->{$rename->{$k}} = delete $doc->{$k}; | ||
| 329 | } | ||
| 330 | } | ||
| 331 | # Remove unwanted keys | ||
| 332 | if( $mutate->{remove} ) { | ||
| 333 | foreach my $k ( @{ $mutate->{remove} } ) { | ||
| 334 | delete $doc->{$k} if exists $doc->{$k}; | ||
| 335 | } | ||
| 336 | } | ||
| 337 | # Append | ||
| 338 | if( my $append = $mutate->{append} ) { | ||
| 339 | foreach my $k ( keys %{ $append } ) { | ||
| 340 | $doc ||= {}; | ||
| 341 | $doc->{$k} = $append->{$k}; | ||
| 342 | } | ||
| 343 | } | ||
| 344 | # Prune empty or undefined keys | ||
| 345 | if( $mutate->{prune} ) { | ||
| 346 | foreach my $k (keys %{ $doc }) { | ||
| 347 | delete $doc->{$k} unless defined $doc->{$k} and length $doc->{$k}; | ||
| 348 | } | ||
| 349 | } | ||
| 350 | } | ||
| 351 | |||
| 352 | foreach my $meta (qw(index type)) { | ||
| 353 | $doc->{"_$meta"} = $instr->{$meta} if exists $instr->{$meta}; | ||
| 354 | } | ||
| 355 | |||
| 356 | if( $opt->debug ) { | ||
| 357 | TRACE("Indexing: " . encode_json($doc)); | ||
| 358 | } | ||
| 359 | |||
| 360 | # Send the document to ElasticSearch | ||
| 361 | $kernel->post( es => queue => $doc ); | ||
| 362 | } | ||
| 363 | |||
| 364 | __END__ |