Class: GRI::ExecCollector

Inherits:
Collector show all
Defined in:
lib/gri/plugin/exec_collector.rb

Constant Summary collapse

MAX_INPUT_SIZE =
8192

Constants inherited from Collector

Collector::TYPES

Instance Attribute Summary

Attributes inherited from Collector

#attached_at, #host, #interval, #loop, #options, #timeout

Instance Method Summary collapse

Methods inherited from Collector

#attach, create, #initialize, #on_detach, #on_error, #on_retry, #on_timeout

Constructor Details

This class inherits a constructor from GRI::Collector

Instance Method Details

#on_attachObject



29
30
31
32
33
34
35
# File 'lib/gri/plugin/exec_collector.rb', line 29

def on_attach
  cmd = options['cmd']
  stdin, stdout, stderr, wait_thr = popen cmd
  stdin.close
  loop.watch stdout, :r, 0, self
  loop.watch stderr, :r, 0, self
end

#on_closeObject



83
84
85
# File 'lib/gri/plugin/exec_collector.rb', line 83

def on_close
  loop.detach self
end

#on_initObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/gri/plugin/exec_collector.rb', line 13

def on_init
  @rbuf = ''
  case options['separator']
  when 'tab'
    @sep = /\t/
  when /^[!"%&,->@-Z_-z]+/
    @sep = Regexp.new options['separator']
  else
    @sep = nil
  end
  if options['out_keys']
    @out_keys = options['out_keys'].split(/\s*,\s*/)
  end
  @transpose = !!options['transpose']
end

#on_read(data) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/gri/plugin/exec_collector.rb', line 53

def on_read data
  @rbuf << data
  records = []
  while true
    break unless @rbuf =~ /\n/
    line, rbuf = @rbuf.split /^/, 2
    @rbuf.replace(rbuf || '')
    line.chomp!
    record = values2record line.split(@sep)
    if @transpose
      records += record.inject([]) {|a, kv|
        a.push({'_host'=>host, '_key'=>"num_#{kv.first}", 'num'=>kv.last})
        a
      }
    else
      record['_host'] = host
      records.push record
    end
  end
  @cb.call records unless records.empty?
end

#on_readable(io = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/gri/plugin/exec_collector.rb', line 41

def on_readable io=nil
  begin
    while data = io.read_nonblock(MAX_INPUT_SIZE)
      on_read data
    end
  rescue Errno::EAGAIN, Errno::EINTR
    loop.watch io, :r, 0, self
  rescue SystemCallError, EOFError, IOError, SocketError
    on_close
  end
end

#popen(cmd) ⇒ Object



37
38
39
# File 'lib/gri/plugin/exec_collector.rb', line 37

def popen cmd
  Open3.popen3 cmd
end

#sync?Boolean

Returns:

  • (Boolean)


11
# File 'lib/gri/plugin/exec_collector.rb', line 11

def sync?; false; end

#values2record(values) ⇒ Object



75
76
77
78
79
80
81
# File 'lib/gri/plugin/exec_collector.rb', line 75

def values2record values
  h = {}
  values.each_with_index {|v, i|
    h[@out_keys[i]] = v if @out_keys[i]
  }
  h
end