zbx_user_media.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 = {'userids': 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 main():
  102. '''
  103. Ansible zabbix module for mediatype
  104. '''
  105. module = AnsibleModule(
  106. argument_spec=dict(
  107. server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  108. user=dict(default=None, type='str'),
  109. password=dict(default=None, type='str'),
  110. name=dict(default=None, type='str'),
  111. active=dict(default=False, type='bool'),
  112. medias=dict(default=None, type='list'),
  113. mediaid=dict(default=None, type='int'),
  114. mediatype=dict(default=None, type='str'),
  115. mediatype_desc=dict(default=None, type='str'),
  116. #d-d,hh:mm-hh:mm;d-d,hh:mm-hh:mm...
  117. period=dict(default=None, type='str'),
  118. sendto=dict(default=None, type='str'),
  119. severity=dict(default=None, type='str'),
  120. debug=dict(default=False, type='bool'),
  121. state=dict(default='present', type='str'),
  122. ),
  123. #supports_check_mode=True
  124. )
  125. user = module.params.get('user', os.environ['ZABBIX_USER'])
  126. passwd = module.params.get('password', os.environ['ZABBIX_PASSWORD'])
  127. zapi = ZabbixAPI(ZabbixConnection(module.params['server'], user, passwd, module.params['debug']))
  128. #Set the instance and the template for the rest of the calls
  129. zbx_class_name = 'user'
  130. idname = "mediaid"
  131. state = module.params['state']
  132. # User media is fetched through the usermedia.get
  133. zbx_user_query = get_zbx_user_query_data(zapi, module.params['name'])
  134. content = zapi.get_content('usermedia', 'get', zbx_user_query)
  135. if state == 'list':
  136. module.exit_json(changed=False, results=content['result'], state="list")
  137. if state == 'absent':
  138. if not exists(content) or len(content['result']) == 0:
  139. module.exit_json(changed=False, state="absent")
  140. # TODO: Do we remove all the queried results? This could be catastrophic or desired.
  141. #ids = [med[idname] for med in content['result']]
  142. ids = [content['result'][0][idname]]
  143. content = zapi.get_content(zbx_class_name, 'deletemedia', ids)
  144. if content.has_key('error'):
  145. module.exit_json(changed=False, results=content['error'], state="absent")
  146. module.exit_json(changed=True, results=content['result'], state="absent")
  147. if state == 'present':
  148. active = get_active(module.params['active'])
  149. mtypeid = None
  150. if module.params['mediatype']:
  151. mtypeid = get_mtype(zapi, module.params['mediatype'])
  152. elif module.params['mediatype_desc']:
  153. mtypeid = get_mtype(zapi, module.params['mediatype_desc'])
  154. medias = module.params['medias']
  155. if medias == None:
  156. medias = [{'mediatypeid': mtypeid,
  157. 'sendto': module.params['sendto'],
  158. 'active': active,
  159. 'severity': int(get_severity(module.params['severity'])),
  160. 'period': module.params['period'],
  161. }]
  162. params = {'users': [zbx_user_query],
  163. 'medias': medias,
  164. 'output': 'extend',
  165. }
  166. if not exists(content):
  167. # if we didn't find it, create it
  168. content = zapi.get_content(zbx_class_name, 'addmedia', params)
  169. if content.has_key('error'):
  170. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  171. module.exit_json(changed=True, results=content['result'], state='present')
  172. # mediaid signifies an update
  173. # If user params exists, check to see if they already exist in zabbix
  174. # if they exist, then return as no update
  175. # elif they do not exist, then take user params only
  176. differences = {'medias': [], 'users': {}}
  177. for media in params['medias']:
  178. m_result = find_media(content['result'], media)
  179. if not m_result:
  180. differences['medias'].append(media)
  181. if not differences['medias']:
  182. module.exit_json(changed=False, results=content['result'], state="present")
  183. for user in params['users']:
  184. differences['users']['userid'] = user['userids']
  185. # We have differences and need to update
  186. content = zapi.get_content(zbx_class_name, 'updatemedia', differences)
  187. if content.has_key('error'):
  188. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  189. module.exit_json(changed=True, results=content['result'], state="present")
  190. module.exit_json(failed=True,
  191. changed=False,
  192. results='Unknown state passed. %s' % state,
  193. state="unknown")
  194. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  195. # import module snippets. This are required
  196. from ansible.module_utils.basic import *
  197. main()