当前位置:   article > 正文

利用ambari rest api实现集群监控及短信告警_ambari告警接口

ambari告警接口

短信接口请自行实现
此处主要参考:https://github.com/apache/ambari/blob/trunk/ambari-server/docs/api/v1/alerts.md

  1. # -*- coding:utf-8 -*-
  2. import datetime
  3. import sys
  4. import requests
  5. '''修改编码字符集为utf-8'''
  6. default_encoding = 'utf-8'
  7. if sys.getdefaultencoding() != default_encoding:
  8. reload(sys)
  9. sys.setdefaultencoding(default_encoding)
  10. intervals = (
  11. ('周', 604800), # 60 * 60 * 24 * 7
  12. ('天', 86400), # 60 * 60 * 24
  13. ('小时', 3600), # 60 * 60
  14. ('分钟', 60),
  15. ('秒', 1),
  16. )
  17. def display_time(seconds, granularity=2):
  18. result = []
  19. for name, count in intervals:
  20. value = seconds // count
  21. if value:
  22. seconds -= value * count
  23. if value == 1:
  24. name = name.rstrip('s')
  25. result.append("{}{}".format(value, name))
  26. else:
  27. # Add a blank if we're in the middle of other values
  28. if len(result) > 0:
  29. result.append(None)
  30. return ''.join([x for x in result[:granularity] if x is not None])
  31. def time_format(timestamp):
  32. dateArray = datetime.datetime.utcfromtimestamp(timestamp / 1000)
  33. return dateArray.strftime("%Y-%m-%d %H:%M:%S")
  34. def get_alert_items():
  35. global items_
  36. auth = ('admin', 'admin')
  37. ##此处ip地址为ambari-server节点的ip或hostname
  38. url = 'http://192.168.0.101:8080/api/v1/clusters/xcarbigdata/alerts'
  39. params = {
  40. 'fields': '*',
  41. 'Alert/state': 'CRITICAL',
  42. 'sortBy': 'Alert/original_timestamp'
  43. }
  44. response = requests.get(url, params=params, auth=auth)
  45. response_json = response.json()
  46. return response_json['items']
  47. items_ = get_alert_items()
  48. alert_messages=[]
  49. for item in items_:
  50. alert_ = item['Alert']
  51. original_timestamp_ = alert_['original_timestamp']
  52. latest_timestamp_ = alert_['latest_timestamp']
  53. timestamp_ = (latest_timestamp_ - original_timestamp_) / 1000
  54. alert_['duration'] = display_time(timestamp_)
  55. alert_['original_timestamp'] = time_format(original_timestamp_)
  56. alert_messages.append('组件:%(service_name)s/%(host_name)s \r\n'
  57. '告警内容:%(label)s:%(text)s\r\n'
  58. '开始时间:%(original_timestamp)s\r\n'
  59. '持续时间:%(duration)s\r\n' % alert_)
  60. if alert_messages:
  61. send_sms('\r\n'.join(alert_messages))#send_sms(message)方法请自行实现

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/683620
推荐阅读
相关标签
  

闽ICP备14008679号