Class: Fluent::GroupCounterOutput

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

Defined Under Namespace

Classes: UndefOpenStruct

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGroupCounterOutput

Returns a new instance of GroupCounterOutput.



4
5
6
7
# File 'lib/fluent/plugin/out_groupcounter.rb', line 4

def initialize
  super
  require 'pathname'
end

Instance Attribute Details

#count_intervalObject

Returns the value of attribute count_interval.



28
29
30
# File 'lib/fluent/plugin/out_groupcounter.rb', line 28

def count_interval
  @count_interval
end

#countsObject

Returns the value of attribute counts.



29
30
31
# File 'lib/fluent/plugin/out_groupcounter.rb', line 29

def counts
  @counts
end

#last_checkedObject

Returns the value of attribute last_checked.



32
33
34
# File 'lib/fluent/plugin/out_groupcounter.rb', line 32

def last_checked
  @last_checked
end

#saved_atObject

Returns the value of attribute saved_at.



31
32
33
# File 'lib/fluent/plugin/out_groupcounter.rb', line 31

def saved_at
  @saved_at
end

#saved_durationObject

Returns the value of attribute saved_duration.



30
31
32
# File 'lib/fluent/plugin/out_groupcounter.rb', line 30

def saved_duration
  @saved_duration
end

Instance Method Details

#configure(conf) ⇒ Object



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

def configure(conf)
  super

  if @group_by_keys.nil? and @group_by_expression.nil?
    raise Fluent::ConfigError, "Either of group_by_keys or group_by_expression must be specified"
  end

  if @count_interval
    @count_interval = @count_interval.to_i
  else
    @count_interval = case @unit
            when 'minute' then 60
            when 'hour' then 3600
            when 'day' then 86400
            else 
              raise RuntimeError, "@unit must be one of minute/hour/day"
            end
  end

  @aggregate = case @aggregate
               when 'tag' then :tag
               when 'all' then :all
               else
                 raise Fluent::ConfigError, "groupcounter aggregate allows tag/all"
               end

  if @output_per_tag
    raise Fluent::ConfigError, "tag_prefix must be specified with output_per_tag" unless @tag_prefix
    @tag_prefix_string = @tag_prefix + '.'
  end

  if @input_tag_remove_prefix
    @removed_prefix_string = @input_tag_remove_prefix + '.'
    @removed_length = @removed_prefix_string.length
  end

  @group_by_keys = @group_by_keys.split(',') if @group_by_keys

  if @store_file
    f = Pathname.new(@store_file)
    if (f.exist? && !f.writable_real?) || (!f.exist? && !f.parent.writable_real?)
      raise Fluent::ConfigError, "#{@store_file} is not writable"
    end
  end

  @counts = count_initialized
  @hostname = Socket.gethostname
  @mutex = Mutex.new
end

#count_initializedObject



97
98
99
# File 'lib/fluent/plugin/out_groupcounter.rb', line 97

def count_initialized
  {}
end

#countup(counts, count) ⇒ Object



217
218
219
220
221
222
# File 'lib/fluent/plugin/out_groupcounter.rb', line 217

def countup(counts, count)
  counts[:count] = sum(counts[:count], count[:count])
  counts[:sum]   = sum(counts[:sum], count[:sum]) if @avg_key and count[:sum]
  counts[:max]   = max(counts[:max], count[:max]) if @max_key and count[:max]
  counts[:min]   = min(counts[:min], count[:min]) if @min_key and count[:min]
end

#emit(tag, es, chain) ⇒ Object

recieve messages at here



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/fluent/plugin/out_groupcounter.rb', line 178

def emit(tag, es, chain)
  group_counts = {}

  tags = tag.split('.')
  es.each do |time, record|
    count = {}
    count[:count] = 1
    count[:sum] = record[@avg_key].to_f if @avg_key and record[@avg_key]
    count[:max] = record[@max_key].to_f if @max_key and record[@max_key]
    count[:min] = record[@min_key].to_f if @min_key and record[@min_key]

    group_key = group_key(tag, time, record)

    group_counts[group_key] ||= {}
    countup(group_counts[group_key], count)
  end
  summarize_counts(tag, group_counts)

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

#flushObject



137
138
139
140
# File 'lib/fluent/plugin/out_groupcounter.rb', line 137

def flush
  flushed, @counts = @counts, count_initialized()
  generate_output(flushed)
end

#flush_emitObject

this method emits messages (periodically called)



143
144
145
146
147
148
149
150
151
152
153
# File 'lib/fluent/plugin/out_groupcounter.rb', line 143

def flush_emit
  time = Fluent::Engine.now
  if @output_per_tag
    flush.each do |tag, message|
      Fluent::Engine.emit(@tag_prefix_string + tag, time, message)
    end
  else
    message = flush
    Fluent::Engine.emit(@tag, time, message) unless message.empty?
  end
end

#generate_fields(counts_per_tag, output = {}, key_prefix = '') ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/fluent/plugin/out_groupcounter.rb', line 101

def generate_fields(counts_per_tag, output = {}, key_prefix = '')
  return {} unless counts_per_tag
  # total_count = counts_per_tag.delete('__total_count')

  counts_per_tag.each do |group_key, count|
    output[key_prefix + group_key + @count_suffix] = count[:count] if count[:count]
    output[key_prefix + group_key + "#{@delimiter}#{@min_key}#{@min_suffix}"] = count[:min] if count[:min]
    output[key_prefix + group_key + "#{@delimiter}#{@max_key}#{@max_suffix}"] = count[:max] if count[:max]
    output[key_prefix + group_key + "#{@delimiter}#{@avg_key}#{@avg_suffix}"] = count[:sum] / (count[:count] * 1.0) if count[:sum] and count[:count] > 0
    # output[key_prefix + group_key + "#{@delimiter}rate"] = ((count[:count] * 100.0) / (1.00 * step)).floor / 100.0
    # output[key_prefix + group_key + "#{@delimiter}percentage"] = count[:count] * 100.0 / (1.00 * total_count) if total_count > 0
  end

  output
end

#generate_output(counts) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/fluent/plugin/out_groupcounter.rb', line 117

def generate_output(counts)
  if @output_per_tag # tag => output
    return {'all' => generate_fields(counts['all'])} if @aggregate == :all

    output_pairs = {}
    counts.keys.each do |tag|
      output_pairs[stripped_tag(tag)] = generate_fields(counts[tag])
    end
    output_pairs
  else
    return generate_fields(counts['all']) if @aggregate == :all

    output = {}
    counts.keys.each do |tag|
      generate_fields(counts[tag], output, stripped_tag(tag) + '_')
    end
    output
  end
end

#group_key(tag, time, record) ⇒ Object

Expand record with @group_by_keys, and get a value to be a group_key



225
226
227
228
229
230
231
232
233
234
# File 'lib/fluent/plugin/out_groupcounter.rb', line 225

def group_key(tag, time, record)
  if @group_by_expression
    tags = tag.split('.')
    group_key = expand_placeholder(@group_by_expression, record, tag, tags, Time.at(time))
  else # @group_by_keys
    values = @group_by_keys.map {|key| record[key] || 'undef'}
    group_key = values.join(@delimiter)
  end
  group_key = group_key.to_s.force_encoding('ASCII-8BIT')
end

#load_status(file_path, count_interval) ⇒ Object

Load internal status from a file

Parameters:

  • file_path (String)
  • count_interval (Interger)


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

def load_status(file_path, count_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[:group_by_keys] == @group_by_keys and

        if Fluent::Engine.now <= stored[:saved_at] + count_interval
          @counts = stored[:counts]
          @saved_at = stored[:saved_at]
          @saved_duration = stored[:saved_duration]

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

#max(a, b) ⇒ Object



242
243
244
245
246
# File 'lib/fluent/plugin/out_groupcounter.rb', line 242

def max(a, b)
  return b if a.nil?
  return a if b.nil?
  a > b ? a : b
end

#min(a, b) ⇒ Object



248
249
250
251
252
# File 'lib/fluent/plugin/out_groupcounter.rb', line 248

def min(a, b)
  return b if a.nil?
  return a if b.nil?
  a > b ? b : a
end

#save_status(file_path) ⇒ Object

Store internal status into a file

Parameters:

  • file_path (String)


264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/fluent/plugin/out_groupcounter.rb', line 264

def save_status(file_path)

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

#shutdownObject



90
91
92
93
94
95
# File 'lib/fluent/plugin/out_groupcounter.rb', line 90

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

#startObject



84
85
86
87
88
# File 'lib/fluent/plugin/out_groupcounter.rb', line 84

def start
  super
  load_status(@store_file, @count_interval) if @store_file
  start_watch
end

#start_watchObject



155
156
157
158
# File 'lib/fluent/plugin/out_groupcounter.rb', line 155

def start_watch
  # for internal, or tests only
  @watcher = Thread.new(&method(:watch))
end

#stripped_tag(tag) ⇒ Object



254
255
256
257
258
259
# File 'lib/fluent/plugin/out_groupcounter.rb', line 254

def stripped_tag(tag)
  return tag unless @input_tag_remove_prefix
  return tag[@removed_length..-1] if tag.start_with?(@removed_prefix_string) and tag.length > @removed_length
  return tag[@removed_length..-1] if tag == @input_tag_remove_prefix
  tag
end

#sum(a, b) ⇒ Object



236
237
238
239
240
# File 'lib/fluent/plugin/out_groupcounter.rb', line 236

def sum(a, b)
  a ||= 0
  b ||= 0
  a + b
end

#summarize_counts(tag, group_counts) ⇒ Object

Summarize counts for each tag



202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/fluent/plugin/out_groupcounter.rb', line 202

def summarize_counts(tag, group_counts)
  tag = 'all' if @aggregate == :all
  @counts[tag] ||= {}
  
  @mutex.synchronize {
    group_counts.each do |group_key, count|
      @counts[tag][group_key] ||= {}
      countup(@counts[tag][group_key], count)
    end

    # total_count = group_counts.map {|group_key, count| count[:count] }.inject(:+)
    # @counts[tag]['__total_count'] = sum(@counts[tag]['__total_count'], total_count)
  }
end

#watchObject



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/fluent/plugin/out_groupcounter.rb', line 160

def watch
  # instance variable, and public accessable, for test
  @last_checked ||= Fluent::Engine.now
  while true
    sleep 0.5
    begin
      if Fluent::Engine.now - @last_checked >= @count_interval
        now = Fluent::Engine.now
        flush_emit
        @last_checked = now
      end
    rescue => e
      $log.warn "#{e.class} #{e.message} #{e.backtrace.first}"
    end
  end
end