Class: Fluent::Site24x7Output

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

Constant Summary collapse

S247_MAX_RECORD_COUNT =
500
S247_MAX_RECORD_SIZE =
1000000
S247_MAX_BATCH_SIZE =
5000000
S247_LOG_UPLOAD_CHECK_INTERVAL =

10 minutes

600
S247_TRUNCATION_SUFFIX =
"##TRUNCATED###"

Instance Method Summary collapse

Constructor Details

#initializeSite24x7Output

Returns a new instance of Site24x7Output.



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

def initialize
  super
end

Instance Method Details

#add_message_metadataObject



235
236
237
# File 'lib/fluent/plugin/out_site24x7.rb', line 235

def ()
  @log_fields.update({'_zl_timestamp' => get_timestamp(@log_fields[@logtype_config['dateField']]), 's247agentuid' => @log_source})
end

#applyHashingObject



670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# File 'lib/fluent/plugin/out_site24x7.rb', line 670

def applyHashing()
  if @hashing_config
    begin
      for key,value in @hashing_config do
        hash_regex = @hashing_config[key]["regex"]
        if @formatted_line.has_key?key 
          field_value = @formatted_line[key]
          if (hash_regex.eql?(@general_regex))
            hash_string =  Digest::SHA256.hexdigest(field_value)
            field_value = hash_string
          else 
            adjust_length = 0 
            matcher = field_value.to_enum(:scan, hash_regex).map { Regexp.last_match }
            if matcher
              (0..(matcher.length)-1).map do |index| 
                start = matcher[index].offset(1)[0] 
                _end = matcher[index].offset(1)[1] 
                if ((start >= 0) && (_end > 0))
                  start = start - adjust_length
                  _end = _end - adjust_length
                  hash_string =  Digest::SHA256.hexdigest(field_value[start..(_end-1)])
                  adjust_length += (_end - start) - hash_string.bytesize
                  field_value = field_value[0..(start-1)] + hash_string + field_value[_end..field_value.bytesize]
                end
              end
            end
          end 
          if adjust_length
            @log_size -= adjust_length
          else
            @log_size -= (@formatted_line[key].bytesize - field_value.bytesize)
          end
          @formatted_line[key] = field_value
        end
      end
    rescue Exception => e
      log.error "Exception occurred in hashing : #{e.backtrace}"
    end
  end
end

#applyMaskingObject



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# File 'lib/fluent/plugin/out_site24x7.rb', line 634

def applyMasking()
  if @masking_config
    begin
      for key,value in @masking_config do
        adjust_length = 0
        mask_regex = @masking_config[key]["regex"]
        if @formatted_line.has_key?key
          field_value = @formatted_line[key]
          if !(mask_regex.eql?(@general_regex))
            matcher = field_value.to_enum(:scan, mask_regex).map { Regexp.last_match }
            if matcher
              (0..(matcher.length)-1).map do |index| 
                start = matcher[index].offset(1)[0]  
                _end = matcher[index].offset(1)[1]
                if ((start >= 0) && (_end > 0))
                  start = start - adjust_length
                  _end = _end - adjust_length
                  adjust_length += (_end - start) - @masking_config[key]['string'].bytesize
                  field_value = field_value[0..(start-1)] + @masking_config[key]['string'] + field_value[_end..field_value.bytesize]
                end
              end
            end
            @formatted_line[key] = field_value
            @log_size -= adjust_length
          else
            @log_size -= (@formatted_line[key].bytesize - @masking_config[key]['string'].bytesize)
            @formatted_line[key] = @masking_config[key]['string']
          end
        end
      end
    rescue Exception => e
      log.error "Exception occurred in masking : #{e.backtrace}"
    end        
  end
end

#base64_url_decode(str) ⇒ Object



69
70
71
72
# File 'lib/fluent/plugin/out_site24x7.rb', line 69

def base64_url_decode(str)
   str += '=' * (4 - str.length.modulo(4))
   Base64.decode64(str.tr('-_','+/'))
end

#batch_http_events(encoded_events) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/fluent/plugin/out_site24x7.rb', line 490

def batch_http_events(encoded_events)
  batches = []
  current_batch = []
  current_batch_size = 0
  encoded_events.each_with_index do |encoded_event, i|
    current_event_size = String(encoded_event).bytesize
    if current_event_size > S247_MAX_RECORD_SIZE
      encoded_event = encoded_event[0..(S247_MAX_RECORD_SIZE-DD_TRUNCATION_SUFFIX.length)]+DD_TRUNCATION_SUFFIX
      current_event_size = encoded_event.bytesize
    end

    if (i > 0 and i % S247_MAX_RECORD_COUNT == 0) or (current_batch_size + current_event_size > S247_MAX_BATCH_SIZE)
      batches << current_batch
      current_batch = []
      current_batch_size = 0
    end

    current_batch_size += current_event_size
    current_batch << encoded_event
  end
  batches << current_batch
  batches
end

#configure(conf) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/fluent/plugin/out_site24x7.rb', line 38

def configure(conf)
  compat_parameters_convert(conf, :buffer)
  super
  if conf['http_proxy']
      ENV['http_proxy'] = @http_proxy
  end
end

#format(tag, time, record) ⇒ Object



453
454
455
456
457
458
459
460
461
462
463
# File 'lib/fluent/plugin/out_site24x7.rb', line 453

def format(tag, time, record)
  if @valid_logtype && (@log_upload_allowed || (time.to_i - @log_upload_stopped_time > S247_LOG_UPLOAD_CHECK_INTERVAL))
    if (record.size == 1)
      if record.has_key?'message'
        [record['message']].to_msgpack
      end
    else
      [record.to_json].to_msgpack
    end
  end
end

#format_http_event_batch(events) ⇒ Object



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/fluent/plugin/out_site24x7.rb', line 514

def format_http_event_batch(events)
  parsed_lines = []
  @log_size = 0
  @old_log_size=0
  if @logtype_config.has_key?'jsonPath'
    parsed_lines = json_log_parser(events)
  elsif @logtype_config.has_key?'ml_regex'
    parsed_lines = ml_log_parser(events)
  else
    parsed_lines = parse_lines(events)
  end
  if (parsed_lines.length > 0)
    return Yajl.dump(parsed_lines), @log_size
  end
  return [],0
end

#formatted_to_msgpack_binary?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/fluent/plugin/out_site24x7.rb', line 50

def formatted_to_msgpack_binary?
  true
end

#get_json_value(obj, key, datatype = nil) ⇒ Object



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

def get_json_value(obj, key, datatype=nil)
  if obj != nil && (obj.has_key?key)
    if datatype and datatype == 'json-object'
      arr_json = []
      child_obj = obj[key]
      if child_obj.class == String
        child_obj = Yajl::Parser.parse(child_obj.gsub('\\','\\\\'))
      end             
      child_obj.each do |key, value|
        arr_json.push({'key' => key, 'value' => String(value)})
      end
      return arr_json
    else
      return (if obj.has_key?key then obj[key] else obj[key.downcase] end)
    end
  elsif key.include?'.'
    parent_key = key[0..key.index('.')-1]
    child_key = key[key.index('.')+1..-1]
    child_obj = obj[if obj.has_key?parent_key then parent_key else parent_key.capitalize() end]
    if child_obj.class == String
      child_obj = Yajl::Parser.parse(child_obj.replace('\\','\\\\'))
    end
    return get_json_value(child_obj, child_key,datatype)
  end
end

#get_last_group_inregex(s247_custom_regex) ⇒ Object



225
226
227
# File 'lib/fluent/plugin/out_site24x7.rb', line 225

def get_last_group_inregex(s247_custom_regex)
  return @s247_custom_regex.names[-1]
end

#get_timestamp(datetime_string) ⇒ Object



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

def get_timestamp(datetime_string)
  begin
      # If the date value is in unix format the no need to process the date string
      if @s247_datetime_format_string.include? 'unix'
          return (if @s247_datetime_format_string == 'unix' then datetime_string+'000' else datetime_string end)
      end
      datetime_string += if !@is_year_present then ' '+String(Time.new.year) else '' end
      if !@is_timezone_present && @logtype_config.has_key?('timezone')
          time_zone = String(@s247_tz['hrs'])+':'+String(@s247_tz['mins'])
          datetime_string += if time_zone.start_with?('-') then time_zone else '+'+time_zone end
      end
      datetime_data = DateTime.strptime(datetime_string, @s247_datetime_format_string)
      return Integer(datetime_data.strftime('%Q'))
  rescue Exception => e
    @logger.error "Exception in parsing date: #{e.backtrace}"
      return 0
  end
end

#getDerivedFieldsObject



711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/fluent/plugin/out_site24x7.rb', line 711

def getDerivedFields()
  if @derived_config
    begin
      for key,value in @derived_fields do
        for each in @derived_fields[key] do
            if @formatted_line.has_key?key
              match_derived = each.match(@formatted_line[key])
              if match_derived
                @formatted_line.update(match_derived.named_captures)
                for field_name,value in match_derived.named_captures do
                  @log_size += @formatted_line[field_name].bytesize
                end  
              end
              break
            end
        end
      end
    rescue Exception => e
      log.error "Exception occurred in derived fields : #{e.backtrace}"
    end  
  end
end

#gzip_compress(payload) ⇒ Object



531
532
533
534
535
536
537
538
539
540
541
# File 'lib/fluent/plugin/out_site24x7.rb', line 531

def gzip_compress(payload)
  gz = StringIO.new
  gz.set_encoding("BINARY")
  z = Zlib::GzipWriter.new(gz, 9)
  begin
    z.write(payload)
  ensure
    z.close
  end
  gz.string
end

#init_http_client(logtype_config) ⇒ Object



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

def init_http_client(logtype_config)
  require 'net/http/persistent'
  upload_url = 'https://'+logtype_config['uploadDomain']+'/upload'
  @uri = URI(upload_url)
  log.info "Starting HTTP connection to #{upload_url}"
  @s247_http_client = Net::HTTP::Persistent.new name: "fluent-plugin-site24x7", proxy: :ENV
  @s247_http_client.verify_mode = OpenSSL::SSL::VERIFY_NONE
  @s247_http_client.idle_timeout = @http_idle_timeout
  @s247_http_client.read_timeout = @http_read_timeout
  @s247_http_client.override_headers["Content-Type"] = "application/json"
  @s247_http_client.override_headers["Content-Encoding"] = "gzip"
  @s247_http_client.override_headers["X-DeviceKey"] = logtype_config['apiKey']
  @s247_http_client.override_headers["X-LogType"] = logtype_config['logType']
  @s247_http_client.override_headers["X-StreamMode"] = 1
  @s247_http_client.override_headers["User-Agent"] = 'Fluentd'
  if !@s247_http_client.proxy_uri.nil?
      log.info "Using HTTP proxy #{@s247_http_client.proxy_uri.scheme}://#{@s247_http_client.proxy_uri.host}:#{@s247_http_client.proxy_uri.port} username: #{@s247_http_client.proxy_uri.user ? "configured" : "not configured"}, password: #{@s247_http_client.proxy_uri.password ? "configured" : "not configured"}"
  end    
end

#init_variablesObject



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

def init_variables()
  @logtype_config = Yajl::Parser.parse(base64_url_decode(@log_type_config))
  @s247_custom_regex = if @logtype_config.has_key? 'regex' then Regexp.compile(@logtype_config['regex'].gsub('?P<','?<')) else nil end
  @s247_ignored_fields = if @logtype_config.has_key? 'ignored_fields' then @logtype_config['ignored_fields'] else [] end
  @datetime_regex = if @logtype_config.has_key?'dateRegex' then Regexp.compile(@logtype_config['dateRegex'].gsub('?P<','?<')) else nil end

  @ml_regex = if @logtype_config.has_key? 'ml_regex' then Regexp.compile(@logtype_config['ml_regex'].gsub('?P<','?<')) else nil end
  @ml_end_regex = if @logtype_config.has_key? 'ml_end_regex' then Regexp.compile(@logtype_config['ml_end_regex'].gsub('?P<','?<')) else nil end
  @max_ml_count = if @logtype_config.has_key? 'ml_regex' then @s247_custom_regex.inspect.scan('\<NewLine\>').length else nil end
  @max_trace_line = 100
  @ml_trace = ''
  @ml_trace_buffer = ''
  @ml_found = false
  @ml_end_line_found = false
  @ml_data = nil
  @ml_count = 0
  
  @json_data = ''
  @sub_pattern = {}

  if !(@logtype_config.has_key?('jsonPath'))
    @message_key = get_last_group_inregex(@s247_custom_regex)
  end
  
  if @logtype_config.has_key?('jsonPath')
    @logtype_config['jsonPath'].each_with_index do | key, index |
      if key.has_key?('pattern')
        begin
          if Regexp.new(key['pattern'].gsub('?P<','?<'))
            @sub_pattern[key['name']] = Regexp.compile(key['pattern'].gsub('?P<','?<'))
          end
        rescue Exception => e
          log.error "Invalid subpattern regex #{e.backtrace}"
        end
      end
    end 
  end

  @old_formatted_line = {}
  @formatted_line = {}

  @masking_config = if @logtype_config.has_key? 'maskingConfig' then  @logtype_config['maskingConfig']  else nil end
  @hashing_config = if @logtype_config.has_key? 'hashingConfig' then  @logtype_config['hashingConfig']  else nil end
  @derived_config = if @logtype_config.has_key? 'derivedConfig' then @logtype_config['derivedConfig'] else nil end
  @general_regex = Regexp.compile("(.*)")
  
  if @derived_config
    @derived_fields = {}
    for key,value in @derived_config do
      @derived_fields[key] = []
      for values in @derived_config[key] do
        @derived_fields[key].push(Regexp.compile(values.gsub('\\\\', '\\')))
      end
    end
  end
  
  if @masking_config
    for key,value in @masking_config do
      @masking_config[key]["regex"] = Regexp.compile(@masking_config[key]["regex"])
    end
  end
  
  if @hashing_config
    for key,value in @hashing_config do
      @hashing_config[key]["regex"] = Regexp.compile(@hashing_config[key]["regex"])
    end
  end

  if @logtype_config.has_key?'filterConfig'
    for field,rules in @logtype_config['filterConfig'] do
      temp = []
      for value in @logtype_config['filterConfig'][field]['values'] do
        temp.push(Regexp.compile(value))
      end
      @logtype_config['filterConfig'][field]['values'] = temp.join('|') 
    end
  end  
  
  @s247_tz = {'hrs': 0, 'mins': 0} #UTC
  @log_source = Socket.gethostname
  @valid_logtype = true
  @log_upload_allowed = true
  @log_upload_stopped_time = 0
  @s247_datetime_format_string = @logtype_config['dateFormat']
  @s247_datetime_format_string = @s247_datetime_format_string.sub('%f', '%N')
  if !@s247_datetime_format_string.include? 'unix'
    @is_year_present = if @s247_datetime_format_string.include?('%y') || @s247_datetime_format_string.include?('%Y') then true else false end
    if !@is_year_present
  @s247_datetime_format_string = @s247_datetime_format_string+ ' %Y'
    end   
    @is_timezone_present = if @s247_datetime_format_string.include? '%z' then true else false end
    if !@is_timezone_present && @logtype_config.has_key?('timezone')
@s247_datetime_format_string += '%z'
  tz_value = @logtype_config['timezone']
  if tz_value.start_with?('+')
   @s247_tz['hrs'] = Integer('-' + tz_value[1..4])
   @s247_tz['mins'] = Integer('-' + tz_value[3..6])
  elsif tz_value.start_with?('-')
   @s247_tz['hrs'] = Integer('+' + tz_value[1..4])
   @s247_tz['mins'] = Integer('+' + tz_value[3..6])
  end
    end
  end
  Thread.new { timer_task() }
end

#is_filters_matchedObject



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/fluent/plugin/out_site24x7.rb', line 282

def is_filters_matched()
  begin
    if @logtype_config.has_key?'filterConfig'
      @logtype_config['filterConfig'].each do |config,value|
        if @formatted_line[config].scan(Regexp.new(@logtype_config['filterConfig'][config]['values'])).length > 0
          val = true 
        else
          val = false
        end
        if (@formatted_line.has_key?config) && (@logtype_config['filterConfig'][config]['match'] ^ (val))
          return false
        end
      end
    end
  rescue Exception => e
    log.error "Exception occurred in filter: #{e.backtrace}" 
  end
  return true
end

#json_log_applier(line) ⇒ Object



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/fluent/plugin/out_site24x7.rb', line 328

def json_log_applier(line)
  json_log_size=0
  @formatted_line = {}
  @log_fields = {}
  event_obj = if line.is_a?(String) then Yajl::Parser.parse(line) else line end
  @logtype_config['jsonPath'].each do |path_obj|
    value = get_json_value(event_obj, path_obj[if path_obj.has_key?'key' then 'key' else 'name' end], path_obj['type'])
    if value
      @log_fields[path_obj['name']] = value 
      json_log_size+= String(value).bytesize - (if value.class == Array then value.size*20 else 0 end)
    end
  end
  for key,regex in @sub_pattern do
    if @log_fields.has_key?(key)
      matcher = regex.match(@log_fields.delete(key))
      if matcher
        @log_fields.update(matcher.named_captures)
        remove_ignored_fields()
        @formatted_line.update(@log_fields)
      end 
    end
  end
  if !(is_filters_matched())
    return false
  else
    ()
    @formatted_line.update(@log_fields)
    log_line_filter()
    @log_size += json_log_size
    return true
   end
end

#json_log_parser(lines) ⇒ Object



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/fluent/plugin/out_site24x7.rb', line 361

def json_log_parser(lines)
  parsed_lines = []
  lines.each do |line|
    begin
      @logged = false
      if !line.empty?
        if line[0] == '{' && @json_data[-1] == '}'
          if json_log_applier(@json_data)
            parsed_lines.push(@formatted_line)
            end
          @json_data=''
        end
        @json_data += line
      end
    rescue Exception => e
      log.error "Exception in parse_line #{e.backtrace}"
    end
  end
  return parsed_lines
end

#log_line_filterObject



219
220
221
222
223
# File 'lib/fluent/plugin/out_site24x7.rb', line 219

def log_line_filter()
  applyMasking()
  applyHashing()
  getDerivedFields()
end

#log_the_holded_lineObject



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/fluent/plugin/out_site24x7.rb', line 595

def log_the_holded_line()
  @log_size = 0
  if @logged == false
    if (@ml_trace.length>0)
      ml_regex_applier(@ml_trace, @ml_data)
      if @ml_trace_buffer
        if !(@formatted_line.empty?)
          @formatted_line[@message_key] = @formatted_line[@message_key] + @ml_trace_buffer
          @log_size += @ml_trace_buffer.bytesize  
        else
          @ml_trace += @ml_trace_buffer.gsub('\n', '<NewLine>')
          ml_regex_applier(@ml_trace, @ml_data)
        end
        @ml_trace_buffer = ''          
      end    
      @ml_trace = ''
    elsif (@json_data.length>0)
      if !(json_log_applier(@json_data))
        @formatted_line={}
      end
      @json_data = ''
    elsif @old_formatted_line
      @formatted_line.update(@old_formatted_line)
      log_line_filter()
      @log_size += @old_log_size
      @old_formatted_line = {}
      @old_log_size = 0
    end
    @logged = true
    if @format_record
      @custom_parser.format_record()
    end
    if !(@formatted_line.empty?)
      return @formatted_line
    end
  end
  return nil
end

#ml_log_parser(lines) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/fluent/plugin/out_site24x7.rb', line 400

def ml_log_parser(lines)
  parsed_lines = []
  lines.each do |line|
    if !line.empty?
      begin
        @logged = false
        ml_start_matcher = @ml_regex.match(line)
        if ml_start_matcher || @ml_end_line_found
          @ml_found = ml_start_matcher
          @ml_end_line_found = false
          @formatted_line = {}
          if @ml_trace.length > 0 
            begin
                ml_regex_applier(@ml_trace, @ml_data)
                if @ml_trace_buffer && @formatted_line
                    @formatted_line[@message_key] = @formatted_line[@message_key] + @ml_trace_buffer
                    @log_size += @ml_trace_buffer.bytesize
                end
                parsed_lines.push(@formatted_line)
                @ml_trace = ''
                @ml_trace_buffer = ''
                if @ml_found
                  @ml_data = ml_start_matcher.named_captures
                  @log_size += line.bytesize
                else
                    @ml_data = {}
                end
                @ml_count = 0
            rescue Exception => e
              log.error "Exception occurred in ml_parser : #{e.backtrace}"
              end
          elsif @ml_found
            @log_size += line.bytesize
            @ml_data = ml_start_matcher.named_captures
          end
        elsif @ml_found
          if @ml_count < @max_ml_count
            @ml_trace += '<NewLine>' + line
          elsif @ml_end_regex && @ml_end_regex.match(line)
            @ml_end_line_found = True
          elsif (@ml_count - @max_ml_count) < @max_trace_line
            @ml_trace_buffer += "\n" + line
          end
          @ml_count += 1
        end
      rescue Exception => e
        log.error "Exception occurred in ml_parser : #{e.backtrace}"
      end
    end
  end
  return parsed_lines
end

#ml_regex_applier(ml_trace, ml_data) ⇒ Object



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/fluent/plugin/out_site24x7.rb', line 382

def ml_regex_applier(ml_trace, ml_data)
  begin    
    @log_size += @ml_trace.bytesize
    matcher = @s247_custom_regex.match(@ml_trace)  
    @log_fields = matcher.named_captures
    @log_fields.update(@ml_data)
    if @s247_ignored_fields
      remove_ignored_fields()
    end
    ()
    @formatted_line.update(@log_fields)
    log_line_filter()
  rescue Exception => e
    log.error "Exception occurred in ml_parser : #{e.backtrace}"
    @formatted_line = {}
  end
end

#multi_workers_ready?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/fluent/plugin/out_site24x7.rb', line 46

def multi_workers_ready?
  true
end

#parse_lines(lines) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/fluent/plugin/out_site24x7.rb', line 239

def parse_lines(lines)
  parsed_lines = []
  lines.each do |line|
    if !line.empty?
      begin
        @logged = false
        match = line.match(@s247_custom_regex)
        if match
          @formatted_line.update(@old_formatted_line)
          @log_size += @old_log_size
          @old_log_size = line.bytesize
          @log_fields = match&.named_captures
          remove_ignored_fields()
          ()
          @old_formatted_line = @log_fields
          @last_line_matched = true
          @trace_started = false             
        elsif @last_line_matched || @trace_started
          is_date_present = !(line.scan(@datetime_regex).empty?)
          @trace_started = !(is_date_present)
          if !(is_date_present) && @old_formatted_line
            if @old_formatted_line.has_key?(@message_key)
              @old_formatted_line[@message_key] += '\n' + line
              @old_log_size += line.bytesize
              @trace_started = true
              @last_line_matched = false
            end 
          end
        end   
        if @formatted_line.has_key?('_zl_timestamp')
          log_line_filter()
          parsed_lines.push(@formatted_line)
          @formatted_line = {}
        end    
      rescue Exception => e
        log.error "Exception in parse_line #{e.backtrace}"
        @formatted_line = {}
      end
    end
  end
  return parsed_lines
end

#process_http_events(events) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
# File 'lib/fluent/plugin/out_site24x7.rb', line 478

def process_http_events(events)
  @before_time = Time.now
  batches = batch_http_events(events)
  batches.each do |batched_event|
    formatted_events, @log_size = format_http_event_batch(batched_event)
    if (formatted_events.length>0)
      formatted_events = gzip_compress(formatted_events)
      send_logs_to_s247(formatted_events, @log_size)
    end
  end 
end

#remove_ignored_fieldsObject



229
230
231
232
233
# File 'lib/fluent/plugin/out_site24x7.rb', line 229

def remove_ignored_fields()
  @s247_ignored_fields.each do |field_name|
    @log_size -= if @log_fields.has_key?field_name then @log_fields.delete(field_name).bytesize else 0 end
  end
end

#send_logs_to_s247(gzipped_parsed_lines, log_size) ⇒ Object



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/fluent/plugin/out_site24x7.rb', line 543

def send_logs_to_s247(gzipped_parsed_lines, log_size)
    request = Net::HTTP::Post.new @uri.request_uri
    request.body = gzipped_parsed_lines
    @s247_http_client.override_headers["Log-Size"] = @log_size
    sleep_interval = @retry_interval
   begin
      @max_retry.times do |counter|
        need_retry = false
        begin
          response = @s247_http_client.request @uri, request
          resp_headers = response.each_header.to_h

          if response.code == '200'
            if resp_headers.has_key?'LOG_LICENSE_EXCEEDS' && resp_headers['LOG_LICENSE_EXCEEDS'] == 'True'
              log.error "Log license limit exceeds so not able to send logs"
              @log_upload_allowed = false
            @log_upload_stopped_time =Time.now.to_i
            elsif resp_headers.has_key?'BLOCKED_LOGTYPE' && resp_headers['BLOCKED_LOGTYPE'] == 'True'
              log.error "Max upload limit reached for log type"
              @log_upload_allowed = false
            @log_upload_stopped_time =Time.now.to_i
            elsif resp_headers.has_key?'INVALID_LOGTYPE' && resp_headers['INVALID_LOGTYPE'] == 'True'
              log.error "Log type not present in this account so stopping log collection"
            @valid_logtype = false
            else
            @log_upload_allowed = true
              log.debug "Successfully sent logs with size #{gzipped_parsed_lines.size} / #{@log_size} to site24x7. Upload Id : #{resp_headers['x-uploadid']}"
            end
          else
            log.error "Response Code #{resp_headers} from Site24x7, so retrying (#{counter + 1}/#{@max_retry})"
            need_retry = true
          end
        rescue StandardError => e
          log.error "Error connecting to Site24x7. exception: #{e} (#{counter + 1}/#{@max_retry})"
        end

        if need_retry
          if counter == @max_retry - 1
            log.error "Could not send your logs after #{max_retry} tries"
            break
          end
          sleep(sleep_interval)
          sleep_interval *= 2
        else
          return
        end
      end
    rescue Exception => e
      log.error "Exception occurred in sendig logs : #{e.backtrace}"
    end
end

#shutdownObject



60
61
62
# File 'lib/fluent/plugin/out_site24x7.rb', line 60

def shutdown
  super
end

#startObject



54
55
56
57
58
# File 'lib/fluent/plugin/out_site24x7.rb', line 54

def start
  super
  init_variables()
  init_http_client(@logtype_config)
end

#terminateObject



64
65
66
67
# File 'lib/fluent/plugin/out_site24x7.rb', line 64

def terminate
  super
  @s247_http_client.shutdown if @s247_http_client
end

#timer_taskObject



734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/fluent/plugin/out_site24x7.rb', line 734

def timer_task()
  while true
    @after_time = Time.now
    if @before_time
      diff = @after_time-@before_time
      if diff.to_i > 29
        out = log_the_holded_line()
        if out != nil
          out = Yajl.dump([out])
          out = gzip_compress(out)
          send_logs_to_s247(out, @log_size)
        end
      end
    end
    sleep(30)
  end
end

#write(chunk) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
476
# File 'lib/fluent/plugin/out_site24x7.rb', line 465

def write(chunk)
  begin
  events = Array.new
  chunk.msgpack_each do |record|
 next if record.empty?
 events.push record[0]
  end
  process_http_events(events)
  rescue Exception => e
    log.error "Exception #{e.backtrace}"
  end
end