Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

can create new hosts on zabbix

  • Loading branch information...
commit 66bbfabfdcb421e0ad6750547663f4fa2f53bb38 1 parent 11a72dc
@neerfri authored
View
39 lib/rzabbix.rb
@@ -2,7 +2,42 @@ module RZabbix
end
-require 'rzabbix/version'
+require 'rzabbix/connection'
require 'rzabbix/base'
require 'rzabbix/host'
-require 'rzabbix/host_group'
+require 'rzabbix/host_group'
+require 'rzabbix/template'
+require 'rzabbix/version'
+
+class Hash
+
+ def rzbx_symbolize_keys
+ inject({}) do |options, (key, value)|
+ options[(key.to_sym rescue key) || key] = value
+ options
+ end
+ end
+
+
+ def rzbx_recursively_symbolize_keys
+ result = self.rzbx_symbolize_keys
+ result.keys.each do |key|
+ if result[key].is_a?(Hash) || result[key].is_a?(Array)
+ result[key] = result[key].rzbx_recursively_symbolize_keys
+ end
+ end
+ result
+ end
+end
+
+class Array
+ def rzbx_recursively_symbolize_keys
+ self.map do |item|
+ if item.is_a?(Hash) || item.is_a?(Array)
+ item.rzbx_recursively_symbolize_keys
+ else
+ item
+ end
+ end
+ end
+end
View
103 lib/rzabbix/base.rb
@@ -7,105 +7,32 @@ module RZabbix
class Base
- class ResponceCodeError < StandardError; end
-
- class << self
- attr_accessor :credentials
- attr_accessor :use_ssl
- attr_accessor :auth
- end
-
- self.use_ssl = false
-
- def self.set_credentials(api_url, api_user, api_password)
- self.credentials = {:api_url=>api_url, :api_user=>api_user, :api_password=>api_password}
+ def self.perform_request(*args)
+ Connection.perform_request(*args)
end
- def self.next_request_id
- @request_id = @request_id ? @request_id+1 : 1
- end
+ ###########################################################################################################
+ # Instance methods
+ ###########################################################################################################
- def self.auth
- @auth ||= begin
- auth_message = {
- 'auth' => nil,
- 'method' => 'user.authenticate',
- 'params' => {
- 'user' => Base.credentials[:api_user],
- 'password' => Base.credentials[:api_password],
- '0' => '0'
- }
- }
- do_request(auth_message)
- end
- end
+ attr_accessor :attributes
-
- def self.perform_request(action, params)
- message = message_for(self.resource_name, action, params)
- do_request(message)
+ def initialize(attributes)
+ super()
+ self.attributes = self.class.default_attributes.merge(attributes)
end
- def self.message_for(controller, action, params = {})
- {
- 'method' => "#{controller}.#{action}",
- 'params' => params,
- 'auth' => Base.auth
- }
+ def [](key)
+ self.attributes[key.to_sym]
end
- def self.do_request(message)
- id = next_request_id
-
- message['id'] = id
- message['jsonrpc'] = '2.0'
-
- message_json = JSON.generate(message)
-
- uri = URI.parse(Base.credentials[:api_url])
- http = Net::HTTP.new(uri.host, uri.port)
- if (use_ssl)
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
- end
-
- request = Net::HTTP::Post.new(uri.request_uri)
- request.add_field('Content-Type', 'application/json-rpc')
- request.body=(message_json)
- responce = http.request(request)
-
- if ( responce.code != "200" ) then
- raise ResponceCodeError.new("Responce code from [" + credentials[:api_url] + "] is " + responce.code)
- end
-
- responce_body_hash = JSON.parse(responce.body)
-
- #if not ( responce_body_hash['id'] == id ) then
- # raise Zabbix::InvalidAnswerId.new("Wrong ID in zabbix answer")
- #end
-
-
- # Check errors in zabbix answer. If error exist - raise exception Zabbix::Error
- if ( error = responce_body_hash['error'] ) then
- error_message = error['message']
- error_data = error['data']
- error_code = error['code']
-
- e_message = "Code: [" + error_code.to_s + "]. Message: [" + error_message +\
- "]. Data: [" + error_data + "]."
-
- raise StandardError.new(e_message)
- end
-
- responce_body_hash['result']
+ def to_json(*args)
+ self.attributes.to_json(*args)
end
-
- def initialize(attributes)
- super()
- self.attributes = default_attributes.merge(attributes)
+ def to_hash
+ self.attributes
end
-
end
end
View
108 lib/rzabbix/connection.rb
@@ -0,0 +1,108 @@
+module RZabbix
+
+ class Connection
+
+ API_OUTPUT_SHORTEN = "shorten"
+ API_OUTPUT_REFER = "refer"
+ API_OUTPUT_EXTEND = "extend"
+
+ class ResponseCodeError < StandardError; end
+
+ class << self
+ attr_accessor :credentials
+ attr_accessor :use_ssl
+ attr_accessor :auth
+ end
+
+ self.use_ssl = false
+
+ def self.set_credentials(api_url, api_user, api_password)
+ self.credentials = {:api_url=>api_url, :api_user=>api_user, :api_password=>api_password}
+ end
+
+ def self.next_request_id
+ @request_id = @request_id ? @request_id+1 : 1
+ end
+
+ def self.auth
+ @auth ||= begin
+ auth_message = {
+ 'auth' => nil,
+ 'method' => 'user.authenticate',
+ 'params' => {
+ 'user' => Connection.credentials[:api_user],
+ 'password' => Connection.credentials[:api_password],
+ '0' => '0'
+ }
+ }
+ do_request(auth_message)
+ end
+ end
+
+
+ def self.perform_request(controller, action, params)
+ message = message_for(controller, action, params)
+ do_request(message)
+ end
+
+ def self.message_for(controller, action, params = {})
+ {
+ 'method' => "#{controller}.#{action}",
+ 'params' => params.to_hash.merge(:output=>API_OUTPUT_EXTEND),
+ 'auth' => Connection.auth
+ }
+ end
+
+ def self.do_request(message)
+ id = next_request_id
+
+ message['id'] = id
+ message['jsonrpc'] = '2.0'
+
+ message_json = JSON.generate(message)
+
+ #puts "#{JSON.parse(message_json).inspect}\n\n\n"
+
+ uri = URI.parse(Connection.credentials[:api_url])
+ http = Net::HTTP.new(uri.host, uri.port)
+ if (use_ssl)
+ http.use_ssl = true
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
+ end
+
+ request = Net::HTTP::Post.new(uri.request_uri)
+ request.add_field('Content-Type', 'application/json-rpc')
+ request.body=(message_json)
+ responce = http.request(request)
+
+ if ( responce.code != "200" ) then
+ raise ResponseCodeError.new("Responce code from [" + credentials[:api_url] + "] is " + responce.code)
+ end
+
+ responce_body_hash = JSON.parse(responce.body)
+
+ #if not ( responce_body_hash['id'] == id ) then
+ # raise Zabbix::InvalidAnswerId.new("Wrong ID in zabbix answer")
+ #end
+
+
+ # Check errors in zabbix answer. If error exist - raise exception Zabbix::Error
+ if ( error = responce_body_hash['error'] ) then
+ error_message = error['message']
+ error_data = error['data']
+ error_code = error['code']
+
+ e_message = "Code: [" + error_code.to_s + "]. Message: [" + error_message +\
+ "]. Data: [" + error_data + "]."
+
+ raise StandardError.new(e_message)
+ end
+
+ result = responce_body_hash['result']
+ result.respond_to?(:rzbx_recursively_symbolize_keys) ? result.rzbx_recursively_symbolize_keys : result
+ end
+
+
+ end
+
+end
View
64 lib/rzabbix/host.rb
@@ -2,49 +2,30 @@ module RZabbix
class Host < Base
- attr_accessor :attributes
-
- # attr_accessor :hostid
- # attr_accessor :host
- # attr_accessor :port
- # attr_accessor :status
- # attr_accessor :useip
- # attr_accessor :dns
- # attr_accessor :ip
- # attr_accessor :proxy_hostid
- # attr_accessor :useipmi
- # attr_accessor :ipmi_ip
- # attr_accessor :ipmi_port
- # attr_accessor :ipmi_authtype
- # attr_accessor :ipmi_privilege
- # attr_accessor :ipmi_username
- # attr_accessor :ipmi_password
-
+ def self.find(host_id)
+ hosts = perform_request(:host, :get, :hostids=>[host_id], :output=>"extend")
+ self.new(hosts.first.rzbx_recursively_symbolize_keys) unless hosts.empty?
+ end
def self.find_host_id_by_hostname(hostname)
- hosts = perform_request(:get, 'filter' => {'host'=>hostname})
- hosts.first["hostid"]
+ hosts = perform_request(:host, :get, :filter => {:host=>hostname})
+ hosts.first[:hostid]
end
def self.find_by_hostname(hostname)
- #host_id = find_host_id_by_hostname(hostname)
- hosts = perform_request(:get, 'filter' => {'host'=>hostname}, "output"=>"extend")
+ hosts = perform_request(:host, :get, :filter => {:host=>hostname}, :output=>"extend")
self.new(hosts.first) unless hosts.empty?
end
def self.create(attributes)
- groups = attributes.delete(:groups)
- hosts = perform_request(:create, "host data"=>attributes, "groups"=>groups)
- self.new(attributes)
- end
-
- def self.resource_name
- "host"
+ host = self.new(attributes)
+ result = perform_request(:host, :create, host)
+ result && result[:hostids] ? self.find(result[:hostids].first) : nil
end
- def default_attributes
- {
- :hostid=>nil, #int Host ID
+ def self.default_attributes
+ {
+ #:hostid=>nil, #int Host ID
:host=>nil, #string Host name.
:port=>10050, #int Port number.
:status=>0, #int Host Status.
@@ -57,11 +38,26 @@ def default_attributes
:ipmi_port=>623, #int IPMI port.
:ipmi_authtype=>0, #int IPMI authentication type.
:ipmi_privilege=>0, #int IPMI privilege.
- :ipmi_username=>'', #string IPMI username.
- :ipmi_password=>'' #string IPMI password.
+ :ipmi_username=>'', #string IPMI username.
+ :ipmi_password=>'' #string IPMI password.
}
end
+ def to_hash(*args)
+ host_hash = self.attributes.inject({}) do |hash, (attr, v)|
+ case attr.to_sym
+ when :groups
+ hash[:groups] = v.map {|g| { :groupid=>g.attributes[:groupid]}}
+ when :templates
+ hash[:templates] = v.map {|t| {:templateid=>t.attributes[:templateid]}}
+ else
+ hash[attr] = v
+ end
+ hash
+ end
+ host_hash
+ end
+
end
end
View
66 lib/rzabbix/host_group.rb
@@ -2,35 +2,53 @@ module RZabbix
class HostGroup < Base
- attr_accessor :attributes
-
def self.find_by_name(name)
- groups = perform_request(:get, 'filter' => {'name'=>name}, "output"=>"extend")
- self.new(groups.first) unless groups.empty?
+ groups = perform_request(:hostgroup, :get, :filter => {:name=>name}, :output=>"extend")
+ self.new(groups.first.rzbx_recursively_symbolize_keys) unless groups.empty?
end
- def self.resource_name
- "hostgroup"
+ def self.default_attributes
+ {
+ :nodeids => nil,
+ :groupids => nil,
+ :hostids => nil,
+ :templateids => nil,
+ :graphids => nil,
+ :triggerids => nil,
+ :maintenanceids => nil,
+ :monitored_hosts => nil,
+ :templated_hosts => nil,
+ :real_hosts => nil,
+ :not_proxy_hosts => nil,
+ :with_items => nil,
+ :with_monitored_items => nil,
+ :with_historical_items => nil,
+ :with_triggers => nil,
+ :with_monitored_triggers => nil,
+ :with_httptests => nil,
+ :with_monitored_httptests => nil,
+ :with_graphs => nil,
+ :editable => nil,
+ :nopermissions => nil
+
+# :filter => nil,
+# :pattern => '',
+#
+# :output => Connection::API_OUTPUT_REFER,
+# :extendoutput => nil,
+# :select_hosts => nil,
+# :select_templates => nil,
+# :count => nil,
+# :preservekeys => nil,
+# :sortfield => '',
+# :sortorder => '',
+# :limit => nil,
+# :limitSelects => nil
+ }
end
- def default_attributes
- {
- :hostid=>nil, #int Host ID
- :host=>nil, #string Host name.
- :port=>10050, #int Port number.
- :status=>0, #int Host Status.
- :useip=>0, #int Use IP.
- :dns=>'', #string DNS.
- :ip=>'0.0.0.0', #string IP.
- :proxy_hostid=> 0, #int Proxy Host ID.
- :useipmi=> 0 , #int Use IPMI.
- :ipmi_ip=>'', #string IPMAI IP.
- :ipmi_port=>623, #int IPMI port.
- :ipmi_authtype=>0, #int IPMI authentication type.
- :ipmi_privilege=>0, #int IPMI privilege.
- :ipmi_username=>'', #string IPMI username.
- :ipmi_password=>'' #string IPMI password.
- }
+ def to_json(*args)
+ self.attributes.to_json(*args)
end
end
View
55 lib/rzabbix/template.rb
@@ -0,0 +1,55 @@
+module RZabbix
+
+ class Template < Base
+
+ def self.find_by_name(name)
+ templates_hash = perform_request(:template, :get, :filter => {:host=>name}, :output=>"extend")
+ if templates_hash.kind_of?(Hash) && !templates_hash.keys.empty?
+ template_hash = templates_hash[templates_hash.keys.first]
+ self.new(template_hash.rzbx_recursively_symbolize_keys)
+ end
+ end
+
+ def self.default_attributes
+ {
+ :nodeids => nil,
+ :groupids => nil,
+ :templateids => nil,
+ :parentTemplateids => nil,
+ :hostids => nil,
+ :graphids => nil,
+ :itemids => nil,
+ :triggerids => nil,
+ :with_items => nil,
+ :with_triggers => nil,
+ :with_graphs => nil,
+ :editable => nil,
+ :nopermissions => nil
+
+# :filter => nil,
+# :pattern => '',
+#
+# :output => API_OUTPUT_REFER,
+# :extendoutput => nil,
+# :select_groups => nil,
+# :select_hosts => nil,
+# :select_templates => nil,
+# :selectParentTemplates => nil,
+# :select_items => nil,
+# :select_triggers => nil,
+# :select_graphs => nil,
+# :select_applications => nil,
+# :select_macros => nil,
+# :countOutput => nil,
+# :groupCount => nil,
+# :preservekeys => nil,
+# :sortfield => '',
+# :sortorder => '',
+# :limit => nil,
+# :limitSelects => nil
+ }
+ end
+
+ end
+
+end
View
32 test.html
@@ -1,32 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>ZABBIX</title>
- <meta name="Author" content="ZABBIX SIA" />
- <link rel="shortcut icon" href="images/general/zabbix.ico" />
- <link rel="stylesheet" type="text/css" href="css.css" />
-<!--[if IE 6]>
- <script type="text/javascript" src="js/ie6fix.js"></script>
- <link rel="stylesheet" type="text/css" href="styles/ie.css" />
-<![endif]-->
-
-<link rel="stylesheet" type="text/css" href="styles/default.css" />
-<!--[if IE 6]><link rel="stylesheet" type="text/css" href="styles/ie_default.css" /><![endif]-->
-<script type="text/javascript"> var PHP_TZ_OFFSET = -28800;</script>
-<script type="text/javascript" src="jsLoader.php?ver=1.8.3&lang=en_gb"></script>
-</head>
-<body onload="zbxCallPostScripts();">
-<table class="page_header" cellspacing="0" cellpadding="5"><tr><td class="page_header_l"><a class="image" href="http://www.zabbix.com/" target="_blank"><div class="zabbix_logo">&nbsp;</div></a></td><td class="page_header_r" width="100%"><a class="small_font" href="http://www.zabbix.com/documentation/" target="_blank">Help</a>|<a class="small_font" href="http://www.zabbix.com/support.php" target="_blank">Get support</a>|<a class="small_font" href="/?print=1&amp;sid=670f2d8f8a4e946d">Print</a>|<a class="small_font" href="index.php?reconnect=1">Login</a></td></tr></table><div id="mmenu"><table cellspacing="0" cellpadding="0" style="width: 100%;"><tr><td><table class="menu" cellspacing="0" cellpadding="5"><tr><td class="horizontal_menu_n" id="view" onclick="javascript: redirect('dashboard.php');" onmouseover="javascript: MMenu.mouseOver(&quot;view&quot;);" onmouseout="javascript: MMenu.mouseOut();">Monitoring</td><td class="horizontal_menu_n" id="cm" onclick="javascript: redirect('hostprofiles.php');" onmouseover="javascript: MMenu.mouseOver(&quot;cm&quot;);" onmouseout="javascript: MMenu.mouseOut();">Inventory</td><td class="horizontal_menu_n" id="reports" onclick="javascript: redirect('report2.php');" onmouseover="javascript: MMenu.mouseOver(&quot;reports&quot;);" onmouseout="javascript: MMenu.mouseOut();">Reports</td></tr></table></td><td align="right"></td></tr></table><table class="sub_menu" cellspacing="0" cellpadding="5"><tr><td><div id="sub_view" onmouseover="javascript: MMenu.submenu_mouseOver();" onmouseout="javascript: MMenu.mouseOut();" style="display: none;"><a class="highlight nowrap" href="dashboard.php?sid=670f2d8f8a4e946d">Dashboard</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="overview.php?sid=670f2d8f8a4e946d">Overview</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="httpmon.php?sid=670f2d8f8a4e946d">Web</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="latest.php?sid=670f2d8f8a4e946d">Latest data</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="tr_status.php?sid=670f2d8f8a4e946d">Triggers</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="events.php?sid=670f2d8f8a4e946d">Events</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="charts.php?sid=670f2d8f8a4e946d">Graphs</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="screens.php?sid=670f2d8f8a4e946d">Screens</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="maps.php?sid=670f2d8f8a4e946d">Maps</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="srv_status.php?sid=670f2d8f8a4e946d">IT services</a><span class="divider">&nbsp; | &nbsp;</span></div><div id="sub_cm" onmouseover="javascript: MMenu.submenu_mouseOver();" onmouseout="javascript: MMenu.mouseOut();" style="display: none;"><a class="highlight nowrap" href="hostprofiles.php?sid=670f2d8f8a4e946d">Hosts</a><span class="divider">&nbsp; | &nbsp;</span></div><div id="sub_reports" onmouseover="javascript: MMenu.submenu_mouseOver();" onmouseout="javascript: MMenu.mouseOut();" style="display: none;"><a class="highlight nowrap" href="report2.php?sid=670f2d8f8a4e946d">Availability report</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="report5.php?sid=670f2d8f8a4e946d">Most busy triggers top 100</a><span class="divider">&nbsp; | &nbsp;</span><a class="highlight nowrap" href="report6.php?sid=670f2d8f8a4e946d">Bar reports</a><span class="divider">&nbsp; | &nbsp;</span></div><div id="sub_empty" style="display: block;">&nbsp;</div></td></tr></table></div><br/>
-<form method="post" action="index.php?login=1" enctype="multipart/form-data" accept-charset="utf-8" name="web.index.login" id="web.index.login"><table class="formtable" cellspacing="0" cellpadding="1" align=""><tr class="header"><td class="form_row_first" colspan="2"><div class="iconhelp menu_icon" title="http://www.zabbix.com/documentation" onclick="window.open(&quot;http://www.zabbix.com/documentation/&quot;);" style="float:right; text-decoration: none;">&nbsp;</div>Login</td></tr><input type="hidden" name="sid" id="sid" value="670f2d8f8a4e946d" /><input type="hidden" name="form_refresh" id="form_refresh" value="1" /><input type="hidden" name="form" id="form" value="1" /><tr><td class="form_row_l">Login&nbsp;name</td><td class="form_row_r"><input class="biginput" name="name" id="name" type="text" size="20" value="" style="width: 150px" /></td></tr><tr><td class="form_row_l">Password</td><td class="form_row_r"><input class="biginput" name="password" id="password" type="password" size="20" value="" style="width: 150px" /></td></tr><tr class="footer"><td class="form_row_last" colspan="2">&nbsp;<input type="submit" value="Enter" class="button" id="enter" name="enter" /></td></tr></table></form><script type="text/javascript">// <![CDATA[
-document.forms["web.index.login"].elements["name"].focus();
-// ]]></script><table class="page_footer" cellspacing="0" cellpadding="1"><tr><td class="page_footer_l"><a class="highlight" href="http://www.zabbix.com">Zabbix&nbsp;1.8.3&nbsp;Copyright 2001-2010 by&nbsp;SIA Zabbix</a></td><td class="page_footer_r"><span class="divider">&nbsp;&nbsp;|&nbsp;&nbsp;</span><span class="footer_sign">Connected as&nbsp;'guest'</span></td></tr></table><script type="text/javascript">// <![CDATA[
-var page_refresh = null;
-function zbxCallPostScripts(){
-var msglistid = initMessages({});
-cookie.init();
-chkbxRange.init();
-if(IE6){ie6pngfix.run(false);}
-}
-
-// ]]></script></body>
-</html>
View
16 test.rb
@@ -1,18 +1,26 @@
require 'rubygems'
require 'lib/rzabbix'
-RZabbix::Base.set_credentials("http://zabbix.applicaster.com/api_jsonrpc.php", "api_user", "api_pass")
+RZabbix::Connection.set_credentials("http://zabbix.applicaster.com/api_jsonrpc.php", "api_user", "api_pass")
def find_or_create_group(name)
RZabbix::HostGroup.find_by_name(name)
end
-def find_or_create_host(hostname)
+def find_or_create_host(hostname, groups, templates)
host = RZabbix::Host.find_by_hostname(hostname)
if !host
puts "Creating new Host"
- host = RZabbix::Host.create(:host=>hostname, :groups=>[RZabbix::HostGroup.find_by_name("Application servers")])
+ host = RZabbix::Host.create(:host=>hostname, :dns=>hostname, :groups=>groups, :templates=>templates)
end
+ host
end
-find_or_create_host("my-new-host-f394ec9e.us-east-1a.applicaster.com")
+groups = ["Application servers"].map {|name| RZabbix::HostGroup.find_by_name(name) || raise("group '#{name} not found") }
+#puts "\n\nFound #{groups.size} groups:\n" + groups.map {|g| g.inspect}.join($/)
+
+#templates = ["Template_Applicaster_Passenger"].map {|name| RZabbix::Template.find_by_name(name) || raise("template '#{name} not found") }
+templates = []
+
+host = find_or_create_host("my-new-host-f394ec9e.us-east-1a.applicaster.com", groups, templates)
+puts "Host: #{host.attributes[:host].inspect}"
Please sign in to comment.
Something went wrong with that request. Please try again.