zbx_user_media.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. #!/usr/bin/env python
  2. '''
  3. Ansible module for user media
  4. '''
  5. # vim: expandtab:tabstop=4:shiftwidth=4
  6. #
  7. # Zabbix user media 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_mtype(zapi, mtype):
  39. '''Get mediatype
  40. If passed an int, return it as the mediatypeid
  41. if its a string, then try to fetch through a description
  42. '''
  43. if isinstance(mtype, int):
  44. return mtype
  45. try:
  46. return int(mtype)
  47. except ValueError:
  48. pass
  49. content = zapi.get_content('mediatype', 'get', {'search': {'description': mtype}})
  50. if content.has_key['result'] and content['result']:
  51. return content['result'][0]['mediatypeid']
  52. return None
  53. def get_user(zapi, user):
  54. ''' Get userids from user aliases
  55. '''
  56. content = zapi.get_content('user', 'get', {'search': {'alias': user}})
  57. if content['result']:
  58. return content['result'][0]
  59. return None
  60. def get_severity(severity):
  61. ''' determine severity
  62. '''
  63. if isinstance(severity, int) or \
  64. isinstance(severity, str):
  65. return severity
  66. val = 0
  67. sev_map = {
  68. 'not': 2**0,
  69. 'inf': 2**1,
  70. 'war': 2**2,
  71. 'ave': 2**3,
  72. 'avg': 2**3,
  73. 'hig': 2**4,
  74. 'dis': 2**5,
  75. }
  76. for level in severity:
  77. val |= sev_map[level[:3].lower()]
  78. return val
  79. def get_zbx_user_query_data(zapi, user_name):
  80. ''' If name exists, retrieve it, and build query params.
  81. '''
  82. query = {}
  83. if user_name:
  84. zbx_user = get_user(zapi, user_name)
  85. query = {'userid': zbx_user['userid']}
  86. return query
  87. def find_media(medias, user_media):
  88. ''' Find the user media in the list of medias
  89. '''
  90. for media in medias:
  91. if all([media[key] == user_media[key] for key in user_media.keys()]):
  92. return media
  93. return None
  94. def get_active(in_active):
  95. '''Determine active value
  96. '''
  97. active = 1
  98. if in_active:
  99. active = 0
  100. return active
  101. def get_mediatype(zapi, mediatype, mediatype_desc):
  102. ''' Determine mediatypeid
  103. '''
  104. mtypeid = None
  105. if mediatype:
  106. mtypeid = get_mtype(zapi, mediatype)
  107. elif mediatype_desc:
  108. mtypeid = get_mtype(zapi, mediatype_desc)
  109. return mtypeid
  110. def main():
  111. '''
  112. Ansible zabbix module for mediatype
  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['ZABBIX_USER'], type='str'),
  118. zbx_password=dict(default=os.environ['ZABBIX_PASSWORD'], type='str'),
  119. zbx_debug=dict(default=False, type='bool'),
  120. login=dict(default=None, type='str'),
  121. active=dict(default=False, type='bool'),
  122. medias=dict(default=None, type='list'),
  123. mediaid=dict(default=None, type='int'),
  124. mediatype=dict(default=None, type='str'),
  125. mediatype_desc=dict(default=None, type='str'),
  126. #d-d,hh:mm-hh:mm;d-d,hh:mm-hh:mm...
  127. period=dict(default=None, type='str'),
  128. sendto=dict(default=None, type='str'),
  129. severity=dict(default=None, type='str'),
  130. state=dict(default='present', 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 = 'user'
  140. idname = "mediaid"
  141. state = module.params['state']
  142. # User media is fetched through the usermedia.get
  143. zbx_user_query = get_zbx_user_query_data(zapi, module.params['login'])
  144. content = zapi.get_content('usermedia', 'get', zbx_user_query)
  145. if state == 'list':
  146. module.exit_json(changed=False, results=content['result'], state="list")
  147. if state == 'absent':
  148. if not exists(content) or len(content['result']) == 0:
  149. module.exit_json(changed=False, state="absent")
  150. if not module.params['login']:
  151. module.exit_json(failed=True, changed=False, results='Must specifiy a user login.', state="absent")
  152. content = zapi.get_content(zbx_class_name, 'deletemedia', [content['result'][0][idname]])
  153. if content.has_key('error'):
  154. module.exit_json(changed=False, results=content['error'], state="absent")
  155. module.exit_json(changed=True, results=content['result'], state="absent")
  156. if state == 'present':
  157. active = get_active(module.params['active'])
  158. mtypeid = get_mediatype(zapi, module.params['mediatype'], module.params['mediatype_desc'])
  159. medias = module.params['medias']
  160. if medias == None:
  161. medias = [{'mediatypeid': mtypeid,
  162. 'sendto': module.params['sendto'],
  163. 'active': active,
  164. 'severity': int(get_severity(module.params['severity'])),
  165. 'period': module.params['period'],
  166. }]
  167. params = {'users': [zbx_user_query],
  168. 'medias': medias,
  169. 'output': 'extend',
  170. }
  171. if not exists(content):
  172. # if we didn't find it, create it
  173. content = zapi.get_content(zbx_class_name, 'addmedia', params)
  174. if content.has_key('error'):
  175. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  176. module.exit_json(changed=True, results=content['result'], state='present')
  177. # mediaid signifies an update
  178. # If user params exists, check to see if they already exist in zabbix
  179. # if they exist, then return as no update
  180. # elif they do not exist, then take user params only
  181. diff = {'medias': [], 'users': {}}
  182. _ = [diff['medias'].append(media) for media in params['medias'] if not find_media(content['result'], media)]
  183. if not diff['medias']:
  184. module.exit_json(changed=False, results=content['result'], state="present")
  185. for user in params['users']:
  186. diff['users']['userid'] = user['userid']
  187. # We have differences and need to update
  188. content = zapi.get_content(zbx_class_name, 'updatemedia', diff)
  189. if content.has_key('error'):
  190. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  191. module.exit_json(changed=True, results=content['result'], state="present")
  192. module.exit_json(failed=True,
  193. changed=False,
  194. results='Unknown state passed. %s' % state,
  195. state="unknown")
  196. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  197. # import module snippets. This are required
  198. from ansible.module_utils.basic import *
  199. main()