Class: Fluent::WatchProcessInput

Inherits:
Input
  • Object
show all
Includes:
HandleTagNameMixin, Mixin::RewriteTagName, Mixin::TypeConverter
Defined in:
lib/fluent/plugin/in_watch_process.rb

Defined Under Namespace

Modules: OS

Constant Summary collapse

DEFAULT_KEYS =
%w(start_time user pid parent_pid cpu_time cpu_percent memory_percent mem_rss mem_size state proc_name command)
DEFAULT_TYPES =
"pid:integer,parent_pid:integer,cpu_percent:float,memory_percent:float,mem_rss:integer,mem_size:integer"

Instance Method Summary collapse

Constructor Details

#initializeWatchProcessInput

Returns a new instance of WatchProcessInput.



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

def initialize
  super
  require 'time'
end

Instance Method Details

#configure(conf) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/fluent/plugin/in_watch_process.rb', line 32

def configure(conf)
  super

  @command = @command || get_ps_command
  @keys = @keys.nil? ? DEFAULT_KEYS : @keys.to_s.gsub(' ', '').split(',')
  @lookup_user = @lookup_user.gsub(' ', '').split(',') unless @lookup_user.nil?
  @interval = Config.time_value(@interval)
  $log.info "watch_process: polling start. :tag=>#{@tag} :lookup_user=>#{@lookup_user} :interval=>#{@interval} :command=>#{@command}"
end

#get_ps_commandObject



76
77
78
79
80
81
82
# File 'lib/fluent/plugin/in_watch_process.rb', line 76

def get_ps_command
  if OS.linux?
    "LANG=en_US.UTF-8 && ps -ewwo lstart,user:20,pid,ppid,time,%cpu,%mem,rss,sz,s,comm,cmd"
  elsif OS.mac?
    "LANG=en_US.UTF-8 && ps -ewwo lstart,user,pid,ppid,time,%cpu,%mem,rss,vsz,state,comm,command"
  end
end

#runObject



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

def run
  loop do
    io = IO.popen(@command, 'r')
    io.gets
    while result = io.gets
      keys_size = @keys.size
      if result =~ /(?<lstart>(^\w+\s+\w+\s+\d+\s+\d\d:\d\d:\d\d \d+))/
        lstart = Time.parse($~[:lstart])
        result = result.sub($~[:lstart], '')
        keys_size -= 1
      end
      values = [lstart.to_s, result.chomp.strip.split(/\s+/, keys_size)]
      data = Hash[@keys.zip(values.reject(&:empty?).flatten)]
      data['elapsed_time'] = (Time.now - Time.parse(data['start_time'])).to_i if data['start_time']
      next unless @lookup_user.nil? || @lookup_user.include?(data['user'])
      emit_tag = tag.dup
      filter_record(emit_tag, Engine.now, data)
      Engine.emit(emit_tag, Engine.now, data)
    end
    io.close
    sleep @interval
  end
  rescue StandardError => e
    $log.error "watch_process: error has occured. #{e.message}"
end

#shutdownObject



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

def shutdown
  Thread.kill(@thread)
end

#startObject



42
43
44
# File 'lib/fluent/plugin/in_watch_process.rb', line 42

def start
  @thread = Thread.new(&method(:run))
end