tmm1 (owner)

Forks

Revisions

gist: 168126 Download_button fork
public
Public Clone URL: git://gist.github.com/168126.git
Embed All Files: show embed
stats.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
require 'socket'
require 'rubygems'
require 'collectd/pkt'
 
class Stats
  def initialize name, instance, opts = {}
    @name, @instance = name, instance
 
    @sock = UDPSocket.new
    @sock.connect opts[:host] || '239.192.74.66',
                  opts[:port] || 25826
 
    @hostname = opts[:hostname] || `/bin/hostname -s`.strip
    @interval = opts[:interval] || 10
 
    @counters, @gauges, @counts = {}, {}, {}
  end
 
  def counter_set name, val
    flush_outbound
    @counters[name] = val
  end
 
  def counter_inc name, val
    flush_outbound
    @counters[name] = @counters.has_key?(name) ? @counters[name] + val : val
  end
 
  def gauge_set name, val
    flush_outbound
    @gauges[name] = @gauges.has_key?(name) ? @gauges[name] + val : val
    @counts[name] = @counts.has_key?(name) ? @counts[name] + 1 : 1.0
  end
 
  private
 
  include Collectd
 
  def flush_outbound
    @time ||= Time.now
 
    if @time < Time.now - @interval
      @packet = [
        Packet::Host.new(@hostname),
        Packet::Time.new(@time.to_i),
        Packet::Interval.new(@interval),
        Packet::Plugin.new(@name),
        Packet::PluginInstance.new(@instance)
      ]
 
      @counters.each do |key, val|
        @packet << Packet::Type.new(:counter)
        @packet << Packet::TypeInstance.new(key)
        @packet << Packet::Values.new([ Packet::Values::Counter.new(val) ])
      end
 
      @gauges.each do |key, val|
        @packet << Packet::Type.new(:gauge)
        @packet << Packet::TypeInstance.new(key)
        @packet << Packet::Values.new([ Packet::Values::Gauge.new(val/@counts[key]) ])
      end
      @gauges = {}
      @counts = {}
 
      @sock.send @packet.join(''), 0
 
      @time = Time.now
    end
  end
end
 
if __FILE__ == $0
  s = Stats.new('ruby', 'test', :interval => 1)
 
  s.counter_set(:seconds, 5)
  while sleep(0.1)
    s.counter_inc(:seconds, 1)
    s.gauge_set(:sinwave, Math.sin(Time.now.to_f/60) * 100)
  end
end