zbx_user_media.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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', {'filter': {'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', {'filter': {'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] == str(user_media[key]) for key in user_media.keys()]):
  92. return media
  93. return None
  94. def get_active(is_active):
  95. '''Determine active value
  96. 0 - enabled
  97. 1 - disabled
  98. '''
  99. active = 1
  100. if is_active:
  101. active = 0
  102. return active
  103. def get_mediatype(zapi, mediatype, mediatype_desc):
  104. ''' Determine mediatypeid
  105. '''
  106. mtypeid = None
  107. if mediatype:
  108. mtypeid = get_mtype(zapi, mediatype)
  109. elif mediatype_desc:
  110. mtypeid = get_mtype(zapi, mediatype_desc)
  111. return mtypeid
  112. def preprocess_medias(zapi, medias):
  113. ''' Insert the correct information when processing medias '''
  114. for media in medias:
  115. # Fetch the mediatypeid from the media desc (name)
  116. if media.has_key('mediatype'):
  117. media['mediatypeid'] = get_mediatype(zapi, mediatype=None, mediatype_desc=media.pop('mediatype'))
  118. media['active'] = get_active(media.get('active'))
  119. media['severity'] = int(get_severity(media['severity']))
  120. return medias
  121. # Disabling branching as the logic requires branches.
  122. # I've also added a few safeguards which required more branches.
  123. # pylint: disable=too-many-branches
  124. def main():
  125. '''
  126. Ansible zabbix module for mediatype
  127. '''
  128. module = AnsibleModule(
  129. argument_spec=dict(
  130. zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'),
  131. zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'),
  132. zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'),
  133. zbx_debug=dict(default=False, type='bool'),
  134. login=dict(default=None, type='str'),
  135. active=dict(default=False, type='bool'),
  136. medias=dict(default=None, type='list'),
  137. mediaid=dict(default=None, type='int'),
  138. mediatype=dict(default=None, type='str'),
  139. mediatype_desc=dict(default=None, type='str'),
  140. #d-d,hh:mm-hh:mm;d-d,hh:mm-hh:mm...
  141. period=dict(default=None, type='str'),
  142. sendto=dict(default=None, type='str'),
  143. severity=dict(default=None, type='str'),
  144. state=dict(default='present', type='str'),
  145. ),
  146. #supports_check_mode=True
  147. )
  148. zapi = ZabbixAPI(ZabbixConnection(module.params['zbx_server'],
  149. module.params['zbx_user'],
  150. module.params['zbx_password'],
  151. module.params['zbx_debug']))
  152. #Set the instance and the template for the rest of the calls
  153. zbx_class_name = 'user'
  154. idname = "mediaid"
  155. state = module.params['state']
  156. # User media is fetched through the usermedia.get
  157. zbx_user_query = get_zbx_user_query_data(zapi, module.params['login'])
  158. content = zapi.get_content('usermedia', 'get',
  159. {'userids': [uid for user, uid in zbx_user_query.items()]})
  160. #####
  161. # Get
  162. #####
  163. if state == 'list':
  164. module.exit_json(changed=False, results=content['result'], state="list")
  165. ########
  166. # Delete
  167. ########
  168. if state == 'absent':
  169. if not exists(content) or len(content['result']) == 0:
  170. module.exit_json(changed=False, state="absent")
  171. if not module.params['login']:
  172. module.exit_json(failed=True, changed=False, results='Must specifiy a user login.', state="absent")
  173. content = zapi.get_content(zbx_class_name, 'deletemedia', [res[idname] for res in content['result']])
  174. if content.has_key('error'):
  175. module.exit_json(changed=False, results=content['error'], state="absent")
  176. module.exit_json(changed=True, results=content['result'], state="absent")
  177. # Create and Update
  178. if state == 'present':
  179. active = get_active(module.params['active'])
  180. mtypeid = get_mediatype(zapi, module.params['mediatype'], module.params['mediatype_desc'])
  181. medias = module.params['medias']
  182. if medias == None:
  183. medias = [{'mediatypeid': mtypeid,
  184. 'sendto': module.params['sendto'],
  185. 'active': active,
  186. 'severity': int(get_severity(module.params['severity'])),
  187. 'period': module.params['period'],
  188. }]
  189. else:
  190. medias = preprocess_medias(zapi, medias)
  191. params = {'users': [zbx_user_query],
  192. 'medias': medias,
  193. 'output': 'extend',
  194. }
  195. ########
  196. # Create
  197. ########
  198. if not exists(content):
  199. if not params['medias']:
  200. module.exit_json(changed=False, results=content['result'], state='present')
  201. # if we didn't find it, create it
  202. content = zapi.get_content(zbx_class_name, 'addmedia', params)
  203. if content.has_key('error'):
  204. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  205. module.exit_json(changed=True, results=content['result'], state='present')
  206. # mediaid signifies an update
  207. # If user params exists, check to see if they already exist in zabbix
  208. # if they exist, then return as no update
  209. # elif they do not exist, then take user params only
  210. ########
  211. # Update
  212. ########
  213. diff = {'medias': [], 'users': {}}
  214. _ = [diff['medias'].append(media) for media in params['medias'] if not find_media(content['result'], media)]
  215. if not diff['medias']:
  216. module.exit_json(changed=False, results=content['result'], state="present")
  217. for user in params['users']:
  218. diff['users']['userid'] = user['userid']
  219. # Medias have no real unique key so therefore we need to make it like the incoming user's request
  220. diff['medias'] = medias
  221. # We have differences and need to update
  222. content = zapi.get_content(zbx_class_name, 'updatemedia', diff)
  223. if content.has_key('error'):
  224. module.exit_json(failed=True, changed=False, results=content['error'], state="present")
  225. module.exit_json(changed=True, results=content['result'], state="present")
  226. module.exit_json(failed=True,
  227. changed=False,
  228. results='Unknown state passed. %s' % state,
  229. state="unknown")
  230. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  231. # import module snippets. This are required
  232. from ansible.module_utils.basic import *
  233. main()