zbx_itservice.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. #!/usr/bin/env python
  2. '''
  3. Ansible module for zabbix itservices
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix itservice 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_parent(dependencies):
  39. '''Put dependencies into the proper update format'''
  40. rval = None
  41. for dep in dependencies:
  42. if dep['relationship'] == 'parent':
  43. return dep
  44. return rval
  45. def format_dependencies(dependencies):
  46. '''Put dependencies into the proper update format'''
  47. rval = []
  48. for dep in dependencies:
  49. rval.append({'dependsOnServiceid': dep['serviceid'],
  50. 'soft': get_dependency_type(dep['dep_type']),
  51. })
  52. return rval
  53. def get_dependency_type(dep_type):
  54. '''Determine the dependency type'''
  55. rval = 0
  56. if 'soft' == dep_type:
  57. rval = 1
  58. return rval
  59. def get_service_id_by_name(zapi, dependencies):
  60. '''Fetch the service id for an itservice'''
  61. deps = []
  62. for dep in dependencies:
  63. if dep['name'] == 'root':
  64. deps.append(dep)
  65. continue
  66. content = zapi.get_content('service',
  67. 'get',
  68. {'filter': {'name': dep['name']},
  69. 'selectDependencies': 'extend',
  70. })
  71. if content.has_key('result') and content['result']:
  72. dep['serviceid'] = content['result'][0]['serviceid']
  73. deps.append(dep)
  74. return deps
  75. def add_dependencies(zapi, service_name, dependencies):
  76. '''Fetch the service id for an itservice
  77. Add a dependency on the parent for this current service item.
  78. '''
  79. results = get_service_id_by_name(zapi, [{'name': service_name}])
  80. content = {}
  81. for dep in dependencies:
  82. content = zapi.get_content('service',
  83. 'adddependencies',
  84. {'serviceid': results[0]['serviceid'],
  85. 'dependsOnServiceid': dep['serviceid'],
  86. 'soft': get_dependency_type(dep['dep_type']),
  87. })
  88. if content.has_key('result') and content['result']:
  89. continue
  90. else:
  91. break
  92. return content
  93. def get_show_sla(inc_sla):
  94. ''' Determine the showsla paramter
  95. '''
  96. rval = 1
  97. if 'do not cacluate' in inc_sla:
  98. rval = 0
  99. return rval
  100. def get_algorithm(inc_algorithm_str):
  101. '''
  102. Determine which type algorithm
  103. '''
  104. rval = 0
  105. if 'at least one' in inc_algorithm_str:
  106. rval = 1
  107. elif 'all' in inc_algorithm_str:
  108. rval = 2
  109. return rval
  110. # The branches are needed for CRUD and error handling
  111. # pylint: disable=too-many-branches
  112. def main():
  113. '''
  114. ansible zabbix module for zbx_itservice
  115. '''
  116. module = AnsibleModule(
  117. argument_spec=dict(
  118. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  119. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  120. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  121. zbx_debug=dict(default=False, type='bool'),
  122. name=dict(default=None, type='str'),
  123. algorithm=dict(default='do not calculate', choices=['do not calculate', 'at least one', 'all'], type='str'),
  124. show_sla=dict(default='calculate', choices=['do not calculate', 'calculate'], type='str'),
  125. good_sla=dict(default='99.9', type='float'),
  126. sort_order=dict(default=1, type='int'),
  127. state=dict(default='present', type='str'),
  128. trigger_id=dict(default=None, type='int'),
  129. dependencies=dict(default=[], type='list'),
  130. dep_type=dict(default='hard', choices=['hard', 'soft'], type='str'),
  131. ),
  132. #supports_check_mode=True
  133. )
  134. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  135. module.params['zbx_user'],
  136. module.params['zbx_password'],
  137. module.params['zbx_debug']))
  138. #Set the instance and the template for the rest of the calls
  139. zbx_class_name = 'service'
  140. state = module.params['state']
  141. content = zapi.get_content(zbx_class_name,
  142. 'get',
  143. {'filter': {'name': module.params['name']},
  144. 'selectDependencies': 'extend',
  145. })
  146. #******#
  147. # GET
  148. #******#
  149. if state == 'list':
  150. module.exit_json(changed=False, results=content['result'], state="list")
  151. #******#
  152. # DELETE
  153. #******#
  154. if state == 'absent':
  155. if not exists(content):
  156. module.exit_json(changed=False, state="absent")
  157. content = zapi.get_content(zbx_class_name, 'delete', [content['result'][0]['serviceid']])
  158. module.exit_json(changed=True, results=content['result'], state="absent")
  159. # Create and Update
  160. if state == 'present':
  161. dependencies = get_service_id_by_name(zapi, module.params['dependencies'])
  162. params = {'name': module.params['name'],
  163. 'algorithm': get_algorithm(module.params['algorithm']),
  164. 'showsla': get_show_sla(module.params['show_sla']),
  165. 'goodsla': module.params['good_sla'],
  166. 'sortorder': module.params['sort_order'],
  167. 'triggerid': module.params['trigger_id']
  168. }
  169. # Remove any None valued params
  170. _ = [params.pop(key, None) for key in params.keys() if params[key] is None]
  171. #******#
  172. # CREATE
  173. #******#
  174. if not exists(content):
  175. content = zapi.get_content(zbx_class_name, 'create', params)
  176. if content.has_key('error'):
  177. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  178. if dependencies:
  179. content = add_dependencies(zapi, module.params['name'], dependencies)
  180. if content.has_key('error'):
  181. module.exit_json(failed=True, changed=True, results=content['error'], state="present")
  182. module.exit_json(changed=True, results=content['result'], state='present')
  183. ########
  184. # UPDATE
  185. ########
  186. params['dependencies'] = dependencies
  187. differences = {}
  188. zab_results = content['result'][0]
  189. for key, value in params.items():
  190. if key == 'goodsla':
  191. if float(value) != float(zab_results[key]):
  192. differences[key] = value
  193. elif key == 'dependencies':
  194. zab_dep_ids = [item['serviceid'] for item in zab_results[key]]
  195. user_dep_ids = [item['serviceid'] for item in dependencies]
  196. if set(zab_dep_ids) != set(user_dep_ids):
  197. differences[key] = format_dependencies(dependencies)
  198. elif zab_results[key] != value and zab_results[key] != str(value):
  199. differences[key] = value
  200. if not differences:
  201. module.exit_json(changed=False, results=zab_results, state="present")
  202. differences['serviceid'] = zab_results['serviceid']
  203. content = zapi.get_content(zbx_class_name, 'update', differences)
  204. if content.has_key('error'):
  205. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  206. module.exit_json(changed=True, results=content['result'], state="present")
  207. module.exit_json(failed=True,
  208. changed=False,
  209. results='Unknown state passed. %s' % state,
  210. state="unknown")
  211. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  212. # import module snippets. This are required
  213. from ansible.module_utils.basic import *
  214. main()