Class: Fluent::KafkaOutputBuffered
- Inherits:
-
BufferedOutput
- Object
- BufferedOutput
- Fluent::KafkaOutputBuffered
- Includes:
- Fluent::KafkaPluginUtil::SSLSettings
- Defined in:
- lib/fluent/plugin/out_kafka_buffered.rb
Instance Attribute Summary collapse
-
#field_separator ⇒ Object
Returns the value of attribute field_separator.
-
#output_data_type ⇒ Object
Returns the value of attribute output_data_type.
Instance Method Summary collapse
- #configure(conf) ⇒ Object
- #emit(tag, es, chain) ⇒ Object
- #format_stream(tag, es) ⇒ Object
- #get_producer ⇒ Object
- #get_schema_from_redis_by_name(schema_name) ⇒ Object
- #init_redis ⇒ Object
-
#initialize ⇒ KafkaOutputBuffered
constructor
A new instance of KafkaOutputBuffered.
- #refresh_client(raise_error = true) ⇒ Object
- #set_schema_to_redis(schema_name, schema) ⇒ Object
- #setup_formatter(conf) ⇒ Object
- #shutdown ⇒ Object
- #shutdown_producers ⇒ Object
- #start ⇒ Object
- #write(chunk) ⇒ Object
Methods included from Fluent::KafkaPluginUtil::SSLSettings
Constructor Details
#initialize ⇒ KafkaOutputBuffered
Returns a new instance of KafkaOutputBuffered.
81 82 83 84 85 86 87 88 89 90 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 81 def initialize super require 'kafka' require 'fluent/plugin/kafka_producer_ext' @kafka = nil @producers = {} @producers_mutex = Mutex.new end |
Instance Attribute Details
#field_separator ⇒ Object
Returns the value of attribute field_separator.
75 76 77 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 75 def field_separator @field_separator end |
#output_data_type ⇒ Object
Returns the value of attribute output_data_type.
74 75 76 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 74 def output_data_type @output_data_type end |
Instance Method Details
#configure(conf) ⇒ Object
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 121 def configure(conf) super if @zookeeper require 'zookeeper' else @seed_brokers = @brokers.match(",").nil? ? [@brokers] : @brokers.split(",") log.info "brokers has been set directly: #{@seed_brokers}" end if conf['ack_timeout_ms'] log.warn "'ack_timeout_ms' parameter is deprecated. Use second unit 'ack_timeout' instead" @ack_timeout = conf['ack_timeout_ms'].to_i / 1000 end @f_separator = case @field_separator when /SPACE/i then ' ' when /COMMA/i then ',' when /SOH/i then "\x01" else "\t" end @formatter_proc = setup_formatter(conf) @producer_opts = {max_retries: @max_send_retries, required_acks: @required_acks} @producer_opts[:ack_timeout] = @ack_timeout if @ack_timeout @producer_opts[:compression_codec] = @compression_codec.to_sym if @compression_codec end |
#emit(tag, es, chain) ⇒ Object
161 162 163 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 161 def emit(tag, es, chain) super(tag, es, chain, tag) end |
#format_stream(tag, es) ⇒ Object
165 166 167 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 165 def format_stream(tag, es) es.to_msgpack_stream end |
#get_producer ⇒ Object
178 179 180 181 182 183 184 185 186 187 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 178 def get_producer @producers_mutex.synchronize { producer = @producers[Thread.current.object_id] unless producer producer = @kafka.producer(@producer_opts) @producers[Thread.current.object_id] = producer end producer } end |
#get_schema_from_redis_by_name(schema_name) ⇒ Object
346 347 348 349 350 351 352 353 354 355 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 346 def get_schema_from_redis_by_name schema_name if stored_schema = $redis.get(schema_name) parsed_schema = JSON.parse($redis.get(schema_name)) { 'schema_id' => parsed_schema['schema_id'], 'schema' => Avro::Schema.parse(parsed_schema['schema_json']), 'field_types' => parsed_schema['field_types'] } end end |
#init_redis ⇒ Object
338 339 340 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 338 def init_redis $redis = Redis.new end |
#refresh_client(raise_error = true) ⇒ Object
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 92 def refresh_client(raise_error = true) if @zookeeper @seed_brokers = [] z = Zookeeper.new(@zookeeper) z.get_children(:path => @zookeeper_path)[:children].each do |id| broker = Yajl.load(z.get(:path => @zookeeper_path + "/#{id}")[:data]) @seed_brokers.push("#{broker['host']}:#{broker['port']}") end z.close log.info "brokers has been refreshed via Zookeeper: #{@seed_brokers}" end begin if @seed_brokers.length > 0 logger = @get_kafka_client_log ? log : nil @kafka = Kafka.new(seed_brokers: @seed_brokers, client_id: @client_id, logger: logger, ssl_ca_cert: read_ssl_file(@ssl_ca_cert), ssl_client_cert: read_ssl_file(@ssl_client_cert), ssl_client_cert_key: read_ssl_file(@ssl_client_cert_key)) log.info "initialized kafka producer: #{@client_id}" else log.warn "No brokers found on Zookeeper" end rescue Exception => e if raise_error # During startup, error should be reported to engine and stop its phase for safety. raise e else log.error e end end end |
#set_schema_to_redis(schema_name, schema) ⇒ Object
342 343 344 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 342 def set_schema_to_redis schema_name, schema $redis.set(schema_name, schema.to_json) end |
#setup_formatter(conf) ⇒ Object
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 189 def setup_formatter(conf) if @output_data_type == 'json' require 'yajl' Proc.new { |tag, time, record| Yajl::Encoder.encode(record) } elsif @output_data_type == 'ltsv' require 'ltsv' Proc.new { |tag, time, record| LTSV.dump(record) } elsif @output_data_type == 'msgpack' require 'msgpack' Proc.new { |tag, time, record| record.to_msgpack } elsif @output_data_type == 'avro' require "avro_turf" require 'avro_turf/messaging' require "avro/builder" init_redis Proc.new do |tag, time, record| record = record.select{|key, value| !key.nil? && !key.empty?}.map do |k, v| [ k.tr('[]-', '_').delete('$'), (v.is_a?(Fixnum) || v.is_a?(Float) || v.nil? ? v : v.to_s.force_encoding("UTF-8")) ] end.to_h = Time.new record['enchilada_time_with_format'] = .strftime("%Y-%m-%dT%H:%M:%S.%LZ") @topic_name = schema_name = "#{tag.to_s.tr('.$:', '_')}_#{Digest::MD5.new.hexdigest(record.keys.to_s)[0..5]}" avro = AvroTurf::Messaging.new(registry_url: @schema_registry) unless (stored_schema = get_schema_from_redis_by_name(schema_name)) fields = record.map do |key, value| { 'name' => key, 'type' => ['null', (value.is_a?(Fixnum) ? 'int' : (value.is_a?(Float) ? 'float' : 'string'))] } end field_types = fields.map{|field| [field['name'], (field['type'] - ['null']).first]}.to_h fields << {"name" => "enchilada_timestamp", "type" => "long"} schema_json = { "type": "record", "name": schema_name, "fields": fields }.to_json registry = avro.instance_variable_get('@registry') schema = Avro::Schema.parse(schema_json) schema_id = registry.register("#{schema_name}-value", schema) stored_schema = { 'schema_json' => schema_json, 'schema_id' => schema_id, 'field_types' => field_types, 'schema' => schema } set_schema_to_redis(schema_name, stored_schema) end record['enchilada_timestamp'] = .strftime('%s%3N').to_i record = record.map do |key, val| [key, (stored_schema['field_types'][key] != 'string' || val.nil? ? val : val.to_s)] end.to_h avro.encode(record, stored_schema['schema_id'], schema: stored_schema['schema']) end elsif @output_data_type =~ /^attr:(.*)$/ @custom_attributes = $1.split(',').map(&:strip).reject(&:empty?) @custom_attributes.unshift('time') if @output_include_time @custom_attributes.unshift('tag') if @output_include_tag Proc.new { |tag, time, record| @custom_attributes.map { |attr| record[attr].nil? ? '' : record[attr].to_s }.join(@f_separator) } else @formatter = Fluent::Plugin.new_formatter(@output_data_type) @formatter.configure(conf) @formatter.method(:format) end end |
#shutdown ⇒ Object
155 156 157 158 159 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 155 def shutdown super shutdown_producers @kafka = nil end |
#shutdown_producers ⇒ Object
169 170 171 172 173 174 175 176 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 169 def shutdown_producers @producers_mutex.synchronize { @producers.each { |key, producer| producer.shutdown } @producers = {} } end |
#start ⇒ Object
150 151 152 153 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 150 def start super refresh_client end |
#write(chunk) ⇒ Object
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
# File 'lib/fluent/plugin/out_kafka_buffered.rb', line 269 def write(chunk) tag = chunk.key producer = get_producer records_by_topic = {} bytes_by_topic = {} = 0 = 0 record_buf = nil record_buf_bytes = nil begin chunk.msgpack_each { |time, record| begin if @output_include_time if @time_format record['time'.freeze] = Time.at(time).strftime(@time_format) else record['time'.freeze] = time end end record['tag'] = tag if @output_include_tag record_buf = @formatter_proc.call(tag, time, record) topic = (@exclude_topic_key ? record.delete('topic'.freeze) : record['topic'.freeze]) || @topic_name partition_key = (@exclude_partition_key ? record.delete('partition_key'.freeze) : record['partition_key'.freeze]) || @default_partition_key partition = (@exclude_partition ? record.delete('partition'.freeze) : record['partition'.freeze]) || @default_partition = (@exclude_message_key ? record.delete('message_key'.freeze) : record['message_key'.freeze]) || @default_message_key records_by_topic[topic] ||= 0 bytes_by_topic[topic] ||= 0 record_buf = @formatter_proc.call(tag, time, record) record_buf_bytes = record_buf.bytesize rescue StandardError => e log.warn "unexpected error during format record. Skip broken event:", :error => e.to_s, :error_class => e.class.to_s, :time => time, :record => record next end if ( > 0) and ( + record_buf_bytes > @kafka_agg_max_bytes) log.on_trace { log.trace("#{} messages send.") } producer. = 0 = 0 end log.on_trace { log.trace("message will send to #{topic} with partition_key: #{partition_key}, partition: #{partition}, message_key: #{} and value: #{record_buf}.") } += 1 producer.produce2(record_buf, topic: topic, key: , partition_key: partition_key, partition: partition) += record_buf_bytes records_by_topic[topic] += 1 bytes_by_topic[topic] += record_buf_bytes } if > 0 log.trace { "#{} messages send." } producer. end log.debug { "(records|bytes) (#{records_by_topic}|#{bytes_by_topic})" } end rescue Exception => e log.warn "Send exception occurred: #{e}" log.warn "Exception Backtrace : #{e.backtrace.join("\n")}" # For safety, refresh client and its producers shutdown_producers refresh_client(false) # Raise exception to retry sendind messages raise e end |