Class: Fluent::QueryCombinerOutput

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

Instance Method Summary collapse

Constructor Details

#initializeQueryCombinerOutput

Returns a new instance of QueryCombinerOutput.



24
25
26
27
28
29
30
31
# File 'lib/fluent/plugin/out_query_combiner.rb', line 24

def initialize
  super
  require 'redis'
  require 'msgpack'
  require 'json'
  require 'rubygems'
  require 'time'
end

Instance Method Details

#configure(conf) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/fluent/plugin/out_query_combiner.rb', line 33

def configure(conf)
  super
  @host = conf.has_key?('host') ? conf['host'] : 'localhost'
  @port = conf.has_key?('port') ? conf['port'].to_i : 6379
  @db_number = conf.has_key?('db_number') ? conf['db_number'].to_i : nil

  @query_identify = @query_identify.split(',').map { |qid| qid.strip }

  # functions for time format
  def create_time_formatter(expr)
    begin
      f = eval('lambda {|__arg_time__| ' + expr.gsub("$time", "__arg_time__") + '}')
      return f
    rescue SyntaxError
      raise Fluent::ConfigError, "SyntaxError at time_format `#{expr}`"
    end
  end
  @_time_formatter = create_time_formatter(@time_format)

  @_time_keys = {}

  # Create functions for each conditions
  @_cond_funcs = {}
  @_replace_keys = {
    'catch' => {},
    'dump' => {},
  }

  def get_arguments(eval_str)
    eval_str.scan(/[\"\']?[a-zA-Z][\w\d\.\-\_]*[\"\']?/).uniq.select{|x|
      not (x.start_with?('\'') or x.start_with?('\"')) and \
      not %w{and or xor not}.include? x
    }
  end

  def parse_replace_expr(element_name, condition_name, str)
    result = {}
    str.split(',').each{|cond|
      before, after = cond.split('=>').map{|var| var.strip}
      result[before] = after
      if not (before.length > 0 and after.length > 0)
        raise Fluent::ConfigError, "SyntaxError at replace condition `#{element_name}`: #{condition_name}"
      end
    }
    if result.none?
      raise Fluent::ConfigError, "SyntaxError at replace condition `#{element_name}`: #{condition_name}"
    end
    result
  end

  def create_func(var, expr)
    begin
      f_argv = get_arguments(expr)
      f = eval('lambda {|' + f_argv.join(',') + '| ' + expr + '}')
      return [f, f_argv]
    rescue SyntaxError
      raise Fluent::ConfigError, "SyntaxError at condition `#{var}`: #{expr}"
    end
  end
  conf.elements.select { |element|
    %w{catch prolong dump release}.include? element.name
  }.each { |element|
    element.each_pair { |var, expr|
      element.has_key?(var)   # to suppress unread configuration warning

      if var == 'condition'
        formula, f_argv = create_func(var, expr)
        @_cond_funcs[element.name] = [f_argv, formula]

      elsif var == 'replace'
        if %w{catch dump}.include? element.name
          @_replace_keys[element.name] = parse_replace_expr(element.name, var, expr)
        else
          raise Fluent::ConfigError, "`replace` configuration in #{element.name}: only allowed in `catch` and `dump`"
        end

      elsif var == 'time'
        if %w{catch dump}.include? element.name
          @_time_keys[element.name] = expr
        else
          raise Fluent::ConfigError, "`time` configuration in #{element.name}: only allowed in `catch` and `dump`"
        end

      else
        raise Fluent::ConfigError, "Unknown configuration `#{var}` in #{element.name}"
      end
    }
  }

  if not (@_cond_funcs.has_key?('catch') and @_cond_funcs.has_key?('dump'))
    raise Fluent::ConfigError, "Must have <catch> and <dump> blocks"
  end
end

#create_func(var, expr) ⇒ Object



83
84
85
86
87
88
89
90
91
# File 'lib/fluent/plugin/out_query_combiner.rb', line 83

def create_func(var, expr)
  begin
    f_argv = get_arguments(expr)
    f = eval('lambda {|' + f_argv.join(',') + '| ' + expr + '}')
    return [f, f_argv]
  rescue SyntaxError
    raise Fluent::ConfigError, "SyntaxError at condition `#{var}`: #{expr}"
  end
end

#create_time_formatter(expr) ⇒ Object

functions for time format



42
43
44
45
46
47
48
49
# File 'lib/fluent/plugin/out_query_combiner.rb', line 42

def create_time_formatter(expr)
  begin
    f = eval('lambda {|__arg_time__| ' + expr.gsub("$time", "__arg_time__") + '}')
    return f
  rescue SyntaxError
    raise Fluent::ConfigError, "SyntaxError at time_format `#{expr}`"
  end
end

#do_catch(qid, record, time) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/fluent/plugin/out_query_combiner.rb', line 188

def do_catch(qid, record, time)
  # replace record keys
  @_replace_keys['catch'].each_pair { |before, after|
    record[after] = record[before]
    record.delete(before)
  }
  # add time key if configured
  if @_time_keys.has_key? 'catch'
    record[@_time_keys['catch']] = @_time_formatter.call(time)
  end

  # save record
  tryOnRedis 'set',    @redis_key_prefix + qid, JSON.dump(record)
  # update qid's timestamp
  tryOnRedis 'zadd', @redis_key_prefix, time, qid
  tryOnRedis 'expire', @redis_key_prefix + qid, @query_ttl
end

#do_dump(qid, record, time) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/fluent/plugin/out_query_combiner.rb', line 214

def do_dump(qid, record, time)
  if (tryOnRedis 'exists', @redis_key_prefix + qid)
    # replace record keys
    @_replace_keys['dump'].each_pair { |before, after|
      record[after] = record[before]
      record.delete(before)
    }

    # add time key if configured
    if @_time_keys.has_key? 'dump'
      record[@_time_keys['dump']] = @_time_formatter.call(time)
    end

    # emit
    catched_record = JSON.load(tryOnRedis('get', @redis_key_prefix + qid))
    combined_record = catched_record.merge(record)
    Fluent::Engine.emit @tag, Fluent::Engine.now, combined_record

    # remove qid
    if not @continuous_dump
      do_release(qid)
    else
      # continuous_dump will prolong qid's TTL.
      tryOnRedis 'zadd', @redis_key_prefix, time, qid
      tryOnRedis 'expire', @redis_key_prefix + qid, @query_ttl
    end

  end
end

#do_prolong(qid, time) ⇒ Object



206
207
208
209
210
211
212
# File 'lib/fluent/plugin/out_query_combiner.rb', line 206

def do_prolong(qid, time)
  if (tryOnRedis 'exists', @redis_key_prefix + qid)
    # update qid's timestamp
    tryOnRedis 'zadd', @redis_key_prefix, time, qid
    tryOnRedis 'expire', @redis_key_prefix + qid, @query_ttl
  end
end

#do_release(qid) ⇒ Object



244
245
246
247
# File 'lib/fluent/plugin/out_query_combiner.rb', line 244

def do_release(qid)
  tryOnRedis 'del', @redis_key_prefix + qid
  tryOnRedis 'zrem', @redis_key_prefix, qid
end

#exec_func(record, f_argv, formula) ⇒ Object



136
137
138
139
140
141
142
# File 'lib/fluent/plugin/out_query_combiner.rb', line 136

def exec_func(record, f_argv, formula)
  argv = []
  f_argv.each {|v|
    argv.push(record[v])
  }
  return formula.call(*argv)
end

#extract_qid(record) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
# File 'lib/fluent/plugin/out_query_combiner.rb', line 249

def extract_qid(record)
  qid = []
  @query_identify.each { |attr|
    if record.has_key?(attr)
      qid.push(record[attr])
    else
      return nil
    end
  }
  qid.join(':')
end

#format(tag, time, record) ⇒ Object



184
185
186
# File 'lib/fluent/plugin/out_query_combiner.rb', line 184

def format(tag, time, record)
  [tag, time, record].to_msgpack
end

#get_arguments(eval_str) ⇒ Object



61
62
63
64
65
66
# File 'lib/fluent/plugin/out_query_combiner.rb', line 61

def get_arguments(eval_str)
  eval_str.scan(/[\"\']?[a-zA-Z][\w\d\.\-\_]*[\"\']?/).uniq.select{|x|
    not (x.start_with?('\'') or x.start_with?('\"')) and \
    not %w{and or xor not}.include? x
  }
end

#has_all_keys?(record, argv) ⇒ Boolean

Returns:

  • (Boolean)


127
128
129
130
131
132
133
134
# File 'lib/fluent/plugin/out_query_combiner.rb', line 127

def has_all_keys?(record, argv)
  argv.each {|var|
    if not record.has_key?(var)
      return false
    end
  }
  true
end

#parse_replace_expr(element_name, condition_name, str) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/fluent/plugin/out_query_combiner.rb', line 68

def parse_replace_expr(element_name, condition_name, str)
  result = {}
  str.split(',').each{|cond|
    before, after = cond.split('=>').map{|var| var.strip}
    result[before] = after
    if not (before.length > 0 and after.length > 0)
      raise Fluent::ConfigError, "SyntaxError at replace condition `#{element_name}`: #{condition_name}"
    end
  }
  if result.none?
    raise Fluent::ConfigError, "SyntaxError at replace condition `#{element_name}`: #{condition_name}"
  end
  result
end

#shutdownObject



163
164
165
# File 'lib/fluent/plugin/out_query_combiner.rb', line 163

def shutdown
  @redis.quit
end

#startObject



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/fluent/plugin/out_query_combiner.rb', line 144

def start
  super

  begin
    gem "hiredis"
    @redis = Redis.new(
        :host => @host, :port => @port, :driver => :hiredis,
        :thread_safe => true, :db => @db_index
    )
  rescue LoadError
    @redis = Redis.new(
        :host => @host, :port => @port,
        :thread_safe => true, :db => @db_index
    )
  end

  start_watch
end

#start_watchObject



180
181
182
# File 'lib/fluent/plugin/out_query_combiner.rb', line 180

def start_watch
  @watcher = Thread.new(&method(:watch))
end

#tryOnRedis(method, *args) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/fluent/plugin/out_query_combiner.rb', line 167

def tryOnRedis(method, *args)
  tries = 0
  begin
    @redis.send(method, *args) if @redis.respond_to? method
  rescue Redis::CommandError => e
    tries += 1
    # retry 3 times
    retry if tries <= @redis_retry
    $log.warn %Q[redis command retry failed : #{method}(#{args.join(', ')})]
    raise e.message
  end
end

#watchObject



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

def watch
  @last_checked = Fluent::Engine.now
  tick = @remove_interval
  while true
    sleep 0.5
    if Fluent::Engine.now - @last_checked >= tick
      now = Fluent::Engine.now
      to_expire = now - @query_ttl

      # Delete expired qids
      tryOnRedis 'zremrangebyscore', @redis_key_prefix, '-inf', to_expire

      # Delete buffer_size over qids
      tryOnRedis 'zremrangebyrank', @redis_key_prefix, 0, -@buffer_size

      @last_checked = now
    end
  end
end

#write(chunk) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/fluent/plugin/out_query_combiner.rb', line 261

def write(chunk)

  begin
    chunk.msgpack_each do |(tag, time, record)|
      if (qid = extract_qid record)

        @_cond_funcs.each_pair { |cond, argv_and_func|
          argv, func = argv_and_func
          if exec_func(record, argv, func)
            case cond
            when "catch"
              do_catch(qid, record, time)
            when "prolong"
              do_prolong(qid, time)
            when "dump"
              do_dump(qid, record, time)
            when "release"
              do_release(qid)
            end
            break   # very important!
          end
        }
      end
    end

  end
end