Class: ZabbixRPCClient

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

Defined Under Namespace

Classes: JSONRPCError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ ZabbixRPCClient

Returns a new instance of ZabbixRPCClient.



9
10
11
12
13
14
15
# File 'lib/zapix/zabbix_rpc_client.rb', line 9

def initialize(options)
  @uri = URI.parse(options[:service_url])
  @username = options[:username]
  @password = options[:password]
  @debug = options[:debug]
  @auth_token = authenticate
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object

Raises:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/zapix/zabbix_rpc_client.rb', line 17

def method_missing(name, *args)
  method_name = map_name(name)

  post_body = {
    'method' => method_name,
    'params' => args.first,
    'id' => id,
    'jsonrpc' => '2.0',
    'auth' => @auth_token 
  }.to_json

  resp = JSON.parse( http_post_request(post_body) )
  raise JSONRPCError, resp['error'] if resp['error']
  puts "[DEBUG] Get answer: #{resp}" if debug
  resp["result"]
end

Instance Attribute Details

#debugObject (readonly)

Returns the value of attribute debug.



7
8
9
# File 'lib/zapix/zabbix_rpc_client.rb', line 7

def debug
  @debug
end

#uriObject (readonly)

Returns the value of attribute uri.



7
8
9
# File 'lib/zapix/zabbix_rpc_client.rb', line 7

def uri
  @uri
end

Instance Method Details

#authenticateObject



43
44
45
# File 'lib/zapix/zabbix_rpc_client.rb', line 43

def authenticate
  ({'user' => @username, 'password' => @password})
end

#http_post_request(post_body) ⇒ Object



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

def http_post_request(post_body)
  http    = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Post.new(uri.request_uri)
  request.content_type = 'application/json'
  request.body = post_body
  puts "[DEBUG] Send request: #{request.body}" if debug
  http.request(request).body
end

#idObject



47
48
49
# File 'lib/zapix/zabbix_rpc_client.rb', line 47

def id
  rand(100000)
end

#map_name(name) ⇒ Object



51
52
53
# File 'lib/zapix/zabbix_rpc_client.rb', line 51

def map_name(name)
 name.to_s.sub('_', '.')
end