ECSMonitorApi.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # coding: utf-8
  2. import json
  3. import time
  4. from datetime import datetime, timezone
  5. from pprint import pprint
  6. from config import Config
  7. from word_generater import decodestr
  8. from influxdb import InfluxDBClient
  9. from aliyunsdkcore.client import AcsClient
  10. from aliyunsdkcore.acs_exception.exceptions import ClientException
  11. from aliyunsdkcore.acs_exception.exceptions import ServerException
  12. from aliyunsdkcms.request.v20190101.DescribeMetricLastRequest import DescribeMetricLastRequest
  13. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  14. class ECSData2InfluxDB():
  15. def __init__(self, region):
  16. self.region = region
  17. self.client = AcsClient(decodestr(Config.accessKeyId), decodestr(
  18. Config.accessSecret), self.region)
  19. self.influxclient = InfluxDBClient(
  20. '127.0.0.1', 8086, 'root', 'root', 'aliyun')
  21. @property
  22. def doAaction(self):
  23. self.request.set_accept_format('json')
  24. response = self.client.do_action_with_exception(self.request)
  25. return json.loads(str(response, encoding='utf-8'))
  26. ''' data['Datapoints']
  27. {'Average': 0,
  28. 'Maximum': 0,
  29. 'Minimum': 0,
  30. 'instanceId': 'i-2ze551ld3zvhp56r24vy',
  31. 'timestamp': 1575360720000,
  32. 'userId': '1655840174173842'},
  33. {'Average': 0,
  34. 'Maximum': 0,
  35. 'Minimum': 0,
  36. 'instanceId': 'i-2ze551ld3zvhp56r24uw',
  37. 'timestamp': 1575360720000,
  38. 'userId': '1655840174173842'}]
  39. '''
  40. @property
  41. def DescribeECSInternetOutRate(self):
  42. self.request = DescribeMetricLastRequest()
  43. self.request.set_MetricName(self.action)
  44. self.request.set_Period("60")
  45. self.request.set_Namespace("acs_ecs_dashboard")
  46. self.request.set_Express("{\"groupby\":[\"instanceId\"]}")
  47. self.request.set_Length("10000")
  48. data = self.doAaction
  49. # with open("DescribeECSInternetOutRate.log", 'w') as f:
  50. # f.write(str(data))
  51. return eval(data.get('Datapoints'))
  52. def DescribeInstances(self, InstanceIds):
  53. self.request = DescribeInstancesRequest()
  54. self.request.set_PageSize(100)
  55. # InstanceIds ["i-2ze551ld3zvhp56r2504"]
  56. self.request.set_InstanceIds(InstanceIds)
  57. Data = self.doAaction
  58. InstancesInfo = {}
  59. for instance in Data['Instances']["Instance"]:
  60. # pprint(instance)
  61. if instance.get("NetworkInterfaces"):
  62. PrivateIpAddress = instance['NetworkInterfaces']["NetworkInterface"][0]["PrimaryIpAddress"]
  63. else:
  64. PrivateIpAddress = instance["InnerIpAddress"]["IpAddress"][0]
  65. if instance.get('PublicIpAddress') and len(instance.get('PublicIpAddress')) > 1:
  66. PublicIpAddress = instance["PublicIpAddress"]["IpAddress"][0]
  67. elif instance.get('EipAddress'):
  68. IpAddress = instance["EipAddress"]["IpAddress"]
  69. if isinstance(IpAddress, str):
  70. PublicIpAddress = instance["EipAddress"]["IpAddress"]
  71. else:
  72. PublicIpAddress = instance["EipAddress"]["IpAddress"][0]
  73. else:
  74. PublicIpAddress = ""
  75. #PublicIpAddress = instance["PublicIpAddress"]["IpAddress"][0]
  76. InstanceId = instance["InstanceId"]
  77. InstanceChargeType = instance["InstanceChargeType"]
  78. InstancesInfo[InstanceId] = {"PublicIpAddress": PublicIpAddress, "PrivateIpAddress": PrivateIpAddress,
  79. "InstanceChargeType": InstanceChargeType, 'InstanceId': InstanceId}
  80. # InstancesInfo.append({'InstanceId':InstanceId, "PublicIpAddress": PublicIpAddress, "PrivateIpAddress":PrivateIpAddress, "InstanceChargeType":InstanceChargeType})
  81. return InstancesInfo
  82. @property
  83. def RearrangeData(self):
  84. ecsdatalist = self.DescribeECSInternetOutRate
  85. ecsdatadict = {}
  86. for data in ecsdatalist:
  87. ecsdatadict[data['instanceId']] = data
  88. instanceids = [x['instanceId'] for x in ecsdatalist]
  89. instanceids = [instanceids[i:i+100]
  90. for i in range(0, len(instanceids), 100)]
  91. for arr in instanceids:
  92. Ipinfos = self.DescribeInstances(arr)
  93. for data in Ipinfos.keys():
  94. ecsdatadict[data]['PrivateIpAddress'] = Ipinfos[data]['PrivateIpAddress']
  95. ecsdatadict[data]['PublicIpAddress'] = Ipinfos[data]['PublicIpAddress']
  96. #instanceid = data['instanceId']
  97. # print(instanceid)
  98. #PrivateIpAddress = Ipinfos[instanceid]['PrivateIpAddress']
  99. #PublicIpAddress = Ipinfos[instanceid]['PublicIpAddress']
  100. #data['PrivateIpAddress'] = PrivateIpAddress
  101. #data['PublicIpAddress'] = PublicIpAddress
  102. return ecsdatadict
  103. @property
  104. def Save2Influx(self):
  105. data = self.RearrangeData
  106. influx_jsons = self.GenInfluxJson(data)
  107. # pprint(influx_jsons)
  108. res = self.influxclient.write_points(influx_jsons)
  109. return res
  110. def GenInfluxJson(self, data):
  111. influx_jsons = []
  112. table = self.action
  113. n = 0.01
  114. if self.action == "VPC_PublicIP_InternetOutRate":
  115. for k, v in data.items():
  116. if v.get("PublicIpAddress"):
  117. timestamp = int(str(v['timestamp'])[:10])
  118. if int(str(timestamp+n)[-1]) == 9:
  119. n += 0.02
  120. jsonbody = {"measurement": table,
  121. "time": datetime.fromtimestamp(timestamp+n, timezone.utc).isoformat("T"),
  122. "tags": {"PrivateIpAddress": v["PrivateIpAddress"]
  123. },
  124. "fields": {"value": int(v['Average'])
  125. }
  126. }
  127. n += 0.01
  128. influx_jsons.append(jsonbody)
  129. # if self.action == "cpu_total" or self.action == "IntranetOutRate":
  130. else:
  131. for k, v in data.items():
  132. if v.get("PrivateIpAddress") and "10.0." in v.get("PrivateIpAddress"):
  133. timestamp = int(str(v['timestamp'])[:10])
  134. if int(str(timestamp+n)[-1]) == 9:
  135. n += 0.02
  136. jsonbody = {"measurement": table,
  137. "time": datetime.fromtimestamp(timestamp+n, timezone.utc).isoformat("T"),
  138. "tags": {"PrivateIpAddress": v["PrivateIpAddress"]
  139. },
  140. "fields": {"value": int(v['Average'])
  141. }
  142. }
  143. n += 0.01
  144. influx_jsons.append(jsonbody)
  145. return influx_jsons
  146. def Run(self):
  147. actions = ["VPC_PublicIP_InternetOutRate", "IntranetOutRate", "cpu_total", "memory_usedutilization", "net_tcpconnection","load_5m"]
  148. for action in actions:
  149. self.action = action
  150. self.Save2Influx
  151. if __name__ == "__main__":
  152. while 1:
  153. ins = ECSData2InfluxDB("cn-beijing")
  154. ins.Run()
  155. time.sleep(30)