Class: MetricsCapacitor::Utils::Graphite

Inherits:
Object
  • Object
show all
Defined in:
lib/metrics-capacitor/utils/graphite.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Graphite

Returns a new instance of Graphite.



11
12
13
14
15
16
17
18
19
20
# File 'lib/metrics-capacitor/utils/graphite.rb', line 11

def initialize(opts)
  Config.load!
  @options = opts
  @metrics = Model::Metrics.new
  begin
    @input = $stdin.readlines
  rescue Interrupt
    $stderr.puts 'Interrupted'
  end
end

Instance Method Details

#apply_tag_map(path) ⇒ Object



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
# File 'lib/metrics-capacitor/utils/graphite.rb', line 27

def apply_tag_map path
  name = []
  autodetect = []
  tags = {}
  map = @options[:tag_map].split '.'
  fields = path.split '.'
  if fields.length < map.length
    $stderr.puts "Map length can't be deeper than source tree length"
  else
    fields.each_with_index do |field, idx|
      next if map[idx] == '_'
      i = Integer(map[idx]) rescue i = map[idx]
      case i
      when nil
        autodetect.push field
      when Integer
        name[i] = field
      when String
        tags[i] = field
      end
    end
  end
  tags['autodetect'] = autodetect.join(':')
  tags.merge! @options[:add_tag]
  return [ name.join(':'), tags ]
end

#debug(msg) ⇒ Object



54
55
56
# File 'lib/metrics-capacitor/utils/graphite.rb', line 54

def debug msg
  $stderr.puts "DEBUG: #{msg}" if @options[:debug]
end

#parse_input!Object



58
59
60
61
62
63
64
# File 'lib/metrics-capacitor/utils/graphite.rb', line 58

def parse_input!
  @input.each do |line|
    fields = line.split(/\s+/)
    ( name, tags ) = apply_tag_map(fields[0]) unless fields.empty?
    @metrics << Model::Metric.new(name: name, tags: tags, values: fields[1].to_f) unless name == ''
  end
end

#run!Object



22
23
24
25
# File 'lib/metrics-capacitor/utils/graphite.rb', line 22

def run!
  parse_input!
  send_metrics!
end

#send_metrics!Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/metrics-capacitor/utils/graphite.rb', line 66

def send_metrics!
  @redis = Redis.new(url: Config.redis[:url])
  msg = JSON.dump({
    'class' => 'MetricsCapacitor::Processor::Scrubber',
    'args' => @metrics.to_redis,
    'jid' => SecureRandom.hex(12),
    'retry' => true,
    'enqueued_at' => Time.now.to_f
  })
  debug "Metrics packet to send"
  debug msg
  begin
    @redis.lpush('queue:scrubber', msg) unless @options[:debug]
    exit 0
  rescue StandardError => e
    $stderr.puts "#{e.class}: #{e.message}"
    $stderr.puts @metrics.to_redis
    exit 1
  end
end