repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/in_udp.rb | lib/fluent/plugin/in_udp.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/input'
module Fluent::Plugin
class UdpInput < Input
Fluent::Plugin.register_input('udp', self)
helpers :server, :parser, :extract, :compat_parameters
desc 'Tag of output events.'
config_param :tag, :string
desc 'The port to listen to.'
config_param :port, :integer, default: 5160
desc 'The bind address to listen to.'
config_param :bind, :string, default: '0.0.0.0'
desc "The field name of the client's hostname."
config_param :source_host_key, :string, default: nil, deprecated: "use source_hostname_key instead."
desc "The field name of the client's hostname."
config_param :source_hostname_key, :string, default: nil
desc "The field name of the client's address."
config_param :source_address_key, :string, default: nil
desc "Deprecated parameter. Use message_length_limit instead"
config_param :body_size_limit, :size, default: nil, deprecated: "use message_length_limit instead."
desc "The max bytes of message"
config_param :message_length_limit, :size, default: 4096
desc "Remove newline from the end of incoming payload"
config_param :remove_newline, :bool, default: true
desc "The max size of socket receive buffer. SO_RCVBUF"
config_param :receive_buffer_size, :size, default: nil, deprecated: "use receive_buffer_size in transport section instead."
config_param :blocking_timeout, :time, default: 0.5
# overwrite server plugin to change default to :udp and remove tcp/tls protocol from list
config_section :transport, required: false, multi: false, init: true, param_name: :transport_config do
config_argument :protocol, :enum, list: [:udp], default: :udp
end
def configure(conf)
compat_parameters_convert(conf, :parser)
parser_config = conf.elements('parse').first
unless parser_config
raise Fluent::ConfigError, "<parse> section is required."
end
super
@_event_loop_blocking_timeout = @blocking_timeout
@source_hostname_key ||= @source_host_key if @source_host_key
@message_length_limit = @body_size_limit if @body_size_limit
@parser = parser_create(conf: parser_config)
end
def multi_workers_ready?
true
end
def zero_downtime_restart_ready?
true
end
def start
super
log.info "listening udp socket", bind: @bind, port: @port
server_create(:in_udp_server, @port, proto: :udp, bind: @bind, resolve_name: !!@source_hostname_key, max_bytes: @message_length_limit, receive_buffer_size: @receive_buffer_size) do |data, sock|
data.chomp! if @remove_newline
begin
@parser.parse(data) do |time, record|
unless time && record
log.on_warn { log.warn "pattern not matched", data: data }
next
end
tag = extract_tag_from_record(record)
tag ||= @tag
time ||= extract_time_from_record(record) || Fluent::EventTime.now
record[@source_address_key] = sock.remote_addr if @source_address_key
record[@source_hostname_key] = sock.remote_host if @source_hostname_key
router.emit(tag, time, record)
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/formatter_out_file.rb | lib/fluent/plugin/formatter_out_file.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/formatter'
require 'fluent/time'
require 'json'
module Fluent
module Plugin
class OutFileFormatter < Formatter
include Fluent::Plugin::Newline::Mixin
Plugin.register_formatter('out_file', self)
config_param :output_time, :bool, default: true
config_param :output_tag, :bool, default: true
config_param :delimiter, default: "\t" do |val|
case val
when /SPACE/i then ' '.freeze
when /COMMA/i then ','.freeze
else "\t".freeze
end
end
config_set_default :time_type, :string
config_set_default :time_format, nil # time_format nil => iso8601
def configure(conf)
super
@timef = time_formatter_create
end
def format(tag, time, record)
json_str = JSON.generate(record)
header = ''
header << "#{@timef.format(time)}#{@delimiter}" if @output_time
header << "#{tag}#{@delimiter}" if @output_tag
"#{header}#{json_str}#{@newline}"
ensure
json_str&.clear
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/buf_file.rb | lib/fluent/plugin/buf_file.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fileutils'
require 'fluent/plugin/buffer'
require 'fluent/plugin/buffer/file_chunk'
require 'fluent/system_config'
require 'fluent/variable_store'
module Fluent
module Plugin
class FileBuffer < Fluent::Plugin::Buffer
Plugin.register_buffer('file', self)
include SystemConfig::Mixin
DEFAULT_CHUNK_LIMIT_SIZE = 256 * 1024 * 1024 # 256MB
DEFAULT_TOTAL_LIMIT_SIZE = 64 * 1024 * 1024 * 1024 # 64GB, same with v0.12 (TimeSlicedOutput + buf_file)
desc 'The path where buffer chunks are stored.'
config_param :path, :string, default: nil
desc 'The suffix of buffer chunks'
config_param :path_suffix, :string, default: '.log'
config_set_default :chunk_limit_size, DEFAULT_CHUNK_LIMIT_SIZE
config_set_default :total_limit_size, DEFAULT_TOTAL_LIMIT_SIZE
config_param :file_permission, :string, default: nil # '0644' (Fluent::DEFAULT_FILE_PERMISSION)
config_param :dir_permission, :string, default: nil # '0755' (Fluent::DEFAULT_DIR_PERMISSION)
def initialize
super
@symlink_path = nil
@multi_workers_available = false
@additional_resume_path = nil
@buffer_path = nil
@variable_store = nil
end
def configure(conf)
super
@variable_store = Fluent::VariableStore.fetch_or_build(:buf_file)
multi_workers_configured = owner.system_config.workers > 1
using_plugin_root_dir = false
unless @path
if root_dir = owner.plugin_root_dir
@path = File.join(root_dir, 'buffer')
using_plugin_root_dir = true # plugin_root_dir path contains worker id
else
raise Fluent::ConfigError, "buffer path is not configured. specify 'path' in <buffer>"
end
end
type_of_owner = Plugin.lookup_type_from_class(@_owner.class)
if @variable_store.has_key?(@path) && !called_in_test?
type_using_this_path = @variable_store[@path]
raise ConfigError, "Other '#{type_using_this_path}' plugin already use same buffer path: type = #{type_of_owner}, buffer path = #{@path}"
end
@buffer_path = @path
@variable_store[@buffer_path] = type_of_owner
specified_directory_exists = File.exist?(@path) && File.directory?(@path)
unexisting_path_for_directory = !File.exist?(@path) && !@path.include?('.*')
if specified_directory_exists || unexisting_path_for_directory # directory
if using_plugin_root_dir || !multi_workers_configured
@path = File.join(@path, "buffer.*#{@path_suffix}")
else
@path = File.join(@path, "worker#{fluentd_worker_id}", "buffer.*#{@path_suffix}")
if fluentd_worker_id == 0
# worker 0 always checks unflushed buffer chunks to be resumed (might be created while non-multi-worker configuration)
@additional_resume_path = File.join(File.expand_path("../../", @path), "buffer.*#{@path_suffix}")
end
end
@multi_workers_available = true
else # specified path is file path
if File.basename(@path).include?('.*.')
# valid file path
elsif File.basename(@path).end_with?('.*')
@path = @path + @path_suffix
else
# existing file will be ignored
@path = @path + ".*#{@path_suffix}"
end
@multi_workers_available = false
end
if @dir_permission
@dir_permission = @dir_permission.to_i(8) if @dir_permission.is_a?(String)
else
@dir_permission = system_config.dir_permission || Fluent::DEFAULT_DIR_PERMISSION
end
end
# This method is called only when multi worker is configured
def multi_workers_ready?
unless @multi_workers_available
log.error "file buffer with multi workers should be configured to use directory 'path', or system root_dir and plugin id"
end
@multi_workers_available
end
def start
FileUtils.mkdir_p File.dirname(@path), mode: @dir_permission
super
end
def stop
if @variable_store
@variable_store.delete(@buffer_path)
end
super
end
def persistent?
true
end
def resume
stage = {}
queue = []
exist_broken_file = false
patterns = [@path]
patterns.unshift @additional_resume_path if @additional_resume_path
Dir.glob(escaped_patterns(patterns)) do |path|
next unless File.file?(path)
if owner.respond_to?(:buffer_config) && owner.buffer_config&.flush_at_shutdown
# When `flush_at_shutdown` is `true`, the remaining chunk files during resuming are possibly broken
# since there may be a power failure or similar failure.
log.warn { "restoring buffer file: path = #{path}" }
else
log.debug { "restoring buffer file: path = #{path}" }
end
m = new_metadata() # this metadata will be overwritten by resuming .meta file content
# so it should not added into @metadata_list for now
mode = Fluent::Plugin::Buffer::FileChunk.assume_chunk_state(path)
if mode == :unknown
log.debug "unknown state chunk found", path: path
next
end
begin
chunk = Fluent::Plugin::Buffer::FileChunk.new(m, path, mode, compress: @compress) # file chunk resumes contents of metadata
rescue Fluent::Plugin::Buffer::FileChunk::FileChunkError => e
exist_broken_file = true
handle_broken_files(path, mode, e)
next
end
case chunk.state
when :staged
# unstaged chunk created at Buffer#write_step_by_step is identified as the staged chunk here because FileChunk#assume_chunk_state checks only the file name.
# https://github.com/fluent/fluentd/blob/9d113029d4550ce576d8825bfa9612aa3e55bff0/lib/fluent/plugin/buffer.rb#L663
# This case can happen when fluentd process is killed by signal or other reasons between creating unstaged chunks and changing them to staged mode in Buffer#write
# these chunks(unstaged chunks) has shared the same metadata
# So perform enqueue step again https://github.com/fluent/fluentd/blob/9d113029d4550ce576d8825bfa9612aa3e55bff0/lib/fluent/plugin/buffer.rb#L364
if chunk_size_full?(chunk) || stage.key?(chunk.metadata)
chunk.metadata.seq = 0 # metadata.seq should be 0 for counting @queued_num
queue << chunk.enqueued!
else
stage[chunk.metadata] = chunk
end
when :queued
queue << chunk
end
end
queue.sort_by!{ |chunk| chunk.modified_at }
# If one of the files is corrupted, other files may also be corrupted and be undetected.
# The time periods of each chunk are helpful to check the data.
if exist_broken_file
log.info "Since a broken chunk file was found, it is possible that other files remaining at the time of resuming were also broken. Here is the list of the files."
(stage.values + queue).each { |chunk|
log.info " #{chunk.path}:", :created_at => chunk.created_at, :modified_at => chunk.modified_at
}
end
return stage, queue
end
def generate_chunk(metadata)
# FileChunk generates real path with unique_id
perm = @file_permission || system_config.file_permission
chunk = Fluent::Plugin::Buffer::FileChunk.new(metadata, @path, :create, perm: perm, compress: @compress)
log.debug "Created new chunk", chunk_id: dump_unique_id_hex(chunk.unique_id), metadata: metadata
return chunk
end
def handle_broken_files(path, mode, e)
log.error "found broken chunk file during resume.", :path => path, :mode => mode, :err_msg => e.message
unique_id = Fluent::Plugin::Buffer::FileChunk.unique_id_from_path(path)
backup(unique_id) { |f|
File.open(path, 'rb') { |chunk|
chunk.set_encoding(Encoding::ASCII_8BIT)
chunk.sync = true
chunk.binmode
IO.copy_stream(chunk, f)
}
}
rescue => error
log.error "backup failed. Delete corresponding files.", :err_msg => error.message
ensure
log.warn "disable_chunk_backup is true. #{dump_unique_id_hex(unique_id)} chunk is thrown away." if @disable_chunk_backup
File.unlink(path, path + '.meta') rescue nil
end
def evacuate_chunk(chunk)
unless chunk.is_a?(Fluent::Plugin::Buffer::FileChunk)
raise ArgumentError, "The chunk must be FileChunk, but it was #{chunk.class}."
end
backup_dir = File.join(backup_base_dir, 'buffer', safe_owner_id)
FileUtils.mkdir_p(backup_dir, mode: system_config.dir_permission || Fluent::DEFAULT_DIR_PERMISSION) unless Dir.exist?(backup_dir)
FileUtils.copy([chunk.path, chunk.meta_path], backup_dir)
log.warn "chunk files are evacuated to #{backup_dir}.", chunk_id: dump_unique_id_hex(chunk.unique_id)
rescue => e
log.error "unexpected error while evacuating chunk files.", error: e
end
private
def escaped_patterns(patterns)
patterns.map { |pattern|
# '{' '}' are special character in Dir.glob
pattern.gsub(/[\{\}]/) { |c| "\\#{c}" }
}
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/parser_apache.rb | lib/fluent/plugin/parser_apache.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/parser_regexp'
module Fluent
module Plugin
class ApacheParser < RegexpParser
Plugin.register_parser("apache", self)
config_set_default :expression, /^(?<host>[^ ]*) [^ ]* (?<user>[^ ]*) \[(?<time>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^ ]*) +\S*)?" (?<code>[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)")?$/
config_set_default :time_format, "%d/%b/%Y:%H:%M:%S %z"
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_exec.rb | lib/fluent/plugin/out_exec.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'tempfile'
require 'fluent/plugin/output'
require 'fluent/config/error'
module Fluent::Plugin
class ExecOutput < Output
Fluent::Plugin.register_output('exec', self)
helpers :inject, :formatter, :compat_parameters, :child_process
desc 'The command (program) to execute. The exec plugin passes the path of a TSV file as the last argument'
config_param :command, :string
config_param :command_timeout, :time, default: 270 # 4min 30sec
config_section :format do
config_set_default :@type, 'tsv'
end
config_section :inject do
config_set_default :time_type, :string
config_set_default :localtime, false
end
config_section :buffer do
config_set_default :delayed_commit_timeout, 300 # 5 min
end
attr_reader :formatter # for tests
def configure(conf)
compat_parameters_convert(conf, :inject, :formatter, :buffer, default_chunk_key: 'time')
super
@formatter = formatter_create
end
def multi_workers_ready?
true
end
NEWLINE = "\n"
def format(tag, time, record)
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
def try_write(chunk)
tmpfile = nil
prog = if chunk.respond_to?(:path)
"#{@command} #{chunk.path}"
else
tmpfile = Tempfile.new("fluent-plugin-out-exec-")
tmpfile.binmode
chunk.write_to(tmpfile)
tmpfile.close
"#{@command} #{tmpfile.path}"
end
chunk_id = chunk.unique_id
callback = ->(status){
begin
if tmpfile
tmpfile.delete rescue nil
end
if status && status.success?
commit_write(chunk_id)
elsif status
# #rollback_write will be done automatically if it isn't called at here.
# But it's after command_timeout, and this timeout should be longer than users expectation.
# So here, this plugin calls it explicitly.
rollback_write(chunk_id)
log.warn "command exits with error code", prog: prog, status: status.exitstatus, signal: status.termsig
else
rollback_write(chunk_id)
log.warn "command unexpectedly exits without exit status", prog: prog
end
rescue => e
log.error "unexpected error in child process callback", error: e
end
}
child_process_execute(:out_exec_process, prog, stderr: :connect, immediate: true, parallel: true, mode: [], wait_timeout: @command_timeout, on_exit_callback: callback)
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_forward/load_balancer.rb | lib/fluent/plugin/out_forward/load_balancer.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/output'
require 'fluent/plugin/out_forward/error'
module Fluent::Plugin
class ForwardOutput < Output
class LoadBalancer
def initialize(log)
@log = log
@weight_array = []
@rand_seed = Random.new.seed
@rr = 0
@mutex = Mutex.new
end
def select_healthy_node
error = nil
# Don't care about the change of @weight_array's size while looping since
# it's only used for determining the number of loops and it is not so important.
wlen = @weight_array.size
wlen.times do
node = @mutex.synchronize do
r = @rr % @weight_array.size
@rr = (r + 1) % @weight_array.size
@weight_array[r]
end
next unless node.available?
begin
ret = yield node
return ret, node
rescue
# for load balancing during detecting crashed servers
error = $! # use the latest error
end
end
raise error if error
raise NoNodesAvailable, "no nodes are available"
end
def rebuild_weight_array(nodes)
standby_nodes, regular_nodes = nodes.select { |e| e.weight > 0 }.partition {|n|
n.standby?
}
lost_weight = 0
regular_nodes.each {|n|
unless n.available?
lost_weight += n.weight
end
}
@log.debug("rebuilding weight array", lost_weight: lost_weight)
if lost_weight > 0
standby_nodes.each {|n|
if n.available?
regular_nodes << n
@log.warn "using standby node #{n.host}:#{n.port}", weight: n.weight
lost_weight -= n.weight
break if lost_weight <= 0
end
}
end
weight_array = []
if regular_nodes.empty?
@log.warn('No nodes are available')
@mutex.synchronize do
@weight_array = weight_array
end
return @weight_array
end
gcd = regular_nodes.map {|n| n.weight }.inject(0) {|r,w| r.gcd(w) }
regular_nodes.each {|n|
(n.weight / gcd).times {
weight_array << n
}
}
# for load balancing during detecting crashed servers
coe = (regular_nodes.size * 6) / weight_array.size
weight_array *= coe if coe > 1
r = Random.new(@rand_seed)
weight_array.sort_by! { r.rand }
@mutex.synchronize do
@weight_array = weight_array
end
end
alias select_service select_healthy_node
alias rebalance rebuild_weight_array
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_forward/connection_manager.rb | lib/fluent/plugin/out_forward/connection_manager.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/output'
module Fluent::Plugin
class ForwardOutput < Output
class ConnectionManager
RequestInfo = Struct.new(:state, :shared_key_nonce, :auth)
# @param log [Logger]
# @param secure [Boolean]
# @param connection_factory [Proc]
# @param socket_cache [Fluent::ForwardOutput::SocketCache]
def initialize(log:, secure:, connection_factory:, socket_cache:)
@log = log
@secure = secure
@connection_factory = connection_factory
@socket_cache = socket_cache
end
def stop
@socket_cache && @socket_cache.clear
end
# @param ack [Fluent::Plugin::ForwardOutput::AckHandler::Ack|nil]
def connect(host:, port:, hostname:, ack: nil, &block)
if @socket_cache
return connect_keepalive(host: host, port: port, hostname: hostname, ack: ack, &block)
end
@log.debug('connect new socket')
socket = @connection_factory.call(host, port, hostname)
request_info = RequestInfo.new(@secure ? :helo : :established)
unless block_given?
return [socket, request_info]
end
begin
yield(socket, request_info)
ensure
if ack
ack.enqueue(socket)
else
socket.close_write rescue nil
socket.close rescue nil
end
end
end
def purge_obsolete_socks
unless @socket_cache
raise "Do not call this method without keepalive option"
end
@socket_cache.purge_obsolete_socks
end
def close(sock)
if @socket_cache
@socket_cache.checkin(sock)
else
sock.close_write rescue nil
sock.close rescue nil
end
end
private
def connect_keepalive(host:, port:, hostname:, ack: nil)
request_info = RequestInfo.new(:established)
socket = @socket_cache.checkout_or([host, port, hostname]) do
s = @connection_factory.call(host, port, hostname)
request_info = RequestInfo.new(@secure ? :helo : :established) # overwrite if new connection
s
end
unless block_given?
return [socket, request_info]
end
ret = nil
begin
ret = yield(socket, request_info)
rescue
@socket_cache.revoke(socket)
raise
else
if ack
ack.enqueue(socket)
else
@socket_cache.checkin(socket)
end
end
ret
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_forward/handshake_protocol.rb | lib/fluent/plugin/out_forward/handshake_protocol.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/output'
require 'fluent/plugin/out_forward/error'
require 'digest'
module Fluent::Plugin
class ForwardOutput < Output
class HandshakeProtocol
def initialize(log:, hostname:, shared_key:, password:, username:)
@log = log
@hostname = hostname
@shared_key = shared_key
@password = password
@username = username
@shared_key_salt = generate_salt
end
def invoke(sock, ri, data)
@log.trace __callee__
case ri.state
when :helo
unless check_helo(ri, data)
raise HeloError, 'received invalid helo message'
end
sock.write(generate_ping(ri).to_msgpack)
ri.state = :pingpong
when :pingpong
succeeded, reason = check_pong(ri, data)
unless succeeded
raise PingpongError, reason
end
ri.state = :established
else
raise "BUG: unknown session state: #{ri.state}"
end
end
private
def check_pong(ri, message)
@log.debug('checking pong')
# ['PONG', bool(authentication result), 'reason if authentication failed',
# self_hostname, sha512\_hex(salt + self_hostname + nonce + sharedkey)]
unless message.size == 5 && message[0] == 'PONG'
return false, 'invalid format for PONG message'
end
_pong, auth_result, reason, hostname, shared_key_hexdigest = message
unless auth_result
return false, 'authentication failed: ' + reason
end
if hostname == @hostname
return false, 'same hostname between input and output: invalid configuration'
end
clientside = Digest::SHA512.new.update(@shared_key_salt).update(hostname).update(ri.shared_key_nonce).update(@shared_key).hexdigest
unless shared_key_hexdigest == clientside
return false, 'shared key mismatch'
end
[true, nil]
end
def check_helo(ri, message)
@log.debug('checking helo')
# ['HELO', options(hash)]
unless message.size == 2 && message[0] == 'HELO'
return false
end
opts = message[1] || {}
# make shared_key_check failed (instead of error) if protocol version mismatch exist
ri.shared_key_nonce = opts['nonce'] || ''
ri.auth = opts['auth'] || ''
true
end
def generate_ping(ri)
@log.debug('generating ping')
# ['PING', self_hostname, sharedkey\_salt, sha512\_hex(sharedkey\_salt + self_hostname + nonce + shared_key),
# username || '', sha512\_hex(auth\_salt + username + password) || '']
shared_key_hexdigest = Digest::SHA512.new.update(@shared_key_salt)
.update(@hostname)
.update(ri.shared_key_nonce)
.update(@shared_key)
.hexdigest
ping = ['PING', @hostname, @shared_key_salt, shared_key_hexdigest]
if !ri.auth.empty?
if @username.nil? || @password.nil?
raise PingpongError, "username and password are required"
end
password_hexdigest = Digest::SHA512.new.update(ri.auth).update(@username).update(@password).hexdigest
ping.push(@username, password_hexdigest)
else
ping.push('', '')
end
ping
end
def generate_salt
SecureRandom.hex(16)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_forward/ack_handler.rb | lib/fluent/plugin/out_forward/ack_handler.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/output'
require 'fluent/plugin_helper/socket'
require 'fluent/engine'
require 'fluent/clock'
module Fluent::Plugin
class ForwardOutput < Output
class AckHandler
module Result
SUCCESS = :success
FAILED = :failed
CHUNKID_UNMATCHED = :chunkid_unmatched
end
def initialize(timeout:, log:, read_length:)
@mutex = Mutex.new
@ack_waitings = []
@timeout = timeout
@log = log
@read_length = read_length
@unpacker = Fluent::MessagePackFactory.msgpack_unpacker
end
def collect_response(select_interval)
now = Fluent::Clock.now
sockets = []
results = []
begin
new_list = []
@mutex.synchronize do
@ack_waitings.each do |info|
if info.expired?(now)
# There are 2 types of cases when no response has been received from socket:
# (1) the node does not support sending responses
# (2) the node does support sending response but responses have not arrived for some reasons.
@log.warn 'no response from node. regard it as unavailable.', host: info.node.host, port: info.node.port
results << [info, Result::FAILED]
else
sockets << info.sock
new_list << info
end
end
@ack_waitings = new_list
end
begin
readable_sockets, _, _ = IO.select(sockets, nil, nil, select_interval)
rescue IOError
@log.info "connection closed while waiting for readable sockets"
readable_sockets = nil
end
if readable_sockets
readable_sockets.each do |sock|
results << read_ack_from_sock(sock)
end
end
results.each do |info, ret|
if info.nil?
yield nil, nil, nil, ret
else
yield info.chunk_id, info.node, info.sock, ret
end
end
rescue => e
@log.error 'unexpected error while receiving ack', error: e
@log.error_backtrace
end
end
ACKWaitingSockInfo = Struct.new(:sock, :chunk_id, :chunk_id_base64, :node, :expired_time) do
def expired?(now)
expired_time < now
end
end
Ack = Struct.new(:chunk_id, :node, :handler) do
def enqueue(sock)
handler.enqueue(node, sock, chunk_id)
end
end
def create_ack(chunk_id, node)
Ack.new(chunk_id, node, self)
end
def enqueue(node, sock, cid)
info = ACKWaitingSockInfo.new(sock, cid, Base64.encode64(cid), node, Fluent::Clock.now + @timeout)
@mutex.synchronize do
@ack_waitings << info
end
end
private
def read_ack_from_sock(sock)
begin
raw_data = sock.instance_of?(Fluent::PluginHelper::Socket::WrappedSocket::TLS) ? sock.readpartial(@read_length) : sock.recv(@read_length)
rescue Errno::ECONNRESET, EOFError # ECONNRESET for #recv, #EOFError for #readpartial
raw_data = ''
rescue IOError
@log.info "socket closed while receiving ack response"
return nil, Result::FAILED
end
info = find(sock)
if info.nil?
# The info can be deleted by another thread during `sock.recv()` and `find()`.
# This is OK since another thread has completed to process the ack, so we can skip this.
# Note: exclusion mechanism about `collect_response()` may need to be considered.
@log.debug "could not find the ack info. this ack may be processed by another thread."
return nil, Result::FAILED
elsif raw_data.empty?
# When connection is closed by remote host, socket is ready to read and #recv returns an empty string that means EOF.
# If this happens we assume the data wasn't delivered and retry it.
@log.warn 'destination node closed the connection. regard it as unavailable.', host: info.node.host, port: info.node.port
# info.node.disable!
return info, Result::FAILED
else
@unpacker.feed(raw_data)
res = @unpacker.read
@log.trace 'getting response from destination', host: info.node.host, port: info.node.port, chunk_id: dump_unique_id_hex(info.chunk_id), response: res
if res['ack'] != info.chunk_id_base64
# Some errors may have occurred when ack and chunk id is different, so send the chunk again.
@log.warn 'ack in response and chunk id in sent data are different', chunk_id: dump_unique_id_hex(info.chunk_id), ack: res['ack']
return info, Result::CHUNKID_UNMATCHED
else
@log.trace 'got a correct ack response', chunk_id: dump_unique_id_hex(info.chunk_id)
end
return info, Result::SUCCESS
end
rescue => e
@log.error 'unexpected error while receiving ack message', error: e
@log.error_backtrace
[nil, Result::FAILED]
ensure
delete(info)
end
def dump_unique_id_hex(unique_id)
Fluent::UniqueId.hex(unique_id)
end
def find(sock)
@mutex.synchronize do
@ack_waitings.find { |info| info.sock == sock }
end
end
def delete(info)
@mutex.synchronize do
@ack_waitings.delete(info)
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_forward/socket_cache.rb | lib/fluent/plugin/out_forward/socket_cache.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/output'
module Fluent::Plugin
class ForwardOutput < Output
class SocketCache
TimedSocket = Struct.new(:timeout, :key, :sock)
def initialize(timeout, log)
@log = log
@timeout = timeout
@available_sockets = Hash.new { |obj, k| obj[k] = [] }
@inflight_sockets = {}
@inactive_sockets = []
@mutex = Mutex.new
end
def checkout_or(key)
@mutex.synchronize do
tsock = pick_socket(key)
if tsock
tsock.sock
else
sock = yield
new_tsock = TimedSocket.new(timeout, key, sock)
@log.debug("connect new socket #{new_tsock}")
@inflight_sockets[sock] = new_tsock
new_tsock.sock
end
end
end
def checkin(sock)
@mutex.synchronize do
if (s = @inflight_sockets.delete(sock))
s.timeout = timeout
@available_sockets[s.key] << s
else
@log.debug("there is no socket #{sock}")
end
end
end
def revoke(sock)
@mutex.synchronize do
if (s = @inflight_sockets.delete(sock))
@inactive_sockets << s
else
@log.debug("there is no socket #{sock}")
end
end
end
def purge_obsolete_socks
sockets = []
@mutex.synchronize do
# don't touch @inflight_sockets
@available_sockets.each do |_, socks|
socks.each do |sock|
if expired_socket?(sock)
sockets << sock
socks.delete(sock)
end
end
end
# reuse same object (@available_sockets)
@available_sockets.reject! { |_, v| v.empty? }
sockets += @inactive_sockets
@inactive_sockets.clear
end
sockets.each do |s|
s.sock.close rescue nil
end
end
def clear
sockets = []
@mutex.synchronize do
sockets += @available_sockets.values.flat_map { |v| v }
sockets += @inflight_sockets.values
sockets += @inactive_sockets
@available_sockets.clear
@inflight_sockets.clear
@inactive_sockets.clear
end
sockets.each do |s|
s.sock.close rescue nil
end
end
private
# this method is not thread safe
def pick_socket(key)
if @available_sockets[key].empty?
return nil
end
t = Time.now
if (s = @available_sockets[key].find { |sock| !expired_socket?(sock, time: t) })
@inflight_sockets[s.sock] = @available_sockets[key].delete(s)
s.timeout = timeout
s
else
nil
end
end
def timeout
@timeout && Time.now + @timeout
end
def expired_socket?(sock, time: Time.now)
sock.timeout ? sock.timeout < time : false
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_forward/failure_detector.rb | lib/fluent/plugin/out_forward/failure_detector.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/output'
module Fluent::Plugin
class ForwardOutput < Output
class FailureDetector
PHI_FACTOR = 1.0 / Math.log(10.0)
SAMPLE_SIZE = 1000
def initialize(heartbeat_interval, hard_timeout, init_last)
@heartbeat_interval = heartbeat_interval
@last = init_last
@hard_timeout = hard_timeout
# microsec
@init_gap = (heartbeat_interval * 1e6).to_i
@window = [@init_gap]
end
def hard_timeout?(now)
now - @last > @hard_timeout
end
def add(now)
if @window.empty?
@window << @init_gap
@last = now
else
gap = now - @last
@window << (gap * 1e6).to_i
@window.shift if @window.length > SAMPLE_SIZE
@last = now
end
end
def phi(now)
size = @window.size
return 0.0 if size == 0
# Calculate weighted moving average
mean_usec = 0
fact = 0
@window.each_with_index {|gap,i|
mean_usec += gap * (1+i)
fact += (1+i)
}
mean_usec = mean_usec / fact
# Normalize arrive intervals into 1sec
mean = (mean_usec.to_f / 1e6) - @heartbeat_interval + 1
# Calculate phi of the phi accrual failure detector
t = now - @last - @heartbeat_interval + 1
phi = PHI_FACTOR * t / mean
return phi
end
def sample_size
@window.size
end
def clear
@window.clear
@last = 0
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/out_forward/error.rb | lib/fluent/plugin/out_forward/error.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/output'
module Fluent::Plugin
class ForwardOutput < Output
class Error < StandardError; end
class NoNodesAvailable < Error; end
class ConnectionClosedError < Error; end
class HandshakeError < Error; end
class HeloError < HandshakeError; end
class PingpongError < HandshakeError; end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/in_tail/group_watch.rb | lib/fluent/plugin/in_tail/group_watch.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/input'
module Fluent::Plugin
class TailInput < Fluent::Plugin::Input
module GroupWatchParams
include Fluent::Configurable
DEFAULT_KEY = /.*/
DEFAULT_LIMIT = -1
REGEXP_JOIN = "_"
config_section :group, param_name: :group, required: false, multi: false do
desc 'Regex for extracting group\'s metadata'
config_param :pattern,
:regexp,
default: /^\/var\/log\/containers\/(?<podname>[a-z0-9]([-a-z0-9]*[a-z0-9])?(\/[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)_(?<namespace>[^_]+)_(?<container>.+)-(?<docker_id>[a-z0-9]{64})\.log$/
desc 'Period of time in which the group_line_limit is applied'
config_param :rate_period, :time, default: 5
config_section :rule, param_name: :rule, required: true, multi: true do
desc 'Key-value pairs for grouping'
config_param :match, :hash, value_type: :regexp, default: { namespace: [DEFAULT_KEY], podname: [DEFAULT_KEY] }
desc 'Maximum number of log lines allowed per group over a period of rate_period'
config_param :limit, :integer, default: DEFAULT_LIMIT
end
end
end
module GroupWatch
def self.included(mod)
mod.include GroupWatchParams
end
attr_reader :group_watchers, :default_group_key
def initialize
super
@group_watchers = {}
@group_keys = nil
@default_group_key = nil
end
def configure(conf)
super
unless @group.nil?
## Ensuring correct time period syntax
@group.rule.each { |rule|
raise "Metadata Group Limit >= DEFAULT_LIMIT" unless rule.limit >= GroupWatchParams::DEFAULT_LIMIT
}
@group_keys = Regexp.compile(@group.pattern).named_captures.keys
@default_group_key = ([GroupWatchParams::DEFAULT_KEY] * @group_keys.length).join(GroupWatchParams::REGEXP_JOIN)
## Ensures that "specific" rules (with larger number of `rule.match` keys)
## have a higher priority against "generic" rules (with less number of `rule.match` keys).
## This will be helpful when a file satisfies more than one rule.
@group.rule.sort_by! { |rule| -rule.match.length() }
construct_groupwatchers
@group_watchers[@default_group_key] ||= GroupWatcher.new(@group.rate_period, GroupWatchParams::DEFAULT_LIMIT)
end
end
def add_path_to_group_watcher(path)
return nil if @group.nil?
group_watcher = find_group_from_metadata(path)
group_watcher.add(path) unless group_watcher.include?(path)
group_watcher
end
def remove_path_from_group_watcher(path)
return if @group.nil?
group_watcher = find_group_from_metadata(path)
group_watcher.delete(path)
end
def construct_group_key(named_captures)
match_rule = []
@group_keys.each { |key|
match_rule.append(named_captures.fetch(key, GroupWatchParams::DEFAULT_KEY))
}
match_rule = match_rule.join(GroupWatchParams::REGEXP_JOIN)
match_rule
end
def construct_groupwatchers
@group.rule.each { |rule|
match_rule = construct_group_key(rule.match)
@group_watchers[match_rule] ||= GroupWatcher.new(@group.rate_period, rule.limit)
}
end
def find_group(metadata)
metadata_key = construct_group_key(metadata)
gw_key = @group_watchers.keys.find { |regexp| metadata_key.match?(regexp) && regexp != @default_group_key }
gw_key ||= @default_group_key
@group_watchers[gw_key]
end
def find_group_from_metadata(path)
begin
metadata = @group.pattern.match(path).named_captures
group_watcher = find_group(metadata)
rescue
log.warn "Cannot find group from metadata, Adding file in the default group"
group_watcher = @group_watchers[@default_group_key]
end
group_watcher
end
end
class GroupWatcher
attr_accessor :current_paths, :limit, :number_lines_read, :start_reading_time, :rate_period
FileCounter = Struct.new(
:number_lines_read,
:start_reading_time,
)
def initialize(rate_period = 60, limit = -1)
@current_paths = {}
@rate_period = rate_period
@limit = limit
end
def add(path)
@current_paths[path] = FileCounter.new(0, nil)
end
def include?(path)
@current_paths.key?(path)
end
def size
@current_paths.size
end
def delete(path)
@current_paths.delete(path)
end
def update_reading_time(path)
@current_paths[path].start_reading_time ||= Fluent::Clock.now
end
def update_lines_read(path, value)
@current_paths[path].number_lines_read += value
end
def reset_counter(path)
@current_paths[path].start_reading_time = nil
@current_paths[path].number_lines_read = 0
end
def time_spent_reading(path)
Fluent::Clock.now - @current_paths[path].start_reading_time
end
def limit_time_period_reached?(path)
time_spent_reading(path) < @rate_period
end
def limit_lines_reached?(path)
return true unless include?(path)
return true if @limit == 0
return false if @limit < 0
return false if @current_paths[path].number_lines_read < @limit / size
# update_reading_time(path)
if limit_time_period_reached?(path) # Exceeds limit
true
else # Does not exceed limit
reset_counter(path)
false
end
end
def to_s
super + " current_paths: #{@current_paths} rate_period: #{@rate_period} limit: #{@limit}"
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/in_tail/position_file.rb | lib/fluent/plugin/in_tail/position_file.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/input'
module Fluent::Plugin
class TailInput < Fluent::Plugin::Input
class PositionFile
UNWATCHED_POSITION = 0xffffffffffffffff
POSITION_FILE_ENTRY_REGEX = /^([^\t]+)\t([0-9a-fA-F]+)\t([0-9a-fA-F]+)/.freeze
def self.load(file, follow_inodes, existing_targets, logger:)
pf = new(file, follow_inodes, logger: logger)
pf.load(existing_targets)
pf
end
def initialize(file, follow_inodes, logger: nil)
@file = file
@logger = logger
@file_mutex = Mutex.new
@map = {}
@follow_inodes = follow_inodes
end
def [](target_info)
if m = @map[@follow_inodes ? target_info.ino : target_info.path]
return m
end
@file_mutex.synchronize {
@file.seek(0, IO::SEEK_END)
seek = @file.pos + target_info.path.bytesize + 1
@file.write "#{target_info.path}\t0000000000000000\t0000000000000000\n"
if @follow_inodes
@map[target_info.ino] = FilePositionEntry.new(@file, @file_mutex, seek, 0, 0)
else
@map[target_info.path] = FilePositionEntry.new(@file, @file_mutex, seek, 0, 0)
end
}
end
def unwatch_removed_targets(existing_targets)
@map.reject { |key, entry|
existing_targets.key?(key)
}.each_key { |key|
unwatch_key(key)
}
end
def unwatch(target_info)
unwatch_key(@follow_inodes ? target_info.ino : target_info.path)
end
def load(existing_targets = nil)
compact(existing_targets)
map = {}
@file_mutex.synchronize do
@file.pos = 0
@file.each_line do |line|
m = POSITION_FILE_ENTRY_REGEX.match(line)
next if m.nil?
path = m[1]
pos = m[2].to_i(16)
ino = m[3].to_i(16)
seek = @file.pos - line.bytesize + path.bytesize + 1
if @follow_inodes
map[ino] = FilePositionEntry.new(@file, @file_mutex, seek, pos, ino)
else
map[path] = FilePositionEntry.new(@file, @file_mutex, seek, pos, ino)
end
end
end
@map = map
end
# This method is similar to #compact but it tries to get less lock to avoid a lock contention
def try_compact
last_modified = nil
size = nil
@file_mutex.synchronize do
size = @file.size
last_modified = @file.mtime
end
entries = fetch_compacted_entries
@logger&.debug "Compacted entries: ", entries.keys
@file_mutex.synchronize do
if last_modified == @file.mtime && size == @file.size
@file.pos = 0
@file.truncate(0)
@file.write(entries.values.map(&:to_entry_fmt).join)
# entry contains path/ino key and value.
entries.each do |key, val|
if (m = @map[key])
m.seek = val.seek
end
end
else
# skip
end
end
end
private
def unwatch_key(key)
if (entry = @map.delete(key))
entry.update_pos(UNWATCHED_POSITION)
end
end
def compact(existing_targets = nil)
@file_mutex.synchronize do
entries = fetch_compacted_entries
@logger&.debug "Compacted entries: ", entries.keys
if existing_targets
entries = remove_deleted_files_entries(entries, existing_targets)
@logger&.debug "Remove missing entries.",
existing_targets: existing_targets.keys,
entries_after_removing: entries.keys
end
@file.pos = 0
@file.truncate(0)
@file.write(entries.values.map(&:to_entry_fmt).join)
end
end
def fetch_compacted_entries
entries = {}
@file.pos = 0
file_pos = 0
@file.each_line do |line|
m = POSITION_FILE_ENTRY_REGEX.match(line)
if m.nil?
@logger.warn "Unparsable line in pos_file: #{line}" if @logger
next
end
path = m[1]
pos = m[2].to_i(16)
ino = m[3].to_i(16)
if pos == UNWATCHED_POSITION
@logger.debug "Remove unwatched line from pos_file: #{line}" if @logger
else
if @follow_inodes
@logger&.warn("#{path} (inode: #{ino}) already exists. use latest one: deleted #{entries[ino]}") if entries.include?(ino)
entries[ino] = Entry.new(path, pos, ino, file_pos + path.bytesize + 1)
else
@logger&.warn("#{path} already exists. use latest one: deleted #{entries[path]}") if entries.include?(path)
entries[path] = Entry.new(path, pos, ino, file_pos + path.bytesize + 1)
end
file_pos += line.size
end
end
entries
end
def remove_deleted_files_entries(existent_entries, existing_targets)
existent_entries.select { |path_or_ino|
existing_targets.key?(path_or_ino)
}
end
end
Entry = Struct.new(:path, :pos, :ino, :seek) do
POSITION_FILE_ENTRY_FORMAT = "%s\t%016x\t%016x\n".freeze
def to_entry_fmt
POSITION_FILE_ENTRY_FORMAT % [path, pos, ino]
end
end
# pos inode
# ffffffffffffffff\tffffffffffffffff\n
class FilePositionEntry
POS_SIZE = 16
INO_OFFSET = 17
INO_SIZE = 16
LN_OFFSET = 33
SIZE = 34
def initialize(file, file_mutex, seek, pos, inode)
@file = file
@file_mutex = file_mutex
@seek = seek
@pos = pos
@inode = inode
end
attr_writer :seek
def update(ino, pos)
@file_mutex.synchronize {
@file.pos = @seek
@file.write "%016x\t%016x" % [pos, ino]
}
@pos = pos
@inode = ino
end
def update_pos(pos)
@file_mutex.synchronize {
@file.pos = @seek
@file.write "%016x" % pos
}
@pos = pos
end
def read_inode
@inode
end
def read_pos
@pos
end
end
class MemoryPositionEntry
def initialize
@pos = 0
@inode = 0
end
def update(ino, pos)
@inode = ino
@pos = pos
end
def update_pos(pos)
@pos = pos
end
def read_pos
@pos
end
def read_inode
@inode
end
end
TargetInfo = Struct.new(:path, :ino)
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/buffer/chunk.rb | lib/fluent/plugin/buffer/chunk.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/buffer'
require 'fluent/plugin/compressable'
require 'fluent/unique_id'
require 'fluent/event'
require 'fluent/ext_monitor_require'
require 'tempfile'
require 'zlib'
module Fluent
module Plugin
class Buffer # fluent/plugin/buffer is already loaded
class Chunk
include MonitorMixin
include UniqueId::Mixin
# Chunks has 2 part:
# * metadata: contains metadata which should be restored after resume (if possible)
# v: {key=>value,key=>value,...} (optional)
# t: tag as string (optional)
# k: time slice key (optional)
#
# id: unique_id of chunk (*)
# s: size (number of events in chunk) (*)
# c: created_at as unix time (*)
# m: modified_at as unix time (*)
# (*): fields automatically injected by chunk itself
# * data: binary data, combined records represented as String, maybe compressed
# NOTE: keys of metadata are named with a single letter
# to decread bytesize of metadata I/O
# TODO: CompressedPackedMessage of forward protocol?
def initialize(metadata, compress: :text)
super()
@unique_id = generate_unique_id
@metadata = metadata
# state: unstaged/staged/queued/closed
@state = :unstaged
@size = 0
@created_at = Fluent::Clock.real_now
@modified_at = Fluent::Clock.real_now
if compress == :gzip
extend GzipDecompressable
elsif compress == :zstd
extend ZstdDecompressable
end
end
attr_reader :unique_id, :metadata, :state
def raw_create_at
@created_at
end
def raw_modified_at
@modified_at
end
# for compatibility
def created_at
@created_at_object ||= Time.at(@created_at)
end
# for compatibility
def modified_at
@modified_at_object ||= Time.at(@modified_at)
end
# data is array of formatted record string
def append(data, **kwargs)
raise ArgumentError, "`compress: #{kwargs[:compress]}` can be used for Compressable module" if kwargs[:compress] == :gzip || kwargs[:compress] == :zstd
begin
adding = data.join.force_encoding(Encoding::ASCII_8BIT)
rescue
# Fallback
# Array#join throws an exception if data contains strings with a different encoding.
# Although such cases may be rare, it should be considered as a safety precaution.
adding = ''.force_encoding(Encoding::ASCII_8BIT)
data.each do |d|
adding << d.b
end
end
concat(adding, data.size)
end
# for event streams which is packed or zipped (and we want not to unpack/uncompress)
def concat(bulk, records)
raise NotImplementedError, "Implement this method in child class"
end
def commit
raise NotImplementedError, "Implement this method in child class"
end
def rollback
raise NotImplementedError, "Implement this method in child class"
end
def bytesize
raise NotImplementedError, "Implement this method in child class"
end
def size
raise NotImplementedError, "Implement this method in child class"
end
alias :length :size
def empty?
size == 0
end
def writable?
@state == :staged || @state == :unstaged
end
def unstaged?
@state == :unstaged
end
def staged?
@state == :staged
end
def queued?
@state == :queued
end
def closed?
@state == :closed
end
def staged!
@state = :staged
self
end
def unstaged!
@state = :unstaged
self
end
def enqueued!
@state = :queued
self
end
def close
@state = :closed
self
end
def purge
@state = :closed
self
end
def read(**kwargs)
raise ArgumentError, "`compressed: #{kwargs[:compressed]}` can be used for Compressable module" if kwargs[:compressed] == :gzip || kwargs[:compressed] == :zstd
raise NotImplementedError, "Implement this method in child class"
end
def open(**kwargs, &block)
raise ArgumentError, "`compressed: #{kwargs[:compressed]}` can be used for Compressable module" if kwargs[:compressed] == :gzip || kwargs[:compressed] == :zstd
raise NotImplementedError, "Implement this method in child class"
end
def write_to(io, **kwargs)
raise ArgumentError, "`compressed: #{kwargs[:compressed]}` can be used for Compressable module" if kwargs[:compressed] == :gzip || kwargs[:compressed] == :zstd
open do |i|
IO.copy_stream(i, io)
end
end
module GzipDecompressable
include Fluent::Plugin::Compressable
def append(data, **kwargs)
if kwargs[:compress] == :gzip
io = StringIO.new
Zlib::GzipWriter.wrap(io) do |gz|
data.each do |d|
gz.write d
end
end
concat(io.string, data.size)
else
super
end
end
def open(**kwargs, &block)
if kwargs[:compressed] == :gzip
super
else
super(**kwargs) do |chunk_io|
output_io = if chunk_io.is_a?(StringIO)
StringIO.new
else
Tempfile.new('decompressed-data')
end
output_io.binmode if output_io.is_a?(Tempfile)
decompress(input_io: chunk_io, output_io: output_io)
output_io.seek(0, IO::SEEK_SET)
yield output_io
end
end
end
def read(**kwargs)
if kwargs[:compressed] == :gzip
super
else
decompress(super)
end
end
def write_to(io, **kwargs)
open(compressed: :gzip) do |chunk_io|
if kwargs[:compressed] == :gzip
IO.copy_stream(chunk_io, io)
else
decompress(input_io: chunk_io, output_io: io)
end
end
end
end
module ZstdDecompressable
include Fluent::Plugin::Compressable
def append(data, **kwargs)
if kwargs[:compress] == :zstd
io = StringIO.new
stream = Zstd::StreamWriter.new(io)
data.each do |d|
stream.write(d)
end
stream.finish
concat(io.string, data.size)
else
super
end
end
def open(**kwargs, &block)
if kwargs[:compressed] == :zstd
super
else
super(**kwargs) do |chunk_io|
output_io = if chunk_io.is_a?(StringIO)
StringIO.new
else
Tempfile.new('decompressed-data')
end
output_io.binmode if output_io.is_a?(Tempfile)
decompress(input_io: chunk_io, output_io: output_io, type: :zstd)
output_io.seek(0, IO::SEEK_SET)
yield output_io
end
end
end
def read(**kwargs)
if kwargs[:compressed] == :zstd
super
else
decompress(super,type: :zstd)
end
end
def write_to(io, **kwargs)
open(compressed: :zstd) do |chunk_io|
if kwargs[:compressed] == :zstd
IO.copy_stream(chunk_io, io)
else
decompress(input_io: chunk_io, output_io: io, type: :zstd)
end
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/buffer/file_single_chunk.rb | lib/fluent/plugin/buffer/file_single_chunk.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'uri'
require 'fluent/plugin/buffer/chunk'
require 'fluent/unique_id'
require 'fluent/msgpack_factory'
module Fluent
module Plugin
class Buffer
class FileSingleChunk < Chunk
class FileChunkError < StandardError; end
## buffer path user specified : /path/to/directory
## buffer chunk path : /path/to/directory/fsb.key.b513b61c9791029c2513b61c9791029c2.buf
## state: b/q - 'b'(on stage), 'q'(enqueued)
PATH_EXT = 'buf'
PATH_SUFFIX = ".#{PATH_EXT}"
PATH_REGEXP = /\.(b|q)([0-9a-f]+)\.#{PATH_EXT}*\Z/n # //n switch means explicit 'ASCII-8BIT' pattern
attr_reader :path, :permission
def initialize(metadata, path, mode, key, perm: Fluent::DEFAULT_FILE_PERMISSION, compress: :text)
super(metadata, compress: compress)
@key = key
perm ||= Fluent::DEFAULT_FILE_PERMISSION
@permission = perm.is_a?(String) ? perm.to_i(8) : perm
@bytesize = @size = @adding_bytes = @adding_size = 0
case mode
when :create then create_new_chunk(path, metadata, @permission)
when :staged then load_existing_staged_chunk(path)
when :queued then load_existing_enqueued_chunk(path)
else
raise ArgumentError, "Invalid file chunk mode: #{mode}"
end
end
def concat(bulk, bulk_size)
raise "BUG: concatenating to unwritable chunk, now '#{self.state}'" unless self.writable?
bulk.force_encoding(Encoding::ASCII_8BIT)
@chunk.write(bulk)
@adding_bytes += bulk.bytesize
@adding_size += bulk_size
true
end
def commit
@commit_position = @chunk.pos
@size += @adding_size
@bytesize += @adding_bytes
@adding_bytes = @adding_size = 0
@modified_at = Fluent::Clock.real_now
true
end
def rollback
if @chunk.pos != @commit_position
@chunk.seek(@commit_position, IO::SEEK_SET)
@chunk.truncate(@commit_position)
end
@adding_bytes = @adding_size = 0
true
end
def bytesize
@bytesize + @adding_bytes
end
def size
@size + @adding_size
end
def empty?
@bytesize.zero?
end
def enqueued!
return unless self.staged?
new_chunk_path = self.class.generate_queued_chunk_path(@path, @unique_id)
begin
file_rename(@chunk, @path, new_chunk_path, ->(new_io) { @chunk = new_io })
rescue => e
begin
file_rename(@chunk, new_chunk_path, @path, ->(new_io) { @chunk = new_io }) if File.exist?(new_chunk_path)
rescue => re
# In this point, restore buffer state is hard because previous `file_rename` failed by resource problem.
# Retry is one possible approach but it may cause livelock under limited resources or high load environment.
# So we ignore such errors for now and log better message instead.
# "Too many open files" should be fixed by proper buffer configuration and system setting.
raise "can't enqueue buffer file and failed to restore. This may causes inconsistent state: path = #{@path}, error = '#{e}', retry error = '#{re}'"
else
raise "can't enqueue buffer file: path = #{@path}, error = '#{e}'"
end
end
@path = new_chunk_path
super
end
def close
super
size = @chunk.size
@chunk.close
if size == 0
File.unlink(@path)
end
end
def purge
super
@chunk.close
@bytesize = @size = @adding_bytes = @adding_size = 0
File.unlink(@path)
end
def read(**kwargs)
@chunk.seek(0, IO::SEEK_SET)
@chunk.read
end
def open(**kwargs, &block)
@chunk.seek(0, IO::SEEK_SET)
val = yield @chunk
@chunk.seek(0, IO::SEEK_END) if self.staged?
val
end
def self.assume_chunk_state(path)
return :unknown unless path.end_with?(PATH_SUFFIX)
if PATH_REGEXP =~ path
$1 == 'b' ? :staged : :queued
else
# files which matches to glob of buffer file pattern
# it includes files which are created by out_file
:unknown
end
end
def self.unique_id_and_key_from_path(path)
base = File.basename(path)
res = PATH_REGEXP =~ base
return nil unless res
key = base[4..res - 1] # remove 'fsb.' and '.'
hex_id = $2 # remove '.' and '.buf'
unique_id = hex_id.scan(/../).map {|x| x.to_i(16) }.pack('C*')
[unique_id, key]
end
def self.generate_stage_chunk_path(path, key, unique_id)
pos = path.index('.*.')
raise "BUG: buffer chunk path on stage MUST have '.*.'" unless pos
prefix = path[0...pos]
suffix = path[(pos + 3)..-1]
chunk_id = Fluent::UniqueId.hex(unique_id)
"#{prefix}.#{key}.b#{chunk_id}.#{suffix}"
end
def self.generate_queued_chunk_path(path, unique_id)
chunk_id = Fluent::UniqueId.hex(unique_id)
staged_path = ".b#{chunk_id}."
if path.index(staged_path)
path.sub(staged_path, ".q#{chunk_id}.")
else # for unexpected cases (ex: users rename files while opened by fluentd)
path + ".q#{chunk_id}.chunk"
end
end
def restore_metadata
if res = self.class.unique_id_and_key_from_path(@path)
@unique_id = res.first
key = decode_key(res.last)
if @key
@metadata.variables = {@key => key}
else
@metadata.tag = key
end
else
raise FileChunkError, "Invalid chunk found. unique_id and key not exist: #{@path}"
end
@size = 0
stat = File.stat(@path)
@created_at = stat.ctime.to_i
@modified_at = stat.mtime.to_i
end
def restore_size(chunk_format)
count = 0
File.open(@path, 'rb') { |f|
if chunk_format == :msgpack
Fluent::MessagePackFactory.msgpack_unpacker(f).each { |d| count += 1 }
else
f.each_line { |l| count += 1 }
end
}
@size = count
end
def file_rename(file, old_path, new_path, callback = nil)
pos = file.pos
if Fluent.windows?
file.close
File.rename(old_path, new_path)
file = File.open(new_path, 'rb', @permission)
else
File.rename(old_path, new_path)
file.reopen(new_path, 'rb')
end
file.set_encoding(Encoding::ASCII_8BIT)
file.sync = true
file.binmode
file.pos = pos
callback.call(file) if callback
end
ESCAPE_REGEXP = /[^-_.a-zA-Z0-9]/n
def encode_key(metadata)
k = @key ? metadata.variables[@key] : metadata.tag
k ||= ''
URI::RFC2396_PARSER.escape(k, ESCAPE_REGEXP)
end
def decode_key(key)
URI::RFC2396_PARSER.unescape(key)
end
def create_new_chunk(path, metadata, perm)
@path = self.class.generate_stage_chunk_path(path, encode_key(metadata), @unique_id)
begin
@chunk = File.open(@path, 'wb+', perm)
@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.sync = true
@chunk.binmode
rescue => e
# Here assumes "Too many open files" like recoverable error so raising BufferOverflowError.
# If other cases are possible, we will change error handling with proper classes.
raise BufferOverflowError, "can't create buffer file for #{path}. Stop creating buffer files: error = #{e}"
end
@state = :unstaged
@bytesize = 0
@commit_position = @chunk.pos # must be 0
@adding_bytes = 0
@adding_size = 0
end
def load_existing_staged_chunk(path)
@path = path
raise FileChunkError, "staged file chunk is empty" if File.size(@path).zero?
@chunk = File.open(@path, 'rb+')
@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.sync = true
@chunk.binmode
@chunk.seek(0, IO::SEEK_END)
restore_metadata
@state = :staged
@bytesize = @chunk.size
@commit_position = @chunk.pos
@adding_bytes = 0
@adding_size = 0
end
def load_existing_enqueued_chunk(path)
@path = path
raise FileChunkError, "enqueued file chunk is empty" if File.size(@path).zero?
@chunk = File.open(@path, 'rb')
@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.binmode
@chunk.seek(0, IO::SEEK_SET)
restore_metadata
@state = :queued
@bytesize = @chunk.size
@commit_position = @chunk.size
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/buffer/file_chunk.rb | lib/fluent/plugin/buffer/file_chunk.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/buffer/chunk'
require 'fluent/unique_id'
require 'fluent/msgpack_factory'
module Fluent
module Plugin
class Buffer
class FileChunk < Chunk
class FileChunkError < StandardError; end
BUFFER_HEADER = "\xc1\x00".force_encoding(Encoding::ASCII_8BIT).freeze
### buffer path user specified : /path/to/directory/user_specified_prefix.*.log
### buffer chunk path : /path/to/directory/user_specified_prefix.b513b61c9791029c2513b61c9791029c2.log
### buffer chunk metadata path : /path/to/directory/user_specified_prefix.b513b61c9791029c2513b61c9791029c2.log.meta
# NOTE: Old style buffer path of time sliced output plugins had a part of key: prefix.20150414.b513b61...suffix
# But this part is not used now for any purpose. (Now metadata is used instead.)
# state: b/q - 'b'(on stage, compatible with v0.12), 'q'(enqueued)
# path_prefix: path prefix string, ended with '.'
# path_suffix: path suffix string, like '.log' (or any other user specified)
attr_reader :path, :meta_path, :permission
def initialize(metadata, path, mode, perm: nil, compress: :text)
super(metadata, compress: compress)
perm ||= Fluent::DEFAULT_FILE_PERMISSION
@permission = perm.is_a?(String) ? perm.to_i(8) : perm
@bytesize = @size = @adding_bytes = @adding_size = 0
@meta = nil
case mode
when :create then create_new_chunk(path, @permission)
when :staged then load_existing_staged_chunk(path)
when :queued then load_existing_enqueued_chunk(path)
else
raise ArgumentError, "Invalid file chunk mode: #{mode}"
end
end
def concat(bulk, bulk_size)
raise "BUG: concatenating to unwritable chunk, now '#{self.state}'" unless self.writable?
bulk.force_encoding(Encoding::ASCII_8BIT)
@chunk.write bulk
@adding_bytes += bulk.bytesize
@adding_size += bulk_size
true
end
def commit
write_metadata # this should be at first: of course, this operation may fail
@commit_position = @chunk.pos
@size += @adding_size
@bytesize += @adding_bytes
@adding_bytes = @adding_size = 0
@modified_at = Fluent::Clock.real_now
@modified_at_object = nil
true
end
def rollback
if @chunk.pos != @commit_position
@chunk.seek(@commit_position, IO::SEEK_SET)
@chunk.truncate(@commit_position)
end
@adding_bytes = @adding_size = 0
true
end
def bytesize
@bytesize + @adding_bytes
end
def size
@size + @adding_size
end
def empty?
@bytesize == 0
end
def enqueued!
return unless self.staged?
new_chunk_path = self.class.generate_queued_chunk_path(@path, @unique_id)
new_meta_path = new_chunk_path + '.meta'
write_metadata(update: false) # re-write metadata w/ finalized records
begin
file_rename(@chunk, @path, new_chunk_path, ->(new_io) { @chunk = new_io })
rescue => e
begin
file_rename(@chunk, new_chunk_path, @path, ->(new_io) { @chunk = new_io }) if File.exist?(new_chunk_path)
rescue => re
# In this point, restore buffer state is hard because previous `file_rename` failed by resource problem.
# Retry is one possible approach but it may cause livelock under limited resources or high load environment.
# So we ignore such errors for now and log better message instead.
# "Too many open files" should be fixed by proper buffer configuration and system setting.
raise "can't enqueue buffer file and failed to restore. This may causes inconsistent state: path = #{@path}, error = '#{e}', retry error = '#{re}'"
else
raise "can't enqueue buffer file: path = #{@path}, error = '#{e}'"
end
end
begin
file_rename(@meta, @meta_path, new_meta_path, ->(new_io) { @meta = new_io })
rescue => e
begin
file_rename(@chunk, new_chunk_path, @path, ->(new_io) { @chunk = new_io }) if File.exist?(new_chunk_path)
file_rename(@meta, new_meta_path, @meta_path, ->(new_io) { @meta = new_io }) if File.exist?(new_meta_path)
rescue => re
# See above
raise "can't enqueue buffer metadata and failed to restore. This may causes inconsistent state: path = #{@meta_path}, error = '#{e}', retry error = '#{re}'"
else
raise "can't enqueue buffer metadata: path = #{@meta_path}, error = '#{e}'"
end
end
@path = new_chunk_path
@meta_path = new_meta_path
super
end
def close
super
size = @chunk.size
@chunk.close
@meta.close if @meta # meta may be missing if chunk is queued at first
if size == 0
File.unlink(@path, @meta_path)
end
end
def purge
super
@chunk.close
@meta.close if @meta
@bytesize = @size = @adding_bytes = @adding_size = 0
File.unlink(@path, @meta_path)
end
def read(**kwargs)
@chunk.seek(0, IO::SEEK_SET)
@chunk.read
end
def open(**kwargs, &block)
@chunk.seek(0, IO::SEEK_SET)
val = yield @chunk
@chunk.seek(0, IO::SEEK_END) if self.staged?
val
end
def self.assume_chunk_state(path)
if /\.(b|q)([0-9a-f]+)\.[^\/]*\Z/n =~ path # //n switch means explicit 'ASCII-8BIT' pattern
$1 == 'b' ? :staged : :queued
else
# files which matches to glob of buffer file pattern
# it includes files which are created by out_file
:unknown
end
end
def self.generate_stage_chunk_path(path, unique_id)
pos = path.index('.*.')
raise "BUG: buffer chunk path on stage MUST have '.*.'" unless pos
prefix = path[0...pos]
suffix = path[(pos+3)..-1]
chunk_id = Fluent::UniqueId.hex(unique_id)
state = 'b'
"#{prefix}.#{state}#{chunk_id}.#{suffix}"
end
def self.generate_queued_chunk_path(path, unique_id)
chunk_id = Fluent::UniqueId.hex(unique_id)
if path.index(".b#{chunk_id}.")
path.sub(".b#{chunk_id}.", ".q#{chunk_id}.")
else # for unexpected cases (ex: users rename files while opened by fluentd)
path + ".q#{chunk_id}.chunk"
end
end
# used only for queued v0.12 buffer path or broken files
def self.unique_id_from_path(path)
if /\.(b|q)([0-9a-f]+)\.[^\/]*\Z/n =~ path # //n switch means explicit 'ASCII-8BIT' pattern
return $2.scan(/../).map{|x| x.to_i(16) }.pack('C*')
end
nil
end
def restore_metadata(bindata)
data = restore_metadata_with_new_format(bindata)
unless data
# old type of restore
data = Fluent::MessagePackFactory.msgpack_unpacker(symbolize_keys: true).feed(bindata).read rescue {}
end
raise FileChunkError, "invalid meta data" if data.nil? || !data.is_a?(Hash)
raise FileChunkError, "invalid unique_id" unless data[:id]
raise FileChunkError, "invalid created_at" unless data[:c].to_i > 0
raise FileChunkError, "invalid modified_at" unless data[:m].to_i > 0
now = Fluent::Clock.real_now
@unique_id = data[:id]
@size = data[:s] || 0
@created_at = data[:c]
@modified_at = data[:m]
@metadata.timekey = data[:timekey]
@metadata.tag = data[:tag]
@metadata.variables = data[:variables]
@metadata.seq = data[:seq] || 0
end
def restore_metadata_partially(chunk)
@unique_id = self.class.unique_id_from_path(chunk.path) || @unique_id
@size = 0
@created_at = chunk.ctime.to_i # birthtime isn't supported on Windows (and Travis?)
@modified_at = chunk.mtime.to_i
@metadata.timekey = nil
@metadata.tag = nil
@metadata.variables = nil
@metadata.seq = 0
end
def write_metadata(update: true)
data = @metadata.to_h.merge({
id: @unique_id,
s: (update ? @size + @adding_size : @size),
c: @created_at,
m: (update ? Fluent::Clock.real_now : @modified_at),
})
bin = Fluent::MessagePackFactory.thread_local_msgpack_packer.pack(data).full_pack
size = [bin.bytesize].pack('N')
@meta.seek(0, IO::SEEK_SET)
@meta.write(BUFFER_HEADER + size + bin)
end
def file_rename(file, old_path, new_path, callback=nil)
pos = file.pos
if Fluent.windows?
file.close
File.rename(old_path, new_path)
file = File.open(new_path, 'rb', @permission)
else
File.rename(old_path, new_path)
file.reopen(new_path, 'rb')
end
file.set_encoding(Encoding::ASCII_8BIT)
file.sync = true
file.binmode
file.pos = pos
callback.call(file) if callback
end
def create_new_chunk(path, perm)
@path = self.class.generate_stage_chunk_path(path, @unique_id)
@meta_path = @path + '.meta'
begin
@chunk = File.open(@path, 'wb+', perm)
@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.sync = true
@chunk.binmode
rescue => e
# Here assumes "Too many open files" like recoverable error so raising BufferOverflowError.
# If other cases are possible, we will change error handling with proper classes.
raise BufferOverflowError, "can't create buffer file for #{path}. Stop creating buffer files: error = #{e}"
end
begin
@meta = File.open(@meta_path, 'wb', perm)
@meta.set_encoding(Encoding::ASCII_8BIT)
@meta.sync = true
@meta.binmode
write_metadata(update: false)
rescue => e
# This case is easier than enqueued!. Just removing pre-create buffer file
@chunk.close rescue nil
File.unlink(@path) rescue nil
if @meta
# ensure to unlink when #write_metadata fails
@meta.close rescue nil
File.unlink(@meta_path) rescue nil
end
# Same as @chunk case. See above
raise BufferOverflowError, "can't create buffer metadata for #{path}. Stop creating buffer files: error = #{e}"
end
@state = :unstaged
@bytesize = 0
@commit_position = @chunk.pos # must be 0
@adding_bytes = 0
@adding_size = 0
end
def load_existing_staged_chunk(path)
@path = path
@meta_path = @path + '.meta'
@meta = nil
# staging buffer chunk without metadata is classic buffer chunk file
# and it should be enqueued immediately
if File.exist?(@meta_path)
raise FileChunkError, "staged file chunk is empty" if File.size(@path).zero?
@chunk = File.open(@path, 'rb+')
@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.sync = true
@chunk.seek(0, IO::SEEK_END)
@chunk.binmode
@meta = File.open(@meta_path, 'rb+')
@meta.set_encoding(Encoding::ASCII_8BIT)
@meta.sync = true
@meta.binmode
begin
restore_metadata(@meta.read)
rescue => e
@chunk.close
@meta.close
raise FileChunkError, "staged meta file is broken. #{e.message}"
end
@meta.seek(0, IO::SEEK_SET)
@state = :staged
@bytesize = @chunk.size
@commit_position = @chunk.pos
@adding_bytes = 0
@adding_size = 0
else
# classic buffer chunk - read only chunk
@chunk = File.open(@path, 'rb')
@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.binmode
@chunk.seek(0, IO::SEEK_SET)
@state = :queued
@bytesize = @chunk.size
restore_metadata_partially(@chunk)
@commit_position = @chunk.size
@unique_id = self.class.unique_id_from_path(@path) || @unique_id
end
end
def load_existing_enqueued_chunk(path)
@path = path
raise FileChunkError, "enqueued file chunk is empty" if File.size(@path).zero?
@chunk = File.open(@path, 'rb')
@chunk.set_encoding(Encoding::ASCII_8BIT)
@chunk.binmode
@chunk.seek(0, IO::SEEK_SET)
@bytesize = @chunk.size
@commit_position = @chunk.size
@meta_path = @path + '.meta'
if File.readable?(@meta_path)
begin
restore_metadata(File.open(@meta_path){|f| f.set_encoding(Encoding::ASCII_8BIT); f.binmode; f.read })
rescue => e
@chunk.close
raise FileChunkError, "enqueued meta file is broken. #{e.message}"
end
else
restore_metadata_partially(@chunk)
end
@state = :queued
end
private
def restore_metadata_with_new_format(chunk)
if chunk.size <= 6 # size of BUFFER_HEADER (2) + size of data size(4)
return nil
end
if chunk.slice(0, 2) == BUFFER_HEADER
size = chunk.slice(2, 4).unpack1('N')
if size
return Fluent::MessagePackFactory.msgpack_unpacker(symbolize_keys: true).feed(chunk.slice(6, size)).read rescue nil
end
end
nil
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin/buffer/memory_chunk.rb | lib/fluent/plugin/buffer/memory_chunk.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/buffer/chunk'
module Fluent
module Plugin
class Buffer
class MemoryChunk < Chunk
def initialize(metadata, compress: :text)
super
@chunk = ''.force_encoding(Encoding::ASCII_8BIT)
@chunk_bytes = 0
@adding_bytes = 0
@adding_size = 0
end
def concat(bulk, bulk_size)
raise "BUG: concatenating to unwritable chunk, now '#{self.state}'" unless self.writable?
bulk.force_encoding(Encoding::ASCII_8BIT)
@chunk << bulk
@adding_bytes += bulk.bytesize
@adding_size += bulk_size
true
end
def commit
@size += @adding_size
@chunk_bytes += @adding_bytes
@adding_bytes = @adding_size = 0
@modified_at = Fluent::Clock.real_now
@modified_at_object = nil
true
end
def rollback
@chunk.slice!(@chunk_bytes, @adding_bytes)
@adding_bytes = @adding_size = 0
true
end
def bytesize
@chunk_bytes + @adding_bytes
end
def size
@size + @adding_size
end
def empty?
@chunk.empty?
end
def purge
super
@chunk.clear
@chunk_bytes = @size = @adding_bytes = @adding_size = 0
true
end
def read(**kwargs)
@chunk.dup
end
def open(**kwargs, &block)
StringIO.open(@chunk, &block)
end
def write_to(io, **kwargs)
# re-implementation to optimize not to create StringIO
io.write @chunk
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/ctl.rb | lib/fluent/command/ctl.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'optparse'
require 'fluent/env'
require 'fluent/version'
if Fluent.windows?
require 'win32/event'
require 'win32/service'
end
module Fluent
class Ctl
DEFAULT_OPTIONS = {}
if Fluent.windows?
include Windows::ServiceConstants
include Windows::ServiceStructs
include Windows::ServiceFunctions
COMMAND_MAP = {
shutdown: "",
restart: "HUP",
flush: "USR1",
reload: "USR2",
dump: "CONT",
}
WINSVC_CONTROL_CODE_MAP = {
shutdown: SERVICE_CONTROL_STOP,
# 128 - 255: user-defined control code
# See https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-controlservice
restart: 128,
flush: 129,
reload: SERVICE_CONTROL_PARAMCHANGE,
dump: 130,
}
else
COMMAND_MAP = {
shutdown: :TERM,
restart: :HUP,
flush: :USR1,
reload: :USR2,
dump: :CONT,
}
end
def initialize(argv = ARGV)
@argv = argv
@options = {}
@opt_parser = OptionParser.new
configure_option_parser
@options.merge!(DEFAULT_OPTIONS)
parse_options!
end
def help_text
text = "\n"
if Fluent.windows?
text << "Usage: #{$PROGRAM_NAME} COMMAND [PID_OR_SVCNAME]\n"
else
text << "Usage: #{$PROGRAM_NAME} COMMAND PID\n"
end
text << "\n"
text << "Commands: \n"
COMMAND_MAP.each do |key, value|
text << " #{key}\n"
end
text
end
def usage(msg = nil)
puts help_text
if msg
puts
puts "Error: #{msg}"
end
exit 1
end
def call
if Fluent.windows?
if /^[0-9]+$/.match?(@pid_or_svcname)
# Use as PID
return call_windows_event(@command, "fluentd_#{@pid_or_svcname}")
end
unless call_winsvc_control_code(@command, @pid_or_svcname)
puts "Cannot send control code to #{@pid_or_svcname} service, try to send an event with this name ..."
call_windows_event(@command, @pid_or_svcname)
end
else
call_signal(@command, @pid_or_svcname)
end
end
private
def call_signal(command, pid)
signal = COMMAND_MAP[command.to_sym]
Process.kill(signal, pid.to_i)
end
def call_winsvc_control_code(command, pid_or_svcname)
status = SERVICE_STATUS.new
begin
handle_scm = OpenSCManager(nil, nil, SC_MANAGER_CONNECT)
FFI.raise_windows_error('OpenSCManager') if handle_scm == 0
handle_scs = OpenService(handle_scm, "fluentdwinsvc", SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_USER_DEFINED_CONTROL)
FFI.raise_windows_error('OpenService') if handle_scs == 0
control_code = WINSVC_CONTROL_CODE_MAP[command.to_sym]
unless ControlService(handle_scs, control_code, status)
FFI.raise_windows_error('ControlService')
end
rescue => e
puts e
state = status[:dwCurrentState]
return state == SERVICE_STOPPED || state == SERVICE_STOP_PENDING
ensure
CloseServiceHandle(handle_scs)
CloseServiceHandle(handle_scm)
end
return true
end
def call_windows_event(command, pid_or_svcname)
prefix = pid_or_svcname
event_name = COMMAND_MAP[command.to_sym]
suffix = event_name.empty? ? "" : "_#{event_name}"
begin
event = Win32::Event.open("#{prefix}#{suffix}")
event.set
event.close
rescue Errno::ENOENT
puts "Error: Cannot find the fluentd process with the event name: \"#{prefix}\""
end
end
def configure_option_parser
@opt_parser.banner = help_text
@opt_parser.version = Fluent::VERSION
end
def parse_options!
@opt_parser.parse!(@argv)
@command = @argv[0]
@pid_or_svcname = @argv[1] || "fluentdwinsvc"
usage("Command isn't specified!") if @command.nil? || @command.empty?
usage("Unknown command: #{@command}") unless COMMAND_MAP.has_key?(@command.to_sym)
if Fluent.windows?
usage("PID or SVCNAME isn't specified!") if @pid_or_svcname.nil? || @pid_or_svcname.empty?
else
usage("PID isn't specified!") if @pid_or_svcname.nil? || @pid_or_svcname.empty?
usage("Invalid PID: #{pid}") unless /^[0-9]+$/.match?(@pid_or_svcname)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/cap_ctl.rb | lib/fluent/command/cap_ctl.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'optparse'
require 'fluent/log'
require 'fluent/env'
require 'fluent/capability'
module Fluent
class CapCtl
def prepare_option_parser
@op = OptionParser.new
@op.on('--clear', "Clear Fluentd Ruby capability") {|s|
@opts[:clear_capabilities] = true
}
@op.on('--add [CAPABILITY1,CAPABILITY2, ...]', "Add capabilities into Fluentd Ruby") {|s|
@opts[:add_capabilities] = s
}
@op.on('--drop [CAPABILITY1,CAPABILITY2, ...]', "Drop capabilities from Fluentd Ruby") {|s|
@opts[:drop_capabilities] = s
}
@op.on('--get', "Get capabilities for Fluentd Ruby") {|s|
@opts[:get_capabilities] = true
}
@op.on('-f', '--file FILE', "Specify target file to add Linux capabilities") {|s|
@opts[:target_file] = s
}
end
def usage(msg)
puts @op.to_s
puts "error: #{msg}" if msg
exit 1
end
def initialize(argv = ARGV)
@opts = {}
@argv = argv
if Fluent.linux?
begin
require 'capng'
@capng = CapNG.new
rescue LoadError
puts "Error: capng_c is not loaded. Please install it first."
exit 1
end
else
puts "Error: This environment is not supported."
exit 2
end
prepare_option_parser
end
def call
parse_options!(@argv)
target_file = if !!@opts[:target_file]
@opts[:target_file]
else
File.readlink("/proc/self/exe")
end
if @opts[:clear_capabilities]
clear_capabilities(@opts, target_file)
elsif @opts[:add_capabilities]
add_capabilities(@opts, target_file)
elsif @opts[:drop_capabilities]
drop_capabilities(@opts, target_file)
end
if @opts[:get_capabilities]
get_capabilities(@opts, target_file)
end
end
def clear_capabilities(opts, target_file)
if !!opts[:clear_capabilities]
@capng.clear(:caps)
ret = @capng.apply_caps_file(target_file)
puts "Clear capabilities #{ret ? 'done' : 'fail'}."
end
end
def add_capabilities(opts, target_file)
if add_caps = opts[:add_capabilities]
@capng.clear(:caps)
@capng.caps_file(target_file)
capabilities = add_caps.split(/\s*,\s*/)
check_capabilities(capabilities, get_valid_capabilities)
ret = @capng.update(:add,
CapNG::Type::EFFECTIVE | CapNG::Type::INHERITABLE | CapNG::Type::PERMITTED,
capabilities)
puts "Updating #{add_caps} #{ret ? 'done' : 'fail'}."
ret = @capng.apply_caps_file(target_file)
puts "Adding #{add_caps} #{ret ? 'done' : 'fail'}."
end
end
def drop_capabilities(opts, target_file)
if drop_caps = opts[:drop_capabilities]
@capng.clear(:caps)
@capng.caps_file(target_file)
capabilities = drop_caps.split(/\s*,\s*/)
check_capabilities(capabilities, get_valid_capabilities)
ret = @capng.update(:drop,
CapNG::Type::EFFECTIVE | CapNG::Type::INHERITABLE | CapNG::Type::PERMITTED,
capabilities)
puts "Updating #{drop_caps} #{ret ? 'done' : 'fail'}."
@capng.apply_caps_file(target_file)
puts "Dropping #{drop_caps} #{ret ? 'done' : 'fail'}."
end
end
def get_capabilities(opts, target_file)
if opts[:get_capabilities]
@capng.caps_file(target_file)
print = CapNG::Print.new
puts "Capabilities in '#{target_file}',"
puts "Effective: #{print.caps_text(:buffer, :effective)}"
puts "Inheritable: #{print.caps_text(:buffer, :inheritable)}"
puts "Permitted: #{print.caps_text(:buffer, :permitted)}"
end
end
def get_valid_capabilities
capabilities = []
cap = CapNG::Capability.new
cap.each do |_code, capability|
capabilities << capability
end
capabilities
end
def check_capabilities(capabilities, valid_capabilities)
capabilities.each do |capability|
unless valid_capabilities.include?(capability)
raise ArgumentError, "'#{capability}' is not valid capability. Valid Capabilities are: #{valid_capabilities.join(", ")}"
end
end
end
def parse_options!(argv)
begin
rest = @op.parse(argv)
if rest.length != 0
usage nil
end
rescue
usage $!.to_s
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/plugin_generator.rb | lib/fluent/command/plugin_generator.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "optparse"
require "pathname"
require "fileutils"
require "erb"
require "open-uri"
require "fluent/registry"
require 'fluent/version'
class FluentPluginGenerator
attr_reader :type, :name
attr_reader :license_name
SUPPORTED_TYPES = ["input", "output", "filter", "parser", "formatter", "storage"]
def initialize(argv = ARGV)
@argv = argv
@parser = prepare_parser
@license_name = "Apache-2.0"
@overwrite_all = false
end
def call
parse_options!
FileUtils.mkdir_p(gem_name)
Dir.chdir(gem_name) do
copy_license
template_directory.find do |path|
next if path.directory?
dest_dir = path.dirname.sub(/\A#{Regexp.quote(template_directory.to_s)}\/?/, "")
dest_file = dest_filename(path)
if path.extname == ".erb"
if path.fnmatch?("*/plugin/*")
next unless path.basename.fnmatch?("*#{type}*")
end
template(path, dest_dir + dest_file)
else
file(path, dest_dir + dest_file)
end
end
pid = spawn("git", "init", ".")
Process.wait(pid)
end
end
private
def template_directory
(Pathname(__dir__) + "../../../templates/new_gem").realpath
end
def template_file(filename)
template_directory + filename
end
def template(source, dest)
dest.dirname.mkpath
contents =
if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+
ERB.new(source.read, trim_mode: "-")
else
ERB.new(source.read, nil, "-")
end.result(binding)
label = create_label(dest, contents)
puts "\t#{label} #{dest}"
if label == "conflict"
return unless overwrite?(dest)
end
File.write(dest, contents)
end
def file(source, dest)
label = create_label(dest, source.read)
puts "\t#{label} #{dest}"
if label == "conflict"
return unless overwrite?(dest)
end
FileUtils.cp(source, dest)
end
def prepare_parser
@parser = OptionParser.new
@parser.version = Fluent::VERSION
@parser.banner = <<BANNER
Usage: fluent-plugin-generate [options] <type> <name>
Generate a project skeleton for creating a Fluentd plugin
Arguments:
\ttype: #{SUPPORTED_TYPES.join(",")}
\tname: Your plugin name (fluent-plugin- prefix will be added to <name>)
Options:
BANNER
@parser.on("--[no-]license=NAME", "Specify license name (default: Apache-2.0)") do |v|
@license_name = v || "no-license"
end
@parser
end
def parse_options!
@parser.parse!(@argv)
unless @argv.size == 2
raise ArgumentError, "Missing arguments"
end
@type, @name = @argv
rescue => e
usage("#{e.class}:#{e.message}")
end
def usage(message = "")
puts message
puts
puts @parser.help
exit(false)
end
def user_name
v = `git config --get user.name`.chomp
v.empty? ? "TODO: Write your name" : v
end
def user_email
v = `git config --get user.email`.chomp
v.empty? ? "TODO: Write your email" : v
end
def gem_name
"fluent-plugin-#{dash_name}"
end
def plugin_name
underscore_name
end
def gem_file_path
File.expand_path(File.join(File.dirname(__FILE__),
"../../../",
"Gemfile"))
end
def lock_file_path
File.expand_path(File.join(File.dirname(__FILE__),
"../../../",
"Gemfile.lock"))
end
def locked_gem_version(gem_name)
if File.exist?(lock_file_path)
d = Bundler::Definition.build(gem_file_path, lock_file_path, false)
d.locked_gems.dependencies[gem_name].requirement.requirements.first.last.version
else
# fallback even though Fluentd is installed without bundler
Gem::Specification.find_by_name(gem_name).version.version
end
end
def rake_version
locked_gem_version("rake")
end
def test_unit_version
locked_gem_version("test-unit")
end
def bundler_version
if File.exist?(lock_file_path)
d = Bundler::Definition.build(gem_file_path, lock_file_path, false)
d.locked_gems.bundler_version.version
else
# fallback even though Fluentd is installed without bundler
Gem::Specification.find_by_name("bundler").version.version
end
end
def class_name
"#{capitalized_name}#{type.capitalize}"
end
def plugin_filename
case type
when "input"
"in_#{underscore_name}.rb"
when "output"
"out_#{underscore_name}.rb"
else
"#{type}_#{underscore_name}.rb"
end
end
def test_filename
case type
when "input"
"test_in_#{underscore_name}.rb"
when "output"
"test_out_#{underscore_name}.rb"
else
"test_#{type}_#{underscore_name}.rb"
end
end
def dest_filename(path)
case path.to_s
when %r!\.gemspec!
"#{gem_name}.gemspec"
when %r!lib/fluent/plugin!
plugin_filename
when %r!test/plugin!
test_filename
else
path.basename.sub_ext("")
end
end
def capitalized_name
@capitalized_name ||= name.split(/[-_]/).map(&:capitalize).join
end
def underscore_name
@underscore_name ||= name.tr("-", "_")
end
def dash_name
@dash_name ||= name.tr("_", "-")
end
def preamble
@license.preamble(user_name)
end
def copy_license
# in gem_name directory
return unless license_name
puts "License: #{license_name}"
license_class = self.class.lookup_license(license_name)
@license = license_class.new
Pathname("LICENSE").write(@license.text) unless @license.text.empty?
rescue Fluent::ConfigError
usage("Unknown license: #{license_name}")
rescue => ex
usage("#{ex.class}: #{ex.message}")
end
def create_label(dest, contents)
if dest.exist?
if dest.read == contents
"identical"
else
"conflict"
end
else
"create"
end
end
def overwrite?(dest)
return true if @overwrite_all
loop do
print "Overwrite #{dest}? (enter \"h\" for help) [Ynaqh]"
answer = $stdin.gets.chomp
return true if /\Ay\z/i =~ answer || answer.empty?
case answer
when "n"
return false
when "a"
@overwrite_all = true
return true
when "q"
exit
when "h"
puts <<HELP
\tY - yes, overwrite
\tn - no, do not overwrite
\ta - all, overwrite this and all others
\tq - quit, abort
\th - help, show this help
HELP
end
puts "Retrying..."
end
end
class NoLicense
attr_reader :name, :full_name, :text
def initialize
@name = ""
@full_name = ""
@text = ""
end
def preamble(usename)
""
end
end
class ApacheLicense
LICENSE_URL = "http://www.apache.org/licenses/LICENSE-2.0.txt"
attr_reader :text
def initialize
@text = ""
@preamble_source = ""
@preamble = nil
uri = URI.parse(LICENSE_URL)
uri.open do |io|
@text = io.read
end
@preamble_source = @text[/^(\s*Copyright.+)/m, 1]
end
def name
"Apache-2.0"
end
def full_name
"Apache License, Version 2.0"
end
def preamble(user_name)
@preamble ||= @preamble_source.dup.tap do |source|
source.gsub!(/\[yyyy\]/, "#{Date.today.year}-")
source.gsub!(/\[name of copyright owner\]/, user_name)
source.gsub!(/^ {2}|^$/, "#")
source.chomp!
end
end
end
LICENSE_REGISTRY = Fluent::Registry.new(:license, "")
def self.register_license(license, klass)
LICENSE_REGISTRY.register(license, klass)
end
def self.lookup_license(license)
LICENSE_REGISTRY.lookup(license)
end
{
"no-license" => NoLicense,
"Apache-2.0" => ApacheLicense
}.each do |license, klass|
register_license(license, klass)
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/bundler_injection.rb | lib/fluent/command/bundler_injection.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'rbconfig'
if ENV['BUNDLE_BIN_PATH']
puts 'error: You seem to use `bundle exec` already.'
exit 1
else
begin
bundle_bin = Gem::Specification.find_by_name('bundler').bin_file('bundle')
rescue Gem::LoadError => e
puts "error: #{e}"
exit 1
end
ruby_bin = RbConfig.ruby
system("#{ruby_bin} #{bundle_bin} install")
unless $?.success?
exit $?.exitstatus
end
cmdline = [
ruby_bin,
bundle_bin,
'exec',
ruby_bin,
File.expand_path(File.join(File.dirname(__FILE__), 'fluentd.rb')),
] + ARGV
exec(*cmdline)
exit! 127
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/debug.rb | lib/fluent/command/debug.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'optparse'
op = OptionParser.new
host = '127.0.0.1'
port = 24230
unix = nil
op.on('-h', '--host HOST', "fluent host (default: #{host})") {|s|
host = s
}
op.on('-p', '--port PORT', "debug_agent tcp port (default: #{port})", Integer) {|i|
port = i
}
op.on('-u', '--unix PATH', "use unix socket instead of tcp") {|b|
unix = b
}
singleton_class.module_eval do
define_method(:usage) do |msg|
puts op.to_s
puts "error: #{msg}" if msg
exit 1
end
end
begin
op.parse!(ARGV)
if ARGV.length != 0
usage nil
end
rescue
usage $!.to_s
end
require 'drb/drb'
if unix
uri = "drbunix:#{unix}"
else
uri = "druby://#{host}:#{port}"
end
require 'fluent/log'
require 'fluent/env'
require 'fluent/engine'
require 'fluent/system_config'
require 'serverengine'
include Fluent::SystemConfig::Mixin
dl_opts = {}
dl_opts[:log_level] = ServerEngine::DaemonLogger::TRACE
logger = ServerEngine::DaemonLogger.new(STDERR, dl_opts)
$log = Fluent::Log.new(logger)
Fluent::Engine.init(system_config)
DRb::DRbObject.class_eval do
undef_method :methods
undef_method :instance_eval
undef_method :instance_variables
undef_method :instance_variable_get
end
remote_engine = DRb::DRbObject.new_with_uri(uri)
Fluent.module_eval do
remove_const(:Engine)
const_set(:Engine, remote_engine)
end
include Fluent
puts "Connected to #{uri}."
puts "Usage:"
puts " Fluent::Engine.root_agent.event_router.match('some.tag') : get an output plugin instance"
puts " Fluent::Engine.root_agent.inputs[i] : get input plugin instances"
puts " Fluent::Plugin::OUTPUT_REGISTRY.lookup(name) : load output plugin class (use this if you get DRb::DRbUnknown)"
puts ""
Encoding.default_internal = nil if Encoding.respond_to?(:default_internal)
require 'irb'
IRB.start
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/binlog_reader.rb | lib/fluent/command/binlog_reader.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'optparse'
require 'msgpack'
require 'fluent/msgpack_factory'
require 'fluent/formatter'
require 'fluent/plugin'
require 'fluent/config/element'
require 'fluent/engine'
require 'fluent/version'
class FluentBinlogReader
SUBCOMMAND = %w(cat head formats)
HELP_TEXT = <<HELP
Usage: fluent-binlog-reader <command> [<args>]
Commands of fluent-binlog-reader:
cat : Read files sequentially, writing them to standard output.
head : Display the beginning of a text file.
formats : Display plugins that you can use.
See 'fluent-binlog-reader <command> --help' for more information on a specific command.
HELP
def initialize(argv = ARGV)
@argv = argv
end
def call
command_class = BinlogReaderCommand.const_get(command)
command_class.new(@argv).call
end
private
def command
command = @argv.shift
if command
if command == '--version'
puts "#{File.basename($PROGRAM_NAME)} #{Fluent::VERSION}"
exit 0
elsif !SUBCOMMAND.include?(command)
usage "'#{command}' is not supported: Required subcommand : #{SUBCOMMAND.join(' | ')}"
end
else
usage "Required subcommand : #{SUBCOMMAND.join(' | ')}"
end
command.split('_').map(&:capitalize).join('')
end
def usage(msg = nil)
puts HELP_TEXT
puts "Error: #{msg}" if msg
exit 1
end
end
module BinlogReaderCommand
class Base
def initialize(argv = ARGV)
@argv = argv
@options = { plugin: [] }
@opt_parser = OptionParser.new do |opt|
opt.version = Fluent::VERSION
opt.separator 'Options:'
opt.on('-p DIR', '--plugin', 'add library directory path') do |v|
@options[:plugin] << v
end
end
end
def call
raise NotImplementedError, 'BUG: command MUST implement this method'
end
private
def usage(msg = nil)
puts @opt_parser.to_s
puts "Error: #{msg}" if msg
exit 1
end
def parse_options!
@opt_parser.parse!(@argv)
unless @options[:plugin].empty?
if dir = @options[:plugin].find { |d| !Dir.exist?(d) }
usage "Directory #{dir} doesn't exist"
else
@options[:plugin].each do |d|
Fluent::Plugin.add_plugin_dir(d)
end
end
end
rescue => e
usage e
end
end
module Formattable
DEFAULT_OPTIONS = {
format: :out_file
}
def initialize(argv = ARGV)
super
@options.merge!(DEFAULT_OPTIONS)
configure_option_parser
end
private
def configure_option_parser
@options[:config_params] = {}
@opt_parser.banner = "Usage: fluent-binlog-reader #{self.class.to_s.split('::').last.downcase} [options] file"
@opt_parser.on('-f TYPE', '--format', 'configure output format') do |v|
@options[:format] = v.to_sym
end
@opt_parser.on('-e KEY=VALUE', 'configure formatter config params') do |v|
key, value = v.split('=')
usage "#{v} is invalid. valid format is like `key=value`" unless value
@options[:config_params].merge!(key => value)
end
end
def lookup_formatter(format, params)
conf = Fluent::Config::Element.new('ROOT', '', params, [])
formatter = Fluent::Plugin.new_formatter(format)
if formatter.respond_to?(:configure)
formatter.configure(conf)
end
formatter
rescue => e
usage e
end
end
class Head < Base
include Formattable
DEFAULT_HEAD_OPTIONS = {
count: 5
}
def initialize(argv = ARGV)
super
@options.merge!(default_options)
parse_options!
end
def call
@formatter = lookup_formatter(@options[:format], @options[:config_params])
File.open(@path, 'rb') do |io|
i = 1
Fluent::MessagePackFactory.unpacker(io).each do |(time, record)|
print @formatter.format(@path, time, record) # path is used for tag
break if @options[:count] && i == @options[:count]
i += 1
end
end
end
private
def default_options
DEFAULT_HEAD_OPTIONS
end
def parse_options!
@opt_parser.on('-n COUNT', 'Set the number of lines to display') do |v|
@options[:count] = v.to_i
usage "illegal line count -- #{@options[:count]}" if @options[:count] < 1
end
super
usage 'Path is required' if @argv.empty?
@path = @argv.first
usage "#{@path} is not found" unless File.exist?(@path)
end
end
class Cat < Head
DEFAULT_CAT_OPTIONS = {
count: nil # Overwrite DEFAULT_HEAD_OPTIONS[:count]
}
def default_options
DEFAULT_CAT_OPTIONS
end
end
class Formats < Base
def initialize(argv = ARGV)
super
parse_options!
end
def call
prefix = Fluent::Plugin::FORMATTER_REGISTRY.dir_search_prefix || 'formatter_'
plugin_dirs = @options[:plugin]
unless plugin_dirs.empty?
plugin_dirs.each do |d|
Dir.glob("#{d}/#{prefix}*.rb").each do |path|
require File.absolute_path(path)
end
end
end
$LOAD_PATH.map do |lp|
Dir.glob("#{lp}/#{prefix}*.rb").each do |path|
require path
end
end
puts Fluent::Plugin::FORMATTER_REGISTRY.map.keys
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/ca_generate.rb | lib/fluent/command/ca_generate.rb | require 'openssl'
require 'optparse'
require 'fileutils'
require 'fluent/version'
module Fluent
class CaGenerate
DEFAULT_OPTIONS = {
private_key_length: 2048,
cert_country: 'US',
cert_state: 'CA',
cert_locality: 'Mountain View',
cert_common_name: 'Fluentd Forward CA',
}
HELP_TEXT = <<HELP
Usage: fluent-ca-generate DIR_PATH PRIVATE_KEY_PASSPHRASE [--country COUNTRY] [--state STATE] [--locality LOCALITY] [--common-name COMMON_NAME]
HELP
def initialize(argv = ARGV)
@argv = argv
@options = {}
@opt_parser = OptionParser.new
configure_option_parser
@options.merge!(DEFAULT_OPTIONS)
parse_options!
end
def usage(msg = nil)
puts HELP_TEXT
puts "Error: #{msg}" if msg
exit 1
end
def call
ca_dir, passphrase, = @argv[0..1]
unless ca_dir && passphrase
puts "#{HELP_TEXT}"
puts ''
exit 1
end
FileUtils.mkdir_p(ca_dir)
cert, key = Fluent::CaGenerate.generate_ca_pair(@options)
key_data = key.export(OpenSSL::Cipher.new('aes256'), passphrase)
File.open(File.join(ca_dir, 'ca_key.pem'), 'w') do |file|
file.write key_data
end
File.open(File.join(ca_dir, 'ca_cert.pem'), 'w') do |file|
file.write cert.to_pem
end
puts "successfully generated: ca_key.pem, ca_cert.pem"
puts "copy and use ca_cert.pem to client(out_forward)"
end
def self.certificates_from_file(path)
data = File.read(path)
pattern = Regexp.compile('-+BEGIN CERTIFICATE-+\n(?:[^-]*\n)+-+END CERTIFICATE-+\n', Regexp::MULTILINE)
list = []
data.scan(pattern){|match| list << OpenSSL::X509::Certificate.new(match)}
list
end
def self.generate_ca_pair(opts={})
key = OpenSSL::PKey::RSA.generate(opts[:private_key_length])
issuer = subject = OpenSSL::X509::Name.new
subject.add_entry('C', opts[:cert_country])
subject.add_entry('ST', opts[:cert_state])
subject.add_entry('L', opts[:cert_locality])
subject.add_entry('CN', opts[:cert_common_name])
digest = OpenSSL::Digest::SHA256.new
factory = OpenSSL::X509::ExtensionFactory.new
cert = OpenSSL::X509::Certificate.new
cert.not_before = Time.at(0)
cert.not_after = Time.now + 5 * 365 * 86400 # 5 years after
cert.public_key = key
cert.serial = 1
cert.issuer = issuer
cert.subject = subject
cert.add_extension(factory.create_extension('basicConstraints', 'CA:TRUE'))
cert.sign(key, digest)
return cert, key
end
def self.generate_server_pair(opts={})
key = OpenSSL::PKey::RSA.generate(opts[:private_key_length])
ca_key = OpenSSL::PKey::read(File.read(opts[:ca_key_path]), opts[:ca_key_passphrase])
ca_cert = OpenSSL::X509::Certificate.new(File.read(opts[:ca_cert_path]))
issuer = ca_cert.issuer
subject = OpenSSL::X509::Name.new
subject.add_entry('C', opts[:country])
subject.add_entry('ST', opts[:state])
subject.add_entry('L', opts[:locality])
subject.add_entry('CN', opts[:common_name])
digest = OpenSSL::Digest::SHA256.new
cert = OpenSSL::X509::Certificate.new
cert.not_before = Time.at(0)
cert.not_after = Time.now + 5 * 365 * 86400 # 5 years after
cert.public_key = key
cert.serial = 2
cert.issuer = issuer
cert.subject = subject
factory = OpenSSL::X509::ExtensionFactory.new
server_cert.add_extension(factory.create_extension('basicConstraints', 'CA:FALSE'))
server_cert.add_extension(factory.create_extension('nsCertType', 'server'))
cert.sign ca_key, digest
return cert, key
end
def self.generate_self_signed_server_pair(opts={})
key = OpenSSL::PKey::RSA.generate(opts[:private_key_length])
issuer = subject = OpenSSL::X509::Name.new
subject.add_entry('C', opts[:country])
subject.add_entry('ST', opts[:state])
subject.add_entry('L', opts[:locality])
subject.add_entry('CN', opts[:common_name])
digest = OpenSSL::Digest::SHA256.new
cert = OpenSSL::X509::Certificate.new
cert.not_before = Time.at(0)
cert.not_after = Time.now + 5 * 365 * 86400 # 5 years after
cert.public_key = key
cert.serial = 1
cert.issuer = issuer
cert.subject = subject
cert.sign(key, digest)
return cert, key
end
private
def configure_option_parser
@opt_parser.banner = HELP_TEXT
@opt_parser.version = Fluent::VERSION
@opt_parser.on('--key-length [KEY_LENGTH]',
"configure key length. (default: #{DEFAULT_OPTIONS[:private_key_length]})") do |v|
@options[:private_key_length] = v.to_i
end
@opt_parser.on('--country [COUNTRY]',
"configure country. (default: #{DEFAULT_OPTIONS[:cert_country]})") do |v|
@options[:cert_country] = v.upcase
end
@opt_parser.on('--state [STATE]',
"configure state. (default: #{DEFAULT_OPTIONS[:cert_state]})") do |v|
@options[:cert_state] = v
end
@opt_parser.on('--locality [LOCALITY]',
"configure locality. (default: #{DEFAULT_OPTIONS[:cert_locality]})") do |v|
@options[:cert_locality] = v
end
@opt_parser.on('--common-name [COMMON_NAME]',
"configure common name (default: #{DEFAULT_OPTIONS[:cert_common_name]})") do |v|
@options[:cert_common_name] = v
end
end
def parse_options!
@opt_parser.parse!(@argv)
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/plugin_config_formatter.rb | lib/fluent/command/plugin_config_formatter.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "erb"
require "optparse"
require "pathname"
require "fluent/plugin"
require "fluent/env"
require "fluent/engine"
require "fluent/system_config"
require "fluent/config/element"
require 'fluent/version'
class FluentPluginConfigFormatter
AVAILABLE_FORMATS = [:markdown, :txt, :json]
SUPPORTED_TYPES = [
"input", "output", "filter",
"buffer", "parser", "formatter", "storage",
"service_discovery"
]
DOCS_BASE_URL = "https://docs.fluentd.org/v/1.0"
DOCS_PLUGIN_HELPER_BASE_URL = "#{DOCS_BASE_URL}/plugin-helper-overview/"
def initialize(argv = ARGV)
@argv = argv
@compact = false
@format = :markdown
@verbose = false
@libs = []
@plugin_dirs = []
@table = false
@options = {}
prepare_option_parser
end
def call
parse_options!
init_libraries
@plugin = Fluent::Plugin.__send__("new_#{@plugin_type}", @plugin_name)
dumped_config = {}
if @plugin.class.respond_to?(:plugin_helpers)
dumped_config[:plugin_helpers] = @plugin.class.plugin_helpers
end
@plugin.class.ancestors.reverse_each do |plugin_class|
next unless plugin_class.respond_to?(:dump_config_definition)
unless @verbose
next if /::PluginHelper::/.match?(plugin_class.name)
end
dumped_config_definition = plugin_class.dump_config_definition
dumped_config[plugin_class.name] = dumped_config_definition unless dumped_config_definition.empty?
end
case @format
when :txt
puts dump_txt(dumped_config)
when :markdown
puts dump_markdown(dumped_config)
when :json
puts dump_json(dumped_config)
end
end
private
def dump_txt(dumped_config)
dumped = ""
plugin_helpers = dumped_config.delete(:plugin_helpers)
if plugin_helpers && !plugin_helpers.empty?
dumped << "helpers: #{plugin_helpers.join(',')}\n"
end
if @verbose
dumped_config.each do |name, config|
dumped << "#{name}\n"
dumped << dump_section_txt(config)
end
else
configs = dumped_config.values
root_section = configs.shift
configs.each do |config|
root_section.update(config)
end
dumped << dump_section_txt(root_section)
end
dumped
end
def dump_section_txt(base_section, level = 0)
dumped = ""
indent = " " * level
if base_section[:section]
sections = []
params = base_section
else
sections, params = base_section.partition {|_name, value| value[:section] }
end
params.each do |name, config|
next if name == :section
dumped << "#{indent}#{name}: #{config[:type]}: (#{config[:default].inspect})"
dumped << " # #{config[:description]}" if config.key?(:description)
dumped << "\n"
end
sections.each do |section_name, sub_section|
required = sub_section.delete(:required)
multi = sub_section.delete(:multi)
alias_name = sub_section.delete(:alias)
required_label = required ? "required" : "optional"
multi_label = multi ? "multiple" : "single"
alias_label = "alias: #{alias_name}"
dumped << "#{indent}<#{section_name}>: #{required_label}, #{multi_label}"
if alias_name
dumped << ", #{alias_label}\n"
else
dumped << "\n"
end
sub_section.delete(:section)
dumped << dump_section_txt(sub_section, level + 1)
end
dumped
end
def dump_markdown(dumped_config)
dumped = ""
plugin_helpers = dumped_config.delete(:plugin_helpers)
if plugin_helpers && !plugin_helpers.empty?
dumped = "## Plugin helpers\n\n"
plugin_helpers.each do |plugin_helper|
dumped << "* #{plugin_helper_markdown_link(plugin_helper)}\n"
end
dumped << "\n"
end
dumped_config.each do |name, config|
if name == @plugin.class.name
dumped << "## #{name}\n\n"
dumped << dump_section_markdown(config)
else
dumped << "* See also: #{plugin_overview_markdown_link(name)}\n\n"
end
end
dumped
end
def dump_section_markdown(base_section, level = 0)
dumped = ""
if base_section[:section]
sections = []
params = base_section
else
sections, params = base_section.partition {|_name, value| value[:section] }
end
if @table && (not params.empty?)
dumped << "### Configuration\n\n"
dumped << "|parameter|type|description|default|\n"
dumped << "|---|---|---|---|\n"
end
params.each do |name, config|
next if name == :section
template_name = if @compact
"param.md-compact.erb"
elsif @table
"param.md-table.erb"
else
"param.md.erb"
end
template = template_path(template_name).read
dumped <<
if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+
ERB.new(template, trim_mode: "-")
else
ERB.new(template, nil, "-")
end.result(binding)
end
dumped << "\n"
sections.each do |section_name, sub_section|
required = sub_section.delete(:required)
multi = sub_section.delete(:multi)
alias_name = sub_section.delete(:alias)
sub_section.delete(:section)
template = template_path("section.md.erb").read
dumped <<
if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+
ERB.new(template, trim_mode: "-")
else
ERB.new(template, nil, "-")
end.result(binding)
end
dumped
end
def dump_json(dumped_config)
if @compact
JSON.generate(dumped_config)
else
JSON.pretty_generate(dumped_config)
end
end
def plugin_helper_url(plugin_helper)
"#{DOCS_PLUGIN_HELPER_BASE_URL}api-plugin-helper-#{plugin_helper}"
end
def plugin_helper_markdown_link(plugin_helper)
"[#{plugin_helper}](#{plugin_helper_url(plugin_helper)})"
end
def plugin_overview_url(class_name)
plugin_type = class_name.slice(/::(\w+)\z/, 1).downcase
"#{DOCS_BASE_URL}/#{plugin_type}#overview"
end
def plugin_overview_markdown_link(class_name)
plugin_type = class_name.slice(/::(\w+)\z/, 1)
"[#{plugin_type} Plugin Overview](#{plugin_overview_url(class_name)})"
end
def usage(message = nil)
puts @parser.to_s
puts
puts "Error: #{message}" if message
exit(false)
end
def prepare_option_parser
@parser = OptionParser.new
@parser.version = Fluent::VERSION
@parser.banner = <<BANNER
Usage: #{$0} [options] <type> <name>
Output plugin config definitions
Arguments:
\ttype: #{SUPPORTED_TYPES.join(",")}
\tname: registered plugin name
Options:
BANNER
@parser.on("--verbose", "Be verbose") do
@verbose = true
end
@parser.on("-c", "--compact", "Compact output") do
@compact = true
end
@parser.on("-f", "--format=FORMAT", "Specify format. (#{AVAILABLE_FORMATS.join(',')})") do |s|
format = s.to_sym
usage("Unsupported format: #{s}") unless AVAILABLE_FORMATS.include?(format)
@format = format
end
@parser.on("-I PATH", "Add PATH to $LOAD_PATH") do |s|
$LOAD_PATH.unshift(s)
end
@parser.on("-r NAME", "Load library") do |s|
@libs << s
end
@parser.on("-p", "--plugin=DIR", "Add plugin directory") do |s|
@plugin_dirs << s
end
@parser.on("-t", "--table", "Use table syntax to dump parameters") do
@table = true
end
end
def parse_options!
@parser.parse!(@argv)
raise "Must specify plugin type and name" unless @argv.size == 2
@plugin_type, @plugin_name = @argv
@options = {
compact: @compact,
format: @format,
verbose: @verbose,
}
rescue => e
usage(e)
end
def init_libraries
@libs.each do |lib|
require lib
end
@plugin_dirs.each do |dir|
if Dir.exist?(dir)
dir = File.expand_path(dir)
Fluent::Plugin.add_plugin_dir(dir)
end
end
end
def template_path(name)
(Pathname(__dir__) + "../../../templates/plugin_config_formatter/#{name}").realpath
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/fluentd.rb | lib/fluent/command/fluentd.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'optparse'
require 'fluent/supervisor'
require 'fluent/log'
require 'fluent/env'
require 'fluent/version'
$fluentdargv = Marshal.load(Marshal.dump(ARGV))
op = OptionParser.new
op.version = Fluent::VERSION
default_opts = Fluent::Supervisor.default_options
cmd_opts = {}
op.on('-s', "--setup [DIR=#{File.dirname(Fluent::DEFAULT_CONFIG_PATH)}]", "install sample configuration file to the directory") {|s|
cmd_opts[:setup_path] = s || File.dirname(Fluent::DEFAULT_CONFIG_PATH)
}
op.on('-c', '--config PATH', "config file path (default: #{Fluent::DEFAULT_CONFIG_PATH})") {|s|
cmd_opts[:config_path] = s
}
op.on('--dry-run', "Check fluentd setup is correct or not", TrueClass) {|b|
cmd_opts[:dry_run] = b
}
op.on('--show-plugin-config=PLUGIN', "[DEPRECATED] Show PLUGIN configuration and exit(ex: input:dummy)") {|plugin|
cmd_opts[:show_plugin_config] = plugin
}
op.on('-p', '--plugin DIR', "add plugin directory") {|s|
(cmd_opts[:plugin_dirs] ||= default_opts[:plugin_dirs]) << s
}
op.on('-I PATH', "add library path") {|s|
$LOAD_PATH << s
}
op.on('-r NAME', "load library") {|s|
(cmd_opts[:libs] ||= []) << s
}
op.on('-d', '--daemon PIDFILE', "daemonize fluent process") {|s|
cmd_opts[:daemonize] = s
}
op.on('--under-supervisor', "run fluent worker under supervisor (this option is NOT for users)") {
cmd_opts[:supervise] = false
}
op.on('--no-supervisor', "run fluent worker without supervisor") {
cmd_opts[:supervise] = false
cmd_opts[:standalone_worker] = true
}
op.on('--workers NUM', "specify the number of workers under supervisor") { |i|
cmd_opts[:workers] = i.to_i
}
op.on('--user USER', "change user") {|s|
cmd_opts[:chuser] = s
}
op.on('--group GROUP', "change group") {|s|
cmd_opts[:chgroup] = s
}
op.on('--umask UMASK', "change umask") {|s|
cmd_opts[:chumask] = s
}
op.on('-o', '--log PATH', "log file path") {|s|
cmd_opts[:log_path] = s
}
op.on('--log-rotate-age AGE', 'generations to keep rotated log files') {|age|
if Fluent::Log::LOG_ROTATE_AGE.include?(age)
cmd_opts[:log_rotate_age] = age
else
begin
cmd_opts[:log_rotate_age] = Integer(age)
rescue TypeError, ArgumentError
usage "log-rotate-age should be #{ROTATE_AGE.join(', ')} or a number"
end
end
}
op.on('--log-rotate-size BYTES', 'sets the byte size to rotate log files') {|s|
cmd_opts[:log_rotate_size] = s.to_i
}
op.on('--log-event-verbose', 'enable log events during process startup/shutdown') {|b|
cmd_opts[:log_event_verbose] = b
}
op.on('-i', '--inline-config CONFIG_STRING', "inline config which is appended to the config file on-the-fly") {|s|
cmd_opts[:inline_config] = s
}
op.on('--emit-error-log-interval SECONDS', "suppress interval seconds of emit error logs") {|s|
cmd_opts[:suppress_interval] = s.to_i
}
op.on('--suppress-repeated-stacktrace [VALUE]', "suppress repeated stacktrace", TrueClass) {|b|
b = true if b.nil?
cmd_opts[:suppress_repeated_stacktrace] = b
}
op.on('--without-source', "invoke a fluentd without input plugins", TrueClass) {|b|
cmd_opts[:without_source] = b
}
unless Fluent.windows?
op.on('--with-source-only', "Invoke a fluentd only with input plugins. The data is stored in a temporary buffer. Send SIGWINCH to cancel this mode and process the data (Not supported on Windows).", TrueClass) {|b|
cmd_opts[:with_source_only] = b
}
end
op.on('--config-file-type VALUE', 'guessing file type of fluentd configuration. yaml/yml or guess') { |s|
if (s == 'yaml') || (s == 'yml')
cmd_opts[:config_file_type] = s.to_sym
elsif (s == 'guess')
cmd_opts[:config_file_type] = s.to_sym
else
usage '--config-file-type accepts yaml/yml or guess'
end
}
op.on('--use-v1-config', "Use v1 configuration format (default)", TrueClass) {|b|
cmd_opts[:use_v1_config] = b
}
op.on('--use-v0-config', "Use v0 configuration format", TrueClass) {|b|
cmd_opts[:use_v1_config] = !b
}
op.on('--strict-config-value', "Parse config values strictly", TrueClass) {|b|
cmd_opts[:strict_config_value] = b
}
op.on('--enable-input-metrics', "[DEPRECATED] Enable input plugin metrics on fluentd", TrueClass) {|b|
cmd_opts[:enable_input_metrics] = b
}
op.on('--disable-input-metrics', "Disable input plugin metrics on fluentd", FalseClass) {|b|
cmd_opts[:enable_input_metrics] = b
}
op.on('--enable-size-metrics', "Enable plugin record size metrics on fluentd", TrueClass) {|b|
cmd_opts[:enable_size_metrics] = b
}
op.on('-v', '--verbose', "increase verbose level (-v: debug, -vv: trace)", TrueClass) {|b|
return unless b
cur_level = cmd_opts.fetch(:log_level, default_opts[:log_level])
cmd_opts[:log_level] = [cur_level - 1, Fluent::Log::LEVEL_TRACE].max
}
op.on('-q', '--quiet', "decrease verbose level (-q: warn, -qq: error)", TrueClass) {|b|
return unless b
cur_level = cmd_opts.fetch(:log_level, default_opts[:log_level])
cmd_opts[:log_level] = [cur_level + 1, Fluent::Log::LEVEL_ERROR].min
}
op.on('--suppress-config-dump', "suppress config dumping when fluentd starts", TrueClass) {|b|
cmd_opts[:suppress_config_dump] = b
}
op.on('-g', '--gemfile GEMFILE', "Gemfile path") {|s|
cmd_opts[:gemfile] = s
}
op.on('-G', '--gem-path GEM_INSTALL_PATH', "Gemfile install path (default: $(dirname $gemfile)/vendor/bundle)") {|s|
cmd_opts[:gem_install_path] = s
}
op.on('--conf-encoding ENCODING', "specify configuration file encoding") { |s|
cmd_opts[:conf_encoding] = s
}
op.on('--disable-shared-socket', "Don't open shared socket for multiple workers") { |b|
cmd_opts[:disable_shared_socket] = b
}
if Fluent.windows?
cmd_opts.merge!(
:winsvc_name => 'fluentdwinsvc',
:winsvc_display_name => 'Fluentd Windows Service',
:winsvc_desc => 'Fluentd is an event collector system.',
)
op.on('-x', '--signame INTSIGNAME', "an object name which is used for Windows Service signal (Windows only)") {|s|
cmd_opts[:signame] = s
}
op.on('--reg-winsvc MODE', "install/uninstall as Windows Service. (i: install, u: uninstall) (Windows only)") {|s|
cmd_opts[:regwinsvc] = s
}
op.on('--[no-]reg-winsvc-auto-start', "Automatically start the Windows Service at boot. (only effective with '--reg-winsvc i') (Windows only)") {|s|
cmd_opts[:regwinsvcautostart] = s
}
op.on('--[no-]reg-winsvc-delay-start', "Automatically start the Windows Service at boot with delay. (only effective with '--reg-winsvc i' and '--reg-winsvc-auto-start') (Windows only)") {|s|
cmd_opts[:regwinsvcdelaystart] = s
}
op.on('--reg-winsvc-fluentdopt OPTION', "specify fluentd option parameters for Windows Service. (Windows only)") {|s|
cmd_opts[:fluentdopt] = s
}
op.on('--winsvc-name NAME', "The Windows Service name to run as (Windows only)") {|s|
cmd_opts[:winsvc_name] = s
}
op.on('--winsvc-display-name DISPLAY_NAME', "The Windows Service display name (Windows only)") {|s|
cmd_opts[:winsvc_display_name] = s
}
op.on('--winsvc-desc DESC', "The Windows Service description (Windows only)") {|s|
cmd_opts[:winsvc_desc] = s
}
end
singleton_class.module_eval do
define_method(:usage) do |msg|
puts op.to_s
puts "error: #{msg}" if msg
exit 1
end
end
begin
rest = op.parse(ARGV)
if rest.length != 0
usage nil
end
rescue
usage $!.to_s
end
opts = default_opts.merge(cmd_opts)
##
## Bundler injection
#
if ENV['FLUENTD_DISABLE_BUNDLER_INJECTION'] != '1' && gemfile = opts[:gemfile]
ENV['BUNDLE_GEMFILE'] = gemfile
if path = opts[:gem_install_path]
ENV['BUNDLE_PATH'] = path
else
ENV['BUNDLE_PATH'] = File.expand_path(File.join(File.dirname(gemfile), 'vendor/bundle'))
end
ENV['FLUENTD_DISABLE_BUNDLER_INJECTION'] = '1'
load File.expand_path(File.join(File.dirname(__FILE__), 'bundler_injection.rb'))
end
if setup_path = opts[:setup_path]
require 'fileutils'
FileUtils.mkdir_p File.join(setup_path, "plugin")
confpath = File.join(setup_path, "fluent.conf")
if File.exist?(confpath)
puts "#{confpath} already exists."
else
File.open(confpath, "w") {|f|
conf = File.read File.join(File.dirname(__FILE__), "..", "..", "..", "fluent.conf")
f.write conf
}
puts "Installed #{confpath}."
end
exit 0
end
early_exit = false
start_service = false
if winsvcinstmode = opts[:regwinsvc]
require 'fileutils'
require "win32/service"
require "win32/registry"
include Win32
case winsvcinstmode
when 'i'
binary_path = File.join(File.dirname(__FILE__), "..")
ruby_path = ServerEngine.ruby_bin_path
start_type = Service::DEMAND_START
if opts[:regwinsvcautostart]
start_type = Service::AUTO_START
start_service = true
end
Service.create(
service_name: opts[:winsvc_name],
host: nil,
service_type: Service::WIN32_OWN_PROCESS,
description: opts[:winsvc_desc],
start_type: start_type,
error_control: Service::ERROR_NORMAL,
binary_path_name: "\"#{ruby_path}\" -C \"#{binary_path}\" winsvc.rb --service-name #{opts[:winsvc_name]}",
load_order_group: "",
dependencies: [""],
display_name: opts[:winsvc_display_name]
)
if opts[:regwinsvcdelaystart]
Service.configure(
service_name: opts[:winsvc_name],
delayed_start: true
)
end
when 'u'
if Service.status(opts[:winsvc_name]).current_state != 'stopped'
begin
Service.stop(opts[:winsvc_name])
rescue => ex
puts "Warning: Failed to stop service: ", ex
end
end
Service.delete(opts[:winsvc_name])
else
# none
end
early_exit = true
end
if fluentdopt = opts[:fluentdopt]
Win32::Registry::HKEY_LOCAL_MACHINE.open("SYSTEM\\CurrentControlSet\\Services\\#{opts[:winsvc_name]}", Win32::Registry::KEY_ALL_ACCESS) do |reg|
reg['fluentdopt', Win32::Registry::REG_SZ] = fluentdopt
end
early_exit = true
end
if start_service
Service.start(opts[:winsvc_name])
end
exit 0 if early_exit
if opts[:supervise]
supervisor = Fluent::Supervisor.new(cmd_opts)
supervisor.configure(supervisor: true)
supervisor.run_supervisor(dry_run: opts[:dry_run])
else
if opts[:standalone_worker] && opts[:workers] && opts[:workers] > 1
puts "Error: multi workers is not supported with --no-supervisor"
exit 2
end
worker = Fluent::Supervisor.new(cmd_opts)
worker.configure
if opts[:daemonize] && opts[:standalone_worker]
require 'fluent/daemonizer'
args = ARGV.dup
i = args.index('--daemon')
args.delete_at(i + 1) # value of --daemon
args.delete_at(i) # --daemon itself
Fluent::Daemonizer.daemonize(opts[:daemonize], args) do
worker.run_worker
end
else
worker.run_worker
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/command/cat.rb | lib/fluent/command/cat.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'optparse'
require 'fluent/env'
require 'fluent/time'
require 'fluent/msgpack_factory'
require 'fluent/version'
op = OptionParser.new
op.banner += " <tag>"
op.version = Fluent::VERSION
port = 24224
host = '127.0.0.1'
unix = false
socket_path = Fluent::DEFAULT_SOCKET_PATH
config_path = Fluent::DEFAULT_CONFIG_PATH
format = 'json'
message_key = 'message'
time_as_integer = false
retry_limit = 5
event_time = nil
op.on('-p', '--port PORT', "fluent tcp port (default: #{port})", Integer) {|i|
port = i
}
op.on('-h', '--host HOST', "fluent host (default: #{host})") {|s|
host = s
}
op.on('-u', '--unix', "use unix socket instead of tcp", TrueClass) {|b|
unix = b
}
op.on('-s', '--socket PATH', "unix socket path (default: #{socket_path})") {|s|
socket_path = s
}
op.on('-f', '--format FORMAT', "input format (default: #{format})") {|s|
format = s
}
op.on('--json', "same as: -f json", TrueClass) {|b|
format = 'json'
}
op.on('--msgpack', "same as: -f msgpack", TrueClass) {|b|
format = 'msgpack'
}
op.on('--none', "same as: -f none", TrueClass) {|b|
format = 'none'
}
op.on('--message-key KEY', "key field for none format (default: #{message_key})") {|s|
message_key = s
}
op.on('--time-as-integer', "Send time as integer for v0.12 or earlier", TrueClass) { |b|
time_as_integer = true
}
op.on('--retry-limit N', "Specify the number of retry limit (default: #{retry_limit})", Integer) {|n|
retry_limit = n
}
op.on('--event-time TIME_STRING', "Specify the time expression string (default: nil)") {|v|
event_time = v
}
singleton_class.module_eval do
define_method(:usage) do |msg|
puts op.to_s
puts "error: #{msg}" if msg
exit 1
end
end
begin
op.parse!(ARGV)
if ARGV.length != 1
usage nil
end
tag = ARGV.shift
rescue
usage $!.to_s
end
require 'socket'
require 'json'
require 'msgpack'
require 'fluent/ext_monitor_require'
class Writer
include MonitorMixin
RetryLimitError = Class.new(StandardError)
class TimerThread
def initialize(writer)
@writer = writer
end
def start
@finish = false
@thread = Thread.new(&method(:run))
end
def shutdown
@finish = true
@thread.join
end
def run
until @finish
sleep 1
@writer.on_timer
end
end
end
def initialize(tag, connector, time_as_integer: false, retry_limit: 5, event_time: nil)
@tag = tag
@connector = connector
@socket = false
@socket_time = Time.now.to_i
@socket_ttl = 10 # TODO
@error_history = []
@pending = []
@pending_limit = 1024 # TODO
@retry_wait = 1
@retry_limit = retry_limit
@time_as_integer = time_as_integer
@event_time = event_time
super()
end
def secondary_record?(record)
record.class != Hash &&
record.size == 2 &&
record.first.class == Fluent::EventTime &&
record.last.class == Hash
end
def write(record)
unless secondary_record?(record)
if record.class != Hash
raise ArgumentError, "Input must be a map (got #{record.class})"
end
end
time = if @event_time
Fluent::EventTime.parse(@event_time)
else
Fluent::EventTime.now
end
time = time.to_i if @time_as_integer
entry = if secondary_record?(record)
# Even though secondary contains Fluent::EventTime in record,
# fluent-cat just ignore it and set Fluent::EventTime.now instead.
# This specification is adopted to keep consistency.
[time, record.last]
else
[time, record]
end
synchronize {
unless write_impl([entry])
# write failed
@pending.push(entry)
while @pending.size > @pending_limit
# exceeds pending limit; trash oldest record
time, record = @pending.shift
abort_message(time, record)
end
end
}
end
def on_timer
now = Time.now.to_i
synchronize {
unless @pending.empty?
# flush pending records
if write_impl(@pending)
# write succeeded
@pending.clear
end
end
if @socket && @socket_time + @socket_ttl < now
# socket is not used @socket_ttl seconds
close
end
}
end
def close
@socket.close
@socket = nil
end
def start
@timer = TimerThread.new(self)
@timer.start
self
end
def shutdown
@timer.shutdown
end
private
def write_impl(array)
socket = get_socket
unless socket
return false
end
begin
packer = Fluent::MessagePackFactory.packer
socket.write packer.pack([@tag, array])
socket.flush
rescue
$stderr.puts "write failed: #{$!}"
close
return false
end
return true
end
def get_socket
unless @socket
unless try_connect
return nil
end
end
@socket_time = Time.now.to_i
return @socket
end
def try_connect
begin
now = Time.now.to_i
unless @error_history.empty?
# wait before re-connecting
wait = 1 #@retry_wait * (2 ** (@error_history.size-1))
if now <= @socket_time + wait
sleep(wait)
try_connect
end
end
@socket = @connector.call
@error_history.clear
return true
rescue RetryLimitError => ex
raise ex
rescue
$stderr.puts "connect failed: #{$!}"
@error_history << $!
@socket_time = now
if @retry_limit < @error_history.size
# abort all pending records
@pending.each {|(time, record)|
abort_message(time, record)
}
@pending.clear
@error_history.clear
raise RetryLimitError, "exceed retry limit"
else
retry
end
end
end
def abort_message(time, record)
$stdout.puts "!#{time}:#{JSON.generate(record)}"
end
end
if unix
connector = Proc.new {
UNIXSocket.open(socket_path)
}
else
connector = Proc.new {
TCPSocket.new(host, port)
}
end
w = Writer.new(tag, connector, time_as_integer: time_as_integer, retry_limit: retry_limit, event_time: event_time)
w.start
case format
when 'json'
begin
while line = $stdin.gets
record = JSON.parse(line)
w.write(record)
end
rescue
$stderr.puts $!
exit 1
end
when 'msgpack'
require 'fluent/engine'
begin
u = Fluent::MessagePackFactory.msgpack_unpacker($stdin)
u.each {|record|
w.write(record)
}
rescue EOFError
rescue
$stderr.puts $!
exit 1
end
when 'none'
begin
while line = $stdin.gets
record = { message_key => line.chomp }
w.write(record)
end
rescue
$stderr.puts $!
exit 1
end
else
$stderr.puts "Unknown format '#{format}'"
exit 1
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/formatter_test.rb | lib/fluent/test/formatter_test.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/formatter'
require 'fluent/config'
require 'fluent/plugin'
module Fluent
module Test
class FormatterTestDriver
def initialize(klass_or_str, proc=nil, &block)
if klass_or_str.is_a?(Class)
if block
# Create new class for test w/ overwritten methods
# klass.dup is worse because its ancestors does NOT include original class name
klass_name = klass_or_str.name
klass_or_str = Class.new(klass_or_str)
klass_or_str.define_singleton_method(:name) { klass_name }
klass_or_str.module_eval(&block)
end
@instance = klass_or_str.new
elsif klass_or_str.is_a?(String)
@instance = Fluent::Plugin.new_formatter(klass_or_str)
else
@instance = klass_or_str
end
@config = Config.new
end
attr_reader :instance, :config
def configure(conf)
case conf
when Fluent::Config::Element
@config = conf
when String
@config = Config.parse(conf, 'fluent.conf')
when Hash
@config = Config::Element.new('ROOT', '', conf, [])
else
raise "Unknown type... #{conf}"
end
@instance.configure(@config)
self
end
def format(tag, time, record)
@instance.format(tag, time, record)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/log.rb | lib/fluent/test/log.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'serverengine'
require 'fluent/log'
module Fluent
module Test
class DummyLogDevice
attr_reader :logs
attr_accessor :flush_logs
def initialize
@logs = []
@flush_logs = true
@use_stderr = false
end
def reset
@logs = [] if @flush_logs
end
def tty?
false
end
def puts(*args)
args.each{ |arg| write(arg + "\n") }
end
def write(message)
if @use_stderr
STDERR.write message
end
@logs.push message
end
def flush
true
end
def close
true
end
end
class TestLogger < Fluent::PluginLogger
def initialize
@logdev = DummyLogDevice.new
dl_opts = {}
dl_opts[:log_level] = ServerEngine::DaemonLogger::INFO
logger = ServerEngine::DaemonLogger.new(@logdev, dl_opts)
log = Fluent::Log.new(logger)
super(log)
end
def reset
@logdev.reset
end
def logs
@logdev.logs
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/input_test.rb | lib/fluent/test/input_test.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/engine'
require 'fluent/time'
require 'fluent/test/base'
module Fluent
module Test
class InputTestDriver < TestDriver
def initialize(klass, &block)
super(klass, &block)
@emit_streams = []
@event_streams = []
@expects = nil
# for checking only the number of emitted records during run
@expected_emits_length = nil
@run_timeout = 5
@run_post_conditions = []
end
def expect_emit(tag, time, record)
(@expects ||= []) << [tag, time, record]
self
end
def expected_emits
@expects ||= []
end
attr_accessor :expected_emits_length
attr_accessor :run_timeout
attr_reader :emit_streams, :event_streams
def emits
all = []
@emit_streams.each {|tag,events|
events.each {|time,record|
all << [tag, time, record]
}
}
all
end
def events
all = []
@emit_streams.each {|tag,events|
all.concat events
}
all
end
def records
all = []
@emit_streams.each {|tag,events|
events.each {|time,record|
all << record
}
}
all
end
def register_run_post_condition(&block)
if block
@run_post_conditions << block
end
end
def register_run_breaking_condition(&block)
if block
@run_breaking_conditions ||= []
@run_breaking_conditions << block
end
end
def run_should_stop?
# Should stop running if post conditions are not registered.
return true unless @run_post_conditions
# Should stop running if all of the post conditions are true.
return true if @run_post_conditions.all? {|proc| proc.call }
# Should stop running if any of the breaking conditions is true.
# In this case, some post conditions may be not true.
return true if @run_breaking_conditions && @run_breaking_conditions.any? {|proc| proc.call }
false
end
module EmitStreamWrapper
def emit_stream_callee=(method)
@emit_stream_callee = method
end
def emit_stream(tag, es)
@emit_stream_callee.call(tag, es)
end
end
def run(num_waits = 10)
m = method(:emit_stream)
unless Engine.singleton_class.ancestors.include?(EmitStreamWrapper)
Engine.singleton_class.prepend EmitStreamWrapper
end
Engine.emit_stream_callee = m
unless instance.router.singleton_class.ancestors.include?(EmitStreamWrapper)
instance.router.singleton_class.prepend EmitStreamWrapper
end
instance.router.emit_stream_callee = m
super(num_waits) {
yield if block_given?
if @expected_emits_length || @expects || @run_post_conditions
# counters for emits and emit_streams
i, j = 0, 0
# Events of expected length will be emitted at the end.
max_length = @expected_emits_length
max_length ||= @expects.length if @expects
if max_length
register_run_post_condition do
i == max_length
end
end
# Set running timeout to avoid infinite loop caused by some errors.
started_at = Time.now
register_run_breaking_condition do
Time.now >= started_at + @run_timeout
end
until run_should_stop?
if j >= @emit_streams.length
sleep 0.01
next
end
tag, events = @emit_streams[j]
events.each do |time, record|
if @expects
assert_equal(@expects[i], [tag, time, record])
assert_equal_event_time(@expects[i][1], time) if @expects[i][1].is_a?(Fluent::EventTime)
end
i += 1
end
j += 1
end
assert_equal(@expects.length, i) if @expects
end
}
self
end
private
def emit_stream(tag, es)
@event_streams << es
@emit_streams << [tag, es.to_a]
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/filter_test.rb | lib/fluent/test/filter_test.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/base'
require 'fluent/event'
module Fluent
module Test
class FilterTestDriver < TestDriver
def initialize(klass, tag = 'filter.test', &block)
super(klass, &block)
@tag = tag
@events = {}
@filtered = MultiEventStream.new
end
attr_reader :filtered
attr_accessor :tag
def emit(record, time = EventTime.now)
emit_with_tag(@tag, record, time)
end
alias_method :filter, :emit
def emit_with_tag(tag, record, time = EventTime.now)
@events[tag] ||= MultiEventStream.new
@events[tag].add(time, record)
end
alias_method :filter_with_tag, :emit_with_tag
def filter_stream(es)
filter_stream_with_tag(@tag, es)
end
def filter_stream_with_tag(tag, es)
@events[tag] = es
end
def filtered_as_array
all = []
@filtered.each { |time, record|
all << [@tag, time, record]
}
all
end
alias_method :emits, :filtered_as_array # emits is for consistent with other drivers
# Almost filters don't use threads so default is 0. It reduces test time.
def run(num_waits = 0)
super(num_waits) {
yield if block_given?
@events.each { |tag, es|
processed = @instance.filter_stream(tag, es)
processed.each { |time, record|
@filtered.add(time, record)
}
}
}
self
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/helpers.rb | lib/fluent/test/helpers.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config/element'
require 'fluent/msgpack_factory'
require 'fluent/time'
module Fluent
module Test
module Helpers
# See "Example Custom Assertion: https://test-unit.github.io/test-unit/en/Test/Unit/Assertions.html
def assert_equal_event_time(expected, actual, message = nil)
expected_s = "#{Time.at(expected.sec)} (nsec #{expected.nsec})"
actual_s = "#{Time.at(actual.sec) } (nsec #{actual.nsec})"
message = build_message(message, <<EOT, expected_s, actual_s)
<?> expected but was
<?>.
EOT
assert_block(message) do
expected.is_a?(Fluent::EventTime) && actual.is_a?(Fluent::EventTime) && expected.sec == actual.sec && expected.nsec == actual.nsec
end
end
def config_element(name = 'test', argument = '', params = {}, elements = [])
Fluent::Config::Element.new(name, argument, params, elements)
end
def event_time(str=nil, format: nil)
if str
if format
Fluent::EventTime.from_time(Time.strptime(str, format))
else
Fluent::EventTime.parse(str)
end
else
Fluent::EventTime.now
end
end
def event_time_without_nsec(str=nil, format: nil)
Fluent::EventTime.new(event_time(str, format: format))
end
def with_timezone(tz)
oldtz, ENV['TZ'] = ENV['TZ'], tz
yield
ensure
ENV['TZ'] = oldtz
end
def with_worker_config(root_dir: nil, workers: nil, worker_id: nil, &block)
if workers
if worker_id
if worker_id >= workers
raise "worker_id must be between 0 and (workers - 1)"
end
else
worker_id = 0
end
end
opts = {}
opts['root_dir'] = root_dir if root_dir
opts['workers'] = workers if workers
ENV['SERVERENGINE_WORKER_ID'] = worker_id.to_s
Fluent::SystemConfig.overwrite_system_config(opts, &block)
ensure
ENV.delete('SERVERENGINE_WORKER_ID')
end
def time2str(time, localtime: false, format: nil)
if format
if localtime
Time.at(time).strftime(format)
else
Time.at(time).utc.strftime(format)
end
else
if localtime
Time.at(time).iso8601
else
Time.at(time).utc.iso8601
end
end
end
def msgpack(type)
case type
when :factory
Fluent::MessagePackFactory.factory
when :packer
Fluent::MessagePackFactory.packer
when :unpacker
Fluent::MessagePackFactory.unpacker
else
raise ArgumentError, "unknown msgpack object type '#{type}'"
end
end
#
# Use this method with v0.12 compatibility layer.
#
# For v0.14 API, use `driver.logs` instead.
#
def capture_log(driver)
tmp = driver.instance.log.out
driver.instance.log.out = StringIO.new
yield
return driver.instance.log.out.string
ensure
driver.instance.log.out = tmp
end
def capture_stdout
out = StringIO.new
$stdout = out
yield
out.string.force_encoding('utf-8')
ensure
$stdout = STDOUT
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/base.rb | lib/fluent/test/base.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config'
require 'fluent/engine'
require 'fluent/system_config'
require 'fluent/test/log'
require 'serverengine'
module Fluent
module Test
class TestDriver
include ::Test::Unit::Assertions
def initialize(klass, &block)
if klass.is_a?(Class)
if block
# Create new class for test w/ overwritten methods
# klass.dup is worse because its ancestors does NOT include original class name
klass_name = klass.name
klass = Class.new(klass)
klass.define_singleton_method(:name) { klass_name }
klass.module_eval(&block)
end
@instance = klass.new
else
@instance = klass
end
@instance.router = Engine.root_agent.event_router
@instance.log = TestLogger.new
Engine.root_agent.instance_variable_set(:@log, @instance.log)
@config = Config.new
end
attr_reader :instance, :config
def configure(str, use_v1 = false)
if str.is_a?(Fluent::Config::Element)
@config = str
else
@config = Config.parse(str, "(test)", "(test_dir)", use_v1)
end
if label_name = @config['@label']
Engine.root_agent.add_label(label_name)
end
@instance.configure(@config)
self
end
# num_waits is for checking thread status. This will be removed after improved plugin API
def run(num_waits = 10, &block)
@instance.start
@instance.after_start
begin
# wait until thread starts
num_waits.times { sleep 0.05 }
return yield
ensure
@instance.shutdown
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/output_test.rb | lib/fluent/test/output_test.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/engine'
require 'fluent/event'
require 'fluent/test/input_test'
module Fluent
module Test
class TestOutputChain
def initialize
@called = 0
end
def next
@called += 1
end
attr_reader :called
end
class OutputTestDriver < InputTestDriver
def initialize(klass, tag='test', &block)
super(klass, &block)
@tag = tag
end
attr_accessor :tag
def emit(record, time=EventTime.now)
es = OneEventStream.new(time, record)
@instance.emit_events(@tag, es)
end
end
class BufferedOutputTestDriver < InputTestDriver
def initialize(klass, tag='test', &block)
super(klass, &block)
@entries = []
@expected_buffer = nil
@tag = tag
def @instance.buffer
@buffer
end
end
attr_accessor :tag
def emit(record, time=EventTime.now)
@entries << [time, record]
self
end
def expect_format(str)
(@expected_buffer ||= '') << str
end
def run(num_waits = 10)
result = nil
super(num_waits) {
yield if block_given?
es = ArrayEventStream.new(@entries)
buffer = @instance.format_stream(@tag, es)
if @expected_buffer
assert_equal(@expected_buffer, buffer)
end
chunk = if @instance.instance_eval{ @chunk_key_tag }
@instance.buffer.generate_chunk(@instance.metadata(@tag, nil, nil)).staged!
else
@instance.buffer.generate_chunk(@instance.metadata(nil, nil, nil)).staged!
end
chunk.concat(buffer, es.size)
begin
result = @instance.write(chunk)
ensure
chunk.purge
end
}
result
end
end
class TimeSlicedOutputTestDriver < InputTestDriver
def initialize(klass, tag='test', &block)
super(klass, &block)
@entries = []
@expected_buffer = nil
@tag = tag
end
attr_accessor :tag
def emit(record, time=EventTime.now)
@entries << [time, record]
self
end
def expect_format(str)
(@expected_buffer ||= '') << str
end
def run
result = []
super {
yield if block_given?
buffer = ''
lines = {}
# v0.12 TimeSlicedOutput doesn't call #format_stream
@entries.each do |time, record|
meta = @instance.metadata(@tag, time, record)
line = @instance.format(@tag, time, record)
buffer << line
lines[meta] ||= []
lines[meta] << line
end
if @expected_buffer
assert_equal(@expected_buffer, buffer)
end
lines.each_key do |meta|
chunk = @instance.buffer.generate_chunk(meta).staged!
chunk.append(lines[meta])
begin
result.push(@instance.write(chunk))
ensure
chunk.purge
end
end
}
result
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/parser_test.rb | lib/fluent/test/parser_test.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/parser'
require 'fluent/config'
module Fluent
module Test
class ParserTestDriver
def initialize(klass_or_str, format=nil, conf={}, &block)
if klass_or_str.is_a?(Class)
if block
# Create new class for test w/ overwritten methods
# klass.dup is worse because its ancestors does NOT include original class name
klass_name = klass_or_str.name
klass_or_str = Class.new(klass_or_str)
klass_or_str.define_singleton_method(:name) { klass_name }
klass_or_str.module_eval(&block)
end
case klass_or_str.instance_method(:initialize).arity
when 0
@instance = klass_or_str.new
when -2
# for RegexpParser
@instance = klass_or_str.new(format, conf)
end
elsif klass_or_str.is_a?(String)
@instance = Fluent::Plugin.new_parser(klass_or_str)
else
@instance = klass_or_str
end
@config = Config.new
end
attr_reader :instance, :config
def configure(conf)
case conf
when Fluent::Config::Element
@config = conf
when String
@config = Config.parse(conf, 'fluent.conf')
when Hash
@config = Config::Element.new('ROOT', '', conf, [])
else
raise "Unknown type... #{conf}"
end
@instance.configure(@config)
self
end
def parse(text, &block)
@instance.parse(text, &block)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/startup_shutdown.rb | lib/fluent/test/startup_shutdown.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'serverengine'
require 'fileutils'
module Fluent
module Test
module StartupShutdown
def startup
@server = ServerEngine::SocketManager::Server.open
ENV['SERVERENGINE_SOCKETMANAGER_PATH'] = @server.path.to_s
end
def shutdown
@server.close
end
def self.setup
@server = ServerEngine::SocketManager::Server.open
ENV['SERVERENGINE_SOCKETMANAGER_PATH'] = @server.path.to_s
end
def self.teardown
@server.close
# on Windows, the path is a TCP port number
FileUtils.rm_f @server.path unless Fluent.windows?
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/storage.rb | lib/fluent/test/driver/storage.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base_owned'
module Fluent
module Test
module Driver
class Storage < BaseOwned
def initialize(klass, **kwargs, &block)
super
@section_name = "storage"
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/test_event_router.rb | lib/fluent/test/driver/test_event_router.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/event'
module Fluent
module Test
module Driver
class TestEventRouter
def initialize(driver)
@driver = driver
end
def emit(tag, time, record)
@driver.emit_event_stream(tag, OneEventStream.new(time, record))
end
def emit_array(tag, array)
@driver.emit_event_stream(tag, ArrayEventStream.new(array))
end
def emit_stream(tag, es)
@driver.emit_event_stream(tag, es)
end
def emit_error_event(tag, time, record, error)
@driver.emit_error_event(tag, time, record, error)
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/base_owner.rb | lib/fluent/test/driver/base_owner.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base'
require 'fluent/test/driver/test_event_router'
module Fluent
module Test
module Driver
class BaseOwner < Base
def initialize(klass, opts: {}, &block)
super
if opts
@instance.system_config_override(opts)
end
@instance.log = TestLogger.new
@logs = @instance.log.out.logs
@event_streams = nil
@error_events = nil
end
def configure(conf, syntax: :v1)
if conf.is_a?(Fluent::Config::Element)
@config = conf
else
@config = Config.parse(conf, "(test)", "(test_dir)", syntax: syntax)
end
if @instance.respond_to?(:router=)
@event_streams = []
@error_events = []
driver = self
mojule = Module.new do
define_method(:event_emitter_router) do |label_name|
TestEventRouter.new(driver)
end
end
@instance.singleton_class.prepend mojule
end
@instance.configure(@config)
self
end
Emit = Struct.new(:tag, :es)
ErrorEvent = Struct.new(:tag, :time, :record, :error)
# via TestEventRouter
def emit_event_stream(tag, es)
@event_streams << Emit.new(tag, es)
end
def emit_error_event(tag, time, record, error)
@error_events << ErrorEvent.new(tag, time, record, error)
end
def events(tag: nil)
if block_given?
event_streams(tag: tag) do |t, es|
es.each do |time, record|
yield t, time, record
end
end
else
list = []
event_streams(tag: tag) do |t, es|
es.each do |time, record|
list << [t, time, record]
end
end
list
end
end
def event_streams(tag: nil)
return [] if @event_streams.nil?
selected = @event_streams.select{|e| tag.nil? ? true : e.tag == tag }
if block_given?
selected.each do |e|
yield e.tag, e.es
end
else
selected.map{|e| [e.tag, e.es] }
end
end
def emit_count
@event_streams.size
end
def record_count
@event_streams.reduce(0) {|a, e| a + e.es.size }
end
def error_events(tag: nil)
selected = @error_events.select{|e| tag.nil? ? true : e.tag == tag }
if block_given?
selected.each do |e|
yield e.tag, e.time, e.record, e.error
end
else
selected.map{|e| [e.tag, e.time, e.record, e.error] }
end
end
def run(expect_emits: nil, expect_records: nil, timeout: nil, start: true, shutdown: true, &block)
if expect_emits
@run_post_conditions << ->(){ emit_count >= expect_emits }
end
if expect_records
@run_post_conditions << ->(){ record_count >= expect_records }
end
super(timeout: timeout, start: start, shutdown: shutdown, &block)
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/filter.rb | lib/fluent/test/driver/filter.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base_owner'
require 'fluent/test/driver/event_feeder'
require 'fluent/plugin/filter'
module Fluent
module Test
module Driver
class Filter < BaseOwner
include EventFeeder
attr_reader :filtered
def initialize(klass, opts: {}, &block)
super
raise ArgumentError, "plugin is not an instance of Fluent::Plugin::Filter" unless @instance.is_a? Fluent::Plugin::Filter
@filtered = []
end
def filtered_records
@filtered.map {|_time, record| record }
end
def filtered_time
@filtered.map {|time, _record| time }
end
def instance_hook_after_started
super
filter_hook = ->(time, record) { @filtered << [time, record] }
m = Module.new do
define_method(:filter_stream) do |tag, es|
new_es = super(tag, es)
new_es.each do |time, record|
filter_hook.call(time, record)
end
new_es
end
end
@instance.singleton_class.prepend(m)
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/output.rb | lib/fluent/test/driver/output.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base_owner'
require 'fluent/test/driver/event_feeder'
require 'fluent/plugin/output'
require 'timeout'
module Fluent
module Test
module Driver
class Output < BaseOwner
include EventFeeder
def initialize(klass, opts: {}, &block)
super
raise ArgumentError, "plugin is not an instance of Fluent::Plugin::Output" unless @instance.is_a? Fluent::Plugin::Output
@flush_buffer_at_cleanup = nil
@wait_flush_completion = nil
@force_flush_retry = nil
@format_hook = nil
@format_results = []
end
def run(flush: true, wait_flush_completion: true, force_flush_retry: false, **kwargs, &block)
@flush_buffer_at_cleanup = flush
@wait_flush_completion = wait_flush_completion
@force_flush_retry = force_flush_retry
super(**kwargs, &block)
end
def run_actual(**kwargs, &block)
if @force_flush_retry
@instance.retry_for_error_chunk = true
end
val = super(**kwargs, &block)
if @flush_buffer_at_cleanup
self.flush
end
val
ensure
@instance.retry_for_error_chunk = false
end
def formatted
@format_results
end
def flush
@instance.force_flush
wait_flush_completion if @wait_flush_completion
end
def wait_flush_completion
buffer_queue = ->(){ @instance.buffer && @instance.buffer.queue.size > 0 }
dequeued_chunks = ->(){
@instance.dequeued_chunks_mutex &&
@instance.dequeued_chunks &&
@instance.dequeued_chunks_mutex.synchronize{ @instance.dequeued_chunks.size > 0 }
}
Timeout.timeout(10) do
while buffer_queue.call || dequeued_chunks.call
sleep 0.1
end
end
end
def instance_hook_after_started
super
# it's decided after #start whether output plugin instances use @custom_format or not.
if @instance.instance_eval{ @custom_format }
@format_hook = format_hook = ->(result){ @format_results << result }
m = Module.new do
define_method(:format) do |tag, time, record|
result = super(tag, time, record)
format_hook.call(result)
result
end
end
@instance.singleton_class.prepend m
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/parser.rb | lib/fluent/test/driver/parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base_owned'
module Fluent
module Test
module Driver
class Parser < BaseOwned
def initialize(klass, **kwargs, &block)
super
@section_name = "parse"
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/base.rb | lib/fluent/test/driver/base.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config'
require 'fluent/config/element'
require 'fluent/env'
require 'fluent/log'
require 'fluent/clock'
require 'serverengine/socket_manager'
require 'fileutils'
require 'timeout'
require 'logger'
module Fluent
module Test
module Driver
class TestTimedOut < RuntimeError; end
class Base
attr_reader :instance, :logs
DEFAULT_TIMEOUT = 300
def initialize(klass, opts: {}, &block)
if klass.is_a?(Class)
@instance = klass.new
if block
@instance.singleton_class.module_eval(&block)
@instance.send(:initialize)
end
else
@instance = klass
end
@instance.under_plugin_development = true
@socket_manager_server = nil
@logs = []
@run_post_conditions = []
@run_breaking_conditions = []
@broken = false
end
def configure(conf, syntax: :v1)
raise NotImplementedError
end
def end_if(&block)
raise ArgumentError, "block is not given" unless block_given?
@run_post_conditions << block
end
def break_if(&block)
raise ArgumentError, "block is not given" unless block_given?
@run_breaking_conditions << block
end
def broken?
@broken
end
def run(timeout: nil, start: true, shutdown: true, &block)
instance_start if start
timeout ||= DEFAULT_TIMEOUT
stop_at = Fluent::Clock.now + timeout
@run_breaking_conditions << ->(){ Fluent::Clock.now >= stop_at }
if !block_given? && @run_post_conditions.empty? && @run_breaking_conditions.empty?
raise ArgumentError, "no stop conditions nor block specified"
end
sleep_with_watching_threads = ->(){
if @instance.respond_to?(:_threads)
@instance._threads.values.each{|t| t.join(0) }
end
sleep 0.1
}
begin
retval = run_actual(timeout: timeout, &block)
sleep_with_watching_threads.call until stop?
retval
ensure
instance_shutdown if shutdown
end
end
def instance_start
if @instance.respond_to?(:server_wait_until_start)
if Fluent.windows?
@socket_manager_server = ServerEngine::SocketManager::Server.open
@socket_manager_path = @socket_manager_server.path
else
@socket_manager_path = ServerEngine::SocketManager::Server.generate_path
if @socket_manager_path.is_a?(String) && File.exist?(@socket_manager_path)
FileUtils.rm_f @socket_manager_path
end
@socket_manager_server = ServerEngine::SocketManager::Server.open(@socket_manager_path)
end
ENV['SERVERENGINE_SOCKETMANAGER_PATH'] = @socket_manager_path.to_s
end
unless @instance.started?
@instance.start
end
unless @instance.after_started?
@instance.after_start
end
if @instance.respond_to?(:thread_wait_until_start)
@instance.thread_wait_until_start
end
if @instance.respond_to?(:event_loop_wait_until_start)
@instance.event_loop_wait_until_start
end
instance_hook_after_started
end
def instance_hook_after_started
# insert hooks for tests available after instance.start
end
def instance_hook_before_stopped
# same with above
end
def instance_shutdown(log: Logger.new($stdout))
instance_hook_before_stopped
show_errors_if_exists = ->(label, block){
begin
block.call
rescue => e
log.error "unexpected error while #{label}, #{e.class}:#{e.message}"
e.backtrace.each do |bt|
log.error "\t#{bt}"
end
end
}
show_errors_if_exists.call(:stop, ->(){ @instance.stop unless @instance.stopped? })
show_errors_if_exists.call(:before_shutdown, ->(){ @instance.before_shutdown unless @instance.before_shutdown? })
show_errors_if_exists.call(:shutdown, ->(){ @instance.shutdown unless @instance.shutdown? })
show_errors_if_exists.call(:after_shutdown, ->(){ @instance.after_shutdown unless @instance.after_shutdown? })
if @instance.respond_to?(:server_wait_until_stop)
@instance.server_wait_until_stop
end
if @instance.respond_to?(:event_loop_wait_until_stop)
@instance.event_loop_wait_until_stop
end
show_errors_if_exists.call(:close, ->(){ @instance.close unless @instance.closed? })
if @instance.respond_to?(:thread_wait_until_stop)
@instance.thread_wait_until_stop
end
show_errors_if_exists.call(:terminate, ->(){ @instance.terminate unless @instance.terminated? })
if @socket_manager_server
@socket_manager_server.close
if @socket_manager_path.is_a?(String) && File.exist?(@socket_manager_path)
FileUtils.rm_f @socket_manager_path
end
end
end
def run_actual(timeout: DEFAULT_TIMEOUT)
if @instance.respond_to?(:_threads)
sleep 0.1 until @instance._threads.values.all?(&:alive?)
end
if @instance.respond_to?(:event_loop_running?)
sleep 0.1 until @instance.event_loop_running?
end
if @instance.respond_to?(:_child_process_processes)
sleep 0.1 until @instance._child_process_processes.values.all?{|pinfo| pinfo.alive }
end
return_value = nil
begin
Timeout.timeout(timeout * 2) do |sec|
return_value = yield if block_given?
end
rescue Timeout::Error
raise TestTimedOut, "Test case timed out with hard limit."
end
return_value
end
def stop?
# Should stop running if post conditions are not registered.
return true unless @run_post_conditions || @run_post_conditions.empty?
# Should stop running if all of the post conditions are true.
return true if @run_post_conditions.all? {|proc| proc.call }
# Should stop running if some of the breaking conditions is true.
# In this case, some post conditions may be not true.
if @run_breaking_conditions.any? {|proc| proc.call }
@broken = true
return true
end
false
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/input.rb | lib/fluent/test/driver/input.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base_owner'
require 'fluent/plugin/input'
module Fluent
module Test
module Driver
class Input < BaseOwner
def initialize(klass, opts: {}, &block)
super
raise ArgumentError, "plugin is not an instance of Fluent::Plugin::Input" unless @instance.is_a? Fluent::Plugin::Input
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/event_feeder.rb | lib/fluent/test/driver/event_feeder.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/event'
require 'fluent/time'
module Fluent
module Test
module Driver
module EventFeeder
def initialize(klass, opts: {}, &block)
super
@default_tag = nil
@feed_method = nil
end
def run(default_tag: nil, **kwargs, &block)
@feed_method = if @instance.respond_to?(:filter_stream)
:filter_stream
else
:emit_events
end
if default_tag
@default_tag = default_tag
end
super(**kwargs, &block)
end
def feed_to_plugin(tag, es)
@instance.__send__(@feed_method, tag, es)
end
# d.run do
# d.feed('tag', time, {record})
# d.feed('tag', [ [time, {record}], [time, {record}], ... ])
# d.feed('tag', es)
# end
# d.run(default_tag: 'tag') do
# d.feed({record})
# d.feed(time, {record})
# d.feed([ [time, {record}], [time, {record}], ... ])
# d.feed(es)
# end
def feed(*args)
case args.size
when 1
raise ArgumentError, "tag not specified without default_tag" unless @default_tag
case args.first
when Fluent::EventStream
feed_to_plugin(@default_tag, args.first)
when Array
feed_to_plugin(@default_tag, ArrayEventStream.new(args.first))
when Hash
record = args.first
time = Fluent::EventTime.now
feed_to_plugin(@default_tag, OneEventStream.new(time, record))
else
raise ArgumentError, "unexpected events object (neither event(Hash), EventStream nor Array): #{args.first.class}"
end
when 2
if args[0].is_a?(String) && (args[1].is_a?(Array) || args[1].is_a?(Fluent::EventStream))
tag, es = args
es = ArrayEventStream.new(es) if es.is_a?(Array)
feed_to_plugin(tag, es)
elsif @default_tag && (args[0].is_a?(Fluent::EventTime) || args[0].is_a?(Integer)) && args[1].is_a?(Hash)
time, record = args
feed_to_plugin(@default_tag, OneEventStream.new(time, record))
else
raise ArgumentError, "unexpected values of argument: #{args[0].class}, #{args[1].class}"
end
when 3
tag, time, record = args
if tag.is_a?(String) && (time.is_a?(Fluent::EventTime) || time.is_a?(Integer)) && record.is_a?(Hash)
feed_to_plugin(tag, OneEventStream.new(time, record))
else
raise ArgumentError, "unexpected values of argument: #{tag.class}, #{time.class}, #{record.class}"
end
else
raise ArgumentError, "unexpected number of arguments: #{args}"
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/multi_output.rb | lib/fluent/test/driver/multi_output.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base_owner'
require 'fluent/test/driver/event_feeder'
require 'fluent/plugin/multi_output'
module Fluent
module Test
module Driver
class MultiOutput < BaseOwner
include EventFeeder
def initialize(klass, opts: {}, &block)
super
raise ArgumentError, "plugin is not an instance of Fluent::Plugin::MultiOutput" unless @instance.is_a? Fluent::Plugin::MultiOutput
@flush_buffer_at_cleanup = nil
end
def run(flush: true, **kwargs, &block)
@flush_buffer_at_cleanup = flush
super(**kwargs, &block)
end
def run_actual(**kwargs, &block)
val = super(**kwargs, &block)
if @flush_buffer_at_cleanup
@instance.outputs.each{|o| o.force_flush }
end
val
end
def flush
@instance.outputs.each{|o| o.force_flush }
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/formatter.rb | lib/fluent/test/driver/formatter.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base_owned'
module Fluent
module Test
module Driver
class Formatter < BaseOwned
def initialize(klass, **kwargs, &block)
super
@section_name = "format"
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/test/driver/base_owned.rb | lib/fluent/test/driver/base_owned.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/test/driver/base'
require 'fluent/plugin/base'
require 'fluent/plugin_id'
require 'fluent/log'
require 'fluent/plugin_helper'
module Fluent
module Test
module Driver
class OwnerDummy < Fluent::Plugin::Base
include PluginId
include PluginLoggerMixin
include PluginHelper::Mixin
end
class BaseOwned < Base
attr_accessor :section_name
def initialize(klass, opts: {}, &block)
super
owner = OwnerDummy.new
if opts
owner.system_config_override(opts)
end
owner.log = TestLogger.new
if @instance.respond_to?(:owner=)
@instance.owner = owner
if opts
@instance.system_config_override(opts)
end
end
@logs = owner.log.out.logs
@section_name = ''
end
def configure(conf)
if conf.is_a?(Fluent::Config::Element)
@config = conf
elsif conf.is_a?(Hash)
@config = Fluent::Config::Element.new(@section_name, "", Hash[conf.map{|k,v| [k.to_s, v]}], [])
else
@config = Fluent::Config.parse(conf, @section_name, "", syntax: :v1)
end
@instance.configure(@config)
self
end
# this is special method for v0 and should be deleted
def configure_v0(conf)
if conf.is_a?(Fluent::Config::Element)
@config = conf
elsif conf.is_a?(Hash)
@config = Fluent::Config::Element.new(@section_name, "", Hash[conf.map{|k,v| [k.to_s, v]}], [])
else
@config = Fluent::Config.parse(conf, @section_name, "", syntax: :v0)
end
@instance.configure(@config)
self
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/counter/base_socket.rb | lib/fluent/counter/base_socket.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'cool.io'
require 'fluent/msgpack_factory'
module Fluent
module Counter
class BaseSocket < Coolio::TCPSocket
def packed_write(data)
write pack(data)
end
def on_read(data)
Fluent::MessagePackFactory.msgpack_unpacker.feed_each(data) do |d|
on_message d
end
end
def on_message(data)
raise NotImplementedError
end
private
def pack(data)
Fluent::MessagePackFactory.msgpack_packer.pack(data)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/counter/store.rb | lib/fluent/counter/store.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config'
require 'fluent/counter/error'
require 'fluent/plugin/storage_local'
require 'fluent/time'
module Fluent
module Counter
class Store
def self.gen_key(scope, key)
"#{scope}\t#{key}"
end
def initialize(opt = {})
@log = opt[:log] || $log
# Notice: This storage is not be implemented auto save.
@storage = Plugin.new_storage('local', parent: DummyParent.new(@log))
conf = if opt[:path]
{'persistent' => true, 'path' => opt[:path] }
else
{'persistent' => false }
end
@storage.configure(Fluent::Config::Element.new('storage', {}, conf, []))
end
# This class behaves as a configurable plugin for using in storage (OwnedByMixin).
class DummyParent
include Configurable
attr_reader :log
def initialize(log)
@log = log
end
def plugin_id
'dummy_parent_store'
end
def plugin_id_configured?
false
end
# storage_local calls PluginId#plugin_root_dir
def plugin_root_dir
nil
end
end
def start
@storage.load
end
def stop
@storage.save
end
def init(key, data, ignore: false)
ret = if v = get(key)
raise InvalidParams.new("#{key} already exists in counter") unless ignore
v
else
@storage.put(key, build_value(data))
end
build_response(ret)
end
def get(key, raise_error: false, raw: false)
ret = if raise_error
@storage.get(key) or raise UnknownKey.new("`#{key}` doesn't exist in counter")
else
@storage.get(key)
end
if raw
ret
else
ret && build_response(ret)
end
end
def key?(key)
!!@storage.get(key)
end
def delete(key)
ret = @storage.delete(key) or raise UnknownKey.new("`#{key}` doesn't exist in counter")
build_response(ret)
end
def inc(key, data, force: false)
value = data.delete('value')
init(key, data) if !key?(key) && force
v = get(key, raise_error: true, raw: true)
valid_type!(v, value)
v['total'] += value
v['current'] += value
t = EventTime.now
v['last_modified_at'] = [t.sec, t.nsec]
@storage.put(key, v)
build_response(v)
end
def reset(key)
v = get(key, raise_error: true, raw: true)
success = false
old_data = v.dup
now = EventTime.now
last_reset_at = EventTime.new(*v['last_reset_at'])
# Does it need reset?
if (last_reset_at + v['reset_interval']) <= now
success = true
v['current'] = initial_value(v['type'])
t = [now.sec, now.nsec]
v['last_reset_at'] = t
v['last_modified_at'] = t
@storage.put(key, v)
end
{
'elapsed_time' => now - last_reset_at,
'success' => success,
'counter_data' => build_response(old_data)
}
end
private
def build_response(d)
{
'name' => d['name'],
'total' => d['total'],
'current' => d['current'],
'type' => d['type'],
'reset_interval' => d['reset_interval'],
'last_reset_at' => EventTime.new(*d['last_reset_at']),
}
end
# value is Hash. value requires these fields.
# :name, :total, :current, :type, :reset_interval, :last_reset_at, :last_modified_at
def build_value(data)
type = data['type'] || 'numeric'
now = EventTime.now
t = [now.sec, now.nsec]
v = initial_value(type)
data.merge(
'type' => type,
'last_reset_at' => t,
'last_modified_at' => t,
'current' => v,
'total' => v,
)
end
def initial_value(type)
case type
when 'numeric', 'integer' then 0
when 'float' then 0.0
else raise InvalidParams.new('`type` should be integer, float, or numeric')
end
end
def valid_type!(v, value)
type = v['type']
return unless (type != 'numeric') && (type_str(value) != type)
raise InvalidParams.new("`type` is #{type}. You should pass #{type} value as a `value`")
end
def type_str(v)
case v
when Integer
'integer'
when Float
'float'
when Numeric
'numeric'
else
raise InvalidParams.new("`type` should be integer, float, or numeric")
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/counter/mutex_hash.rb | lib/fluent/counter/mutex_hash.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'timeout'
module Fluent
module Counter
class MutexHash
def initialize(data_store)
@mutex = Mutex.new
@data_store = data_store
@mutex_hash = {}
@thread = nil
@cleanup_thread = CleanupThread.new(@data_store, @mutex_hash, @mutex)
end
def start
@data_store.start
@cleanup_thread.start
end
def stop
@data_store.stop
@cleanup_thread.stop
end
def synchronize(*keys)
return if keys.empty?
locks = {}
loop do
@mutex.synchronize do
keys.each do |key|
mutex = @mutex_hash[key]
unless mutex
v = Mutex.new
@mutex_hash[key] = v
mutex = v
end
if mutex.try_lock
locks[key] = mutex
else
locks.each_value(&:unlock)
locks = {} # flush locked keys
break
end
end
end
next if locks.empty? # failed to lock all keys
locks.each do |(k, v)|
yield @data_store, k
v.unlock
end
break
end
end
def synchronize_keys(*keys)
return if keys.empty?
keys = keys.dup
while key = keys.shift
@mutex.lock
mutex = @mutex_hash[key]
unless mutex
v = Mutex.new
@mutex_hash[key] = v
mutex = v
end
if mutex.try_lock
@mutex.unlock
yield @data_store, key
mutex.unlock
else
# release global lock
@mutex.unlock
keys.push(key) # failed lock, retry this key
end
end
end
end
class CleanupThread
CLEANUP_INTERVAL = 60 * 15 # 15 min
def initialize(store, mutex_hash, mutex)
@store = store
@mutex_hash = mutex_hash
@mutex = mutex
@thread = nil
@running = false
end
def start
@running = true
@thread = Thread.new do
while @running
sleep CLEANUP_INTERVAL
run_once
end
end
end
def stop
return unless @running
@running = false
begin
# Avoid waiting CLEANUP_INTERVAL
Timeout.timeout(1) do
@thread.join
end
rescue Timeout::Error
@thread.kill
end
end
private
def run_once
@mutex.synchronize do
last_cleanup_at = (Time.now - CLEANUP_INTERVAL).to_i
@mutex_hash.each do |(key, mutex)|
v = @store.get(key, raw: true)
next unless v
next if last_cleanup_at < v['last_modified_at'][0] # v['last_modified_at'] = [sec, nsec]
next unless mutex.try_lock
@mutex_hash[key] = nil
mutex.unlock
# Check that a waiting thread is in a lock queue.
# Can't get a lock here means this key is used in other places.
# So restore a mutex value to a corresponding key.
if mutex.try_lock
@mutex_hash.delete(key)
mutex.unlock
else
@mutex_hash[key] = mutex
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/counter/validator.rb | lib/fluent/counter/validator.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/counter/error'
module Fluent
module Counter
class Validator
VALID_NAME = /\A[a-z][a-zA-Z0-9\-_]*\Z/
VALID_SCOPE_NAME = /\A[a-z][\ta-zA-Z0-9\-_]*\Z/
VALID_METHODS = %w(establish init delete inc get reset)
def self.request(data)
errors = []
raise "Received data is not Hash: #{data}" unless data.is_a?(Hash)
unless data['id']
errors << Fluent::Counter::InvalidRequest.new('Request should include `id`')
end
if !data['method']
errors << Fluent::Counter::InvalidRequest.new('Request should include `method`')
elsif !(VALID_NAME =~ data['method'])
errors << Fluent::Counter::InvalidRequest.new('`method` is the invalid format')
elsif !VALID_METHODS.include?(data['method'])
errors << Fluent::Counter::MethodNotFound.new("Unknown method name passed: #{data['method']}")
end
errors.map(&:to_hash)
end
def initialize(*types)
@types = types.map(&:to_s)
@empty = @types.delete('empty')
end
def call(data)
success = []
errors = []
if @empty && data.empty?
errors << Fluent::Counter::InvalidParams.new('One or more `params` are required')
else
data.each do |d|
begin
@types.each { |type| dispatch(type, d) }
success << d
rescue => e
errors << e
end
end
end
[success, errors]
end
private
def dispatch(type, data)
send("validate_#{type}!", data)
rescue NoMethodError => e
raise Fluent::Counter::InternalServerError.new(e)
end
end
class ArrayValidator < Validator
def validate_key!(name)
unless name.is_a?(String)
raise Fluent::Counter::InvalidParams.new('The type of `key` should be String')
end
unless VALID_NAME.match?(name)
raise Fluent::Counter::InvalidParams.new('`key` is the invalid format')
end
end
def validate_scope!(name)
unless name.is_a?(String)
raise Fluent::Counter::InvalidParams.new('The type of `scope` should be String')
end
unless VALID_SCOPE_NAME.match?(name)
raise Fluent::Counter::InvalidParams.new('`scope` is the invalid format')
end
end
end
class HashValidator < Validator
def validate_name!(hash)
name = hash['name']
unless name
raise Fluent::Counter::InvalidParams.new('`name` is required')
end
unless name.is_a?(String)
raise Fluent::Counter::InvalidParams.new('The type of `name` should be String')
end
unless VALID_NAME.match?(name)
raise Fluent::Counter::InvalidParams.new("`name` is the invalid format")
end
end
def validate_value!(hash)
value = hash['value']
unless value
raise Fluent::Counter::InvalidParams.new('`value` is required')
end
unless value.is_a?(Numeric)
raise Fluent::Counter::InvalidParams.new("The type of `value` type should be Numeric")
end
end
def validate_reset_interval!(hash)
interval = hash['reset_interval']
unless interval
raise Fluent::Counter::InvalidParams.new('`reset_interval` is required')
end
unless interval.is_a?(Numeric)
raise Fluent::Counter::InvalidParams.new('The type of `reset_interval` should be Numeric')
end
if interval < 0
raise Fluent::Counter::InvalidParams.new('`reset_interval` should be a positive number')
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/counter/client.rb | lib/fluent/counter/client.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'cool.io'
require 'fluent/counter/base_socket'
require 'fluent/counter/error'
require 'timeout'
module Fluent
module Counter
class Client
DEFAULT_PORT = 24321
DEFAULT_ADDR = '127.0.0.1'
DEFAULT_TIMEOUT = 5
ID_LIMIT_COUNT = 1 << 31
def initialize(loop = nil, opt = {})
@loop = loop || Coolio::Loop.new
@port = opt[:port] || DEFAULT_PORT
@host = opt[:host] || DEFAULT_ADDR
@log = opt[:log] || $log
@timeout = opt[:timeout] || DEFAULT_TIMEOUT
@conn = Connection.connect(@host, @port, method(:on_message))
@responses = {}
@id = 0
@id_mutex = Mutex.new
@loop_mutex = Mutex.new
end
def start
@loop.attach(@conn)
@log.debug("starting counter client: #{@host}:#{@port}")
self
rescue => e
if @log
@log.error e
else
STDERR.puts e
end
end
def stop
@conn.close
@log.debug("calling stop in counter client: #{@host}:#{@port}")
end
def establish(scope)
scope = Timeout.timeout(@timeout) {
response = send_request('establish', nil, [scope])
Fluent::Counter.raise_error(response.errors.first) if response.errors?
data = response.data
data.first
}
@scope = scope
rescue Timeout::Error
raise "Can't establish the connection to counter server due to timeout"
end
# === Example
# `init` receives various arguments.
#
# 1. init(name: 'name')
# 2. init({ name: 'name',reset_interval: 20 }, options: {})
# 3. init([{ name: 'name1',reset_interval: 20 }, { name: 'name2',reset_interval: 20 }])
# 4. init([{ name: 'name1',reset_interval: 20 }, { name: 'name2',reset_interval: 20 }], options: {})
# 5. init([{ name: 'name1',reset_interval: 20 }, { name: 'name2',reset_interval: 20 }]) { |res| ... }
def init(params, options: {})
exist_scope!
params = [params] unless params.is_a?(Array)
res = send_request('init', @scope, params, options)
# if `async` is false or missing, block at this method and return a Future::Result object.
if block_given?
Thread.start do
yield res.get
end
else
res
end
end
def delete(*params, options: {})
exist_scope!
res = send_request('delete', @scope, params, options)
if block_given?
Thread.start do
yield res.get
end
else
res
end
end
# === Example
# `inc` receives various arguments.
#
# 1. inc(name: 'name')
# 2. inc({ name: 'name',value: 20 }, options: {})
# 3. inc([{ name: 'name1',value: 20 }, { name: 'name2',value: 20 }])
# 4. inc([{ name: 'name1',value: 20 }, { name: 'name2',value: 20 }], options: {})
def inc(params, options: {})
exist_scope!
params = [params] unless params.is_a?(Array)
res = send_request('inc', @scope, params, options)
if block_given?
Thread.start do
yield res.get
end
else
res
end
end
def get(*params, options: {})
exist_scope!
res = send_request('get', @scope, params, options)
if block_given?
Thread.start do
yield res.get
end
else
res
end
end
def reset(*params, options: {})
exist_scope!
res = send_request('reset', @scope, params, options)
if block_given?
Thread.start do
yield res.get
end
else
res
end
end
private
def exist_scope!
raise 'Call `establish` method to get a `scope` before calling this method' unless @scope
end
def on_message(data)
if response = @responses.delete(data['id'])
response.set(data)
else
@log.warn("Receiving missing id data: #{data}")
end
end
def send_request(method, scope, params, opt = {})
id = generate_id
res = Future.new(@loop, @loop_mutex)
@responses[id] = res # set a response value to this future object at `on_message`
request = build_request(method, id, scope, params, opt)
@log.debug(request)
@conn.send_data request
res
end
def build_request(method, id, scope = nil, params = nil, options = nil)
r = { id: id, method: method }
r[:scope] = scope if scope
r[:params] = params if params
r[:options] = options if options
r
end
def generate_id
id = 0
@id_mutex.synchronize do
id = @id
@id += 1
@id = 0 if ID_LIMIT_COUNT < @id
end
id
end
end
class Connection < Fluent::Counter::BaseSocket
def initialize(io, on_message)
super(io)
@connection = false
@buffer = ''
@on_message = on_message
end
def send_data(data)
if @connection
packed_write data
else
@buffer += pack(data)
end
end
def on_connect
@connection = true
write @buffer
@buffer = ''
end
def on_close
@connection = false
end
def on_message(data)
@on_message.call(data)
end
end
class Future
class Result
attr_reader :data, :errors
def initialize(result)
@errors = result['errors']
@data = result['data']
end
def success?
@errors.nil? || @errors.empty?
end
def error?
!success?
end
end
def initialize(loop, mutex)
@set = false
@result = nil
@mutex = mutex
@loop = loop
end
def set(v)
@result = Result.new(v)
@set = true
end
def errors
get.errors
end
def errors?
es = errors
es && !es.empty?
end
def data
get.data
end
def get
# Block until `set` method is called and @result is set
join if @result.nil?
@result
end
def wait
res = get
if res.error?
Fluent::Counter.raise_error(res.errors.first)
end
res
end
private
def join
until @set
@mutex.synchronize do
@loop.run_once(0.0001) # return a lock as soon as possible
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/counter/server.rb | lib/fluent/counter/server.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'cool.io'
require 'fluent/counter/base_socket'
require 'fluent/counter/validator'
require 'fluent/counter/store'
require 'fluent/counter/mutex_hash'
module Fluent
module Counter
class Server
DEFAULT_ADDR = '127.0.0.1'
DEFAULT_PORT = 24321
def initialize(name, opt = {})
raise 'Counter server name is invalid' unless Validator::VALID_NAME.match?(name)
@name = name
@opt = opt
@addr = @opt[:addr] || DEFAULT_ADDR
@port = @opt[:port] || DEFAULT_PORT
@loop = @opt[:loop] || Coolio::Loop.new
@log = @opt[:log] || $log
@store = Fluent::Counter::Store.new(opt)
@mutex_hash = MutexHash.new(@store)
@server = Coolio::TCPServer.new(@addr, @port, Handler, method(:on_message))
@thread = nil
@running = false
end
def start
@server.attach(@loop)
@thread = Thread.new do
@running = true
@loop.run(0.5)
@running = false
end
@log.debug("starting counter server #{@addr}:#{@port}")
@mutex_hash.start
self
end
def stop
# This `sleep` for a test to wait for a `@loop` to begin to run
sleep 0.1
@server.close
@loop.stop if @running
@mutex_hash.stop
@thread.join if @thread
@log.debug("calling stop in counter server #{@addr}:#{@port}")
end
def on_message(data)
errors = Validator.request(data)
unless errors.empty?
return { 'id' => data['id'], 'data' => [], 'errors' => errors }
end
result = safe_run do
send(data['method'], data['params'], data['scope'], data['options'])
end
result.merge('id' => data['id'])
rescue => e
@log.error e.to_s
end
private
def establish(params, _scope, _options)
validator = Fluent::Counter::ArrayValidator.new(:empty, :scope)
valid_params, errors = validator.call(params)
res = Response.new(errors)
if scope = valid_params.first
new_scope = "#{@name}\t#{scope}"
res.push_data new_scope
@log.debug("Establish new key: #{new_scope}")
end
res.to_hash
end
def init(params, scope, options)
validator = Fluent::Counter::HashValidator.new(:empty, :name, :reset_interval)
valid_params, errors = validator.call(params)
res = Response.new(errors)
key_hash = valid_params.reduce({}) do |acc, vp|
acc.merge(Store.gen_key(scope, vp['name']) => vp)
end
do_init = lambda do |store, key|
begin
param = key_hash[key]
v = store.init(key, param, ignore: options['ignore'])
@log.debug("Create new key: #{param['name']}")
res.push_data v
rescue => e
res.push_error e
end
end
if options['random']
@mutex_hash.synchronize_keys(*(key_hash.keys), &do_init)
else
@mutex_hash.synchronize(*(key_hash.keys), &do_init)
end
res.to_hash
end
def delete(params, scope, options)
validator = Fluent::Counter::ArrayValidator.new(:empty, :key)
valid_params, errors = validator.call(params)
res = Response.new(errors)
keys = valid_params.map { |vp| Store.gen_key(scope, vp) }
do_delete = lambda do |store, key|
begin
v = store.delete(key)
@log.debug("delete a key: #{key}")
res.push_data v
rescue => e
res.push_error e
end
end
if options['random']
@mutex_hash.synchronize_keys(*keys, &do_delete)
else
@mutex_hash.synchronize(*keys, &do_delete)
end
res.to_hash
end
def inc(params, scope, options)
validate_param = [:empty, :name, :value]
validate_param << :reset_interval if options['force']
validator = Fluent::Counter::HashValidator.new(*validate_param)
valid_params, errors = validator.call(params)
res = Response.new(errors)
key_hash = valid_params.reduce({}) do |acc, vp|
acc.merge(Store.gen_key(scope, vp['name']) => vp)
end
do_inc = lambda do |store, key|
begin
param = key_hash[key]
v = store.inc(key, param, force: options['force'])
@log.debug("Increment #{key} by #{param['value']}")
res.push_data v
rescue => e
res.push_error e
end
end
if options['random']
@mutex_hash.synchronize_keys(*(key_hash.keys), &do_inc)
else
@mutex_hash.synchronize(*(key_hash.keys), &do_inc)
end
res.to_hash
end
def reset(params, scope, options)
validator = Fluent::Counter::ArrayValidator.new(:empty, :key)
valid_params, errors = validator.call(params)
res = Response.new(errors)
keys = valid_params.map { |vp| Store.gen_key(scope, vp) }
do_reset = lambda do |store, key|
begin
v = store.reset(key)
@log.debug("Reset #{key}'s' counter value")
res.push_data v
rescue => e
res.push_error e
end
end
if options['random']
@mutex_hash.synchronize_keys(*keys, &do_reset)
else
@mutex_hash.synchronize(*keys, &do_reset)
end
res.to_hash
end
def get(params, scope, _options)
validator = Fluent::Counter::ArrayValidator.new(:empty, :key)
valid_params, errors = validator.call(params)
res = Response.new(errors)
keys = valid_params.map { |vp| Store.gen_key(scope, vp) }
keys.each do |key|
begin
v = @store.get(key, raise_error: true)
@log.debug("Get counter value: #{key}")
res.push_data v
rescue => e
res.push_error e
end
end
res.to_hash
end
def safe_run
yield
rescue => e
{
'errors' => [InternalServerError.new(e).to_hash],
'data' => []
}
end
class Response
def initialize(errors = [], data = [])
@errors = errors
@data = data
end
def push_error(error)
@errors << error
end
def push_data(data)
@data << data
end
def to_hash
if @errors.empty?
{ 'data' => @data }
else
errors = @errors.map do |e|
error = e.respond_to?(:to_hash) ? e : InternalServerError.new(e.to_s)
error.to_hash
end
{ 'data' => @data, 'errors' => errors }
end
end
end
end
class Handler < Fluent::Counter::BaseSocket
def initialize(io, on_message)
super(io)
@on_message = on_message
end
def on_message(data)
res = @on_message.call(data)
packed_write res if res
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/counter/error.rb | lib/fluent/counter/error.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
module Counter
class BaseError < StandardError
def to_hash
{ 'code' => code, 'message' => message }
end
def code
raise NotImplementedError
end
end
class InvalidParams < BaseError
def code
'invalid_params'
end
end
class UnknownKey < BaseError
def code
'unknown_key'
end
end
class ParseError < BaseError
def code
'parse_error'
end
end
class InvalidRequest < BaseError
def code
'invalid_request'
end
end
class MethodNotFound < BaseError
def code
'method_not_found'
end
end
class InternalServerError < BaseError
def code
'internal_server_error'
end
end
def raise_error(response)
msg = response['message']
case response['code']
when 'invalid_params'
raise InvalidParams.new(msg)
when 'unknown_key'
raise UnknownKey.new(msg)
when 'parse_error'
raise ParseError.new(msg)
when 'invalid_request'
raise InvalidRequest.new(msg)
when 'method_not_found'
raise MethodNotFound.new(msg)
when 'internal_server_error'
raise InternalServerError.new(msg)
else
raise "Unknown code: #{response['code']}"
end
end
module_function :raise_error
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/configure_proxy.rb | lib/fluent/config/configure_proxy.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
module Config
class ConfigureProxy
attr_accessor :name, :final, :param_name, :init, :required, :multi, :alias, :configured_in_section
attr_accessor :argument, :params, :defaults, :descriptions, :sections
# config_param :desc, :string, default: '....'
# config_set_default :buffer_type, :memory
#
# config_section :default, required: true, multi: false do
# config_argument :arg, :string
# config_param :required, :bool, default: false
# config_param :name, :string
# config_param :power, :integer
# end
#
# config_section :child, param_name: 'children', required: false, multi: true, alias: 'node' do
# config_param :name, :string
# config_param :power, :integer, default: nil
# config_section :item do
# config_param :name
# end
# end
def initialize(name, root: false, param_name: nil, final: nil, init: nil, required: nil, multi: nil, alias: nil, type_lookup:)
@name = name.to_sym
@final = final
# For ConfigureProxy of root section, "@name" should be a class name of plugins.
# Otherwise (like subsections), "@name" should be a name of section, like "buffer", "store".
# For subsections, name will be used as parameter names (unless param_name exists), so overriding proxy's name
# should override "@name".
@root_section = root
@param_name = param_name&.to_sym
@init = init
@required = required
@multi = multi
@alias = binding.local_variable_get(:alias)
@type_lookup = type_lookup
raise "init and required are exclusive" if @init && @required
# specify section name for viewpoint of owner(parent) plugin
# for buffer plugins: all params are in <buffer> section of owner
# others: <storage>, <format> (formatter/parser), ...
@configured_in_section = nil
@argument = nil # nil: ignore argument
@params = {}
@defaults = {}
@descriptions = {}
@sections = {}
@current_description = nil
end
def variable_name
@param_name || @name
end
def root?
@root_section
end
def init?
@init.nil? ? false : @init
end
def required?
@required.nil? ? false : @required
end
def multi?
@multi.nil? ? true : @multi
end
def final?
!!@final
end
def merge(other) # self is base class, other is subclass
return merge_for_finalized(other) if self.final?
[:param_name, :required, :multi, :alias, :configured_in_section].each do |prohibited_name|
if overwrite?(other, prohibited_name)
raise ConfigError, "BUG: subclass cannot overwrite base class's config_section: #{prohibited_name}"
end
end
options = {}
# param_name affects instance variable name, which is just "internal" of each plugins.
# so it must not be changed. base class's name (or param_name) is always used.
options[:param_name] = @param_name
# subclass cannot overwrite base class's definition
options[:init] = @init.nil? ? other.init : self.init
options[:required] = @required.nil? ? other.required : self.required
options[:multi] = @multi.nil? ? other.multi : self.multi
options[:alias] = @alias.nil? ? other.alias : self.alias
options[:final] = @final || other.final
options[:type_lookup] = @type_lookup
merged = if self.root?
options[:root] = true
self.class.new(other.name, **options)
else
self.class.new(@name, **options)
end
# configured_in MUST be kept
merged.configured_in_section = self.configured_in_section || other.configured_in_section
merged.argument = other.argument || self.argument
merged.params = self.params.merge(other.params)
merged.defaults = self.defaults.merge(other.defaults)
merged.sections = {}
(self.sections.keys + other.sections.keys).uniq.each do |section_key|
self_section = self.sections[section_key]
other_section = other.sections[section_key]
merged_section = if self_section && other_section
self_section.merge(other_section)
elsif self_section || other_section
self_section || other_section
else
raise "BUG: both of self and other section are nil"
end
merged.sections[section_key] = merged_section
end
merged
end
def merge_for_finalized(other)
# list what subclass can do for finalized section
# * append params/defaults/sections which are missing in superclass
# * change default values of superclass
# * overwrite init to make it enable to instantiate section objects with added default values
if other.final == false && overwrite?(other, :final)
raise ConfigError, "BUG: subclass cannot overwrite finalized base class's config_section"
end
[:param_name, :required, :multi, :alias, :configured_in_section].each do |prohibited_name|
if overwrite?(other, prohibited_name)
raise ConfigError, "BUG: subclass cannot overwrite base class's config_section: #{prohibited_name}"
end
end
options = {}
options[:param_name] = @param_name
options[:init] = @init || other.init
options[:required] = @required.nil? ? other.required : self.required
options[:multi] = @multi.nil? ? other.multi : self.multi
options[:alias] = @alias.nil? ? other.alias : self.alias
options[:final] = true
options[:type_lookup] = @type_lookup
merged = if self.root?
options[:root] = true
self.class.new(other.name, **options)
else
self.class.new(@name, **options)
end
merged.configured_in_section = self.configured_in_section || other.configured_in_section
merged.argument = self.argument || other.argument
merged.params = other.params.merge(self.params)
merged.defaults = self.defaults.merge(other.defaults)
merged.sections = {}
(self.sections.keys + other.sections.keys).uniq.each do |section_key|
self_section = self.sections[section_key]
other_section = other.sections[section_key]
merged_section = if self_section && other_section
other_section.merge(self_section)
elsif self_section || other_section
self_section || other_section
else
raise "BUG: both of self and other section are nil"
end
merged.sections[section_key] = merged_section
end
merged
end
def overwrite_defaults(other) # other is owner plugin's corresponding proxy
self.defaults = self.defaults.merge(other.defaults)
self.sections.each_key do |section_key|
if other.sections.has_key?(section_key)
self.sections[section_key].overwrite_defaults(other.sections[section_key])
end
end
end
def option_value_type!(name, opts, key, klass=nil, type: nil)
if opts.has_key?(key)
if klass && !opts[key].is_a?(klass)
raise ArgumentError, "#{name}: #{key} must be a #{klass}, but #{opts[key].class}"
end
case type
when :boolean
unless opts[key].is_a?(TrueClass) || opts[key].is_a?(FalseClass)
raise ArgumentError, "#{name}: #{key} must be true or false, but #{opts[key].class}"
end
when nil
# ignore
else
raise "unknown type: #{type} for option #{key}"
end
end
end
def config_parameter_option_validate!(name, type, **kwargs, &block)
if type.nil? && !block
type = :string
end
kwargs.each_key do |key|
case key
when :default, :alias, :secret, :skip_accessor, :deprecated, :obsoleted, :desc
# valid for all types
when :list
raise ArgumentError, ":list is valid only for :enum type, but #{type}: #{name}" if type != :enum
when :value_type
raise ArgumentError, ":value_type is valid only for :hash and :array, but #{type}: #{name}" if type != :hash && type != :array
when :symbolize_keys
raise ArgumentError, ":symbolize_keys is valid only for :hash, but #{type}: #{name}" if type != :hash
else
raise ArgumentError, "unknown option '#{key}' for configuration parameter: #{name}"
end
end
end
def parameter_configuration(name, type = nil, **kwargs, &block)
config_parameter_option_validate!(name, type, **kwargs, &block)
name = name.to_sym
if block && type
raise ArgumentError, "#{name}: both of block and type cannot be specified"
elsif !block && !type
type = :string
end
opts = {}
opts[:type] = type
opts.merge!(kwargs)
begin
block ||= @type_lookup.call(type)
rescue ConfigError
# override error message
raise ArgumentError, "#{name}: unknown config_argument type `#{type}'"
end
# options for config_param
option_value_type!(name, opts, :desc, String)
option_value_type!(name, opts, :alias, Symbol)
option_value_type!(name, opts, :secret, type: :boolean)
option_value_type!(name, opts, :deprecated, String)
option_value_type!(name, opts, :obsoleted, String)
if type == :enum
if !opts.has_key?(:list) || !opts[:list].is_a?(Array) || opts[:list].empty? || !opts[:list].all?(Symbol)
raise ArgumentError, "#{name}: enum parameter requires :list of Symbols"
end
end
option_value_type!(name, opts, :symbolize_keys, type: :boolean)
option_value_type!(name, opts, :value_type, Symbol) # hash, array
option_value_type!(name, opts, :skip_accessor, type: :boolean)
if opts.has_key?(:default)
config_set_default(name, opts[:default])
end
if opts.has_key?(:desc)
config_set_desc(name, opts[:desc])
end
if opts[:deprecated] && opts[:obsoleted]
raise ArgumentError, "#{name}: both of deprecated and obsoleted cannot be specified at once"
end
[name, block, opts]
end
def configured_in(section_name)
if @configured_in_section
raise ArgumentError, "#{self.name}: configured_in called twice"
end
@configured_in_section = section_name.to_sym
end
def config_argument(name, type = nil, **kwargs, &block)
if @argument
raise ArgumentError, "#{self.name}: config_argument called twice"
end
name, block, opts = parameter_configuration(name, type, **kwargs, &block)
@argument = [name, block, opts]
name
end
def config_param(name, type = nil, **kwargs, &block)
name, block, opts = parameter_configuration(name, type, **kwargs, &block)
if @current_description
config_set_desc(name, @current_description)
@current_description = nil
end
@sections.delete(name)
@params[name] = [block, opts]
name
end
def config_set_default(name, defval)
name = name.to_sym
if @defaults.has_key?(name)
raise ArgumentError, "#{self.name}: default value specified twice for #{name}"
end
@defaults[name] = defval
nil
end
def config_set_desc(name, description)
name = name.to_sym
if @descriptions.has_key?(name)
raise ArgumentError, "#{self.name}: description specified twice for #{name}"
end
@descriptions[name] = description
nil
end
def desc(description)
@current_description = description
end
def config_section(name, **kwargs, &block)
unless block_given?
raise ArgumentError, "#{name}: config_section requires block parameter"
end
name = name.to_sym
sub_proxy = ConfigureProxy.new(name, type_lookup: @type_lookup, **kwargs)
sub_proxy.instance_exec(&block)
@params.delete(name)
@sections[name] = sub_proxy
name
end
def dump_config_definition
dumped_config = {}
if @argument
argument_name, _block, options = @argument
options[:required] = !@defaults.key?(argument_name)
options[:argument] = true
dumped_config[argument_name] = options
end
@params.each do |name, config|
dumped_config[name] = config[1]
dumped_config[name][:required] = !@defaults.key?(name)
dumped_config[name][:default] = @defaults[name] if @defaults.key?(name)
dumped_config[name][:desc] = @descriptions[name] if @descriptions.key?(name)
end
# Overwrite by config_set_default
@defaults.each do |name, value|
if @params.key?(name) || (@argument && @argument.first == name)
dumped_config[name][:default] = value
else
dumped_config[name] = { default: value }
end
end
# Overwrite by config_set_desc
@descriptions.each do |name, value|
if @params.key?(name)
dumped_config[name][:desc] = value
else
dumped_config[name] = { desc: value }
end
end
@sections.each do |section_name, sub_proxy|
if dumped_config.key?(section_name)
dumped_config[section_name].update(sub_proxy.dump_config_definition)
else
dumped_config[section_name] = sub_proxy.dump_config_definition
dumped_config[section_name][:required] = sub_proxy.required?
dumped_config[section_name][:multi] = sub_proxy.multi?
dumped_config[section_name][:alias] = sub_proxy.alias
dumped_config[section_name][:section] = true
end
end
dumped_config
end
private
def overwrite?(other, attribute_name)
value = instance_variable_get("@#{attribute_name}")
other_value = other.__send__(attribute_name)
!value.nil? && !other_value.nil? && value != other_value
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/element.rb | lib/fluent/config/element.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config/error'
require 'fluent/config/literal_parser'
module Fluent
module Config
class Element < Hash
def initialize(name, arg, attrs, elements, unused = nil)
@name = name
@arg = arg
@elements = elements
super()
attrs.each { |k, v|
self[k] = v
}
@unused = unused || attrs.keys
@v1_config = false
@corresponding_proxies = [] # some plugins use flat parameters, e.g. in_http doesn't provide <format> section for parser.
@unused_in = nil # if this element is not used in plugins, corresponding plugin name and parent element name is set, e.g. [source, plugin class].
# it's global logger, not plugin logger: deprecated message should be global warning, not plugin level.
@logger = defined?($log) ? $log : nil
@target_worker_ids = []
end
attr_accessor :name, :arg, :unused, :v1_config, :corresponding_proxies, :unused_in
attr_writer :elements
attr_reader :target_worker_ids
RESERVED_PARAMETERS_COMPAT = {
'@type' => 'type',
'@id' => 'id',
'@log_level' => 'log_level',
'@label' => nil,
}
RESERVED_PARAMETERS = RESERVED_PARAMETERS_COMPAT.keys
def elements(*names, name: nil, arg: nil)
raise ArgumentError, "name and names are exclusive" if name && !names.empty?
raise ArgumentError, "arg is available only with name" if arg && !name
if name
@elements.select{|e| e.name == name && (!arg || e.arg == arg) }
elsif !names.empty?
@elements.select{|e| names.include?(e.name) }
else
@elements
end
end
def add_element(name, arg = '')
e = Element.new(name, arg, {}, [])
e.v1_config = @v1_config
@elements << e
e
end
def inspect
attrs = super
"<name:#{@name}, arg:#{@arg}, attrs:#{attrs}, elements:#{@elements.inspect}>"
end
# Used by PP and Pry
def pretty_print(q)
q.text(inspect)
end
# This method assumes _o_ is an Element object. Should return false for nil or other object
def ==(o)
self.name == o.name && self.arg == o.arg &&
self.keys.size == o.keys.size &&
self.keys.reduce(true){|r, k| r && self[k] == o[k] } &&
self.elements.size == o.elements.size &&
[self.elements, o.elements].transpose.reduce(true){|r, e| r && e[0] == e[1] }
end
def +(o)
e = Element.new(@name.dup, @arg.dup, o.merge(self), @elements + o.elements, (@unused + o.unused).uniq)
e.v1_config = @v1_config
e
end
# no code in fluentd uses this method
def each_element(*names, &block)
if names.empty?
@elements.each(&block)
else
@elements.each { |e|
if names.include?(e.name)
block.yield(e)
end
}
end
end
def has_key?(key)
@unused_in = [] # some sections, e.g. <store> in copy, is not defined by config_section so clear unused flag for better warning message in check_not_fetched.
@unused.delete(key)
super
end
def [](key)
@unused_in = [] # ditto
@unused.delete(key)
if RESERVED_PARAMETERS.include?(key) && !has_key?(key) && has_key?(RESERVED_PARAMETERS_COMPAT[key])
@logger.warn "'#{RESERVED_PARAMETERS_COMPAT[key]}' is deprecated parameter name. use '#{key}' instead." if @logger
return self[RESERVED_PARAMETERS_COMPAT[key]]
end
super
end
def check_not_fetched(&block)
each_key { |key|
if @unused.include?(key)
block.call(key, self)
end
}
@elements.each { |e|
e.check_not_fetched(&block)
}
end
def to_s(nest = 0)
indent = " " * nest
nindent = " " * (nest + 1)
out = ""
if @arg.nil? || @arg.empty?
out << "#{indent}<#{@name}>\n"
else
out << "#{indent}<#{@name} #{@arg}>\n"
end
each_pair { |k, v|
out << dump_value(k, v, nindent)
}
@elements.each { |e|
out << e.to_s(nest + 1)
}
out << "#{indent}</#{@name}>\n"
out
end
def to_masked_element
new_elems = @elements.map { |e| e.to_masked_element }
new_elem = Element.new(@name, @arg, {}, new_elems, @unused)
new_elem.v1_config = @v1_config
new_elem.corresponding_proxies = @corresponding_proxies
each_pair { |k, v|
new_elem[k] = secret_param?(k) ? 'xxxxxx' : v
}
new_elem
end
def secret_param?(key)
return false if @corresponding_proxies.empty?
param_key = key.to_sym
@corresponding_proxies.each { |proxy|
_block, opts = proxy.params[param_key]
if opts && opts.has_key?(:secret)
return opts[:secret]
end
}
false
end
def param_type(key)
return nil if @corresponding_proxies.empty?
param_key = key.to_sym
proxy = @corresponding_proxies.detect do |_proxy|
_proxy.params.has_key?(param_key)
end
return nil unless proxy
_block, opts = proxy.params[param_key]
opts[:type]
end
def default_value(key)
return nil if @corresponding_proxies.empty?
param_key = key.to_sym
proxy = @corresponding_proxies.detect do |_proxy|
_proxy.params.has_key?(param_key)
end
return nil unless proxy
proxy.defaults[param_key]
end
def dump_value(k, v, nindent)
return "#{nindent}#{k} xxxxxx\n" if secret_param?(k)
return "#{nindent}#{k} #{v}\n" unless @v1_config
# for v1 config
if v.nil?
"#{nindent}#{k} \n"
elsif v == :default
"#{nindent}#{k} #{default_value(k)}\n"
else
case param_type(k)
when :string
"#{nindent}#{k} \"#{self.class.unescape_parameter(v)}\"\n"
when :enum, :integer, :float, :size, :bool, :time
"#{nindent}#{k} #{v}\n"
when :hash, :array
"#{nindent}#{k} #{v}\n"
else
# Unknown type
"#{nindent}#{k} #{v}\n"
end
end
end
def self.unescape_parameter(v)
result = ''
v.each_char { |c| result << LiteralParser.unescape_char(c) }
result
end
def set_target_worker_id(worker_id)
@target_worker_ids = [worker_id]
@elements.each { |e|
e.set_target_worker_id(worker_id)
}
end
def set_target_worker_ids(worker_ids)
@target_worker_ids = worker_ids.uniq
@elements.each { |e|
e.set_target_worker_ids(worker_ids.uniq)
}
end
def for_every_workers?
@target_worker_ids.empty?
end
def for_this_worker?
@target_worker_ids.include?(Fluent::Engine.worker_id)
end
def for_another_worker?
!@target_worker_ids.empty? && !@target_worker_ids.include?(Fluent::Engine.worker_id)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/section.rb | lib/fluent/config/section.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'json'
require 'fluent/config/error'
require 'fluent/config/v1_parser'
module Fluent
module Config
class Section < BasicObject
def self.name
'Fluent::Config::Section'
end
def initialize(params = {}, config_element = nil)
@klass = 'Fluent::Config::Section'
@params = params
@corresponding_config_element = config_element
end
alias :object_id :__id__
def corresponding_config_element
@corresponding_config_element
end
def class
Section
end
def to_s
inspect
end
def inspect
"<Fluent::Config::Section #{@params.to_json}>"
end
# Used by PP and Pry
def pretty_print(q)
q.text(inspect)
end
def nil?
false
end
def to_h
@params
end
def dup
Section.new(@params.dup, @corresponding_config_element.dup)
end
def +(other)
Section.new(self.to_h.merge(other.to_h))
end
def instance_of?(mod)
@klass == mod.name
end
def kind_of?(mod)
@klass == mod.name || BasicObject == mod
end
alias is_a? kind_of?
def [](key)
@params[key.to_sym]
end
def []=(key, value)
@params[key.to_sym] = value
end
def respond_to?(symbol, include_all=false)
case symbol
when :inspect, :nil?, :to_h, :+, :instance_of?, :kind_of?, :[], :respond_to?, :respond_to_missing?
true
when :!, :!= , :==, :equal?, :instance_eval, :instance_exec
true
when :method_missing, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined
include_all
else
false
end
end
def respond_to_missing?(symbol, include_private)
@params.has_key?(symbol)
end
def method_missing(name, *args)
if @params.has_key?(name)
@params[name]
else
::Kernel.raise ::NoMethodError, "undefined method `#{name}' for #{self.inspect}"
end
end
end
module SectionGenerator
def self.generate(proxy, conf, logger, plugin_class, stack = [], strict_config_value = false)
return nil if conf.nil?
section_stack = ""
unless stack.empty?
section_stack = ", in section " + stack.join(" > ")
end
section_params = {}
proxy.defaults.each_pair do |name, defval|
varname = name.to_sym
section_params[varname] = (defval.dup rescue defval)
end
if proxy.argument
unless conf.arg.nil? || conf.arg.empty?
key, block, opts = proxy.argument
opts = opts.merge(strict: true) if strict_config_value
if conf.arg == :default
unless section_params.has_key?(key)
logger.error "config error in:\n#{conf}" if logger
raise ConfigError, "'#{key}' doesn't have default value"
end
else
begin
section_params[key] = self.instance_exec(conf.arg, opts, key, &block)
rescue ConfigError => e
logger.error "config error in:\n#{conf}" if logger
raise e
end
end
end
unless section_params.has_key?(proxy.argument.first)
logger.error "config error in:\n#{conf}" if logger # logger should exist, but sometimes it's nil (e.g, in tests)
raise ConfigError, "'<#{proxy.name} ARG>' section requires argument" + section_stack
end
# argument should NOT be deprecated... (argument always has a value: '')
end
proxy.params.each_pair do |name, defval|
varname = name.to_sym
block, opts = defval
opts = opts.merge(strict: true) if strict_config_value
if conf.has_key?(name.to_s) || opts[:alias] && conf.has_key?(opts[:alias].to_s)
val = if conf.has_key?(name.to_s)
conf[name.to_s]
else
conf[opts[:alias].to_s]
end
if val == :default
# default value is already set if it exists
unless section_params.has_key?(varname)
logger.error "config error in:\n#{conf}" if logger
raise ConfigError, "'#{varname}' doesn't have default value"
end
else
begin
section_params[varname] = self.instance_exec(val, opts, name, &block)
rescue ConfigError => e
logger.error "config error in:\n#{conf}" if logger
raise e
end
end
if section_params[varname].nil?
unless proxy.defaults.has_key?(varname) && proxy.defaults[varname].nil?
logger.error "config error in:\n#{conf}" if logger
raise ConfigError, "'#{name}' parameter is required but nil is specified"
end
end
# Source of definitions of deprecated/obsoleted:
# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features
#
# Deprecated: These deprecated features can still be used, but should be used with caution
# because they are expected to be removed entirely sometime in the future.
# Obsoleted: These obsolete features have been entirely removed from JavaScript and can no longer be used.
if opts[:deprecated]
logger.warn "'#{name}' parameter is deprecated: #{opts[:deprecated]}" if logger
end
if opts[:obsoleted]
logger.error "config error in:\n#{conf}" if logger
raise ObsoletedParameterError, "'#{name}' parameter is already removed: #{opts[:obsoleted]}" + section_stack
end
end
unless section_params.has_key?(varname)
logger.error "config error in:\n#{conf}" if logger
raise ConfigError, "'#{name}' parameter is required" + section_stack
end
end
check_unused_section(proxy, conf, plugin_class)
proxy.sections.each do |name, subproxy|
varname = subproxy.variable_name
elements = (conf.respond_to?(:elements) ? conf.elements : []).select{ |e| e.name == subproxy.name.to_s || e.name == subproxy.alias.to_s }
if elements.empty? && subproxy.init?
if subproxy.argument && !subproxy.defaults.has_key?(subproxy.argument.first)
raise ArgumentError, "#{name}: init is specified, but default value of argument is missing"
end
missing_keys = subproxy.params.keys.select{|param_name| !subproxy.defaults.has_key?(param_name)}
if !missing_keys.empty?
raise ArgumentError, "#{name}: init is specified, but there're parameters without default values:#{missing_keys.join(',')}"
end
elements << Fluent::Config::Element.new(subproxy.name.to_s, '', {}, [])
end
# set subproxy for secret option
elements.each { |element|
element.corresponding_proxies << subproxy
}
if subproxy.required? && elements.size < 1
logger.error "config error in:\n#{conf}" if logger
raise ConfigError, "'<#{subproxy.name}>' sections are required" + section_stack
end
if subproxy.multi?
section_params[varname] = elements.map{ |e| generate(subproxy, e, logger, plugin_class, stack + [subproxy.name], strict_config_value) }
else
if elements.size > 1
logger.error "config error in:\n#{conf}" if logger
raise ConfigError, "'<#{subproxy.name}>' section cannot be written twice or more" + section_stack
end
section_params[varname] = generate(subproxy, elements.first, logger, plugin_class, stack + [subproxy.name], strict_config_value)
end
end
Section.new(section_params, conf)
end
def self.check_unused_section(proxy, conf, plugin_class)
elems = conf.respond_to?(:elements) ? conf.elements : []
elems.each { |e|
next if plugin_class.nil? && Fluent::Config::V1Parser::ELEM_SYMBOLS.include?(e.name) # skip pre-defined non-plugin elements because it doesn't have proxy section
next if e.unused_in&.empty? # the section is used at least once
if proxy.sections.any? { |name, subproxy| e.name == subproxy.name.to_s || e.name == subproxy.alias.to_s }
e.unused_in = []
else
parent_name = if conf.arg.empty?
conf.name
else
"#{conf.name} #{conf.arg}"
end
e.unused_in = [parent_name, plugin_class]
end
}
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/parser.rb | lib/fluent/config/parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'uri'
require 'fluent/config/error'
require 'fluent/config/element'
module Fluent
module Config
class Parser
def self.parse(io, fname, basepath = Dir.pwd)
attrs, elems = Parser.new(basepath, io.each_line, fname).parse!(true)
Element.new('ROOT', '', attrs, elems)
end
def initialize(basepath, iterator, fname, i = 0)
@basepath = basepath
@iterator = iterator
@i = i
@fname = fname
end
def parse!(allow_include, elem_name = nil, attrs = {}, elems = [])
while line = @iterator.next
line.force_encoding('UTF-8')
@i += 1
line.lstrip!
line.gsub!(/\s*(?:\#.*)?$/,'')
if line.empty?
next
elsif m = /^\<include\s*(.*)\s*\/\>$/.match(line)
value = m[1].strip
process_include(attrs, elems, value, allow_include)
elsif m = /^\<([a-zA-Z0-9_]+)\s*(.+?)?\>$/.match(line)
e_name = m[1]
e_arg = m[2] || ""
e_attrs, e_elems = parse!(false, e_name)
elems << Element.new(e_name, e_arg, e_attrs, e_elems)
elsif line == "</#{elem_name}>"
break
elsif m = /^([a-zA-Z0-9_]+)\s*(.*)$/.match(line)
key = m[1]
value = m[2]
if allow_include && key == 'include'
process_include(attrs, elems, value)
else
attrs[key] = value
end
next
else
raise ConfigParseError, "parse error at #{@fname} line #{@i}"
end
end
return attrs, elems
rescue StopIteration
return attrs, elems
end
def process_include(attrs, elems, uri, allow_include = true)
u = URI.parse(uri)
if u.scheme == 'file' || u.path == uri # file path
path = u.path
if path[0] != ?/
pattern = File.expand_path("#{@basepath}/#{path}")
else
pattern = path
end
Dir.glob(pattern).sort.each { |entry|
basepath = File.dirname(entry)
fname = File.basename(entry)
File.open(entry) { |f|
Parser.new(basepath, f.each_line, fname).parse!(allow_include, nil, attrs, elems)
}
}
else
basepath = '/'
fname = path
parser_proc = ->(f) {
Parser.new(basepath, f.each_line, fname).parse!(allow_include, nil, attrs, elems)
}
case u.scheme
when 'http', 'https', 'ftp'
# URI#open can be able to handle URIs for http, https and ftp.
require 'open-uri'
u.open(&parser_proc)
else
# TODO: This case should be handled in the previous if condition. Glob is not applied to some Windows path formats.
# 'c:/path/to/file' will be passed as URI, 'uri' and 'u.path' will be:
# - uri is 'c:/path/to/file'
# - u.path is '/path/to/file' and u.scheme is 'c'
# Therefore, the condition of the if statement above is not met and it is handled here.
File.open(uri, &parser_proc)
end
end
rescue SystemCallError => e
raise ConfigParseError, "include error at #{@fname} line #{@i}: #{e.to_s}"
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/literal_parser.rb | lib/fluent/config/literal_parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'stringio'
require 'json'
require 'yajl'
require 'socket'
require 'ripper'
require 'fluent/config/basic_parser'
module Fluent
module Config
class LiteralParser < BasicParser
def self.unescape_char(c)
case c
when '"'
'\"'
when "'"
"\\'"
when '\\'
'\\\\'
when "\r"
'\r'
when "\n"
'\n'
when "\t"
'\t'
when "\f"
'\f'
when "\b"
'\b'
else
c
end
end
def initialize(strscan, eval_context)
super(strscan)
@eval_context = eval_context
unless @eval_context.respond_to?(:use_nil)
def @eval_context.use_nil
raise SetNil
end
end
unless @eval_context.respond_to?(:use_default)
def @eval_context.use_default
raise SetDefault
end
end
end
def parse_literal(string_boundary_charset = LINE_END)
spacing_without_comment
value = if skip(/\[/)
scan_json(true)
elsif skip(/\{/)
scan_json(false)
else
scan_string(string_boundary_charset)
end
value
end
def scan_string(string_boundary_charset = LINE_END)
if skip(/\"/)
return scan_double_quoted_string
elsif skip(/\'/)
return scan_single_quoted_string
else
return scan_nonquoted_string(string_boundary_charset)
end
end
def scan_double_quoted_string
string = []
while true
if skip(/\"/)
if string.include?(nil)
return nil
elsif string.include?(:default)
return :default
else
return string.join
end
elsif check(/[^"]#{LINE_END_WITHOUT_SPACING_AND_COMMENT}/o)
if s = check(/[^\\]#{LINE_END_WITHOUT_SPACING_AND_COMMENT}/o)
string << s
end
skip(/[^"]#{LINE_END_WITHOUT_SPACING_AND_COMMENT}/o)
elsif s = scan(/\\./)
string << eval_escape_char(s[1,1])
elsif skip(/\#\{/)
string << eval_embedded_code(scan_embedded_code)
skip(/\}/)
elsif s = scan(/./)
string << s
else
parse_error! "unexpected end of file in a double quoted string"
end
end
end
def scan_single_quoted_string
string = []
while true
if skip(/\'/)
return string.join
elsif s = scan(/\\'/)
string << "'"
elsif s = scan(/\\\\/)
string << "\\"
elsif s = scan(/./)
string << s
else
parse_error! "unexpected end of file in a single quoted string"
end
end
end
def scan_nonquoted_string(boundary_charset = LINE_END)
charset = /(?!#{boundary_charset})./
string = []
while true
if s = scan(/\#/)
string << '#'
elsif s = scan(charset)
string << s
else
break
end
end
if string.empty?
return nil
end
string.join
end
def scan_embedded_code
src = '"#{'+@ss.rest+"\n=begin\n=end\n}"
seek = -1
while (seek = src.index('}', seek + 1))
unless Ripper.sexp(src[0..seek] + '"').nil? # eager parsing until valid expression
break
end
end
unless seek
raise Fluent::ConfigParseError, @ss.rest
end
code = src[3, seek-3]
if @ss.rest.length < code.length
@ss.pos += @ss.rest.length
parse_error! "expected end of embedded code but $end"
end
@ss.pos += code.length
'"#{' + code + '}"'
end
def eval_embedded_code(code)
if @eval_context.nil?
parse_error! "embedded code is not allowed in this file"
end
# Add hostname and worker_id to code for preventing unused warnings
code = <<EOM + code
hostname = Socket.gethostname
worker_id = ENV['SERVERENGINE_WORKER_ID'] || ''
EOM
begin
@eval_context.instance_eval(code)
rescue SetNil
nil
rescue SetDefault
:default
end
end
def eval_escape_char(c)
case c
when '"'
'"'
when "'"
"'"
when "r"
"\r"
when "n"
"\n"
when "t"
"\t"
when "f"
"\f"
when "b"
"\b"
when "0"
"\0"
when /[a-zA-Z0-9]/
parse_error! "unexpected back-slash escape character '#{c}'"
else # symbols
c
end
end
def scan_json(is_array)
result = nil
# Yajl does not raise ParseError for incomplete json string, like '[1', '{"h"', '{"h":' or '{"h1":1'
# This is the reason to use JSON module.
buffer = (is_array ? "[" : "{")
line_buffer = ""
until result
char = getch
break if char.nil?
if char == "#"
# If this is out of json string literals, this object can be parsed correctly
# '{"foo":"bar", #' -> '{"foo":"bar"}' (to check)
parsed = nil
begin
parsed = JSON.parse(buffer + line_buffer.rstrip.sub(/,$/, '') + (is_array ? "]" : "}"))
rescue JSON::ParserError
# This '#' is in json string literals
end
if parsed
# ignore chars as comment before newline
while (char = getch) != "\n"
# ignore comment char
end
buffer << line_buffer + "\n"
line_buffer = ""
else
if @ss.exist?(/^\{[^}]+\}/)
# if it's interpolated string
skip(/\{/)
line_buffer << eval_embedded_code(scan_embedded_code)
skip(/\}/)
else
# '#' is a char in json string
line_buffer << char
end
end
next # This char '#' MUST NOT terminate json object.
end
if char == "\n"
buffer << line_buffer + "\n"
line_buffer = ""
next
end
line_buffer << char
begin
result = JSON.parse(buffer + line_buffer)
rescue JSON::ParserError
# Incomplete json string yet
end
end
unless result
parse_error! "got incomplete JSON #{is_array ? 'array' : 'hash'} configuration"
end
JSON.dump(result)
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/dsl.rb | lib/fluent/config/dsl.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'json'
require 'fluent/config'
require 'fluent/config/element'
module Fluent
module Config
module DSL
RESERVED_PARAMETERS = [:type, :id, :log_level, :label] # Need '@' prefix for reserved parameters
module Parser
def self.read(path)
path = File.expand_path(path)
data = File.read(path)
parse(data, path)
end
def self.parse(source, source_path="config.rb")
Proxy.new('ROOT', nil).eval(source, source_path).to_config_element
end
end
class Proxy
def initialize(name, arg, include_basepath = Dir.pwd)
@element = Element.new(name, arg, self)
@include_basepath = include_basepath
end
def element
@element
end
def include_basepath
@include_basepath
end
def eval(source, source_path)
@element.instance_eval(source, source_path)
self
end
def to_config_element
@element.instance_eval do
Config::Element.new(@name, @arg, @attrs, @elements)
end
end
def add_element(name, arg, block)
::Kernel.raise ::ArgumentError, "#{name} block must be specified" if block.nil?
proxy = self.class.new(name.to_s, arg)
proxy.element.instance_exec(&block)
@element.instance_eval do
@elements.push(proxy.to_config_element)
end
self
end
end
class Element < BasicObject
def initialize(name, arg, proxy)
@name = name
@arg = arg || ''
@attrs = {}
@elements = []
@proxy = proxy
end
def to_int
__id__
end
def method_missing(name, *args, &block)
::Kernel.raise ::ArgumentError, "Configuration DSL Syntax Error: only one argument allowed" if args.size > 1
value = args.first
if block
proxy = Proxy.new(name.to_s, value)
proxy.element.instance_exec(&block)
@elements.push(proxy.to_config_element)
else
param_name = RESERVED_PARAMETERS.include?(name) ? "@#{name}" : name.to_s
@attrs[param_name] = if value.is_a?(Array) || value.is_a?(Hash)
JSON.dump(value)
else
value.to_s
end
end
self
end
def include(*args)
::Kernel.raise ::ArgumentError, "#{name} block requires arguments for include path" if args.nil? || args.size != 1
if /\.rb$/.match?(args.first)
path = File.expand_path(args.first)
data = File.read(path)
self.instance_eval(data, path)
else
ss = StringScanner.new('')
Config::V1Parser.new(ss, @proxy.include_basepath, '', nil).eval_include(@attrs, @elements, args.first)
end
end
def source(&block)
@proxy.add_element('source', nil, block)
end
def match(*args, &block)
::Kernel.raise ::ArgumentError, "#{name} block requires arguments for match pattern" if args.nil? || args.size != 1
@proxy.add_element('match', args.first, block)
end
def self.const_missing(name)
return ::Kernel.const_get(name) if ::Kernel.const_defined?(name)
if name.to_s =~ /^Fluent::Config::DSL::Element::(.*)$/
name = "#{$1}".to_sym
return ::Kernel.const_get(name) if ::Kernel.const_defined?(name)
end
::Kernel.eval("#{name}")
end
def ruby(&block)
if block
@proxy.instance_exec(&block)
else
::Kernel
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/v1_parser.rb | lib/fluent/config/v1_parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'strscan'
require 'uri'
require 'fluent/config/error'
require 'fluent/config/basic_parser'
require 'fluent/config/literal_parser'
require 'fluent/config/element'
module Fluent
module Config
class V1Parser < LiteralParser
ELEMENT_NAME = /[a-zA-Z0-9_]+/
def self.parse(data, fname, basepath = Dir.pwd, eval_context = nil)
ss = StringScanner.new(data)
ps = V1Parser.new(ss, basepath, fname, eval_context)
ps.parse!
end
def initialize(strscan, include_basepath, fname, eval_context)
super(strscan, eval_context)
@include_basepath = include_basepath
@fname = fname
@logger = defined?($log) ? $log : nil
end
def parse!
attrs, elems = parse_element(true, nil)
root = Element.new('ROOT', '', attrs, elems)
root.v1_config = true
spacing
unless eof?
parse_error! "expected EOF"
end
return root
end
ELEM_SYMBOLS = ['match', 'source', 'filter', 'system']
RESERVED_PARAMS = %W(@type @id @label @log_level)
def parse_element(root_element, elem_name, attrs = {}, elems = [])
while true
spacing
if eof?
if root_element
break
end
parse_error! "expected end tag '</#{elem_name}>' but got end of file"
end
if skip(/\<\//)
e_name = scan(ELEMENT_NAME)
spacing
unless skip(/\>/)
parse_error! "expected character in tag name"
end
unless line_end
parse_error! "expected end of line after end tag"
end
if e_name != elem_name
parse_error! "unmatched end tag"
end
break
elsif skip(/\</)
e_name = scan(ELEMENT_NAME)
spacing
e_arg = scan_string(/(?:#{ZERO_OR_MORE_SPACING}\>)/o)
spacing
unless skip(/\>/)
parse_error! "expected '>'"
end
unless line_end
parse_error! "expected end of line after tag"
end
e_arg ||= ''
# call parse_element recursively
e_attrs, e_elems = parse_element(false, e_name)
new_e = Element.new(e_name, e_arg, e_attrs, e_elems)
new_e.v1_config = true
elems << new_e
elsif root_element && skip(/(\@include|include)#{SPACING}/o)
if !prev_match.start_with?('@')
@logger.warn "'include' is deprecated. Use '@include' instead" if @logger
end
parse_include(attrs, elems)
else
k = scan_string(SPACING)
spacing_without_comment
if prev_match.include?("\n") || eof? # support 'tag_mapped' like "without value" configuration
attrs[k] = ""
else
if k == '@include'
parse_include(attrs, elems)
elsif RESERVED_PARAMS.include?(k)
v = parse_literal
unless line_end
parse_error! "expected end of line"
end
attrs[k] = v
else
if k.start_with?('@')
if root_element || ELEM_SYMBOLS.include?(elem_name)
parse_error! "'@' is the system reserved prefix. Don't use '@' prefix parameter in the configuration: #{k}"
else
# TODO: This is for backward compatibility. It will throw an error in the future.
@logger.warn "'@' is the system reserved prefix. It works in the nested configuration for now but it will be rejected: #{k}" if @logger
end
end
v = parse_literal
unless line_end
parse_error! "expected end of line"
end
attrs[k] = v
end
end
end
end
return attrs, elems
end
def parse_include(attrs, elems)
uri = scan_string(LINE_END)
eval_include(attrs, elems, uri)
line_end
end
def eval_include(attrs, elems, uri)
# replace space(s)(' ') with '+' to prevent invalid uri due to space(s).
# See: https://github.com/fluent/fluentd/pull/2780#issuecomment-576081212
u = URI.parse(uri.tr(' ', '+'))
if u.scheme == 'file' || (!u.scheme.nil? && u.scheme.length == 1) || u.path == uri.tr(' ', '+') # file path
# When the Windows absolute path then u.scheme.length == 1
# e.g. C:
path = URI.decode_www_form_component(u.path)
if path[0] != ?/
pattern = File.expand_path("#{@include_basepath}/#{path}")
else
pattern = path
end
Dir.glob(pattern).sort.each { |entry|
basepath = File.dirname(entry)
fname = File.basename(entry)
data = File.read(entry)
data.force_encoding('UTF-8')
ss = StringScanner.new(data)
V1Parser.new(ss, basepath, fname, @eval_context).parse_element(true, nil, attrs, elems)
}
else
require 'open-uri'
basepath = '/'
fname = path
data = u.open { |f| f.read }
data.force_encoding('UTF-8')
ss = StringScanner.new(data)
V1Parser.new(ss, basepath, fname, @eval_context).parse_element(true, nil, attrs, elems)
end
rescue SystemCallError => e
cpe = ConfigParseError.new("include error #{uri} - #{e}")
cpe.set_backtrace(e.backtrace)
raise cpe
end
# override
def error_sample
"#{@fname} #{super}"
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/types.rb | lib/fluent/config/types.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'json'
require 'fluent/config/error'
module Fluent
module Config
def self.reformatted_value(type, val, opts = {}, name = nil)
REFORMAT_VALUE.call(type, val, opts, name)
end
def self.size_value(str, opts = {}, name = nil)
return nil if str.nil?
case str.to_s
when /([0-9]+)k/i
$~[1].to_i * 1024
when /([0-9]+)m/i
$~[1].to_i * (1024 ** 2)
when /([0-9]+)g/i
$~[1].to_i * (1024 ** 3)
when /([0-9]+)t/i
$~[1].to_i * (1024 ** 4)
else
INTEGER_TYPE.call(str, opts, name)
end
end
def self.time_value(str, opts = {}, name = nil)
return nil if str.nil?
case str.to_s
when /([0-9]+)s/
$~[1].to_i
when /([0-9]+)m/
$~[1].to_i * 60
when /([0-9]+)h/
$~[1].to_i * 60 * 60
when /([0-9]+)d/
$~[1].to_i * 24 * 60 * 60
else
FLOAT_TYPE.call(str, opts, name)
end
end
def self.bool_value(str, opts = {}, name = nil)
return nil if str.nil?
case str.to_s
when 'true', 'yes'
true
when 'false', 'no'
false
when ''
true
else
# Current parser passes comment without actual values, e.g. "param #foo".
# parser should pass empty string in this case but changing behaviour may break existing environment so keep parser behaviour. Just ignore comment value in boolean handling for now.
if str.respond_to?(:start_with?) && str.start_with?('#')
true
elsif opts[:strict]
raise Fluent::ConfigError, "#{name}: invalid bool value: #{str}"
else
nil
end
end
end
def self.regexp_value(str, opts = {}, name = nil)
return nil unless str
return Regexp.compile(str) unless str.start_with?("/")
right_slash_position = str.rindex("/")
if right_slash_position < str.size - 3
raise Fluent::ConfigError, "invalid regexp: missing right slash: #{str}"
end
options = str[(right_slash_position + 1)..-1]
option = 0
option |= Regexp::IGNORECASE if options.include?("i")
option |= Regexp::MULTILINE if options.include?("m")
Regexp.compile(str[1...right_slash_position], option)
end
def self.string_value(val, opts = {}, name = nil)
return nil if val.nil?
v = val.to_s
v = v.frozen? ? v.dup : v # config_param can't assume incoming string is mutable
v.force_encoding(Encoding::UTF_8)
end
STRING_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.string_value(val, opts, name)
}
def self.symbol_value(val, opts = {}, name = nil)
return nil if val.nil? || val.empty?
val.delete_prefix(":").to_sym
end
SYMBOL_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.symbol_value(val, opts, name)
}
def self.enum_value(val, opts = {}, name = nil)
return nil if val.nil?
s = val.to_sym
list = opts[:list]
raise "Plugin BUG: config type 'enum' requires :list of symbols" unless list.is_a?(Array) && list.all?(Symbol)
unless list.include?(s)
raise ConfigError, "valid options are #{list.join(',')} but got #{val}"
end
s
end
ENUM_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.enum_value(val, opts, name)
}
INTEGER_TYPE = Proc.new { |val, opts = {}, name = nil|
if val.nil?
nil
elsif opts[:strict]
begin
Integer(val)
rescue ArgumentError, TypeError => e
raise ConfigError, "#{name}: #{e.message}"
end
else
val.to_i
end
}
FLOAT_TYPE = Proc.new { |val, opts = {}, name = nil|
if val.nil?
nil
elsif opts[:strict]
begin
Float(val)
rescue ArgumentError, TypeError => e
raise ConfigError, "#{name}: #{e.message}"
end
else
val.to_f
end
}
SIZE_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.size_value(val, opts, name)
}
BOOL_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.bool_value(val, opts, name)
}
TIME_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.time_value(val, opts, name)
}
REGEXP_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.regexp_value(val, opts, name)
}
REFORMAT_VALUE = ->(type, value, opts = {}, name = nil) {
if value.nil?
value
else
case type
when :string then value.to_s.force_encoding(Encoding::UTF_8)
when :integer then INTEGER_TYPE.call(value, opts, name)
when :float then FLOAT_TYPE.call(value, opts, name)
when :size then Config.size_value(value, opts, name)
when :bool then Config.bool_value(value, opts, name)
when :time then Config.time_value(value, opts, name)
when :regexp then Config.regexp_value(value, opts, name)
when :symbol then Config.symbol_value(value, opts, name)
else
raise "unknown type in REFORMAT: #{type}"
end
end
}
def self.hash_value(val, opts = {}, name = nil)
return nil if val.nil?
param = if val.is_a?(String)
val.start_with?('{') ? JSON.parse(val) : Hash[val.strip.split(/\s*,\s*/).map{|v| v.split(':', 2)}]
else
val
end
if param.class != Hash
raise ConfigError, "hash required but got #{val.inspect}"
end
if opts.empty?
param
else
newparam = {}
param.each_pair do |key, value|
new_key = opts[:symbolize_keys] ? key.to_sym : key
newparam[new_key] = opts[:value_type] ? REFORMAT_VALUE.call(opts[:value_type], value, opts, new_key) : value
end
newparam
end
end
HASH_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.hash_value(val, opts, name)
}
def self.array_value(val, opts = {}, name = nil)
return nil if val.nil?
param = if val.is_a?(String)
val.start_with?('[') ? JSON.parse(val) : val.strip.split(/\s*,\s*/)
else
val
end
if param.class != Array
raise ConfigError, "array required but got #{val.inspect}"
end
if opts[:value_type]
param.map{|v| REFORMAT_VALUE.call(opts[:value_type], v, opts, nil) }
else
param
end
end
ARRAY_TYPE = Proc.new { |val, opts = {}, name = nil|
Config.array_value(val, opts, name)
}
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/basic_parser.rb | lib/fluent/config/basic_parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'stringio'
require 'fluent/config/error'
module Fluent
module Config
class BasicParser
def initialize(strscan)
@ss = strscan
end
LINE_END = /(?:[ \t]*(?:\#.*)?(?:\z|[\r\n]))+/
SPACING = /(?:[ \t\r\n]|\z|\#.*?(?:\z|[\r\n]))+/
ZERO_OR_MORE_SPACING = /(?:[ \t\r\n]|\z|\#.*?(?:\z|[\r\n]))*/
SPACING_WITHOUT_COMMENT = /(?:[ \t\r\n]|\z)+/
LINE_END_WITHOUT_SPACING_AND_COMMENT = /(?:\z|[\r\n])/
module ClassMethods
def symbol(string)
/#{Regexp.escape(string)}/
end
def def_symbol(method_name, string)
pattern = symbol(string)
define_method(method_name) do
skip(pattern) && string
end
end
def def_literal(method_name, string)
pattern = /#{string}#{LINE_END}/
define_method(method_name) do
skip(pattern) && string
end
end
end
extend ClassMethods
def skip(pattern)
@ss.skip(pattern)
end
def scan(pattern)
@ss.scan(pattern)
end
def getch
@ss.getch
end
def eof?
@ss.eos?
end
def prev_match
@ss[0]
end
def check(pattern)
@ss.check(pattern)
end
def line_end
skip(LINE_END)
end
def spacing
skip(SPACING)
end
def spacing_without_comment
skip(SPACING_WITHOUT_COMMENT)
end
def parse_error!(message)
raise ConfigParseError, "#{message} at #{error_sample}"
end
def error_sample
pos = @ss.pos
lines = @ss.string.lines.to_a
lines.each_with_index { |line, ln|
if line.size >= pos
msgs = ["line #{ln + 1},#{pos}\n"]
if ln > 0
last_line = lines[ln - 1]
msgs << "%3s: %s" % [ln, last_line]
end
msgs << "%3s: %s" % [ln + 1, line]
msgs << "\n #{'-' * pos}^\n"
if next_line = lines[ln + 1]
msgs << "%3s: %s" % [ln + 2, next_line]
end
return msgs.join
end
pos -= line.size
last_line = line
}
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/yaml_parser.rb | lib/fluent/config/yaml_parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config/yaml_parser/loader'
require 'fluent/config/yaml_parser/parser'
require 'pathname'
module Fluent
module Config
module YamlParser
def self.parse(path)
context = Kernel.binding
unless context.respond_to?(:use_nil)
context.define_singleton_method(:use_nil) do
raise Fluent::SetNil
end
end
unless context.respond_to?(:use_default)
context.define_singleton_method(:use_default) do
raise Fluent::SetDefault
end
end
unless context.respond_to?(:hostname)
context.define_singleton_method(:hostname) do
Socket.gethostname
end
end
unless context.respond_to?(:worker_id)
context.define_singleton_method(:worker_id) do
ENV['SERVERENGINE_WORKER_ID'] || ''
end
end
s = Fluent::Config::YamlParser::Loader.new(context).load(Pathname.new(path))
Fluent::Config::YamlParser::Parser.new(s).build.to_element
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/error.rb | lib/fluent/config/error.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
class ConfigError < StandardError
end
class ConfigParseError < ConfigError
end
class ObsoletedParameterError < ConfigError
end
class SetNil < Exception
end
class SetDefault < Exception
end
class NotFoundPluginError < ConfigError
attr_reader :type, :kind
def initialize(msg, type: nil, kind: nil)
@msg = msg
@type = type
@kind = kind
super(msg)
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/yaml_parser/loader.rb | lib/fluent/config/yaml_parser/loader.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'psych'
require 'json'
require 'fluent/config/error'
require 'fluent/config/yaml_parser/fluent_value'
# Based on https://github.com/eagletmt/hako/blob/34cdde06fe8f3aeafd794be830180c3cedfbb4dc/lib/hako/yaml_loader.rb
module Fluent
module Config
module YamlParser
class Loader
INCLUDE_TAG = 'tag:include'.freeze
FLUENT_JSON_TAG = 'tag:fluent/json'.freeze
FLUENT_STR_TAG = 'tag:fluent/s'.freeze
SHOVEL = '<<'.freeze
def initialize(context = Kernel.binding)
@context = context
@current_path = nil
end
# @param [String] path
# @return [Hash]
def load(path)
class_loader = Psych::ClassLoader.new
scanner = Psych::ScalarScanner.new(class_loader)
visitor = Visitor.new(scanner, class_loader)
visitor._register_domain(INCLUDE_TAG) do |_, val|
eval_include(Pathname.new(val), path.parent)
end
visitor._register_domain(FLUENT_JSON_TAG) do |_, val|
Fluent::Config::YamlParser::FluentValue::JsonValue.new(val)
end
visitor._register_domain(FLUENT_STR_TAG) do |_, val|
Fluent::Config::YamlParser::FluentValue::StringValue.new(val, @context)
end
path.open do |f|
visitor.accept(Psych.parse(f))
end
end
def eval_include(path, parent)
if path.relative?
pattern = parent.join(path)
else
pattern = path
end
result = []
Dir.glob(pattern).sort.each do |path|
result.concat(load(Pathname.new(path)))
end
result
rescue SystemCallError => e
parse_error = ConfigParseError.new("include error #{path} - #{e}")
parse_error.set_backtrace(e.backtrace)
raise parse_error
end
class Visitor < Psych::Visitors::ToRuby
def initialize(scanner, class_loader)
super(scanner, class_loader)
end
def _register_domain(name, &block)
@domain_types.merge!({ name => [name, block] })
end
def revive_hash(hash, o)
super(hash, o).tap do |r|
if r[SHOVEL].is_a?(Hash)
h2 = {}
r.each do |k, v|
if k == SHOVEL
h2.merge!(v)
else
h2[k] = v
end
end
r.replace(h2)
end
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/yaml_parser/parser.rb | lib/fluent/config/yaml_parser/parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config/yaml_parser/section_builder'
module Fluent
module Config
module YamlParser
class Parser
def initialize(config, indent: 2)
@base_indent = indent
@config = config
end
def build
s = @config['system'] && system_config_build(@config['system'])
c = @config['config'] && config_build(@config['config'], root: true)
RootBuilder.new(s, c)
end
private
def system_config_build(config)
section_build('system', config)
end
def config_build(config, indent: 0, root: false)
sb = SectionBodyBuilder.new(indent, root: root)
config.each do |c|
if (lc = c.delete('label'))
sb.add_section(label_build(lc, indent: indent))
end
if (sc = c.delete('source'))
sb.add_section(source_build(sc, indent: indent))
end
if (fc = c.delete('filter'))
sb.add_section(filter_build(fc, indent: indent))
end
if (mc = c.delete('match'))
sb.add_section(match_build(mc, indent: indent))
end
if (wc = c.delete('worker'))
sb.add_section(worker_build(wc, indent: indent))
end
included_sections_build(c, sb, indent: indent)
end
sb
end
def label_build(config, indent: 0)
config = config.dup
name = config.delete('$name')
c = config.delete('config')
SectionBuilder.new('label', config_build(c, indent: indent + @base_indent), indent, name)
end
def worker_build(config, indent: 0)
config = config.dup
num = config.delete('$arg')
c = config.delete('config')
SectionBuilder.new('worker', config_build(c, indent: indent + @base_indent), indent, num)
end
def source_build(config, indent: 0)
section_build('source', config, indent: indent)
end
def filter_build(config, indent: 0)
config = config.dup
tag = config.delete('$tag')
if tag.is_a?(Array)
section_build('filter', config, indent: indent, arg: tag&.join(','))
else
section_build('filter', config, indent: indent, arg: tag)
end
end
def match_build(config, indent: 0)
config = config.dup
tag = config.delete('$tag')
if tag.is_a?(Array)
section_build('match', config, indent: indent, arg: tag&.join(','))
else
section_build('match', config, indent: indent, arg: tag)
end
end
def included_sections_build(config, section_builder, indent: 0)
config.each_entry do |e|
k = e.keys.first
cc = e.delete(k)
case k
when 'label'
section_builder.add_section(label_build(cc, indent: indent))
when 'worker'
section_builder.add_section(worker_build(cc, indent: indent))
when 'source'
section_builder.add_section(source_build(cc, indent: indent))
when 'filter'
section_builder.add_section(filter_build(cc, indent: indent))
when 'match'
section_builder.add_section(match_build(cc, indent: indent))
end
end
end
def section_build(name, config, indent: 0, arg: nil)
sb = SectionBodyBuilder.new(indent + @base_indent)
if (v = config.delete('$type'))
sb.add_line('@type', v)
end
if (v = config.delete('$label'))
sb.add_line('@label', v)
end
if (v = config.delete('$id'))
sb.add_line('@id', v)
end
if (v = config.delete('$log_level'))
sb.add_line('@log_level', v)
end
config.each do |key, val|
if val.is_a?(Array)
if section?(val.first)
val.each do |v|
sb.add_section(section_build(key, v, indent: indent + @base_indent))
end
else
sb.add_line(key, val)
end
elsif val.is_a?(Hash)
harg = val.delete('$arg')
if harg.is_a?(Array)
# To prevent to generate invalid configuration for arg.
# "arg" should be String object and concatenated by ","
# when two or more objects are specified there.
sb.add_section(section_build(key, val, indent: indent + @base_indent, arg: harg&.join(',')))
else
sb.add_section(section_build(key, val, indent: indent + @base_indent, arg: harg))
end
else
sb.add_line(key, val)
end
end
SectionBuilder.new(name, sb, indent, arg)
end
def section?(value)
value.is_a?(Array) or value.is_a?(Hash)
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/yaml_parser/fluent_value.rb | lib/fluent/config/yaml_parser/fluent_value.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
module Config
module YamlParser
module FluentValue
JsonValue = Struct.new(:val) do
def to_s
val.to_json
end
def to_element
to_s
end
end
StringValue = Struct.new(:val, :context) do
def to_s
context.instance_eval("\"#{val}\"")
rescue Fluent::SetNil => _
''
rescue Fluent::SetDefault => _
':default'
end
def to_element
to_s
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/config/yaml_parser/section_builder.rb | lib/fluent/config/yaml_parser/section_builder.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
module Config
module YamlParser
SectionBuilder = Struct.new(:name, :body, :indent_size, :arg) do
def to_s
indent = ' ' * indent_size
if arg && !arg.to_s.empty?
"#{indent}<#{name} #{arg}>\n#{body}\n#{indent}</#{name}>"
else
"#{indent}<#{name}>\n#{body}\n#{indent}</#{name}>"
end
end
def to_element
elem = body.to_element
elem.name = name
elem.arg = arg.to_s if arg
elem.v1_config = true
elem
end
end
class RootBuilder
def initialize(system, conf)
@system = system
@conf = conf
end
attr_reader :system, :conf
def to_element
Fluent::Config::Element.new('ROOT', '', {}, [@system, @conf].compact.map(&:to_element).flatten)
end
def to_s
s = StringIO.new(+'')
s.puts(@system.to_s) if @system
s.puts(@conf.to_s) if @conf
s.string
end
end
class SectionBodyBuilder
Row = Struct.new(:key, :value, :indent) do
def to_s
"#{indent}#{key} #{value}"
end
end
def initialize(indent, root: false)
@indent = ' ' * indent
@bodies = []
@root = root
end
def add_line(k, v)
@bodies << Row.new(k, v, @indent)
end
def add_section(section)
@bodies << section
end
def to_element
if @root
return @bodies.map(&:to_element)
end
not_section, section = @bodies.partition { |e| e.is_a?(Row) }
r = {}
not_section.each do |e|
v = e.value
r[e.key] = v.respond_to?(:to_element) ? v.to_element : v
end
if @root
section.map(&:to_element)
else
Fluent::Config::Element.new('', '', r, section.map(&:to_element))
end
end
def to_s
@bodies.map(&:to_s).join("\n")
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/storage.rb | lib/fluent/plugin_helper/storage.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'forwardable'
require 'fluent/plugin'
require 'fluent/plugin/storage'
require 'fluent/plugin_helper/timer'
require 'fluent/config/element'
require 'fluent/configurable'
module Fluent
module PluginHelper
module Storage
include Fluent::PluginHelper::Timer
StorageState = Struct.new(:storage, :running)
def storage_create(usage: '', type: nil, conf: nil, default_type: nil)
if conf && conf.respond_to?(:arg) && !conf.arg.empty?
usage = conf.arg
end
if !usage.empty? && usage !~ /^[a-zA-Z][-_.a-zA-Z0-9]*$/
raise Fluent::ConfigError, "Argument in <storage ARG> uses invalid characters: '#{usage}'"
end
s = @_storages[usage]
if s&.running
return s.storage
elsif s
# storage is already created, but not loaded / started
else # !s
type = if type
type
elsif conf && conf.respond_to?(:[])
raise Fluent::ConfigError, "@type is required in <storage>" unless conf['@type']
conf['@type']
elsif default_type
default_type
else
raise ArgumentError, "BUG: both type and conf are not specified"
end
storage = Plugin.new_storage(type, parent: self)
config = case conf
when Fluent::Config::Element
conf
when Hash
# in code, programmer may use symbols as keys, but Element needs strings
conf = Hash[conf.map{|k,v| [k.to_s, v]}]
Fluent::Config::Element.new('storage', usage, conf, [])
when nil
Fluent::Config::Element.new('storage', usage, {'@type' => type}, [])
else
raise ArgumentError, "BUG: conf must be a Element, Hash (or unspecified), but '#{conf.class}'"
end
storage.configure(config)
if @_storages_started
storage.start
end
s = @_storages[usage] = StorageState.new(wrap_instance(storage), false)
end
s.storage
end
module StorageParams
include Fluent::Configurable
# minimum section definition to instantiate storage plugin instances
config_section :storage, required: false, multi: true, param_name: :storage_configs, init: true do
config_argument :usage, :string, default: ''
config_param :@type, :string, default: Fluent::Plugin::Storage::DEFAULT_TYPE
end
end
def self.included(mod)
mod.include StorageParams
end
attr_reader :_storages # for tests
def initialize
super
@_storages_started = false
@_storages = {} # usage => storage_state
end
def configure(conf)
super
@storage_configs.each do |section|
if !section.usage.empty? && section.usage !~ /^[a-zA-Z][-_.a-zA-Z0-9]*$/
raise Fluent::ConfigError, "Argument in <storage ARG> uses invalid characters: '#{section.usage}'"
end
if @_storages[section.usage]
raise Fluent::ConfigError, "duplicated storages configured: #{section.usage}"
end
storage = Plugin.new_storage(section[:@type], parent: self)
storage.configure(section.corresponding_config_element)
@_storages[section.usage] = StorageState.new(wrap_instance(storage), false)
end
end
def start
super
@_storages_started = true
@_storages.each_pair do |usage, s|
s.storage.start
s.storage.load
if s.storage.autosave && !s.storage.persistent
timer_execute(:storage_autosave, s.storage.autosave_interval, repeat: true) do
begin
s.storage.save
rescue => e
log.error "plugin storage failed to save its data", usage: usage, type: type, error: e
end
end
end
s.running = true
end
end
def storage_operate(method_name, &block)
@_storages.each_pair do |usage, s|
begin
block.call(s) if block_given?
s.storage.__send__(method_name)
rescue => e
log.error "unexpected error while #{method_name}", usage: usage, storage: s.storage, error: e
end
end
end
def stop
super
# timer stops automatically in super
storage_operate(:stop)
end
def before_shutdown
storage_operate(:before_shutdown)
super
end
def shutdown
storage_operate(:shutdown) do |s|
s.storage.save if s.storage.save_at_shutdown
end
super
end
def after_shutdown
storage_operate(:after_shutdown)
super
end
def close
storage_operate(:close){|s| s.running = false }
super
end
def terminate
storage_operate(:terminate)
@_storages = {}
super
end
def wrap_instance(storage)
if storage.persistent && storage.persistent_always?
storage
elsif storage.persistent
PersistentWrapper.new(storage)
elsif !storage.synchronized?
SynchronizeWrapper.new(storage)
else
storage
end
end
class PersistentWrapper
# PersistentWrapper always provides synchronized operations
extend Forwardable
def initialize(storage)
@storage = storage
@monitor = Monitor.new
end
def_delegators :@storage, :autosave_interval, :save_at_shutdown
def_delegators :@storage, :start, :stop, :before_shutdown, :shutdown, :after_shutdown, :close, :terminate
def_delegators :@storage, :started?, :stopped?, :before_shutdown?, :shutdown?, :after_shutdown?, :closed?, :terminated?
def method_missing(name, *args)
@monitor.synchronize{ @storage.__send__(name, *args) }
end
def persistent_always?
true
end
def persistent
true
end
def autosave
false
end
def synchronized?
true
end
def implementation
@storage
end
def load
@monitor.synchronize do
@storage.load
end
end
def save
@monitor.synchronize do
@storage.save
end
end
def get(key)
@monitor.synchronize do
@storage.load
@storage.get(key)
end
end
def fetch(key, defval)
@monitor.synchronize do
@storage.load
@storage.fetch(key, defval)
end
end
def put(key, value)
@monitor.synchronize do
@storage.load
@storage.put(key, value)
@storage.save
value
end
end
def delete(key)
@monitor.synchronize do
@storage.load
val = @storage.delete(key)
@storage.save
val
end
end
def update(key, &block)
@monitor.synchronize do
@storage.load
v = block.call(@storage.get(key))
@storage.put(key, v)
@storage.save
v
end
end
end
class SynchronizeWrapper
extend Forwardable
def initialize(storage)
@storage = storage
@monitor = Monitor.new
end
def_delegators :@storage, :persistent, :autosave, :autosave_interval, :save_at_shutdown
def_delegators :@storage, :persistent_always?
def_delegators :@storage, :start, :stop, :before_shutdown, :shutdown, :after_shutdown, :close, :terminate
def_delegators :@storage, :started?, :stopped?, :before_shutdown?, :shutdown?, :after_shutdown?, :closed?, :terminated?
def method_missing(name, *args)
@monitor.synchronize{ @storage.__send__(name, *args) }
end
def synchronized?
true
end
def implementation
@storage
end
def load
@monitor.synchronize do
@storage.load
end
end
def save
@monitor.synchronize do
@storage.save
end
end
def get(key)
@monitor.synchronize{ @storage.get(key) }
end
def fetch(key, defval)
@monitor.synchronize{ @storage.fetch(key, defval) }
end
def put(key, value)
@monitor.synchronize{ @storage.put(key, value) }
end
def delete(key)
@monitor.synchronize{ @storage.delete(key) }
end
def update(key, &block)
@monitor.synchronize do
v = block.call(@storage.get(key))
@storage.put(key, v)
v
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/event_loop.rb | lib/fluent/plugin_helper/event_loop.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'cool.io'
require 'fluent/plugin_helper/thread'
require 'fluent/clock'
module Fluent
module PluginHelper
module EventLoop
# Currently this plugin helper is only for other helpers, not plugins.
# there's no way to create customized watchers to attach event loops.
include Fluent::PluginHelper::Thread
# stop : [-]
# shutdown : detach all event watchers on event loop
# close : stop event loop
# terminate: initialize internal state
EVENT_LOOP_RUN_DEFAULT_TIMEOUT = 0.5
EVENT_LOOP_SHUTDOWN_TIMEOUT = 5
attr_reader :_event_loop # for tests
def event_loop_attach(watcher)
@_event_loop_mutex.synchronize do
@_event_loop.attach(watcher)
@_event_loop_attached_watchers << watcher
watcher
end
end
def event_loop_detach(watcher)
if watcher.attached?
watcher.detach
end
@_event_loop_mutex.synchronize do
@_event_loop_attached_watchers.delete(watcher)
end
end
def event_loop_wait_until_start
sleep(0.1) until event_loop_running?
end
def event_loop_wait_until_stop
timeout_at = Fluent::Clock.now + EVENT_LOOP_SHUTDOWN_TIMEOUT
sleep(0.1) while event_loop_running? && Fluent::Clock.now < timeout_at
if @_event_loop_running
puts "terminating event_loop forcedly"
caller.each{|bt| puts "\t#{bt}" }
@_event_loop.stop rescue nil
@_event_loop_running = true
end
end
def event_loop_running?
@_event_loop_running
end
def initialize
super
@_event_loop = Coolio::Loop.new
@_event_loop_running = false
@_event_loop_mutex = Mutex.new
# plugin MAY configure loop run timeout in #configure
@_event_loop_run_timeout = EVENT_LOOP_RUN_DEFAULT_TIMEOUT
@_event_loop_attached_watchers = []
end
def start
super
# event loop does not run here, so mutex lock is not required
thread_create :event_loop do
begin
default_watcher = DefaultWatcher.new
event_loop_attach(default_watcher)
@_event_loop_running = true
@_event_loop.run(@_event_loop_run_timeout) # this method blocks
ensure
@_event_loop_running = false
end
end
end
def shutdown
@_event_loop_mutex.synchronize do
@_event_loop_attached_watchers.reverse_each do |w|
if w.attached?
begin
w.detach
rescue => e
log.warn "unexpected error while detaching event loop watcher", error: e
end
end
end
end
super
end
def after_shutdown
timeout_at = Fluent::Clock.now + EVENT_LOOP_SHUTDOWN_TIMEOUT
@_event_loop_mutex.synchronize do
@_event_loop.watchers.reverse_each do |w|
begin
w.detach
rescue => e
log.warn "unexpected error while detaching event loop watcher", error: e
end
end
end
while @_event_loop_running
if Fluent::Clock.now >= timeout_at
log.warn "event loop does NOT exit until hard timeout."
raise "event loop does NOT exit until hard timeout." if @under_plugin_development
break
end
sleep 0.1
end
super
end
def close
if @_event_loop_running
begin
@_event_loop.stop # we cannot check loop is running or not
rescue RuntimeError => e
raise unless e.message == 'loop not running'
end
end
super
end
def terminate
@_event_loop = nil
@_event_loop_running = false
@_event_loop_mutex = nil
@_event_loop_run_timeout = nil
super
end
# watcher to block to run event loop until shutdown
class DefaultWatcher < Coolio::TimerWatcher
def initialize
super(1, true) # interval: 1, repeat: true
end
# do nothing
def on_timer; end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/http_server.rb | lib/fluent/plugin_helper/http_server.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin_helper/thread'
require 'fluent/plugin_helper/server' # For Server::ServerTransportParams
require 'fluent/plugin_helper/http_server/server'
require 'fluent/plugin_helper/http_server/ssl_context_builder'
module Fluent
module PluginHelper
module HttpServer
include Fluent::PluginHelper::Thread
include Fluent::Configurable
# stop : stop http server and mark callback thread as stopped
# shutdown : [-]
# close : correct stopped threads
# terminate: kill thread
def self.included(mod)
mod.include Fluent::PluginHelper::Server::ServerTransportParams
end
def initialize(*)
super
@_http_server = nil
end
def create_http_server(title, addr:, port:, logger:, default_app: nil, proto: nil, tls_opts: nil, &block)
logger.warn('this method is deprecated. Use #http_server_create_http_server instead')
http_server_create_http_server(title, addr: addr, port: port, logger: logger, default_app: default_app, proto: proto, tls_opts: tls_opts, &block)
end
# @param title [Symbol] the thread name. this value should be unique.
# @param addr [String] Listen address
# @param port [String] Listen port
# @param logger [Logger] logger used in this server
# @param default_app [Object] This method must have #call.
# @param proto [Symbol] :tls or :tcp
# @param tls_opts [Hash] options for TLS.
def http_server_create_http_server(title, addr:, port:, logger:, default_app: nil, proto: nil, tls_opts: nil, &block)
unless block_given?
raise ArgumentError, 'BUG: callback not specified'
end
if proto == :tls || (@transport_config && @transport_config.protocol == :tls)
http_server_create_https_server(title, addr: addr, port: port, logger: logger, default_app: default_app, tls_opts: tls_opts, &block)
else
@_http_server = HttpServer::Server.new(addr: addr, port: port, logger: logger, default_app: default_app) do |serv|
yield(serv)
end
_block_until_http_server_start do |notify|
thread_create(title) do
@_http_server.start(notify)
end
end
end
end
# @param title [Symbol] the thread name. this value should be unique.
# @param addr [String] Listen address
# @param port [String] Listen port
# @param logger [Logger] logger used in this server
# @param default_app [Object] This method must have #call.
# @param tls_opts [Hash] options for TLS.
def http_server_create_https_server(title, addr:, port:, logger:, default_app: nil, tls_opts: nil)
topt =
if tls_opts
_http_server_overwrite_config(@transport_config, tls_opts)
else
@transport_config
end
ctx = Fluent::PluginHelper::HttpServer::SSLContextBuilder.new($log).build(topt)
@_http_server = HttpServer::Server.new(addr: addr, port: port, logger: logger, default_app: default_app, tls_context: ctx) do |serv|
yield(serv)
end
_block_until_http_server_start do |notify|
thread_create(title) do
@_http_server.start(notify)
end
end
end
def stop
if @_http_server
@_http_server.stop
end
super
end
private
def _http_server_overwrite_config(config, opts)
conf = config.dup
Fluent::PluginHelper::Server::SERVER_TRANSPORT_PARAMS.map(&:to_s).each do |param|
if opts.key?(param)
conf[param] = opts[param]
end
end
conf
end
# To block until server is ready to listen
def _block_until_http_server_start
que = Queue.new
yield(que)
que.pop
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/extract.rb | lib/fluent/plugin_helper/extract.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/event'
require 'fluent/time'
require 'fluent/configurable'
module Fluent
module PluginHelper
module Extract
def extract_tag_from_record(record)
return nil unless @_extract_enabled
if @_extract_tag_key && record.has_key?(@_extract_tag_key)
v = @_extract_keep_tag_key ? record[@_extract_tag_key] : record.delete(@_extract_tag_key)
return v.to_s
end
nil
end
def extract_time_from_record(record)
return nil unless @_extract_enabled
if @_extract_time_key && record.has_key?(@_extract_time_key)
v = @_extract_keep_time_key ? record[@_extract_time_key] : record.delete(@_extract_time_key)
return @_extract_time_parser.call(v)
end
nil
end
module ExtractParams
include Fluent::Configurable
config_section :extract, required: false, multi: false, param_name: :extract_config do
config_param :tag_key, :string, default: nil
config_param :keep_tag_key, :bool, default: false
config_param :time_key, :string, default: nil
config_param :keep_time_key, :bool, default: false
# To avoid defining :time_type twice
config_param :time_type, :enum, list: [:float, :unixtime, :string], default: :float
Fluent::TimeMixin::TIME_PARAMETERS.each do |name, type, opts|
config_param(name, type, **opts)
end
end
end
def self.included(mod)
mod.include ExtractParams
end
def initialize
super
@_extract_enabled = false
@_extract_tag_key = nil
@_extract_keep_tag_key = nil
@_extract_time_key = nil
@_extract_keep_time_key = nil
@_extract_time_parser = nil
end
def configure(conf)
super
if @extract_config
@_extract_tag_key = @extract_config.tag_key
@_extract_keep_tag_key = @extract_config.keep_tag_key
@_extract_time_key = @extract_config.time_key
if @_extract_time_key
@_extract_keep_time_key = @extract_config.keep_time_key
@_extract_time_parser = case @extract_config.time_type
when :float then Fluent::NumericTimeParser.new(:float)
when :unixtime then Fluent::NumericTimeParser.new(:unixtime)
else
localtime = @extract_config.localtime && !@extract_config.utc
Fluent::TimeParser.new(@extract_config.time_format, localtime, @extract_config.timezone)
end
else
if @extract_config.time_format
log.warn "'time_format' specified without 'time_key', will be ignored"
end
end
@_extract_enabled = @_extract_tag_key || @_extract_time_key
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/thread.rb | lib/fluent/plugin_helper/thread.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/clock'
module Fluent
module PluginHelper
module Thread
THREAD_DEFAULT_WAIT_SECONDS = 1
THREAD_SHUTDOWN_HARD_TIMEOUT_IN_TESTS = 100 # second
# stop : mark callback thread as stopped
# shutdown : [-]
# close : correct stopped threads
# terminate: kill all threads
attr_reader :_threads # for test driver
def thread_current_running?
# checker for code in callback of thread_create
::Thread.current[:_fluentd_plugin_helper_thread_running] || false
end
def thread_wait_until_start
until @_threads_mutex.synchronize{ @_threads.values.reduce(true){|r,t| r && t[:_fluentd_plugin_helper_thread_started] } }
sleep 0.1
end
end
def thread_wait_until_stop
timeout_at = Fluent::Clock.now + THREAD_SHUTDOWN_HARD_TIMEOUT_IN_TESTS
until @_threads_mutex.synchronize{ @_threads.values.reduce(true){|r,t| r && !t[:_fluentd_plugin_helper_thread_running] } }
break if Fluent::Clock.now > timeout_at
sleep 0.1
end
@_threads_mutex.synchronize{ @_threads.values }.each do |t|
if t.alive?
puts "going to kill the thread still running: #{t[:_fluentd_plugin_helper_thread_title]}"
t.kill rescue nil
t[:_fluentd_plugin_helper_thread_running] = false
end
end
end
# Ruby 2.2.3 or earlier (and all 2.1.x) cause bug about Threading ("Stack consistency error")
# by passing splatted argument to `yield`
# https://bugs.ruby-lang.org/issues/11027
# We can enable to pass arguments after expire of Ruby 2.1 (& older 2.2.x)
# def thread_create(title, *args)
# Thread.new(*args) do |*t_args|
# yield *t_args
def thread_create(title)
raise ArgumentError, "BUG: title must be a symbol" unless title.is_a? Symbol
raise ArgumentError, "BUG: callback not specified" unless block_given?
m = Mutex.new
m.lock
thread = ::Thread.new do
m.lock # run thread after that thread is successfully set into @_threads
m.unlock
thread_exit = false
::Thread.current[:_fluentd_plugin_helper_thread_title] = title
::Thread.current[:_fluentd_plugin_helper_thread_started] = true
::Thread.current[:_fluentd_plugin_helper_thread_running] = true
begin
yield
thread_exit = true
rescue Exception => e
log.warn "thread exited by unexpected error", plugin: self.class, title: title, error: e
thread_exit = true
raise
ensure
@_threads_mutex.synchronize do
@_threads.delete(::Thread.current.object_id)
end
::Thread.current[:_fluentd_plugin_helper_thread_running] = false
if ::Thread.current.alive? && !thread_exit
log.warn "thread doesn't exit correctly (killed or other reason)", plugin: self.class, title: title, thread: ::Thread.current, error: $!
end
end
end
thread.abort_on_exception = true
thread.name = title.to_s if thread.respond_to?(:name)
@_threads_mutex.synchronize do
@_threads[thread.object_id] = thread
end
m.unlock
thread
end
def thread_exist?(title)
@_threads.values.count{|thread| title == thread[:_fluentd_plugin_helper_thread_title] } > 0
end
def thread_started?(title)
t = @_threads.values.find{|thread| title == thread[:_fluentd_plugin_helper_thread_title] }
t && t[:_fluentd_plugin_helper_thread_started]
end
def thread_running?(title)
t = @_threads.values.find{|thread| title == thread[:_fluentd_plugin_helper_thread_title] }
t && t[:_fluentd_plugin_helper_thread_running]
end
def initialize
super
@_threads_mutex = Mutex.new
@_threads = {}
@_thread_wait_seconds = THREAD_DEFAULT_WAIT_SECONDS
end
def stop
super
wakeup_threads = []
@_threads_mutex.synchronize do
@_threads.each_value do |thread|
thread[:_fluentd_plugin_helper_thread_running] = false
wakeup_threads << thread if thread.alive? && thread.status == "sleep"
end
end
wakeup_threads.each do |thread|
if thread.alive?
thread.wakeup
end
end
end
def after_shutdown
super
wakeup_threads = []
@_threads_mutex.synchronize do
@_threads.each_value do |thread|
wakeup_threads << thread if thread.alive? && thread.status == "sleep"
end
end
wakeup_threads.each do |thread|
thread.wakeup if thread.alive?
end
end
def close
@_threads_mutex.synchronize{ @_threads.keys }.each do |obj_id|
thread = @_threads[obj_id]
if !thread || thread.join(@_thread_wait_seconds)
@_threads_mutex.synchronize{ @_threads.delete(obj_id) }
end
end
super
end
def terminate
super
@_threads_mutex.synchronize{ @_threads.keys }.each do |obj_id|
thread = @_threads[obj_id]
log.warn "killing existing thread", thread: thread
thread.kill if thread
end
@_threads_mutex.synchronize{ @_threads.keys }.each do |obj_id|
thread = @_threads[obj_id]
thread.join
@_threads_mutex.synchronize{ @_threads.delete(obj_id) }
end
@_thread_wait_seconds = nil
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/socket_option.rb | lib/fluent/plugin_helper/socket_option.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'socket'
require 'fcntl'
# this module is only for Socket/Server plugin helpers
module Fluent
module PluginHelper
module SocketOption
# ref: https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-linger
FORMAT_STRUCT_LINGER_WINDOWS = 'S!S!' # { u_short l_onoff; u_short l_linger; }
FORMAT_STRUCT_LINGER = 'I!I!' # { int l_onoff; int l_linger; }
FORMAT_STRUCT_TIMEVAL = 'L!L!' # { time_t tv_sec; suseconds_t tv_usec; }
def socket_option_validate!(protocol, resolve_name: nil, linger_timeout: nil, recv_timeout: nil, send_timeout: nil, receive_buffer_size: nil, send_keepalive_packet: nil)
unless resolve_name.nil?
if protocol != :tcp && protocol != :udp && protocol != :tls
raise ArgumentError, "BUG: resolve_name in available for tcp/udp/tls"
end
end
if linger_timeout
if protocol != :tcp && protocol != :tls
raise ArgumentError, "BUG: linger_timeout is available for tcp/tls"
end
end
if send_keepalive_packet
if protocol != :tcp && protocol != :tls
raise ArgumentError, "BUG: send_keepalive_packet is available for tcp/tls"
end
end
end
def socket_option_set(sock, resolve_name: nil, nonblock: false, linger_timeout: nil, recv_timeout: nil, send_timeout: nil, receive_buffer_size: nil, send_keepalive_packet: nil)
unless resolve_name.nil?
sock.do_not_reverse_lookup = !resolve_name
end
if nonblock
sock.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK)
end
if Fluent.windows?
# To prevent closing socket forcibly on Windows,
# this options shouldn't be set up when linger_timeout equals to 0 (including nil).
# This unintended behavior always occurs on Windows when linger_timeout.to_i == 0.
# This unintended behavior causes "Errno::ECONNRESET: An existing connection was forcibly
# closed by the remote host." on Windows.
if linger_timeout.to_i > 0
if linger_timeout >= 2**16
log.warn "maximum linger_timeout is 65535(2^16 - 1). Set to 65535 forcibly."
linger_timeout = 2**16 - 1
end
optval = [1, linger_timeout.to_i].pack(FORMAT_STRUCT_LINGER_WINDOWS)
socket_option_set_one(sock, :SO_LINGER, optval)
end
else
if linger_timeout
optval = [1, linger_timeout.to_i].pack(FORMAT_STRUCT_LINGER)
socket_option_set_one(sock, :SO_LINGER, optval)
end
end
if recv_timeout
optval = [recv_timeout.to_i, 0].pack(FORMAT_STRUCT_TIMEVAL)
socket_option_set_one(sock, :SO_RCVTIMEO, optval)
end
if send_timeout
optval = [send_timeout.to_i, 0].pack(FORMAT_STRUCT_TIMEVAL)
socket_option_set_one(sock, :SO_SNDTIMEO, optval)
end
if receive_buffer_size
socket_option_set_one(sock, :SO_RCVBUF, receive_buffer_size.to_i)
end
if send_keepalive_packet
socket_option_set_one(sock, :SO_KEEPALIVE, true)
end
sock
end
def socket_option_set_one(sock, option, value)
sock.setsockopt(::Socket::SOL_SOCKET, option, value)
rescue => e
log.warn "failed to set socket option", sock: sock.class, option: option, value: value, error: e
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/service_discovery.rb | lib/fluent/plugin_helper/service_discovery.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin_helper/timer'
require 'fluent/plugin_helper/service_discovery/manager'
module Fluent
module PluginHelper
module ServiceDiscovery
include Fluent::PluginHelper::Timer
# For the compatibility with older versions without `param_name: :service_discovery_configs`
attr_reader :service_discovery
def self.included(mod)
mod.include ServiceDiscoveryParams
end
def configure(conf)
super
# For the compatibility with older versions without `param_name: :service_discovery_configs`
@service_discovery = @service_discovery_configs
end
def start
unless @discovery_manager
log.warn('There is no discovery_manager. skip start them')
super
return
end
@discovery_manager.start
unless @discovery_manager.static_config?
timer_execute(@_plugin_helper_service_discovery_title, @_plugin_helper_service_discovery_interval) do
@discovery_manager.run_once
end
end
super
end
%i[after_start stop before_shutdown shutdown after_shutdown close terminate].each do |mth|
define_method(mth) do
@discovery_manager&.__send__(mth)
super()
end
end
private
# @param title [Symbol] the thread name. this value should be unique.
# @param static_default_service_directive [String] the directive name of each service when "static" service discovery is enabled in default
# @param load_balancer [Object] object which has two methods #rebalance and #select_service
# @param custom_build_method [Proc]
def service_discovery_configure(title, static_default_service_directive: nil, load_balancer: nil, custom_build_method: nil, interval: 3)
configs = @service_discovery_configs.map(&:corresponding_config_element)
if static_default_service_directive
configs.prepend Fluent::Config::Element.new(
'service_discovery',
'',
{'@type' => 'static'},
@config.elements(name: static_default_service_directive.to_s).map{|e| Fluent::Config::Element.new('service', e.arg, e.dup, e.elements, e.unused) }
)
end
service_discovery_create_manager(title, configurations: configs, load_balancer: load_balancer, custom_build_method: custom_build_method, interval: interval)
end
def service_discovery_select_service(&block)
@discovery_manager.select_service(&block)
end
def service_discovery_services
@discovery_manager.services
end
def service_discovery_rebalance
@discovery_manager.rebalance
end
# @param title [Symbol] the thread name. this value should be unique.
# @param configurations [Hash] hash which must has discovery_service type and its configuration like `{ type: :static, conf: <Fluent::Config::Element> }`
# @param load_balancer [Object] object which has two methods #rebalance and #select_service
# @param custom_build_method [Proc]
def service_discovery_create_manager(title, configurations:, load_balancer: nil, custom_build_method: nil, interval: 3)
@_plugin_helper_service_discovery_title = title
@_plugin_helper_service_discovery_interval = interval
@discovery_manager = Fluent::PluginHelper::ServiceDiscovery::Manager.new(
log: log,
load_balancer: load_balancer,
custom_build_method: custom_build_method,
)
@discovery_manager.configure(configurations, parent: self)
@discovery_manager
end
def discovery_manager
@discovery_manager
end
module ServiceDiscoveryParams
include Fluent::Configurable
config_section :service_discovery, multi: true, param_name: :service_discovery_configs do
config_param :@type, :string
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/socket.rb | lib/fluent/plugin_helper/socket.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'socket'
require 'ipaddr'
require 'openssl'
if Fluent.windows?
require 'certstore'
end
require 'fluent/tls'
require_relative 'socket_option'
module Fluent
module PluginHelper
module Socket
# stop : [-]
# shutdown : [-]
# close : [-]
# terminate: [-]
include Fluent::PluginHelper::SocketOption
attr_reader :_sockets # for tests
# TODO: implement connection pool for specified host
def socket_create(proto, host, port, **kwargs, &block)
case proto
when :tcp
socket_create_tcp(host, port, **kwargs, &block)
when :udp
socket_create_udp(host, port, **kwargs, &block)
when :tls
socket_create_tls(host, port, **kwargs, &block)
when :unix
raise "not implemented yet"
else
raise ArgumentError, "invalid protocol: #{proto}"
end
end
def socket_create_tcp(host, port, resolve_name: false, connect_timeout: nil, **kwargs, &block)
sock = if connect_timeout
s = ::Socket.tcp(host, port, connect_timeout: connect_timeout)
s.autoclose = false # avoid GC triggered close
WrappedSocket::TCP.for_fd(s.fileno)
else
WrappedSocket::TCP.new(host, port)
end
socket_option_set(sock, resolve_name: resolve_name, **kwargs)
if block
begin
block.call(sock)
ensure
sock.close_write rescue nil
sock.close rescue nil
end
else
sock
end
end
def socket_create_udp(host, port, resolve_name: false, connect: false, **kwargs, &block)
family = IPAddr.new(IPSocket.getaddress(host)).ipv4? ? ::Socket::AF_INET : ::Socket::AF_INET6
sock = WrappedSocket::UDP.new(family)
socket_option_set(sock, resolve_name: resolve_name, **kwargs)
sock.connect(host, port) if connect
if block
begin
block.call(sock)
ensure
sock.close rescue nil
end
else
sock
end
end
def socket_create_tls(
host, port,
version: Fluent::TLS::DEFAULT_VERSION, min_version: nil, max_version: nil, ciphers: Fluent::TLS::CIPHERS_DEFAULT, insecure: false, verify_fqdn: true, fqdn: nil,
enable_system_cert_store: true, allow_self_signed_cert: false, cert_paths: nil,
cert_path: nil, private_key_path: nil, private_key_passphrase: nil,
cert_thumbprint: nil, cert_logical_store_name: nil, cert_use_enterprise_store: true,
connect_timeout: nil,
**kwargs, &block)
host_is_ipaddress = IPAddr.new(host) rescue false
fqdn ||= host unless host_is_ipaddress
context = OpenSSL::SSL::SSLContext.new
if insecure
log.trace "setting TLS verify_mode NONE"
context.verify_mode = OpenSSL::SSL::VERIFY_NONE
else
cert_store = OpenSSL::X509::Store.new
if allow_self_signed_cert && OpenSSL::X509.const_defined?('V_FLAG_CHECK_SS_SIGNATURE')
cert_store.flags = OpenSSL::X509::V_FLAG_CHECK_SS_SIGNATURE
end
begin
if enable_system_cert_store
if Fluent.windows? && cert_logical_store_name
log.trace "loading Windows system certificate store"
loader = Certstore::OpenSSL::Loader.new(log, cert_store, cert_logical_store_name,
enterprise: cert_use_enterprise_store)
loader.load_cert_store
cert_store = loader.cert_store
context.cert = loader.get_certificate(cert_thumbprint) if cert_thumbprint
end
log.trace "loading system default certificate store"
cert_store.set_default_paths
end
rescue OpenSSL::X509::StoreError
log.warn "failed to load system default certificate store", error: e
end
if cert_paths
if cert_paths.respond_to?(:each)
cert_paths.each do |cert_path|
log.trace "adding CA cert", path: cert_path
cert_store.add_file(cert_path)
end
else
cert_path = cert_paths
log.trace "adding CA cert", path: cert_path
cert_store.add_file(cert_path)
end
end
log.trace "setting TLS context", mode: "peer", ciphers: ciphers
context.set_params({})
context.ciphers = ciphers
context.verify_mode = OpenSSL::SSL::VERIFY_PEER
context.cert_store = cert_store
context.verify_hostname = verify_fqdn && fqdn
context.key = OpenSSL::PKey::read(File.read(private_key_path), private_key_passphrase) if private_key_path
if cert_path
certs = socket_certificates_from_file(cert_path)
context.cert = certs.shift
unless certs.empty?
context.extra_chain_cert = certs
end
end
end
Fluent::TLS.set_version_to_context(context, version, min_version, max_version)
tcpsock = socket_create_tcp(host, port, connect_timeout: connect_timeout, **kwargs)
sock = WrappedSocket::TLS.new(tcpsock, context)
sock.sync_close = true
sock.hostname = fqdn if verify_fqdn && fqdn && sock.respond_to?(:hostname=)
log.trace "entering TLS handshake"
if connect_timeout
begin
Timeout.timeout(connect_timeout) { sock.connect }
rescue Timeout::Error
log.warn "timeout while connecting tls session", host: host
sock.close rescue nil
raise
end
else
sock.connect
end
begin
if verify_fqdn
log.trace "checking peer's certificate", subject: sock.peer_cert.subject
sock.post_connection_check(fqdn)
verify = sock.verify_result
if verify != OpenSSL::X509::V_OK
err_name = Socket.tls_verify_result_name(verify)
log.warn "BUG: failed to verify certification while connecting (but not raised, why?)", host: host, fqdn: fqdn, error: err_name
raise RuntimeError, "BUG: failed to verify certification and to handle it correctly while connecting host #{host} as #{fqdn}"
end
end
rescue OpenSSL::SSL::SSLError => e
log.warn "failed to verify certification while connecting tls session", host: host, fqdn: fqdn, error: e
raise
end
if block
begin
block.call(sock)
ensure
sock.close rescue nil
end
else
sock
end
end
def socket_certificates_from_file(path)
data = File.read(path)
pattern = Regexp.compile('-+BEGIN CERTIFICATE-+\r?\n(?:[^-]*\r?\n)+-+END CERTIFICATE-+\r?\n?', Regexp::MULTILINE)
list = []
data.scan(pattern) { |match| list << OpenSSL::X509::Certificate.new(match) }
if list.length == 0
raise Fluent::ConfigError, "cert_path does not contain a valid certificate"
end
list
end
def self.tls_verify_result_name(code)
case code
when OpenSSL::X509::V_OK then 'V_OK'
when OpenSSL::X509::V_ERR_AKID_SKID_MISMATCH then 'V_ERR_AKID_SKID_MISMATCH'
when OpenSSL::X509::V_ERR_APPLICATION_VERIFICATION then 'V_ERR_APPLICATION_VERIFICATION'
when OpenSSL::X509::V_ERR_CERT_CHAIN_TOO_LONG then 'V_ERR_CERT_CHAIN_TOO_LONG'
when OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED then 'V_ERR_CERT_HAS_EXPIRED'
when OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID then 'V_ERR_CERT_NOT_YET_VALID'
when OpenSSL::X509::V_ERR_CERT_REJECTED then 'V_ERR_CERT_REJECTED'
when OpenSSL::X509::V_ERR_CERT_REVOKED then 'V_ERR_CERT_REVOKED'
when OpenSSL::X509::V_ERR_CERT_SIGNATURE_FAILURE then 'V_ERR_CERT_SIGNATURE_FAILURE'
when OpenSSL::X509::V_ERR_CERT_UNTRUSTED then 'V_ERR_CERT_UNTRUSTED'
when OpenSSL::X509::V_ERR_CRL_HAS_EXPIRED then 'V_ERR_CRL_HAS_EXPIRED'
when OpenSSL::X509::V_ERR_CRL_NOT_YET_VALID then 'V_ERR_CRL_NOT_YET_VALID'
when OpenSSL::X509::V_ERR_CRL_SIGNATURE_FAILURE then 'V_ERR_CRL_SIGNATURE_FAILURE'
when OpenSSL::X509::V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT then 'V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT'
when OpenSSL::X509::V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD then 'V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD'
when OpenSSL::X509::V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD then 'V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD'
when OpenSSL::X509::V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD then 'V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD'
when OpenSSL::X509::V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD then 'V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD'
when OpenSSL::X509::V_ERR_INVALID_CA then 'V_ERR_INVALID_CA'
when OpenSSL::X509::V_ERR_INVALID_PURPOSE then 'V_ERR_INVALID_PURPOSE'
when OpenSSL::X509::V_ERR_KEYUSAGE_NO_CERTSIGN then 'V_ERR_KEYUSAGE_NO_CERTSIGN'
when OpenSSL::X509::V_ERR_OUT_OF_MEM then 'V_ERR_OUT_OF_MEM'
when OpenSSL::X509::V_ERR_PATH_LENGTH_EXCEEDED then 'V_ERR_PATH_LENGTH_EXCEEDED'
when OpenSSL::X509::V_ERR_SELF_SIGNED_CERT_IN_CHAIN then 'V_ERR_SELF_SIGNED_CERT_IN_CHAIN'
when OpenSSL::X509::V_ERR_SUBJECT_ISSUER_MISMATCH then 'V_ERR_SUBJECT_ISSUER_MISMATCH'
when OpenSSL::X509::V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY then 'V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY'
when OpenSSL::X509::V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE then 'V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY'
when OpenSSL::X509::V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE then 'V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE'
when OpenSSL::X509::V_ERR_UNABLE_TO_GET_CRL then 'V_ERR_UNABLE_TO_GET_CRL'
when OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT then 'V_ERR_UNABLE_TO_GET_ISSUER_CERT'
when OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY then 'V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY'
when OpenSSL::X509::V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE then 'V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE'
end
end
# socket_create_socks ?
module WrappedSocket
class TCP < ::TCPSocket
def remote_addr; peeraddr[3]; end
def remote_host; peeraddr[2]; end
def remote_port; peeraddr[1]; end
end
class UDP < ::UDPSocket
def remote_addr; peeraddr[3]; end
def remote_host; peeraddr[2]; end
def remote_port; peeraddr[1]; end
end
class TLS < OpenSSL::SSL::SSLSocket
def remote_addr; peeraddr[3]; end
def remote_host; peeraddr[2]; end
def remote_port; peeraddr[1]; end
end
end
def initialize
super
# @_sockets = [] # for keepalived sockets / connection pool
end
# def close
# @_sockets.each do |sock|
# sock.close
# end
# super
# end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/parser.rb | lib/fluent/plugin_helper/parser.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin'
require 'fluent/plugin/parser'
require 'fluent/config/element'
require 'fluent/configurable'
module Fluent
module PluginHelper
module Parser
def parser_create(usage: '', type: nil, conf: nil, default_type: nil)
parser = @_parsers[usage]
return parser if parser && !type && !conf
type = if type
type
elsif conf && conf.respond_to?(:[])
raise Fluent::ConfigError, "@type is required in <parse>" unless conf['@type']
conf['@type']
elsif default_type
default_type
else
raise ArgumentError, "BUG: both type and conf are not specified"
end
parser = Fluent::Plugin.new_parser(type, parent: self)
config = case conf
when Fluent::Config::Element
conf
when Hash
# in code, programmer may use symbols as keys, but Element needs strings
conf = Hash[conf.map{|k,v| [k.to_s, v]}]
Fluent::Config::Element.new('parse', usage, conf, [])
when nil
Fluent::Config::Element.new('parse', usage, {}, [])
else
raise ArgumentError, "BUG: conf must be a Element, Hash (or unspecified), but '#{conf.class}'"
end
parser.configure(config)
if @_parsers_started
parser.start
end
@_parsers[usage] = parser
parser
end
module ParserParams
include Fluent::Configurable
# minimum section definition to instantiate parser plugin instances
config_section :parse, required: false, multi: true, init: true, param_name: :parser_configs do
config_argument :usage, :string, default: ''
config_param :@type, :string # config_set_default required for :@type
end
end
def self.included(mod)
mod.include ParserParams
end
attr_reader :_parsers # for tests
def initialize
super
@_parsers_started = false
@_parsers = {} # usage => parser
end
def configure(conf)
super
@parser_configs.each do |section|
if @_parsers[section.usage]
raise Fluent::ConfigError, "duplicated parsers configured: #{section.usage}"
end
parser = Plugin.new_parser(section[:@type], parent: self)
parser.configure(section.corresponding_config_element)
@_parsers[section.usage] = parser
end
end
def start
super
@_parsers_started = true
@_parsers.each_pair do |usage, parser|
parser.start
end
end
def parser_operate(method_name, &block)
@_parsers.each_pair do |usage, parser|
begin
parser.__send__(method_name)
block.call(parser) if block_given?
rescue => e
log.error "unexpected error while #{method_name}", usage: usage, parser: parser, error: e
end
end
end
def stop
super
parser_operate(:stop)
end
def before_shutdown
parser_operate(:before_shutdown)
super
end
def shutdown
parser_operate(:shutdown)
super
end
def after_shutdown
parser_operate(:after_shutdown)
super
end
def close
parser_operate(:close)
super
end
def terminate
parser_operate(:terminate)
@_parsers_started = false
@_parsers = {}
super
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/record_accessor.rb | lib/fluent/plugin_helper/record_accessor.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config/error'
module Fluent
module PluginHelper
module RecordAccessor
def record_accessor_create(param)
Accessor.new(param)
end
def record_accessor_nested?(param)
Accessor.parse_parameter(param).is_a?(Array)
end
class Accessor
attr_reader :keys
def initialize(param)
@keys = Accessor.parse_parameter(param)
if @keys.is_a?(Array)
@last_key = @keys.last
@dig_keys = @keys[0..-2]
if @dig_keys.empty?
@keys = @keys.first
else
mcall = method(:call_dig)
mdelete = method(:delete_nest)
mset = method(:set_nest)
singleton_class.module_eval do
define_method(:call, mcall)
define_method(:delete, mdelete)
define_method(:set, mset)
end
end
end
end
def call(r)
r[@keys]
end
# To optimize the performance, use class_eval with pre-expanding @keys
# See https://gist.github.com/repeatedly/ab553ed260cd080bd01ec71da9427312
def call_dig(r)
r.dig(*@keys)
end
def delete(r)
r.delete(@keys)
end
def delete_nest(r)
if target = r.dig(*@dig_keys)
if target.is_a?(Array)
target.delete_at(@last_key)
else
target.delete(@last_key)
end
end
rescue
nil
end
def set(r, v)
r[@keys] = v
end
# set_nest doesn't create intermediate object. If key doesn't exist, no effect.
# See also: https://bugs.ruby-lang.org/issues/11747
def set_nest(r, v)
r.dig(*@dig_keys)&.[]=(@last_key, v)
rescue
nil
end
def self.parse_parameter(param)
if param.start_with?('$.')
parse_dot_notation(param)
elsif param.start_with?('$[')
parse_bracket_notation(param)
else
param
end
end
def self.parse_dot_notation(param)
result = []
keys = param[2..-1].split('.')
keys.each { |key|
if key.include?('[')
result.concat(parse_dot_array_op(key, param))
else
result << key
end
}
raise Fluent::ConfigError, "empty keys in dot notation" if result.empty?
validate_dot_keys(result)
result
end
def self.validate_dot_keys(keys)
keys.each { |key|
next unless key.is_a?(String)
if /\s+/.match?(key)
raise Fluent::ConfigError, "whitespace character is not allowed in dot notation. Use bracket notation: #{key}"
end
}
end
def self.parse_dot_array_op(key, param)
start = key.index('[')
result = if start.zero?
[]
else
[key[0..start - 1]]
end
key = key[start + 1..-1]
in_bracket = true
until key.empty?
if in_bracket
if i = key.index(']')
index_value = key[0..i - 1]
raise Fluent::ConfigError, "missing array index in '[]'. Invalid syntax: #{param}" if index_value == ']'
result << Integer(index_value)
key = key[i + 1..-1]
in_bracket = false
else
raise Fluent::ConfigError, "'[' found but ']' not found. Invalid syntax: #{param}"
end
else
if i = key.index('[')
key = key[i + 1..-1]
in_bracket = true
else
raise Fluent::ConfigError, "found more characters after ']'. Invalid syntax: #{param}"
end
end
end
result
end
def self.parse_bracket_notation(param)
orig_param = param
result = []
param = param[1..-1]
in_bracket = false
until param.empty?
if in_bracket
if param[0] == "'" || param[0] == '"'
if i = param.index("']") || param.index('"]')
raise Fluent::ConfigError, "Mismatched quotes. Invalid syntax: #{orig_param}" unless param[0] == param[i]
result << param[1..i - 1]
param = param[i + 2..-1]
in_bracket = false
else
raise Fluent::ConfigError, "Incomplete bracket. Invalid syntax: #{orig_param}"
end
else
if i = param.index(']')
index_value = param[0..i - 1]
raise Fluent::ConfigError, "missing array index in '[]'. Invalid syntax: #{param}" if index_value == ']'
result << Integer(index_value)
param = param[i + 1..-1]
in_bracket = false
else
raise Fluent::ConfigError, "'[' found but ']' not found. Invalid syntax: #{orig_param}"
end
end
else
if i = param.index('[')
param = param[i + 1..-1]
in_bracket = true
else
raise Fluent::ConfigError, "found more characters after ']'. Invalid syntax: #{orig_param}"
end
end
end
raise Fluent::ConfigError, "empty keys in bracket notation" if result.empty?
result
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/retry_state.rb | lib/fluent/plugin_helper/retry_state.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
module PluginHelper
module RetryState
def retry_state_create(
title, retry_type, wait, timeout,
forever: false, max_steps: nil, backoff_base: 2, max_interval: nil, randomize: true, randomize_width: 0.125,
secondary: false, secondary_threshold: 0.8
)
case retry_type
when :exponential_backoff
ExponentialBackOffRetry.new(title, wait, timeout, forever, max_steps, randomize, randomize_width, backoff_base, max_interval, secondary, secondary_threshold)
when :periodic
PeriodicRetry.new(title, wait, timeout, forever, max_steps, randomize, randomize_width, secondary, secondary_threshold)
else
raise "BUG: unknown retry_type specified: '#{retry_type}'"
end
end
class RetryStateMachine
attr_reader :title, :start, :steps, :next_time, :timeout_at, :current, :secondary_transition_at, :secondary_transition_steps
def initialize(title, wait, timeout, forever, max_steps, randomize, randomize_width, secondary, secondary_threshold)
@title = title
@start = current_time
@steps = 0
@next_time = nil # should be initialized for first retry by child class
@timeout = timeout
@timeout_at = @start + timeout
@has_reached_timeout = false
@has_timed_out = false
@current = :primary
if randomize_width < 0 || randomize_width > 0.5
raise "BUG: randomize_width MUST be between 0 and 0.5"
end
@randomize = randomize
@randomize_width = randomize_width
@forever = forever
@max_steps = max_steps
@secondary = secondary
@secondary_threshold = secondary_threshold
if @secondary
raise "BUG: secondary_transition_threshold MUST be between 0 and 1" if @secondary_threshold <= 0 || @secondary_threshold >= 1
max_retry_timeout = timeout
if max_steps
timeout_by_max_steps = calc_max_retry_timeout(max_steps)
max_retry_timeout = timeout_by_max_steps if timeout_by_max_steps < max_retry_timeout
end
@secondary_transition_at = @start + max_retry_timeout * @secondary_threshold
@secondary_transition_steps = nil
end
end
def current_time
Time.now
end
def randomize(interval)
return interval unless @randomize
interval + (interval * @randomize_width * (2 * rand - 1.0))
end
def calc_next_time
if @forever || !@secondary # primary
naive = naive_next_time(@steps)
if @forever
naive
elsif naive >= @timeout_at
@timeout_at
else
naive
end
elsif @current == :primary && @secondary
naive = naive_next_time(@steps)
if naive >= @secondary_transition_at
@secondary_transition_at
else
naive
end
elsif @current == :secondary
naive = naive_next_time(@steps - @secondary_transition_steps)
if naive >= @timeout_at
@timeout_at
else
naive
end
else
raise "BUG: it's out of design"
end
end
def naive_next_time(retry_times)
raise NotImplementedError
end
def secondary?
!@forever && @secondary && (@current == :secondary || current_time >= @secondary_transition_at)
end
def step
@steps += 1
if !@forever && @secondary && @current != :secondary && current_time >= @secondary_transition_at
@current = :secondary
@secondary_transition_steps = @steps
end
@next_time = calc_next_time
if @has_reached_timeout
@has_timed_out = @next_time >= @timeout_at
else
@has_reached_timeout = @next_time >= @timeout_at
end
nil
end
def recalc_next_time
@next_time = calc_next_time
end
def limit?
if @forever
false
else
@has_timed_out || !!(@max_steps && @steps >= @max_steps)
end
end
end
class ExponentialBackOffRetry < RetryStateMachine
def initialize(title, wait, timeout, forever, max_steps, randomize, randomize_width, backoff_base, max_interval, secondary, secondary_threshold)
@constant_factor = wait
@backoff_base = backoff_base
@max_interval = max_interval
super(title, wait, timeout, forever, max_steps, randomize, randomize_width, secondary, secondary_threshold)
@next_time = @start + @constant_factor
end
def naive_next_time(retry_next_times)
intr = calc_interval(retry_next_times)
current_time + randomize(intr)
end
def calc_max_retry_timeout(max_steps)
result = 0
max_steps.times { |i|
result += calc_interval(i)
}
result
end
def calc_interval(num)
interval = raw_interval(num)
if @max_interval && interval > @max_interval
@max_interval
else
if interval.finite?
interval
else
# Calculate previous finite value to avoid inf related errors. If this re-computing is heavy, use cache.
until interval.finite?
num -= 1
interval = raw_interval(num)
end
interval
end
end
end
def raw_interval(num)
@constant_factor.to_f * (@backoff_base ** (num))
end
end
class PeriodicRetry < RetryStateMachine
def initialize(title, wait, timeout, forever, max_steps, randomize, randomize_width, secondary, secondary_threshold)
@retry_wait = wait
super(title, wait, timeout, forever, max_steps, randomize, randomize_width, secondary, secondary_threshold)
@next_time = @start + @retry_wait
end
def naive_next_time(retry_next_times)
current_time + randomize(@retry_wait)
end
def calc_max_retry_timeout(max_steps)
@retry_wait * max_steps
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/compat_parameters.rb | lib/fluent/plugin_helper/compat_parameters.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/config/types'
require 'fluent/config/element'
module Fluent
module PluginHelper
module CompatParameters
# This plugin helper is to bring old-fashioned buffer/other
# configuration parameters to v0.14 plugin API configurations.
# This helper is mainly to convert plugins from v0.12 API
# to v0.14 API safely, without breaking user deployment.
BUFFER_PARAMS = {
"buffer_type" => "@type",
"buffer_path" => "path",
"num_threads" => "flush_thread_count",
"flush_interval" => "flush_interval",
"try_flush_interval" => "flush_thread_interval",
"queued_chunk_flush_interval" => "flush_thread_burst_interval",
"disable_retry_limit" => "retry_forever",
"retry_limit" => "retry_max_times",
"max_retry_wait" => "retry_max_interval",
"buffer_chunk_limit" => "chunk_limit_size",
"buffer_queue_limit" => "queue_limit_length",
"buffer_queue_full_action" => "overflow_action",
"flush_at_shutdown" => "flush_at_shutdown",
}
BUFFER_TIME_SLICED_PARAMS = {
"time_slice_format" => nil,
"time_slice_wait" => "timekey_wait",
"timezone" => "timekey_zone",
}
PARSER_PARAMS = {
"format" => nil,
"types" => nil,
"types_delimiter" => nil,
"types_label_delimiter" => nil,
"keys" => "keys", # CSVParser, TSVParser (old ValuesParser)
"time_key" => "time_key",
"time_format" => "time_format",
"localtime" => nil,
"utc" => nil,
"delimiter" => "delimiter",
"keep_time_key" => "keep_time_key",
"null_empty_string" => "null_empty_string",
"null_value_pattern" => "null_value_pattern",
"json_parser" => "json_parser", # JSONParser
"label_delimiter" => "label_delimiter", # LabeledTSVParser
"format_firstline" => "format_firstline", # MultilineParser
"message_key" => "message_key", # NoneParser
"with_priority" => "with_priority", # SyslogParser
"message_format" => "message_format", # SyslogParser
"rfc5424_time_format" => "rfc5424_time_format", # SyslogParser
# There has been no parsers which can handle timezone in v0.12
}
INJECT_PARAMS = {
"include_time_key" => nil,
"time_key" => "time_key",
"time_format" => "time_format",
"timezone" => "timezone",
"include_tag_key" => nil,
"tag_key" => "tag_key",
"localtime" => nil,
"utc" => nil,
}
EXTRACT_PARAMS = {
"time_key" => "time_key",
"time_format" => "time_format",
"timezone" => "timezone",
"tag_key" => "tag_key",
"localtime" => nil,
"utc" => nil,
}
FORMATTER_PARAMS = {
"format" => "@type",
"delimiter" => "delimiter",
"force_quotes" => "force_quotes", # CsvFormatter
"keys" => "keys", # TSVFormatter
"fields" => "fields", # CsvFormatter
"json_parser" => "json_parser", # JSONFormatter
"label_delimiter" => "label_delimiter", # LabeledTSVFormatter
"output_time" => "output_time", # OutFileFormatter
"output_tag" => "output_tag", # OutFileFormatter
"localtime" => "localtime", # OutFileFormatter
"utc" => "utc", # OutFileFormatter
"timezone" => "timezone", # OutFileFormatter
"message_key" => "message_key", # SingleValueFormatter
"add_newline" => "add_newline", # SingleValueFormatter
"output_type" => "output_type", # StdoutFormatter
}
def compat_parameters_convert(conf, *types, **kwargs)
types.each do |type|
case type
when :buffer
compat_parameters_buffer(conf, **kwargs)
when :inject
compat_parameters_inject(conf)
when :extract
compat_parameters_extract(conf)
when :parser
compat_parameters_parser(conf)
when :formatter
compat_parameters_formatter(conf)
else
raise "BUG: unknown compat_parameters type: #{type}"
end
end
conf
end
def compat_parameters_buffer(conf, default_chunk_key: '')
# return immediately if <buffer> section exists, or any buffer-related parameters don't exist
return unless conf.elements('buffer').empty?
return if (BUFFER_PARAMS.keys + BUFFER_TIME_SLICED_PARAMS.keys).all?{|k| !conf.has_key?(k) }
# TODO: warn obsolete parameters if these are deprecated
buffer_params = BUFFER_PARAMS.merge(BUFFER_TIME_SLICED_PARAMS)
hash = compat_parameters_copy_to_subsection_attributes(conf, buffer_params) do |compat_key, value|
if compat_key == 'buffer_queue_full_action' && value == 'exception'
'throw_exception'
else
value
end
end
chunk_key = default_chunk_key
if conf.has_key?('time_slice_format')
chunk_key = 'time'
hash['timekey'] = case conf['time_slice_format']
when /\%S/ then 1
when /\%M/ then 60
when /\%H/ then 3600
when /\%d/ then 86400
else
raise Fluent::ConfigError, "time_slice_format only with %Y or %m is too long"
end
if conf.has_key?('localtime') || conf.has_key?('utc')
if conf.has_key?('localtime') && conf.has_key?('utc')
raise Fluent::ConfigError, "both of utc and localtime are specified, use only one of them"
elsif conf.has_key?('localtime')
hash['timekey_use_utc'] = !(Fluent::Config.bool_value(conf['localtime']))
elsif conf.has_key?('utc')
hash['timekey_use_utc'] = Fluent::Config.bool_value(conf['utc'])
end
end
else
if chunk_key == 'time'
hash['timekey'] = 86400 # TimeSliceOutput.time_slice_format default value is '%Y%m%d'
end
end
e = Fluent::Config::Element.new('buffer', chunk_key, hash, [])
conf.elements << e
conf
end
def compat_parameters_inject(conf)
return unless conf.elements('inject').empty?
return if INJECT_PARAMS.keys.all?{|k| !conf.has_key?(k) }
# TODO: warn obsolete parameters if these are deprecated
hash = compat_parameters_copy_to_subsection_attributes(conf, INJECT_PARAMS)
if conf.has_key?('include_time_key') && Fluent::Config.bool_value(conf['include_time_key'])
hash['time_key'] ||= 'time'
hash['time_type'] ||= 'string'
end
if conf.has_key?('time_as_epoch') && Fluent::Config.bool_value(conf['time_as_epoch'])
hash['time_key'] ||= 'time'
hash['time_type'] = 'unixtime'
end
if conf.has_key?('localtime') || conf.has_key?('utc')
utc = to_bool(conf['utc'])
localtime = to_bool(conf['localtime'])
if conf.has_key?('localtime') && conf.has_key?('utc') && !(localtime ^ utc)
raise Fluent::ConfigError, "both of utc and localtime are specified, use only one of them"
elsif conf.has_key?('localtime')
hash['localtime'] = Fluent::Config.bool_value(conf['localtime'])
elsif conf.has_key?('utc')
hash['localtime'] = !(Fluent::Config.bool_value(conf['utc']))
# Specifying "localtime false" means using UTC in TimeFormatter
# And specifying "utc" is different from specifying "timezone +0000"(it's not always UTC).
# There are difference between "Z" and "+0000" in timezone formatting.
# TODO: add kwargs to TimeFormatter to specify "using localtime", "using UTC" or "using specified timezone" in more explicit way
end
end
if conf.has_key?('include_tag_key') && Fluent::Config.bool_value(conf['include_tag_key'])
hash['tag_key'] ||= 'tag'
end
e = Fluent::Config::Element.new('inject', '', hash, [])
conf.elements << e
conf
end
def to_bool(v)
if v.is_a?(FalseClass) || v == 'false' || v.nil?
false
else
true
end
end
def compat_parameters_extract(conf)
return unless conf.elements('extract').empty?
return if EXTRACT_PARAMS.keys.all?{|k| !conf.has_key?(k) } && !conf.has_key?('format')
# TODO: warn obsolete parameters if these are deprecated
hash = compat_parameters_copy_to_subsection_attributes(conf, EXTRACT_PARAMS)
if conf.has_key?('time_as_epoch') && Fluent::Config.bool_value(conf['time_as_epoch'])
hash['time_key'] ||= 'time'
hash['time_type'] = 'unixtime'
elsif conf.has_key?('format') && conf["format"].start_with?("/") && conf["format"].end_with?("/") # old-style regexp parser
hash['time_key'] ||= 'time'
hash['time_type'] ||= 'string'
end
if conf.has_key?('localtime') || conf.has_key?('utc')
if conf.has_key?('localtime') && conf.has_key?('utc')
raise Fluent::ConfigError, "both of utc and localtime are specified, use only one of them"
elsif conf.has_key?('localtime')
hash['localtime'] = Fluent::Config.bool_value(conf['localtime'])
elsif conf.has_key?('utc')
hash['localtime'] = !(Fluent::Config.bool_value(conf['utc']))
# Specifying "localtime false" means using UTC in TimeFormatter
# And specifying "utc" is different from specifying "timezone +0000"(it's not always UTC).
# There are difference between "Z" and "+0000" in timezone formatting.
# TODO: add kwargs to TimeFormatter to specify "using localtime", "using UTC" or "using specified timezone" in more explicit way
end
end
e = Fluent::Config::Element.new('extract', '', hash, [])
conf.elements << e
conf
end
def compat_parameters_parser(conf)
return unless conf.elements('parse').empty?
return if PARSER_PARAMS.keys.all?{|k| !conf.has_key?(k) }
# TODO: warn obsolete parameters if these are deprecated
hash = compat_parameters_copy_to_subsection_attributes(conf, PARSER_PARAMS)
if conf["format"]
if conf["format"].start_with?("/") && conf["format"].end_with?("/")
hash["@type"] = "regexp"
hash["expression"] = conf["format"][1..-2]
else
hash["@type"] = conf["format"]
end
end
if conf["types"]
delimiter = conf["types_delimiter"] || ','
label_delimiter = conf["types_label_delimiter"] || ':'
types = {}
conf['types'].split(delimiter).each do |pair|
key, value = pair.split(label_delimiter, 2)
types[key] = value
end
hash["types"] = JSON.dump(types)
end
if conf.has_key?('localtime') || conf.has_key?('utc')
if conf.has_key?('localtime') && conf.has_key?('utc')
raise Fluent::ConfigError, "both of utc and localtime are specified, use only one of them"
elsif conf.has_key?('localtime')
hash['localtime'] = Fluent::Config.bool_value(conf['localtime'])
elsif conf.has_key?('utc')
hash['localtime'] = !(Fluent::Config.bool_value(conf['utc']))
# Specifying "localtime false" means using UTC in TimeFormatter
# And specifying "utc" is different from specifying "timezone +0000"(it's not always UTC).
# There are difference between "Z" and "+0000" in timezone formatting.
# TODO: add kwargs to TimeFormatter to specify "using localtime", "using UTC" or "using specified timezone" in more explicit way
end
end
e = Fluent::Config::Element.new('parse', '', hash, [])
conf.elements << e
conf
end
def compat_parameters_formatter(conf)
return unless conf.elements('format').empty?
return if FORMATTER_PARAMS.keys.all?{|k| !conf.has_key?(k) }
# TODO: warn obsolete parameters if these are deprecated
hash = compat_parameters_copy_to_subsection_attributes(conf, FORMATTER_PARAMS)
if conf.has_key?('time_as_epoch') && Fluent::Config.bool_value(conf['time_as_epoch'])
hash['time_type'] = 'unixtime'
end
e = Fluent::Config::Element.new('format', '', hash, [])
conf.elements << e
conf
end
def compat_parameters_copy_to_subsection_attributes(conf, params, &block)
hash = {}
params.each do |compat, current|
next unless current
if conf.has_key?(compat)
if block_given?
hash[current] = block.call(compat, conf[compat])
else
hash[current] = conf[compat]
end
end
end
hash
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/counter.rb | lib/fluent/plugin_helper/counter.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin'
require 'fluent/counter/client'
module Fluent
module PluginHelper
module Counter
def counter_client_create(scope:, loop: Coolio::Loop.new)
client_conf = system_config.counter_client
raise Fluent::ConfigError, '<counter_client> is required in <system>' unless client_conf
counter_client = Fluent::Counter::Client.new(loop, port: client_conf.port, host: client_conf.host, log: log, timeout: client_conf.timeout)
counter_client.start
counter_client.establish(scope)
@_counter_client = counter_client
counter_client
end
attr_reader :_counter_client
def initialize
super
@_counter_client = nil
end
def stop
super
@_counter_client.stop
end
def terminate
@_counter_client = nil
super
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/child_process.rb | lib/fluent/plugin_helper/child_process.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin_helper/thread'
require 'fluent/plugin_helper/timer'
require 'fluent/clock'
require 'open3'
require 'timeout'
module Fluent
module PluginHelper
module ChildProcess
include Fluent::PluginHelper::Thread
include Fluent::PluginHelper::Timer
CHILD_PROCESS_LOOP_CHECK_INTERVAL = 0.2 # sec
CHILD_PROCESS_DEFAULT_EXIT_TIMEOUT = 10 # sec
CHILD_PROCESS_DEFAULT_KILL_TIMEOUT = 60 # sec
MODE_PARAMS = [:read, :write, :stderr, :read_with_stderr]
STDERR_OPTIONS = [:discard, :connect]
# stop : mark callback thread as stopped
# shutdown : close write IO to child processes (STDIN of child processes), send TERM (KILL for Windows) to all child processes
# close : send KILL to all child processes
# terminate: [-]
attr_reader :_child_process_processes # for tests
def child_process_running?
# checker for code in callback of child_process_execute
::Thread.current[:_fluentd_plugin_helper_child_process_running] || false
end
def child_process_id
::Thread.current[:_fluentd_plugin_helper_child_process_pid]
end
def child_process_exist?(pid)
pinfo = @_child_process_processes[pid]
return false unless pinfo
return false if pinfo.exit_status
true
end
# on_exit_callback = ->(status){ ... }
# status is an instance of Process::Status
# On Windows, exitstatus=0 and termsig=nil even when child process was killed.
def child_process_execute(
title, command,
arguments: nil, subprocess_name: nil, interval: nil, immediate: false, parallel: false,
mode: [:read, :write], stderr: :discard, env: {}, unsetenv: false, chdir: nil,
internal_encoding: 'utf-8', external_encoding: 'ascii-8bit', scrub: true, replace_string: nil,
wait_timeout: nil, on_exit_callback: nil,
&block
)
raise ArgumentError, "BUG: title must be a symbol" unless title.is_a? Symbol
raise ArgumentError, "BUG: arguments required if subprocess name is replaced" if subprocess_name && !arguments
mode ||= []
mode = [] unless block
raise ArgumentError, "BUG: invalid mode specification" unless mode.all?{|m| MODE_PARAMS.include?(m) }
raise ArgumentError, "BUG: read_with_stderr is exclusive with :read and :stderr" if mode.include?(:read_with_stderr) && (mode.include?(:read) || mode.include?(:stderr))
raise ArgumentError, "BUG: invalid stderr handling specification" unless STDERR_OPTIONS.include?(stderr)
raise ArgumentError, "BUG: number of block arguments are different from size of mode" if block && block.arity != mode.size
running = false
callback = ->(*args) {
running = true
begin
block && block.call(*args)
ensure
running = false
end
}
retval = nil
execute_child_process = ->(){
child_process_execute_once(
title, command, arguments,
subprocess_name, mode, stderr, env, unsetenv, chdir,
internal_encoding, external_encoding, scrub, replace_string,
wait_timeout, on_exit_callback,
&callback
)
}
if immediate || !interval
retval = execute_child_process.call
end
if interval
timer_execute(:child_process_execute, interval, repeat: true) do
if !parallel && running
log.warn "previous child process is still running. skipped.", title: title, command: command, arguments: arguments, interval: interval, parallel: parallel
else
execute_child_process.call
end
end
end
retval # nil if interval
end
def initialize
super
# plugins MAY configure this parameter
@_child_process_exit_timeout = CHILD_PROCESS_DEFAULT_EXIT_TIMEOUT
@_child_process_kill_timeout = CHILD_PROCESS_DEFAULT_KILL_TIMEOUT
@_child_process_mutex = Mutex.new
@_child_process_processes = {} # pid => ProcessInfo
end
def stop
@_child_process_mutex.synchronize{ @_child_process_processes.keys }.each do |pid|
process_info = @_child_process_processes[pid]
if process_info
process_info.thread[:_fluentd_plugin_helper_child_process_running] = false
end
end
super
end
def shutdown
@_child_process_mutex.synchronize{ @_child_process_processes.keys }.each do |pid|
process_info = @_child_process_processes[pid]
next if !process_info
process_info.writeio&.close rescue nil
end
super
@_child_process_mutex.synchronize{ @_child_process_processes.keys }.each do |pid|
process_info = @_child_process_processes[pid]
next if !process_info
child_process_kill(process_info)
end
exit_wait_timeout = Fluent::Clock.now + @_child_process_exit_timeout
while Fluent::Clock.now < exit_wait_timeout
process_exists = false
@_child_process_mutex.synchronize{ @_child_process_processes.keys }.each do |pid|
unless @_child_process_processes[pid].exit_status
process_exists = true
break
end
end
if process_exists
sleep CHILD_PROCESS_LOOP_CHECK_INTERVAL
else
break
end
end
end
def close
while true
pids = @_child_process_mutex.synchronize{ @_child_process_processes.keys }
break if pids.size < 1
living_process_exist = false
pids.each do |pid|
process_info = @_child_process_processes[pid]
next if !process_info || process_info.exit_status
living_process_exist = true
process_info.killed_at ||= Fluent::Clock.now # for irregular case (e.g., created after shutdown)
timeout_at = process_info.killed_at + @_child_process_kill_timeout
now = Fluent::Clock.now
next if now < timeout_at
child_process_kill(process_info, force: true)
end
break if living_process_exist
sleep CHILD_PROCESS_LOOP_CHECK_INTERVAL
end
super
end
def terminate
@_child_process_processes = {}
super
end
def child_process_kill(pinfo, force: false)
return if !pinfo
pinfo.killed_at = Fluent::Clock.now unless force
pid = pinfo.pid
begin
if !pinfo.exit_status && child_process_exist?(pid)
signal = (Fluent.windows? || force) ? :KILL : :TERM
Process.kill(signal, pinfo.pid)
end
rescue Errno::ECHILD, Errno::ESRCH
# ignore
end
end
ProcessInfo = Struct.new(
:title,
:thread, :pid,
:readio, :readio_in_use, :writeio, :writeio_in_use, :stderrio, :stderrio_in_use,
:wait_thread, :alive, :killed_at, :exit_status,
:on_exit_callback, :on_exit_callback_mutex,
)
def child_process_execute_once(
title, command, arguments, subprocess_name, mode, stderr, env, unsetenv, chdir,
internal_encoding, external_encoding, scrub, replace_string, wait_timeout, on_exit_callback, &block
)
spawn_args = if arguments || subprocess_name
[ env, (subprocess_name ? [command, subprocess_name] : command), *(arguments || []) ]
else
[ env, command ]
end
spawn_opts = {
unsetenv_others: unsetenv,
}
if chdir
spawn_opts[:chdir] = chdir
end
encoding_options = {}
if scrub
encoding_options[:invalid] = encoding_options[:undef] = :replace
if replace_string
encoding_options[:replace] = replace_string
end
end
log.debug "Executing command", title: title, spawn: spawn_args, mode: mode, stderr: stderr
readio = writeio = stderrio = wait_thread = nil
readio_in_use = writeio_in_use = stderrio_in_use = false
if !mode.include?(:stderr) && !mode.include?(:read_with_stderr)
spawn_opts[:err] = IO::NULL if stderr == :discard
if !mode.include?(:read) && !mode.include?(:read_with_stderr)
spawn_opts[:out] = IO::NULL
end
writeio, readio, wait_thread = *Open3.popen2(*spawn_args, spawn_opts)
elsif mode.include?(:read_with_stderr)
writeio, readio, wait_thread = *Open3.popen2e(*spawn_args, spawn_opts)
else
writeio, readio, stderrio, wait_thread = *Open3.popen3(*spawn_args, spawn_opts)
end
if mode.include?(:write)
writeio.set_encoding(external_encoding, internal_encoding, **encoding_options)
writeio_in_use = true
else
writeio.reopen(IO::NULL) if writeio
end
if mode.include?(:read) || mode.include?(:read_with_stderr)
readio.set_encoding(external_encoding, internal_encoding, **encoding_options)
readio_in_use = true
end
if mode.include?(:stderr)
stderrio.set_encoding(external_encoding, internal_encoding, **encoding_options)
stderrio_in_use = true
else
stderrio.reopen(IO::NULL) if stderrio && stderr == :discard
end
pid = wait_thread.pid # wait_thread => Process::Waiter
io_objects = []
mode.each do |m|
io_obj = case m
when :read then readio
when :write then writeio
when :read_with_stderr then readio
when :stderr then stderrio
else
raise "BUG: invalid mode must be checked before here: '#{m}'"
end
io_objects << io_obj
end
m = Mutex.new
m.lock
thread = thread_create :child_process_callback do
m.lock # run after plugin thread get pid, thread instance and i/o
m.unlock
begin
@_child_process_processes[pid].alive = true
block.call(*io_objects) if block_given?
writeio.close if writeio
rescue EOFError => e
log.debug "Process exit and I/O closed", title: title, pid: pid, command: command, arguments: arguments
rescue IOError => e
if e.message == 'stream closed' || e.message == 'closed stream' # "closed stream" is of ruby 2.1
log.debug "Process I/O stream closed", title: title, pid: pid, command: command, arguments: arguments
else
log.error "Unexpected I/O error for child process", title: title, pid: pid, command: command, arguments: arguments, error: e
end
rescue Errno::EPIPE => e
log.debug "Broken pipe, child process unexpectedly exits", title: title, pid: pid, command: command, arguments: arguments
rescue => e
log.warn "Unexpected error while processing I/O for child process", title: title, pid: pid, command: command, error: e
end
if wait_timeout
if wait_thread.join(wait_timeout) # Thread#join returns nil when limit expires
# wait_thread successfully exits
@_child_process_processes[pid].exit_status = wait_thread.value
else
log.warn "child process timed out", title: title, pid: pid, command: command, arguments: arguments
child_process_kill(@_child_process_processes[pid], force: true)
@_child_process_processes[pid].exit_status = wait_thread.value
end
else
@_child_process_processes[pid].exit_status = wait_thread.value # with join
end
process_info = @_child_process_mutex.synchronize{ @_child_process_processes.delete(pid) }
cb = process_info.on_exit_callback_mutex.synchronize do
cback = process_info.on_exit_callback
process_info.on_exit_callback = nil
cback
end
if cb
cb.call(process_info.exit_status) rescue nil
end
process_info.readio&.close rescue nil
process_info.writeio&.close rescue nil
process_info.stderrio&.close rescue nil
end
thread[:_fluentd_plugin_helper_child_process_running] = true
thread[:_fluentd_plugin_helper_child_process_pid] = pid
pinfo = ProcessInfo.new(
title, thread, pid,
readio, readio_in_use, writeio, writeio_in_use, stderrio, stderrio_in_use,
wait_thread, false, nil, nil, on_exit_callback, Mutex.new
)
@_child_process_mutex.synchronize do
@_child_process_processes[pid] = pinfo
end
m.unlock
pid
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/event_emitter.rb | lib/fluent/plugin_helper/event_emitter.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/time'
module Fluent
module PluginHelper
module EventEmitter
# stop : [-]
# shutdown : disable @router
# close : [-]
# terminate: [-]
def router
@_event_emitter_used_actually = true
return Engine.root_agent.source_only_router if @_event_emitter_force_source_only_router
if @_event_emitter_lazy_init
@router = @primary_instance.router
end
if @router.respond_to?(:caller_plugin_id=)
@router.caller_plugin_id = self.plugin_id
end
@router
end
def router=(r)
# not recommended now...
@router = r
end
def has_router?
true
end
def event_emitter_used_actually?
@_event_emitter_used_actually
end
def event_emitter_apply_source_only
@_event_emitter_force_source_only_router = true
end
def event_emitter_cancel_source_only
@_event_emitter_force_source_only_router = false
end
def event_emitter_router(label_name)
if label_name
if label_name == "@ROOT"
Engine.root_agent.event_router
else
Engine.root_agent.find_label(label_name).event_router
end
elsif self.respond_to?(:as_secondary) && self.as_secondary
if @primary_instance.has_router?
@_event_emitter_lazy_init = true
nil # primary plugin's event router is not initialized yet, here.
else
@primary_instance.context_router
end
else
# `Engine.root_agent.event_router` is for testing
self.context_router || Engine.root_agent.event_router
end
end
def initialize
super
@_event_emitter_used_actually = false
@_event_emitter_lazy_init = false
@_event_emitter_force_source_only_router = false
@router = nil
end
def configure(conf)
require 'fluent/engine'
super
@router = event_emitter_router(conf['@label'])
end
def after_shutdown
@router = nil
super
end
def close # unset router many times to reduce test cost
@router = nil
super
end
def terminate
@router = nil
super
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/server.rb | lib/fluent/plugin_helper/server.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin_helper/event_loop'
require 'serverengine'
require 'cool.io'
require 'socket'
require 'ipaddr'
require 'fcntl'
require 'openssl'
require_relative 'socket_option'
require_relative 'cert_option'
module Fluent
module PluginHelper
module Server
include Fluent::PluginHelper::EventLoop
include Fluent::PluginHelper::SocketOption
include Fluent::PluginHelper::CertOption
# This plugin helper doesn't support these things for now:
# * TCP/TLS keepalive
# * TLS session cache/tickets
# * unix domain sockets
# stop : [-]
# shutdown : detach server event handler from event loop (event_loop)
# close : close listening sockets
# terminate: remote all server instances
attr_reader :_servers # for tests
def server_wait_until_start
# event_loop_wait_until_start works well for this
end
def server_wait_until_stop
sleep 0.1 while @_servers.any?{|si| si.server.attached? }
@_servers.each{|si| si.server.close rescue nil }
end
PROTOCOLS = [:tcp, :udp, :tls, :unix]
CONNECTION_PROTOCOLS = [:tcp, :tls, :unix]
# server_create_connection(:title, @port) do |conn|
# # on connection
# source_addr = conn.remote_host
# source_port = conn.remote_port
# conn.data do |data|
# # on data
# conn.write resp # ...
# conn.close
# end
# end
def server_create_connection(title, port, proto: nil, bind: '0.0.0.0', shared: true, backlog: nil, tls_options: nil, **socket_options, &block)
proto ||= (@transport_config && @transport_config.protocol == :tls) ? :tls : :tcp
raise ArgumentError, "BUG: title must be a symbol" unless title && title.is_a?(Symbol)
raise ArgumentError, "BUG: port must be an integer" unless port && port.is_a?(Integer)
raise ArgumentError, "BUG: invalid protocol name" unless PROTOCOLS.include?(proto)
raise ArgumentError, "BUG: cannot create connection for UDP" unless CONNECTION_PROTOCOLS.include?(proto)
raise ArgumentError, "BUG: tls_options is available only for tls" if tls_options && proto != :tls
raise ArgumentError, "BUG: block not specified which handles connection" unless block_given?
raise ArgumentError, "BUG: block must have just one argument" unless block.arity == 1
if proto == :tcp || proto == :tls
socket_options[:linger_timeout] ||= @transport_config&.linger_timeout || 0
end
socket_options[:receive_buffer_size] ||= @transport_config&.receive_buffer_size
socket_option_validate!(proto, **socket_options)
socket_option_setter = ->(sock){ socket_option_set(sock, **socket_options) }
case proto
when :tcp
server = server_create_for_tcp_connection(shared, bind, port, backlog, socket_option_setter, &block)
when :tls
transport_config = if tls_options
server_create_transport_section_object(tls_options)
elsif @transport_config && @transport_config.protocol == :tls
@transport_config
else
raise ArgumentError, "BUG: TLS transport specified, but certification options are not specified"
end
server = server_create_for_tls_connection(shared, bind, port, transport_config, backlog, socket_option_setter, &block)
when :unix
raise "not implemented yet"
else
raise "unknown protocol #{proto}"
end
server_attach(title, proto, port, bind, shared, server)
end
# server_create(:title, @port) do |data|
# # ...
# end
# server_create(:title, @port) do |data, conn|
# # ...
# end
# server_create(:title, @port, proto: :udp, max_bytes: 2048) do |data, sock|
# sock.remote_host
# sock.remote_port
# # ...
# end
def server_create(title, port, proto: nil, bind: '0.0.0.0', shared: true, socket: nil, backlog: nil, tls_options: nil, max_bytes: nil, flags: 0, **socket_options, &callback)
proto ||= (@transport_config && @transport_config.protocol == :tls) ? :tls : :tcp
raise ArgumentError, "BUG: title must be a symbol" unless title && title.is_a?(Symbol)
raise ArgumentError, "BUG: port must be an integer" unless port && port.is_a?(Integer)
raise ArgumentError, "BUG: invalid protocol name" unless PROTOCOLS.include?(proto)
raise ArgumentError, "BUG: socket option is available only for udp" if socket && proto != :udp
raise ArgumentError, "BUG: tls_options is available only for tls" if tls_options && proto != :tls
raise ArgumentError, "BUG: block not specified which handles received data" unless block_given?
raise ArgumentError, "BUG: block must have 1 or 2 arguments" unless callback.arity == 1 || callback.arity == 2
if proto == :tcp || proto == :tls
socket_options[:linger_timeout] ||= @transport_config&.linger_timeout || 0
end
socket_options[:receive_buffer_size] ||= @transport_config&.receive_buffer_size
unless socket
socket_option_validate!(proto, **socket_options)
socket_option_setter = ->(sock){ socket_option_set(sock, **socket_options) }
end
if proto != :tcp && proto != :tls && proto != :unix # options to listen/accept connections
raise ArgumentError, "BUG: backlog is available for tcp/tls" if backlog
end
if proto != :udp # UDP options
raise ArgumentError, "BUG: max_bytes is available only for udp" if max_bytes
raise ArgumentError, "BUG: flags is available only for udp" if flags != 0
end
case proto
when :tcp
server = server_create_for_tcp_connection(shared, bind, port, backlog, socket_option_setter) do |conn|
conn.data(&callback)
end
when :tls
transport_config = if tls_options
server_create_transport_section_object(tls_options)
elsif @transport_config && @transport_config.protocol == :tls
@transport_config
else
raise ArgumentError, "BUG: TLS transport specified, but certification options are not specified"
end
server = server_create_for_tls_connection(shared, bind, port, transport_config, backlog, socket_option_setter) do |conn|
conn.data(&callback)
end
when :udp
raise ArgumentError, "BUG: max_bytes must be specified for UDP" unless max_bytes
if socket
sock = socket
close_socket = false
else
sock = server_create_udp_socket(shared, bind, port)
socket_option_setter.call(sock)
close_socket = true
end
server = EventHandler::UDPServer.new(sock, max_bytes, flags, close_socket, @log, @under_plugin_development, &callback)
when :unix
raise "not implemented yet"
else
raise "BUG: unknown protocol #{proto}"
end
server_attach(title, proto, port, bind, shared, server)
end
def server_create_tcp(title, port, **kwargs, &callback)
server_create(title, port, proto: :tcp, **kwargs, &callback)
end
def server_create_udp(title, port, **kwargs, &callback)
server_create(title, port, proto: :udp, **kwargs, &callback)
end
def server_create_tls(title, port, **kwargs, &callback)
server_create(title, port, proto: :tls, **kwargs, &callback)
end
def server_create_unix(title, port, **kwargs, &callback)
server_create(title, port, proto: :unix, **kwargs, &callback)
end
ServerInfo = Struct.new(:title, :proto, :port, :bind, :shared, :server)
def server_attach(title, proto, port, bind, shared, server)
@_servers << ServerInfo.new(title, proto, port, bind, shared, server)
event_loop_attach(server)
end
def server_create_for_tcp_connection(shared, bind, port, backlog, socket_option_setter, &block)
sock = server_create_tcp_socket(shared, bind, port)
socket_option_setter.call(sock)
close_callback = ->(conn){ @_server_mutex.synchronize{ @_server_connections.delete(conn) } }
server = Coolio::TCPServer.new(sock, nil, EventHandler::TCPServer, socket_option_setter, close_callback, @log, @under_plugin_development, block) do |conn|
unless conn.closing
@_server_mutex.synchronize do
@_server_connections << conn
end
end
end
server.listen(backlog) if backlog
server
end
def server_create_for_tls_connection(shared, bind, port, conf, backlog, socket_option_setter, &block)
context = cert_option_create_context(conf.version, conf.insecure, conf.ciphers, conf)
sock = server_create_tcp_socket(shared, bind, port)
socket_option_setter.call(sock)
close_callback = ->(conn){ @_server_mutex.synchronize{ @_server_connections.delete(conn) } }
server = Coolio::TCPServer.new(sock, nil, EventHandler::TLSServer, context, socket_option_setter, close_callback, @log, @under_plugin_development, block) do |conn|
unless conn.closing
@_server_mutex.synchronize do
@_server_connections << conn
end
end
end
server.listen(backlog) if backlog
server
end
SERVER_TRANSPORT_PARAMS = [
:protocol, :version, :min_version, :max_version, :ciphers, :insecure,
:ca_path, :cert_path, :private_key_path, :private_key_passphrase, :client_cert_auth,
:ca_cert_path, :ca_private_key_path, :ca_private_key_passphrase,
:cert_verifier, :generate_private_key_length,
:generate_cert_country, :generate_cert_state, :generate_cert_state,
:generate_cert_locality, :generate_cert_common_name,
:generate_cert_expiration, :generate_cert_digest,
:ensure_fips,
]
def server_create_transport_section_object(opts)
transport_section = configured_section_create(:transport)
SERVER_TRANSPORT_PARAMS.each do |param|
if opts.has_key?(param)
transport_section[param] = opts[param]
end
end
transport_section
end
module ServerTransportParams
include Fluent::Configurable
config_section :transport, required: false, multi: false, init: true, param_name: :transport_config do
config_argument :protocol, :enum, list: [:tcp, :tls], default: :tcp
### Socket Params ###
desc "The max size of socket receive buffer. SO_RCVBUF"
config_param :receive_buffer_size, :size, default: nil
# SO_LINGER 0 to send RST rather than FIN to avoid lots of connections sitting in TIME_WAIT at src.
# Set positive value if needing to send FIN on closing on non-Windows.
# (On Windows, Fluentd can send FIN with zero `linger_timeout` since Fluentd doesn't set 0 to SO_LINGER on Windows.
# See `socket_option.rb`.)
# NOTE:
# Socket-options can be specified from each plugin as needed, so most of them is not defined here for now.
# This is because there is no positive reason to do so.
# `linger_timeout` option in particular needs to be defined here
# although it can be specified from each plugin as well.
# This is because this helper fixes the default value to `0` for its own reason
# and it has a critical effect on the behavior.
desc 'The timeout time used to set linger option.'
config_param :linger_timeout, :integer, default: 0
### TLS Params ###
config_param :version, :enum, list: Fluent::TLS::SUPPORTED_VERSIONS, default: Fluent::TLS::DEFAULT_VERSION
config_param :min_version, :enum, list: Fluent::TLS::SUPPORTED_VERSIONS, default: nil
config_param :max_version, :enum, list: Fluent::TLS::SUPPORTED_VERSIONS, default: nil
config_param :ciphers, :string, default: Fluent::TLS::CIPHERS_DEFAULT
config_param :insecure, :bool, default: false
config_param :ensure_fips, :bool, default: false
# Cert signed by public CA
config_param :ca_path, :string, default: nil
config_param :cert_path, :string, default: nil
config_param :private_key_path, :string, default: nil
config_param :private_key_passphrase, :string, default: nil, secret: true
config_param :client_cert_auth, :bool, default: false
# Cert generated and signed by private CA Certificate
config_param :ca_cert_path, :string, default: nil
config_param :ca_private_key_path, :string, default: nil
config_param :ca_private_key_passphrase, :string, default: nil, secret: true
config_param :cert_verifier, :string, default: nil
# Options for generating certs by private CA certs or self-signed
config_param :generate_private_key_length, :integer, default: 2048
config_param :generate_cert_country, :string, default: 'US'
config_param :generate_cert_state, :string, default: 'CA'
config_param :generate_cert_locality, :string, default: 'Mountain View'
config_param :generate_cert_common_name, :string, default: nil
config_param :generate_cert_expiration, :time, default: 10 * 365 * 86400 # 10years later
config_param :generate_cert_digest, :enum, list: [:sha1, :sha256, :sha384, :sha512], default: :sha256
end
end
def self.included(mod)
mod.include ServerTransportParams
end
def initialize
super
@_servers = []
@_server_connections = []
@_server_mutex = Mutex.new
end
def configure(conf)
super
if @transport_config
if @transport_config.protocol == :tls
cert_option_server_validate!(@transport_config)
end
end
end
def stop
@_server_mutex.synchronize do
@_servers.each do |si|
si.server.detach if si.server.attached?
# to refuse more connections: (connected sockets are still alive here)
si.server.close rescue nil
end
end
super
end
def shutdown
# When it invokes conn.cose, it reduces elements in @_server_connections by close_callback,
# and it reduces the number of loops. This prevents the connection closing.
# So, it requires invoking #dup to avoid the problem.
@_server_connections.dup.each do |conn|
conn.close rescue nil
end
super
end
def terminate
@_servers = []
super
end
def server_socket_manager_client
socket_manager_path = ENV['SERVERENGINE_SOCKETMANAGER_PATH']
if Fluent.windows?
socket_manager_path = socket_manager_path.to_i
end
ServerEngine::SocketManager::Client.new(socket_manager_path)
end
def server_create_tcp_socket(shared, bind, port)
sock = if shared
server_socket_manager_client.listen_tcp(bind, port)
else
# TCPServer.new doesn't set IPV6_V6ONLY flag, so use Addrinfo class instead.
# backlog will be set by the caller, we don't need to set backlog here
tsock = Addrinfo.tcp(bind, port).listen
tsock.autoclose = false
TCPServer.for_fd(tsock.fileno)
end
# close-on-exec is set by default in Ruby 2.0 or later (, and it's unavailable on Windows)
sock.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK) # nonblock
sock
end
def server_create_udp_socket(shared, bind, port)
sock = if shared
server_socket_manager_client.listen_udp(bind, port)
else
# UDPSocket.new doesn't set IPV6_V6ONLY flag, so use Addrinfo class instead.
usock = Addrinfo.udp(bind, port).bind
usock.autoclose = false
UDPSocket.for_fd(usock.fileno)
end
# close-on-exec is set by default in Ruby 2.0 or later (, and it's unavailable on Windows)
sock.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK) # nonblock
sock
end
# Use string "?" for port, not integer or nil. "?" is clear than -1 or nil in the log.
PEERADDR_FAILED = ["?", "?", "name resolution failed", "?"]
class CallbackSocket
def initialize(server_type, sock, enabled_events = [], close_socket: true)
@server_type = server_type
@sock = sock
@peeraddr = nil
@enabled_events = enabled_events
@close_socket = close_socket
end
def remote_addr
@peeraddr[3]
end
def remote_host
@peeraddr[2]
end
def remote_port
@peeraddr[1]
end
def send(data, flags = 0)
@sock.send(data, flags)
end
def write(data)
raise "not implemented here"
end
def close_after_write_complete
@sock.close_after_write_complete = true
end
def close
@sock.close if @close_socket
end
def data(&callback)
on(:data, &callback)
end
def on(event, &callback)
raise "BUG: this event is disabled for #{@server_type}: #{event}" unless @enabled_events.include?(event)
case event
when :data
@sock.data(&callback)
when :write_complete
cb = ->(){ callback.call(self) }
@sock.on_write_complete(&cb)
when :close
cb = ->(){ callback.call(self) }
@sock.on_close(&cb)
else
raise "BUG: unknown event: #{event}"
end
end
end
class TCPCallbackSocket < CallbackSocket
ENABLED_EVENTS = [:data, :write_complete, :close]
attr_accessor :buffer
def initialize(sock)
super("tcp", sock, ENABLED_EVENTS)
@peeraddr = (@sock.peeraddr rescue PEERADDR_FAILED)
@buffer = ''
end
def write(data)
@sock.write(data)
end
end
class TLSCallbackSocket < CallbackSocket
ENABLED_EVENTS = [:data, :write_complete, :close]
attr_accessor :buffer
def initialize(sock)
super("tls", sock, ENABLED_EVENTS)
@peeraddr = (@sock.to_io.peeraddr rescue PEERADDR_FAILED)
@buffer = ''
end
def write(data)
@sock.write(data)
end
end
class UDPCallbackSocket < CallbackSocket
ENABLED_EVENTS = []
def initialize(sock, peeraddr, **kwargs)
super("udp", sock, ENABLED_EVENTS, **kwargs)
@peeraddr = peeraddr
end
def remote_addr
@peeraddr[3]
end
def remote_host
@peeraddr[2]
end
def remote_port
@peeraddr[1]
end
def write(data)
@sock.send(data, 0, @peeraddr[3], @peeraddr[1])
end
end
module EventHandler
class UDPServer < Coolio::IO
attr_writer :close_after_write_complete # dummy for consistent method call in callbacks
def initialize(sock, max_bytes, flags, close_socket, log, under_plugin_development, &callback)
raise ArgumentError, "socket must be a UDPSocket: sock = #{sock}" unless sock.is_a?(UDPSocket)
super(sock)
@sock = sock
@max_bytes = max_bytes
@flags = flags
@close_socket = close_socket
@log = log
@under_plugin_development = under_plugin_development
@callback = callback
on_readable_impl = case @callback.arity
when 1 then :on_readable_without_sock
when 2 then :on_readable_with_sock
else
raise "BUG: callback block must have 1 or 2 arguments"
end
self.define_singleton_method(:on_readable, method(on_readable_impl))
end
def on_readable_without_sock
begin
data = @sock.recv(@max_bytes, @flags)
rescue Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINTR, Errno::ECONNRESET, IOError, Errno::EBADF
return
rescue Errno::EMSGSIZE
# Windows ONLY: This happens when the data size is larger than `@max_bytes`.
@log.info "A received data was ignored since it was too large."
return
end
@callback.call(data)
rescue => e
@log.error "unexpected error in processing UDP data", error: e
@log.error_backtrace
raise if @under_plugin_development
end
def on_readable_with_sock
begin
data, addr = @sock.recvfrom(@max_bytes)
rescue Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINTR, Errno::ECONNRESET, IOError, Errno::EBADF
return
rescue Errno::EMSGSIZE
# Windows ONLY: This happens when the data size is larger than `@max_bytes`.
@log.info "A received data was ignored since it was too large."
return
end
@callback.call(data, UDPCallbackSocket.new(@sock, addr, close_socket: @close_socket))
rescue => e
@log.error "unexpected error in processing UDP data", error: e
@log.error_backtrace
raise if @under_plugin_development
end
end
class TCPServer < Coolio::TCPSocket
attr_reader :closing
attr_writer :close_after_write_complete
def initialize(sock, socket_option_setter, close_callback, log, under_plugin_development, connect_callback)
raise ArgumentError, "socket must be a TCPSocket: sock=#{sock}" unless sock.is_a?(TCPSocket)
socket_option_setter.call(sock)
@_handler_socket = sock
super(sock)
@log = log
@under_plugin_development = under_plugin_development
@connect_callback = connect_callback
@data_callback = nil
@close_callback = close_callback
@callback_connection = nil
@close_after_write_complete = false
@closing = false
@mutex = Mutex.new # to serialize #write and #close
end
def to_io
@_handler_socket
end
def data(&callback)
raise "data callback can be registered just once, but registered twice" if self.singleton_methods.include?(:on_read)
@data_callback = callback
on_read_impl = case callback.arity
when 1 then :on_read_without_connection
when 2 then :on_read_with_connection
else
raise "BUG: callback block must have 1 or 2 arguments"
end
self.define_singleton_method(:on_read, method(on_read_impl))
end
def write(data)
@mutex.synchronize do
super
end
end
def on_writable
super
close if @close_after_write_complete
end
def on_connect
@callback_connection = TCPCallbackSocket.new(self)
@connect_callback.call(@callback_connection)
unless @data_callback
raise "connection callback must call #data to set data callback"
end
end
def on_read_without_connection(data)
@data_callback.call(data)
rescue => e
@log.error "unexpected error on reading data", host: @callback_connection.remote_host, port: @callback_connection.remote_port, error: e
@log.error_backtrace
close rescue nil
raise if @under_plugin_development
end
def on_read_with_connection(data)
@data_callback.call(data, @callback_connection)
rescue => e
@log.error "unexpected error on reading data", host: @callback_connection.remote_host, port: @callback_connection.remote_port, error: e
@log.error_backtrace
close rescue nil
raise if @under_plugin_development
end
def close
@mutex.synchronize do
return if @closing
@closing = true
@close_callback.call(self)
super
end
end
end
class TLSServer < Coolio::Socket
attr_reader :closing
attr_writer :close_after_write_complete
# It can't use Coolio::TCPSocket, because Coolio::TCPSocket checks that underlying socket (1st argument of super) is TCPSocket.
def initialize(sock, context, socket_option_setter, close_callback, log, under_plugin_development, connect_callback)
raise ArgumentError, "socket must be a TCPSocket: sock=#{sock}" unless sock.is_a?(TCPSocket)
socket_option_setter.call(sock)
@_handler_socket = OpenSSL::SSL::SSLSocket.new(sock, context)
@_handler_socket.sync_close = true
@_handler_write_buffer = ''.force_encoding('ascii-8bit')
@_handler_accepted = false
super(@_handler_socket)
@log = log
@under_plugin_development = under_plugin_development
@connect_callback = connect_callback
@data_callback = nil
@close_callback = close_callback
@callback_connection = nil
@close_after_write_complete = false
@closing = false
@mutex = Mutex.new # to serialize #write and #close
end
def to_io
@_handler_socket.to_io
end
def data(&callback)
raise "data callback can be registered just once, but registered twice" if self.singleton_methods.include?(:on_read)
@data_callback = callback
on_read_impl = case callback.arity
when 1 then :on_read_without_connection
when 2 then :on_read_with_connection
else
raise "BUG: callback block must have 1 or 2 arguments"
end
self.define_singleton_method(:on_read, method(on_read_impl))
end
def write(data)
@mutex.synchronize do
@_handler_write_buffer << data
schedule_write
data.bytesize
end
end
def try_tls_accept
return true if @_handler_accepted
begin
result = @_handler_socket.accept_nonblock(exception: false) # this method call actually try to do handshake via TLS
if result == :wait_readable || result == :wait_writable
# retry accept_nonblock: there aren't enough data in underlying socket buffer
else
@_handler_accepted = true
@callback_connection = TLSCallbackSocket.new(self)
@connect_callback.call(@callback_connection)
unless @data_callback
raise "connection callback must call #data to set data callback"
end
return true
end
rescue Errno::EPIPE, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::EHOSTUNREACH => e
peeraddr = (@_handler_socket.peeraddr rescue PEERADDR_FAILED)
@log.trace "unexpected error before accepting TLS connection",
addr: peeraddr[3], host: peeraddr[2], port: peeraddr[1], error: e
close rescue nil
rescue OpenSSL::SSL::SSLError => e
peeraddr = (@_handler_socket.peeraddr rescue PEERADDR_FAILED)
# Use same log level as on_readable
@log.warn "unexpected error before accepting TLS connection by OpenSSL",
addr: peeraddr[3], host: peeraddr[2], port: peeraddr[1], error: e
close rescue nil
end
false
end
def on_connect
try_tls_accept
end
def on_readable
if try_tls_accept
super
end
rescue IO::WaitReadable, IO::WaitWritable
# ignore and return with doing nothing
rescue OpenSSL::SSL::SSLError => e
@log.warn "close socket due to unexpected ssl error: #{e}"
close rescue nil
end
def on_writable
begin
@mutex.synchronize do
# Consider write_nonblock with {exception: false} when IO::WaitWritable error happens frequently.
written_bytes = @_handler_socket.write_nonblock(@_handler_write_buffer)
@_handler_write_buffer.slice!(0, written_bytes)
end
# No need to call `super` in a synchronized context because TLSServer doesn't use the inner buffer(::IO::Buffer) of Coolio::IO.
# Instead of using Coolio::IO's inner buffer, TLSServer has own buffer(`@_handler_write_buffer`). See also TLSServer#write.
# Actually, the only reason calling `super` here is call Coolio::IO#disable_write_watcher.
# If `super` is called in a synchronized context, it could cause a mutex recursive locking since Coolio::IO#on_write_complete
# eventually calls TLSServer#close which try to get a lock.
super
close if @close_after_write_complete
rescue IO::WaitWritable, IO::WaitReadable
return
rescue Errno::EINTR
return
rescue SystemCallError, IOError, SocketError
# SystemCallError catches Errno::EPIPE & Errno::ECONNRESET amongst others.
close rescue nil
return
rescue OpenSSL::SSL::SSLError => e
@log.debug "unexpected SSLError while writing data into socket connected via TLS", error: e
end
end
def on_read_without_connection(data)
@data_callback.call(data)
rescue => e
@log.error "unexpected error on reading data", host: @callback_connection.remote_host, port: @callback_connection.remote_port, error: e
@log.error_backtrace
close rescue nil
raise if @under_plugin_development
end
def on_read_with_connection(data)
@data_callback.call(data, @callback_connection)
rescue => e
@log.error "unexpected error on reading data", host: @callback_connection.remote_host, port: @callback_connection.remote_port, error: e
@log.error_backtrace
close rescue nil
raise if @under_plugin_development
end
def close
@mutex.synchronize do
return if @closing
@closing = true
@close_callback.call(self)
super
end
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/formatter.rb | lib/fluent/plugin_helper/formatter.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin'
require 'fluent/plugin/formatter'
require 'fluent/config/element'
require 'fluent/configurable'
module Fluent
module PluginHelper
module Formatter
def formatter_create(usage: '', type: nil, conf: nil, default_type: nil)
formatter = @_formatters[usage]
return formatter if formatter && !type && !conf
type = if type
type
elsif conf && conf.respond_to?(:[])
raise Fluent::ConfigError, "@type is required in <format>" unless conf['@type']
conf['@type']
elsif default_type
default_type
else
raise ArgumentError, "BUG: both type and conf are not specified"
end
formatter = Fluent::Plugin.new_formatter(type, parent: self)
config = case conf
when Fluent::Config::Element
conf
when Hash
# in code, programmer may use symbols as keys, but Element needs strings
conf = Hash[conf.map{|k,v| [k.to_s, v]}]
Fluent::Config::Element.new('format', usage, conf, [])
when nil
Fluent::Config::Element.new('format', usage, {}, [])
else
raise ArgumentError, "BUG: conf must be a Element, Hash (or unspecified), but '#{conf.class}'"
end
formatter.configure(config)
if @_formatters_started
formatter.start
end
@_formatters[usage] = formatter
formatter
end
module FormatterParams
include Fluent::Configurable
# minimum section definition to instantiate formatter plugin instances
config_section :format, required: false, multi: true, init: true, param_name: :formatter_configs do
config_argument :usage, :string, default: ''
config_param :@type, :string # config_set_default required for :@type
end
end
def self.included(mod)
mod.include FormatterParams
end
attr_reader :_formatters # for tests
def initialize
super
@_formatters_started = false
@_formatters = {} # usage => formatter
end
def configure(conf)
super
@formatter_configs.each do |section|
if @_formatters[section.usage]
raise Fluent::ConfigError, "duplicated formatter configured: #{section.usage}"
end
formatter = Plugin.new_formatter(section[:@type], parent: self)
formatter.configure(section.corresponding_config_element)
@_formatters[section.usage] = formatter
end
end
def start
super
@_formatters_started = true
@_formatters.each_pair do |usage, formatter|
formatter.start
end
end
def formatter_operate(method_name, &block)
@_formatters.each_pair do |usage, formatter|
begin
formatter.__send__(method_name)
block.call(formatter) if block_given?
rescue => e
log.error "unexpected error while #{method_name}", usage: usage, formatter: formatter, error: e
end
end
end
def stop
super
formatter_operate(:stop)
end
def before_shutdown
formatter_operate(:before_shutdown)
super
end
def shutdown
formatter_operate(:shutdown)
super
end
def after_shutdown
formatter_operate(:after_shutdown)
super
end
def close
formatter_operate(:close)
super
end
def terminate
formatter_operate(:terminate)
@_formatters_started = false
@_formatters = {}
super
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/timer.rb | lib/fluent/plugin_helper/timer.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin_helper/event_loop'
require 'set'
module Fluent
module PluginHelper
module Timer
include Fluent::PluginHelper::EventLoop
# stop : turn checker into false (callbacks not called anymore)
# shutdown : [-]
# close : [-]
# terminate: [-]
attr_reader :_timers # for tests
# interval: integer/float, repeat: true/false
def timer_execute(title, interval, repeat: true, &block)
raise ArgumentError, "BUG: title must be a symbol" unless title.is_a? Symbol
raise ArgumentError, "BUG: block not specified for callback" unless block_given?
checker = ->(){ @_timer_running }
detacher = ->(watcher){ event_loop_detach(watcher) }
timer = TimerWatcher.new(title, interval, repeat, log, checker, detacher, &block)
@_timers << title
event_loop_attach(timer)
timer
end
def timer_running?
defined?(@_timer_running) && @_timer_running
end
def initialize
super
@_timers ||= Set.new
end
def start
super
@_timer_running = true
end
def stop
super
@_timer_running = false
end
def terminate
super
@_timers = nil
end
class TimerWatcher < Coolio::TimerWatcher
def initialize(title, interval, repeat, log, checker, detacher, &callback)
@title = title
@callback = callback
@repeat = repeat
@log = log
@checker = checker
@detacher = detacher
super(interval, repeat)
end
def on_timer
@callback.call if @checker.call
rescue => e
@log.error "Unexpected error raised. Stopping the timer.", title: @title, error: e
@log.error_backtrace
detach
@log.error "Timer detached.", title: @title
ensure
@detacher.call(self) unless @repeat
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/inject.rb | lib/fluent/plugin_helper/inject.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/event'
require 'fluent/time'
require 'fluent/configurable'
require 'socket'
module Fluent
module PluginHelper
module Inject
def inject_values_to_record(tag, time, record)
return record unless @_inject_enabled
r = record.dup
if @_inject_hostname_key
r[@_inject_hostname_key] = @_inject_hostname
end
if @_inject_worker_id_key
r[@_inject_worker_id_key] = @_inject_worker_id
end
if @_inject_tag_key
r[@_inject_tag_key] = tag
end
if @_inject_time_key
r[@_inject_time_key] = @_inject_time_formatter.call(time)
end
r
end
def inject_values_to_event_stream(tag, es)
return es unless @_inject_enabled
new_es = Fluent::MultiEventStream.new
es.each do |time, record|
r = record.dup
if @_inject_hostname_key
r[@_inject_hostname_key] = @_inject_hostname
end
if @_inject_worker_id_key
r[@_inject_worker_id_key] = @_inject_worker_id
end
if @_inject_tag_key
r[@_inject_tag_key] = tag
end
if @_inject_time_key
r[@_inject_time_key] = @_inject_time_formatter.call(time)
end
new_es.add(time, r)
end
new_es
end
module InjectParams
include Fluent::Configurable
config_section :inject, required: false, multi: false, param_name: :inject_config do
config_param :hostname_key, :string, default: nil
config_param :hostname, :string, default: nil
config_param :worker_id_key, :string, default: nil
config_param :tag_key, :string, default: nil
config_param :time_key, :string, default: nil
# To avoid defining :time_type twice
config_param :time_type, :enum, list: [:float, :unixtime, :unixtime_millis, :unixtime_micros, :unixtime_nanos, :string], default: :float
Fluent::TimeMixin::TIME_PARAMETERS.each do |name, type, opts|
config_param(name, type, **opts)
end
end
end
def self.included(mod)
mod.include InjectParams
end
def initialize
super
@_inject_enabled = false
@_inject_hostname_key = nil
@_inject_hostname = nil
@_inject_worker_id_key = nil
@_inject_worker_id = nil
@_inject_tag_key = nil
@_inject_time_key = nil
@_inject_time_formatter = nil
end
def configure(conf)
super
if @inject_config
@_inject_hostname_key = @inject_config.hostname_key
if @_inject_hostname_key
if self.respond_to?(:buffer_config)
# Output plugin cannot use "hostname"(specified by @hostname_key),
# injected by this plugin helper, in chunk keys.
# This plugin helper works in `#format` (in many cases), but modified record
# don't have any side effect in chunking of output plugin.
if self.buffer_config.chunk_keys.include?(@_inject_hostname_key)
log.error "Use filters to inject hostname to use it in buffer chunking."
raise Fluent::ConfigError, "the key specified by 'hostname_key' in <inject> cannot be used in buffering chunk key."
end
end
@_inject_hostname = @inject_config.hostname
unless @_inject_hostname
@_inject_hostname = ::Socket.gethostname
log.info "using hostname for specified field", host_key: @_inject_hostname_key, host_name: @_inject_hostname
end
end
@_inject_worker_id_key = @inject_config.worker_id_key
if @_inject_worker_id_key
@_inject_worker_id = fluentd_worker_id # get id here, because #with_worker_config method may be used only for #configure in tests
end
@_inject_tag_key = @inject_config.tag_key
@_inject_time_key = @inject_config.time_key
if @_inject_time_key
@_inject_time_formatter = case @inject_config.time_type
when :float then ->(time){ time.to_r.truncate(+6).to_f } # microsecond floating point value
when :unixtime_millis then ->(time) { time.respond_to?(:nsec) ? time.to_i * 1_000 + time.nsec / 1_000_000 : (time * 1_000).floor }
when :unixtime_micros then ->(time) { time.respond_to?(:nsec) ? time.to_i * 1_000_000 + time.nsec / 1_000 : (time * 1_000_000).floor }
when :unixtime_nanos then ->(time) { time.respond_to?(:nsec) ? time.to_i * 1_000_000_000 + time.nsec : (time * 1_000_000_000).floor }
when :unixtime then ->(time){ time.to_i }
else
localtime = @inject_config.localtime && !@inject_config.utc
Fluent::TimeFormatter.new(@inject_config.time_format, localtime, @inject_config.timezone)
end
else
if @inject_config.time_format
log.warn "'time_format' specified without 'time_key', will be ignored"
end
end
@_inject_enabled = @_inject_hostname_key || @_inject_worker_id_key || @_inject_tag_key || @_inject_time_key
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/metrics.rb | lib/fluent/plugin_helper/metrics.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'forwardable'
require 'fluent/plugin'
require 'fluent/plugin/metrics'
require 'fluent/plugin_helper/timer'
require 'fluent/config/element'
require 'fluent/configurable'
require 'fluent/system_config'
module Fluent
module PluginHelper
module Metrics
include Fluent::SystemConfig::Mixin
attr_reader :_metrics # For tests.
def initialize
super
@_metrics_started = false
@_metrics = {} # usage => metrics_state
end
def configure(conf)
super
@plugin_type_or_id = if self.plugin_id_configured?
self.plugin_id
else
if type = (conf["@type"] || conf["type"])
"#{type}.#{self.plugin_id}"
else
"#{self.class.to_s.split("::").last.downcase}.#{self.plugin_id}"
end
end
end
def metrics_create(namespace: "fluentd", subsystem: "metrics", name:, help_text:, labels: {}, prefer_gauge: false)
metrics = if system_config.metrics
Fluent::Plugin.new_metrics(system_config.metrics[:@type], parent: self)
else
Fluent::Plugin.new_metrics(Fluent::Plugin::Metrics::DEFAULT_TYPE, parent: self)
end
config = if system_config.metrics
system_config.metrics.corresponding_config_element
else
Fluent::Config::Element.new('metrics', '', {'@type' => Fluent::Plugin::Metrics::DEFAULT_TYPE}, [])
end
metrics.use_gauge_metric = prefer_gauge
metrics.configure(config)
# For multi workers environment, cmetrics should be distinguish with static labels.
if Fluent::Engine.system_config.workers > 1
labels[:worker_id] = fluentd_worker_id.to_s
end
labels[:plugin] = @plugin_type_or_id
metrics.create(namespace: namespace, subsystem: subsystem, name: name, help_text: help_text, labels: labels)
@_metrics["#{@plugin_type_or_id}_#{namespace}_#{subsystem}_#{name}"] = metrics
# define the getter method for the calling instance.
singleton_class.module_eval do
unless method_defined?(name)
define_method(name) { metrics.get }
end
end
metrics
end
def metrics_operate(method_name, &block)
@_metrics.each_pair do |key, m|
begin
block.call(s) if block_given?
m.__send__(method_name)
rescue => e
log.error "unexpected error while #{method_name}", key: key, metrics: m, error: e
end
end
end
def start
super
metrics_operate(:start)
@_metrics_started = true
end
def stop
super
# timer stops automatically in super
metrics_operate(:stop)
end
def before_shutdown
metrics_operate(:before_shutdown)
super
end
def shutdown
metrics_operate(:shutdown)
super
end
def after_shutdown
metrics_operate(:after_shutdown)
super
end
def close
metrics_operate(:close)
super
end
def terminate
metrics_operate(:terminate)
@_metrics = {}
super
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/cert_option.rb | lib/fluent/plugin_helper/cert_option.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'openssl'
require 'socket'
require 'fluent/tls'
# this module is only for Socket/Server/HttpServer plugin helpers
module Fluent
module PluginHelper
module CertOption
def cert_option_create_context(version, insecure, ciphers, conf)
cert, key, extra = cert_option_server_validate!(conf)
ctx = OpenSSL::SSL::SSLContext.new
# inject OpenSSL::SSL::SSLContext::DEFAULT_PARAMS
# https://bugs.ruby-lang.org/issues/9424
ctx.set_params({}) unless insecure
if conf.client_cert_auth
ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
else
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
if conf.ensure_fips
unless OpenSSL.fips_mode
raise Fluent::ConfigError, "Cannot enable FIPS compliant mode. OpenSSL FIPS configuration is disabled"
end
end
ctx.ca_file = conf.ca_path
ctx.cert = cert
ctx.key = key
if extra && !extra.empty?
ctx.extra_chain_cert = extra
end
if conf.cert_verifier
sandbox = Class.new
ctx.verify_callback = if File.exist?(conf.cert_verifier)
verifier = File.read(conf.cert_verifier)
sandbox.instance_eval(verifier, File.basename(conf.cert_verifier))
else
sandbox.instance_eval(conf.cert_verifier)
end
end
Fluent::TLS.set_version_to_context(ctx, version, conf.min_version, conf.max_version)
ctx.ciphers = ciphers unless insecure
ctx
end
def cert_option_server_validate!(conf)
case
when conf.cert_path
raise Fluent::ConfigError, "private_key_path is required when cert_path is specified" unless conf.private_key_path
log.warn "For security reason, setting private_key_passphrase is recommended when cert_path is specified" unless conf.private_key_passphrase
cert_option_load(conf.cert_path, conf.private_key_path, conf.private_key_passphrase)
when conf.ca_cert_path
raise Fluent::ConfigError, "ca_private_key_path is required when ca_cert_path is specified" unless conf.ca_private_key_path
log.warn "For security reason, setting ca_private_key_passphrase is recommended when ca_cert_path is specified" unless conf.ca_private_key_passphrase
generate_opts = cert_option_cert_generation_opts_from_conf(conf)
cert_option_generate_server_pair_by_ca(
conf.ca_cert_path,
conf.ca_private_key_path,
conf.ca_private_key_passphrase,
generate_opts
)
when conf.insecure
log.warn "insecure TLS communication server is configured (using 'insecure' mode)"
generate_opts = cert_option_cert_generation_opts_from_conf(conf)
cert_option_generate_server_pair_self_signed(generate_opts)
else
raise Fluent::ConfigError, "no valid cert options configured. specify either 'cert_path', 'ca_cert_path' or 'insecure'"
end
end
def cert_option_load(cert_path, private_key_path, private_key_passphrase)
key = OpenSSL::PKey::read(File.read(private_key_path), private_key_passphrase)
certs = cert_option_certificates_from_file(cert_path)
cert = certs.shift
return cert, key, certs
end
def cert_option_cert_generation_opts_from_conf(conf)
{
private_key_length: conf.generate_private_key_length,
country: conf.generate_cert_country,
state: conf.generate_cert_state,
locality: conf.generate_cert_locality,
common_name: conf.generate_cert_common_name || ::Socket.gethostname,
expiration: conf.generate_cert_expiration,
digest: conf.generate_cert_digest,
}
end
def cert_option_generate_pair(opts, issuer = nil)
key = OpenSSL::PKey::RSA.generate(opts[:private_key_length])
subject = OpenSSL::X509::Name.new
subject.add_entry('C', opts[:country])
subject.add_entry('ST', opts[:state])
subject.add_entry('L', opts[:locality])
subject.add_entry('CN', opts[:common_name])
issuer ||= subject
cert = OpenSSL::X509::Certificate.new
cert.not_before = Time.at(0)
cert.not_after = Time.now + opts[:expiration]
cert.public_key = key
cert.version = 2
cert.serial = rand(2**(8*10))
cert.issuer = issuer
cert.subject = subject
return cert, key
end
def cert_option_add_extensions(cert, extensions)
ef = OpenSSL::X509::ExtensionFactory.new
extensions.each do |ext|
oid, value = ext
cert.add_extension ef.create_extension(oid, value)
end
end
def cert_option_generate_ca_pair_self_signed(generate_opts)
cert, key = cert_option_generate_pair(generate_opts)
cert_option_add_extensions(cert, [
['basicConstraints', 'CA:TRUE']
])
cert.sign(key, generate_opts[:digest].to_s)
return cert, key
end
def cert_option_generate_server_pair_by_ca(ca_cert_path, ca_key_path, ca_key_passphrase, generate_opts)
ca_key = OpenSSL::PKey::read(File.read(ca_key_path), ca_key_passphrase)
ca_cert = OpenSSL::X509::Certificate.new(File.read(ca_cert_path))
cert, key = cert_option_generate_pair(generate_opts, ca_cert.subject)
raise "BUG: certificate digest algorithm not set" unless generate_opts[:digest]
cert_option_add_extensions(cert, [
['basicConstraints', 'CA:FALSE'],
['nsCertType', 'server'],
['keyUsage', 'digitalSignature,keyEncipherment'],
['extendedKeyUsage', 'serverAuth']
])
cert.sign(ca_key, generate_opts[:digest].to_s)
return cert, key, nil
end
def cert_option_generate_server_pair_self_signed(generate_opts)
cert, key = cert_option_generate_pair(generate_opts)
raise "BUG: certificate digest algorithm not set" unless generate_opts[:digest]
cert_option_add_extensions(cert, [
['basicConstraints', 'CA:FALSE'],
['nsCertType', 'server']
])
cert.sign(key, generate_opts[:digest].to_s)
return cert, key, nil
end
def cert_option_certificates_from_file(path)
data = File.read(path)
pattern = Regexp.compile('-+BEGIN CERTIFICATE-+\r?\n(?:[^-]*\r?\n)+-+END CERTIFICATE-+\r?\n?', Regexp::MULTILINE)
list = []
data.scan(pattern){|match| list << OpenSSL::X509::Certificate.new(match) }
if list.length == 0
raise Fluent::ConfigError, "cert_path does not contain a valid certificate"
end
list
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/http_server/methods.rb | lib/fluent/plugin_helper/http_server/methods.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
module PluginHelper
module HttpServer
module Methods
GET = 'GET'.freeze
HEAD = 'HEAD'.freeze
POST = 'POST'.freeze
PUT = 'PUT'.freeze
PATCH = 'PATCH'.freeze
DELETE = 'DELETE'.freeze
OPTIONS = 'OPTIONS'.freeze
CONNECT = 'CONNECT'.freeze
TRACE = 'TRACE'.freeze
ALL = [GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS, TRACE].freeze
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/http_server/router.rb | lib/fluent/plugin_helper/http_server/router.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'async/http/protocol'
module Fluent
module PluginHelper
module HttpServer
class Router
class NotFoundApp
def self.call(req)
[404, { 'Content-Type' => 'text/plain' }, "404 Not Found\n"]
end
end
def initialize(default_app = nil)
@router = { get: {}, head: {}, post: {}, put: {}, patch: {}, delete: {}, connect: {}, options: {}, trace: {} }
@default_app = default_app || NotFoundApp
end
# @param method [Symbol]
# @param path [String]
# @param app [Object]
def mount(method, path, app)
if @router[method].include?(path)
raise "#{path} is already mounted"
end
@router[method][path] = app
end
# @param method [Symbol]
# @param path [String]
# @param request [Fluent::PluginHelper::HttpServer::Request]
def route!(method, path, request)
@router.fetch(method).fetch(path, @default_app).call(request)
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/http_server/app.rb | lib/fluent/plugin_helper/http_server/app.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'async/http/protocol'
require 'fluent/plugin_helper/http_server/methods'
require 'fluent/plugin_helper/http_server/request'
module Fluent
module PluginHelper
module HttpServer
class App
def initialize(router, logger)
@logger = logger
@router = router
end
# Required method by async-http
def call(request)
method = request.method
resp =
case method
when HttpServer::Methods::GET
get(request)
when HttpServer::Methods::HEAD
head(request)
when HttpServer::Methods::POST
post(request)
when HttpServer::Methods::PATCH
patch(request)
when HttpServer::Methods::PUT
put(request)
when HttpServer::Methods::DELETE
delete(request)
when HttpServer::Methods::OPTIONS
options(request)
when HttpServer::Methods::CONNECT
connect(request)
when HttpServer::Methods::TRACE
trace(request)
else
raise "Unknown method #{method}"
end
Protocol::HTTP::Response[*resp]
rescue => e
@logger.error(e)
Protocol::HTTP::Response[500, { 'Content-Type' => 'text/plain' }, 'Internal Server Error']
end
HttpServer::Methods::ALL.map { |e| e.downcase.to_sym }.each do |name|
define_method(name) do |request|
req = Request.new(request)
path = req.path
canonical_path =
if path.size >= 2 && !path.end_with?('/')
"#{path}/"
else
path
end
@router.route!(name, canonical_path, req)
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/http_server/server.rb | lib/fluent/plugin_helper/http_server/server.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'async'
require 'async/http'
require 'async/http/endpoint'
require 'fluent/plugin_helper/http_server/app'
require 'fluent/plugin_helper/http_server/router'
require 'fluent/plugin_helper/http_server/methods'
require 'fluent/log/console_adapter'
module Fluent
module PluginHelper
module HttpServer
class Server
# @param logger [Logger]
# @param default_app [Object] This method must have #call.
# @param tls_context [OpenSSL::SSL::SSLContext]
def initialize(addr:, port:, logger:, default_app: nil, tls_context: nil)
@addr = addr
@port = port
@logger = logger
# TODO: support http2
scheme = tls_context ? 'https' : 'http'
@uri = URI("#{scheme}://#{@addr}:#{@port}").to_s
@router = Router.new(default_app)
@server_task = nil
Console.logger = Fluent::Log::ConsoleAdapter.wrap(@logger)
opts = if tls_context
{ ssl_context: tls_context }
else
{}
end
@server = Async::HTTP::Server.new(App.new(@router, @logger), Async::HTTP::Endpoint.parse(@uri, **opts))
if block_given?
yield(self)
end
end
def start(notify = nil)
Console.logger = Fluent::Log::ConsoleAdapter.wrap(@logger)
@logger.debug("Start async HTTP server listening #{@uri}")
Async do |task|
Console.logger = Fluent::Log::ConsoleAdapter.wrap(@logger)
@server_task = task.async do
Console.logger = Fluent::Log::ConsoleAdapter.wrap(@logger)
@server.run
end
if notify
notify.push(:ready)
end
@server_task_queue = ::Thread::Queue.new
@server_task_queue.pop
@server_task&.stop
end
@logger.debug('Finished HTTP server')
end
def stop
@logger.debug('closing HTTP server')
@server_task_queue.push(:stop)
end
HttpServer::Methods::ALL.map { |e| e.downcase.to_sym }.each do |name|
define_method(name) do |path, app = nil, &block|
unless path.end_with?('/')
path += '/'
end
if (block && app) || (!block && !app)
raise 'You must specify either app or block in the same time'
end
@router.mount(name, path, app || block)
end
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/http_server/request.rb | lib/fluent/plugin_helper/http_server/request.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'uri'
require 'async/http/protocol'
require 'fluent/plugin_helper/http_server/methods'
module Fluent
module PluginHelper
module HttpServer
class Request
attr_reader :path, :query_string
def initialize(request)
@request = request
path = request.path
@path, @query_string = path.split('?', 2)
end
def headers
@request.headers
end
def query
if @query_string
hash = Hash.new { |h, k| h[k] = [] }
# For compatibility with CGI.parse
URI.decode_www_form(@query_string).each_with_object(hash) do |(key, value), h|
h[key] << value
end
end
end
def body
@request.body&.read
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/http_server/ssl_context_builder.rb | lib/fluent/plugin_helper/http_server/ssl_context_builder.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin_helper/cert_option'
module Fluent
module PluginHelper
module HttpServer
# In order not to expose CertOption's methods unnecessary
class SSLContextBuilder
include Fluent::PluginHelper::CertOption
def initialize(log)
@log = log
end
# @param config [Fluent::Config::Section] @transport_config
def build(config)
cert_option_create_context(config.version, config.insecure, config.ciphers, config)
end
private
attr_reader :log
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/service_discovery/round_robin_balancer.rb | lib/fluent/plugin_helper/service_discovery/round_robin_balancer.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluent
module PluginHelper
module ServiceDiscovery
class RoundRobinBalancer
def initialize
@services = []
@mutex = Mutex.new
end
def rebalance(services)
@mutex.synchronize do
@services = services
end
end
def select_service
s = @mutex.synchronize do
s = @services.shift
@services.push(s)
s
end
yield(s)
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
fluent/fluentd | https://github.com/fluent/fluentd/blob/088cb0c98b56feeec0e6da70d1314a25ffd19d0a/lib/fluent/plugin_helper/service_discovery/manager.rb | lib/fluent/plugin_helper/service_discovery/manager.rb | #
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'fluent/plugin/service_discovery'
require 'fluent/plugin_helper/service_discovery/round_robin_balancer'
module Fluent
module PluginHelper
module ServiceDiscovery
class Manager
def initialize(log:, load_balancer: nil, custom_build_method: nil)
@log = log
@load_balancer = load_balancer || RoundRobinBalancer.new
@custom_build_method = custom_build_method
@discoveries = []
@services = {}
@queue = Queue.new
@static_config = true
end
def configure(configs, parent: nil)
configs.each do |config|
type, conf = if config.has_key?(:conf) # for compatibility with initial API
[config[:type], config[:conf]]
else
[config['@type'], config]
end
sd = Fluent::Plugin.new_sd(type, parent: parent)
sd.configure(conf)
sd.services.each do |s|
@services[s.discovery_id] = build_service(s)
end
@discoveries << sd
if @static_config && type.to_sym != :static
@static_config = false
end
end
rebalance
end
def static_config?
@static_config
end
def start
@discoveries.each do |d|
d.start(@queue)
end
end
%i[after_start stop before_shutdown shutdown after_shutdown close terminate].each do |mth|
define_method(mth) do
@discoveries.each do |d|
d.__send__(mth)
end
end
end
def run_once
# Don't care race in this loop intentionally
s = @queue.size
if s == 0
return
end
s.times do
msg = @queue.pop
unless msg.is_a?(Fluent::Plugin::ServiceDiscovery::DiscoveryMessage)
@log.warn("BUG: #{msg}")
next
end
begin
handle_message(msg)
rescue => e
@log.error(e)
end
end
rebalance
end
def rebalance
@load_balancer.rebalance(services)
end
def select_service(&block)
@load_balancer.select_service(&block)
end
def services
@services.values
end
private
def handle_message(msg)
service = msg.service
case msg.type
when Fluent::Plugin::ServiceDiscovery::SERVICE_IN
if (n = build_service(service))
@log.info("Service in: name=#{service.name} #{service.host}:#{service.port}")
@services[service.discovery_id] = n
else
raise "failed to build service in name=#{service.name} #{service.host}:#{service.port}"
end
when Fluent::Plugin::ServiceDiscovery::SERVICE_OUT
s = @services.delete(service.discovery_id)
if s
@log.info("Service out: name=#{service.name} #{service.host}:#{service.port}")
else
@log.warn("Not found service: name=#{service.name} #{service.host}:#{service.port}")
end
else
@log.error("BUG: unknow message type: #{msg.type}")
end
end
def build_service(n)
@custom_build_method ? @custom_build_method.call(n) : n
end
end
end
end
end
| ruby | Apache-2.0 | 088cb0c98b56feeec0e6da70d1314a25ffd19d0a | 2026-01-04T15:37:30.958053Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.