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.



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

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:



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

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.



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

def debug
  @debug
end

#uriObject (readonly)

Returns the value of attribute uri.



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

def uri
  @uri
end

Instance Method Details

#authenticateObject



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

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

#http_post_request(post_body) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/zapix/zabbix_rpc_client.rb', line 33

def http_post_request(post_body)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  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

  begin
    return http.request(request).body
  rescue
    puts "[DEBUG] Retrying sending request: #{request.body}" if debug
    retry
  end
end

#idObject



54
55
56
# File 'lib/zapix/zabbix_rpc_client.rb', line 54

def id
  rand(100_000)
end

#map_name(name) ⇒ Object



58
59
60
# File 'lib/zapix/zabbix_rpc_client.rb', line 58

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