Giter Club home page Giter Club logo

zabbixapi's Introduction

Ruby Zabbix Api Module

Gem Version Build Status

Simple and lightweight ruby module for working with Zabbix via the Zabbix API

Installation

# latest
gem install zabbixapi

# specific version
gem install zabbixapi -v 4.2.0

Documentation

http://rdoc.info/gems/zabbixapi

Examples

https://github.com/express42/zabbixapi/tree/master/examples

Version Policy

NOTE: master branch is used for ongoing development on Zabbix API 5.x (5.0 and 5.2).

We support only two last versions of zabbix (5.0 and 5.2), so you should consider all previous versions deprecated.

Supported Ruby Versions

This library aims to support and is tested against the following Ruby versions:

  • Ruby 2.5
  • Ruby 2.6
  • Ruby 2.7
  • JRuby 9.2.10.0

If something doesn't work on one of these versions, it's a bug.

This library may inadvertently work (or seem to work) on other Ruby versions, however support will only be provided for the versions listed above.

If you would like this library to support another Ruby version or implementation, you may volunteer to be a maintainer. Being a maintainer entails making sure all tests run and pass on that implementation. When something breaks on your implementation, you will be responsible for providing patches in a timely fashion. If critical issues for a particular implementation exist at the time of a major release, support for that Ruby version may be dropped.

Dependencies

  • net/http
  • json

Contributing

  • Fork the project.
  • Base your work on the master branch.
  • Make your feature addition or bug fix, write tests, write documentation/examples.
  • Commit, do not mess with rakefile, version.
  • Make a pull request.

Zabbix documentation

Copyright

See LICENSE for details.

zabbixapi's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zabbixapi's Issues

update_users test failing in usergroup spec

Failures:
  1) usergroup when exists update_users should return id
     Failure/Error: expect(zbx.usergroups.update_users(
     ZabbixApi::ApiError:
       Server answer API error
        {
         "code": -32602,
         "message": "Invalid params.",
         "data": "User \"user_173031892\" cannot be without user group."
       }
        on request:
        {
         "method": "usergroup.massUpdate",
         "params": {
           "usrgrpids": [
             22
           ],
           "userids": [
             10
           ]
         },
         "id": 85502,
         "jsonrpc": "2.0",
         "auth": "6ce62ce56e1b30330aced4f1f0402aa3"
       }
     # ./lib/zabbixapi/client.rb:90:in `_request'
     # ./lib/zabbixapi/client.rb:95:in `api_request'
     # ./lib/zabbixapi/classes/usergroups.rb:72:in `update_users'
     # ./spec/usergroup.rb:55:in `block (4 levels) in <top (required)>'

Interact with TLSv1

I use zabbixapi with puppet (via https://forge.puppetlabs.com/wdijkerman/zabbix) so the following may be slightly abstracted...

When my zabbix web frontend is configured to disable TLSV1:

SSLProtocol ALL -SSLv2 -SSLv3 -TLSV1

I receive SSL_connect errors:

Error: /Stage[main]/Zabbix::Resources::Web/Zabbix_host[kickstart.example.com]: Could not evaluate: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A

If I remove the -TLSV1 and restart httpd, I no longer receive the SSL_connect errors. I can otherwise interact with the zabbix web frontend via https and the SYSCALL error string shows up in numerous ruby projects, so I believe this is an issue with the zabbixapi gem itself. Let me know if I can do anything else to help troubleshoot this.

Support HTTPS in zabbix connect

Currently the connect function doesn't support https which seem to be the cause of the error Net::HTTPBadResponse: wrong status line: "" when a connection is tried on a Zabbix installation using https. It will help a lot of installations if https support is available.

Update: Browsing through the code, l see the logic to handle https. But when I make the following connect request, it fails with the HTTPBadResponse typical to making https request. BTW through curl the user.authenticate/user.login request is successful for the URL/User/Password combination.

zbx = ZabbixApi.connect(:url => "https://10.0.100.5:7777/api_jsonrpc.php",:user => "Admin",:password => "siurguhskjfh", :debug => true)
[DEBUG] Send request: {"method":"user.authenticate","params":{"user":"Admin","password":"siurguhskjfh"},"auth":null,"id":49137,"jsonrpc":"2.0"}
[DEBUG] Timeout for request set to 60 seconds
Net::HTTPBadResponse: wrong status line: ""
from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http/response.rb:41:in read_status_line' from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http/response.rb:28:inread_new'
from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:1408:in block in transport_request' from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:1405:incatch'
from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:1405:in transport_request' from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:1378:inrequest'
from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:1371:in block in request' from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:853:instart'
from /Users/zabbix/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/net/http.rb:1369:in request' from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi/client.rb:76:inhttp_request'
from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi/client.rb:84:in _request' from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi/client.rb:90:inapi_request'
from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi/client.rb:19:in auth' from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi/client.rb:36:ininitialize'
from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi.rb:43:in new' from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi.rb:43:ininitialize'
from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi.rb:31:in new' from /Users/zabbix/.rvm/gems/ruby-2.1.2/gems/zabbixapi-2.2.0/lib/zabbixapi.rb:31:inconnect'
from (irb):8
from /Users/zabbix/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `

'2.1.2 :009 >

Update sometimes won't

In abbixapi 2.4.3 the hosts.update command sometimes fails to update the host. For example:

Zbx.hosts.update(
:hostid => 11114,
:host => 'MYHOSTNAME',
:interfaces => [
{
:type => 1,
:main => 1,
:ip => '10.0.0.1',
:useip => 1
}
]
)

If the host already exists and already has some sort of address associated with it, this will fail and debug output will report "equal keys" and "skip update".

I believe the reason for this is that the logic that tests for whether or not there are actually changes to perform only looks at the key side of the kv pairs that define the host. It does not look into the value side, and in this case the value side is a whole structure so testing for differences would need to traverse and compare the entirety of the value side as well.

It might make sense to make the change sensing logic optional (or remove it), as doing complete inspection for difference detection would likely a good deal of complexity, and as the audience using this code is going to be people who know how to write code, I'm not sure how worth while comprehensive difference testing is.

no applications.get method?

I need to be able to test whether or not the application already exists when adding an item.
The zabbix api has application.get and application.exists, but it seems these are not supported in this library. I am pretty new to ruby, so have no idea how to add this functionality. Could someone do that pretty easily?

I'd like to be able to do something like this:

app = "foo"
if zbx.applications.exists(:name => "#{app}", :hostid => id)
  app_id = zbx.applications.get(:name => "#{app}", :hostid => id)
else
  app_id = zbx.applications.create(:name => "#{app}", :hostid => id)
end

Add support for Zabbix API version 3.0.0

Zabbix 3.0.0 is out since about a week, but zabbixapi cannot connect to it:
Zabbix API version: 3.0.0 is not support by this version of zabbixapi (ZabbixApi::ApiError)

Update Groups via zbx.hosts.update

This is what i'm trying to run

zbx.hosts.update(
            :hostid  =>  zbx.hosts.get_id(:host => "hostname"),
            :groups => [ :groupid => 12],

        )

The command completes silently but the group is not updated. I get the following when debug is true

[DEBUG] Equal keys {:hostid=>"10136", :proxy_hostid=>"0", :host=>"hostname", :status=>"0", :disable_until=>"0", :error=>"", :available=>"1", :errors_from=>"0", :lastaccess=>"0", :ipmi_authtype=>"0", :ipmi_privilege=>"2", :ipmi_username=>"", :ipmi_password=>"", :ipmi_disable_until=>"0", :ipmi_available=>"0", :snmp_disable_until=>"0", :snmp_available=>"0", :maintenanceid=>"0", :maintenance_status=>"0", :maintenance_type=>"0", :maintenance_from=>"0", :ipmi_errors_from=>"0", :snmp_errors_from=>"0", :ipmi_error=>"", :snmp_error=>"", :jmx_disable_until=>"0", :jmx_available=>"0", :jmx_errors_from=>"0", :jmx_error=>"", :name=>"hostname", :flags=>"0", :templateid=>"0", :description=>""} and {:hostid=>10136, :groups=>[{:groupid=>12}]}, skip update

It seems the current code can't handle a change of group, looks like there is two places which are causing problems, firstly in the normalize_hash function the array is deleted.

 def normalize_hash(hash)
      result = hash.dup
      result.delete(:hostid) #TODO remove to logig. TemplateID and HostID has different id 
      result.each do |key, value|
        case value
          when Array
            result.delete(key)
          else
            result[key] = value.to_s
        end
      end
      result
    end

Also the code never retrieves a list of host groups to compare to the only data pulled down is

Send request: {"method":"host.get","params":{"filter":{"host":"hostname"},"output":"extend"},"id":16595,"jsonrpc":"2.0","auth":"ea76bb5ebf32728ab518af7daef6bd55"}
Get answer: {"jsonrpc":"2.0","result":[{"hostid":"10136","proxy_hostid":"0","host":"hostname","status":"0","disable_until":"0","error":"","available":"1","errors_from":"0","lastaccess":"0","ipmi_authtype":"0","ipmi_privilege":"2","ipmi_username":"","ipmi_password":"","ipmi_disable_until":"0","ipmi_available":"0","snmp_disable_until":"0","snmp_available":"0","maintenanceid":"0","maintenance_status":"0","maintenance_type":"0","maintenance_from":"0","ipmi_errors_from":"0","snmp_errors_from":"0","ipmi_error":"","snmp_error":"","jmx_disable_until":"0","jmx_available":"0","jmx_errors_from":"0","jmx_error":"","name":"hostname","flags":"0","templateid":"0","description":""}],"id":16595}

This means that when the hashes are compared the keys are equal and the code failed to update.
Something like this does work though when you define a variable that is retrieved in the host.get call

zbx.hosts.update(
            :hostid  =>  zbx.hosts.get_id(:host => "hostname"),
            :groups => [ :groupid => 12],
            :name => "test"

        )

hostgroup.massadd

Hello,
it is hostgroup mass methods covered with this gem or i am missing something? Eg. this method. Thank you.

Branch inconsistencies

I know these versions are deprecated but your older branches seem a bit wonky. zabbix2.2 is at some point after 2.4.9 while zabbix2.4 is at 2.4.5. Please straighten these out. zabbix2.0 seems okay. I'm not sure about zabbix1.8.

Usermacros update not working

When attempting to update usermacros I'm receiving an error about the number of arguments.

It looks like the update methods do not accept any arguments for some reason?

    def create(data)
      request(data, "usermacro.create", "hostmacroids")
    end

    def create_global(data)
      request(data, "usermacro.createglobal", "globalmacroids")
    end

    def delete(data)
      request(data, "usermacro.delete", "hostmacroids")
    end

    def delete_global(data)
      request(data, "usermacro.deleteglobal", "globalmacroids")
    end

    def update
      request(data, "usermacro.update", "hostmacroids")
    end

    def update_global
      request(data, "usermacro.updateglobal", "globalmacroids")
    end

No support for zabbix 2.4

I know your docs clearly state 2.2 is supported and no mention of 2.4.. But i figured i'd put this on your roadmap for later... user.authenticate is a deprecated alias of user.login

When running the ZabbixApi code, you get back an _request': Server answer API error: (RuntimeError)

 {
  "code": -32602,
  "message": "Invalid params.",
  "data": "Incorrect method \"user.authenticate\"."
}

I can submit a PR for this if you are okay.. I checked and user.login exists back to v2.0 of the zabbix API. I forked your repo and I am making changes as I go along and find incompatibilities between API versions.

Unable to add interfaces to a host

Hi, I've got a node already configured with an agent interface and would like to add an snmp interface:

      @zbx_api.hosts.update({
        hostid: zbx_host_id,
        interfaces: [
          {
            type: 3,
            main: 1,
            ip: 10.10.10.10,
            dns: '',
            port: 623,
            useip: 1
          },
          {
            type: 1,
            main: 1,
            ip: '10.111.2.50',
            dns: 'example.com',
            port: 10050,
            useip: 1
          }
        ]
      }, true)

The Zabbix API mentions that the update method replaces all interfaces, so I submit the existing one + the one I want to have added (first one). This results in an error method:

`_request': Server answer API error (ZabbixApi::ApiError)
 {
  "code": -32602,
  "message": "Invalid params.",
  "data": "Interface is linked to item \"Total memory\" on \"example.com\"."
}
 on request:
 {
  "method": "host.update",
  "params": [
    {
      "hostid": 10084,
      "interfaces": [
        {
          "type": 3,
          "main": 1,
          "ip": "10.111.20.50",
          "dns": "",
          "port": 623,
          "useip": 1
        },
        {
          "type": 1,
          "main": 1,
          "ip": "10.111.2.50",
          "dns": 'example.com',
          "port": 10050,
          "useip": 1
        }
      ]
    }
  ],
  "id": 26143,
  "jsonrpc": "2.0",
  "auth": "ea6ee299ab47fb17542938d1a92c7d6c"
}

I also tried to only submit the new interface, but this results in the same error.

  • Can you tell me why the error is happening?
  • Do I need to submit all existing interfaces in your gem or do you handle that internally?
  • Do you've got any method that returns all existing interfaces on a node? I couldn't find one

New maintainer needed!

Sorry everyone but it turned out that we are not going to use Zabbix after all so I can't work on maintaining this module.

If anyone want to do this then please write a comment here so that the owner of the repo can approve your proposal.

retrieving action filters and operators

I couldn't find a way to access filters/operators for a given action;
Looking at the official docs (https://www.zabbix.com/documentation/3.2/manual/api/reference/action/get)
I believe you have to add a selectFilter or selectOperations param to go about it, is there a way to merge those into my query?

ex:

zbx.actions.get(name: 'Mail ambari alerts', selectFilter: true)
[
    [0] {
                "actionid" => "9",
                    "name" => "Mail ambari alerts",
             "eventsource" => "0",
                  "status" => "0",
              "esc_period" => "3600",
           "def_shortdata" => "[UAT] Service critical issue",
            "def_longdata" => "{TRIGGER.URL}\r\n{TRIGGER.NAME}\r\n\r\nHost: {HOST.NAME1}\r\n\r\nIssue: {ITEM.NAME1} \r\n\r\nLink: ({ITEM.KEY1})\r\n\r\nSeverity: {ITEM.VALUE1}\r\n\r\nOriginal event ID: {EVENT.ID}",
             "r_shortdata" => "{TRIGGER.STATUS}: {TRIGGER.NAME}",
              "r_longdata" => "Trigger: {TRIGGER.NAME}\r\nTrigger status: {TRIGGER.STATUS}\r\nTrigger severity: {TRIGGER.SEVERITY}\r\nTrigger URL: {TRIGGER.URL}\r\n\r\nItem values:\r\n\r\n1. {ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}): {ITEM.VALUE1}\r\n2. {ITEM.NAME2} ({HOST.NAME2}:{ITEM.KEY2}): {ITEM.VALUE2}\r\n3. {ITEM.NAME3} ({HOST.NAME3}:{ITEM.KEY3}): {ITEM.VALUE3}\r\n\r\nOriginal event ID: {EVENT.ID}",
        "maintenance_mode" => "1"
    }
]

graph history

Are there any plans to implement grabbing of graph history?

usergroup.massadd is deprecated in 4.x and should be replaced by usergroup.update

After updating our Zabbix servers to version 4.0.5 I'm experiencing this error:

/usr/local/rvm/gems/ruby-2.3.1/gems/zabbixapi-4.1.0/lib/zabbixapi/client.rb:127:in `_request': Server answer API error (ZabbixApi::ApiError)
 {
  "code": -32602,
  "message": "Invalid params.",
  "data": "Incorrect method \"usergroup.massAdd\"."
}
 on request:
 {
  "method": "usergroup.massAdd",
  "params": {
    "usrgrpids": [
      54
    ],
    "rights": [
      {
        "permission": 2,
        "id": "1"
      },
   ..
      {
        "permission": 2,
        "id": "197"
      }
    ]
  },
  "id": 10757,
  "jsonrpc": "2.0",
  "auth": “xxx”
}
from /usr/local/rvm/gems/ruby-2.3.1/gems/zabbixapi-4.1.0/lib/zabbixapi/client.rb:145:in `api_request'
from /usr/local/rvm/gems/ruby-2.3.1/gems/zabbixapi-4.1.0/lib/zabbixapi/classes/usergroups.rb:32:in `set_perms'

which is a result of the deprecation of 'usergroup.massadd, usergroup.massupdate' among others. see:

hosts.create_or_update hash_equals

Hi! I'm using hosts.create_or_update but it's failing to update the host in Zabbix.

I'm attempting to update the groupids and templateids with a host using this method.

With debug turned on I see the following:

[DEBUG] Equal keys {:templates=>[{:templateid=>"0", :hostid=>"0"}], :maintenances=>[], :hostid=>"10967", :proxy_hostid=>"0", :host=>"op1-testwebapp01a.aue1s", :status=>"1", :disable_until=>"0", :error=>"", :available=>"0", :errors_from=>"0", :lastaccess=>"0", :ipmi_authtype=>"0", :ipmi_privilege=>"2", :ipmi_username=>"", :ipmi_password=>"", :ipmi_disable_until=>"0", :ipmi_available=>"0", :snmp_disable_until=>"0", :snmp_available=>"0", :maintenanceid=>"0", :maintenance_status=>"0", :maintenance_type=>"0", :maintenance_from=>"0", :ipmi_errors_from=>"0", :snmp_errors_from=>"0", :ipmi_error=>"", :snmp_error=>"", :jmx_disable_until=>"0", :jmx_available=>"0", :jmx_errors_from=>"0", :jmx_error=>"", :name=>"op1-testwebapp01a.aue1s", :flags=>"0"} and {:host=>"op1-testwebapp01a.aue1s", :interfaces=>[{:type=>1, :main=>1, :ip=>"0.0.0.0", :dns=>"op1-testwebapp01a.aue1s.example.com", :port=>10050, :useip=>0}], :groups=>[{:groupid=>2}, {:groupid=>7}, {:groupid=>39}, {:groupid=>24}], :templates=>[{:templateid=>10278}, {:templateid=>10173}, {:templateid=>10001}, {:templateid=>10376}, {:templateid=>10688}, {:templateid=>10055}], :hostid=>10967}, skip update

Even though you can see the new group and templates, it still says skip update. Am I using this incorrectly?

How I'm calling it.

      @zbx.hosts.create_or_update(
        :host => host,
        :interfaces => [
          {
            :type => 1,
            :main => 1,
            :ip => "0.0.0.0",
            :dns => dnsname,
            :port => port,
            :useip => 0
          }
        ],
        :groups => groupids,
        :templates => templateids
      )

create_or_update multiple groups

Is it possible to create or update a host with multiple host groups?

This seems to work for templates but not for groups. Can you provide an example of adding multiple groups to a host?

options[:no_proxy] has no value

When I tried to use the no_proxy option to bypass the proxy, it didn't delivered it correctly.
It doesn't appear in the initialize function in the client.rb

# Initializes a new Client object
    #
    # @param options [Hash]
    # @return [ZabbixApi::Client]
def initialize(options = {})

      @options = options
      if !ENV['http_proxy'].nil? && options[:no_proxy] != true
        @proxy_uri = URI.parse(ENV['http_proxy'])
        @proxy_host = @proxy_uri.host
        @proxy_port = @proxy_uri.port
        @proxy_user, @proxy_pass = @proxy_uri.userinfo.split(/:/) if @proxy_uri.userinfo
      end
      unless api_version =~ /(2\.4|3\.[02])\.\d+/
        raise ApiError.new("Zabbix API version: #{api_version} is not support by this version of zabbixapi")
      end
      @auth_hash = auth
    end

zabbixapi version

I think we need to support zabbixapi version 2.4.x for zabbix 2.4 with ruby 1.9.3, and version 3 with ruby 2 for zabbix 3.*. Any remarks?

items.create_or_update not working

Hi there, I have the below method in a module, and it fails with the error below every time. Do you have any idea? Thanks for making this gem!

def self.item args
Zbx::Conn.items.create_or_update(
:description => args[:description],
:key => args[:key],
:type => args[:type],
:hostid => Zbx::Conn.templates.get_id(:host => args[:template]),
:applications => [Zbx::Conn.applications.get_id(:name => args[:application])]
)
end

results in:

/Users/pmispagel/.rvm/gems/ruby-1.9.3-p448/gems/zabbixapi-2.0.0/lib/zabbixapi/client.rb:77:in http_request': HTTP Error: 500 on http://10.51.131.7/zabbix/api_jsonrpc.php (RuntimeError) from /Users/pmispagel/.rvm/gems/ruby-1.9.3-p448/gems/zabbixapi-2.0.0/lib/zabbixapi/client.rb:84:in_request'
from /Users/pmispagel/.rvm/gems/ruby-1.9.3-p448/gems/zabbixapi-2.0.0/lib/zabbixapi/client.rb:90:in api_request' from /Users/pmispagel/.rvm/gems/ruby-1.9.3-p448/gems/zabbixapi-2.0.0/lib/zabbixapi/basic/basic_logic.rb:51:inget_full_data'
from /Users/pmispagel/.rvm/gems/ruby-1.9.3-p448/gems/zabbixapi-2.0.0/lib/zabbixapi/basic/basic_logic.rb:87:in get_id' from /Users/pmispagel/.rvm/gems/ruby-1.9.3-p448/gems/zabbixapi-2.0.0/lib/zabbixapi/basic/basic_logic.rb:24:increate_or_update'
from zbx_selenium.rb:53:in item' from zbx_selenium.rb:115:in

'

Can't get application ID by name and host ID

applications.get_id doesn't filter with params such as hostids.

> z.connection.applications.get_id(name: 'Processes', hostids: z.host_id)
 => 4893

The ID returned above is simply the ID of the last element in the array as if we did z.connection.applications.get_full_data(name: 'Processes').

Constructing the query properly:

> z.connection.query(method: 'application.get', params: { filter: { name: 'Processes' }, hostids: z.host_id })
 => [{"hosts"=>[{"hostid"=>"10356"}], "applicationid"=>"3790", "hostid"=>"10356"}]

3790 is the correct application ID in this circumstance.

From the documentation regarding the filter parameter:

Accepts an array, where the keys are property names, and the values are either a single value or an array of values to match against.

I'm not that familiar with the API, but it seems like filter refers to properties of the application itself and not API parameters.
Is filtering by parameters as well as properties something that could fit into this gem? If so, I'd be happy to work on a PR.

create_or_update() not updating to include new graph items unless graph required attribute changes

I am trying to update a zabbix graph to include a new graph item. The graph will not update to add my new graph item unless a required graph attribute such as width or height has changed. Below is my example of existing item itemid"=>"3294310 and adding new item itemid"=>"3294370.

If the graph width or height attributes don't change (graph currently configured with same width and height) then the new itemid does not get included. However, if I make the same call and update either the width or the height (other than 900X200) then the new item id itemid"=>"3294370 will be updated on my graph along with the width/height update.

Ideally this should be updating the graph items if new or existing items are updated without needing to update the graphs height or width.

  zbx.graphs.create_or_update(
    :gitems => [{"gitemid"=>"3037936", "graphid"=>"673302", "itemid"=>"3294310", "drawtype"=>"0", "sortorder"=>"0", "color"=>"1A7C11", "yaxisside"=>"0", "calc_fnc"=>"2", "type"=>"0"},
                {"itemid"=>"3294370", "color"=>"0ab2f1"}],
    :name => graph_name,
    :width => "900",
    :height => "200",
  )

Add support for Zabbix 4.0

Zabbix API version: 4.0.0 is not support by this version of zabbixapi

Please add support for this Zabbix version that has recently been released as stable.

Issue with hosts.delete

Hi,

It seems API has changed a bit.
In documentation (https://www.zabbix.com/documentation/2.2/manual/api/reference/host/delete):

    "method": "host.delete",
    "params": [
        "13",
        "32"
    ],

zabbixapi's request:

  "method": "host.delete",
  "params": [
    {
      "hostid": {
        "hostid": 11593
      }
    }
  ],

So we getting this error:

* Removing from monitoring.../opt/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/zabbixapi-2.2.1/lib/zabbixapi/client.rb:85:in `_request': Server answer API error: (RuntimeError)
 {
  "code": -32500,
  "message": "Application error.",
  "data": "No permissions to referred object or it does not exist!"
}
 on request:
 {
  "method": "host.delete",
  "params": [
    {
      "hostid": {
        "hostid": 11593
      }
    }
  ],
  "auth": "**************************************",
  "id": 80122,
  "jsonrpc": "2.0"
}
        from /opt/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/zabbixapi-2.2.1/lib/zabbixapi/client.rb:90:in `api_request'
        from /opt/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/zabbixapi-2.2.1/lib/zabbixapi/basic/basic_logic.rb:17:in `delete'
        from /opt/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/zabbixapi-2.2.1/lib/zabbixapi/classes/hosts.rb:45:in `delete'
        from /home/ec2tools/ec2tools/zabbix.rb:41:in `remove'
        from /home/ec2tools/ec2tools/zabbix.rb:112:in `<main>

host.update fails when assigning a template to a host that already has that template

Wondering if host.update could just warn and skip over if a template is already assigned to the host, rather than just fail hard.

/usr/local/share/gems1.9/gems/zabbixapi-0.6.4/lib/zabbixapi/client.rb:85:in `_request': Server answer API error: (RuntimeError)
 {
  "code": -32602,
  "message": "Invalid params.",
  "data": "Interface is linked to item \"Zabbix:agent:ping\" on \"host-test\"."
}
 on request:
 {
  "method": "host.update",
  "params": {
    "host": "host-test",
    "hostid": 10851,
    "status": 1,
    "interfaces": [
      {
        "type": 1,
        "main": 1,
        "useip": 0,
        "ip": "0.0.0.0",
        "dns": "host-test",
        "port": "10050"
      }
    ],
    "groups": [
      {
        "groupid": 2
      },
      {
        "groupid": 34
      },
      {
        "groupid": 10
      }
    ],
    "templates": [
      {
        "templateid": 10228
      },
      {
        "templateid": 10001
      },
      {
        "templateid": 10287
      }
    ]
  },
  "auth": "57510d7f92fc1ccb60bc1eaad4735e5f",
  "id": 27796,
  "jsonrpc": "2.0"
}
    from /usr/local/share/gems1.9/gems/zabbixapi-0.6.4/lib/zabbixapi/client.rb:90:in `api_request'
    from /usr/local/share/gems1.9/gems/zabbixapi-0.6.4/lib/zabbixapi.rb:18:in `query'
    from ./zabbix-update-host:50:in `<main>'

Action API (NoMethodError)

I think there is a problem in the 'actions' section of this zabbixapi ruby wrapper. I have been trying to create an action using:
zbx.actions.create

But I keep getting the following error:

1
10001
./action-template-test.rb:14:in `<main>': undefined method `actions' for #<ZabbixApi:0x000000020e44b0> (NoMethodError)

The first two numbers:
1 and 10001 I have displayed just so I know that I am actually connected to the server and able to run queries on it.

I get the same error if I run:
zbx.action.create

Any ideas on what is going on or what I can do to get this to run?

Here is the code that I am running:

#!/usr/bin/env ruby

require "zabbixapi"

zbx = ZabbixApi.connect(
                :url => 'http://localhost/zabbix/api_jsonrpc.php',
                :user => 'Admin',
                :password => 'zabbix'
)

puts zbx.hostgroups.get_id( :name => "Templates")
puts zbx.templates.get_id( :host => "Template OS Linux" )

zbx.actions.create(
  :name => "Register ALL - Hosts",
  :eventsource => '2',                    # event source is a triggerid
  :status => '0',                         # action is enabled
  :esc_period => '120',                   # how long each step should take
  :filter => {
      :evaltype => '2',                   # perform 'and' between the conditions
      :conditions => [
          {
              :conditiontype => '22',
              :operator => '2',
              :value => '.'
          },
          {
              :conditiontype => '22',
              :operator => '2',
              :value => '-'
          }
      ]
  },
  :operations => [
      {
          :operationtype => '2'              # send message
      },
      {
          :operationtype => '6',
          :optemplate => [
                { :templateid => zbx.templates.get_id( :host => "Template OS Linux" ) },
                { :templateid => zbx.templates.get_id( :host => "Template Debian" ) }
          ]
      }
  ]
)

Undefined method error when zabbix has an unsupported version

For example :
[1] pry(#ZabbixApi::Client)> api_version
=> "3.2.6"

Result:
NoMethodError: undefined methodlog' for #ZabbixApi::Client:0x0000000001b5a878
Did you mean? load
from .... gems/ruby-2.6.3/gems/zabbixapi-4.1.1/lib/zabbixapi/client.rb:56:in initialize'

Basic authentication fails

HTTP basic authentication does not seem to work for me when using http_user and http_password for connecting to a 1.8 Zabbix server. I get a 401 error although the credentials seem to be passed to the intermediate web server.

My environment…

I'm running a Zabbix server behind an Apache with mod_auth. My htpasswd has a user "john" with password "doe". The Apache config looks like:

<Location /zabbix>
    AuthType Basic
    AuthName "Zabbix Apache Login"
    AuthUserFile /etc/apache2/htpasswd
    Require valid-user
</Location>

/etc/apache2/htpasswd looks like:

john:uDJoI7HCjer9.

I have also created a user "john" with password "doe" in Zabbix.

I'm using this minimal Ruby script to authenticate against Zabbix:

#!/usr/bin/env ruby
require "zabbixapi"
zbx = ZabbixApi.connect(
  :url => 'http://10.13.0.32/zabbix/api_jsonrpc.php',
  :user => 'john',
  :password => 'doe',
  :http_password => 'john',
  :http_user => 'doe',
  :debug => true
)

However it seems that the basic authentication is not passed through properly because this script fails with:

[DEBUG] Send request: {"method":"user.authenticate","params":{"user":"john","password":"doe"},"auth":null,"id":47329,"jsonrpc":"2.0"}
[DEBUG] Timeout for request set to 60 seconds
/home/chaas/.rvm/gems/ruby-2.0.0-p247/gems/zabbixapi-0.6.4/lib/zabbixapi/client.rb:77:in `http_request': HTTP Error: 401 on http://10.13.0.32/zabbix/api_jsonrpc.php (RuntimeError)

I have recorded the HTTP session and this is what Wireshark gave me:

POST /zabbix/api_jsonrpc.php HTTP/1.1
Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept: */*
User-Agent: Ruby
Authorization: Basic ZG9lOmpvaG4=
Content-Type: application/json-rpc
Connection: close
Host: 10.13.0.32
Content-Length: 111

{"method":"user.authenticate","params":{"user":"john","password":"doe"},"auth":null,"id":33605,"jsonrpc":"2.0"}HTTP/1.1 401 Authorization Required

Date: Fri, 07 Feb 2014 17:04:24 GMT
Server: Apache/2.2.16 (Debian)
WWW-Authenticate: Basic realm="Zabbix Apache Login"
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 342
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<hr>
<address>Apache/2.2.16 (Debian) Server at 10.13.0.32 Port 80</address>
</body></html>

Failing to get_or_create host due to parameters as array instead of hash?

Having trouble with Zabbix API in 3.0 and 3.2 when get_or_create hosts. Here's the error:

/Library/Ruby/Gems/2.0.0/gems/zabbixapi-2.4.7/lib/zabbixapi/client.rb:90:in `_request': Server answer API error (ZabbixApi::ApiError)
 {
  "code": -32602,
  "message": "Invalid params.",
  "data": "Incorrect arguments passed to function."
}
 on request:
 {
  "method": "host.create",
  "params": [
    {
      "host": "jrbeilke.com",
      "interfaces": [
        {
          "type": 1,
          "main": 1,
          "useip": 0,
          "dns": "zabbix.jrbeilke.com",
          "port": "10050"
        }
      ],
      "status": 0,
      "available": 1,
      "groups": [
        {
          "groupid": "94"
        }
      ],
      "proxy_hostid": null
    }
  ],
  "id": 186,
  "jsonrpc": "2.0",
  "auth": "9a41234f712f35fa98e672b301238bcab"
}

Looks like it's complaining that zabbixapi is sending the params as an array instead of a hash when using hosts.get_or_create():

zabbixhostid = zabbixapi.hosts.get_or_create(
        :host => "jrbeilke.com",
        :interfaces => [
          {
            :type => 1,
            :main => 1,
            :useip => 0,
            :dns => "zabbix.jrbeilke.com",
            :port => "10050"
          }
        ],
        :groups => [
          {
            :groupid => "94"
          }
        ]
      )

Enhancement req: Support for actions

Implementing support for Zabbix actions will let users send emails on triggers defined. With "triggers" and "media" already being supported this enhancement will help users fully leverage the zabbixapi gem to implement an end to end monitoring and alerting use case using Zabbix.

changed output for zbx.templates.get_ids_by_host

The README.md mentions a hash, I'm on Zabbix 2.4 and it returns an Array with the IDs only:

[19] pry(main)> zbx.templates.get_ids_by_host( :hostids => [zbx.hosts.get_id(:host => "example.com")] )
=> ["10104", "10102", "10047", "10050", "19814", "10001"]

items.get_id fails on large item number?

Hi,

I'm struggling to make item.get_id to work (to use in item.update). It fails with
PHP Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 76 bytes) in /usr/share/zabbix/include/db.inc.php on line 644
Seems similar to this issue:
https://www.zabbix.com/forum/showthread.php?t=42200

Anyway, it would be possibly good if there was a way to do some sort of partial searches, limiting the result set.

JSON dependency error in 2.4.9

We are getting an error when we attempt to go to any version of chef-client above 12.15.9 when using the 2.4.9 branch. It appears there is a JSON change in chef-client that is conflicting with the JSON here. We are seeing the following:

Gem::ConflictError: carfax_zabbix_api_host[ip-172-26-210-38.w.cdc.cfx] (carfax_zabbix_api::default line 47) had an error: Gem::ConflictError: Unable to activate zabbixapi-2.4.9, because json-2.0.2 conflicts with json (>= 1.6.0, ~> 1.6)

I see talk about JSON2 support, but it appears that is only for the 3.0.x branches - is that correct?

Is project still active?

I'm asking myself if the maintainer of this project is still active? I've opened a PR #86 in the end of march and did not get any response.

@postgred, are you looking for support for maintaining this repo?

get_id() is not specific enough for template items when doing create_or_update()

We're using zabbixapi to keep our Zabbix templates in-sync and up-to-date, but we're having an issue when trying to use create_or_update() on templated items.

Here's the code we're using to create/update one of the items on our templates:

templateid = zabbixapi.templates.create_or_update(
  :host => 'zabbix-templates_aws_ec2-metadata',
  :groups => [:groupid => @zabbixapi.hostgroups.get_or_create(:name => 'zabbix-templates')]
)

zabbixapi.items.create_or_update(
  :name => 'ami-id',
  :description => 'Captures the AMI ID from AWS and adds it to the host inventory under the &quot;OS (Short)&quot; tag.',
  :key_ => 'curl[http://169.254.169.254/latest/meta-data/ami-id]',
  :delay => 60,
  :type => 7, #Zabbix agent (active)
  :value_type => 1, #Character
  :history => 7,
  :trends => 365,
  :inventory_link => 7, #OS (Short)
  :hostid => templateid,
  :applications => [@zabbixapi.applications.get_or_create(:name => 'EC2', :hostid => templateid)]
)

Looks like create_or_update() makes a call to get_id() to find the itemid, but the filter on that query is not specific enough to only pull the itemid attached to the template. Instead get_id() pulls the itemid from one of the hosts linked to the template instead, since the item gets copied to the hosts using that template.

  result = @client.api_request(
    :method => "#{method_name}.get",
    :params => {
      :filter => {
        indentify.to_sym => name
      },
      :output => [key, indentify]
    }
  )
  id = nil
  result.each { |item| id = item[key].to_i if item[indentify] == data[indentify.to_sym] }
  id

Apiinfo.version call with auth param - version 2.2

The Zabbix documentation for 2.2 version says the 'auth' param shouldn't be given when calling the apiinfo.version method although it won't result in an error until 2.4:

2.2 : (https://www.zabbix.com/documentation/2.2/manual/api/reference/apiinfo/version)

2.4 for comparison (https://www.zabbix.com/documentation/2.4/manual/api/reference/apiinfo/version)

I'm running the API version 2.2 and still getting the error caused by this:

 {
  "code": -32602,
  "message": "Invalid params.",
  "data": "Not authorized"
}
 on request:
 {
  "method": "apiinfo.version",
  "params": {
  },
  "auth": "xxxxxxxxxxxxxxxxx",
  "id": 6456,
  "jsonrpc": "2.0"
} (RuntimeError)
  /usr/local/bundle/gems/zabbixapi-2.2.4/lib/zabbixapi/client.rb:85:in `_request'

This bug was corrected in 2.4 version. Can it be backported to 2.2?

Please document .get*() method usage

I'm really struggling trying to figure out what to pass into the get() methods to get anything other than "everything". Would you please provide an example or two of what to actually pass into these methods? I've looked through your examples - they seem all to do with creating and updating. I hate to have to resort to .query if you've already got something nice in place to handle it. Thanks.

Unable to add template with zbx.hosts.update

I want to add a template to a node:

@zbx_api.hosts.update({
  hostid: :10084,
  templates: [
    templateid: 19814
  ]
})

which results in:

[DEBUG] Call update with parametrs: {:hostid=>10084, :templates=>[{:templateid=>19814}]}
[DEBUG] Call dump_by_id with parametrs: {:hostid=>10084}
[DEBUG] Send request: {"method":"host.get","params":{"filter":{"hostid":10084},"output":"extend","selectGroups":"shorten"},"id":44709,"jsonrpc":"2.0","auth":"1dd71d610eafa3f2772a91388b70efc8"}
[DEBUG] Timeout for request set to 60 seconds
[DEBUG] Get answer: {"jsonrpc":"2.0","result":[{"hostid":"10084","proxy_hostid":"0","host":"example.com","status":"0","disable_until":"0","error":"","available":"1","errors_from":"0","lastaccess":"0","ipmi_authtype":"-1","ipmi_privilege":"2","ipmi_username":"","ipmi_password":"","ipmi_disable_until":"0","ipmi_available":"0","snmp_disable_until":"0","snmp_available":"0","maintenanceid":"0","maintenance_status":"0","maintenance_type":"0","maintenance_from":"0","ipmi_errors_from":"0","snmp_errors_from":"0","ipmi_error":"","snmp_error":"","jmx_disable_until":"0","jmx_available":"0","jmx_errors_from":"0","jmx_error":"","name":"example.com","flags":"0","templateid":"0","description":"","groups":[{"groupid":"4"},{"groupid":"11"}]}],"id":44709}
[DEBUG] Equal keys {:hostid=>"10084", :proxy_hostid=>"0", :host=>"example.com", :status=>"0", :disable_until=>"0", :error=>"", :available=>"1", :errors_from=>"0", :lastaccess=>"0", :ipmi_authtype=>"-1", :ipmi_privilege=>"2", :ipmi_username=>"", :ipmi_password=>"", :ipmi_disable_until=>"0", :ipmi_available=>"0", :snmp_disable_until=>"0", :snmp_available=>"0", :maintenanceid=>"0", :maintenance_status=>"0", :maintenance_type=>"0", :maintenance_from=>"0", :ipmi_errors_from=>"0", :snmp_errors_from=>"0", :ipmi_error=>"", :snmp_error=>"", :jmx_disable_until=>"0", :jmx_available=>"0", :jmx_errors_from=>"0", :jmx_error=>"", :name=>"example.com", :flags=>"0", :templateid=>"0", :description=>"", :groups=>[{:groupid=>"4"}, {:groupid=>"11"}]} and {:hostid=>10084, :templates=>[{:templateid=>19814}]}, skip update

the zbx.query call works:

      params = {
        hostid: 10084,
        templates: [
          {
            templateid: 19814,
          }
        ]
      }
          @zbx_api.query(
            method: 'host.update',
            params: params
          )

debug log:

[DEBUG] Send request: {"method":"host.update","params":{"hostid":10084,"templates":[{"templateid":19814}]},"id":73712,"jsonrpc":"2.0","auth":"b39ac74d7c74bf6ef0a299c2f40ce42b"}
[DEBUG] Timeout for request set to 60 seconds
[DEBUG] Get answer: {"jsonrpc":"2.0","result":{"hostids":[10084]},"id":73712}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.