Notification Engine for Monasca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hipchat_notifier.py 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
  2. # Copyright 2017 Fujitsu LIMITED
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  13. # implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import requests
  17. import ujson as json
  18. from debtcollector import removals
  19. from oslo_config import cfg
  20. from six.moves import urllib
  21. from monasca_notification.plugins import abstract_notifier
  22. CONF = cfg.CONF
  23. """
  24. notification.address = https://hipchat.hpcloud.net/v2/room/<room_id>/notification?auth_token=432432
  25. How to get access token?
  26. 1) Login to Hipchat with the user account which is used for notification
  27. 2) Go to this page. https://hipchat.hpcloud.net/account/api (Replace your hipchat server name)
  28. 3) You can see option to "Create token". Use the capability "SendNotification"
  29. How to get the Room ID?
  30. 1) Login to Hipchat with the user account which is used for notification
  31. 2) Go to this page. https://hipchat.hpcloud.net/account/api (Replace your hipchat server name)
  32. 3) Click on the Rooms tab
  33. 4) Click on any Room of your choice.
  34. 5) Room ID is the API ID field
  35. """
  36. SEVERITY_COLORS = {"low": 'green',
  37. 'medium': 'gray',
  38. 'high': 'yellow',
  39. 'critical': 'red'}
  40. def register_opts(conf):
  41. gr = cfg.OptGroup(name='%s_notifier' % HipChatNotifier.type)
  42. opts = [
  43. cfg.IntOpt(name='timeout', default=5, min=1),
  44. cfg.BoolOpt(name='insecure', default=True),
  45. cfg.StrOpt(name='ca_certs', default=None),
  46. cfg.StrOpt(name='proxy', default=None)
  47. ]
  48. conf.register_group(gr)
  49. conf.register_opts(opts, group=gr)
  50. class HipChatNotifier(abstract_notifier.AbstractNotifier):
  51. type = 'hipchat'
  52. def __init__(self, log):
  53. super(HipChatNotifier, self).__init__()
  54. self._log = log
  55. @removals.remove(
  56. message='Configuration of notifier is available through oslo.cfg',
  57. version='1.9.0',
  58. removal_version='3.0.0'
  59. )
  60. def config(self, config_dict=None):
  61. pass
  62. @property
  63. def statsd_name(self):
  64. return 'sent_hipchat_count'
  65. def _build_hipchat_message(self, notification):
  66. """Builds hipchat message body
  67. """
  68. body = {'alarm_id': notification.alarm_id,
  69. 'alarm_definition_id': notification.raw_alarm['alarmDefinitionId'],
  70. 'alarm_name': notification.alarm_name,
  71. 'alarm_description': notification.raw_alarm['alarmDescription'],
  72. 'alarm_timestamp': notification.alarm_timestamp,
  73. 'state': notification.state,
  74. 'old_state': notification.raw_alarm['oldState'],
  75. 'message': notification.message,
  76. 'tenant_id': notification.tenant_id,
  77. 'metrics': notification.metrics}
  78. hipchat_request = {}
  79. hipchat_request['color'] = self._get_color(notification.severity.lower())
  80. hipchat_request['message_format'] = 'text'
  81. hipchat_request['message'] = json.dumps(body, indent=3)
  82. return hipchat_request
  83. def _get_color(self, severity):
  84. return SEVERITY_COLORS.get(severity, 'purple')
  85. def send_notification(self, notification):
  86. """Send the notification via hipchat
  87. Posts on the given url
  88. """
  89. hipchat_message = self._build_hipchat_message(notification)
  90. parsed_url = urllib.parse.urlsplit(notification.address)
  91. query_params = urllib.parse.parse_qs(parsed_url.query)
  92. # URL without query params
  93. url = urllib.parse.urljoin(notification.address, urllib.parse.urlparse(notification.address).path)
  94. # Default option is to do cert verification
  95. verify = not CONF.hipchat_notifier.insecure
  96. ca_certs = CONF.hipchat_notifier.ca_certs
  97. proxy = CONF.hipchat_notifier.proxy
  98. # If ca_certs is specified, do cert validation and ignore insecure flag
  99. if ca_certs is not None:
  100. verify = ca_certs
  101. proxyDict = None
  102. if proxy is not None:
  103. proxyDict = {'https': proxy}
  104. try:
  105. # Posting on the given URL
  106. result = requests.post(url=url,
  107. data=hipchat_message,
  108. verify=verify,
  109. params=query_params,
  110. proxies=proxyDict,
  111. timeout=CONF.hipchat_notifier.timeout)
  112. if result.status_code in range(200, 300):
  113. self._log.info("Notification successfully posted.")
  114. return True
  115. else:
  116. msg = "Received an HTTP code {} when trying to send to hipchat on URL {} with response {}."
  117. self._log.error(msg.format(result.status_code, url, result.text))
  118. return False
  119. except Exception:
  120. self._log.exception("Error trying to send to hipchat on URL {}".format(url))
  121. return False