Class: ZCollective::ZabbixClient

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ZabbixClient

Returns a new instance of ZabbixClient.



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/zcollective/zabbixclient.rb', line 43

def initialize ( options = {} )
    @options   = options

    @log = Logger.new(STDERR)
    if( @options[:debug] )
        @log.level = Logger::DEBUG
    else
        @log.level = Logger::WARN
    end

    @auth_hash = authenticate

end

Instance Method Details

#authenticateObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/zcollective/zabbixclient.rb', line 57

def authenticate ( )

    @version = request( 'apiinfo.version' )

    major, minor, patch = @version.split('.')

    # login method name changed after 2.0
    if major.to_i >= 2 && minor.to_i > 0
         = 'user.login'
    else
         = 'user.authenticate'
    end

    response = request( ,  
        :user     => @options[:user], 
        :password => @options[:password] 
    )

end

#request(method, *args) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/zcollective/zabbixclient.rb', line 94

def request( method, *args ) 

    json = request_json( method, *args )

    uri  = URI.parse( @options[:url] )
    proxy = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : OpenStruct.new
    http = Net::HTTP::Proxy(proxy.host, proxy.port).new( uri.host, uri.port )
    http_timeout = @options[:http_timeout]
    http.read_timeout = http_timeout unless http_timeout.nil?

    request = Net::HTTP::Post.new( uri.request_uri )
    request.add_field( 'Content-Type', 'application/json-rpc' )
    request.body = json

    @log.debug( "HTTP Request: #{uri} #{json}" )

    response = http.request( request )

    unless response.code == "200"
        raise "HTTP Error: #{response.code}"
    end

    @log.debug( "HTTP Response: #{response.body}" )

    result = JSON.parse( response.body )

    if result['error']
        raise "JSON-RPC error: #{result['error']['message']} (#{result['error']['data']})"
    end

    result['result']

end

#request_json(method, *args) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/zcollective/zabbixclient.rb', line 77

def request_json( method, *args )

    req = {
        :jsonrpc => '2.0',
        :method  => method,
        :params  => Hash[*args.flatten],
        :id      => rand( 100000 )
    }

    if @auth_hash
        req[:auth] = @auth_hash
    end

    JSON.generate( req )

end