zbx_httptest.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. # The branches are needed for CRUD and error handling
  109. # pylint: disable=too-many-branches
  110. def main():
  111. '''
  112. ansible zabbix module for zbx_item
  113. '''
  114. module = AnsibleModule(
  115. argument_spec=dict(
  116. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  117. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  118. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  119. zbx_debug=dict(default=False, type='bool'),
  120. name=dict(default=None, require=True, type='str'),
  121. agent=dict(default=None, type='str'),
  122. template_name=dict(default=None, type='str'),
  123. host_name=dict(default=None, type='str'),
  124. interval=dict(default=60, type='int'),
  125. application=dict(default=None, type='str'),
  126. authentication=dict(default=None, type='str'),
  127. http_user=dict(default=None, type='str'),
  128. http_password=dict(default=None, type='str'),
  129. state=dict(default='present', type='str'),
  130. status=dict(default='enabled', type='str'),
  131. steps=dict(default='present', type='list'),
  132. verify_host=dict(default=False, type='bool'),
  133. retries=dict(default=1, type='int'),
  134. headers=dict(default=None, type='dict'),
  135. query_type=dict(default='filter', choices=['filter', 'search'], type='str'),
  136. ),
  137. #supports_check_mode=True
  138. mutually_exclusive=[['template_name', 'host_name']],
  139. )
  140. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  141. module.params['zbx_user'],
  142. module.params['zbx_password'],
  143. module.params['zbx_debug']))
  144. #Set the instance and the template for the rest of the calls
  145. zbx_class_name = 'httptest'
  146. state = module.params['state']
  147. hostid = None
  148. # If a template name was passed then accept the template
  149. if module.params['template_name']:
  150. hostid = get_template_id(zapi, module.params['template_name'])
  151. else:
  152. hostid = get_host_id_by_name(zapi, module.params['host_name'])
  153. # Fail if a template was not found matching the name
  154. if not hostid:
  155. module.exit_json(failed=True,
  156. changed=False,
  157. results='Error: Could find template or host with name [%s].' %
  158. (module.params.get('template_name', module.params['host_name'])),
  159. state="Unkown")
  160. content = zapi.get_content(zbx_class_name,
  161. 'get',
  162. {module.params['query_type']: {'name': module.params['name']},
  163. 'selectSteps': 'extend',
  164. })
  165. #******#
  166. # GET
  167. #******#
  168. if state == 'list':
  169. module.exit_json(changed=False, results=content['result'], state="list")
  170. #******#
  171. # DELETE
  172. #******#
  173. if state == 'absent':
  174. if not exists(content):
  175. module.exit_json(changed=False, state="absent")
  176. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['httptestid']])
  177. module.exit_json(changed=True, results=content['result'], state="absent")
  178. # Create and Update
  179. if state == 'present':
  180. params = {'name': module.params['name'],
  181. 'hostid': hostid,
  182. 'agent': module.params['agent'],
  183. 'retries': module.params['retries'],
  184. 'steps': module.params['steps'],
  185. 'applicationid': get_app_id(zapi, module.params['application']),
  186. 'delay': module.params['interval'],
  187. 'verify_host': get_verify_host(module.params['verify_host']),
  188. 'status': get_status(module.params['status']),
  189. 'headers': module.params['headers'],
  190. 'http_user': module.params['http_user'],
  191. 'http_password': module.params['http_password'],
  192. }
  193. # Remove any None valued params
  194. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  195. #******#
  196. # CREATE
  197. #******#
  198. if not exists(content):
  199. content = zapi.get_content(zbx_class_name, 'create', params)
  200. if content.has_key('error'):
  201. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  202. module.exit_json(changed=True, results=content['result'], state='present')
  203. ########
  204. # UPDATE
  205. ########
  206. differences = {}
  207. zab_results = content['result'][0]
  208. for key, value in params.items():
  209. if key == 'steps':
  210. if not steps_equal(zab_results[key], value):
  211. differences[key] = value
  212. elif zab_results[key] != value and zab_results[key] != str(value):
  213. differences[key] = value
  214. # We have differences and need to update
  215. if not differences:
  216. module.exit_json(changed=False, results=zab_results, state="present")
  217. differences['httptestid'] = zab_results['httptestid']
  218. content = zapi.get_content(zbx_class_name, 'update', differences)
  219. if content.has_key('error'):
  220. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  221. module.exit_json(changed=True, results=content['result'], state="present")
  222. module.exit_json(failed=True,
  223. changed=False,
  224. results='Unknown state passed. %s' % state,
  225. state="unknown")
  226. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  227. # import module snippets. This are required
  228. from ansible.module_utils.basic import *
  229. main()