Class: Fluent::Plugin::OpenSearchOutput

Inherits:
Output
  • Object
show all
Includes:
OpenSearchIndexTemplate, OpenSearchConstants, OpenSearchTLS
Defined in:
lib/fluent/plugin/out_opensearch.rb

Direct Known Subclasses

OpenSearchOutputDataStream

Defined Under Namespace

Classes: MissingIdFieldError, RecoverableRequestFailure, RequestInfo, RetryStreamEmitFailure, RetryStreamError, UnrecoverableRequestFailure

Constant Summary collapse

DEFAULT_BUFFER_TYPE =
"memory"
DEFAULT_OPENSEARCH_VERSION =
1
DEFAULT_TYPE_NAME =
"_doc".freeze
DEFAULT_RELOAD_AFTER =
-1
DEFAULT_TARGET_BULK_BYTES =
-1
DEFAULT_POLICY_ID =
"logstash-policy"

Constants included from OpenSearchTLS

Fluent::Plugin::OpenSearchTLS::DEFAULT_VERSION, Fluent::Plugin::OpenSearchTLS::SUPPORTED_TLS_VERSIONS

Constants included from OpenSearchConstants

Fluent::Plugin::OpenSearchConstants::BODY_DELIMITER, Fluent::Plugin::OpenSearchConstants::CREATE_OP, Fluent::Plugin::OpenSearchConstants::ID_FIELD, Fluent::Plugin::OpenSearchConstants::INDEX_OP, Fluent::Plugin::OpenSearchConstants::TIMESTAMP_FIELD, Fluent::Plugin::OpenSearchConstants::UPDATE_OP, Fluent::Plugin::OpenSearchConstants::UPSERT_OP

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from OpenSearchTLS

included, #set_tls_minmax_version_config

Methods included from OpenSearchIndexTemplate

#get_custom_template, #get_template, #host_unreachable_exceptions, #indexcreation, #retry_operate, #rollover_alias_payload, #template_custom_install, #template_exists?, #template_install, #template_put, #templates_hash_install

Constructor Details

#initializeOpenSearchOutput

Returns a new instance of OpenSearchOutput.



212
213
214
# File 'lib/fluent/plugin/out_opensearch.rb', line 212

def initialize
  super
end

Instance Attribute Details

#compressable_connectionObject (readonly)

Returns the value of attribute compressable_connection.



85
86
87
# File 'lib/fluent/plugin/out_opensearch.rb', line 85

def compressable_connection
  @compressable_connection
end

#ssl_version_optionsObject (readonly)

Returns the value of attribute ssl_version_options.



84
85
86
# File 'lib/fluent/plugin/out_opensearch.rb', line 84

def ssl_version_options
  @ssl_version_options
end

#template_namesObject (readonly)

Returns the value of attribute template_names.



83
84
85
# File 'lib/fluent/plugin/out_opensearch.rb', line 83

def template_names
  @template_names
end

Instance Method Details

#append_record_to_messages(op, meta, header, record, msgs) ⇒ Object

append_record_to_messages adds a record to the bulk message payload to be submitted to OpenSearch. Records that do not include ‘_id’ field are skipped when ‘write_operation’ is configured for ‘create’ or ‘update’

returns ‘true’ if record was appended to the bulk message

and 'false' otherwise


747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'lib/fluent/plugin/out_opensearch.rb', line 747

def append_record_to_messages(op, meta, header, record, msgs)
  case op
  when UPDATE_OP, UPSERT_OP
    if meta.has_key?(ID_FIELD)
      header[UPDATE_OP] = meta
      msgs << @dump_proc.call(header) << BODY_DELIMITER
      msgs << @dump_proc.call(update_body(record, op)) << BODY_DELIMITER
      return true
    end
  when CREATE_OP
    if meta.has_key?(ID_FIELD)
      header[CREATE_OP] = meta
      msgs << @dump_proc.call(header) << BODY_DELIMITER
      msgs << @dump_proc.call(record) << BODY_DELIMITER
      return true
    end
  when INDEX_OP
    header[INDEX_OP] = meta
    msgs << @dump_proc.call(header) << BODY_DELIMITER
    msgs << @dump_proc.call(record) << BODY_DELIMITER
    return true
  end
  return false
end

#aws_credentials(conf) ⇒ Object

This creating AWS credentials code part is heavily based on fluent-plugin-aws-elasticsearch-service: github.com/atomita/fluent-plugin-aws-elasticsearch-service/blob/master/lib/fluent/plugin/out_aws-elasticsearch-service.rb#L73-L134



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/fluent/plugin/out_opensearch.rb', line 220

def aws_credentials(conf)
  credentials = nil
  unless conf[:access_key_id].empty? || conf[:secret_access_key].empty?
    credentials = Aws::Credentials.new(conf[:access_key_id], conf[:secret_access_key])
  else
    if conf[:assume_role_arn].nil?
      aws_container_credentials_relative_uri = conf[:ecs_container_credentials_relative_uri] || ENV["AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"]
      if aws_container_credentials_relative_uri.nil?
        credentials = Aws::SharedCredentials.new({retries: 2}).credentials rescue nil
        credentials ||= Aws::InstanceProfileCredentials.new.credentials rescue nil
        credentials ||= Aws::ECSCredentials.new.credentials
      else
        credentials = Aws::ECSCredentials.new({
                        credential_path: aws_container_credentials_relative_uri
                      }).credentials
      end
    else
      if conf[:assume_role_web_identity_token_file].nil?
        credentials = Aws::AssumeRoleCredentials.new({
                        role_arn: conf[:assume_role_arn],
                        role_session_name: conf[:assume_role_session_name],
                        region: sts_creds_region(conf)
                      }).credentials
      else
        credentials = Aws::AssumeRoleWebIdentityCredentials.new({
                        role_arn: conf[:assume_role_arn],
                        web_identity_token_file: conf[:assume_role_web_identity_token_file],
                        region: sts_creds_region(conf)
                      }).credentials
      end
    end
  end
  raise "No valid AWS credentials found." unless credentials.set?

  credentials
end

#backend_optionsObject



508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/fluent/plugin/out_opensearch.rb', line 508

def backend_options
  case @http_backend
  when :excon
    { client_key: @client_key, client_cert: @client_cert, client_key_pass: @client_key_pass, nonblock: @http_backend_excon_nonblock }
  when :typhoeus
    require 'faraday/typhoeus'
    { sslkey: @client_key, sslcert: @client_cert, keypasswd: @client_key_pass }
  end
rescue LoadError => ex
  log.error_backtrace(ex.backtrace)
  raise Fluent::ConfigError, "You must install #{@http_backend} gem. Exception: #{ex}"
end

#client(host = nil, compress_connection = false) ⇒ Object



613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/fluent/plugin/out_opensearch.rb', line 613

def client(host = nil, compress_connection = false)
  # check here to see if we already have a client connection for the given host
  connection_options = get_connection_options(host)

  @_os = nil unless is_existing_connection(connection_options[:hosts])
  @_os = nil unless @compressable_connection == compress_connection

  @_os ||= begin
    @compressable_connection = compress_connection
    @current_config = connection_options[:hosts].clone
    adapter_conf = if @endpoint
                     lambda do |f|
                       f.request(
                         :aws_sigv4,
                         service: @endpoint.aws_service_name.to_s,
                         region: @endpoint.region,
                         credentials: @_aws_credentials,
                       )

                       f.adapter @http_backend, @backend_options
                     end
                   else
                     lambda {|f| f.adapter @http_backend, @backend_options }
                   end

    local_reload_connections = @reload_connections
    if local_reload_connections && @reload_after > DEFAULT_RELOAD_AFTER
      local_reload_connections = @reload_after
    end

    gzip_headers = if compress_connection
                     {'Content-Encoding' => 'gzip'}
                   else
                     {}
                   end
    headers = {}.merge(@custom_headers)
                .merge(gzip_headers)
    ssl_options = { verify: @ssl_verify, ca_file: @ca_file}.merge(@ssl_version_options)

    transport = OpenSearch::Transport::Transport::HTTP::Faraday.new(connection_options.merge(
                                                                        options: {
                                                                          reload_connections: local_reload_connections,
                                                                          reload_on_failure: @reload_on_failure,
                                                                          resurrect_after: @resurrect_after,
                                                                          logger: @transport_logger,
                                                                          transport_options: {
                                                                            headers: headers,
                                                                            request: { timeout: @request_timeout },
                                                                            ssl: ssl_options,
                                                                          },
                                                                          http: {
                                                                            user: @user,
                                                                            password: @password,
                                                                            scheme: @scheme
                                                                          },
                                                                          sniffer_class: @sniffer_class,
                                                                          serializer_class: @serializer_class,
                                                                          selector_class: @selector_class,
                                                                          compression: compress_connection,
                                                                        }), &adapter_conf)
    OpenSearch::Client.new transport: transport
  end
end

#client_library_versionObject



546
547
548
# File 'lib/fluent/plugin/out_opensearch.rb', line 546

def client_library_version
  OpenSearch::VERSION
end

#compressionObject



491
492
493
# File 'lib/fluent/plugin/out_opensearch.rb', line 491

def compression
  !(@compression_level == :no_compression)
end

#compression_strategyObject



495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/fluent/plugin/out_opensearch.rb', line 495

def compression_strategy
  case @compression_level
  when :default_compression
    Zlib::DEFAULT_COMPRESSION
  when :best_compression
    Zlib::BEST_COMPRESSION
  when :best_speed
    Zlib::BEST_SPEED
  else
    Zlib::NO_COMPRESSION
  end
end

#configure(conf) ⇒ Object

AWS credential part is ended.

Raises:

  • (Fluent::ConfigError)


264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/fluent/plugin/out_opensearch.rb', line 264

def configure(conf)
  compat_parameters_convert(conf, :buffer)

  super

  if @endpoint
    # here overrides default value of reload_connections to false because
    # AWS Elasticsearch Service doesn't return addresses of nodes and Elasticsearch client
    # fails to reload connections properly. This ends up "temporarily failed to flush the buffer"
    # error repeating forever. See this discussion for details:
    # https://discuss.elastic.co/t/elasitcsearch-ruby-raises-cannot-get-new-connection-from-pool-error/36252
    @reload_connections = false
  end

  if placeholder_substitution_needed_for_template?
    # nop.
  elsif not @buffer_config.chunk_keys.include? "tag" and
    not @buffer_config.chunk_keys.include? "_index"
    raise Fluent::ConfigError, "'tag' or '_index' in chunk_keys is required."
  end
  @time_parser = create_time_parser
  @backend_options = backend_options
  @ssl_version_options = set_tls_minmax_version_config(@ssl_version, @ssl_max_version, @ssl_min_version)

  if @remove_keys
    @remove_keys = @remove_keys.split(/\s*,\s*/)
  end

  if @target_index_key && @target_index_key.is_a?(String)
    @target_index_key = @target_index_key.split '.'
  end

  if @remove_keys_on_update && @remove_keys_on_update.is_a?(String)
    @remove_keys_on_update = @remove_keys_on_update.split ','
  end

  raise Fluent::ConfigError, "'max_retry_putting_template' must be greater than or equal to zero." if @max_retry_putting_template < 0
  raise Fluent::ConfigError, "'max_retry_get_os_version' must be greater than or equal to zero." if @max_retry_get_os_version < 0

  # Dump log when using host placeholders and template features at same time.
  valid_host_placeholder = placeholder?(:host_placeholder, @host)
  if valid_host_placeholder && (@template_name && @template_file || @templates)
    if @verify_os_version_at_startup
      raise Fluent::ConfigError, "host placeholder, template installation, and verify OpenSearch version at startup are exclusive feature at same time. Please specify verify_os_version_at_startup as `false` when host placeholder and template installation are enabled."
    end
    log.info "host placeholder and template installation makes your OpenSearch cluster a bit slow down(beta)."
  end

  @template_names = []
  if !dry_run?
    if @template_name && @template_file
      if @logstash_format || placeholder_substitution_needed_for_template?
        class << self
          alias_method :template_installation, :template_installation_actual
        end
      else
        template_installation_actual(@template_name, @customize_template, @application_name, @index_name)
      end
    end
    if @templates
      retry_operate(@max_retry_putting_template,
                    @fail_on_putting_template_retry_exceed,
                    @catch_transport_exception_on_retry) do
        templates_hash_install(@templates, @template_overwrite)
      end
    end
  end

  @truncate_mutex = Mutex.new
  if @truncate_caches_interval
    timer_execute(:out_opensearch_truncate_caches, @truncate_caches_interval) do
      log.info('Clean up the indices and template names cache')

      @truncate_mutex.synchronize {
        @template_names.clear
      }
    end
  end
  # If AWS credentials is set, consider to expire credentials information forcibly before expired.
  @credential_mutex = Mutex.new
  if @endpoint
    @_aws_credentials = aws_credentials(@endpoint)

    if @endpoint.refresh_credentials_interval
      timer_execute(:out_opensearch_expire_credentials, @endpoint.refresh_credentials_interval) do
        log.debug('Recreate the AWS credentials')

        @credential_mutex.synchronize do
          @_os = nil
          @_aws_credentials = aws_credentials(@endpoint)
        end
      end
    end
  end

  @serializer_class = nil
  begin
    require 'oj'
    @dump_proc = Oj.method(:dump)
    if @prefer_oj_serializer
      @serializer_class = Fluent::Plugin::Serializer::Oj
      OpenSearch::API.settings[:serializer] = Fluent::Plugin::Serializer::Oj
    end
  rescue LoadError
    @dump_proc = Yajl.method(:dump)
  end

  raise Fluent::ConfigError, "`password` must be present if `user` is present" if @user && @password.nil?

  if @user && m = @user.match(/%{(?<user>.*)}/)
    @user = URI.encode_www_form_component(m["user"])
  end
  if @password && m = @password.match(/%{(?<password>.*)}/)
    @password = URI.encode_www_form_component(m["password"])
  end

  @transport_logger = nil
  if @with_transporter_log
    @transport_logger = log
    log_level = conf['@log_level'] || conf['log_level']
    log.warn "Consider to specify log_level with @log_level." unless log_level
  end
  # Specify @sniffer_class before calling #client.
  # #detect_os_major_version uses #client.
  @sniffer_class = nil
  begin
    @sniffer_class = Object.const_get(@sniffer_class_name) if @sniffer_class_name
  rescue Exception => ex
    raise Fluent::ConfigError, "Could not load sniffer class #{@sniffer_class_name}: #{ex}"
  end

  @selector_class = nil
  begin
    @selector_class = Object.const_get(@selector_class_name) if @selector_class_name
  rescue Exception => ex
    raise Fluent::ConfigError, "Could not load selector class #{@selector_class_name}: #{ex}"
  end

  @last_seen_major_version = if major_version = handle_last_seen_os_major_version
                               major_version
                             else
                               @default_opensearch_version
                             end

  if @validate_client_version && !dry_run?
    if @last_seen_major_version != client_library_version.to_i
      raise Fluent::ConfigError, <<-EOC
        Detected OpenSearch #{@last_seen_major_version} but you use OpenSearch client #{client_library_version}.
        Please consider to use #{@last_seen_major_version}.x series OpenSearch client.
      EOC
    end
  end

  if @last_seen_major_version >= 1
    case @ssl_version
    when :SSLv23, :TLSv1, :TLSv1_1
      if @scheme == :https
        log.warn "Detected OpenSearch 1.x or above and enabled insecure security:
                  You might have to specify `ssl_version TLSv1_2` in configuration."
      end
    end
  end

  if @ssl_version && @scheme == :https
    if !@http_backend_excon_nonblock
      log.warn "TLS handshake will be stucked with block connection.
                Consider to set `http_backend_excon_nonblock` as true"
    end
  end

  # Consider missing the prefix of "$." in nested key specifiers.
  @id_key = convert_compat_id_key(@id_key) if @id_key
  @parent_key = convert_compat_id_key(@parent_key) if @parent_key
  @routing_key = convert_compat_id_key(@routing_key) if @routing_key

  @routing_key_name = configure_routing_key_name
  @meta_config_map = create_meta_config_map
  @current_config = nil
  @compressable_connection = false

  @ignore_exception_classes = @ignore_exceptions.map do |exception|
    unless Object.const_defined?(exception)
      log.warn "Cannot find class #{exception}. Will ignore it."

      nil
    else
      Object.const_get(exception)
    end
  end.compact

  if @bulk_message_request_threshold < 0
    class << self
      alias_method :split_request?, :split_request_size_uncheck?
    end
  else
    class << self
      alias_method :split_request?, :split_request_size_check?
    end
  end
end

#configure_routing_key_nameObject



550
551
552
# File 'lib/fluent/plugin/out_opensearch.rb', line 550

def configure_routing_key_name
  'routing'.freeze
end

#connection_options_description(con_host = nil) ⇒ Object



732
733
734
735
736
737
738
# File 'lib/fluent/plugin/out_opensearch.rb', line 732

def connection_options_description(con_host=nil)
  get_connection_options(con_host)[:hosts].map do |host_info|
    attributes = host_info.dup
    attributes[:password] = 'obfuscated' if attributes.has_key?(:password)
    attributes.inspect
  end.join(', ')
end

#convert_compat_id_key(key) ⇒ Object



554
555
556
557
558
559
# File 'lib/fluent/plugin/out_opensearch.rb', line 554

def convert_compat_id_key(key)
  if key.include?('.') && !key.start_with?('$[')
    key = "$.#{key}" unless key.start_with?('$.')
  end
  key
end

#convert_numeric_time_into_string(numeric_time, time_key_format = "%Y-%m-%d %H:%M:%S.%N%z") ⇒ Object



599
600
601
602
# File 'lib/fluent/plugin/out_opensearch.rb', line 599

def convert_numeric_time_into_string(numeric_time, time_key_format = "%Y-%m-%d %H:%M:%S.%N%z")
  numeric_time_parser = Fluent::NumericTimeParser.new(:float)
  Time.at(numeric_time_parser.parse(numeric_time).to_r).strftime(time_key_format)
end

#create_meta_config_mapObject



561
562
563
564
565
566
567
# File 'lib/fluent/plugin/out_opensearch.rb', line 561

def create_meta_config_map
  result = []
  result << [record_accessor_create(@id_key), '_id'] if @id_key
  result << [record_accessor_create(@parent_key), '_parent'] if @parent_key
  result << [record_accessor_create(@routing_key), @routing_key_name] if @routing_key
  result
end

#create_time_parserObject

once fluent v0.14 is released we might be able to use Fluent::Parser::TimeParser, but it doesn’t quite do what we want - if gives

sec,nsec

where as we want something we can call ‘strftime` on…



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'lib/fluent/plugin/out_opensearch.rb', line 572

def create_time_parser
  if @time_key_format
    begin
      # Strptime doesn't support all formats, but for those it does it's
      # blazingly fast.
      strptime = Strptime.new(@time_key_format)
      Proc.new { |value|
        value = convert_numeric_time_into_string(value, @time_key_format) if value.is_a?(Numeric)
        strptime.exec(value).to_datetime
      }
    rescue
      # Can happen if Strptime doesn't recognize the format; or
      # if strptime couldn't be required (because it's not installed -- it's
      # ruby 2 only)
      Proc.new { |value|
        value = convert_numeric_time_into_string(value, @time_key_format) if value.is_a?(Numeric)
        DateTime.strptime(value, @time_key_format)
      }
    end
  else
    Proc.new { |value|
      value = convert_numeric_time_into_string(value) if value.is_a?(Numeric)
      DateTime.parse(value)
    }
  end
end

#detect_os_major_versionObject



533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/fluent/plugin/out_opensearch.rb', line 533

def detect_os_major_version
  @_os_info ||= client.info
  begin
    unless version = @_os_info.dig("version", "number")
      version = @default_opensearch_version
    end
  rescue NoMethodError => e
    log.warn "#{@_os_info} can not dig version information. Assuming OpenSearch #{@default_opensearch_version}", error: e
    version = @default_opensearch_version
  end
  version.to_i
end

#dry_run?Boolean

Returns:

  • (Boolean)


465
466
467
468
469
470
471
# File 'lib/fluent/plugin/out_opensearch.rb', line 465

def dry_run?
  if Fluent::Engine.respond_to?(:dry_run_mode)
    Fluent::Engine.dry_run_mode
  elsif Fluent::Engine.respond_to?(:supervisor_mode)
    Fluent::Engine.supervisor_mode
  end
end

#emit_error_label_event?Boolean

Returns:

  • (Boolean)


487
488
489
# File 'lib/fluent/plugin/out_opensearch.rb', line 487

def emit_error_label_event?
  !!@emit_error_label_event
end

#expand_placeholders(chunk) ⇒ Object



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
# File 'lib/fluent/plugin/out_opensearch.rb', line 812

def expand_placeholders(chunk)
  logstash_prefix = extract_placeholders(@logstash_prefix, chunk)
  logstash_dateformat = extract_placeholders(@logstash_dateformat, chunk)
  index_name = extract_placeholders(@index_name, chunk)
  if @template_name
    template_name = extract_placeholders(@template_name, chunk)
  else
    template_name = nil
  end
  if @customize_template
    customize_template = @customize_template.each_with_object({}) { |(key, value), hash| hash[key] = extract_placeholders(value, chunk) }
  else
    customize_template = nil
  end
  if @application_name
    application_name = extract_placeholders(@application_name, chunk)
  else
    application_name = nil
  end
  if @pipeline
    pipeline = extract_placeholders(@pipeline, chunk)
  else
    pipeline = nil
  end
  return logstash_prefix, logstash_dateformat, index_name, template_name, customize_template, application_name, pipeline
end

#flatten_record(record, prefix = []) ⇒ Object



797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'lib/fluent/plugin/out_opensearch.rb', line 797

def flatten_record(record, prefix=[])
  ret = {}
  if record.is_a? Hash
    record.each { |key, value|
      ret.merge! flatten_record(value, prefix + [key.to_s])
    }
  elsif record.is_a? Array
    # Don't mess with arrays, leave them unprocessed
    ret.merge!({prefix.join(@flatten_hashes_separator) => record})
  else
    return {prefix.join(@flatten_hashes_separator) => record}
  end
  ret
end

#get_affinity_target_indices(chunk) ⇒ Object



917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
# File 'lib/fluent/plugin/out_opensearch.rb', line 917

def get_affinity_target_indices(chunk)
  indices = Hash.new
  if target_index_affinity_enabled?()
    id_key_accessor = record_accessor_create(@id_key)
    ids = Set.new
    chunk.msgpack_each do |time, record|
      next unless record.is_a? Hash
      begin
        ids << id_key_accessor.call(record)
      end
    end
    log.debug("Find affinity target_indices by quering on OpenSearch (write_operation #{@write_operation}) for ids: #{ids.to_a}")
    options = {
      :index => "#{logstash_prefix}#{@logstash_prefix_separator}*",
    }
    query = {
      'query' => { 'ids' => { 'values' => ids.to_a } },
      '_source' => false,
      'sort' => [
        {"_index" => {"order" => "desc"}}
     ]
    }
    result = client.search(options.merge(:body => Yajl.dump(query)))
    # There should be just one hit per _id, but in case there still is multiple, just the oldest index is stored to map
    result['hits']['hits'].each do |hit|
      indices[hit["_id"]] = hit["_index"]
      log.debug("target_index for id: #{hit["_id"]} from es: #{hit["_index"]}")
    end
  end
  indices
end

#get_connection_options(con_host = nil) ⇒ Object



689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/fluent/plugin/out_opensearch.rb', line 689

def get_connection_options(con_host=nil)

  hosts = if @endpoint # For AWS OpenSearch Service
    uri = URI(@endpoint.url)
    host = %w(user password path).inject(host: uri.host, port: uri.port, scheme: uri.scheme) do |hash, key|
      hash[key.to_sym] = uri.public_send(key) unless uri.public_send(key).nil? || uri.public_send(key) == ''
      hash
    end
    [host]
  elsif con_host || @hosts
    (con_host || @hosts).split(',').map do |host_str|
      # Support legacy hosts format host:port,host:port,host:port...
      if host_str.match(%r{^[^:]+(\:\d+)?$})
        {
          host:   host_str.split(':')[0],
          port:   (host_str.split(':')[1] || @port).to_i,
          scheme: @scheme.to_s
        }
      else
        # New hosts format expects URLs such as http://logs.foo.com,https://john:[email protected]/elastic
        uri = URI(get_escaped_userinfo(host_str))
        %w(user password path).inject(host: uri.host, port: uri.port, scheme: uri.scheme) do |hash, key|
          hash[key.to_sym] = uri.public_send(key) unless uri.public_send(key).nil? || uri.public_send(key) == ''
          hash
        end
      end
    end.compact
  else
    if Resolv::IPv6::Regex.match(@host)
      [{host: "[#{@host}]", scheme: @scheme.to_s, port: @port}]
    else
      [{host: @host, port: @port, scheme: @scheme.to_s}]
    end
  end.each do |host|
    host.merge!(user: @user, password: @password) if !host[:user] && @user
    host.merge!(path: @path) if !host[:path] && @path
  end

  {
    hosts: hosts
  }
end

#get_escaped_userinfo(host_str) ⇒ Object



677
678
679
680
681
682
683
684
685
686
687
# File 'lib/fluent/plugin/out_opensearch.rb', line 677

def get_escaped_userinfo(host_str)
  if m = host_str.match(/(?<scheme>.*)%{(?<user>.*)}:%{(?<password>.*)}(?<path>@.*)/)
    m["scheme"] +
      URI.encode_www_form_component(m["user"]) +
      ':' +
      URI.encode_www_form_component(m["password"]) +
      m["path"]
  else
    host_str
  end
end

#get_parent_of(record, path) ⇒ Object

returns [parent, child_key] of child described by path array in record’s tree returns [nil, child_key] if path doesnt exist in record



1042
1043
1044
1045
# File 'lib/fluent/plugin/out_opensearch.rb', line 1042

def get_parent_of(record, path)
  parent_object = path[0..-2].reduce(record) { |a, e| a.is_a?(Hash) ? a[e] : nil }
  [parent_object, path[-1]]
end

#gzip(string) ⇒ Object

gzip compress data



1048
1049
1050
1051
1052
1053
1054
# File 'lib/fluent/plugin/out_opensearch.rb', line 1048

def gzip(string)
  wio = StringIO.new("w")
  w_gz = Zlib::GzipWriter.new(wio, strategy = compression_strategy)
  w_gz.write(string)
  w_gz.close
  wio.string
end

#handle_last_seen_os_major_versionObject



521
522
523
524
525
526
527
528
529
530
531
# File 'lib/fluent/plugin/out_opensearch.rb', line 521

def handle_last_seen_os_major_version
  if @verify_os_version_at_startup && !dry_run?
    retry_operate(@max_retry_get_os_version,
                  @fail_on_detecting_os_version_retry_exceed,
                  @catch_transport_exception_on_retry) do
      detect_os_major_version
    end
  else
    nil
  end
end

#inject_chunk_id_to_record_if_needed(record, chunk_id) ⇒ Object



843
844
845
846
847
848
849
850
# File 'lib/fluent/plugin/out_opensearch.rb', line 843

def inject_chunk_id_to_record_if_needed(record, chunk_id)
  if @metainfo&.include_chunk_id
    record[@metainfo.chunk_id_key] = chunk_id
    record
  else
    record
  end
end

#is_existing_connection(host) ⇒ Object



1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
# File 'lib/fluent/plugin/out_opensearch.rb', line 1143

def is_existing_connection(host)
  # check if the host provided match the current connection
  return false if @_os.nil?
  return false if @current_config.nil?
  return false if host.length != @current_config.length

  for i in 0...host.length
    if !host[i][:host].eql? @current_config[i][:host] || host[i][:port] != @current_config[i][:port]
      return false
    end
  end

  return true
end

#multi_workers_ready?Boolean

Returns:

  • (Boolean)


839
840
841
# File 'lib/fluent/plugin/out_opensearch.rb', line 839

def multi_workers_ready?
  true
end

#parse_time(value, event_time, tag) ⇒ Object



604
605
606
607
608
609
610
611
# File 'lib/fluent/plugin/out_opensearch.rb', line 604

def parse_time(value, event_time, tag)
  @time_parser.call(value)
rescue => e
  if emit_error_label_event?
    router.emit_error_event(@time_parse_error_tag, Fluent::Engine.now, {'tag' => tag, 'time' => event_time, 'format' => @time_key_format, 'value' => value}, e)
  end
  return Time.at(event_time).to_datetime
end

#placeholder?(name, param) ⇒ Boolean

Returns:

  • (Boolean)


473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/fluent/plugin/out_opensearch.rb', line 473

def placeholder?(name, param)
  placeholder_validities = []
  placeholder_validators(name, param).each do |v|
    begin
      v.validate!
      placeholder_validities << true
    rescue Fluent::ConfigError => e
      log.debug("'#{name} #{param}' is tested built-in placeholder(s) but there is no valid placeholder(s). error: #{e}")
      placeholder_validities << false
    end
  end
  placeholder_validities.include?(true)
end

#placeholder_substitution_needed_for_template?Boolean

Returns:

  • (Boolean)


1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
# File 'lib/fluent/plugin/out_opensearch.rb', line 1056

def placeholder_substitution_needed_for_template?
  need_substitution = placeholder?(:host, @host.to_s) ||
    placeholder?(:index_name, @index_name.to_s) ||
    placeholder?(:template_name, @template_name.to_s) ||
    @customize_template&.values&.any? { |value| placeholder?(:customize_template, value.to_s) } ||
    placeholder?(:logstash_prefix, @logstash_prefix.to_s) ||
    placeholder?(:logstash_dateformat, @logstash_dateformat.to_s) ||
    placeholder?(:application_name, @application_name.to_s) ||
  log.debug("Need substitution: #{need_substitution}")
  need_substitution
end

#process_message(tag, meta, header, time, record, affinity_target_indices, extracted_values) ⇒ Object



961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
# File 'lib/fluent/plugin/out_opensearch.rb', line 961

def process_message(tag, meta, header, time, record, affinity_target_indices, extracted_values)
  logstash_prefix, logstash_dateformat, index_name, _template_name, _customize_template, application_name, pipeline = extracted_values

  if @flatten_hashes
    record = flatten_record(record)
  end

  dt = nil
  if @logstash_format || @include_timestamp
    if record.has_key?(TIMESTAMP_FIELD)
      rts = record[TIMESTAMP_FIELD]
      dt = parse_time(rts, time, tag)
    elsif record.has_key?(@time_key)
      rts = record[@time_key]
      dt = parse_time(rts, time, tag)
      record[TIMESTAMP_FIELD] = dt.iso8601(@time_precision) unless @time_key_exclude_timestamp
    else
      dt = Time.at(time).to_datetime
      record[TIMESTAMP_FIELD] = dt.iso8601(@time_precision)
    end
  end

  target_index_parent, target_index_child_key = @target_index_key ? get_parent_of(record, @target_index_key) : nil
  if target_index_parent && target_index_parent[target_index_child_key]
    target_index_alias = target_index = target_index_parent.delete(target_index_child_key)
  elsif @logstash_format
    dt = dt.new_offset(0) if @utc_index
    target_index = "#{logstash_prefix}#{@logstash_prefix_separator}#{dt.strftime(logstash_dateformat)}"
    target_index_alias = "#{logstash_prefix}#{@logstash_prefix_separator}#{application_name}#{@logstash_prefix_separator}#{dt.strftime(logstash_dateformat)}"
  else
    target_index_alias = target_index = index_name
  end

  # Change target_index to lower-case since OpenSearch doesn't
  # allow upper-case characters in index names.
  target_index = target_index.downcase
  target_index_alias = target_index_alias.downcase
  if @include_tag_key
    record[@tag_key] = tag
  end

  # If affinity target indices map has value for this particular id, use it as target_index
  if !affinity_target_indices.empty?
    id_accessor = record_accessor_create(@id_key)
    id_value = id_accessor.call(record)
    if affinity_target_indices.key?(id_value)
      target_index = affinity_target_indices[id_value]
    end
  end

  if @suppress_type_name || @last_seen_major_version >= 2
    target_type = nil
  else
    # OpenSearch only supports "_doc".
    target_type = DEFAULT_TYPE_NAME
  end

  meta.clear
  meta["_index".freeze] = target_index
  meta["_type".freeze] = target_type unless target_type.nil?
  meta["_alias".freeze] = target_index_alias

  if @pipeline
    meta["pipeline".freeze] = pipeline
  end

  @meta_config_map.each do |record_accessor, meta_key|
    if raw_value = record_accessor.call(record)
      meta[meta_key] = raw_value
    end
  end

  if @remove_keys
    @remove_keys.each { |key| record.delete(key) }
  end

  return [meta, header, record]
end

#remove_keys(record) ⇒ Object



788
789
790
791
792
793
794
795
# File 'lib/fluent/plugin/out_opensearch.rb', line 788

def remove_keys(record)
  keys = record[@remove_keys_on_update_key] || @remove_keys_on_update || []
  record.delete(@remove_keys_on_update_key)
  return record unless keys.any?
  record = record.dup
  keys.each { |key| record.delete(key) }
  record
end

#retry_stream_retryable?Boolean

Returns:

  • (Boolean)


1139
1140
1141
# File 'lib/fluent/plugin/out_opensearch.rb', line 1139

def retry_stream_retryable?
  @buffer.storable?
end

#send_bulk(data, tag, chunk, bulk_message_count, extracted_values, info) ⇒ Object

send_bulk given a specific bulk request, the original tag, chunk, and bulk_message_count



1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# File 'lib/fluent/plugin/out_opensearch.rb', line 1093

def send_bulk(data, tag, chunk, bulk_message_count, extracted_values, info)
  _logstash_prefix, _logstash_dateformat, index_name, template_name, customize_template, application_name, _pipeline  = extracted_values
  template_installation(template_name, customize_template, application_name, index_name, info.host)

  begin

    log.on_trace { log.trace "bulk request: #{data}" }

    prepared_data = if compression
                      gzip(data)
                    else
                      data
                    end

    response = client(info.host, compression).bulk body: prepared_data, index: info.index
    log.on_trace { log.trace "bulk response: #{response}" }

    if response['errors']
      error = Fluent::Plugin::OpenSearchErrorHandler.new(self)
      error.handle_error(response, tag, chunk, bulk_message_count, extracted_values)
    end
  rescue RetryStreamError => e
    log.trace "router.emit_stream for retry stream doing..."
    emit_tag = @retry_tag ? @retry_tag : tag
    # check capacity of buffer space
    if retry_stream_retryable?
      router.emit_stream(emit_tag, e.retry_stream)
    else
      raise RetryStreamEmitFailure, "buffer is full."
    end
    log.trace "router.emit_stream for retry stream done."
  rescue => e
    ignore = @ignore_exception_classes.any? { |clazz| e.class <= clazz }

    log.warn "Exception ignored in tag #{tag}: #{e.class.name} #{e.message}" if ignore

    @_os = nil if @reconnect_on_error
    @_os_info = nil if @reconnect_on_error

    raise UnrecoverableRequestFailure if ignore && @exception_backup

    # FIXME: identify unrecoverable errors and raise UnrecoverableRequestFailure instead
    raise RecoverableRequestFailure, "could not push logs to OpenSearch cluster (#{connection_options_description(info.host)}): #{e.message}" unless ignore
  end
end

#split_request?(bulk_message, info) ⇒ Boolean

Returns:

  • (Boolean)


949
950
951
# File 'lib/fluent/plugin/out_opensearch.rb', line 949

def split_request?(bulk_message, info)
  # For safety.
end

#split_request_size_check?(bulk_message, info) ⇒ Boolean

Returns:

  • (Boolean)


953
954
955
# File 'lib/fluent/plugin/out_opensearch.rb', line 953

def split_request_size_check?(bulk_message, info)
  bulk_message[info].size > @bulk_message_request_threshold
end

#split_request_size_uncheck?(bulk_message, info) ⇒ Boolean

Returns:

  • (Boolean)


957
958
959
# File 'lib/fluent/plugin/out_opensearch.rb', line 957

def split_request_size_uncheck?(bulk_message, info)
  false
end

#sts_creds_region(conf) ⇒ Object



257
258
259
# File 'lib/fluent/plugin/out_opensearch.rb', line 257

def sts_creds_region(conf)
  conf[:sts_credentials_region] || conf[:region]
end

#target_index_affinity_enabled?Boolean

Returns:

  • (Boolean)


913
914
915
# File 'lib/fluent/plugin/out_opensearch.rb', line 913

def target_index_affinity_enabled?()
  @target_index_affinity && @logstash_format && @id_key && (@write_operation == UPDATE_OP || @write_operation == UPSERT_OP)
end

#template_installation(template_name, customize_template, application_name, target_index, host) ⇒ Object



1068
1069
1070
# File 'lib/fluent/plugin/out_opensearch.rb', line 1068

def template_installation(template_name, customize_template, application_name, target_index, host)
  # for safety.
end

#template_installation_actual(template_name, customize_template, application_name, target_index, host = nil) ⇒ Object



1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
# File 'lib/fluent/plugin/out_opensearch.rb', line 1072

def template_installation_actual(template_name, customize_template, application_name, target_index, host=nil)
  if template_name && @template_file
    if !@logstash_format && @template_names.include?(template_name)
      log.debug("Template #{template_name} already exists (cached)")
    else
      retry_operate(@max_retry_putting_template,
                    @fail_on_putting_template_retry_exceed,
                    @catch_transport_exception_on_retry) do
        if customize_template
          template_custom_install(template_name, @template_file, @template_overwrite, customize_template, host, target_index, @index_separator)
        else
          template_install(template_name, @template_file, @template_overwrite, host, target_index, @index_separator)
        end
      end
      @template_names << template_name
    end
  end
end

#update_body(record, op) ⇒ Object



772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/fluent/plugin/out_opensearch.rb', line 772

def update_body(record, op)
  update = remove_keys(record)
  if @suppress_doc_wrap
    return update
  end
  body = {"doc".freeze => update}
  if op == UPSERT_OP
    if update == record
      body["doc_as_upsert".freeze] = true
    else
      body[UPSERT_OP] = record
    end
  end
  body
end

#write(chunk) ⇒ Object



852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
# File 'lib/fluent/plugin/out_opensearch.rb', line 852

def write(chunk)
  bulk_message_count = Hash.new { |h,k| h[k] = 0 }
  bulk_message = Hash.new { |h,k| h[k] = '' }
  header = {}
  meta = {}

  tag = chunk..tag
  chunk_id = dump_unique_id_hex(chunk.unique_id)
  extracted_values = expand_placeholders(chunk)
  host = if @hosts
           extract_placeholders(@hosts, chunk)
         else
           extract_placeholders(@host, chunk)
         end

  affinity_target_indices = get_affinity_target_indices(chunk)
  chunk.msgpack_each do |time, record|
    next unless record.is_a? Hash

    record = inject_chunk_id_to_record_if_needed(record, chunk_id)

    begin
      meta, header, record = process_message(tag, meta, header, time, record, affinity_target_indices, extracted_values)
      info = if @include_index_in_url
               RequestInfo.new(host, meta.delete("_index".freeze), meta["_index".freeze], meta.delete("_alias".freeze))
             else
               RequestInfo.new(host, nil, meta["_index".freeze], meta.delete("_alias".freeze))
             end

      if split_request?(bulk_message, info)
        bulk_message.each do |info, msgs|
          send_bulk(msgs, tag, chunk, bulk_message_count[info], extracted_values, info) unless msgs.empty?
          msgs.clear
          # Clear bulk_message_count for this info.
          bulk_message_count[info] = 0;
          next
        end
      end

      if append_record_to_messages(@write_operation, meta, header, record, bulk_message[info])
        bulk_message_count[info] += 1;
      else
        if @emit_error_for_missing_id
          raise MissingIdFieldError, "Missing '_id' field. Write operation is #{@write_operation}"
        else
          log.on_debug { log.debug("Dropping record because its missing an '_id' field and write_operation is #{@write_operation}: #{record}") }
        end
      end
    rescue => e
      if emit_error_label_event?
        router.emit_error_event(tag, time, record, e)
      end
    end
  end

  bulk_message.each do |info, msgs|
    send_bulk(msgs, tag, chunk, bulk_message_count[info], extracted_values, info) unless msgs.empty?
    msgs.clear
  end
end