Class: Fluent::Plugin::ElasticsearchOutput
- Inherits:
-
Output
- Object
- Output
- Fluent::Plugin::ElasticsearchOutput
- Includes:
- ElasticsearchIndexTemplate
- Defined in:
- lib/fluent/plugin/out_elasticsearch.rb
Direct Known Subclasses
Defined Under Namespace
Classes: ConnectionFailure
Constant Summary collapse
- DEFAULT_BUFFER_TYPE =
"memory"- BODY_DELIMITER =
"\n".freeze
- UPDATE_OP =
"update".freeze
- UPSERT_OP =
"upsert".freeze
- CREATE_OP =
"create".freeze
- INDEX_OP =
"index".freeze
- ID_FIELD =
"_id".freeze
- TIMESTAMP_FIELD =
"@timestamp".freeze
Instance Method Summary collapse
- #append_record_to_messages(op, meta, header, record, msgs) ⇒ Object
- #client ⇒ Object
- #configure(conf) ⇒ Object
- #connection_options_description ⇒ Object
- #create_meta_config_map ⇒ Object
-
#create_time_parser ⇒ Object
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…
- #expand_placeholders(metadata) ⇒ Object
- #flatten_record(record, prefix = []) ⇒ Object
- #get_connection_options ⇒ Object
- #get_escaped_userinfo(host_str) ⇒ Object
-
#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.
-
#initialize ⇒ ElasticsearchOutput
constructor
A new instance of ElasticsearchOutput.
- #multi_workers_ready? ⇒ Boolean
- #parse_time(value, event_time, tag) ⇒ Object
- #remove_keys(record) ⇒ Object
- #send_bulk(data) ⇒ Object
- #update_body(record, op) ⇒ Object
- #write(chunk) ⇒ Object
Constructor Details
#initialize ⇒ ElasticsearchOutput
Returns a new instance of ElasticsearchOutput.
83 84 85 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 83 def initialize super end |
Instance Method Details
#append_record_to_messages(op, meta, header, record, msgs) ⇒ Object
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 260 def (op, , header, record, msgs) case op when UPDATE_OP, UPSERT_OP if .has_key?(ID_FIELD) header[UPDATE_OP] = msgs << @dump_proc.call(header) << BODY_DELIMITER msgs << @dump_proc.call(update_body(record, op)) << BODY_DELIMITER end when CREATE_OP if .has_key?(ID_FIELD) header[CREATE_OP] = msgs << @dump_proc.call(header) << BODY_DELIMITER msgs << @dump_proc.call(record) << BODY_DELIMITER end when INDEX_OP header[INDEX_OP] = msgs << @dump_proc.call(header) << BODY_DELIMITER msgs << @dump_proc.call(record) << BODY_DELIMITER end end |
#client ⇒ Object
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 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 170 def client @_es ||= begin = { client_key: @client_key, client_cert: @client_cert, client_key_pass: @client_key_pass } adapter_conf = lambda {|f| f.adapter :excon, } transport = Elasticsearch::Transport::Transport::HTTP::Faraday.new(.merge( options: { reload_connections: @reload_connections, reload_on_failure: @reload_on_failure, resurrect_after: @resurrect_after, retry_on_failure: 5, transport_options: { headers: { 'Content-Type' => 'application/json' }, request: { timeout: @request_timeout }, ssl: { verify: @ssl_verify, ca_file: @ca_file, version: @ssl_version } } }), &adapter_conf) es = Elasticsearch::Client.new transport: transport begin raise ConnectionFailure, "Can not reach Elasticsearch cluster (#{})!" unless es.ping rescue *es.transport.host_unreachable_exceptions => e raise ConnectionFailure, "Can not reach Elasticsearch cluster (#{})! #{e.}" end log.info "Connection opened to Elasticsearch cluster => #{}" es end end |
#configure(conf) ⇒ Object
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 87 def configure(conf) compat_parameters_convert(conf, :buffer) super raise Fluent::ConfigError, "'tag' in chunk_keys is required." if not @chunk_key_tag @time_parser = create_time_parser 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 @target_type_key && @target_type_key.is_a?(String) @target_type_key = @target_type_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 if @template_name && @template_file template_install(@template_name, @template_file) elsif @templates templates_hash_install (@templates) end @meta_config_map = begin require 'oj' @dump_proc = Oj.method(:dump) rescue LoadError @dump_proc = Yajl.method(:dump) end 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 end |
#connection_options_description ⇒ Object
244 245 246 247 248 249 250 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 244 def [:hosts].map do |host_info| attributes = host_info.dup attributes[:password] = 'obfuscated' if attributes.has_key?(:password) attributes.inspect end.join(', ') end |
#create_meta_config_map ⇒ Object
134 135 136 137 138 139 140 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 134 def result = [] result << [@id_key, '_id'] if @id_key result << [@parent_key, '_parent'] if @parent_key result << [@routing_key, '_routing'] if @routing_key result end |
#create_time_parser ⇒ Object
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…
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 145 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| 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| DateTime.strptime(value, @time_key_format) } end else Proc.new { |value| DateTime.parse(value) } end end |
#expand_placeholders(metadata) ⇒ Object
318 319 320 321 322 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 318 def () logstash_prefix = extract_placeholders(@logstash_prefix, ) index_name = extract_placeholders(@index_name, ) return logstash_prefix, index_name end |
#flatten_record(record, prefix = []) ⇒ Object
303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 303 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_connection_options ⇒ Object
211 212 213 214 215 216 217 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 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 211 def raise "`password` must be present if `user` is present" if @user && !@password hosts = if @hosts @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 } 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 [{host: @host, port: @port, scheme: @scheme}] 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
199 200 201 202 203 204 205 206 207 208 209 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 199 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
407 408 409 410 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 407 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 |
#multi_workers_ready? ⇒ Boolean
324 325 326 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 324 def multi_workers_ready? true end |
#parse_time(value, event_time, tag) ⇒ Object
163 164 165 166 167 168 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 163 def parse_time(value, event_time, tag) @time_parser.call(value) rescue => e router.emit_error_event(@time_parse_error_tag, Fluent::Engine.now, {'tag' => tag, 'time' => event_time, 'format' => @time_key_format, 'value' => value}, e) return Time.at(event_time).to_datetime end |
#remove_keys(record) ⇒ Object
294 295 296 297 298 299 300 301 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 294 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 |
#send_bulk(data) ⇒ Object
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 412 def send_bulk(data) retries = 0 begin response = client.bulk body: data if response['errors'] log.error "Could not push log to Elasticsearch: #{response}" end rescue *client.transport.host_unreachable_exceptions => e if retries < 2 retries += 1 @_es = nil log.warn "Could not push logs to Elasticsearch, resetting connection and trying again. #{e.}" sleep 2**retries retry end raise ConnectionFailure, "Could not push logs to Elasticsearch after #{retries} retries. #{e.}" rescue Exception @_es = nil if @reconnect_on_error raise end end |
#update_body(record, op) ⇒ Object
281 282 283 284 285 286 287 288 289 290 291 292 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 281 def update_body(record, op) update = remove_keys(record) 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
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 |
# File 'lib/fluent/plugin/out_elasticsearch.rb', line 328 def write(chunk) = '' header = {} = {} tag = chunk..tag logstash_prefix, index_name = (chunk.) chunk.msgpack_each do |time, record| next unless record.is_a? Hash 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] = rts 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 = 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)}" else target_index = index_name end # Change target_index to lower-case since Elasticsearch doesn't # allow upper-case characters in index names. target_index = target_index.downcase if @include_tag_key record[@tag_key] = tag end target_type_parent, target_type_child_key = @target_type_key ? get_parent_of(record, @target_type_key) : nil if target_type_parent && target_type_parent[target_type_child_key] target_type = target_type_parent.delete(target_type_child_key) else target_type = @type_name end .clear ["_index".freeze] = target_index ["_type".freeze] = target_type if @pipeline ["pipeline".freeze] = @pipeline end @meta_config_map.each do |record_key, | [] = record[record_key] if record[record_key] end if @remove_keys @remove_keys.each { |key| record.delete(key) } end (@write_operation, , header, record, ) end send_bulk() unless .empty? .clear end |