zbx_httptest.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. #!/usr/bin/env python
  2. '''
  3. Ansible module for zabbix httpservice
  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_authentication_method(auth):
  39. ''' determine authentication type'''
  40. rval = 0
  41. if 'basic' in auth:
  42. rval = 1
  43. elif 'ntlm' in auth:
  44. rval = 2
  45. return rval
  46. def get_verify_host(verify):
  47. '''
  48. get the values for verify_host
  49. '''
  50. if verify:
  51. return 1
  52. return 0
  53. def get_app_id(zapi, application):
  54. '''
  55. get related templates
  56. '''
  57. # Fetch templates by name
  58. content = zapi.get_content('application',
  59. 'get',
  60. {'search': {'name': application},
  61. 'selectApplications': ['applicationid', 'name']})
  62. if content.has_key('result'):
  63. return content['result'][0]['applicationid']
  64. return None
  65. def get_template_id(zapi, template_name):
  66. '''
  67. get related templates
  68. '''
  69. # Fetch templates by name
  70. content = zapi.get_content('template',
  71. 'get',
  72. {'search': {'host': template_name},
  73. 'selectApplications': ['applicationid', 'name']})
  74. if content.has_key('result'):
  75. return content['result'][0]['templateid']
  76. return None
  77. def get_host_id_by_name(zapi, host_name):
  78. '''Get host id by name'''
  79. content = zapi.get_content('host',
  80. 'get',
  81. {'filter': {'name': host_name}})
  82. return content['result'][0]['hostid']
  83. def get_status(status):
  84. ''' Determine the status of the web scenario '''
  85. rval = 0
  86. if 'disabled' in status:
  87. return 1
  88. return rval
  89. def find_step(idx, step_list):
  90. ''' find step by index '''
  91. for step in step_list:
  92. if str(step['no']) == str(idx):
  93. return step
  94. return None
  95. def steps_equal(zab_steps, user_steps):
  96. '''compare steps returned from zabbix
  97. and steps passed from user
  98. '''
  99. if len(user_steps) != len(zab_steps):
  100. return False
  101. for idx in range(1, len(user_steps)+1):
  102. user = find_step(idx, user_steps)
  103. zab = find_step(idx, zab_steps)
  104. for key, value in user.items():
  105. if str(value) != str(zab[key]):
  106. return False
  107. return True
  108. def process_steps(steps):
  109. '''Preprocess the step parameters'''
  110. for idx, step in enumerate(steps):
  111. if not step.has_key('no'):
  112. step['no'] = idx + 1
  113. return steps
  114. # The branches are needed for CRUD and error handling
  115. # pylint: disable=too-many-branches
  116. def main():
  117. '''
  118. ansible zabbix module for zbx_item
  119. '''
  120. module = AnsibleModule(
  121. argument_spec=dict(
  122. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  123. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  124. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  125. zbx_debug=dict(default=False, type='bool'),
  126. name=dict(default=None, require=True, type='str'),
  127. agent=dict(default=None, type='str'),
  128. template_name=dict(default=None, type='str'),
  129. host_name=dict(default=None, type='str'),
  130. interval=dict(default=60, type='int'),
  131. application=dict(default=None, type='str'),
  132. authentication=dict(default=None, type='str'),
  133. http_user=dict(default=None, type='str'),
  134. http_password=dict(default=None, type='str'),
  135. state=dict(default='present', type='str'),
  136. status=dict(default='enabled', type='str'),
  137. steps=dict(default='present', type='list'),
  138. verify_host=dict(default=False, type='bool'),
  139. retries=dict(default=1, type='int'),
  140. headers=dict(default=None, type='dict'),
  141. query_type=dict(default='filter', choices=['filter', 'search'], type='str'),
  142. ),
  143. #supports_check_mode=True
  144. mutually_exclusive=[['template_name', 'host_name']],
  145. )
  146. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  147. module.params['zbx_user'],
  148. module.params['zbx_password'],
  149. module.params['zbx_debug']))
  150. #Set the instance and the template for the rest of the calls
  151. zbx_class_name = 'httptest'
  152. state = module.params['state']
  153. hostid = None
  154. # If a template name was passed then accept the template
  155. if module.params['template_name']:
  156. hostid = get_template_id(zapi, module.params['template_name'])
  157. else:
  158. hostid = get_host_id_by_name(zapi, module.params['host_name'])
  159. # Fail if a template was not found matching the name
  160. if not hostid:
  161. module.exit_json(failed=True,
  162. changed=False,
  163. results='Error: Could find template or host with name [%s].' %
  164. (module.params.get('template_name', module.params['host_name'])),
  165. state="Unkown")
  166. content = zapi.get_content(zbx_class_name,
  167. 'get',
  168. {module.params['query_type']: {'name': module.params['name']},
  169. 'selectSteps': 'extend',
  170. })
  171. #******#
  172. # GET
  173. #******#
  174. if state == 'list':
  175. module.exit_json(changed=False, results=content['result'], state="list")
  176. #******#
  177. # DELETE
  178. #******#
  179. if state == 'absent':
  180. if not exists(content):
  181. module.exit_json(changed=False, state="absent")
  182. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['httptestid']])
  183. module.exit_json(changed=True, results=content['result'], state="absent")
  184. # Create and Update
  185. if state == 'present':
  186. params = {'name': module.params['name'],
  187. 'hostid': hostid,
  188. 'agent': module.params['agent'],
  189. 'retries': module.params['retries'],
  190. 'steps': process_steps(module.params['steps']),
  191. 'applicationid': get_app_id(zapi, module.params['application']),
  192. 'delay': module.params['interval'],
  193. 'verify_host': get_verify_host(module.params['verify_host']),
  194. 'status': get_status(module.params['status']),
  195. 'headers': module.params['headers'],
  196. 'http_user': module.params['http_user'],
  197. 'http_password': module.params['http_password'],
  198. }
  199. # Remove any None valued params
  200. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  201. #******#
  202. # CREATE
  203. #******#
  204. if not exists(content):
  205. content = zapi.get_content(zbx_class_name, 'create', params)
  206. if content.has_key('error'):
  207. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  208. module.exit_json(changed=True, results=content['result'], state='present')
  209. ########
  210. # UPDATE
  211. ########
  212. differences = {}
  213. zab_results = content['result'][0]
  214. for key, value in params.items():
  215. if key == 'steps':
  216. if not steps_equal(zab_results[key], value):
  217. differences[key] = value
  218. elif zab_results[key] != value and zab_results[key] != str(value):
  219. differences[key] = value
  220. # We have differences and need to update
  221. if not differences:
  222. module.exit_json(changed=False, results=zab_results, state="present")
  223. differences['httptestid'] = zab_results['httptestid']
  224. content = zapi.get_content(zbx_class_name, 'update', differences)
  225. if content.has_key('error'):
  226. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  227. module.exit_json(changed=True, results=content['result'], state="present")
  228. module.exit_json(failed=True,
  229. changed=False,
  230. results='Unknown state passed. %s' % state,
  231. state="unknown")
  232. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  233. # import module snippets. This are required
  234. from ansible.module_utils.basic import *
  235. main()