Class: Fluent::Plugin::OpenSearchOutputDataStream

Inherits:
OpenSearchOutput show all
Defined in:
lib/fluent/plugin/out_opensearch_data_stream.rb

Constant Summary collapse

INVALID_START_CHRACTERS =
["-", "_", "+", "."]
INVALID_CHARACTERS =
["\\", "/", "*", "?", "\"", "<", ">", "|", " ", ",", "#", ":"]

Constants inherited from OpenSearchOutput

Fluent::Plugin::OpenSearchOutput::DEFAULT_BUFFER_TYPE, Fluent::Plugin::OpenSearchOutput::DEFAULT_OPENSEARCH_VERSION, Fluent::Plugin::OpenSearchOutput::DEFAULT_POLICY_ID, Fluent::Plugin::OpenSearchOutput::DEFAULT_RELOAD_AFTER, Fluent::Plugin::OpenSearchOutput::DEFAULT_TARGET_BULK_BYTES, Fluent::Plugin::OpenSearchOutput::DEFAULT_TYPE_NAME

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

Attributes inherited from OpenSearchOutput

#compressable_connection, #ssl_version_options, #template_names

Instance Method Summary collapse

Methods inherited from OpenSearchOutput

#aws_credentials, #backend_options, #client, #compression, #compression_strategy, #configure_routing_key_name, #connection_options_description, #convert_compat_id_key, #convert_numeric_time_into_string, #create_meta_config_map, #create_time_parser, #detect_os_major_version, #dry_run?, #emit_error_label_event?, #expand_placeholders, #flatten_record, #get_affinity_target_indices, #get_connection_options, #get_escaped_userinfo, #get_parent_of, #gzip, #handle_last_seen_os_major_version, #initialize, #inject_chunk_id_to_record_if_needed, #is_existing_connection, #parse_time, #placeholder?, #placeholder_substitution_needed_for_template?, #process_message, #remove_keys, #send_bulk, #split_request?, #split_request_size_check?, #split_request_size_uncheck?, #sts_creds_region, #target_index_affinity_enabled?, #template_installation, #template_installation_actual, #update_body

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_install, #template_put, #templates_hash_install

Constructor Details

This class inherits a constructor from Fluent::Plugin::OpenSearchOutput

Instance Method Details

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



220
221
222
223
224
225
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 220

def append_record_to_messages(op, meta, header, record, msgs)
  header[CREATE_OP] = meta
  msgs << @dump_proc.call(header) << BODY_DELIMITER
  msgs << @dump_proc.call(record) << BODY_DELIMITER
  msgs
end

#client_library_versionObject



145
146
147
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 145

def client_library_version
  OpenSearch::VERSION
end

#configure(conf) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 19

def configure(conf)
  super

  @data_stream_template_name = "#{@data_stream_name}_template" if @data_stream_template_name.nil?

  # ref. https://opensearch.org/docs/latest/opensearch/data-streams/
  unless placeholder?(:data_stream_name_placeholder, @data_stream_name)
    validate_data_stream_parameters
  else
    @use_placeholder = true
    @data_stream_names = []
  end

  unless @use_placeholder
    begin
      @data_stream_names = [@data_stream_name]
      retry_operate(@max_retry_putting_template,
                    @fail_on_putting_template_retry_exceed,
                    @catch_transport_exception_on_retry) do
        create_index_template(@data_stream_name, @data_stream_template_name)
      end
    rescue => e
      raise Fluent::ConfigError, "Failed to create data stream: <#{@data_stream_name}> #{e.message}"
    end
  end
end

#create_index_template(datastream_name, template_name, host = nil) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 70

def create_index_template(datastream_name, template_name, host = nil)
  # Create index template from file
  if !dry_run?
    if @template_file
      return if data_stream_exist?(datastream_name, host) or template_exists?(template_name, host)
      template_installation_actual(template_name, @customize_template, @application_name, datastream_name, host)
    else # Create default index template
      return if data_stream_exist?(datastream_name, host) or template_exists?(template_name, host)
      body = {
        "index_patterns" => ["#{datastream_name}*"],
        "data_stream" => {},
      }

      params = {
        name: template_name,
        body: body
      }
      retry_operate(@max_retry_putting_template,
                    @fail_on_putting_template_retry_exceed,
                    @catch_transport_exception_on_retry) do
        client(host).indices.put_index_template(params)
      end
    end
  end
end

#data_stream_exist?(datastream_name, host = nil) ⇒ Boolean

Returns:

  • (Boolean)


96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 96

def data_stream_exist?(datastream_name, host = nil)
  params = {
    name: datastream_name
  }
  begin
    # TODO: Use X-Pack equivalent performing DataStream operation method on the following line
    response = client(host).perform_request('GET', "/_data_stream/#{datastream_name}", {}, params)
    return (not response.is_a?(OpenSearch::Transport::Transport::Errors::NotFound))
  rescue OpenSearch::Transport::Transport::Errors::NotFound => e
    log.info "Specified data stream does not exist. Will be created: <#{e}>"
    return false
  end
end

#lowercase_only?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


129
130
131
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 129

def lowercase_only?(data_stream_parameter)
  data_stream_parameter.downcase == data_stream_parameter
end

#multi_workers_ready?Boolean

Returns:

  • (Boolean)


149
150
151
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 149

def multi_workers_ready?
  true
end

#not_dots?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


141
142
143
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 141

def not_dots?(data_stream_parameter)
  not (data_stream_parameter == "." or data_stream_parameter == "..")
end

#retry_stream_retryable?Boolean

Returns:

  • (Boolean)


227
228
229
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 227

def retry_stream_retryable?
  @buffer.storable?
end

#start_with_valid_characters?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


137
138
139
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 137

def start_with_valid_characters?(data_stream_parameter)
  not (INVALID_START_CHRACTERS.each.any? do |v| data_stream_parameter.start_with?(v) end)
end

#template_exists?(name, host = nil) ⇒ Boolean

Returns:

  • (Boolean)


110
111
112
113
114
115
116
117
118
119
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 110

def template_exists?(name, host = nil)
  if @use_legacy_template
    client(host).indices.get_template(:name => name)
  else
    client(host).indices.get_index_template(:name => name)
  end
  return true
rescue OpenSearch::Transport::Transport::Errors::NotFound
  return false
end

#valid_characters?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


133
134
135
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 133

def valid_characters?(data_stream_parameter)
  not (INVALID_CHARACTERS.each.any? do |v| data_stream_parameter.include?(v) end)
end

#valid_data_stream_parameters?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


121
122
123
124
125
126
127
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 121

def valid_data_stream_parameters?(data_stream_parameter)
  lowercase_only?(data_stream_parameter) and
    valid_characters?(data_stream_parameter) and
    start_with_valid_characters?(data_stream_parameter) and
    not_dots?(data_stream_parameter) and
    data_stream_parameter.bytes.size <= 255
end

#validate_data_stream_parametersObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 46

def validate_data_stream_parameters
  {"data_stream_name" => @data_stream_name,
   "data_stream_template_name" => @data_stream_template_name}.each do |parameter, value|
    unless valid_data_stream_parameters?(value)
      unless start_with_valid_characters?(value)
        if not_dots?(value)
          raise Fluent::ConfigError, "'#{parameter}' must not start with #{INVALID_START_CHRACTERS.join(",")}: <#{value}>"
        else
          raise Fluent::ConfigError, "'#{parameter}' must not be . or ..: <#{value}>"
        end
      end
      unless valid_characters?(value)
        raise Fluent::ConfigError, "'#{parameter}' must not contain invalid characters #{INVALID_CHARACTERS.join(",")}: <#{value}>"
      end
      unless lowercase_only?(value)
        raise Fluent::ConfigError, "'#{parameter}' must be lowercase only: <#{value}>"
      end
      if value.bytes.size > 255
        raise Fluent::ConfigError, "'#{parameter}' must not be longer than 255 bytes: <#{value}>"
      end
    end
  end
end

#write(chunk) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/fluent/plugin/out_opensearch_data_stream.rb', line 153

def write(chunk)
  data_stream_name = @data_stream_name
  data_stream_template_name = @data_stream_template_name
  host = nil
  if @use_placeholder
    host = if @hosts
             extract_placeholders(@hosts, chunk)
           else
             extract_placeholders(@host, chunk)
           end
    data_stream_name = extract_placeholders(@data_stream_name, chunk).downcase
    data_stream_template_name = extract_placeholders(@data_stream_template_name, chunk).downcase
    begin
      create_index_template(data_stream_name, data_stream_template_name, host)
    rescue => e
      raise Fluent::ConfigError, "Failed to create data stream: <#{data_stream_name}> #{e.message}"
    end
  end

  bulk_message = ""
  headers = {
    CREATE_OP => {}
  }
  tag = chunk..tag
  chunk.msgpack_each do |time, record|
    next unless record.is_a? Hash
    begin
      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)
      else
        dt = Time.at(time).to_datetime
      end
      record.merge!({"@timestamp" => dt.iso8601(@time_precision)})
      if @include_tag_key
        record[@tag_key] = tag
      end
      if @remove_keys
        @remove_keys.each { |key| record.delete(key) }
      end
      bulk_message = append_record_to_messages(CREATE_OP, {}, headers, record, bulk_message)
    rescue => e
      emit_error_label_event do
        router.emit_error_event(tag, time, record, e)
      end
    end
  end

  return if bulk_message.to_s.empty?

  params = {
    index: data_stream_name,
    body: bulk_message
  }
  begin
    response = client(host).bulk(params)
    if response['errors']
      log.error "Could not bulk insert to Data Stream: #{data_stream_name} #{response}"
    end
  rescue => e
    raise RecoverableRequestFailure, "could not push logs to OpenSearch cluster (#{data_stream_name}): #{e.message}"
  end
end