zbx_item.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/env python
  2. '''
  3. Ansible module for zabbix items
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix item ansible module
  8. #
  9. #
  10. # Copyright 2015 Red Hat Inc.
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. #
  24. # This is in place because each module looks similar to each other.
  25. # These need duplicate code as their behavior is very similar
  26. # but different for each zabbix class.
  27. # pylint: disable=duplicate-code
  28. # pylint: disable=import-error
  29. from openshift_tools.zbxapi import ZabbixAPI, ZabbixConnection
  30. def exists(content, key='result'):
  31. ''' Check if key exists in content or the size of content[key] > 0
  32. '''
  33. if not content.has_key(key):
  34. return False
  35. if not content[key]:
  36. return False
  37. return True
  38. def get_data_type(data_type):
  39. '''
  40. Possible values:
  41. 0 - decimal;
  42. 1 - octal;
  43. 2 - hexadecimal;
  44. 3 - bool;
  45. '''
  46. vtype = 0
  47. if 'octal' in data_type:
  48. vtype = 1
  49. elif 'hexadecimal' in data_type:
  50. vtype = 2
  51. elif 'bool' in data_type:
  52. vtype = 3
  53. return vtype
  54. def get_value_type(value_type):
  55. '''
  56. Possible values:
  57. 0 - numeric float;
  58. 1 - character;
  59. 2 - log;
  60. 3 - numeric unsigned;
  61. 4 - text
  62. '''
  63. vtype = 0
  64. if 'int' in value_type:
  65. vtype = 3
  66. elif 'log' in value_type:
  67. vtype = 2
  68. elif 'char' in value_type:
  69. vtype = 1
  70. elif 'str' in value_type:
  71. vtype = 4
  72. return vtype
  73. def get_app_ids(application_names, app_name_ids):
  74. ''' get application ids from names
  75. '''
  76. applications = []
  77. if application_names:
  78. for app in application_names:
  79. applications.append(app_name_ids[app])
  80. return applications
  81. def get_template_id(zapi, template_name):
  82. '''
  83. get related templates
  84. '''
  85. template_ids = []
  86. app_ids = {}
  87. # Fetch templates by name
  88. content = zapi.get_content('template',
  89. 'get',
  90. {'search': {'host': template_name},
  91. 'selectApplications': ['applicationid', 'name']})
  92. if content.has_key('result'):
  93. template_ids.append(content['result'][0]['templateid'])
  94. for app in content['result'][0]['applications']:
  95. app_ids[app['name']] = app['applicationid']
  96. return template_ids, app_ids
  97. def get_multiplier(inval):
  98. ''' Determine the multiplier
  99. '''
  100. if inval == None or inval == '':
  101. return None, 0
  102. rval = None
  103. try:
  104. rval = int(inval)
  105. except ValueError:
  106. pass
  107. if rval:
  108. return rval, 1
  109. return rval, 0
  110. def get_zabbix_type(ztype):
  111. '''
  112. Determine which type of discoverrule this is
  113. '''
  114. _types = {'agent': 0,
  115. 'SNMPv1': 1,
  116. 'trapper': 2,
  117. 'simple': 3,
  118. 'SNMPv2': 4,
  119. 'internal': 5,
  120. 'SNMPv3': 6,
  121. 'active': 7,
  122. 'aggregate': 8,
  123. 'web': 9,
  124. 'external': 10,
  125. 'database monitor': 11,
  126. 'ipmi': 12,
  127. 'ssh': 13,
  128. 'telnet': 14,
  129. 'calculated': 15,
  130. 'JMX': 16,
  131. 'SNMP trap': 17,
  132. }
  133. for typ in _types.keys():
  134. if ztype in typ or ztype == typ:
  135. _vtype = _types[typ]
  136. break
  137. else:
  138. _vtype = 2
  139. return _vtype
  140. # The branches are needed for CRUD and error handling
  141. # pylint: disable=too-many-branches
  142. def main():
  143. '''
  144. ansible zabbix module for zbx_item
  145. '''
  146. module = AnsibleModule(
  147. argument_spec=dict(
  148. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  149. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  150. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  151. zbx_debug=dict(default=False, type='bool'),
  152. name=dict(default=None, type='str'),
  153. key=dict(default=None, type='str'),
  154. template_name=dict(default=None, type='str'),
  155. zabbix_type=dict(default='trapper', type='str'),
  156. value_type=dict(default='int', type='str'),
  157. data_type=dict(default='decimal', type='str'),
  158. interval=dict(default=60, type='int'),
  159. delta=dict(default=0, type='int'),
  160. multiplier=dict(default=None, type='str'),
  161. description=dict(default=None, type='str'),
  162. units=dict(default=None, type='str'),
  163. applications=dict(default=None, type='list'),
  164. state=dict(default='present', type='str'),
  165. ),
  166. #supports_check_mode=True
  167. )
  168. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  169. module.params['zbx_user'],
  170. module.params['zbx_password'],
  171. module.params['zbx_debug']))
  172. #Set the instance and the template for the rest of the calls
  173. zbx_class_name = 'item'
  174. state = module.params['state']
  175. templateid, app_name_ids = get_template_id(zapi, module.params['template_name'])
  176. # Fail if a template was not found matching the name
  177. if not templateid:
  178. module.exit_json(failed=True,
  179. changed=False,
  180. results='Error: Could find template with name %s for item.' % module.params['template_name'],
  181. state="Unkown")
  182. content = zapi.get_content(zbx_class_name,
  183. 'get',
  184. {'search': {'key_': module.params['key']},
  185. 'selectApplications': 'applicationid',
  186. 'templateids': templateid,
  187. })
  188. #******#
  189. # GET
  190. #******#
  191. if state == 'list':
  192. module.exit_json(changed=False, results=content['result'], state="list")
  193. #******#
  194. # DELETE
  195. #******#
  196. if state == 'absent':
  197. if not exists(content):
  198. module.exit_json(changed=False, state="absent")
  199. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['itemid']])
  200. module.exit_json(changed=True, results=content['result'], state="absent")
  201. # Create and Update
  202. if state == 'present':
  203. formula, use_multiplier = get_multiplier(module.params['multiplier'])
  204. params = {'name': module.params.get('name', module.params['key']),
  205. 'key_': module.params['key'],
  206. 'hostid': templateid[0],
  207. 'type': get_zabbix_type(module.params['zabbix_type']),
  208. 'value_type': get_value_type(module.params['value_type']),
  209. 'data_type': get_data_type(module.params['data_type']),
  210. 'applications': get_app_ids(module.params['applications'], app_name_ids),
  211. 'formula': formula,
  212. 'multiplier': use_multiplier,
  213. 'description': module.params['description'],
  214. 'units': module.params['units'],
  215. 'delay': module.params['interval'],
  216. 'delta': module.params['delta'],
  217. }
  218. # Remove any None valued params
  219. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  220. #******#
  221. # CREATE
  222. #******#
  223. if not exists(content):
  224. content = zapi.get_content(zbx_class_name, 'create', params)
  225. if content.has_key('error'):
  226. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  227. module.exit_json(changed=True, results=content['result'], state='present')
  228. ########
  229. # UPDATE
  230. ########
  231. _ = params.pop('hostid', None)
  232. differences = {}
  233. zab_results = content['result'][0]
  234. for key, value in params.items():
  235. if key == 'applications':
  236. app_ids = [item['applicationid'] for item in zab_results[key]]
  237. if set(app_ids) != set(value):
  238. differences[key] = value
  239. elif zab_results[key] != value and zab_results[key] != str(value):
  240. differences[key] = value
  241. if not differences:
  242. module.exit_json(changed=False, results=zab_results, state="present")
  243. # We have differences and need to update
  244. differences['itemid'] = zab_results['itemid']
  245. content = zapi.get_content(zbx_class_name, 'update', differences)
  246. if content.has_key('error'):
  247. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  248. module.exit_json(changed=True, results=content['result'], state="present")
  249. module.exit_json(failed=True,
  250. changed=False,
  251. results='Unknown state passed. %s' % state,
  252. state="unknown")
  253. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  254. # import module snippets. This are required
  255. from ansible.module_utils.basic import *
  256. main()