From 6d4b46f38a70eaddfb2c3f1557eb00d9005f3cf9 Mon Sep 17 00:00:00 2001 From: Jon Beilke Date: Wed, 19 Apr 2017 15:03:47 -0500 Subject: [PATCH] document all the things! --- .codeclimate.yml | 16 +++ .gitignore | 45 ++++++- .rubocop.yml | 60 +++++++++ .rubocop_todo.yml | 20 +++ .travis.yml | 27 ++-- .yardopts | 9 ++ Gemfile | 18 +++ Gemfile.lock | 88 ++++++++++++- README.md | 2 + Rakefile | 26 +++- lib/zabbixapi.rb | 154 +++++++++++++--------- lib/zabbixapi/basic/basic_alias.rb | 25 +++- lib/zabbixapi/basic/basic_func.rb | 79 +++++++---- lib/zabbixapi/basic/basic_init.rb | 25 +++- lib/zabbixapi/basic/basic_logic.rb | 93 ++++++++++--- lib/zabbixapi/classes/actions.rb | 12 +- lib/zabbixapi/classes/applications.rb | 26 +++- lib/zabbixapi/classes/configurations.rb | 40 +++--- lib/zabbixapi/classes/errors.rb | 8 +- lib/zabbixapi/classes/graphs.rb | 80 ++++++++--- lib/zabbixapi/classes/hostgroups.rb | 16 ++- lib/zabbixapi/classes/hosts.rb | 46 +++++-- lib/zabbixapi/classes/httptests.rb | 28 +++- lib/zabbixapi/classes/items.rb | 29 +++- lib/zabbixapi/classes/maintenance.rb | 12 +- lib/zabbixapi/classes/mediatypes.rb | 33 +++-- lib/zabbixapi/classes/proxies.rb | 37 ++++-- lib/zabbixapi/classes/screens.rb | 66 ++++++---- lib/zabbixapi/classes/server.rb | 12 +- lib/zabbixapi/classes/templates.rb | 89 +++++++------ lib/zabbixapi/classes/triggers.rb | 59 ++++++--- lib/zabbixapi/classes/unusable.rb | 2 - lib/zabbixapi/classes/usergroups.rb | 59 +++++---- lib/zabbixapi/classes/usermacros.rb | 168 +++++++++++++++++++----- lib/zabbixapi/classes/users.rb | 42 ++++-- lib/zabbixapi/client.rb | 63 ++++++--- lib/zabbixapi/version.rb | 2 +- spec/action.rb | 106 +++++++-------- spec/application.rb | 40 +++--- spec/configuration.rb | 94 ++++++------- spec/graph.rb | 93 ++++++------- spec/host.rb | 158 ++++++++++++---------- spec/hostgroup.rb | 18 +-- spec/httptest.rb | 114 ++++++++-------- spec/item.rb | 74 ++++++----- spec/maintenance.rb | 70 +++++----- spec/mediatype.rb | 44 ++++--- spec/query.rb | 27 ++-- spec/screen.rb | 22 ++-- spec/server.rb | 6 +- spec/spec_helper.rb | 3 +- spec/template.rb | 120 +++++++++-------- spec/trigger.rb | 66 +++++----- spec/user.rb | 56 ++++---- spec/usergroup.rb | 41 +++--- spec/usermacro.rb | 110 +++++++++------- zabbixapi.gemspec | 49 +++---- 57 files changed, 1904 insertions(+), 1023 deletions(-) create mode 100644 .codeclimate.yml create mode 100644 .rubocop.yml create mode 100644 .rubocop_todo.yml create mode 100644 .yardopts diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 0000000..412aff0 --- /dev/null +++ b/.codeclimate.yml @@ -0,0 +1,16 @@ +engines: + rubocop: + enabled: true + duplication: + enabled: true + config: + languages: + - ruby + +ratings: + paths: + - "**.rb" + +exclude_paths: + - examples/**/* + - spec/**/* \ No newline at end of file diff --git a/.gitignore b/.gitignore index 5a11022..bf36dc2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,40 @@ -.rvmrc +## Based on the templates from https://github.com/github/gitignore + +## Ruby *.gem -*.swp -.idea -.gemtags -pkg -test +*.rbc +/.config +/coverage/ +/InstalledFiles +/measurement/ +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +#Gemfile.lock +.ruby-version +.ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc \ No newline at end of file diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..f56fe56 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,60 @@ +inherit_from: .rubocop_todo.yml + +Metrics/AbcSize: + Max: 58 # TODO: Lower to 15 + +Metrics/BlockLength: + Max: 35 + Exclude: + - spec/**/*.rb + +Metrics/BlockNesting: + Max: 2 + +Metrics/CyclomaticComplexity: + Max: 10 + +Metrics/LineLength: + AllowURI: true + Enabled: false + +Metrics/MethodLength: + CountComments: false + Max: 35 # TODO: Lower to 15 + +Metrics/ModuleLength: + Max: 150 # TODO: Lower to 100 + +Metrics/ParameterLists: + Max: 4 + CountKeywordArgs: true + +Metrics/PerceivedComplexity: + Max: 10 + +Style/AccessModifierIndentation: + EnforcedStyle: outdent + +Style/Documentation: + Enabled: false + +Style/DoubleNegation: + Enabled: false + +Style/FrozenStringLiteralComment: + Enabled: false + +Style/HashSyntax: + Enabled: false + +Style/RaiseArgs: + EnforcedStyle: compact + +Style/SpaceInsideHashLiteralBraces: + EnforcedStyle: no_space + +Style/SymbolArray: + EnforcedStyle: brackets + +Style/TrailingCommaInLiteral: + EnforcedStyleForMultiline: 'comma' diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..44dc9bb --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,20 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2017-04-19 14:47:45 -0500 using RuboCop version 0.48.1. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 1 +Style/AccessorMethodName: + Exclude: + - 'lib/zabbixapi/classes/usergroups.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, SingleLineConditionsOnly, IncludeTernaryExpressions. +# SupportedStyles: assign_to_condition, assign_inside_condition +Style/ConditionalAssignment: + Exclude: + - 'lib/zabbixapi/client.rb' diff --git a/.travis.yml b/.travis.yml index 697f362..a898da5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ language: - ruby + addons: postgresql: '9.5' apt: @@ -10,18 +11,22 @@ addons: - php5-pgsql - zabbix-frontend-php - zabbix-server-pgsql + services: - postgresql + rvm: - - 1.9.3 - 2.0 - 2.1 - 2.2 - 2.3 -gemfile: - - Gemfile - - json-1.x.Gemfile + - 2.4 + - ruby-head + - jruby-9.1.1.0 + - jruby-head + dist: trusty + sudo: required before_script: @@ -32,10 +37,16 @@ before_script: - zcat /usr/share/doc/zabbix-server-pgsql/create.sql.gz | LC_ALL=C psql -U zabbix - echo "$(curl -fsSL https://gist.githubusercontent.com/evtuhovich/9544441/raw/d661863063b76cc8e2599bc44d8595b1f86ece38/zabbix)" | sudo tee /etc/zabbix/web/zabbix.conf.php - sudo service apache2 restart + script: "ZABBIX_HOST_URL=http://localhost/zabbix/api_jsonrpc.php bundle exec rspec spec/*" +env: + global: + - JRUBY_OPTS="$JRUBY_OPTS --debug" + matrix: - exclude: - # json 2.x requires ruby 2.x - - rvm: 1.9.3 - gemfile: json-1.x.Gemfile + allow_failures: + - rvm: ruby-head + - rvm: jruby-head + fast_finish: true + diff --git a/.yardopts b/.yardopts new file mode 100644 index 0000000..e758f7a --- /dev/null +++ b/.yardopts @@ -0,0 +1,9 @@ +--no-private +--protected +--tag authentication:"Authentication" +--markup markdown +- +CHANGELOG.md +LICENSE.md +README.md +examples/*.md diff --git a/Gemfile b/Gemfile index fa75df1..f8f1275 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,21 @@ source 'https://rubygems.org' +gem 'jruby-openssl', platforms: :jruby +gem 'rake', '~> 11.1' +gem 'yard', '>= 0.9' + +group :development do + gem 'pry' +end + +group :test do + gem 'coveralls' + gem 'rspec', '>= 3.4.4' + gem 'rubocop', '>= 0.38' + gem 'simplecov', '>= 0.9' + gem 'timecop' + gem 'webmock', '>= 2.0.3' + gem 'yardstick' +end + gemspec diff --git a/Gemfile.lock b/Gemfile.lock index 3bce908..9cb5ed8 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -2,14 +2,50 @@ PATH remote: . specs: zabbixapi (3.0.0) - json + http (~> 2.0) + json (~> 2.0) GEM remote: https://rubygems.org/ specs: + addressable (2.5.1) + public_suffix (~> 2.0, >= 2.0.2) + ast (2.3.0) + coderay (1.1.1) + coveralls (0.8.20) + json (>= 1.8, < 3) + simplecov (~> 0.14.1) + term-ansicolor (~> 1.3) + thor (~> 0.19.4) + tins (~> 1.6) + crack (0.4.3) + safe_yaml (~> 1.0.0) diff-lcs (1.2.5) - json (2.0.3) - rake (12.0.0) + docile (1.1.5) + domain_name (0.5.20170404) + unf (>= 0.0.5, < 1.0.0) + hashdiff (0.3.2) + http (2.2.1) + addressable (~> 2.3) + http-cookie (~> 1.0) + http-form_data (~> 1.0.1) + http_parser.rb (~> 0.6.0) + http-cookie (1.0.3) + domain_name (~> 0.5) + http-form_data (1.0.1) + http_parser.rb (0.6.0) + json (2.1.0) + method_source (0.8.2) + parser (2.4.0.0) + ast (~> 2.2) + powerpack (0.1.1) + pry (0.10.4) + coderay (~> 1.1.0) + method_source (~> 0.8.1) + slop (~> 3.4) + public_suffix (2.0.5) + rainbow (2.2.1) + rake (11.3.0) rspec (3.5.0) rspec-core (~> 3.5.0) rspec-expectations (~> 3.5.0) @@ -23,14 +59,54 @@ GEM diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.5.0) rspec-support (3.5.0) + rubocop (0.48.1) + parser (>= 2.3.3.1, < 3.0) + powerpack (~> 0.1) + rainbow (>= 1.99.1, < 3.0) + ruby-progressbar (~> 1.7) + unicode-display_width (~> 1.0, >= 1.0.1) + ruby-progressbar (1.8.1) + safe_yaml (1.0.4) + simplecov (0.14.1) + docile (~> 1.1.0) + json (>= 1.8, < 3) + simplecov-html (~> 0.10.0) + simplecov-html (0.10.0) + slop (3.6.0) + term-ansicolor (1.6.0) + tins (~> 1.0) + thor (0.19.4) + timecop (0.8.1) + tins (1.13.2) + unf (0.1.4) + unf_ext + unf_ext (0.0.7.4) + unicode-display_width (1.2.1) + webmock (3.0.1) + addressable (>= 2.3.6) + crack (>= 0.3.2) + hashdiff + yard (0.9.8) + yardstick (0.9.9) + yard (~> 0.8, >= 0.8.7.2) PLATFORMS ruby DEPENDENCIES - rake - rspec + bundler (~> 1.0) + coveralls + jruby-openssl + pry + rake (~> 11.1) + rspec (>= 3.4.4) + rubocop (>= 0.38) + simplecov (>= 0.9) + timecop + webmock (>= 2.0.3) + yard (>= 0.9) + yardstick zabbixapi! BUNDLED WITH - 1.14.3 + 1.14.6 diff --git a/README.md b/README.md index 3b19cda..cc0ef40 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,8 @@ versions: * Ruby 2.1 * Ruby 2.2 * Ruby 2.3 +* Ruby 2.4 +* JRuby 9.1.1.0 If something doesn't work on one of these versions, it's a bug. diff --git a/Rakefile b/Rakefile index c702cfc..54351ca 100644 --- a/Rakefile +++ b/Rakefile @@ -1 +1,25 @@ -require 'bundler/gem_tasks' +require 'bundler' +Bundler::GemHelper.install_tasks + +require 'rspec/core/rake_task' +RSpec::Core::RakeTask.new(:spec) + +task test: :spec + +require 'rubocop/rake_task' +RuboCop::RakeTask.new + +require 'yard' +YARD::Rake::YardocTask.new + +require 'yardstick/rake/measurement' +Yardstick::Rake::Measurement.new do |measurement| + measurement.output = 'measurement/report.txt' +end + +require 'yardstick/rake/verify' +Yardstick::Rake::Verify.new do |verify| + verify.threshold = 67.1 +end + +task default: [:spec, :rubocop, :verify_measurements] diff --git a/lib/zabbixapi.rb b/lib/zabbixapi.rb index 9dacce8..b229307 100644 --- a/lib/zabbixapi.rb +++ b/lib/zabbixapi.rb @@ -1,122 +1,152 @@ -require "zabbixapi/version" -require "zabbixapi/client" - -require "zabbixapi/basic/basic_alias" -require "zabbixapi/basic/basic_func" -require "zabbixapi/basic/basic_init" -require "zabbixapi/basic/basic_logic" - -require "zabbixapi/classes/applications" -require "zabbixapi/classes/errors" -require "zabbixapi/classes/graphs" -require "zabbixapi/classes/hostgroups" -require "zabbixapi/classes/maintenance" -require "zabbixapi/classes/hosts" -require "zabbixapi/classes/httptests" -require "zabbixapi/classes/items" -require "zabbixapi/classes/mediatypes" -require "zabbixapi/classes/proxies" -require "zabbixapi/classes/screens" -require "zabbixapi/classes/server" -require "zabbixapi/classes/templates" -require "zabbixapi/classes/triggers" -require "zabbixapi/classes/unusable" -require "zabbixapi/classes/usergroups" -require "zabbixapi/classes/usermacros" -require "zabbixapi/classes/users" -require "zabbixapi/classes/configurations" -require "zabbixapi/classes/actions" +require 'zabbixapi/version' +require 'zabbixapi/client' + +require 'zabbixapi/basic/basic_alias' +require 'zabbixapi/basic/basic_func' +require 'zabbixapi/basic/basic_init' +require 'zabbixapi/basic/basic_logic' + +require 'zabbixapi/classes/actions' +require 'zabbixapi/classes/applications' +require 'zabbixapi/classes/configurations' +require 'zabbixapi/classes/errors' +require 'zabbixapi/classes/graphs' +require 'zabbixapi/classes/hostgroups' +require 'zabbixapi/classes/hosts' +require 'zabbixapi/classes/httptests' +require 'zabbixapi/classes/items' +require 'zabbixapi/classes/maintenance' +require 'zabbixapi/classes/mediatypes' +require 'zabbixapi/classes/proxies' +require 'zabbixapi/classes/screens' +require 'zabbixapi/classes/server' +require 'zabbixapi/classes/templates' +require 'zabbixapi/classes/triggers' +require 'zabbixapi/classes/unusable' +require 'zabbixapi/classes/usergroups' +require 'zabbixapi/classes/usermacros' +require 'zabbixapi/classes/users' class ZabbixApi + # @return [ZabbixApi::Client] + attr_reader :client - attr :client - + # Initializes a new ZabbixApi object + # + # @param options [Hash] + # @return [ZabbixApi] def self.connect(options = {}) new(options) end + # @return [ZabbixApi] def self.current @current ||= ZabbixApi.new end + # Executes an API request directly using a custom query + # + # @param data [Hash] + # @return [Hash] def query(data) @client.api_request(:method => data[:method], :params => data[:params]) end + # Initializes a new ZabbixApi object + # + # @param options [Hash] + # @return [ZabbixApi::Client] def initialize(options = {}) @client = Client.new(options) end - def server - @server ||= Server.new(@client) + # @return [ZabbixApi::Actions] + def actions + @actions ||= Actions.new(@client) end - def users - @users ||= Users.new(@client) + # @return [ZabbixApi::Applications] + def applications + @applications ||= Applications.new(@client) end - def items - @items ||= Items.new(@client) + # @return [ZabbixApi::Configurations] + def configurations + @configurations ||= Configurations.new(@client) end - def hosts - @hosts ||= Hosts.new(@client) + # @return [ZabbixApi::Graphs] + def graphs + @graphs ||= Graphs.new(@client) end - def httptests - @httptests ||= HttpTests.new(@client) + # @return [ZabbixApi::HostGroups] + def hostgroups + @hostgroups ||= HostGroups.new(@client) end - def applications - @applications ||= Applications.new(@client) + # @return [ZabbixApi::Hosts] + def hosts + @hosts ||= Hosts.new(@client) end - def templates - @templates ||= Templates.new(@client) + # @return [ZabbixApi::HttpTests] + def httptests + @httptests ||= HttpTests.new(@client) end - def hostgroups - @hostgroups ||= HostGroups.new(@client) + # @return [ZabbixApi::Items] + def items + @items ||= Items.new(@client) end + # @return [ZabbixApi::Maintenance] def maintenance @maintenance ||= Maintenance.new(@client) end - def triggers - @triggers ||= Triggers.new(@client) - end - - def graphs - @graphs ||= Graphs.new(@client) + # @return [ZabbixApi::Mediatypes] + def mediatypes + @mediatypes ||= Mediatypes.new(@client) end + # @return [ZabbixApi::Proxies] def proxies @proxies ||= Proxies.new(@client) end + # @return [ZabbixApi::Screens] def screens @screens ||= Screens.new(@client) end - def usergroups - @usergroups ||= Usergroups.new(@client) + # @return [ZabbixApi::Server] + def server + @server ||= Server.new(@client) end - def usermacros - @usermacros ||= Usermacros.new(@client) + # @return [ZabbixApi::Templates] + def templates + @templates ||= Templates.new(@client) end - def mediatypes - @mediatypes ||= Mediatypes.new(@client) + # @return [ZabbixApi::Triggers] + def triggers + @triggers ||= Triggers.new(@client) end - def configurations - @configurations ||= Configurations.new(@client) + # @return [ZabbixApi::Usergroups] + def usergroups + @usergroups ||= Usergroups.new(@client) end - def actions - @actions ||= Actions.new(@client) + # @return [ZabbixApi::Usermacros] + def usermacros + @usermacros ||= Usermacros.new(@client) end + # @return [ZabbixApi::Users] + def users + @users ||= Users.new(@client) + end end diff --git a/lib/zabbixapi/basic/basic_alias.rb b/lib/zabbixapi/basic/basic_alias.rb index c0c18ae..1502ffc 100644 --- a/lib/zabbixapi/basic/basic_alias.rb +++ b/lib/zabbixapi/basic/basic_alias.rb @@ -1,20 +1,37 @@ class ZabbixApi class Basic - + # Get Zabbix object data from API by id + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def get(data) get_full_data(data) end + # Add new Zabbix object using API create + # + # @param data [Hash] + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created def add(data) create(data) end + # Destroy Zabbix object using API delete + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is deleted + # @return [Boolean] True/False if multiple objects are deleted def destroy(data) delete(data) end - def method_name - end - + def method_name; end end end diff --git a/lib/zabbixapi/basic/basic_func.rb b/lib/zabbixapi/basic/basic_func.rb index 500e0a9..b50e036 100644 --- a/lib/zabbixapi/basic/basic_func.rb +++ b/lib/zabbixapi/basic/basic_func.rb @@ -1,10 +1,17 @@ class ZabbixApi class Basic - + # Log messages to stdout when debugging + # + # @param message [String] def log(message) - puts "#{message}" if @client.options[:debug] + puts message.to_s if @client.options[:debug] end + # Compare two hashes for equality + # + # @param a [Hash] + # @param b [Hash] + # @return [Boolean] def hash_equals?(a, b) a_new = normalize_hash(a) b_new = normalize_hash(b) @@ -13,40 +20,64 @@ def hash_equals?(a, b) hash1 == hash2 end - def symbolize_keys(obj) - return obj.inject({}){|memo,(k,v)| memo[k.to_sym] = symbolize_keys(v); memo} if obj.is_a? Hash - return obj.inject([]){|memo,v | memo << symbolize_keys(v); memo} if obj.is_a? Array - obj + # Convert all hash/array keys to symbols + # + # @param object [Array, Hash] + # @return [Array, Hash] + def symbolize_keys!(object) + if object.is_a?(Array) + object.each_with_index do |val, index| + object[index] = symbolize_keys!(val) + end + elsif object.is_a?(Hash) + object.keys.each do |key| + object[key.to_sym] = symbolize_keys!(object.delete(key)) + end + end + object end + # Normalize all hash values to strings + # + # @param hash [Hash] + # @return [Hash] def normalize_hash(hash) result = hash.dup - result.delete(:hostid) #TODO remove to logig. TemplateID and HostID has different id + + result.delete(:hostid) # TODO: remove to logig. TemplateID and HostID has different id + result.each do |key, value| - case value - when Array - result[key] = normalize_array(value) - else - result[key] = value.to_s - end + result[key] = value.is_a?(Array) ? normalize_array(value) : value.to_s end + result end + # Normalize all array values to strings + # + # @param array [Array] + # @return [Array] def normalize_array(array) result = [] + array.each do |e| - case e - when Array - result << normalize_array(e) - when Hash - result << normalize_hash(e) - else - result << e.to_s + if e.is_a?(Array) + result.push(normalize_array(e)) + elsif e.is_a?(Hash) + result.push(normalize_hash(e)) + else + result.push(e.to_s) end end + + result end + # Parse a data hash for id key or boolean to return + # + # @param data [Hash] + # @return [Integer] The object id if a single object hash is provided with key + # @return [Boolean] True/False if multiple class object hash is provided def parse_keys(data) case data when Hash @@ -55,15 +86,17 @@ def parse_keys(data) true when FalseClass false - else - nil end end + # Merge two hashes into a single new hash + # + # @param a [Hash] + # @param b [Hash] + # @return [Hash] def merge_params(a, b) new = a.dup new.merge(b) end - end end diff --git a/lib/zabbixapi/basic/basic_init.rb b/lib/zabbixapi/basic/basic_init.rb index 495258c..ebcec69 100644 --- a/lib/zabbixapi/basic/basic_init.rb +++ b/lib/zabbixapi/basic/basic_init.rb @@ -1,29 +1,46 @@ class ZabbixApi class Basic - + # Initializes a new Basic object with ZabbixApi Client + # + # @param client [ZabbixApi::Client] + # @return [ZabbixApi::Client] def initialize(client) @client = client end + # Placeholder for inherited objects to provide object-specific method name + # + # @raise [ApiError] Basic object does not directly support method_name def method_name raise ApiError.new("Can't call method_name here") end + # Placeholder for inherited objects to provide default options + # + # @return [Hash] def default_options {} end + # Returns the object's plural id field name (indentify) based on key + # + # @return [String] def keys - key + "s" + key + 's' end + # Returns the object's id field name (indentify) based on method_name + id + # + # @return [String] def key - method_name + "id" + method_name + 'id' end + # Placeholder for inherited objects to provide object-specific id field name + # + # @raise [ApiError] Basic object does not directly support indentify def indentify raise ApiError.new("Can't call indentify here") end - end end diff --git a/lib/zabbixapi/basic/basic_logic.rb b/lib/zabbixapi/basic/basic_logic.rb index f1b882a..7e309d4 100644 --- a/lib/zabbixapi/basic/basic_logic.rb +++ b/lib/zabbixapi/basic/basic_logic.rb @@ -1,6 +1,12 @@ class ZabbixApi class Basic - + # Create new Zabbix object using API (with defaults) + # + # @param data [Hash] + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created def create(data) log "[DEBUG] Call create with parameters: #{data.inspect}" @@ -10,6 +16,13 @@ def create(data) parse_keys result end + # Delete Zabbix object using API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is deleted + # @return [Boolean] True/False if multiple objects are deleted def delete(data) log "[DEBUG] Call delete with parameters: #{data.inspect}" @@ -18,6 +31,13 @@ def delete(data) parse_keys result end + # Create or update Zabbix object using API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created def create_or_update(data) log "[DEBUG] Call create_or_update with parameters: #{data.inspect}" @@ -25,26 +45,36 @@ def create_or_update(data) id ? update(data.merge(key.to_sym => id.to_s)) : create(data) end - def update(data, force=false) + # Update Zabbix object using API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @param force [Boolean] Whether to force an object update even if provided data matches Zabbix + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created + def update(data, force = false) log "[DEBUG] Call update with parameters: #{data.inspect}" - dump = {} - item_id = data[key.to_sym].to_i dump_by_id(key.to_sym => data[key.to_sym]).each do |item| dump = symbolize_keys(item) if item[key].to_i == data[key.to_sym].to_i end - - if hash_equals?(dump, data) and not force + if hash_equals?(dump, data) && !force log "[DEBUG] Equal keys #{dump} and #{data}, skip update" - item_id + data[key.to_sym].to_i else data_update = [data] result = @client.api_request(:method => "#{method_name}.update", :params => data_update) parse_keys result end - end + # Get full/extended Zabbix object data from API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parameters: #{data.inspect}" @@ -52,13 +82,19 @@ def get_full_data(data) :method => "#{method_name}.get", :params => { :filter => { - indentify.to_sym => data[indentify.to_sym] + indentify.to_sym => data[indentify.to_sym], }, - :output => "extend" + :output => 'extend', } ) end + # Get raw Zabbix object data from API + # + # @param data [Hash] + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def get_raw(data) log "[DEBUG] Call get_raw with parameters: #{data.inspect}" @@ -68,6 +104,12 @@ def get_raw(data) ) end + # Dump Zabbix object data by key from API + # + # @param data [Hash] Should include desired object's key and value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parameters: #{data.inspect}" @@ -75,34 +117,44 @@ def dump_by_id(data) :method => "#{method_name}.get", :params => { :filter => { - key.to_sym => data[key.to_sym] + key.to_sym => data[key.to_sym], }, - :output => "extend" + :output => 'extend', } ) end + # Get full/extended Zabbix data for all objects of type/class from API + # + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Array] Array of matching objects def all result = {} - @client.api_request(:method => "#{method_name}.get", :params => {:output => "extend"}).each do |item| + @client.api_request(:method => "#{method_name}.get", :params => {:output => 'extend'}).each do |item| result[item[indentify]] = item[key] end result end + # Get Zabbix object id from API based on provided data + # + # @param data [Hash] + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call or missing object's id field name (indentify). + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_id(data) log "[DEBUG] Call get_id with parameters: #{data.inspect}" - # symbolize keys if the user used string keys instead of symbols data = symbolize_keys(data) if data.key?(indentify) - # raise an error if indentify name was not supplied + # raise an error if indentify name was not supplied name = data[indentify.to_sym] - raise ApiError.new("#{indentify} not supplied in call to get_id") if name == nil + raise ApiError.new("#{indentify} not supplied in call to get_id") if name.nil? result = @client.api_request( :method => "#{method_name}.get", :params => { :filter => data, - :output => [key, indentify] + :output => [key, indentify], } ) id = nil @@ -110,6 +162,12 @@ def get_id(data) id end + # Get or Create Zabbix object using API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" @@ -118,6 +176,5 @@ def get_or_create(data) end id end - end end diff --git a/lib/zabbixapi/classes/actions.rb b/lib/zabbixapi/classes/actions.rb index 23d9516..db43bbd 100644 --- a/lib/zabbixapi/classes/actions.rb +++ b/lib/zabbixapi/classes/actions.rb @@ -1,13 +1,17 @@ class ZabbixApi class Actions < Basic - + # The method name used for interacting with Actions via Zabbix API + # + # @return [String] def method_name - "action" + 'action' end + # The id field name used for identifying specific Action objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end - end end diff --git a/lib/zabbixapi/classes/applications.rb b/lib/zabbixapi/classes/applications.rb index dad9991..673df6f 100644 --- a/lib/zabbixapi/classes/applications.rb +++ b/lib/zabbixapi/classes/applications.rb @@ -1,16 +1,25 @@ class ZabbixApi class Applications < Basic - - API_PARAMETERS = %w(applicationids groupids hostids inherited itemids templated templateids selectItems) - + # The method name used for interacting with Applications via Zabbix API + # + # @return [String] def method_name - "application" + 'application' end + # The id field name used for identifying specific Application objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end + # Get or Create Application object using Zabbix API + # + # @param data [Hash] Needs to include name and hostid to properly identify Applications via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" @@ -20,10 +29,15 @@ def get_or_create(data) id end + # Create or update Application object using Zabbix API + # + # @param data [Hash] Needs to include name and hostid to properly identify Applications via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update(data) applicationid = get_id(:name => data[:name], :hostid => data[:hostid]) applicationid ? update(data.merge(:applicationid => applicationid)) : create(data) end - end end diff --git a/lib/zabbixapi/classes/configurations.rb b/lib/zabbixapi/classes/configurations.rb index 35ab9a5..7a4c4ee 100644 --- a/lib/zabbixapi/classes/configurations.rb +++ b/lib/zabbixapi/classes/configurations.rb @@ -1,36 +1,42 @@ class ZabbixApi class Configurations < Basic - + # @return [Boolean] def array_flag true end + # The method name used for interacting with Configurations via Zabbix API + # + # @return [String] def method_name - "configuration" + 'configuration' end + # The id field name used for identifying specific Configuration objects via Zabbix API + # + # @return [String] def indentify - "host" + 'host' end - # Export configuration data as a serialized string - # * *Args* : - # see available parameters: https://www.zabbix.com/documentation/2.2/manual/api/reference/configuration/export - # * *Returns* : - # - String + # Export configuration data using Zabbix API + # + # @param data [Hash] + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def export(data) - @client.api_request(:method => "configuration.export", :params => data) + @client.api_request(:method => 'configuration.export', :params => data) end - # Import configurations data from a serialized string - # * *Args* : - # see available parameters: https://www.zabbix.com/documentation/2.2/manual/api/reference/configuration/import - # * *Returns* : - # - Boolean + # Import configuration data using Zabbix API + # + # @param data [Hash] + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def import(data) - @client.api_request(:method => "configuration.import", :params => data) + @client.api_request(:method => 'configuration.import', :params => data) end - end end - diff --git a/lib/zabbixapi/classes/errors.rb b/lib/zabbixapi/classes/errors.rb index c8172ab..10db68a 100644 --- a/lib/zabbixapi/classes/errors.rb +++ b/lib/zabbixapi/classes/errors.rb @@ -1,5 +1,4 @@ class ZabbixApi - class BaseError < RuntimeError attr_accessor :response, :error, :error_message @@ -10,11 +9,11 @@ def initialize(message, response = nil) set_error! if @response end - private + private def set_error! - @error = @response["error"] rescue nil - @error_message = "#{@error['message']}: #{@error['data']}" rescue nil + @error = @response.try(:[], :error) + @error_message = @error.try(:[], :message) + ': ' + @error.try(:[], :data) end end @@ -23,5 +22,4 @@ class ApiError < BaseError class HttpError < BaseError end - end diff --git a/lib/zabbixapi/classes/graphs.rb b/lib/zabbixapi/classes/graphs.rb index 9044a72..398b5e9 100644 --- a/lib/zabbixapi/classes/graphs.rb +++ b/lib/zabbixapi/classes/graphs.rb @@ -1,14 +1,25 @@ class ZabbixApi class Graphs < Basic - + # The method name used for interacting with Graphs via Zabbix API + # + # @return [String] def method_name - "graph" + 'graph' end + # The id field name used for identifying specific Graph objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end + # Get full/extended Graph data from Zabbix API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parametrs: #{data.inspect}" @@ -16,47 +27,87 @@ def get_full_data(data) :method => "#{method_name}.get", :params => { :search => { - indentify.to_sym => data[indentify.to_sym] + indentify.to_sym => data[indentify.to_sym], }, - :output => "extend" + :output => 'extend', } ) end + # Get Graph ids for Host from Zabbix API + # + # @param data [Hash] Should include host value to query for matching graphs + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Array] Returns array of Graph ids def get_ids_by_host(data) ids = [] - graphs = Hash.new - result = @client.api_request(:method => "graph.get", :params => {:filter => {:host => data[:host]}, :output => "extend"}) + graphs = {} + + result = @client.api_request( + :method => 'graph.get', + :params => { + :filter => { + :host => data[:host], + }, + :output => 'extend', + } + ) + result.each do |graph| num = graph['graphid'] name = graph['name'] graphs[name] = num filter = data[:filter] - unless filter.nil? - if /#{filter}/ =~ name - ids.push(graphs[name]) - end - else - ids.push(graphs[name]) + if filter.nil? + ids.push(graphs[name]) + elsif /#{filter}/ =~ name + ids.push(graphs[name]) end end + ids end + # Get Graph Item object using Zabbix API + # + # @param data [Hash] Needs to include graphids to properly identify Graph Items via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def get_items(data) - @client.api_request(:method => "graphitem.get", :params => { :graphids => [data], :output => "extend" } ) + @client.api_request( + :method => 'graphitem.get', + :params => { + :graphids => [data], + :output => 'extend', + } + ) end + # Get or Create Graph object using Zabbix API + # + # @param data [Hash] Needs to include name and templateid to properly identify Graphs via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(:name => data[:name], :templateid => data[:templateid])) id = create(data) end + id end + # Create or update Graph object using Zabbix API + # + # @param data [Hash] Needs to include name and templateid to properly identify Graphs via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update(data) graphid = get_id(:name => data[:name], :templateid => data[:templateid]) graphid ? _update(data.merge(:graphid => graphid)) : create(data) @@ -66,6 +117,5 @@ def _update(data) data.delete(:name) update(data) end - end end diff --git a/lib/zabbixapi/classes/hostgroups.rb b/lib/zabbixapi/classes/hostgroups.rb index 45d9b54..b96d427 100644 --- a/lib/zabbixapi/classes/hostgroups.rb +++ b/lib/zabbixapi/classes/hostgroups.rb @@ -1,16 +1,24 @@ class ZabbixApi class HostGroups < Basic - + # The method name used for interacting with HostGroups via Zabbix API + # + # @return [String] def method_name - "hostgroup" + 'hostgroup' end + # The id field name used for identifying specific HostGroup objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end + # The key field name used for HostGroup objects via Zabbix API + # + # @return [String] def key - "groupid" + 'groupid' end end end diff --git a/lib/zabbixapi/classes/hosts.rb b/lib/zabbixapi/classes/hosts.rb index 691791e..07db74f 100644 --- a/lib/zabbixapi/classes/hosts.rb +++ b/lib/zabbixapi/classes/hosts.rb @@ -1,29 +1,43 @@ class ZabbixApi class Hosts < Basic - + # The method name used for interacting with Hosts via Zabbix API + # + # @return [String] def method_name - "host" + 'host' end + # The id field name used for identifying specific Host objects via Zabbix API + # + # @return [String] def indentify - "host" + 'host' end + # Dump Host object data by key from Zabbix API + # + # @param data [Hash] Should include desired object's key and value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parametrs: #{data.inspect}" @client.api_request( - :method => "host.get", + :method => 'host.get', :params => { :filter => { - key.to_sym => data[key.to_sym] + key.to_sym => data[key.to_sym], }, - :output => "extend", - :selectGroups => "shorten" + :output => 'extend', + :selectGroups => 'shorten', } ) end + # The default options used when creating Host objects via Zabbix API + # + # @return [Hash] def default_options { :host => nil, @@ -31,21 +45,33 @@ def default_options :status => 0, :available => 1, :groups => [], - :proxy_hostid => nil + :proxy_hostid => nil, } end + # Unlink/Remove Templates from Hosts using Zabbix API + # + # @param data [Hash] Should include hosts_id array and templates_id array + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Boolean] def unlink_templates(data) result = @client.api_request( - :method => "host.massRemove", + :method => 'host.massRemove', :params => { :hostids => data[:hosts_id], - :templates => data[:templates_id] + :templates => data[:templates_id], } ) result.empty? ? false : true end + # Create or update Host object using Zabbix API + # + # @param data [Hash] Needs to include host to properly identify Hosts via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update(data) hostid = get_id(:host => data[:host]) hostid ? update(data.merge(:hostid => hostid)) : create(data) diff --git a/lib/zabbixapi/classes/httptests.rb b/lib/zabbixapi/classes/httptests.rb index 3bc9b0f..001509f 100644 --- a/lib/zabbixapi/classes/httptests.rb +++ b/lib/zabbixapi/classes/httptests.rb @@ -1,22 +1,36 @@ class ZabbixApi class HttpTests < Basic - + # The method name used for interacting with HttpTests via Zabbix API + # + # @return [String] def method_name - "httptest" + 'httptest' end + # The id field name used for identifying specific HttpTest objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end + # The default options used when creating HttpTest objects via Zabbix API + # + # @return [Hash] def default_options { :hostid => nil, :name => nil, - :steps => [] + :steps => [], } end + # Get or Create HttpTest object using Zabbix API + # + # @param data [Hash] Needs to include name and hostid to properly identify HttpTests via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" @@ -26,6 +40,12 @@ def get_or_create(data) id end + # Create or update HttpTest object using Zabbix API + # + # @param data [Hash] Needs to include name and hostid to properly identify HttpTests via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update(data) httptestid = get_id(:name => data[:name], :hostid => data[:hostid]) httptestid ? update(data.merge(:httptestid => httptestid)) : create(data) diff --git a/lib/zabbixapi/classes/items.rb b/lib/zabbixapi/classes/items.rb index d7a31b4..403634a 100644 --- a/lib/zabbixapi/classes/items.rb +++ b/lib/zabbixapi/classes/items.rb @@ -1,14 +1,22 @@ class ZabbixApi class Items < Basic - + # The method name used for interacting with Items via Zabbix API + # + # @return [String] def method_name - "item" + 'item' end + # The id field name used for identifying specific Item objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end + # The default options used when creating Item objects via Zabbix API + # + # @return [Hash] def default_options { :name => nil, @@ -42,10 +50,16 @@ def default_options :publickey => '', :privatekey => '', :params => '', - :ipmi_sensor => '' + :ipmi_sensor => '', } end + # Get or Create Item object using Zabbix API + # + # @param data [Hash] Needs to include name and hostid to properly identify Items via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" @@ -55,10 +69,15 @@ def get_or_create(data) id end + # Create or update Item object using Zabbix API + # + # @param data [Hash] Needs to include name and hostid to properly identify Items via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update(data) itemid = get_id(:name => data[:name], :hostid => data[:hostid]) itemid ? update(data.merge(:itemid => itemid)) : create(data) end - end end diff --git a/lib/zabbixapi/classes/maintenance.rb b/lib/zabbixapi/classes/maintenance.rb index 58c6a0b..130b7c7 100644 --- a/lib/zabbixapi/classes/maintenance.rb +++ b/lib/zabbixapi/classes/maintenance.rb @@ -1,13 +1,17 @@ class ZabbixApi class Maintenance < Basic - + # The method name used for interacting with Maintenances via Zabbix API + # + # @return [String] def method_name - "maintenance" + 'maintenance' end + # The id field name used for identifying specific Maintenance objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end - end end diff --git a/lib/zabbixapi/classes/mediatypes.rb b/lib/zabbixapi/classes/mediatypes.rb index a02956a..e7cfec3 100644 --- a/lib/zabbixapi/classes/mediatypes.rb +++ b/lib/zabbixapi/classes/mediatypes.rb @@ -1,27 +1,34 @@ class ZabbixApi class Mediatypes < Basic - + # The method name used for interacting with MediaTypes via Zabbix API + # + # @return [String] def method_name - "mediatype" + 'mediatype' end + # The id field name used for identifying specific MediaType objects via Zabbix API + # + # @return [String] def indentify - "description" + 'description' end + # The default options used when creating MediaType objects via Zabbix API + # + # @return [Hash] def default_options { - :description => "", #Name - :type => 0, #0 - Email, 1 - External script, 2 - SMS, 3 - Jabber, 100 - EzTexting - :smtp_server => "", - :smtp_helo => "", - :smtp_email => "", #Email address of Zabbix server - :exec_path => "", #Name of external script - :gsm_modem => "", #Serial device name of GSM modem - :username => "", #Jabber user name used by Zabbix server - :passwd => "" #Jabber password used by Zabbix server + :description => '', # Name + :type => 0, # 0 - Email, 1 - External script, 2 - SMS, 3 - Jabber, 100 - EzTexting + :smtp_server => '', + :smtp_helo => '', + :smtp_email => '', # Email address of Zabbix server + :exec_path => '', # Name of external script + :gsm_modem => '', # Serial device name of GSM modem + :username => '', # Jabber user name used by Zabbix server + :passwd => '' # Jabber password used by Zabbix server } end - end end diff --git a/lib/zabbixapi/classes/proxies.rb b/lib/zabbixapi/classes/proxies.rb index 9141dca..62e1b88 100644 --- a/lib/zabbixapi/classes/proxies.rb +++ b/lib/zabbixapi/classes/proxies.rb @@ -1,27 +1,48 @@ class ZabbixApi class Proxies < Basic - + # The method name used for interacting with Proxies via Zabbix API + # + # @return [String] def method_name - "proxy" + 'proxy' end + # The id field name used for identifying specific Proxy objects via Zabbix API + # + # @return [String] def indentify - "host" + 'host' end + # Delete Proxy object using Zabbix API + # + # @param data [Array] Should include array of proxyid's + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The Proxy object id that was deleted def delete(data) - result = @client.api_request(:method => "proxy.delete", :params => data) + result = @client.api_request(:method => 'proxy.delete', :params => data) result.empty? ? nil : result['proxyids'][0].to_i end + # Check if a Proxy object is readable using Zabbix API + # + # @param data [Array] Should include array of proxyid's + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Boolean] Returns true if the given proxies are readable def isreadable(data) - result = @client.api_request(:method => "proxy.isreadable", :params => data) + @client.api_request(:method => 'proxy.isreadable', :params => data) end + # Check if a Proxy object is writable using Zabbix API + # + # @param data [Array] Should include array of proxyid's + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Boolean] Returns true if the given proxies are writable def iswritable(data) - result = @client.api_request(:method => "proxy.iswritable", :params => data) + @client.api_request(:method => 'proxy.iswritable', :params => data) end - end end - diff --git a/lib/zabbixapi/classes/screens.rb b/lib/zabbixapi/classes/screens.rb index 19ed11a..7a5a78f 100644 --- a/lib/zabbixapi/classes/screens.rb +++ b/lib/zabbixapi/classes/screens.rb @@ -1,38 +1,55 @@ class ZabbixApi class Screens < Basic - # extracted from frontends/php/include/defines.inc.php - #SCREEN_RESOURCE_GRAPH => 0, - #SCREEN_RESOURCE_SIMPLE_GRAPH => 1, - #SCREEN_RESOURCE_MAP => 2, - #SCREEN_RESOURCE_PLAIN_TEXT => 3, - #SCREEN_RESOURCE_HOSTS_INFO => 4, - #SCREEN_RESOURCE_TRIGGERS_INFO => 5, - #SCREEN_RESOURCE_SERVER_INFO => 6, - #SCREEN_RESOURCE_CLOCK => 7, - #SCREEN_RESOURCE_SCREEN => 8, - #SCREEN_RESOURCE_TRIGGERS_OVERVIEW => 9, - #SCREEN_RESOURCE_DATA_OVERVIEW => 10, - #SCREEN_RESOURCE_URL => 11, - #SCREEN_RESOURCE_ACTIONS => 12, - #SCREEN_RESOURCE_EVENTS => 13, - #SCREEN_RESOURCE_HOSTGROUP_TRIGGERS => 14, - #SCREEN_RESOURCE_SYSTEM_STATUS => 15, - #SCREEN_RESOURCE_HOST_TRIGGERS => 16 + # SCREEN_RESOURCE_GRAPH => 0, + # SCREEN_RESOURCE_SIMPLE_GRAPH => 1, + # SCREEN_RESOURCE_MAP => 2, + # SCREEN_RESOURCE_PLAIN_TEXT => 3, + # SCREEN_RESOURCE_HOSTS_INFO => 4, + # SCREEN_RESOURCE_TRIGGERS_INFO => 5, + # SCREEN_RESOURCE_SERVER_INFO => 6, + # SCREEN_RESOURCE_CLOCK => 7, + # SCREEN_RESOURCE_SCREEN => 8, + # SCREEN_RESOURCE_TRIGGERS_OVERVIEW => 9, + # SCREEN_RESOURCE_DATA_OVERVIEW => 10, + # SCREEN_RESOURCE_URL => 11, + # SCREEN_RESOURCE_ACTIONS => 12, + # SCREEN_RESOURCE_EVENTS => 13, + # SCREEN_RESOURCE_HOSTGROUP_TRIGGERS => 14, + # SCREEN_RESOURCE_SYSTEM_STATUS => 15, + # SCREEN_RESOURCE_HOST_TRIGGERS => 16 + # The method name used for interacting with Screens via Zabbix API + # + # @return [String] def method_name - "screen" + 'screen' end + # The id field name used for identifying specific Screen objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end + # Delete Screen object using Zabbix API + # + # @param data [String, Array] Should include id's of the screens to delete + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def delete(data) - result = @client.api_request(:method => "screen.delete", :params => [data]) + result = @client.api_request(:method => 'screen.delete', :params => [data]) result.empty? ? nil : result['screenids'][0].to_i end + # Get or Create Screen object for Host using Zabbix API + # + # @param data [Hash] Needs to include screen_name and graphids to properly identify Screens via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create_for_host(data) screen_name = data[:screen_name] graphids = data[:graphids] @@ -44,7 +61,7 @@ def get_or_create_for_host(data) colspan = data[:colspan] || 1 height = data[:height] || 320 # default 320 width = data[:width] || 200 # default 200 - vsize = data[:vsize] || [1, (graphids.size/hsize).to_i].max + vsize = data[:vsize] || [1, (graphids.size / hsize).to_i].max screenid = get_id(:name => screen_name) unless screenid @@ -54,13 +71,13 @@ def get_or_create_for_host(data) :resourcetype => 0, :resourceid => graphid, :x => (index % hsize).to_i, - :y => (index % graphids.size/hsize).to_i, + :y => (index % graphids.size / hsize).to_i, :valign => valign, :halign => halign, :rowspan => rowspan, :colspan => colspan, :height => height, - :width => width + :width => width, } end screenid = create( @@ -72,6 +89,5 @@ def get_or_create_for_host(data) end screenid end - end end diff --git a/lib/zabbixapi/classes/server.rb b/lib/zabbixapi/classes/server.rb index 87e893b..1ec817f 100644 --- a/lib/zabbixapi/classes/server.rb +++ b/lib/zabbixapi/classes/server.rb @@ -1,12 +1,16 @@ class ZabbixApi class Server + # @return [String] + attr_reader :version - attr :version - + # Initializes a new Server object with ZabbixApi Client and fetches Zabbix Server API version + # + # @param client [ZabbixApi::Client] + # @return [ZabbixApi::Client] + # @return [String] Zabbix API version number def initialize(client) @client = client - @version = @client.api_request(:method => "apiinfo.version", :params => {}) + @version = @client.api_request(:method => 'apiinfo.version', :params => {}) end - end end diff --git a/lib/zabbixapi/classes/templates.rb b/lib/zabbixapi/classes/templates.rb index 1b42468..d7b0676 100644 --- a/lib/zabbixapi/classes/templates.rb +++ b/lib/zabbixapi/classes/templates.rb @@ -1,46 +1,50 @@ class ZabbixApi class Templates < Basic - + # The method name used for interacting with Templates via Zabbix API + # + # @return [String] def method_name - "template" + 'template' end + # The id field name used for identifying specific Template objects via Zabbix API + # + # @return [String] def indentify - "host" + 'host' end - - # Delete template + # Delete Template object using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :host => "Template_Name" - # * *Returns* : - # - Nil or Integer + # @param data [Array] Should include array of templateid's + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The Template object id that was deleted def delete(data) - result = @client.api_request(:method => "template.delete", :params => [data]) + result = @client.api_request(:method => 'template.delete', :params => [data]) result.empty? ? nil : result['templateids'][0].to_i end - # Return templateids linked with host + # Get Template ids for Host from Zabbix API # - # * *Args* : - # - +data+ -> Hash with :hostids => [hostid] - # * *Returns* : - # - Array with templateids + # @param data [Hash] Should include host value to query for matching templates + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Array] Returns array of Template ids def get_ids_by_host(data) result = [] - @client.api_request(:method => "template.get", :params => data).each do |tmpl| + @client.api_request(:method => 'template.get', :params => data).each do |tmpl| result << tmpl['templateid'] end result end - # Return templateid + # Get or Create Template object using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :host => "Template_Name" and :groups => array with hostgroup ids - # * *Returns* : - # - Integer + # @param data [Hash] Needs to include host to properly identify Templates via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) unless (templateid = get_id(:host => data[:host])) templateid = create(data) @@ -48,58 +52,57 @@ def get_or_create(data) templateid end - # Analog Zabbix api call massUpdate + # Mass update Templates for Hosts using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :hosts_id => [hostid1, hostid2 ...], and :templates_id => [templateid1, templateid2 ...] - # * *Returns* : - # - True or False + # @param data [Hash] Should include hosts_id array and templates_id array + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Boolean] def mass_update(data) result = @client.api_request( - :method => "template.massUpdate", + :method => 'template.massUpdate', :params => { :hosts => data[:hosts_id].map { |t| {:hostid => t} }, - :templates => data[:templates_id].map { |t| {:templateid => t} } + :templates => data[:templates_id].map { |t| {:templateid => t} }, } ) result.empty? ? false : true end - # Analog Zabbix api call massAdd + # Mass add Templates to Hosts using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :hosts_id => [hostid1, hostid2 ...], and :templates_id => [templateid1, templateid2 ...] - # * *Returns* : - # - True or False + # @param data [Hash] Should include hosts_id array and templates_id array + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Boolean] def mass_add(data) result = @client.api_request( - :method => "template.massAdd", + :method => 'template.massAdd', :params => { :hosts => data[:hosts_id].map { |t| {:hostid => t} }, - :templates => data[:templates_id].map { |t| {:templateid => t} } + :templates => data[:templates_id].map { |t| {:templateid => t} }, } ) result.empty? ? false : true end - # Analog Zabbix api call massRemove + # Mass remove Templates to Hosts using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :hosts_id => [hostid1, hostid2 ...], and :templates_id => [templateid1, templateid2 ...] - # * *Returns* : - # - True or False + # @param data [Hash] Should include hosts_id array and templates_id array + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Boolean] def mass_remove(data) result = @client.api_request( - :method => "template.massRemove", + :method => 'template.massRemove', :params => { :hostids => data[:hosts_id], :templateids => data[:templates_id], :groupids => data[:group_id], - :force => 1 + :force => 1, } ) result.empty? ? false : true end - end end diff --git a/lib/zabbixapi/classes/triggers.rb b/lib/zabbixapi/classes/triggers.rb index 0be5c4d..ee54691 100644 --- a/lib/zabbixapi/classes/triggers.rb +++ b/lib/zabbixapi/classes/triggers.rb @@ -1,32 +1,49 @@ class ZabbixApi class Triggers < Basic - + # The method name used for interacting with Triggers via Zabbix API + # + # @return [String] def method_name - "trigger" + 'trigger' end + # The id field name used for identifying specific Trigger objects via Zabbix API + # + # @return [String] def indentify - "description" + 'description' end + # Dump Trigger object data by key from Zabbix API + # + # @param data [Hash] Should include desired object's key and value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parametrs: #{data.inspect}" @client.api_request( - :method => "trigger.get", + :method => 'trigger.get', :params => { :filter => { - key.to_sym => data[key.to_sym] + key.to_sym => data[key.to_sym], }, - :output => "extend", - :select_items => "extend", - :select_functions => "extend" + :output => 'extend', + :select_items => 'extend', + :select_functions => 'extend', } ) end + # Safely update Trigger object using Zabbix API by deleting and replacing trigger + # + # @param data [Hash] Needs to include description and hostid to properly identify Triggers via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def safe_update(data) - log "[DEBUG] Call update with parametrs: #{data.inspect}" + log "[DEBUG] Call safe_update with parameters: #{data.inspect}" dump = {} item_id = data[key.to_sym].to_i @@ -34,31 +51,36 @@ def safe_update(data) dump = symbolize_keys(item) if item[key].to_i == data[key.to_sym].to_i end - expression = dump[:items][0][:key_]+"."+dump[:functions][0][:function]+"("+dump[:functions][0][:parameter]+")" - dump[:expression] = dump[:expression].gsub(/\{(\d*)\}/,"{#{expression}}") #TODO ugly regexp + expression = dump[:items][0][:key_] + '.' + dump[:functions][0][:function] + '(' + dump[:functions][0][:parameter] + ')' + dump[:expression] = dump[:expression].gsub(/\{(\d*)\}/, "{#{expression}}") # TODO: ugly regexp dump.delete(:functions) dump.delete(:items) old_expression = data[:expression] - data[:expression] = data[:expression].gsub(/\{.*\:/,"{") #TODO ugly regexp + data[:expression] = data[:expression].gsub(/\{.*\:/, '{') # TODO: ugly regexp data.delete(:templateid) log "[DEBUG] expression: #{dump[:expression]}\n data: #{data[:expression]}" if hash_equals?(dump, data) - log "[DEBUG] Equal keys #{dump} and #{data}, skip update" + log "[DEBUG] Equal keys #{dump} and #{data}, skip safe_update" item_id else data[:expression] = old_expression # disable old trigger - log "[DEBUG] disable :" + @client.api_request(:method => "#{method_name}.update", :params => [{:triggerid=> data[:triggerid], :status => "1" }]).inspect + log '[DEBUG] disable :' + @client.api_request(:method => "#{method_name}.update", :params => [{:triggerid => data[:triggerid], :status => '1'}]).inspect # create new trigger data.delete(:triggerid) create(data) end - end + # Get or Create Trigger object using Zabbix API + # + # @param data [Hash] Needs to include description and hostid to properly identify Triggers via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" @@ -68,10 +90,15 @@ def get_or_create(data) id end + # Create or update Trigger object using Zabbix API + # + # @param data [Hash] Needs to include description and hostid to properly identify Triggers via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update(data) triggerid = get_id(:description => data[:description], :hostid => data[:hostid]) triggerid ? update(data.merge(:triggerid => triggerid)) : create(data) end - end end diff --git a/lib/zabbixapi/classes/unusable.rb b/lib/zabbixapi/classes/unusable.rb index bc3cf6d..23d01e7 100644 --- a/lib/zabbixapi/classes/unusable.rb +++ b/lib/zabbixapi/classes/unusable.rb @@ -1,10 +1,8 @@ class ZabbixApi class Triggers < Basic - def create_or_update(data) log "[DEBUG] Call create_or_update with parametrs: #{data.inspect}" get_or_create(data) end - end end diff --git a/lib/zabbixapi/classes/usergroups.rb b/lib/zabbixapi/classes/usergroups.rb index f028350..6770773 100644 --- a/lib/zabbixapi/classes/usergroups.rb +++ b/lib/zabbixapi/classes/usergroups.rb @@ -1,69 +1,76 @@ class ZabbixApi class Usergroups < Basic - + # The method name used for interacting with Usergroups via Zabbix API + # + # @return [String] def method_name - "usergroup" + 'usergroup' end + # The key field name used for Usergroup objects via Zabbix API + # + # @return [String] def key - "usrgrpid" + 'usrgrpid' end + # The id field name used for identifying specific Usergroup objects via Zabbix API + # + # @return [String] def indentify - "name" + 'name' end - # Set permission for usrgrp on some hostgroup + # Set permissions for usergroup using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :usrgrpids => id, :hostgroupids => [], :permission => 2,3 (read and read write) - # * *Returns* : - # - Integer + # @param data [Hash] Needs to include usrgrpids and hostgroupids along with permissions to set + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id (usergroup) def set_perms(data) permission = data[:permission] || 2 result = @client.api_request( - :method => "usergroup.massAdd", + :method => 'usergroup.massAdd', :params => { :usrgrpids => [data[:usrgrpid]], - :rights => data[:hostgroupids].map { |t| {:permission => permission, :id => t} } + :rights => data[:hostgroupids].map { |t| {:permission => permission, :id => t} }, } ) result ? result['usrgrpids'][0].to_i : nil end - # Update usergroup, add user + # Add users to usergroup using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :usrgrpids => id, :userids => [] - # * *Returns* : - # - Integer + # @param data [Hash] Needs to include userids and usrgrpids to mass add users to groups + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id (usergroup) def add_user(data) result = @client.api_request( - :method => "usergroup.massAdd", + :method => 'usergroup.massAdd', :params => { :usrgrpids => data[:usrgrpids], - :userids => data[:userids] + :userids => data[:userids], } ) result ? result['usrgrpids'][0].to_i : nil end - # Update usergroup, modify users + # Update users in usergroups using Zabbix API # - # * *Args* : - # - +data+ -> Hash with :usrgrpids => id, :userids => [] - # * *Returns* : - # - Integer + # @param data [Hash] Needs to include userids and usrgrpids to mass update users in groups + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id (usergroup) def update_users(data) result = @client.api_request( - :method => "usergroup.massUpdate", + :method => 'usergroup.massUpdate', :params => { :usrgrpids => data[:usrgrpids], - :userids => data[:userids] + :userids => data[:userids], } ) result ? result['usrgrpids'][0].to_i : nil end - end end diff --git a/lib/zabbixapi/classes/usermacros.rb b/lib/zabbixapi/classes/usermacros.rb index 92e389c..96029ee 100644 --- a/lib/zabbixapi/classes/usermacros.rb +++ b/lib/zabbixapi/classes/usermacros.rb @@ -1,79 +1,159 @@ class ZabbixApi class Usermacros < Basic + # The id field name used for identifying specific User macro objects via Zabbix API + # + # @return [String] def indentify - "macro" + 'macro' end + # The method name used for interacting with User macros via Zabbix API + # + # @return [String] def method_name - "usermacro" + 'usermacro' end + # Get User macro object id from Zabbix API based on provided data + # + # @param data [Hash] Needs to include macro to properly identify user macros via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call or missing object's id field name (indentify). + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_id(data) log "[DEBUG] Call get_id with parameters: #{data.inspect}" # symbolize keys if the user used string keys instead of symbols data = symbolize_keys(data) if data.key?(indentify) - # raise an error if indentify name was not supplied + # raise an error if indentify name was not supplied name = data[indentify.to_sym] - raise ApiError.new("#{indentify} not supplied in call to get_id") if name == nil + raise ApiError.new("#{indentify} not supplied in call to get_id") if name.nil? - result = request(data, "usermacro.get", "hostmacroid") + result = request(data, 'usermacro.get', 'hostmacroid') - result.length > 0 && result[0].key?("hostmacroid") ? result[0]["hostmacroid"].to_i : nil + !result.empty? && result[0].key?('hostmacroid') ? result[0]['hostmacroid'].to_i : nil end + # Get Global macro object id from Zabbix API based on provided data + # + # @param data [Hash] Needs to include macro to properly identify global macros via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call or missing object's id field name (indentify). + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_id_global(data) log "[DEBUG] Call get_id_global with parameters: #{data.inspect}" # symbolize keys if the user used string keys instead of symbols data = symbolize_keys(data) if data.key?(indentify) - # raise an error if indentify name was not supplied + # raise an error if indentify name was not supplied name = data[indentify.to_sym] - raise ApiError.new("#{indentify} not supplied in call to get_id") if name == nil + raise ApiError.new("#{indentify} not supplied in call to get_id") if name.nil? - result = request(data, "usermacro.get", "globalmacroid") + result = request(data, 'usermacro.get', 'globalmacroid') - result.length > 0 && result[0].key?("globalmacroid") ? result[0]["globalmacroid"].to_i : nil + !result.empty? && result[0].key?('globalmacroid') ? result[0]['globalmacroid'].to_i : nil end + # Get full/extended User macro data from Zabbix API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parameters: #{data.inspect}" - request(data, "usermacro.get", "hostmacroid") + request(data, 'usermacro.get', 'hostmacroid') end + # Get full/extended Global macro data from Zabbix API + # + # @param data [Hash] Should include object's id field name (indentify) and id value + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Hash] def get_full_data_global(data) log "[DEBUG] Call get_full_data_global with parameters: #{data.inspect}" - request(data, "usermacro.get", "globalmacroid") + request(data, 'usermacro.get', 'globalmacroid') end + # Create new User macro object using Zabbix API (with defaults) + # + # @param data [Hash] Needs to include hostid, macro, and value to create User macro via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created def create(data) - request(data, "usermacro.create", "hostmacroids") + request(data, 'usermacro.create', 'hostmacroids') end + # Create new Global macro object using Zabbix API (with defaults) + # + # @param data [Hash] Needs to include hostid, macro, and value to create Global macro via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created def create_global(data) - request(data, "usermacro.createglobal", "globalmacroids") + request(data, 'usermacro.createglobal', 'globalmacroids') end + # Delete User macro object using Zabbix API + # + # @param data [Hash] Should include hostmacroid's of User macros to delete + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is deleted + # @return [Boolean] True/False if multiple objects are deleted def delete(data) data_delete = [data] - request(data_delete, "usermacro.delete", "hostmacroids") + request(data_delete, 'usermacro.delete', 'hostmacroids') end + # Delete Global macro object using Zabbix API + # + # @param data [Hash] Should include hostmacroid's of Global macros to delete + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is deleted + # @return [Boolean] True/False if multiple objects are deleted def delete_global(data) data_delete = [data] - request(data_delete, "usermacro.deleteglobal", "globalmacroids") + request(data_delete, 'usermacro.deleteglobal', 'globalmacroids') end + # Update User macro object using Zabbix API + # + # @param data [Hash] Should include object's id field name (indentify), id value, and fields to update + # @param force [Boolean] Whether to force an object update even if provided data matches Zabbix + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created def update(data) - request(data, "usermacro.update", "hostmacroids") + request(data, 'usermacro.update', 'hostmacroids') end + # Update Global macro object using Zabbix API + # + # @param data [Hash] Should include object's id field name (indentify), id value, and fields to update + # @param force [Boolean] Whether to force an object update even if provided data matches Zabbix + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] The object id if a single object is created + # @return [Boolean] True/False if multiple objects are created def update_global(data) - request(data, "usermacro.updateglobal", "globalmacroids") + request(data, 'usermacro.updateglobal', 'globalmacroids') end + # Get or Create User macro object using Zabbix API + # + # @param data [Hash] Needs to include macro and hostid to properly identify User macros via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" @@ -83,6 +163,12 @@ def get_or_create(data) id end + # Get or Create Global macro object using Zabbix API + # + # @param data [Hash] Needs to include macro and hostid to properly identify Global macros via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def get_or_create_global(data) log "[DEBUG] Call get_or_create_global with parameters: #{data.inspect}" @@ -92,31 +178,51 @@ def get_or_create_global(data) id end + # Create or update User macro object using Zabbix API + # + # @param data [Hash] Needs to include macro and hostid to properly identify User macros via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update(data) hostmacroid = get_id(:macro => data[:macro], :hostid => data[:hostid]) hostmacroid ? update(data.merge(:hostmacroid => hostmacroid)) : create(data) end + # Create or update Global macro object using Zabbix API + # + # @param data [Hash] Needs to include macro and hostid to properly identify Global macros via Zabbix API + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id def create_or_update_global(data) hostmacroid = get_id_global(:macro => data[:macro], :hostid => data[:hostid]) hostmacroid ? update_global(data.merge(:globalmacroid => globalmacroid)) : create_global(data) end - private - def request(data, method, result_key) - # Zabbix has different result formats for gets vs updates - if method.include?(".get") - if result_key.include?("global") - result = @client.api_request(:method => method, :params => { :globalmacro => true, :filter => data }) - else - result = @client.api_request(:method => method, :params => { :filter => data }) - end + private + + # Custom request method to handle both User and Global macros in one + # + # @param data [Hash] Needs to include macro and hostid to properly identify Global macros via Zabbix API + # @param method [String] Zabbix API method to use for the request + # @param result_key [String] Which key to use for parsing results based on User vs Global macros + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id + def request(data, method, result_key) + # Zabbix has different result formats for gets vs updates + if method.include?('.get') + if result_key.include?('global') + @client.api_request(:method => method, :params => {:globalmacro => true, :filter => data}) else - result = @client.api_request(:method => method, :params => data) - - result.key?(result_key) && result[result_key].length > 0 ? result[result_key][0].to_i : nil + @client.api_request(:method => method, :params => {:filter => data}) end - end + else + result = @client.api_request(:method => method, :params => data) + result.key?(result_key) && !result[result_key].empty? ? result[result_key][0].to_i : nil + end + end end end diff --git a/lib/zabbixapi/classes/users.rb b/lib/zabbixapi/classes/users.rb index cfd20b2..2d42540 100644 --- a/lib/zabbixapi/classes/users.rb +++ b/lib/zabbixapi/classes/users.rb @@ -1,43 +1,65 @@ class ZabbixApi class Users < Basic - + # The method name used for interacting with Users via Zabbix API + # + # @return [String] def method_name - "user" + 'user' end + # The keys field name used for User objects via Zabbix API + # + # @return [String] def keys - "userids" + 'userids' end + # The key field name used for User objects via Zabbix API + # + # @return [String] def key - "userid" + 'userid' end + # The id field name used for identifying specific User objects via Zabbix API + # + # @return [String] def indentify - "alias" + 'alias' end + # Add media to users using Zabbix API + # + # @param data [Hash] Needs to include userids and media to mass add media to users + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id (media) def add_medias(data) result = @client.api_request( - :method => "user.addMedia", + :method => 'user.addMedia', :params => { :users => data[:userids].map { |t| {:userid => t} }, - :medias => data[:media] + :medias => data[:media], } ) result ? result['mediaids'][0].to_i : nil end + # Update media for users using Zabbix API + # + # @param data [Hash] Needs to include userids and media to mass update media for users + # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. + # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. + # @return [Integer] Zabbix object id (user) def update_medias(data) result = @client.api_request( - :method => "user.updateMedia", + :method => 'user.updateMedia', :params => { :users => data[:userids].map { |t| {:userid => t} }, - :medias => data[:media] + :medias => data[:media], } ) result ? result['userids'][0].to_i : nil end - end end diff --git a/lib/zabbixapi/client.rb b/lib/zabbixapi/client.rb index 80370f8..d42d415 100644 --- a/lib/zabbixapi/client.rb +++ b/lib/zabbixapi/client.rb @@ -1,20 +1,26 @@ +require 'http' require 'json' -require 'net/https' -require 'net/http' class ZabbixApi class Client + # @return [Hash] + attr_reader :options - attr :options - + # @return [Integer] def id - rand(100000) + rand(100_000) end + # Returns the API version from the Zabbix Server + # + # @return [String] def api_version - @version ||= api_request(:method => "apiinfo.version", :params => {}) + @version ||= api_request(:method => 'apiinfo.version', :params => {}) end + # Log in to the Zabbix Server and generate an auth token using the API + # + # @return [Hash] def auth api_request( :method => 'user.login', @@ -25,9 +31,13 @@ def auth ) end + # 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 + 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 @@ -39,39 +49,43 @@ def initialize(options = {}) @auth_hash = auth end + # Convert message body to JSON string for the Zabbix API + # + # @param body [Hash] + # @return [String] def message_json(body) message = { :method => body[:method], :params => body[:params], :id => id, - :jsonrpc => '2.0' + :jsonrpc => '2.0', } - message[:auth] = @auth_hash unless (body[:method] == 'apiinfo.version' or body[:method] == 'user.login') + message[:auth] = @auth_hash unless body[:method] == 'apiinfo.version' || body[:method] == 'user.login' JSON.generate(message) end + # @param body [String] + # @return [String] def http_request(body) uri = URI.parse(@options[:url]) + # set the time out the default (60) or to what the user passed - @options[:timeout] == nil ? timeout = 60 : timeout = @options[:timeout] + timeout = @options[:timeout].nil? ? 60 : @options[:timeout] puts "[DEBUG] Timeout for request set to #{timeout} seconds" if @options[:debug] - unless @proxy_uri.nil? + if @proxy_uri http = Net::HTTP.Proxy(@proxy_host, @proxy_port, @proxy_user, @proxy_pass).new(uri.host, uri.port) - - if uri.scheme == 'https' - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - end else http = Net::HTTP.new(uri.host, uri.port) - if uri.scheme == 'https' - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - end end + + if uri.scheme == 'https' + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + end + http.read_timeout = timeout request = Net::HTTP::Post.new(uri.request_uri) @@ -79,11 +93,15 @@ def http_request(body) request.add_field('Content-Type', 'application/json-rpc') request.body = body response = http.request(request) + raise HttpError.new("HTTP Error: #{response.code} on #{@options[:url]}", response) unless response.code == '200' + puts "[DEBUG] Get answer: #{response.body}" if @options[:debug] response.body end + # @param body [String] + # @return [Hash, String] def _request(body) puts "[DEBUG] Send request: #{body}" if @options[:debug] result = JSON.parse(http_request(body)) @@ -91,9 +109,12 @@ def _request(body) result['result'] end + # Execute Zabbix API requests and return response + # + # @param body [Hash] + # @return [Hash, String] def api_request(body) _request message_json(body) end - end end diff --git a/lib/zabbixapi/version.rb b/lib/zabbixapi/version.rb index c843298..65a99c5 100644 --- a/lib/zabbixapi/version.rb +++ b/lib/zabbixapi/version.rb @@ -1,3 +1,3 @@ class ZabbixApi - VERSION = "3.0.0" + VERSION = '3.0.0'.freeze end diff --git a/spec/action.rb b/spec/action.rb index 0aea729..a26629f 100644 --- a/spec/action.rb +++ b/spec/action.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -7,62 +7,62 @@ @actionname = gen_name 'action' @usergroupid = zbx.usergroups.create(:name => gen_name('usergroup')) @actiondata = { - :name => @actionname, - :eventsource => '0', # event source is a triggerid - :status => '0', # action is enabled - :esc_period => '120', # how long each step should take - :def_shortdata => "Email header", - :def_longdata => "Email content", - :maintenance_mode => '1', - :filter => { - :evaltype => '1', # perform 'and' between the conditions - :conditions => [ - { - :conditiontype => '3', # trigger name - :operator => '2', # like - :value => 'pattern' # the pattern - }, - { - :conditiontype => '4', # trigger severity - :operator => '5', # >= - :value => '3' # average - } - ] - }, - :operations => [ - { - :operationtype => '0', # send message - :opmessage_grp => [ # who the message will be sent to - { - :usrgrpid => @usergroupid - } - ], - :opmessage => { - :default_msg => '0', # use default message - :mediatypeid => '1' # email id - } - } + :name => @actionname, + :eventsource => '0', # event source is a triggerid + :status => '0', # action is enabled + :esc_period => '120', # how long each step should take + :def_shortdata => 'Email header', + :def_longdata => 'Email content', + :maintenance_mode => '1', + :filter => { + :evaltype => '1', # perform 'and' between the conditions + :conditions => [ + { + :conditiontype => '3', # trigger name + :operator => '2', # like + :value => 'pattern' # the pattern + }, + { + :conditiontype => '4', # trigger severity + :operator => '5', # >= + :value => '3' # average + }, ], - :recovery_operations => [ + }, + :operations => [ + { + :operationtype => '0', # send message + :opmessage_grp => [ # who the message will be sent to + { + :usrgrpid => @usergroupid, + }, + ], + :opmessage => { + :default_msg => '0', # use default message + :mediatypeid => '1' # email id + }, + }, + ], + :recovery_operations => [ + { + :operationtype => '11', # send recovery message + :opmessage_grp => [ # who the message will be sent to { - :operationtype => '11', # send recovery message - :opmessage_grp => [ # who the message will be sent to - { - :usrgrpid => @usergroupid - } - ], - :opmessage => { - :default_msg => '0', # use default message - :mediatypeid => '1' # email id - } - } - ] + :usrgrpid => @usergroupid, + }, + ], + :opmessage => { + :default_msg => '0', # use default message + :mediatypeid => '1' # email id + }, + }, + ], } end context 'when not exists' do describe 'create' do - it "should return integer id" do + it 'should return integer id' do actionid = zbx.actions.create(@actiondata) expect(actionid).to be_kind_of(Integer) end @@ -75,15 +75,15 @@ end describe 'create_or_update' do - it "should return id" do + it 'should return id' do expect(zbx.actions.create_or_update(@actiondata)).to eq @actionid end end describe 'delete' do - it "should return id" do + it 'should return id' do expect(zbx.actions.delete(@actionid)).to eq @actionid end - end + end end end diff --git a/spec/application.rb b/spec/application.rb index 5538836..ab8cbfa 100644 --- a/spec/application.rb +++ b/spec/application.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -19,7 +19,7 @@ end describe 'create' do - it "should return integer id" do + it 'should return integer id' do applicationid = zbx.applications.create( :name => @application, :hostid => @templateid @@ -29,7 +29,7 @@ end describe 'get_id' do - it "should return nil" do + it 'should return nil' do expect(zbx.applications.get_id(:name => @application)).to be_kind_of(NilClass) end end @@ -45,37 +45,41 @@ end describe 'get_or_create' do - it "should return id of application" do - expect(zbx.applications.get_or_create( - :name => @application, - :hostid => @templateid - )).to eq @applicationid + it 'should return id of application' do + expect( + zbx.applications.get_or_create( + :name => @application, + :hostid => @templateid + ) + ).to eq @applicationid end end describe 'get_full_data' do - it "should contains created application" do - expect(zbx.applications.get_full_data(:name => @application)[0]).to include("name" => @application) + it 'should contains created application' do + expect(zbx.applications.get_full_data(:name => @application)[0]).to include('name' => @application) end end describe 'get_id' do - it "should return id of application" do + it 'should return id of application' do expect(zbx.applications.get_id(:name => @application)).to eq @applicationid end end describe 'create_or_update' do - it "should return id of updated application" do - expect(zbx.applications.create_or_update( - :name => @application, - :hostid => @templateid - )).to eq @applicationid + it 'should return id of updated application' do + expect( + zbx.applications.create_or_update( + :name => @application, + :hostid => @templateid + ) + ).to eq @applicationid end end - describe "delete" do - it "should return id" do + describe 'delete' do + it 'should return id' do expect(zbx.applications.delete(@applicationid)).to eq @applicationid end end diff --git a/spec/configuration.rb b/spec/configuration.rb index 379d6b1..17d8ad0 100644 --- a/spec/configuration.rb +++ b/spec/configuration.rb @@ -1,30 +1,30 @@ -#encoding: utf-8 +# encoding: utf-8 -require "spec_helper" +require 'spec_helper' -describe "configuration" do +describe 'configuration' do before :all do - @hostgroup = gen_name "hostgroup" + @hostgroup = gen_name 'hostgroup' @hostgroup_id = zbx.hostgroups.create(:name => @hostgroup) - @template = gen_name "template" + @template = gen_name 'template' @template_id = zbx.templates.create( :host => @template, :groups => [:groupid => @hostgroup_id] ) @source = zbx.configurations.export( - :format => "xml", + :format => 'xml', :options => { - :templates => [@template_id] + :templates => [@template_id], } ) - @item = gen_name "item" + @item = gen_name 'item' @item_id = zbx.items.create( :name => @item, - :description => "item", - :key_ => "proc.num[aaa]", + :description => 'item', + :key_ => 'proc.num[aaa]', :type => 0, :value_type => 3, - :hostid => zbx.templates.get_id(:host => @template), + :hostid => zbx.templates.get_id(:host => @template) ) end @@ -34,89 +34,91 @@ zbx.hostgroups.delete(zbx.hostgroups.get_id(:name => @hostgroup)) end - context "when object not exists" do - describe "import with createMissing" do + context 'when object not exists' do + describe 'import with createMissing' do before do zbx.items.delete(@item_id) zbx.templates.delete(@template_id) zbx.hostgroups.delete(@hostgroup_id) zbx.configurations.import( - :format => "xml", + :format => 'xml', :rules => { :groups => { - :createMissing => true + :createMissing => true, }, :templates => { - :createMissing => true - } + :createMissing => true, + }, }, :source => @source ) end - it "should create object" do + it 'should create object' do expect(zbx.hostgroups.get_id(:name => @hostgroup)).to be_kind_of(Integer) expect(zbx.templates.get_id(:host => @template)).to be_kind_of(Integer) end end end - context "when object exists" do - - describe "export" do + context 'when object exists' do + describe 'export' do before do zbx.items.create( :name => @item, - :description => "item", - :key_ => "proc.num[aaa]", + :description => 'item', + :key_ => 'proc.num[aaa]', :type => 0, :value_type => 3, - :hostid => zbx.templates.get_id(:host => @template), + :hostid => zbx.templates.get_id(:host => @template) ) end - it "should export updated object" do - expect(zbx.configurations.export( - :format => "xml", - :options => { - :templates => [zbx.templates.get_id(:host => @template)] - } - )).to match(/#{@item}/) + it 'should export updated object' do + expect( + zbx.configurations.export( + :format => 'xml', + :options => { + :templates => [zbx.templates.get_id(:host => @template)], + } + ) + ).to match(/#{@item}/) end end - describe "import with updateExisting" do + describe 'import with updateExisting' do before do @source_updated = zbx.configurations.export( - :format => "xml", + :format => 'xml', :options => { - :templates => [zbx.templates.get_id(:host => @template)] + :templates => [zbx.templates.get_id(:host => @template)], } ) zbx.items.delete(zbx.items.get_id(:name => @item)) zbx.configurations.import( - :format => "xml", + :format => 'xml', :rules => { :templates => { - :updateExisting => true + :updateExisting => true, }, :items => { - :createMissing => true - } + :createMissing => true, + }, }, :source => @source_updated ) end - it "should update object" do - expect(zbx.configurations.export( - :format => "xml", - :options => { - :templates => [zbx.templates.get_id(:host => @template)] - } - )).to match(/#{@item}/) + it 'should update object' do + expect( + zbx.configurations.export( + :format => 'xml', + :options => { + :templates => [zbx.templates.get_id(:host => @template)], + } + ) + ).to match(/#{@item}/) end end end end - diff --git a/spec/graph.rb b/spec/graph.rb index df65ff3..28e393e 100644 --- a/spec/graph.rb +++ b/spec/graph.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -25,33 +25,32 @@ :applications => [@applicationid] ) - @color = "123456" + @color = '123456' end def gitems { :itemid => @itemid, - :calc_fnc => "3", + :calc_fnc => '3', :color => @color, - :type => "0", - :periods_cnt => "5" + :type => '0', + :periods_cnt => '5', } end - def create_graph(graph, itemid) + def create_graph(graph, _itemid) zbx.graphs.create( :gitems => [gitems], - :show_triggers => "0", + :show_triggers => '0', :name => graph, - :width => "900", - :height => "200" + :width => '900', + :height => '200' ) end - context 'when name not exists' do describe 'create' do - it "should return integer id" do + it 'should return integer id' do @graph = gen_name 'graph' expect(create_graph(@graph, @itemid)).to be_kind_of(Integer) end @@ -65,69 +64,75 @@ def create_graph(graph, itemid) end describe 'get_or_create' do - it "should return id of existing graph" do - expect(zbx.graphs.get_or_create( - :gitems => [gitems], - :show_triggers => "0", - :name => @graph, - :width => "900", - :height => "200" - )).to eq @graphid + it 'should return id of existing graph' do + expect( + zbx.graphs.get_or_create( + :gitems => [gitems], + :show_triggers => '0', + :name => @graph, + :width => '900', + :height => '200' + ) + ).to eq @graphid end end describe 'get_items' do - it "should return array" do - expect(zbx.graphs.get_items( @graphid )).to be_kind_of(Array) + it 'should return array' do + expect(zbx.graphs.get_items(@graphid)).to be_kind_of(Array) end - it "should return array of size 1" do - expect(zbx.graphs.get_items( @graphid ).size).to eq 1 + it 'should return array of size 1' do + expect(zbx.graphs.get_items(@graphid).size).to eq 1 end - it "should include correct item" do - expect(zbx.graphs.get_items( @graphid )[0]).to include("color" => @color) + it 'should include correct item' do + expect(zbx.graphs.get_items(@graphid)[0]).to include('color' => @color) end end describe 'get_id' do - it "should return id" do - expect(zbx.graphs.get_id( :name => @graph )).to eq @graphid + it 'should return id' do + expect(zbx.graphs.get_id(:name => @graph)).to eq @graphid end end describe 'get_ids_by_host' do - it "should contains id of graph" do - graph_array = zbx.graphs.get_ids_by_host( :host => @host ) + it 'should contains id of graph' do + graph_array = zbx.graphs.get_ids_by_host(:host => @host) expect(graph_array).to be_kind_of(Array) expect(graph_array).to include(@graphid.to_s) end end describe 'update' do - it "should return id" do - expect(zbx.graphs.update( - :graphid => @graphid, - :gitems => [gitems], - :ymax_type => 1 - )).to eq @graphid + it 'should return id' do + expect( + zbx.graphs.update( + :graphid => @graphid, + :gitems => [gitems], + :ymax_type => 1 + ) + ).to eq @graphid end end describe 'create_or_update' do - it "should return existing id" do - expect(zbx.graphs.create_or_update( - :gitems => [gitems], - :show_triggers => "1", - :name => @graph, - :width => "900", - :height => "200" - )).to eq @graphid + it 'should return existing id' do + expect( + zbx.graphs.create_or_update( + :gitems => [gitems], + :show_triggers => '1', + :name => @graph, + :width => '900', + :height => '200' + ) + ).to eq @graphid end end describe 'delete' do - it "should return true" do + it 'should return true' do expect(zbx.graphs.delete(@graphid)).to eq @graphid end end diff --git a/spec/host.rb b/spec/host.rb index 22af4a7..689188c 100644 --- a/spec/host.rb +++ b/spec/host.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -14,37 +14,47 @@ end describe 'create' do - it "should return integer id" do + it 'should return integer id' do hostid = zbx.hosts.create( :host => @host, :interfaces => [ { :type => 1, :main => 1, - :ip => "10.20.48.88", - :dns => "", - :port => 10050, - :useip => 1 - } + :ip => '10.20.48.88', + :dns => '', + :port => '10050', + :useip => 1, + }, ], :groups => [:groupid => @hostgroupid] ) expect(hostid).to be_kind_of(Integer) end - it "should create host in multiple groups" do + it 'should create host in multiple groups' do @hostgroupid2 = zbx.hostgroups.create(:name => gen_name('hostgroup')) host = gen_name('host') hostid = zbx.hosts.create( host: host, - interfaces: [{ type: 1, main: 1, ip: '192.168.0.1', dns: 'server.example.org', port: 10050, useip: 0 }], + interfaces: [ + { + type: 1, + main: 1, + ip: '192.168.0.1', + dns: 'server.example.org', + port: '10050', + useip: 0, + }, + ], groups: [ {groupid: @hostgroupid}, - {groupid: @hostgroupid2} - ]) + {groupid: @hostgroupid2}, + ] + ) expect(hostid).to be_kind_of Integer - host = zbx.query(method: 'host.get', params: { hostids: [hostid], selectGroups: 'extend' }).first + host = zbx.query(method: 'host.get', params: {hostids: [hostid], selectGroups: 'extend'}).first expect(host['hostid'].to_i).to eq hostid expect(host['groups'].size).to eq 2 @@ -52,7 +62,7 @@ end describe 'get_id' do - it "should return nil" do + it 'should return nil' do expect(zbx.hosts.get_id(:host => @host)).to be_kind_of(NilClass) expect(zbx.hosts.get_id('host' => @host)).to be_kind_of(NilClass) end @@ -68,108 +78,118 @@ { :type => 1, :main => 1, - :ip => "10.20.48.88", - :dns => "", - :port => 10050, - :useip => 1 - } + :ip => '10.20.48.88', + :dns => '', + :port => '10050', + :useip => 1, + }, ], :groups => [:groupid => @hostgroupid] ) end describe 'get_or_create' do - it "should return id of host" do - expect(zbx.hosts.get_or_create( - :host => @host, - :groups => [:groupid => @hostgroupid] - )).to eq @hostid + it 'should return id of host' do + expect( + zbx.hosts.get_or_create( + :host => @host, + :groups => [:groupid => @hostgroupid] + ) + ).to eq @hostid end end describe 'get_full_data' do - it "should contains created host" do - expect(zbx.hosts.get_full_data(:host => @host)[0]).to include("host" => @host) + it 'should contains created host' do + expect(zbx.hosts.get_full_data(:host => @host)[0]).to include('host' => @host) end end describe 'get_id' do - it "should return id of host" do + it 'should return id of host' do expect(zbx.hosts.get_id(:host => @host)).to eq @hostid expect(zbx.hosts.get_id('host' => @host)).to eq @hostid end end describe 'create_or_update' do - it "should return id of updated host" do - expect(zbx.hosts.create_or_update( - :host => @host, - :interfaces => [ - { - :type => 1, - :main => 1, - :ip => "10.20.48.89", - :port => 10050, - :useip => 1, - :dns => '' - } - ], - :groups => [:groupid => @hostgroupid] - )).to eq @hostid + it 'should return id of updated host' do + expect( + zbx.hosts.create_or_update( + :host => @host, + :interfaces => [ + { + :type => 1, + :main => 1, + :ip => '10.20.48.89', + :port => '10050', + :useip => 1, + :dns => '', + }, + ], + :groups => [:groupid => @hostgroupid] + ) + ).to eq @hostid end end describe 'update' do - it "should return id" do - expect(zbx.hosts.update( - :hostid => @hostid, - :status => 0 - )).to eq @hostid + it 'should return id' do + expect( + zbx.hosts.update( + :hostid => @hostid, + :status => 0 + ) + ).to eq @hostid end - it "should update groups" do + it 'should update groups' do @hostgroupid2 = zbx.hostgroups.create(:name => gen_name('hostgroup')) - expect(zbx.hosts.update( - :hostid => @hostid, - :groups => [ :groupid => @hostgroupid2] - )).to eq @hostid - - expect(zbx.hosts.dump_by_id(:hostid => @hostid).first['groups'].first["groupid"]).to eq @hostgroupid2.to_s + expect( + zbx.hosts.update( + :hostid => @hostid, + :groups => [:groupid => @hostgroupid2] + ) + ).to eq @hostid + expect(zbx.hosts.dump_by_id(:hostid => @hostid).first['groups'].first['groupid']).to eq @hostgroupid2.to_s end - it "should update interfaces when use with force: true" do + it 'should update interfaces when use with force: true' do new_ip = '1.2.3.4' zbx.hosts.update( - {:hostid => @hostid, - :interfaces => [ - { - :type => 1, - :main => 1, - :ip => new_ip, - :port => 10050, - :useip => 1, - :dns => '' - } - ]}, true) + { + :hostid => @hostid, + :interfaces => [ + { + :type => 1, + :main => 1, + :ip => new_ip, + :port => '10050', + :useip => 1, + :dns => '', + }, + ], + }, + true + ) h = zbx.query( method: 'host.get', params: { hostids: @hostid, - selectInterfaces: 'extend' + selectInterfaces: 'extend', } ).first expect(h['interfaces'].first['ip']).to eq new_ip end - end describe 'delete' do - it "HOST: Delete" do - expect(zbx.hosts.delete( @hostid )).to eq @hostid + it 'HOST: Delete' do + expect(zbx.hosts.delete(@hostid)).to eq @hostid end end end diff --git a/spec/hostgroup.rb b/spec/hostgroup.rb index 561631f..0e867c0 100644 --- a/spec/hostgroup.rb +++ b/spec/hostgroup.rb @@ -1,11 +1,11 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' describe 'hostgroup' do context 'when not exists' do describe 'create' do - it "should return integer id after creation" do + it 'should return integer id after creation' do hostgroupid = zbx.hostgroups.create(:name => "hostgroup_#{rand(1_000_000)}") expect(hostgroupid).to be_kind_of(Integer) end @@ -19,35 +19,35 @@ end describe 'get_id' do - it "should return id" do + it 'should return id' do expect(zbx.hostgroups.get_id(:name => @hostgroup)).to eq @hostgroupid end - it "should return nil for not existing group" do + it 'should return nil for not existing group' do expect(zbx.hostgroups.get_id(:name => "#{@hostgroup}______")).to be_kind_of(NilClass) end end describe 'get_or_create' do - it "should return id of existing hostgroup" do + it 'should return id of existing hostgroup' do expect(zbx.hostgroups.get_or_create(:name => @hostgroup)).to eq @hostgroupid end end describe 'create_or_update' do - it "should return id of hostgroup" do + it 'should return id of hostgroup' do expect(zbx.hostgroups.create_or_update(:name => @hostgroup)).to eq @hostgroupid end end describe 'all' do - it "should contains created hostgroup" do + it 'should contains created hostgroup' do expect(zbx.hostgroups.all).to include(@hostgroup => @hostgroupid.to_s) end end - describe "delete" do - it "shold return id" do + describe 'delete' do + it 'shold return id' do expect(zbx.hostgroups.delete(@hostgroupid)).to eq @hostgroupid end end diff --git a/spec/httptest.rb b/spec/httptest.rb index 5e4ff2f..2550a30 100644 --- a/spec/httptest.rb +++ b/spec/httptest.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -20,17 +20,17 @@ end describe 'create' do - it "should return integer id" do + it 'should return integer id' do httptestid = zbx.httptests.create( :name => @httptest_name, :hostid => @templateid, :steps => [ { :name => @step_name, - :url => "http://localhost/zabbix/", + :url => 'http://localhost/zabbix/', :status_codes => 200, - :no => 1 - } + :no => 1, + }, ] ) expect(httptestid).to be_kind_of(Integer) @@ -38,13 +38,13 @@ end describe 'get_id' do - it "should return nil" do + it 'should return nil' do expect(zbx.httptests.get_id(:name => @httptest_name)).to be_kind_of(NilClass) expect(zbx.httptests.get_id('name' => @httptest_name)).to be_kind_of(NilClass) end end end - + context 'when name exists' do before :all do @httptest_name = gen_name 'httptest_name' @@ -55,81 +55,87 @@ :steps => [ { :name => @step_name, - :url => "http://localhost/zabbix/", + :url => 'http://localhost/zabbix/', :status_codes => 200, - :no => 1 - } + :no => 1, + }, ] ) end describe 'get_or_create' do - it "should return id of httptest" do - expect(zbx.httptests.get_or_create( - :name => @httptest_name, - :hostid => @templateid, - :steps => [ - { - :name => @step_name, - :url => "http://localhost/zabbix/", - :status_codes => 200, - :no => 1 - } - ] - )).to eq @httptestid + it 'should return id of httptest' do + expect( + zbx.httptests.get_or_create( + :name => @httptest_name, + :hostid => @templateid, + :steps => [ + { + :name => @step_name, + :url => 'http://localhost/zabbix/', + :status_codes => 200, + :no => 1, + }, + ] + ) + ).to eq @httptestid end end describe 'get_full_data' do - it "should contain created httptest" do - expect(zbx.httptests.get_full_data(:name => @httptest_name)[0]).to include("name" => @httptest_name) + it 'should contain created httptest' do + expect(zbx.httptests.get_full_data(:name => @httptest_name)[0]).to include('name' => @httptest_name) end end describe 'get_id' do - it "should return id of httptest" do + it 'should return id of httptest' do expect(zbx.httptests.get_id(:name => @httptest_name)).to eq @httptestid expect(zbx.httptests.get_id('name' => @httptest_name)).to eq @httptestid end end describe 'create_or_update' do - it "should return id of updated httptest" do - expect(zbx.httptests.create_or_update( - :name => @httptest_name, - :hostid => @templateid, - :steps => [ - { - :name => @step_name, - :url => "http://localhost/zabbix/", - :status_codes => 200, - :no => 1 - } - ] - )).to eq @httptestid + it 'should return id of updated httptest' do + expect( + zbx.httptests.create_or_update( + :name => @httptest_name, + :hostid => @templateid, + :steps => [ + { + :name => @step_name, + :url => 'http://localhost/zabbix/', + :status_codes => 200, + :no => 1, + }, + ] + ) + ).to eq @httptestid end end describe 'update' do - it "should return id" do - expect(zbx.httptests.update( - :httptestid => @httptestid, - :status => 0, - :steps => [ - { - :name => @step_name, - :url => "http://localhost/zabbix/", - :status_codes => 200, - :no => 1 - } - ] - )).to eq @httptestid + it 'should return id' do + expect( + zbx.httptests.update( + :httptestid => @httptestid, + :status => 0, + :steps => [ + { + :name => @step_name, + :url => 'http://localhost/zabbix/', + :status_codes => 200, + :no => 1, + }, + ] + ) + ).to eq @httptestid end end describe 'delete' do - it "HTTPTEST: Delete" do - expect(zbx.httptests.delete( @httptestid )).to eq @httptestid + it 'HTTPTEST: Delete' do + expect(zbx.httptests.delete(@httptestid)).to eq @httptestid end end end diff --git a/spec/item.rb b/spec/item.rb index 3d2e6e1..3d71a5b 100644 --- a/spec/item.rb +++ b/spec/item.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -24,7 +24,7 @@ end describe 'create' do - it "should return integer id" do + it 'should return integer id' do itemid = zbx.items.create( :name => @item, :key_ => "proc.num[#{gen_name 'proc'}]", @@ -37,7 +37,7 @@ end describe 'get_id' do - it "should return nil" do + it 'should return nil' do expect(zbx.items.get_id(:name => @item)).to be_kind_of(NilClass) end end @@ -48,7 +48,7 @@ @item = gen_name 'item' @itemid = zbx.items.create( :name => @item, - :key_ => "proc.num[aaa]", + :key_ => 'proc.num[aaa]', :status => 0, :hostid => @templateid, :applications => [@applicationid] @@ -56,56 +56,62 @@ end describe 'get_or_create' do - it "should return id of item" do - expect(zbx.items.get_or_create( - :name => @item, - :key_ => "proc.num[#{gen_name 'proc'}]", - :status => 0, - :hostid => @templateid, - :applications => [@applicationid] - )).to eq @itemid + it 'should return id of item' do + expect( + zbx.items.get_or_create( + :name => @item, + :key_ => "proc.num[#{gen_name 'proc'}]", + :status => 0, + :hostid => @templateid, + :applications => [@applicationid] + ) + ).to eq @itemid end end describe 'get_full_data' do - it "should contains created item" do - expect(zbx.items.get_full_data(:name => @item)[0]).to include("name" => @item) + it 'should contains created item' do + expect(zbx.items.get_full_data(:name => @item)[0]).to include('name' => @item) end end describe 'get_id' do - it "should return id of item" do + it 'should return id of item' do expect(zbx.items.get_id(:name => @item)).to eq @itemid end end - it "should raise error on no identity given" do - expect { zbx.items.get_id({}) }.to raise_error(ZabbixApi::ApiError) + it 'should raise error on no identity given' do + expect { zbx.items.get_id({}) }.to raise_error(ZabbixApi::ApiError) end describe 'update' do - it "should return id" do - expect(zbx.items.update( - :itemid => zbx.items.get_id(:name => @item), - :status => 1 - )).to eq @itemid + it 'should return id' do + expect( + zbx.items.update( + :itemid => zbx.items.get_id(:name => @item), + :status => 1 + ) + ).to eq @itemid end end describe 'create_or_update' do - it "should update existing item" do - expect(zbx.items.create_or_update( - :name => @item, - :key_ => "proc.num[#{gen_name 'proc'}]", - :status => 0, - :hostid => @templateid, - :applications => [@applicationid] - )).to eq @itemid + it 'should update existing item' do + expect( + zbx.items.create_or_update( + :name => @item, + :key_ => "proc.num[#{gen_name 'proc'}]", + :status => 0, + :hostid => @templateid, + :applications => [@applicationid] + ) + ).to eq @itemid end - it "should create item" do + it 'should create item' do new_item_id = zbx.items.create_or_update( - :name => @item + "____1", + :name => @item + '____1', :key_ => "proc.num[#{gen_name 'proc'}]", :status => 0, :hostid => @templateid, @@ -122,11 +128,11 @@ @result = zbx.items.delete(@itemid) end - it "should return deleted id" do + it 'should return deleted id' do expect(@result).to eq @itemid end - it "should delete item from zabbix" do + it 'should delete item from zabbix' do expect(zbx.items.get_id(:name => @item)).to be_nil end end diff --git a/spec/maintenance.rb b/spec/maintenance.rb index eaafa11..0c2b981 100644 --- a/spec/maintenance.rb +++ b/spec/maintenance.rb @@ -1,81 +1,81 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' describe 'maintenance' do context 'when not exists' do - before :all do - @hostgroupid = zbx.hostgroups.create(:name => "hostgroup_#{rand(1_000_000)}") - end - + before :all do + @hostgroupid = zbx.hostgroups.create(:name => "hostgroup_#{rand(1_000_000)}") + end + describe 'create' do - it "should return integer id after creation" do - maintenanceid = zbx.maintenance.create(:name => "maintenance_#{rand(1_000_000)}", - :groupids => [ @hostgroupid ], - :active_since => 1358844540, - :active_till => 1390466940, - :timeperiods => [ :timeperiod_type => 3, :every => 1, :dayofweek => 64, :start_time => 64800, :period => 3600 ] - ) + it 'should return integer id after creation' do + maintenanceid = zbx.maintenance.create( + :name => "maintenance_#{rand(1_000_000)}", + :groupids => [@hostgroupid], + :active_since => '1358844540', + :active_till => '1390466940', + :timeperiods => [:timeperiod_type => 3, :every => 1, :dayofweek => 64, :start_time => 64_800, :period => 3_600] + ) expect(maintenanceid).to be_kind_of(Integer) - zbx.maintenance.delete(maintenanceid) + zbx.maintenance.delete(maintenanceid) end end - - after :all do - zbx.hostgroups.delete(@hostgroupid) - end + after :all do + zbx.hostgroups.delete(@hostgroupid) + end end context 'when exists' do before :all do - @hostgroupid_when_exists = zbx.hostgroups.create(:name => "hostgroup_#{rand(1_000_000)}") + @hostgroupid_when_exists = zbx.hostgroups.create(:name => "hostgroup_#{rand(1_000_000)}") @maintenance = gen_name('maintenance') - @maintenanceid = zbx.maintenance.create(:name => @maintenance, - :groupids => [ @hostgroupid_when_exists ], - :active_since => 1358844540, - :active_till => 1390466940, - :timeperiods => [ :timeperiod_type => 3, :every => 1, :dayofweek => 64, :start_time => 64800, :period => 3600 ] - ) + @maintenanceid = zbx.maintenance.create( + :name => @maintenance, + :groupids => [@hostgroupid_when_exists], + :active_since => '1358844540', + :active_till => '1390466940', + :timeperiods => [:timeperiod_type => 3, :every => 1, :dayofweek => 64, :start_time => 64_800, :period => 3_600] + ) end describe 'get_id' do - it "should return id" do + it 'should return id' do expect(zbx.maintenance.get_id(:name => @maintenance)).to eq @maintenanceid end - it "should return nil for not existing group" do + it 'should return nil for not existing group' do expect(zbx.maintenance.get_id(:name => "#{@maintenance}______")).to be_kind_of(NilClass) end end describe 'get_or_create' do - it "should return id of existing maintenance" do + it 'should return id of existing maintenance' do expect(zbx.maintenance.get_or_create(:name => @maintenance)).to eq @maintenanceid end end describe 'create_or_update' do - it "should return id of maintenance" do + it 'should return id of maintenance' do expect(zbx.maintenance.create_or_update(:name => @maintenance)).to eq @maintenanceid end end describe 'all' do - it "should contains created maintenance" do + it 'should contains created maintenance' do expect(zbx.maintenance.all).to include(@maintenance => @maintenanceid.to_s) end end - describe "delete" do - it "shold return id" do + describe 'delete' do + it 'shold return id' do expect(zbx.maintenance.delete(@maintenanceid)).to eq @maintenanceid end end - - after :all do - zbx.hostgroups.delete(@hostgroupid_when_exists) - end + after :all do + zbx.hostgroups.delete(@hostgroupid_when_exists) + end end end diff --git a/spec/mediatype.rb b/spec/mediatype.rb index 2859309..d9dad6c 100644 --- a/spec/mediatype.rb +++ b/spec/mediatype.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -9,16 +9,16 @@ context 'when not exists' do describe 'create' do - it "should return integer id" do - mediatypeid = zbx.mediatypes.create( - :description => @mediatype, - :type => 0, - :smtp_server => "127.0.0.1", - :smtp_email => "zabbix@test.com", - :smtp_helo => "test.com" - ) - expect(mediatypeid).to be_kind_of(Integer) - end + it 'should return integer id' do + mediatypeid = zbx.mediatypes.create( + :description => @mediatype, + :type => 0, + :smtp_server => '127.0.0.1', + :smtp_email => 'zabbix@test.com', + :smtp_helo => 'test.com' + ) + expect(mediatypeid).to be_kind_of(Integer) + end end end @@ -27,22 +27,24 @@ @mediatypeid = zbx.mediatypes.create( :description => @mediatype, :type => 0, - :smtp_server => "127.0.0.1", - :smtp_email => "zabbix@test.com", - :smtp_helo => "test.com" + :smtp_server => '127.0.0.1', + :smtp_email => 'zabbix@test.com', + :smtp_helo => 'test.com' ) end describe 'create_or_update' do - it "should return id" do - expect(zbx.mediatypes.create_or_update( - :description => @mediatype, - :smtp_email => "zabbix2@test.com", - :smtp_helo => "test.com" - )).to eq @mediatypeid + it 'should return id' do + expect( + zbx.mediatypes.create_or_update( + :description => @mediatype, + :smtp_email => 'zabbix2@test.com', + :smtp_helo => 'test.com' + ) + ).to eq @mediatypeid end - it "should return id" do + it 'should return id' do expect(@mediatypeid).to eq @mediatypeid end end diff --git a/spec/query.rb b/spec/query.rb index 3851613..26809e9 100644 --- a/spec/query.rb +++ b/spec/query.rb @@ -1,18 +1,19 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' -describe "query" do - it "should works" do - expect(zbx.query( - method: 'host.get', - params: { - filter: { - host: 'asdf' - }, - selectInterfaces: 'refer' - } - )).to be_kind_of(Array) +describe 'query' do + it 'should works' do + expect( + zbx.query( + method: 'host.get', + params: { + filter: { + host: 'asdf', + }, + selectInterfaces: 'refer', + } + ) + ).to be_kind_of(Array) end end - diff --git a/spec/screen.rb b/spec/screen.rb index ccfd7c6..59d1fd7 100644 --- a/spec/screen.rb +++ b/spec/screen.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -25,24 +25,24 @@ :applications => [@applicationid] ) - @color = "123456" + @color = '123456' @gitems = { :itemid => @itemid, - :calc_fnc => "3", + :calc_fnc => '3', :color => @color, - :type => "0", - :periods_cnt => "5" + :type => '0', + :periods_cnt => '5', } @graph = gen_name 'graph' @graphid = zbx.graphs.create( :gitems => [@gitems], - :show_triggers => "0", + :show_triggers => '0', :name => @graph, - :width => "900", - :height => "200" + :width => '900', + :height => '200' ) @screen_name = gen_name 'screen' @@ -50,7 +50,7 @@ context 'when not exists' do describe 'get_or_create_for_host' do - it "should return id" do + it 'should return id' do screenid = zbx.screens.get_or_create_for_host( :screen_name => @screen_name, :graphids => [@graphid] @@ -70,7 +70,7 @@ end describe 'get_or_create_for_host' do - it "should return id" do + it 'should return id' do screenid = zbx.screens.get_or_create_for_host( :screen_name => @screen_name, :graphids => [@graphid] @@ -80,7 +80,7 @@ end describe 'delete' do - it "should return id" do + it 'should return id' do expect(zbx.screens.delete(@screenid)).to eq @screenid end end diff --git a/spec/server.rb b/spec/server.rb index 9129da4..8d09a66 100644 --- a/spec/server.rb +++ b/spec/server.rb @@ -1,14 +1,14 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' describe 'server' do describe 'version' do - it "should be string" do + it 'should be string' do expect(zbx.server.version).to be_kind_of(String) end - it "should be 2.4.x or 3.0.x or 3.2.x" do + it 'should be 2.4.x or 3.0.x or 3.2.x' do expect(zbx.server.version).to match(/(2\.4|3\.[02])\.\d+/) end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index ad93628..6143226 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,6 +1,5 @@ require 'zabbixapi' - def zbx # settings @api_url = ENV['ZABBIX_HOST_URL'] || 'http://10.211.55.6/api_jsonrpc.php' @@ -11,7 +10,7 @@ def zbx :url => @api_url, :user => @api_login, :password => @api_password, - :debug => ENV['ZABBIX_DEBUG']? true : false + :debug => ENV['ZABBIX_DEBUG'] ? true : false ) end diff --git a/spec/template.rb b/spec/template.rb index a328b75..3569879 100644 --- a/spec/template.rb +++ b/spec/template.rb @@ -1,20 +1,20 @@ -#encoding: utf-8 +# encoding: utf-8 -require "spec_helper" +require 'spec_helper' -describe "template" do +describe 'template' do before :all do - @hostgroup = gen_name "hostgroup" + @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(:name => @hostgroup) end - context "when name not exists" do + context 'when name not exists' do before do - @template = gen_name "template" + @template = gen_name 'template' end - describe "create" do - it "should return integer id" do + describe 'create' do + it 'should return integer id' do templateid = zbx.templates.create( :host => @template, :groups => [:groupid => @hostgroupid] @@ -23,52 +23,54 @@ end end - describe "get_id" do - it "should return nil" do + describe 'get_id' do + it 'should return nil' do expect(zbx.templates.get_id(:host => @template)).to be_kind_of(NilClass) end end end - context "when name exists" do + context 'when name exists' do before :all do - @template = gen_name "template" + @template = gen_name 'template' @templateid = zbx.templates.create( :host => @template, :groups => [:groupid => @hostgroupid] ) end - describe "get_or_create" do - it "should return id of template" do - expect(zbx.templates.get_or_create( - :host => @template, - :groups => [:groupid => @hostgroupid] - )).to eq @templateid + describe 'get_or_create' do + it 'should return id of template' do + expect( + zbx.templates.get_or_create( + :host => @template, + :groups => [:groupid => @hostgroupid] + ) + ).to eq @templateid end end - describe "get_full_data" do - it "should contains created template" do - expect(zbx.templates.get_full_data(:host => @template)[0]).to include("host" => @template) + describe 'get_full_data' do + it 'should contains created template' do + expect(zbx.templates.get_full_data(:host => @template)[0]).to include('host' => @template) end end - describe "get_id" do - it "should return id of template" do + describe 'get_id' do + it 'should return id of template' do expect(zbx.templates.get_id(:host => @template)).to eq @templateid end end - describe "all" do - it "should contains template" do + describe 'all' do + it 'should contains template' do expect(zbx.templates.all).to include(@template => @templateid.to_s) end end - describe "delete" do - it "should return id" do - template = gen_name "template" + describe 'delete' do + it 'should return id' do + template = gen_name 'template' templateid = zbx.templates.create( :host => template, :groups => [:groupid => @hostgroupid] @@ -77,7 +79,7 @@ end end - context "host related operations" do + context 'host related operations' do before :all do @host = gen_name 'host' @hostid = zbx.hosts.create( @@ -86,28 +88,30 @@ { :type => 1, :main => 1, - :ip => "10.20.48.88", - :dns => "", - :port => 10050, - :useip => 1 - } + :ip => '10.20.48.88', + :dns => '', + :port => '10050', + :useip => 1, + }, ], :groups => [:groupid => @hostgroupid] ) end - context "not linked with host" do - describe "mass_update" do - it "should return true" do - expect(zbx.templates.mass_update( - :hosts_id => [@hostid], - :templates_id => [@templateid] - )).to be true + context 'not linked with host' do + describe 'mass_update' do + it 'should return true' do + expect( + zbx.templates.mass_update( + :hosts_id => [@hostid], + :templates_id => [@templateid] + ) + ).to be true end end end - context "linked with host" do + context 'linked with host' do before :all do zbx.templates.mass_update( :hosts_id => [@hostid], @@ -115,8 +119,8 @@ ) end - describe "get_ids_by_host" do - it "should contains id of linked template" do + describe 'get_ids_by_host' do + it 'should contains id of linked template' do tmpl_array = zbx.templates.get_ids_by_host( :hostids => [@hostid] ) @@ -125,21 +129,25 @@ end end - describe "mass_add" do - it "should return true" do - expect(zbx.templates.mass_add( - :hosts_id => [@hostid], - :templates_id => [@templateid] - )).to be_kind_of(TrueClass) + describe 'mass_add' do + it 'should return true' do + expect( + zbx.templates.mass_add( + :hosts_id => [@hostid], + :templates_id => [@templateid] + ) + ).to be_kind_of(TrueClass) end end - describe "mass_remove" do - it "should return true" do - expect(zbx.templates.mass_remove( - :hosts_id => [@hostid], - :templates_id => [@templateid] - )).to be true + describe 'mass_remove' do + it 'should return true' do + expect( + zbx.templates.mass_remove( + :hosts_id => [@hostid], + :templates_id => [@templateid] + ) + ).to be true end end end diff --git a/spec/trigger.rb b/spec/trigger.rb index 33de2dd..bdbccbd 100644 --- a/spec/trigger.rb +++ b/spec/trigger.rb @@ -1,13 +1,12 @@ +# encoding: utf-8 -#encoding: utf-8 +require 'spec_helper' -require "spec_helper" - -describe "trigger" do +describe 'trigger' do before :all do - @hostgroup = gen_name "hostgroup" + @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(:name => @hostgroup) - @template = gen_name "template" + @template = gen_name 'template' @templateid = zbx.templates.create( :host => @template, :groups => [:groupid => @hostgroupid] @@ -26,29 +25,28 @@ :hostid => @templateid, :applications => [@applicationid] ) - end - context "when name not exists" do - describe "create" do - it "should return integer id" do + context 'when name not exists' do + describe 'create' do + it 'should return integer id' do @trigger = gen_name 'trigger' triggerid = zbx.triggers.create( :description => @trigger, :expression => "{#{@template}:#{@proc}.last(0)}<1", - :comments => "Bla-bla is faulty (disaster)", + :comments => 'Bla-bla is faulty (disaster)', :priority => 5, :status => 0, :type => 0, :tags => [ { - :tag => "proc", - :value => "#{@proc}" + :tag => 'proc', + :value => @proc.to_s, }, { - :tag => "error", - :value => "" - } + :tag => 'error', + :value => '', + }, ] ) expect(triggerid).to be_kind_of(Integer) @@ -56,47 +54,49 @@ end end - context "when name exists" do + context 'when name exists' do before :all do @trigger = gen_name 'trigger' @triggerid = zbx.triggers.create( :description => @trigger, :expression => "{#{@template}:#{@proc}.last(0)}<1", - :comments => "Bla-bla is faulty (disaster)", + :comments => 'Bla-bla is faulty (disaster)', :priority => 5, :status => 0, :type => 0, :tags => [ { - :tag => "proc", - :value => "#{@proc}" + :tag => 'proc', + :value => @proc.to_s, }, { - :tag => "error", - :value => "" - } + :tag => 'error', + :value => '', + }, ] ) end - describe "get_id" do - it "should return id" do + describe 'get_id' do + it 'should return id' do expect(zbx.triggers.get_id(:description => @trigger)).to eq @triggerid end end describe 'create_or_update' do - it "should return id of updated trigger" do - expect(zbx.triggers.create_or_update( - :description => @trigger, - :hostid => @templateid - )).to eq @triggerid + it 'should return id of updated trigger' do + expect( + zbx.triggers.create_or_update( + :description => @trigger, + :hostid => @templateid + ) + ).to eq @triggerid end end - describe "delete" do - it "should return id" do - expect(zbx.triggers.delete( @triggerid )).to eq @triggerid + describe 'delete' do + it 'should return id' do + expect(zbx.triggers.delete(@triggerid)).to eq @triggerid end end end diff --git a/spec/user.rb b/spec/user.rb index 7cc90ae..129fb69 100644 --- a/spec/user.rb +++ b/spec/user.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -11,25 +11,25 @@ @mediatypeid = zbx.mediatypes.create( :description => @mediatype, :type => 0, - :smtp_server => "127.0.0.1", - :smtp_email => "zabbix@test.com", - :smtp_helo => "test.com" + :smtp_server => '127.0.0.1', + :smtp_email => 'zabbix@test.com', + :smtp_helo => 'test.com' ) end def media { :mediatypeid => @mediatypeid, - :sendto => "test@test", + :sendto => 'test@test', :active => 0, - :period => "1-7,00:00-24:00", - :severity => "56" + :period => '1-7,00:00-24:00', + :severity => '56', } end context 'when not exists' do describe 'create' do - it "should return integer id" do + it 'should return integer id' do user = gen_name 'user' userid = zbx.users.create( :alias => user, @@ -43,8 +43,8 @@ def media end describe 'get_id' do - it "should return nil" do - expect(zbx.users.get_id(:alias => "name_____")).to be_nil + it 'should return nil' do + expect(zbx.users.get_id(:alias => 'name_____')).to be_nil end end end @@ -62,39 +62,43 @@ def media end describe 'create_or_update' do - it "should return id" do - expect(zbx.users.create_or_update( - :alias => @user, - :name => @user, - :surname => @user, - :passwd => @user - )).to eq @userid + it 'should return id' do + expect( + zbx.users.create_or_update( + :alias => @user, + :name => @user, + :surname => @user, + :passwd => @user + ) + ).to eq @userid end end describe 'get_full_data' do - it "should return string name" do + it 'should return string name' do expect(zbx.users.get_full_data(:alias => @user)[0]['name']).to be_kind_of(String) end end describe 'update' do - it "should return id" do + it 'should return id' do expect(zbx.users.update(:userid => @userid, :name => gen_name('user'))).to eq @userid end end describe 'add_medias' do - it "should return integer media id" do - expect(zbx.users.add_medias( - :userids => [@userid], - :media => [media] - )).to be_kind_of(Integer) + it 'should return integer media id' do + expect( + zbx.users.add_medias( + :userids => [@userid], + :media => [media] + ) + ).to be_kind_of(Integer) end end describe 'update_medias' do - it "should return the user id" do + it 'should return the user id' do # Call twice to ensure update_medias first successfully creates the media, then updates it 2.times do returned_userid = zbx.users.update_medias( @@ -108,7 +112,7 @@ def media end describe 'delete' do - it "should return id" do + it 'should return id' do expect(zbx.users.delete(@userid)).to eq @userid end end diff --git a/spec/usergroup.rb b/spec/usergroup.rb index bc0592b..4e507e4 100644 --- a/spec/usergroup.rb +++ b/spec/usergroup.rb @@ -1,11 +1,10 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' describe 'usergroup' do - context 'when not exists' do - it "should be integer id" do + it 'should be integer id' do usergroupid = zbx.usergroups.create(:name => gen_name('usergroup')) expect(usergroupid).to be_kind_of(Integer) end @@ -37,45 +36,51 @@ end describe 'get_or_create' do - it "should return id" do + it 'should return id' do expect(zbx.usergroups.get_or_create(:name => @usergroup)).to eq @usergroupid end end describe 'add_user' do - it "should return id" do - expect(zbx.usergroups.add_user( + it 'should return id' do + expect( + zbx.usergroups.add_user( :usrgrpids => [@usergroupid], :userids => [@userid2] - )).to eq @usergroupid + ) + ).to eq @usergroupid end end describe 'update_users' do - it "should return id" do - expect(zbx.usergroups.update_users( + it 'should return id' do + expect( + zbx.usergroups.update_users( :usrgrpids => [@usergroupid2], :userids => [@userid2] - )).to eq @usergroupid2 + ) + ).to eq @usergroupid2 end end describe 'set_perms' do - it "should return id" do - expect(zbx.usergroups.set_perms( - :usrgrpid => @usergroupid, - :hostgroupids => zbx.hostgroups.all.values, - :permission => 3 - )).to eq @usergroupid + it 'should return id' do + expect( + zbx.usergroups.set_perms( + :usrgrpid => @usergroupid, + :hostgroupids => zbx.hostgroups.all.values, + :permission => 3 + ) + ).to eq @usergroupid end end describe 'delete' do - it "should raise error when has users with only one group" do + it 'should raise error when has users with only one group' do expect { zbx.usergroups.delete(@usergroupid) }.to raise_error(ZabbixApi::ApiError) end - it "should return id of deleted group" do + it 'should return id of deleted group' do usergroupid = zbx.usergroups.create(:name => gen_name('usergroup')) expect(zbx.usergroups.delete(usergroupid)).to eq usergroupid diff --git a/spec/usermacro.rb b/spec/usermacro.rb index 0805cbb..ae0a68c 100644 --- a/spec/usermacro.rb +++ b/spec/usermacro.rb @@ -1,4 +1,4 @@ -#encoding: utf-8 +# encoding: utf-8 require 'spec_helper' @@ -19,10 +19,10 @@ end describe 'create' do - it "should return integer id" do + it 'should return integer id' do hostmacroid = zbx.usermacros.create( :macro => @hostmacro, - :value => "public", + :value => 'public', :hostid => @templateid ) expect(hostmacroid).to be_kind_of(Integer) @@ -30,7 +30,7 @@ end describe 'get_id' do - it "should return nil" do + it 'should return nil' do expect(zbx.usermacros.get_id(:macro => @hostmacro)).to be_kind_of(NilClass) end end @@ -41,59 +41,67 @@ @hostmacro = '{$' + gen_name('HOSTMACRO') + '}' @hostmacroid = zbx.usermacros.create( :macro => @hostmacro, - :value => "public", + :value => 'public', :hostid => @templateid ) end describe 'get_or_create' do - it "should return id of hostmacro" do - expect(zbx.usermacros.get_or_create( - :macro => @hostmacro, - :value => "public", - :hostid => @templateid - )).to eq @hostmacroid + it 'should return id of hostmacro' do + expect( + zbx.usermacros.get_or_create( + :macro => @hostmacro, + :value => 'public', + :hostid => @templateid + ) + ).to eq @hostmacroid end end describe 'get_full_data' do - it "should contains created hostmacro" do - expect(zbx.usermacros.get_full_data(:macro => @hostmacro)[0]).to include("macro" => @hostmacro) + it 'should contains created hostmacro' do + expect(zbx.usermacros.get_full_data(:macro => @hostmacro)[0]).to include('macro' => @hostmacro) end end describe 'get_id' do - it "should return id of hostmacro" do + it 'should return id of hostmacro' do expect(zbx.usermacros.get_id(:macro => @hostmacro)).to eq @hostmacroid end end - it "should raise error on no identity given" do - expect { zbx.usermacros.get_id({}) }.to raise_error(ZabbixApi::ApiError) + it 'should raise error on no identity given' do + expect { zbx.usermacros.get_id({}) }.to raise_error(ZabbixApi::ApiError) end describe 'update' do - it "should return id" do - expect(zbx.usermacros.update( - :hostmacroid => zbx.usermacros.get_id(:macro => @hostmacro), - :value => "private", - )).to eq @hostmacroid + it 'should return id' do + expect( + zbx.usermacros.update( + :hostmacroid => zbx.usermacros.get_id( + :macro => @hostmacro + ), + :value => 'private' + ) + ).to eq @hostmacroid end end describe 'create_or_update' do - it "should update existing usermacro" do - expect(zbx.usermacros.create_or_update( - :macro => @hostmacro, - :value => "public", - :hostid => @templateid - )).to eq @hostmacroid + it 'should update existing usermacro' do + expect( + zbx.usermacros.create_or_update( + :macro => @hostmacro, + :value => 'public', + :hostid => @templateid + ) + ).to eq @hostmacroid end - it "should create usermacro" do + it 'should create usermacro' do new_hostmacro_id = zbx.usermacros.create_or_update( - :macro => @hostmacro.gsub(/}/, "____1}"), - :value => "public", + :macro => @hostmacro.gsub(/}/, '____1}'), + :value => 'public', :hostid => @templateid ) @@ -107,33 +115,33 @@ @result = zbx.usermacros.delete(@hostmacroid) end - it "should return deleted id" do + it 'should return deleted id' do expect(@result).to eq @hostmacroid end - it "should delete item from zabbix" do + it 'should delete item from zabbix' do expect(zbx.usermacros.get_id(:macro => @hostmacro)).to be_nil end end end - + context 'when globalmacro not exists' do before do @globalmacro = '{$' + gen_name('GLOBALMACRO') + '}' end describe 'create_global' do - it "should return integer id" do + it 'should return integer id' do globalmacroid = zbx.usermacros.create_global( :macro => @globalmacro, - :value => "public" + :value => 'public' ) expect(globalmacroid).to be_kind_of(Integer) end end describe 'get_id_global' do - it "should return nil" do + it 'should return nil' do expect(zbx.usermacros.get_id_global(:macro => @globalmacro)).to be_kind_of(NilClass) end end @@ -144,32 +152,36 @@ @globalmacro = '{$' + gen_name('GLOBALMACRO') + '}' @globalmacroid = zbx.usermacros.create_global( :macro => @globalmacro, - :value => "public" + :value => 'public' ) end describe 'get_full_data_global' do - it "should contains created globalmacro" do - expect(zbx.usermacros.get_full_data_global(:macro => @globalmacro)[0]).to include("macro" => @globalmacro) + it 'should contains created globalmacro' do + expect(zbx.usermacros.get_full_data_global(:macro => @globalmacro)[0]).to include('macro' => @globalmacro) end end describe 'get_id_global' do - it "should return id of globalmacro" do + it 'should return id of globalmacro' do expect(zbx.usermacros.get_id_global(:macro => @globalmacro)).to eq @globalmacroid end end - it "should raise error on no identity given" do - expect { zbx.usermacros.get_id_global({}) }.to raise_error(ZabbixApi::ApiError) + it 'should raise error on no identity given' do + expect { zbx.usermacros.get_id_global({}) }.to raise_error(ZabbixApi::ApiError) end describe 'update_global' do - it "should return id" do - expect(zbx.usermacros.update_global( - :globalmacroid => zbx.usermacros.get_id_global(:macro => @globalmacro), - :value => "private", - )).to eq @globalmacroid + it 'should return id' do + expect( + zbx.usermacros.update_global( + :globalmacroid => zbx.usermacros.get_id_global( + :macro => @globalmacro + ), + :value => 'private' + ) + ).to eq @globalmacroid end end @@ -178,11 +190,11 @@ @result = zbx.usermacros.delete_global(@globalmacroid) end - it "should return deleted id" do + it 'should return deleted id' do expect(@result).to eq @globalmacroid end - it "should delete item from zabbix" do + it 'should delete item from zabbix' do expect(zbx.usermacros.get_id_global(:macro => @globalmacro)).to be_nil end end diff --git a/zabbixapi.gemspec b/zabbixapi.gemspec index 30f8488..f4daa23 100644 --- a/zabbixapi.gemspec +++ b/zabbixapi.gemspec @@ -1,26 +1,29 @@ -# -*- encoding: utf-8 -*- -$:.push File.expand_path("../lib", __FILE__) +# coding: utf-8 + +lib = File.expand_path('../lib', __FILE__) + +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) + require 'zabbixapi/version' -Gem::Specification.new do |s| - s.name = "zabbixapi" - s.version = ZabbixApi::VERSION - s.authors = ["Vasiliev D.V.", "Ivan Evtuhovich"] - s.email = %w(vadv.mkn@gmail.com evtuhovich@gmail.com) - s.homepage = "https://github.com/express42/zabbixapi" - s.summary = %q{Simple and lightweight ruby module for working with the Zabbix API} - s.description = %q{Allows you to work with zabbix api from ruby.} - s.licenses = %w(MIT) - - s.add_runtime_dependency 'json' - s.required_ruby_version = Gem::Requirement.new(">= 2".freeze) - s.add_development_dependency 'rake' - s.add_development_dependency 'rspec' - - s.rubyforge_project = "zabbixapi" - - s.files = `git ls-files`.split("\n") - s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") - s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } - s.require_paths = %w(lib) +Gem::Specification.new do |spec| + spec.add_dependency 'http', '~> 2.0' + spec.add_dependency 'json', '~> 2.0' + spec.add_development_dependency 'bundler', '~> 1.0' + + spec.name = 'zabbixapi' + spec.version = ZabbixApi::VERSION + spec.authors = ['Vasiliev D.V.', 'Ivan Evtuhovich'] + spec.email = ['vadv.mkn@gmail.com', 'evtuhovich@gmail.com'] + + spec.summary = 'Simple and lightweight ruby module for working with the Zabbix API' + spec.description = 'Allows you to work with zabbix api from ruby.' + spec.homepage = 'https://github.com/express42/zabbixapi' + spec.licenses = 'MIT' + + spec.rubyforge_project = 'zabbixapi' + + spec.files = ['.yardopts', 'CHANGELOG.md', 'LICENSE.md', 'README.md', 'zabbixapi.gemspec'] + Dir['lib/**/*.rb'] + spec.require_paths = 'lib' + spec.required_ruby_version = '>= 2.0.0' end