Class: Fluent::TreasureDataLogOutput

Inherits:
BufferedOutput
  • Object
show all
Defined in:
lib/fluent/plugin/out_tdlog.rb

Defined Under Namespace

Classes: Anonymizer, IPXORAnonymizer, MD5Anonymizer, RawAnonymizer

Constant Summary collapse

IMPORT_SIZE_LIMIT =
32 * 1024 * 1024

Instance Method Summary collapse

Constructor Details

#initializeTreasureDataLogOutput

Returns a new instance of TreasureDataLogOutput.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/fluent/plugin/out_tdlog.rb', line 77

def initialize
  require 'fileutils'
  require 'tempfile'
  require 'zlib'
  require 'net/http'
  require 'json'
  require 'cgi' # CGI.escape
  require 'time' # Time#rfc2822
  require 'digest/md5'
  require 'stringio'
  super
  @tmpdir = nil
  @apikey = nil
  @key = nil
  @key_num_limit = 512  # TODO: Our one-time import has the restriction about the number of record keys.
  @record_size_limit = 32 * 1024 * 1024  # TODO
  @table_list = {}
  @auto_create_table = true
  @use_ssl = true
  @empty_gz_data = TreasureData::API.create_empty_gz_data
  @user_agent = "fluent-plugin-td: #{TreasureDataPlugin::VERSION}".freeze
end

Instance Method Details

#check_table_exists(key) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/fluent/plugin/out_tdlog.rb', line 312

def check_table_exists(key)
  unless @table_list.has_key?(key)
    database, table = key.split('.', 2)
    log.debug "checking whether table '#{database}.#{table}' exists on Treasure Data"
    io = StringIO.new(@empty_gz_data)
    begin
      @client.import(database, table, "msgpack.gz", io, io.size)
      @table_list[key] = true
    rescue TreasureData::NotFoundError
      raise "Table #{key.inspect} does not exist on Treasure Data. Use 'td table:create #{database} #{table}' to create it."
    rescue => e
      log.warn "failed to check existence of '#{database}.#{table}' table on Treasure Data", :error => e.inspect
      log.debug_backtrace e.backtrace
    end
  end
end

#configure(conf) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/fluent/plugin/out_tdlog.rb', line 100

def configure(conf)
  super

  # overwrite default value of buffer_chunk_limit
  if @buffer.respond_to?(:buffer_chunk_limit=) && !conf['buffer_chunk_limit']
    @buffer.buffer_chunk_limit = IMPORT_SIZE_LIMIT
  end

  if conf.has_key?('tmpdir')
    @tmpdir = conf['tmpdir']
    FileUtils.mkdir_p(@tmpdir)
  end

  @apikey = conf['apikey']
  unless @apikey
    raise ConfigError, "'apikey' parameter is required on tdlog output"
  end

  if auto_create_table = conf['auto_create_table']
    if auto_create_table.empty?
      @auto_create_table = true
    else
      @auto_create_table = Config.bool_value(auto_create_table)
      if @auto_create_table == nil
        raise ConfigError, "'true' or 'false' is required for auto_create_table option on tdlog output"
      end
    end
  end

  if use_ssl = conf['use_ssl']
    if use_ssl.empty?
      @use_ssl = true
    else
      @use_ssl = Config.bool_value(use_ssl)
      if @use_ssl == nil
        raise ConfigError, "'true' or 'false' is required for use_ssl option on tdlog output"
      end
    end
  end

  database = conf['database']
  table = conf['table']
  if database && table
    validate_database_and_table_name(database, table, conf)
    @key = "#{database}.#{table}"
  end

  @anonymizes = {}
  conf.elements.select { |e|
    e.name == 'anonymize'
  }.each { |e|
    key = e['key']
    method = e['method']

    case method
    when 'md5'
      scr = MD5Anonymizer.new
    when 'ip_xor'
      scr = IPXORAnonymizer.new
    else
      raise ConfigError, "Unknown anonymize method: #{method}"
    end

    scr.configure(e)

    @anonymizes[key] = scr
  }
  if @anonymizes.empty?
    @anonymizes = nil
  else
    log.warn "<anonymize> feature is deprecated and will be removed. Use fluent-plugin-anonymizer instead."
  end

  @http_proxy = conf['http_proxy']
end

#emit(tag, es, chain) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/fluent/plugin/out_tdlog.rb', line 195

def emit(tag, es, chain)
  if @key
    key = @key
  else
    database, table = tag.split('.')[-2,2]
    database = TreasureData::API.normalize_database_name(database)
    table = TreasureData::API.normalize_table_name(table)
    key = "#{database}.#{table}"
  end

  unless @auto_create_table
    check_table_exists(key)
  end

  super(tag, es, chain, key)
end

#ensure_database_and_table(database, table) ⇒ Object



342
343
344
345
346
347
348
349
350
351
# File 'lib/fluent/plugin/out_tdlog.rb', line 342

def ensure_database_and_table(database, table)
  log.info "Creating table #{database}.#{table} on TreasureData"
  begin
    @client.create_log_table(database, table)
  rescue TreasureData::NotFoundError
    @client.create_database(database)
    @client.create_log_table(database, table)
  rescue TreasureData::AlreadyExistsError
  end
end

#format_stream(tag, es) ⇒ Object



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

def format_stream(tag, es)
  out = ''
  off = out.bytesize
  es.each { |time, record|
    begin
      if @anonymizes
        @anonymizes.each_pair { |key, scr|
          if value = record[key]
            record[key] = scr.anonymize(value)
          end
        }
      end

      record['time'] = time
      record.delete(:time) if record.has_key?(:time)

      if record.size > @key_num_limit
        raise "Too many number of keys (#{record.size} keys)"  # TODO include summary of the record
      end
    rescue => e
      # TODO (a) Remove the transaction mechanism of fluentd
      #      or (b) keep transaction boundaries in in/out_forward.
      #      This code disables the transaction mechanism (a).
      log.error "#{e}: #{summarize_record(record)}"
      log.error_backtrace e.backtrace
      next
    end

    begin
      record.to_msgpack(out)
    rescue RangeError
      TreasureData::API.normalized_msgpack(record, out)
    end

    noff = out.bytesize
    sz = noff - off
    if sz > @record_size_limit
      # TODO don't raise error
      #raise "Size of a record too large (#{sz} bytes)"  # TODO include summary of the record
      log.warn "Size of a record too large (#{sz} bytes): #{summarize_record(record)}"
    end
    off = noff
  }
  out
end

#startObject



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/fluent/plugin/out_tdlog.rb', line 176

def start
  super

  client_opts = {
    :ssl => @use_ssl, :http_proxy => @http_proxy, :user_agent => @user_agent, :endpoint => @endpoint,
    :connect_timeout => @connect_timeout, :read_timeout => @read_timeout, :send_timeout => @send_timeout
  }
  @client = TreasureData::Client.new(@apikey, client_opts)

  if @key
    if @auto_create_table
      database, table = @key.split('.',2)
      ensure_database_and_table(database, table)
    else
      check_table_exists(@key)
    end
  end
end

#summarize_record(record) ⇒ Object



258
259
260
261
262
263
264
265
# File 'lib/fluent/plugin/out_tdlog.rb', line 258

def summarize_record(record)
  json = Yajl.dump(record)
  if json.size > 100
    json[0..97] + "..."
  else
    json
  end
end

#upload(database, table, io, size, unique_id) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/fluent/plugin/out_tdlog.rb', line 288

def upload(database, table, io, size, unique_id)
  unique_str = unique_id.unpack('C*').map { |x| "%02x" % x }.join
  log.trace { "uploading logs to Treasure Data database=#{database} table=#{table} (#{size}bytes)" }

  begin
    begin
      start = Time.now
      @client.import(database, table, "msgpack.gz", io, size, unique_str)
    rescue TreasureData::NotFoundError => e
      unless @auto_create_table
        raise e
      end
      ensure_database_and_table(database, table)
      io.pos = 0
      retry
    end
  rescue => e
    elapsed = Time.now - start
    ne = RuntimeError.new("Failed to upload to Treasure Data '#{database}.#{table}' table: #{e.inspect} (#{size} bytes; #{elapsed} seconds)")
    ne.set_backtrace(e.backtrace)
    raise ne
  end
end

#validate_database_and_table_name(database, table, conf) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/fluent/plugin/out_tdlog.rb', line 329

def validate_database_and_table_name(database, table, conf)
  begin
    TreasureData::API.validate_database_name(database)
  rescue => e
    raise ConfigError, "Invalid database name #{database.inspect}: #{e}: #{conf}"
  end
  begin
    TreasureData::API.validate_table_name(table)
  rescue => e
    raise ConfigError, "Invalid table name #{table.inspect}: #{e}: #{conf}"
  end
end

#write(chunk) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/fluent/plugin/out_tdlog.rb', line 267

def write(chunk)
  unique_id = chunk.unique_id
  database, table = chunk.key.split('.', 2)

  FileUtils.mkdir_p(@tmpdir) unless @tmpdir.nil?
  f = Tempfile.new("tdlog-", @tmpdir)
  w = Zlib::GzipWriter.new(f)

  chunk.write_to(w)
  w.finish
  w = nil

  size = f.pos
  f.pos = 0
  upload(database, table, f, size, unique_id)

ensure
  w.close if w
  f.close if f
end