data_platform_api.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # -*- coding: utf-8 -*-
  2. """
  3. data_platform_api
  4. ~~~~~~~~~~~~~~~~~
  5. This module handle the data platform api request, query equipment data, creat alarm and so on.
  6. """
  7. import datetime
  8. import logging
  9. import redis
  10. import requests
  11. from requests import exceptions
  12. logger = logging.getLogger(__name__)
  13. pool = redis.ConnectionPool(host='172.16.34.43', port=6379, db=12, password='deepsaga', decode_responses=True)
  14. r = redis.Redis(connection_pool=pool)
  15. DATA_PLATFORM_SERVER = 'http://api.sagacloud.cn/data-platform-3/'
  16. ALARM_SERVER = 'http://47.93.33.207:8890/alarm-system/'
  17. class PlatformRequest:
  18. """The Base Request for Platform"""
  19. def __init__(self, server, url, params, payload, timeout=5):
  20. self._url = server + url
  21. self._params = params
  22. self._payload = payload
  23. self._timeout = timeout
  24. def send_request(self):
  25. result = dict()
  26. try:
  27. response = requests.post(self._url, params=self._params, json=self._payload, timeout=self._timeout)
  28. except exceptions as e:
  29. raise Exception(f'Could not connect to platform server {e}')
  30. else:
  31. if response.status_code == 200:
  32. result = response.json()
  33. else:
  34. logger.info(f'request error {response.status_code}, {response.reason}')
  35. finally:
  36. return result
  37. def query_real_time_data(project_id, equip_id, code_list):
  38. url = 'parameter/batch_query_param'
  39. params = {
  40. 'projectId': project_id,
  41. 'secret': 'saga123456'
  42. }
  43. request_param_list = [{'id': equip_id, 'code': item} for item in code_list]
  44. payload = {
  45. 'criterias': request_param_list
  46. }
  47. porter = PlatformRequest(DATA_PLATFORM_SERVER, url, params, payload)
  48. raw_result = porter.send_request()
  49. result = {item.get('code'): item.get('data') for item in raw_result.get('Content')}
  50. return result
  51. def query_history_time_data(project_id, equip_id, code, period):
  52. url = 'hisdata/query_by_obj'
  53. from_time = (datetime.datetime.now() - datetime.timedelta(minutes=period)).strftime('%Y%m%d%H%M%S')
  54. params = {
  55. 'projectId': project_id,
  56. 'secret': 'saga123456'
  57. }
  58. payload = {
  59. 'criteria': {
  60. 'id': equip_id,
  61. 'code': code,
  62. 'receivetime': {
  63. '$gte': from_time
  64. }
  65. }
  66. }
  67. porter = PlatformRequest(DATA_PLATFORM_SERVER, url, params, payload)
  68. raw_result = porter.send_request()
  69. result = [item.get('data') for item in raw_result.get('Content')]
  70. return result
  71. def send_alarm(project_id, object_id, type_code, description):
  72. url = 'alarm/create'
  73. params = {
  74. 'projectId': project_id,
  75. 'secret': 'saga123456'
  76. }
  77. time_stamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  78. payload = {
  79. 'status': 'alarm',
  80. 'objects': [object_id],
  81. 'ctime': time_stamp,
  82. 'level': 'S',
  83. 'type_code': type_code,
  84. 'description': description
  85. }
  86. porter = PlatformRequest(ALARM_SERVER, url, params, payload)
  87. raw_result = porter.send_request()
  88. result = raw_result.get('id')
  89. logger.info(f'Send alarm: {result}')
  90. save_alarm_info(project_id, object_id, result, time_stamp)
  91. return result
  92. def is_alarmed(project_id, object_id, alarm_type):
  93. logger.info(f'Try to send alarm - {object_id}')
  94. url = 'alarm/query'
  95. params = {
  96. 'projectId': project_id,
  97. 'secret': 'saga123456'
  98. }
  99. from_time = (datetime.datetime.now() - datetime.timedelta(minutes=30)).strftime('%Y%m%d%H%M%S')
  100. payload = {
  101. 'criteria': {
  102. 'object': object_id,
  103. 'type_code': alarm_type,
  104. 'ctime': {
  105. '$gte': from_time
  106. }
  107. },
  108. }
  109. porter = PlatformRequest(ALARM_SERVER, url, params, payload)
  110. raw_result = porter.send_request()
  111. flag = False
  112. for item in raw_result.get('Content'):
  113. if 'alarm' == item.get('status'):
  114. flag = True
  115. return flag
  116. def recover_alarm(project_id, alarm_id):
  117. url = 'alarm/batchRecover'
  118. params = {
  119. 'projectId': project_id,
  120. 'secret': 'saga123456'
  121. }
  122. payload = {
  123. 'alarmId': [alarm_id]
  124. }
  125. porter = PlatformRequest(ALARM_SERVER, url, params, payload)
  126. raw_result = porter.send_request()
  127. logger.info(f'Recover alarm: {alarm_id}')
  128. return raw_result.get('Result')
  129. def save_alarm_info(project_id, object_id, alarm_id, time_stamp):
  130. name = f'alarm_{project_id}_{object_id}'
  131. r.hset(name, alarm_id, time_stamp)
  132. def query_redis_alarm(project_id, object_id):
  133. name = f'alarm_{project_id}_{object_id}'
  134. result = r.hgetall(name)
  135. return result