Class: Fluent::Plugin::ElasticsearchOutputDataStream

Inherits:
ElasticsearchOutput show all
Defined in:
lib/fluent/plugin/out_elasticsearch_data_stream.rb

Constant Summary collapse

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

Constants inherited from ElasticsearchOutput

Fluent::Plugin::ElasticsearchOutput::DEFAULT_BUFFER_TYPE, Fluent::Plugin::ElasticsearchOutput::DEFAULT_ELASTICSEARCH_VERSION, Fluent::Plugin::ElasticsearchOutput::DEFAULT_POLICY_ID, Fluent::Plugin::ElasticsearchOutput::DEFAULT_RELOAD_AFTER, Fluent::Plugin::ElasticsearchOutput::DEFAULT_TARGET_BULK_BYTES, Fluent::Plugin::ElasticsearchOutput::DEFAULT_TYPE_NAME, Fluent::Plugin::ElasticsearchOutput::DEFAULT_TYPE_NAME_ES_7x

Constants included from ElasticsearchTLS

Fluent::Plugin::ElasticsearchTLS::DEFAULT_VERSION, Fluent::Plugin::ElasticsearchTLS::SUPPORTED_TLS_VERSIONS

Constants included from ElasticsearchIndexLifecycleManagement

Fluent::Plugin::ElasticsearchIndexLifecycleManagement::ILM_DEFAULT_POLICY_PATH

Constants included from ElasticsearchConstants

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

Instance Attribute Summary

Attributes inherited from ElasticsearchOutput

#alias_indexes, #api_key_header, #compressable_connection, #ssl_version_options, #template_names

Instance Method Summary collapse

Methods inherited from ElasticsearchOutput

#backend_options, #client, #cloud_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_es_major_version, #dry_run?, #expand_placeholders, #flatten_record, #get_affinity_target_indices, #get_connection_options, #get_escaped_userinfo, #get_parent_of, #gzip, #handle_last_seen_es_major_version, #initialize, #inject_chunk_id_to_record_if_needed, #is_existing_connection, #is_ipv6_host, #parse_time, #placeholder?, #placeholder_substitution_needed_for_template?, #process_message, #remove_keys, #send_bulk, #setup_api_key, #split_request?, #split_request_size_check?, #split_request_size_uncheck?, #target_index_affinity_enabled?, #template_installation, #template_installation_actual, #update_body

Methods included from ElasticsearchTLS

included, #set_tls_minmax_version_config

Methods included from ElasticsearchIndexLifecycleManagement

#default_policy_payload, #get_ilm_policy, #ilm_policy_put, #setup_ilm, #verify_ilm_working, #xpack_info

Methods included from ElasticsearchIndexTemplate

#create_rollover_alias, #get_custom_template, #get_template, #get_template_name, #host_unreachable_exceptions, #indexcreation, #inject_ilm_settings_to_template, #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::ElasticsearchOutput

Instance Method Details

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



287
288
289
290
291
292
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 287

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



210
211
212
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 210

def client_library_version
  Elasticsearch::VERSION
end

#configure(conf) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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_elasticsearch_data_stream.rb', line 24

def configure(conf)
  super

  if Gem::Version.new(TRANSPORT_CLASS::VERSION) < Gem::Version.new("8.0.0")
    begin
      require 'elasticsearch/api'
      require 'elasticsearch/xpack'
    rescue LoadError
      raise Fluent::ConfigError, "'elasticsearch/api', 'elasticsearch/xpack' are required for <@elasticsearch_data_stream>."
    end
  else
    begin
      require 'elasticsearch/api'
    rescue LoadError
      raise Fluent::ConfigError, "'elasticsearch/api is required for <@elasticsearch_data_stream>."
    end
  end

  @data_stream_ilm_name = "#{@data_stream_name}_policy" if @data_stream_ilm_name.nil?
  @data_stream_template_name = "#{@data_stream_name}_template" if @data_stream_template_name.nil?
  @data_stream_ilm_policy = File.read(File.join(File.dirname(__FILE__), "default-ilm-policy.json")) if @data_stream_ilm_policy.nil?

  # ref. https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-create-data-stream.html
  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_ilm_policy(@data_stream_name, @data_stream_template_name, @data_stream_ilm_name)
        create_index_template(@data_stream_name, @data_stream_template_name, @data_stream_ilm_name)
        create_data_stream(@data_stream_name)
      end
    rescue => e
      raise Fluent::ConfigError, "Failed to create data stream: <#{@data_stream_name}> #{e.message}"
    end
  end
end

#create_data_stream(datastream_name, host = nil) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 150

def create_data_stream(datastream_name, host = nil)
  return if data_stream_exist?(datastream_name, host)
  params = {
    name: datastream_name
  }
  retry_operate(@max_retry_putting_template,
                @fail_on_putting_template_retry_exceed,
                @catch_transport_exception_on_retry) do
    client(host).indices.create_data_stream(params)
  end
end

#create_ilm_policy(datastream_name, template_name, ilm_name, host = nil) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 95

def create_ilm_policy(datastream_name, template_name, ilm_name, host = nil)
  unless @data_stream_ilm_policy_overwrite
    return if data_stream_exist?(datastream_name, host) or template_exists?(template_name, host) or ilm_policy_exists?(ilm_name, host)
  end

  params = {
    body: @data_stream_ilm_policy
  }
  retry_operate(@max_retry_putting_template,
                @fail_on_putting_template_retry_exceed,
                @catch_transport_exception_on_retry) do
    if Gem::Version.new(Elasticsearch::VERSION) >= Gem::Version.new("8.0.0")
      client(host).ilm.put_lifecycle(params.merge(policy: ilm_name))
    else
      client(host).xpack.ilm.put_policy(params.merge(policy_id: ilm_name))
    end
  end
end

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



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 114

def create_index_template(datastream_name, template_name, ilm_name, host = nil)
  return if data_stream_exist?(datastream_name, host) or template_exists?(template_name, host)
  wildcard = @data_stream_template_use_index_patterns_wildcard ? '*' : ''
  body = {
    "index_patterns" => ["#{datastream_name}#{wildcard}"],
    "data_stream" => {},
    "template" => {
      "settings" => {
        "index.lifecycle.name" => "#{ilm_name}"
      }
    }
  }
  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

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

Returns:

  • (Boolean)


137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 137

def data_stream_exist?(datastream_name, host = nil)
  params = {
    name: datastream_name
  }
  begin
    response = client(host).indices.get_data_stream(params)
    return (not response.is_a?(TRANSPORT_CLASS::Transport::Errors::NotFound))
  rescue TRANSPORT_CLASS::Transport::Errors::NotFound => e
    log.info "Specified data stream does not exist. Will be created: <#{e}>"
    return false
  end
end

#ilm_policy_exists?(policy_id, host = nil) ⇒ Boolean

Returns:

  • (Boolean)


162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 162

def ilm_policy_exists?(policy_id, host = nil)
  begin
    if Gem::Version.new(Elasticsearch::VERSION) >= Gem::Version.new("8.0.0")
      client(host).ilm.get_lifecycle(policy: policy_id)
    else
      client(host).ilm.get_policy(policy_id: policy_id)
    end
    true
  rescue
    false
  end
end

#lowercase_only?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


194
195
196
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 194

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

#multi_workers_ready?Boolean

Returns:

  • (Boolean)


214
215
216
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 214

def multi_workers_ready?
  true
end

#not_dots?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


206
207
208
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 206

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

#retry_stream_retryable?Boolean

Returns:

  • (Boolean)


294
295
296
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 294

def retry_stream_retryable?
  @buffer.storable?
end

#start_with_valid_characters?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


202
203
204
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 202

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)


175
176
177
178
179
180
181
182
183
184
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 175

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 TRANSPORT_CLASS::Transport::Errors::NotFound
  return false
end

#valid_characters?(data_stream_parameter) ⇒ Boolean

Returns:

  • (Boolean)


198
199
200
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 198

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)


186
187
188
189
190
191
192
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 186

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



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

def validate_data_stream_parameters
  {"data_stream_name" => @data_stream_name,
   "data_stream_template_name"=> @data_stream_template_name,
   "data_stream_ilm_name" => @data_stream_ilm_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



218
219
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/fluent/plugin/out_elasticsearch_data_stream.rb', line 218

def write(chunk)
  data_stream_name = @data_stream_name
  data_stream_template_name = @data_stream_template_name
  data_stream_ilm_name = @data_stream_ilm_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)
    data_stream_template_name = extract_placeholders(@data_stream_template_name, chunk)
    data_stream_ilm_name = extract_placeholders(@data_stream_ilm_name, chunk)
    unless @data_stream_names.include?(data_stream_name)
      begin
        create_ilm_policy(data_stream_name, data_stream_template_name, data_stream_ilm_name, host)
        create_index_template(data_stream_name, data_stream_template_name, data_stream_ilm_name, host)
        create_data_stream(data_stream_name)
        @data_stream_names << data_stream_name
      rescue => e
        raise Fluent::ConfigError, "Failed to create data stream: <#{data_stream_name}> #{e.message}"
      end
    end
  end

  bulk_message = ""
  headers = {
    CREATE_OP => {}
  }
  tag = chunk..tag
  chunk.msgpack_each do |time, record|
    next unless record.is_a? Hash

    if @include_tag_key
      record[@tag_key] = tag
    end

    begin
      unless record.has_key?("@timestamp")
        record.merge!({"@timestamp" => Time.at(time).iso8601(@time_precision)})
      end
      bulk_message = append_record_to_messages(CREATE_OP, {}, headers, record, bulk_message)
    rescue => e
      router.emit_error_event(tag, time, record, e)
    end
  end

  prepared_data = if compression
    gzip(bulk_message)
  else
    bulk_message
  end

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