Class: ZabbixPusher::Pusher

Inherits:
Object
  • Object
show all
Defined in:
lib/zabbix_pusher.rb

Instance Method Summary collapse

Constructor Details

#initialize(templates, options = {}) ⇒ Pusher

Returns a new instance of Pusher.



33
34
35
36
37
38
39
40
41
# File 'lib/zabbix_pusher.rb', line 33

def initialize(templates, options = {} )
  options[:zabbix_server_name] = 'localhost' unless options[:zabbix_server_name]
  options[:zabbix_server_port] = '10051' unless options[:zabbix_server_port]
  options[:sender_hostname] = Socket.gethostname unless options[:sender_hostname]

  @options = options
  @templates = template_files(templates)
  @items = template_items(@templates)
end

Instance Method Details

#send(items = :all) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/zabbix_pusher.rb', line 67

def send(items = :all)

  return if @items.nil?

  pushers = ( items == :all) ? (@items.keys.map{ |key| "ZabbixPusher::#{key.to_s.camelize}".constantize}) : ["ZabbixPusher::#{items.camelize}".constantize]

  processed_items = Hash.new

  pushers.map do |pusher|
    pusher_key = pusher.to_s.demodulize.underscore.to_sym
    processed_items.update pusher.new(@items[pusher_key],@options[pusher_key]).send(:processed_items)
  end

  zbx  = Zabbix::Sender::Buffer.new :host => @options[:zabbix_server_name], :port => @options[:zabbix_server_port]

  processed_items.each do |key,value|
    zbx.append key, value, :host => @options[:sender_hostname]
  end
  zbx.flush

  processed_items
end

#template_files(templates) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/zabbix_pusher.rb', line 43

def template_files(templates)
  template_files = []
  template_files = Dir.glob(File.join(templates,'*.xml')) if !templates.is_a?(Array) && File.directory?(templates)
  template_files = templates.map{ |template| template if File.exist?(template) }.compact if templates.is_a?(Array)
  template_files =  [templates] if !templates.is_a?(Array) && File.exist?(templates) && !File.directory?(templates)
  template_files
end

#template_items(templates) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/zabbix_pusher.rb', line 51

def template_items(templates)
  parsed_items = Hash.new

  templates.each do |template|
    template_items = Nokogiri::XML(File.open(template))
    items = template_items.xpath('//item').map {|item| item.attributes['key'].text}.compact
    items.each do |item|
        parts = item.match(/([^\[]+)\[([^\]]+)/)
        key = parts[1]
        attributes = parts[2]
        (parsed_items[key.to_sym]) ? parsed_items[key.to_sym] << attributes : parsed_items[key.to_sym] = [attributes]
    end
  end
  parsed_items
end