Class: ZabbixManager::Basic

Inherits:
Object
  • Object
show all
Defined in:
lib/zabbix_manager/basic/basic_init.rb,
lib/zabbix_manager/basic/basic_func.rb,
lib/zabbix_manager/basic/basic_alias.rb,
lib/zabbix_manager/basic/basic_logic.rb

Overview

@author: WENWU YAN @email: [email protected] @date: 2023/3/25下午4:47

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ ZabbixManager::Client

Note:

zabbix api 基类

Initializes a new Basic object with ZabbixManager Client

Parameters:



12
13
14
# File 'lib/zabbix_manager/basic/basic_init.rb', line 12

def initialize(client)
  @client = client
end

Instance Method Details

#add(data) ⇒ Integer, Boolean

Note:

通用的新增方法

Add new Zabbix object using API create

Parameters:

  • data (Hash)

Returns:

  • (Integer)

    The object id if a single object is created

  • (Boolean)

    True/False if multiple objects are created

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



22
23
24
# File 'lib/zabbix_manager/basic/basic_alias.rb', line 22

def add(data)
  create(data)
end

#allHash

Note:

查询 zabbix 监控对象所有的 “##identify: ##key

Get full/extended Zabbix data for all objects of type/class from API

Returns:

  • (Hash)

    Array of matching objects

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



192
193
194
195
196
197
198
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 192

def all
  result = {}
  get_raw({ output: "extend" }).each do |item|
    result[item[identify]] = item[key]
  end
  result
end

#create(data) ⇒ Integer, Boolean

Note:

新增 zabbix 监控对象,返回监控对象 id

Create new Zabbix object using API (with defaults)

Parameters:

  • data (Hash)

Returns:

  • (Integer)

    The object id if a single object is created

  • (Boolean)

    True/False if multiple objects are created

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



12
13
14
15
16
17
18
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 12

def create(data)
  log "[DEBUG] Call #{method_name}.create with parameters: #{data.inspect}"

  params = default_options.merge(data)
  result = @client.api_request(method: "#{method_name}.create", params: params)
  parse_keys result
end

#create_or_update(data) ⇒ Integer, Boolean

Note:

创建或更新 zabbix 监控对象,入参为基于符号的哈希对象,返回监控对象 id

Create or update Zabbix object using API

Parameters:

  • data (Hash)

    Should include object’s id field name (identify) and id value

Returns:

  • (Integer)

    The object id if a single object is created

  • (Boolean)

    True/False if multiple objects are created

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



100
101
102
103
104
105
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 100

def create_or_update(data)
  log "[DEBUG] Call #{method_name}.create_or_update with parameters: #{data.inspect}"

  id = get_id(identify.to_sym => data[identify.to_sym])
  id ? update(data.merge(key.to_sym => id.to_s)) : create(data)
end

#default_optionsHash

Note:

子类缺省的 options

Placeholder for inherited objects to provide default options

Returns:

  • (Hash)


33
34
35
# File 'lib/zabbix_manager/basic/basic_init.rb', line 33

def default_options
  {}
end

#delete(data) ⇒ Integer, Boolean

Note:

删除 zabbix 监控对象,返回监控对象 id

Delete Zabbix object using API

Parameters:

  • data (Hash)

    Should include object’s id field name (identify) and id value

Returns:

  • (Integer)

    The object id if a single object is deleted

  • (Boolean)

    True/False if multiple objects are deleted

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



51
52
53
54
55
56
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 51

def delete(data)
  log "[DEBUG] Call #{method_name}.delete with parameters: #{data.inspect}"

  result = @client.api_request(method: "#{method_name}.delete", params: [data].flatten)
  parse_keys result
end

#destroy(data) ⇒ Integer, Boolean

Note:

通用的删除方法

Destroy Zabbix object using API delete

Parameters:

  • data (Hash)

    Should include object’s id field name (identify) and id value

Returns:

  • (Integer)

    The object id if a single object is deleted

  • (Boolean)

    True/False if multiple objects are deleted

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



33
34
35
# File 'lib/zabbix_manager/basic/basic_alias.rb', line 33

def destroy(data)
  delete(data)
end

#dump_by_id(data) ⇒ Hash

Note:

基于 “##key” 打印 zabbix 监控对象详情

Dump Zabbix object data by key from API

Parameters:

  • data (Hash)

    Should include desired object’s key and value

Returns:

  • (Hash)

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 113

def dump_by_id(data)
  log "[DEBUG] Call #{method_name}.dump_by_id with parameters: #{data.inspect}"

  get_raw(
    {
      filter: {
        key.to_sym => data[key.to_sym]
      },
      output: "extend"
    }
  )
end

#get(data) ⇒ Hash

Note:

通用的查询方法

Get Zabbix object data from API by id

Parameters:

  • data (Hash)

    Should include object’s id field name (identify) and id value

Returns:

  • (Hash)

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



11
12
13
# File 'lib/zabbix_manager/basic/basic_alias.rb', line 11

def get(data)
  get_full_data(data)
end

#get_full_data(data) ⇒ Hash

Note:

基于 “##identify” 过滤 zabbix 监控对象,输出详情

Get full/extended Zabbix object data from API

Parameters:

  • data (Hash)

    Should include object’s id field name (identify) and id value

Returns:

  • (Hash)

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 206

def get_full_data(data)
  log "[DEBUG] Call #{method_name}.get_full_data with parameters: #{data.inspect}"

  get_raw(
    {
      filter: {
        identify.to_sym => data[identify.to_sym]
      },
      output: "extend"
    }
  )
end

#get_id(data) ⇒ Integer, NilClass

Note:

基于 zabbix “##identify” 查询监控对象的 “##key

Get Zabbix object id from API based on provided data

Parameters:

  • data (Hash)

Returns:

  • (Integer, NilClass)

    Zabbix object id

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call or missing object’s id field name (identify).

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 132

def get_id(data)
  log "[DEBUG] Call #{method_name}.get_id with parameters: #{data.inspect}"

  # symbolize keys if the user used string keys instead of symbols
  data = symbolize_keys(data) if data.key?(identify)
  # raise an error if identify name was not supplied
  name = data[identify.to_sym]
  raise ZbxError, "#{identify} not supplied in call to get_id" if name.nil?

  result = get_raw(
    {
      filter: data,
      output: [key, identify]
    }
  )

  result.find { |item| item[identify] == data[identify.to_sym] }&.[](key)&.to_i
end

#get_key_ids(data) ⇒ Array

Note:

基于监控对象索引建“##identify”查询 { “##key”: id }

Get Zabbix object [{ key: id }] from API based on provided data

Parameters:

  • data (Hash, Array)

Returns:

  • (Array)

    Zabbix object id

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call or missing object’s id field name (identify).

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



157
158
159
160
161
162
163
164
165
166
167
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 157

def get_key_ids(data)
  log "[DEBUG] Call #{method_name}.get_key_ids with parameters: #{data.inspect}"

  ids = []
  [data].flatten.each do |item|
    if (id = get_id(item))
      ids << { "#{key}": id }
    end
  end
  ids
end

#get_key_ids_by_identify(data) ⇒ Array, NilClass

Note:

基于监控对象索引键(##identify)查询 ##key

Get Zabbix object ID by name using Zabbix API

Parameters:

  • data (String, Array)

    Needs to include host to properly identify Zabbix Objects via Zabbix API

Returns:

  • (Array, NilClass)

    Zabbix object id

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



175
176
177
178
179
180
181
182
183
184
185
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 175

def get_key_ids_by_identify(data)
  log "[DEBUG] Call #{method_name}.get_ids_by_name with parameters: #{data.inspect}"

  result = get_raw(
    {
      filter: { "#{identify}": [data].flatten },
      output: ["#{key}"]
    }
  )
  result.empty? ? nil : result.map { |i| { "#{key}": i[key] } }
end

#get_or_create(data) ⇒ Integer, ...

Note:

创建或更新 zabbix 监控对象,返回监控对象 id

Get or Create Zabbix object using API

Parameters:

  • data (Hash)

    Should include object’s id field name (identify) and id value

Returns:

  • (Integer, Array, TrueClass, FalseClass)

    Zabbix object id

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



64
65
66
67
68
69
70
71
72
73
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 64

def get_or_create(data)
  log "[DEBUG] Call #{method_name}.get_or_create with parameters: #{data.inspect}"

  # Call get_id return object id if exists
  if (id = get_id(identify.to_sym => data[identify.to_sym]))
    id
  else
    create(data)
  end
end

#get_or_create_keys(data) ⇒ Array

Note:

批量创建或更新监控对象并返回 [ { “##key”: id } ]

Get or Create Zabbix object [{ key: id }] using API

Parameters:

  • data (Hash, Array)

    Should include object’s id field name (identify) and id value

Returns:

  • (Array)

    Zabbix object [id]

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



81
82
83
84
85
86
87
88
89
90
91
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 81

def get_or_create_keys(data)
  log "[DEBUG] Call #{method_name}.get_or_create_keys with parameters: #{data.inspect}"

  ids = []
  [data].flatten.each do |item|
    if (id = get_or_create(item))
      ids << { "#{key}": id }
    end
  end
  ids
end

#get_raw(data) ⇒ Hash

Note:

zabbix 监控对象低阶查询方法,静默方法 debug 打印信息

Get raw Zabbix object data from API

Parameters:

  • data (Hash)

Returns:

  • (Hash)

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



225
226
227
228
229
230
231
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 225

def get_raw(data)
  # log "[DEBUG] Call #{method_name}.get_raw with parameters: #{data.inspect}"
  @client.api_request(
    method: "#{method_name}.get",
    params: data
  )
end

#hash_equals?(first_hash, second_hash) ⇒ Boolean

Note:

比较两个哈希是否相等

Compare two hashes for equality

Parameters:

  • first_hash (Hash)
  • second_hash (Hash)

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
# File 'lib/zabbix_manager/basic/basic_func.rb', line 17

def hash_equals?(first_hash, second_hash)
  normalized_first_hash  = normalize_hash(first_hash)
  normalized_second_hash = normalize_hash(second_hash)

  hash1 = normalized_first_hash.merge(normalized_second_hash)
  hash2 = normalized_second_hash.merge(normalized_first_hash)
  hash1 == hash2
end

#identifyObject

Note:

子类必须实现的方法

Placeholder for inherited objects to provide object-specific id field name

Raises:

  • (ZbxError)

    Basic object does not directly support identify



26
27
28
# File 'lib/zabbix_manager/basic/basic_init.rb', line 26

def identify
  raise ZbxError, "Can't call identify here"
end

#keyString

Note:

默认 key 为 “##method_nameid”

Returns the object’s id field name (identify) based on method_name + id

Returns:

  • (String)


40
41
42
# File 'lib/zabbix_manager/basic/basic_init.rb', line 40

def key
  "#{method_name}id"
end

#keysString

Note:

默认 key 为 “##method_nameids”

Returns the object’s plural id field name (identify) based on key

Returns:

  • (String)


47
48
49
# File 'lib/zabbix_manager/basic/basic_init.rb', line 47

def keys
  "#{key}s"
end

#log(message) ⇒ Object

Note:

开启debug模式,打印日志

Log messages to stdout when debugging

Parameters:

  • message (String)


8
9
10
# File 'lib/zabbix_manager/basic/basic_func.rb', line 8

def log(message)
  puts message if @client.options[:debug]
end

#merge_params(first_hash, second_hash) ⇒ Hash

Merge two hashes into a single new hash

Parameters:

  • first_hash (Hash)
  • second_hash (Hash)

Returns:

  • (Hash)


101
102
103
104
# File 'lib/zabbix_manager/basic/basic_func.rb', line 101

def merge_params(first_hash, second_hash)
  new = first_hash.dup
  new.merge(second_hash)
end

#method_nameObject

Note:

子类必须实现的方法 method_name

Placeholder for inherited objects to provide object-specific method name

Raises:

  • (ZbxError)

    Basic object does not directly support method_name



19
20
21
# File 'lib/zabbix_manager/basic/basic_init.rb', line 19

def method_name
  raise ZbxError, "Can't call method_name here"
end

#normalize_array(array) ⇒ Array

Note:

将数组元素序列化成字符串

Normalize all array values to strings

Parameters:

  • array (Array)

Returns:

  • (Array)


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/zabbix_manager/basic/basic_func.rb', line 61

def normalize_array(array)
  result = []

  array.each do |e|
    case e
    when Array
      result.push(normalize_array(e))
    when Hash
      result.push(normalize_hash(e))
    else
      result.push(e.to_s)
    end
  end

  result
end

#normalize_hash(hash) ⇒ Hash

Note:

将哈希元素序列化成字符串

Normalize all hash values to strings

Parameters:

  • hash (Hash)

Returns:

  • (Hash)


45
46
47
48
49
50
51
52
53
54
55
# File 'lib/zabbix_manager/basic/basic_func.rb', line 45

def normalize_hash(hash)
  result = hash.dup

  result.delete(:hostid) # TODO: remove to logig. TemplateID and HostID has different id

  result.each do |key, value|
    result[key.to_sym] = value.is_a?(Array) ? normalize_array(value) : value.to_s
  end

  result
end

#parse_keys(data) ⇒ Integer, Boolean

Note:

提取 zabbix 监控对象 CRUD key 或者 keys

Parse a data hash for id key or boolean to return

Parameters:

  • data

Returns:

  • (Integer)

    The object id if a single object hash is provided with key

  • (Boolean)

    True/False if multiple class object hash is provided



83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/zabbix_manager/basic/basic_func.rb', line 83

def parse_keys(data)
  case data
  when Hash
    data.empty? ? false : data[keys][0].to_i
  when TrueClass
    true
  when FalseClass
    false
  else
    false
  end
end

#symbolize_keys(object) ⇒ Array, Hash

Convert all hash/array keys to symbols @@note 将数组或哈希序列化

Parameters:

  • object (Array, Hash)

Returns:

  • (Array, Hash)


30
31
32
33
34
35
36
37
38
39
# File 'lib/zabbix_manager/basic/basic_func.rb', line 30

def symbolize_keys(object)
  case object
  when Array
    object.map(&method(:symbolize_keys))
  when Hash
    object.transform_keys(&:to_sym).transform_values(&method(:symbolize_keys))
  else
    object
  end
end

#update(data, force = false) ⇒ Integer, Boolean

Note:

更新 zabbix 监控对象,返回监控对象 id

Update Zabbix object using API

Parameters:

  • data (Hash)

    Should include object’s id field name (identify) and id value

  • force (Boolean) (defaults to: false)

    Whether to force an object update even if provided data matches Zabbix

Returns:

  • (Integer)

    The object id if a single object is created

  • (Boolean)

    True/False if multiple objects are created

Raises:

  • (ZbxError)

    Error returned when there is a problem with the Zabbix API call.

  • (HttpError)

    Error raised when HTTP status from Zabbix Server response is not a 200 OK.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/zabbix_manager/basic/basic_logic.rb', line 28

def update(data, force = false)
  log "[DEBUG] Call #{method_name}.update with parameters: #{data.inspect}"

  dump = {}
  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) && !force
    log "[DEBUG] Equal keys #{dump} and #{data}, skip update"
    data[key.to_sym].to_i
  else
    result = @client.api_request(method: "#{method_name}.update", params: data)
    parse_keys result
  end
end