Class: Fluent::Plugin::ExecFilterOutput

Inherits:
Output
  • Object
show all
Defined in:
lib/fluent/plugin/out_exec_filter.rb

Defined Under Namespace

Classes: ExecutedProcess

Constant Summary collapse

KEYS_FOR_IN_AND_OUT =
{
  'tag_key' => ['in_tag_key', 'out_tag_key'],
  'time_key' => ['in_time_key', 'out_time_key'],
  'time_format' => ['in_time_format', 'out_time_format'],
}
COMPAT_INJECT_PARAMS =
{
  'in_tag_key' => 'tag_key',
  'in_time_key' => 'time_key',
  'in_time_format' => 'time_format',
}
COMPAT_FORMAT_PARAMS =
{
  'in_format' => '@type',
  'in_keys' => 'keys',
}
COMPAT_PARSE_PARAMS =
{
  'out_format' => '@type',
  'out_keys' => 'keys',
  'out_stream_buffer_size' => 'stream_buffer_size',
}
COMPAT_EXTRACT_PARAMS =
{
  'out_tag_key' => 'tag_key',
  'out_time_key' => 'time_key',
  'out_time_format' => 'time_format',
}
NEWLINE =
"\n"

Constants inherited from Output

Output::BUFFER_STATS_KEYS, Output::CHUNKING_FIELD_WARN_NUM, Output::CHUNK_ID_PLACEHOLDER_PATTERN, Output::CHUNK_KEY_PATTERN, Output::CHUNK_KEY_PLACEHOLDER_PATTERN, Output::CHUNK_TAG_PLACEHOLDER_PATTERN, Output::FORMAT_COMPRESSED_MSGPACK_STREAM, Output::FORMAT_COMPRESSED_MSGPACK_STREAM_TIME_INT, Output::FORMAT_MSGPACK_STREAM, Output::FORMAT_MSGPACK_STREAM_TIME_INT, Output::TIMESTAMP_CHECK_BASE_TIME, Output::TIME_KEY_PLACEHOLDER_THRESHOLDS, Output::UNRECOVERABLE_ERRORS

Constants included from Configurable

Configurable::CONFIG_TYPE_REGISTRY

Instance Attribute Summary collapse

Attributes inherited from Output

#as_secondary, #buffer, #chunk_key_accessors, #chunk_key_tag, #chunk_key_time, #chunk_keys, #delayed_commit, #delayed_commit_timeout, #dequeued_chunks, #dequeued_chunks_mutex, #output_enqueue_thread_waiting, #retry, #retry_for_error_chunk, #secondary, #timekey_zone

Attributes included from Fluent::PluginLoggerMixin

#log

Attributes inherited from Base

#under_plugin_development

Instance Method Summary collapse

Methods inherited from Output

#acts_as_secondary, #actual_flush_thread_count, #after_shutdown, #after_start, #backup_chunk, #before_shutdown, #calculate_timekey, #check_slow_flush, #chunk_for_test, #close, #commit_write, #emit_buffered, #emit_count, #emit_events, #emit_records, #emit_size, #emit_sync, #enqueue_thread_run, #enqueue_thread_wait, #execute_chunking, #extract_placeholders, #flush_thread_run, #flush_thread_wakeup, #force_flush, #formatted_to_msgpack_binary, #formatted_to_msgpack_binary?, #generate_format_proc, #get_placeholders_keys, #get_placeholders_tag, #get_placeholders_time, #handle_limit_reached, #handle_stream_simple, #handle_stream_with_custom_format, #handle_stream_with_standard_format, #implement?, #initialize, #interrupt_flushes, #keep_buffer_config_compat, #log_retry_error, #metadata, #next_flush_time, #num_errors, #placeholder_validate!, #placeholder_validators, #prefer_buffered_processing, #prefer_delayed_commit, #process, #retry_state, #rollback_count, #rollback_write, #shutdown, #statistics, #stop, #submit_flush_all, #submit_flush_once, #support_in_v12_style?, #synchronize_in_threads, #synchronize_path, #synchronize_path_in_workers, #try_flush, #try_rollback_all, #try_rollback_write, #try_write, #update_retry_state, #write_count, #write_guard

Methods included from UniqueId::Mixin

#dump_unique_id_hex, #generate_unique_id

Methods included from Fluent::PluginHelper::Mixin

included

Methods included from Fluent::PluginLoggerMixin

included, #initialize

Methods included from Fluent::PluginId

#initialize, #plugin_id, #plugin_id_configured?, #plugin_id_for_test?, #plugin_root_dir, #stop

Methods inherited from Base

#acquire_worker_lock, #after_shutdown, #after_shutdown?, #after_start, #after_started?, #before_shutdown, #before_shutdown?, #called_in_test?, #close, #closed?, #configured?, #context_router, #context_router=, #fluentd_worker_id, #get_lock_path, #has_router?, #initialize, #inspect, #plugin_root_dir, #reloadable_plugin?, #shutdown, #shutdown?, #started?, #stop, #stopped?, #string_safe_encoding, #terminated?

Methods included from SystemConfig::Mixin

#system_config, #system_config_override

Methods included from Configurable

#config, #configure_proxy_generate, #configured_section_create, included, #initialize, lookup_type, register_type

Constructor Details

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

Instance Attribute Details

#formatterObject (readonly)

for tests



79
80
81
# File 'lib/fluent/plugin/out_exec_filter.rb', line 79

def formatter
  @formatter
end

#parserObject (readonly)

for tests



79
80
81
# File 'lib/fluent/plugin/out_exec_filter.rb', line 79

def parser
  @parser
end

Instance Method Details

#configure(conf) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/fluent/plugin/out_exec_filter.rb', line 130

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

  if inject_section = conf.elements('inject').first
    if inject_section.has_key?('time_format')
      inject_section['time_type'] ||= 'string'
    end
  end
  if extract_section = conf.elements('extract').first
    if extract_section.has_key?('time_format')
      extract_section['time_type'] ||= 'string'
    end
  end

  super

  if !@tag && (!@extract_config || !@extract_config.tag_key)
    raise Fluent::ConfigError, "'tag' or '<extract> tag_key </extract>' option is required on exec_filter output"
  end

  @formatter = formatter_create
  @parser = parser_create

  if @remove_prefix
    @removed_prefix_string = @remove_prefix + '.'
    @removed_length = @removed_prefix_string.length
  end
  if @add_prefix
    @added_prefix_string = @add_prefix + '.'
  end

  @respawns = if @child_respawn.nil? || (@child_respawn == 'none') || (@child_respawn == '0')
                0
              elsif (@child_respawn == 'inf') || (@child_respawn == '-1')
                -1
              elsif /^\d+$/.match?(@child_respawn)
                @child_respawn.to_i
              else
                raise ConfigError, "child_respawn option argument invalid: none(or 0), inf(or -1) or positive number"
              end

  @suppress_error_log_interval ||= 0
  @next_log_time = Time.now.to_i
end

#exec_filter_compat_parameters_convert!(conf) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/fluent/plugin/out_exec_filter.rb', line 116

def exec_filter_compat_parameters_convert!(conf)
  KEYS_FOR_IN_AND_OUT.each_pair do |inout, keys|
    if conf.has_key?(inout)
      keys.each do |k|
        conf[k] = conf[inout]
      end
    end
  end
  exec_filter_compat_parameters_copy_to_subsection!(conf, 'inject', COMPAT_INJECT_PARAMS)
  exec_filter_compat_parameters_copy_to_subsection!(conf, 'format', COMPAT_FORMAT_PARAMS)
  exec_filter_compat_parameters_copy_to_subsection!(conf, 'parse', COMPAT_PARSE_PARAMS)
  exec_filter_compat_parameters_copy_to_subsection!(conf, 'extract', COMPAT_EXTRACT_PARAMS)
end

#exec_filter_compat_parameters_copy_to_subsection!(conf, subsection_name, params) ⇒ Object



106
107
108
109
110
111
112
113
114
# File 'lib/fluent/plugin/out_exec_filter.rb', line 106

def exec_filter_compat_parameters_copy_to_subsection!(conf, subsection_name, params)
  return unless conf.elements(subsection_name).empty?
  return unless params.keys.any?{|k| conf.has_key?(k) }
  hash = {}
  params.each_pair do |compat, current|
    hash[current] = conf[compat] if conf.has_key?(compat)
  end
  conf.elements << Fluent::Config::Element.new(subsection_name, '', hash, [])
end

#format(tag, time, record) ⇒ Object



263
264
265
266
267
268
269
270
271
# File 'lib/fluent/plugin/out_exec_filter.rb', line 263

def format(tag, time, record)
  tag = tag_remove_prefix(tag)
  record = inject_values_to_record(tag, time, record)
  if @formatter.formatter_type == :text_per_line
    @formatter.format(tag, time, record).chomp + NEWLINE
  else
    @formatter.format(tag, time, record)
  end
end

#multi_workers_ready?Boolean

Returns:

  • (Boolean)


176
177
178
# File 'lib/fluent/plugin/out_exec_filter.rb', line 176

def multi_workers_ready?
  true
end

#on_record(time, record) ⇒ Object



304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/fluent/plugin/out_exec_filter.rb', line 304

def on_record(time, record)
  tag = extract_tag_from_record(record)
  tag = @added_prefix_string + tag if tag && @add_prefix
  tag ||= @tag
  time ||= extract_time_from_record(record) || Fluent::EventTime.now
  router.emit(tag, time, record)
rescue => e
  if @suppress_error_log_interval == 0 || Time.now.to_i > @next_log_time
    log.error "exec_filter failed to emit", record: Yajl.dump(record), error: e
    log.error_backtrace e.backtrace
    @next_log_time = Time.now.to_i + @suppress_error_log_interval
  end
  router.emit_error_event(tag, time, record, e) if tag && time && record
end

#run(io) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/fluent/plugin/out_exec_filter.rb', line 286

def run(io)
  io.set_encoding(Encoding::ASCII_8BIT)
  case
  when @parser.implement?(:parse_io)
    @parser.parse_io(io, &method(:on_record))
  when @parser.implement?(:parse_partial_data)
    until io.eof?
      @parser.parse_partial_data(io.readpartial(@read_block_size), &method(:on_record))
    end
  when @parser.parser_type == :text_per_line
    io.each_line do |line|
      @parser.parse(line.chomp, &method(:on_record))
    end
  else
    @parser.parse(io.read, &method(:on_record))
  end
end

#startObject



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
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
# File 'lib/fluent/plugin/out_exec_filter.rb', line 182

def start
  super

  @children_mutex = Mutex.new
  @children = []
  @rr = 0

  exit_callback = ->(status){
    c = @children.find{|child| child.pid == status.pid }
    if c
      unless self.stopped?
        log.warn "child process exits with error code", code: status.to_i, status: status.exitstatus, signal: status.termsig
      end
      c.mutex.synchronize do
        (c.writeio && c.writeio.close) rescue nil
        (c.readio && c.readio.close) rescue nil
        c.pid = c.readio = c.writeio = nil
      end
    end
  }
  child_process_callback = ->(index, readio, writeio){
    pid = child_process_id
    c = @children[index]
    writeio.sync = true
    c.mutex.synchronize do
      c.pid = pid
      c.respawns = @respawns
      c.readio = readio
      c.writeio = writeio
    end

    run(readio)
  }
  execute_child_process = ->(index){
    child_process_execute("out_exec_filter_child#{index}".to_sym, @command, on_exit_callback: exit_callback) do |readio, writeio|
      child_process_callback.call(index, readio, writeio)
    end
  }

  @children_mutex.synchronize do
    @num_children.times do |i|
      @children << ExecutedProcess.new(Mutex.new, nil, 0, nil, nil)
      execute_child_process.call(i)
    end
  end

  if @respawns != 0
    thread_create(:out_exec_filter_respawn_monitor) do
      while thread_current_running?
        @children.each_with_index do |c, i|
          if c.mutex && c.mutex.synchronize{ c.pid.nil? && c.respawns != 0 }
            respawns = c.mutex.synchronize do
              c.respawns -= 1 if c.respawns > 0
              c.respawns
            end
            log.info "respawning child process", num: i, respawn_counter: respawns
            execute_child_process.call(i)
          end
        end
        sleep 0.2
      end
    end
  end
end

#tag_remove_prefix(tag) ⇒ Object



252
253
254
255
256
257
258
259
# File 'lib/fluent/plugin/out_exec_filter.rb', line 252

def tag_remove_prefix(tag)
  if @remove_prefix
    if ((tag[0, @removed_length] == @removed_prefix_string) && (tag.length > @removed_length)) || (tag == @removed_prefix_string)
      tag = tag[@removed_length..-1] || ''
    end
  end
  tag
end

#terminateObject



247
248
249
250
# File 'lib/fluent/plugin/out_exec_filter.rb', line 247

def terminate
  @children = []
  super
end

#write(chunk) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/fluent/plugin/out_exec_filter.rb', line 273

def write(chunk)
  try_times = 0
  while true
    r = @rr = (@rr + 1) % @children.length
    if @children[r].pid && writeio = @children[r].writeio
      chunk.write_to(writeio)
      break
    end
    try_times += 1
    raise "no healthy child processes exist" if try_times >= @children.length
  end
end