Class: Fluent::StatsOutput

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStatsOutput

Returns a new instance of StatsOutput.



10
11
12
13
# File 'lib/fluent/plugin/out_stats.rb', line 10

def initialize
  super
  require 'pathname'
end

Instance Attribute Details

#last_checkedObject

Returns the value of attribute last_checked.



41
42
43
# File 'lib/fluent/plugin/out_stats.rb', line 41

def last_checked
  @last_checked
end

#matchesObject

Returns the value of attribute matches.



38
39
40
# File 'lib/fluent/plugin/out_stats.rb', line 38

def matches
  @matches
end

#saved_atObject

Returns the value of attribute saved_at.



40
41
42
# File 'lib/fluent/plugin/out_stats.rb', line 40

def saved_at
  @saved_at
end

#saved_durationObject

Returns the value of attribute saved_duration.



39
40
41
# File 'lib/fluent/plugin/out_stats.rb', line 39

def saved_duration
  @saved_duration
end

Instance Method Details

#configure(conf) ⇒ Object



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

def configure(conf)
  super

  @interval = @interval.to_i
  @sum = Regexp.new(@sum) if @sum
  @max = Regexp.new(@max) if @max
  @min = Regexp.new(@min) if @min
  @avg = Regexp.new(@avg) if @avg
  @sum_keys = @sum_keys ? @sum_keys.split(',') : []
  @max_keys = @max_keys ? @max_keys.split(',') : []
  @min_keys = @min_keys ? @min_keys.split(',') : []
  @avg_keys = @avg_keys ? @avg_keys.split(',') : []

  case @aggregate
  when 'tag' # obsolete
    @aggregate = 'in_tag'
  when 'all'
    raise Fluent::ConfigError, "tag must be specified for aggregate all" if @tag.nil?
  end

  unless ['in_tag', 'out_tag', 'all'].include?(@aggregate)
    raise Fluent::ConfigError, "aggregate allows in_tag/out_tag/all"
  end

  if @tag.nil? and @add_tag_prefix.nil? and @remove_tag_prefix.nil? and @add_tag_suffix.nil? and @remove_tag_suffix.nil? and @remove_tag_slice.nil?
    @add_tag_prefix = 'stats' # not ConfigError for lower version compatibility
  end
  @tag_proc = tag_proc

  @aggregate_proc = aggregate_proc(@tag_proc)

  @matches = {}
  @mutex = Mutex.new
end

#emit(tag, es, chain) ⇒ Object

Called when new line comes. This method actually does not emit



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
175
176
177
178
179
180
181
182
183
# File 'lib/fluent/plugin/out_stats.rb', line 112

def emit(tag, es, chain)
  # stats
  matches = { :count => 0, :sum => {}, :max => {}, :min => {}, :avg => {}, :avg_count => {} }
  es.each do |time, record|
    record = stringify_keys(record)
    @sum_keys.each do |key|
      next unless record[key] and value = record[key].to_f
      matches[:sum][key] = sum(matches[:sum][key], value)
    end
    @max_keys.each do |key|
      next unless record[key] and value = record[key].to_f
      matches[:max][key] = max(matches[:max][key], value)
    end
    @min_keys.each do |key|
      next unless record[key] and value = record[key].to_f
      matches[:min][key] = min(matches[:min][key], value)
    end
    @avg_keys.each do |key|
      next unless record[key] and value = record[key].to_f
      matches[:avg][key] = sum(matches[:avg][key], value)
      # ignore zero emitted value
      matches[:avg_count][key] = sum(matches[:avg_count][key], 1) unless (@zero_emit and value.zero?)
    end
    record.keys.each do |key|
      key = key.to_s
      value = record[key].to_f
      if @sum and @sum.match(key)
        matches[:sum][key] = sum(matches[:sum][key], value)
      end
      if @max and @max.match(key)
        matches[:max][key] = max(matches[:max][key], value)
      end
      if @min and @min.match(key)
        matches[:min][key] = min(matches[:min][key], value)
      end
      if @avg and @avg.match(key)
        matches[:avg][key] = sum(matches[:avg][key], value) # sum yet
        # ignore zero emitted value
        matches[:avg_count][key] = sum(matches[:avg_count][key], 1) unless (@zero_emit and value.zero?)
      end
    end if @sum || @max || @min || @avg
    matches[:count] += 1
  end

  aggregate_key = @aggregate_proc.call(tag)

  # thread safe merge
  @matches[aggregate_key] ||= { :count => 0, :sum => {}, :max => {}, :min => {}, :avg => {}, :avg_count => {} }
  @matches[aggregate_key][:avg_count] ||= {} # for lower version compatibility
  @mutex.synchronize do
    matches[:sum].keys.each do |key|
      @matches[aggregate_key][:sum][key] = sum(@matches[aggregate_key][:sum][key], matches[:sum][key])
    end
    matches[:max].keys.each do |key|
      @matches[aggregate_key][:max][key] = max(@matches[aggregate_key][:max][key], matches[:max][key])
    end
    matches[:min].keys.each do |key|
      @matches[aggregate_key][:min][key] = min(@matches[aggregate_key][:min][key], matches[:min][key])
    end
    matches[:avg].keys.each do |key|
      @matches[aggregate_key][:avg][key] = sum(@matches[aggregate_key][:avg][key], matches[:avg][key]) # sum yet
      @matches[aggregate_key][:avg_count][key] = sum(@matches[aggregate_key][:avg_count][key], matches[:avg_count][key])
    end
    @matches[aggregate_key][:count] += matches[:count]
  end

  log.trace "out_stats: tag:#{tag} @matches:#{@matches}"

  chain.next
rescue => e
  log.warn "out_stats: #{e.class} #{e.message} #{e.backtrace.first}"
end

#flush_emitObject

This method is the real one to emit



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/fluent/plugin/out_stats.rb', line 204

def flush_emit
  time = Fluent::Engine.now
  flushed_matches = {}
  @mutex.synchronize do
    flushed_matches, @matches = @matches, initial_matches(@matches)
  end
  log.trace("out_stats: flushed_matches:#{flushed_matches} @matches:#{@matches}") unless flushed_matches.empty?

  flushed_matches.each do |tag, matches|
    case @aggregate
    when 'all'
      emit_tag = @tag
    when 'in_tag'
      emit_tag = @tag_proc.call(tag)
    when 'out_tag'
      emit_tag = tag
    else
    end
    report_time(" emit_tag:#{emit_tag} matches:#{matches}") do
      output = generate_output(matches)
      Fluent::Engine.emit(emit_tag, time, output) if output and !output.empty?
    end
  end
end

#generate_output(matches) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/fluent/plugin/out_stats.rb', line 229

def generate_output(matches)
  return nil if matches.empty?
  output = {}
  matches[:sum].keys.each do |key|
    output[key + @sum_suffix] = matches[:sum][key]
  end
  matches[:max].keys.each do |key|
    output[key + @max_suffix] = matches[:max][key]
  end
  matches[:min].keys.each do |key|
    output[key + @min_suffix] = matches[:min][key]
  end
  matches[:avg_count] ||= {} # for lower version compatibility
  matches[:avg].keys.each do |key|
    output[key + @avg_suffix] = matches[:avg][key]
    count = matches[:avg_count][key].to_f
    output[key + @avg_suffix] /= count unless count.zero?
  end
  output
end

#initial_matches(prev_matches = nil) ⇒ Object



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

def initial_matches(prev_matches = nil)
  if @zero_emit && prev_matches
    matches = {}
    prev_matches.keys.each do |aggregate_key|
      next unless prev_matches[aggregate_key][:count] > 0 # Prohibit to emit anymore
      matches[aggregate_key] = { :count => 0, :sum => {}, :max => {}, :min => {}, :avg => {}, :avg_count => {} }
      # ToDo: would want default configuration for :max, :min
      prev_matches[aggregate_key][:sum].keys.each {|key| matches[aggregate_key][:sum][key] = 0 }
      prev_matches[aggregate_key][:max].keys.each {|key| matches[aggregate_key][:max][key] = 0 }
      prev_matches[aggregate_key][:min].keys.each {|key| matches[aggregate_key][:min][key] = 0 }
      prev_matches[aggregate_key][:avg].keys.each {|key| matches[aggregate_key][:avg][key] = 0 }
      prev_matches[aggregate_key][:avg_count] ||= {} # for lower version compatibility
      prev_matches[aggregate_key][:avg_count].keys.each {|key| matches[aggregate_key][:avg_count][key] = 0 }
    end
    matches
  else
    {}
  end
end

#load_status(file_path, interval) ⇒ Object

Load internal status from a file

Parameters:

  • file_path (String)
  • interval (Interger)


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

def load_status(file_path, interval)
  return unless (f = Pathname.new(file_path)).exist?

  begin
    f.open('rb') do |f|
      stored = Marshal.load(f)
      if stored[:aggregate] == @aggregate and
        stored[:sum] == @sum and
        stored[:max] == @max and
        stored[:min] == @min and
        stored[:avg] == @avg

        if !stored[:matches].empty? and !stored[:matches].first[1].has_key?(:max)
          log.warn "out_stats: stored data does not have compatibility with the current version. ignore stored data"
          return
        end

        if Fluent::Engine.now <= stored[:saved_at] + interval
          @matches = stored[:matches]
          @saved_at = stored[:saved_at]
          @saved_duration = stored[:saved_duration]
          # for lower compatibility
          if counts = stored[:counts]
            @matches.keys.each {|tag| @matches[tag][:count] = counts[tag] }
          end

          # skip the saved duration to continue counting
          @last_checked = Fluent::Engine.now - @saved_duration
        else
          log.warn "out_stats: stored data is outdated. ignore stored data"
        end
      else
        log.warn "out_stats: configuration param was changed. ignore stored data"
      end
    end
  rescue => e
    log.warn "out_stats: Can't load store_file #{e.class} #{e.message}"
  end
end

#max(a, b) ⇒ Object



254
255
256
# File 'lib/fluent/plugin/out_stats.rb', line 254

def max(a, b)
  [a, b].compact.max
end

#min(a, b) ⇒ Object



258
259
260
# File 'lib/fluent/plugin/out_stats.rb', line 258

def min(a, b)
  [a, b].compact.min
end

#save_status(file_path) ⇒ Object

Store internal status into a file

Parameters:

  • file_path (String)


265
266
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_stats.rb', line 265

def save_status(file_path)
  return unless file_path

  begin
    Pathname.new(file_path).open('wb') do |f|
      @saved_at = Fluent::Engine.now
      @saved_duration = @saved_at - @last_checked
      Marshal.dump({
        :matches          => @matches,
        :saved_at         => @saved_at,
        :saved_duration   => @saved_duration,
        :aggregate        => @aggregate,
        :sum              => @sum,
        :max              => @max,
        :min              => @min,
        :avg              => @avg,
      }, f)
    end
  rescue => e
    log.warn "out_stats: Can't write store_file #{e.class} #{e.message}"
  end
end

#shutdownObject



104
105
106
107
108
109
# File 'lib/fluent/plugin/out_stats.rb', line 104

def shutdown
  super
  @watcher.terminate
  @watcher.join
  save_status(@store_file) if @store_file
end

#startObject



98
99
100
101
102
# File 'lib/fluent/plugin/out_stats.rb', line 98

def start
  super
  load_status(@store_file, @interval) if @store_file
  @watcher = Thread.new(&method(:watcher))
end

#sum(a, b) ⇒ Object



250
251
252
# File 'lib/fluent/plugin/out_stats.rb', line 250

def sum(a, b)
  [a, b].compact.inject(:+)
end

#watcherObject

thread callback



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/fluent/plugin/out_stats.rb', line 186

def watcher
  # instance variable, and public accessable, for test
  @last_checked ||= Fluent::Engine.now
  while (sleep 0.5)
    begin
      if Fluent::Engine.now - @last_checked >= @interval
        report_time do
          @last_checked = Fluent::Engine.now
          flush_emit
        end
      end
    rescue => e
      log.warn "out_stats: #{e.class} #{e.message} #{e.backtrace.first}"
    end
  end
end