zbx_item.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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.monitoring.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_value_type(value_type):
  39. '''
  40. Possible values:
  41. 0 - numeric float;
  42. 1 - character;
  43. 2 - log;
  44. 3 - numeric unsigned;
  45. 4 - text
  46. '''
  47. vtype = 0
  48. if 'int' in value_type:
  49. vtype = 3
  50. elif 'log' in value_type:
  51. vtype = 2
  52. elif 'char' in value_type:
  53. vtype = 1
  54. elif 'str' in value_type:
  55. vtype = 4
  56. return vtype
  57. def get_app_ids(application_names, app_name_ids):
  58. ''' get application ids from names
  59. '''
  60. applications = []
  61. if application_names:
  62. for app in application_names:
  63. applications.append(app_name_ids[app])
  64. return applications
  65. def get_template_id(zapi, template_name):
  66. '''
  67. get related templates
  68. '''
  69. template_ids = []
  70. app_ids = {}
  71. # Fetch templates by name
  72. content = zapi.get_content('template',
  73. 'get',
  74. {'search': {'host': template_name},
  75. 'selectApplications': ['applicationid', 'name']})
  76. if content.has_key('result'):
  77. template_ids.append(content['result'][0]['templateid'])
  78. for app in content['result'][0]['applications']:
  79. app_ids[app['name']] = app['applicationid']
  80. return template_ids, app_ids
  81. def get_multiplier(inval):
  82. ''' Determine the multiplier
  83. '''
  84. if inval == None or inval == '':
  85. return None, 0
  86. rval = None
  87. try:
  88. rval = int(inval)
  89. except ValueError:
  90. pass
  91. if rval:
  92. return rval, 1
  93. return rval, 0
  94. # The branches are needed for CRUD and error handling
  95. # pylint: disable=too-many-branches
  96. def main():
  97. '''
  98. ansible zabbix module for zbx_item
  99. '''
  100. module = AnsibleModule(
  101. argument_spec=dict(
  102. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  103. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  104. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  105. zbx_debug=dict(default=False, type='bool'),
  106. name=dict(default=None, type='str'),
  107. key=dict(default=None, type='str'),
  108. template_name=dict(default=None, type='str'),
  109. zabbix_type=dict(default=2, type='int'),
  110. value_type=dict(default='int', type='str'),
  111. multiplier=dict(default=None, type='str'),
  112. description=dict(default=None, type='str'),
  113. units=dict(default=None, type='str'),
  114. applications=dict(default=None, type='list'),
  115. state=dict(default='present', type='str'),
  116. ),
  117. #supports_check_mode=True
  118. )
  119. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  120. module.params['zbx_user'],
  121. module.params['zbx_password'],
  122. module.params['zbx_debug']))
  123. #Set the instance and the template for the rest of the calls
  124. zbx_class_name = 'item'
  125. state = module.params['state']
  126. templateid, app_name_ids = get_template_id(zapi, module.params['template_name'])
  127. # Fail if a template was not found matching the name
  128. if not templateid:
  129. module.exit_json(failed=True,
  130. changed=False,
  131. results='Error: Could find template with name %s for item.' % module.params['template_name'],
  132. state="Unkown")
  133. content = zapi.get_content(zbx_class_name,
  134. 'get',
  135. {'search': {'key_': module.params['key']},
  136. 'selectApplications': 'applicationid',
  137. 'templateids': templateid,
  138. })
  139. #******#
  140. # GET
  141. #******#
  142. if state == 'list':
  143. module.exit_json(changed=False, results=content['result'], state="list")
  144. #******#
  145. # DELETE
  146. #******#
  147. if state == 'absent':
  148. if not exists(content):
  149. module.exit_json(changed=False, state="absent")
  150. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['itemid']])
  151. module.exit_json(changed=True, results=content['result'], state="absent")
  152. # Create and Update
  153. if state == 'present':
  154. formula, use_multiplier = get_multiplier(module.params['multiplier'])
  155. params = {'name': module.params.get('name', module.params['key']),
  156. 'key_': module.params['key'],
  157. 'hostid': templateid[0],
  158. 'type': module.params['zabbix_type'],
  159. 'value_type': get_value_type(module.params['value_type']),
  160. 'applications': get_app_ids(module.params['applications'], app_name_ids),
  161. 'formula': formula,
  162. 'multiplier': use_multiplier,
  163. 'description': module.params['description'],
  164. 'units': module.params['units'],
  165. }
  166. # Remove any None valued params
  167. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  168. #******#
  169. # CREATE
  170. #******#
  171. if not exists(content):
  172. content = zapi.get_content(zbx_class_name, 'create', params)
  173. if content.has_key('error'):
  174. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  175. module.exit_json(changed=True, results=content['result'], state='present')
  176. ########
  177. # UPDATE
  178. ########
  179. _ = params.pop('hostid', None)
  180. differences = {}
  181. zab_results = content['result'][0]
  182. for key, value in params.items():
  183. if key == 'applications':
  184. app_ids = [item['applicationid'] for item in zab_results[key]]
  185. if set(app_ids) != set(value):
  186. differences[key] = value
  187. elif zab_results[key] != value and zab_results[key] != str(value):
  188. differences[key] = value
  189. if not differences:
  190. module.exit_json(changed=False, results=zab_results, state="present")
  191. # We have differences and need to update
  192. differences['itemid'] = zab_results['itemid']
  193. content = zapi.get_content(zbx_class_name, 'update', differences)
  194. if content.has_key('error'):
  195. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  196. module.exit_json(changed=True, results=content['result'], state="present")
  197. module.exit_json(failed=True,
  198. changed=False,
  199. results='Unknown state passed. %s' % state,
  200. state="unknown")
  201. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  202. # import module snippets. This are required
  203. from ansible.module_utils.basic import *
  204. main()