Class: Fluent::GrepCounterOutput

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGrepCounterOutput

Returns a new instance of GrepCounterOutput.



5
6
7
8
# File 'lib/fluent/plugin/out_grepcounter.rb', line 5

def initialize
  super
  require 'pathname'
end

Instance Attribute Details

#countsObject

Returns the value of attribute counts.



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

def counts
  @counts
end

#last_checkedObject

Returns the value of attribute last_checked.



34
35
36
# File 'lib/fluent/plugin/out_grepcounter.rb', line 34

def last_checked
  @last_checked
end

#matchesObject

Returns the value of attribute matches.



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

def matches
  @matches
end

#saved_atObject

Returns the value of attribute saved_at.



33
34
35
# File 'lib/fluent/plugin/out_grepcounter.rb', line 33

def saved_at
  @saved_at
end

#saved_durationObject

Returns the value of attribute saved_duration.



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

def saved_duration
  @saved_duration
end

Instance Method Details

#configure(conf) ⇒ Object



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

def configure(conf)
  super

  @count_interval = @count_interval.to_i
  @input_key = @input_key.to_s
  @regexp = Regexp.compile(@regexp) if @regexp
  @exclude = Regexp.compile(@exclude) if @exclude

  @threshold = @threshold.to_i if @threshold

  unless ['>=', '<='].include?(@comparator)
    raise Fluent::ConfigError, "grepcounter: comparator allows >=, <="
  end

  # to support obsolete `threshold` and `comparator` options
  if @threshold.nil? and @less_than.nil? and @less_equal.nil? and @greater_than.nil? and @greater_equal.nil?
    @threshold = 1
  end
  if @threshold and @comparator
    if @comparator == '>='
      @greater_equal = @threshold
    else
      @less_equal = @threshold
    end
  end

  # to support osolete `output_tag` option
  @tag = @output_tag if !@tag and @output_tag

  # to support obsolete `output_with_joined_delimiter` option
  @delimiter = @output_with_joined_delimiter if !@delimiter and @output_with_joined_delimiter

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

  case @aggregate
  when 'all'
    raise Fluent::ConfigError, "grepcounter: output_tag must be specified with aggregate all" if @output_tag.nil?
  when 'tag'
    # raise Fluent::ConfigError, "grepcounter: add_tag_prefix must be specified with aggregate tag" if @add_tag_prefix.nil?
  end

  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

  if @tag.nil? and @add_tag_prefix.nil? and @remove_tag_prefix.nil?
    @add_tag_prefix = 'count' # not ConfigError to support lower version compatibility
  end

  @tag_prefix = "#{@add_tag_prefix}." if @add_tag_prefix
  @tag_prefix_match = "#{@remove_tag_prefix}." if @remove_tag_prefix
  @tag_proc =
    if @tag
      Proc.new {|tag| @tag }
    elsif @tag_prefix and @tag_prefix_match
      Proc.new {|tag| "#{@tag_prefix}#{lstrip(tag, @tag_prefix_match)}" }
    elsif @tag_prefix_match
      Proc.new {|tag| lstrip(tag, @tag_prefix_match) }
    elsif @tag_prefix
      Proc.new {|tag| "#{@tag_prefix}#{tag}" }
    else
      Proc.new {|tag| tag }
    end

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

#emit(tag, es, chain) ⇒ Object

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



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/fluent/plugin/out_grepcounter.rb', line 124

def emit(tag, es, chain)
  count = 0; matches = []
  # filter out and insert
  es.each do |time,record|
    value = record[@input_key]
    next unless match(value.to_s)
    matches << value
    count += 1
  end
  # thread safe merge
  @counts[tag] ||= 0
  @matches[tag] ||= []
  @mutex.synchronize do
    @counts[tag] += count
    @matches[tag] += matches
  end

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

#flush_emit(step) ⇒ Object

This method is the real one to emit



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/fluent/plugin/out_grepcounter.rb', line 165

def flush_emit(step)
  time = Fluent::Engine.now
  flushed_counts, flushed_matches, @counts, @matches = @counts, @matches, {}, {}

  if @aggregate == 'all'
    count = 0; matches = []
    flushed_counts.keys.each do |tag|
      count += flushed_counts[tag]
      matches += flushed_matches[tag]
    end
    output = generate_output(count, matches)
    Fluent::Engine.emit(@tag, time, output) if output
  else
    flushed_counts.keys.each do |tag|
      count = flushed_counts[tag]
      matches = flushed_matches[tag]
      output = generate_output(count, matches, tag)
      if output
        emit_tag = @tag_proc.call(tag)
        Fluent::Engine.emit(emit_tag, time, output)
      end
    end
  end
end

#generate_output(count, matches, tag = nil) ⇒ Object



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

def generate_output(count, matches, tag = nil)
  return nil if count.nil?
  return nil if count == 0 # ignore 0 because standby nodes receive no message usually
  return nil if @less_than     and @less_than   <= count
  return nil if @less_equal    and @less_equal  <  count
  return nil if @greater_than  and count <= @greater_than
  return nil if @greater_equal and count <  @greater_equal
  output = {}
  output['count'] = count
  output['message'] = @delimiter.nil? ? matches : matches.join(@delimiter)
  if tag
    output['input_tag'] = tag
    output['input_tag_last'] = tag.split('.').last
  end
  output
end

#load_status(file_path, count_interval) ⇒ Object

Load internal status from a file

Parameters:

  • file_path (String)
  • count_interval (Interger)


257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/fluent/plugin/out_grepcounter.rb', line 257

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[:regexp] == @regexp and
        stored[:exclude] == @exclude and
        stored[:input_key]  == @input_key

        if Fluent::Engine.now <= stored[:saved_at] + count_interval
          @counts = stored[:counts]
          @matches = stored[:matches]
          @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_grepcounter: stored data is outdated. ignore stored data"
        end
      else
        $log.warn "out_grepcounter: configuration param was changed. ignore stored data"
      end
    end
  rescue => e
    $log.warn "out_grepcounter: Can't load store_file #{e.class} #{e.message}"
  end
end

#lstrip(string, substring) ⇒ Object



207
208
209
# File 'lib/fluent/plugin/out_grepcounter.rb', line 207

def lstrip(string, substring)
  string.index(substring) == 0 ? string[substring.size..-1] : string
end

#match(string) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
# File 'lib/fluent/plugin/out_grepcounter.rb', line 211

def match(string)
  begin
    return false if @regexp and !@regexp.match(string)
    return false if @exclude and @exclude.match(string)
  rescue ArgumentError => e
    raise e unless e.message.index("invalid byte sequence in") == 0
    string = replace_invalid_byte(string)
    retry
  end
  return true
end

#replace_invalid_byte(string) ⇒ Object



223
224
225
226
227
228
# File 'lib/fluent/plugin/out_grepcounter.rb', line 223

def replace_invalid_byte(string)
  replace_options = { invalid: :replace, undef: :replace, replace: '?' }
  original_encoding = string.encoding
  temporal_encoding = (original_encoding == Encoding::UTF_8 ? Encoding::UTF_16BE : Encoding::UTF_8)
  string.encode(temporal_encoding, original_encoding, replace_options).encode(original_encoding)
end

#save_status(file_path) ⇒ Object

Store internal status into a file

Parameters:

  • file_path (String)


233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/fluent/plugin/out_grepcounter.rb', line 233

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,
        :matches          => @matches,
        :saved_at         => @saved_at,
        :saved_duration   => @saved_duration,
        :regexp           => @regexp,
        :exclude          => @exclude,
        :input_key        => @input_key,
      }, f)
    end
  rescue => e
    $log.warn "out_grepcounter: Can't write store_file #{e.class} #{e.message}"
  end
end

#shutdownObject



116
117
118
119
120
121
# File 'lib/fluent/plugin/out_grepcounter.rb', line 116

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

#startObject



110
111
112
113
114
# File 'lib/fluent/plugin/out_grepcounter.rb', line 110

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

#watcherObject

thread callback



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

def watcher
  # 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(now - @last_checked)
        @last_checked = now
      end
    rescue => e
      $log.warn "grepcounter: #{e.class} #{e.message} #{e.backtrace.first}"
    end
  end
end