Agent_redis_stats.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from __future__ import division
  2. import redis
  3. import time
  4. import psutil
  5. import socket
  6. import pymongo
  7. from pymongo import MongoClient
  8. redis_report_ip = '192.168.4.94'
  9. redis_report_port = 6379
  10. mongodb_stats = "mongodb://192.168.4.97:27017"
  11. mongodb_info = "mongodb://192.168.4.98:27017"
  12. class DockerStats(object):
  13. def __init__(self, redis_report_ip, redis_report_port, redis_port, container):
  14. # self.cli = Client(base_url='tcp://%s:2375' % docker_ip)
  15. self.cli = Client(base_url='unix://var/run/docker.sock')
  16. self.redis_report_ip = redis_report_ip
  17. self.redis_report_port = redis_report_port
  18. self.redis_port = redis_port
  19. self.container = container
  20. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  21. s.connect(('192.168.4.254', 0))
  22. self.host = s.getsockname()[0]
  23. @property
  24. def container_stat(self):
  25. self.stats_obj = self.cli.stats(self.container, stream=False)
  26. return self.stats_obj
  27. @property
  28. def docker_conns(self):
  29. for conn in psutil.net_connections():
  30. try:
  31. if conn[3][1] == self.redis_port:
  32. redis_pid = conn[-1]
  33. break
  34. except:
  35. pass
  36. redis_ins = psutil.Process(redis_pid)
  37. return len(redis_ins.connections())
  38. def redis_info(self):
  39. r = redis.StrictRedis(host=self.host, port=self.redis_port, db=0)
  40. info = r.info()
  41. redis_key = '%s:%s' % (self.host, self.redis_port)
  42. info['time'] = int(time.time())
  43. return redis_key, info
  44. def write_redis(self):
  45. r = redis.StrictRedis(host=self.redis_report_ip, port=self.redis_report_port, db=0)
  46. now_result = self.container_stat # Dict
  47. memory_usage = now_result["memory_stats"]["usage"]
  48. ##pid connections###
  49. cpuPercent = 0.0
  50. TotalUsage = now_result["cpu_stats"]["cpu_usage"]["total_usage"]
  51. SystemUsage = now_result["cpu_stats"]["system_cpu_usage"]
  52. previous = '%s:%s:%s' % (self.host, self.redis_port, 'previous')
  53. get_previous = r.hget('redis_stats_docker', previous)
  54. if not get_previous:
  55. r.hset('redis_stats_docker', previous, [TotalUsage, SystemUsage])
  56. else:
  57. previousCPU, previousSystem = eval(r.hget('redis_stats_docker', previous))
  58. cpuDelta = TotalUsage - previousCPU
  59. systemDelta = SystemUsage - previousSystem
  60. r.hset('redis_stats_docker', previous, [TotalUsage, SystemUsage])
  61. cpuPercent = '%.2f' % (
  62. (cpuDelta / systemDelta) * len(self.stats_obj["cpu_stats"]["cpu_usage"]["percpu_usage"]) * 100.0)
  63. ######################################{'conns': 33, 'cpu_usage': '1.20', 'mem_usage': 2788642816}
  64. redis_key = '%s:%s' % (self.host, self.redis_port)
  65. redis_value = {'conns': self.docker_conns,
  66. 'cpu_usage': cpuPercent,
  67. 'mem_usage': memory_usage,
  68. 'time': int(time.time())
  69. }
  70. r.hset('redis_stats', redis_key, redis_value)
  71. return redis_key, redis_value
  72. class RedisStats(object):
  73. def __init__(self, redis_report_ip, redis_report_port, psinfo):
  74. self.redis_report_ip = redis_report_ip
  75. self.redis_report_port = redis_report_port
  76. self.redis = psinfo
  77. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  78. s.connect(('192.168.4.254', 0))
  79. self.host = s.getsockname()[0]
  80. @property
  81. def cpu_usage(self):
  82. self.cpu = '%.2f' % self.redis.cpu_percent(interval=0.8)
  83. return self.cpu
  84. @property
  85. def mem_usage(self):
  86. self.memory = self.redis.memory_info().rss
  87. return self.memory
  88. @property
  89. def conns(self):
  90. self.connections = self.redis.connections()
  91. return self.connections
  92. @property
  93. def get_redis_port(self):
  94. self.conns
  95. for conn in self.connections:
  96. if conn.status == 'LISTEN':
  97. self.port = conn.laddr[1]
  98. return self.port
  99. def redis_info(self):
  100. self.port = self.get_redis_port
  101. r = redis.StrictRedis(host=self.host, port=self.port, db=0)
  102. info = r.info()
  103. redis_key = '%s:%s' % (self.host, self.port)
  104. info['time'] = int(time.time())
  105. return redis_key, info
  106. def write_redis(self):
  107. self.cpu_usage
  108. self.mem_usage
  109. self.conns
  110. self.get_redis_port
  111. r = redis.StrictRedis(host=self.redis_report_ip, port=self.redis_report_port, db=0)
  112. key = '%s:%s' % (self.host, self.port)
  113. value = {'cpu_usage': self.cpu,
  114. 'mem_usage': self.memory,
  115. 'conns': len(self.connections),
  116. 'time': int(time.time())
  117. }
  118. r.hset('redis_stats', key, value)
  119. return key, value
  120. def get_container():
  121. contianers = []
  122. cli = Client(base_url='unix://var/run/docker.sock')
  123. for contianer in cli.containers():
  124. try:
  125. if contianer['State'] == 'running' and 'dyredis' in contianer['Image']:
  126. contianers.append(contianer['Names'][0][1:])
  127. except:
  128. pass
  129. return contianers
  130. def get_instance_ps():
  131. pslist = []
  132. ps = psutil.process_iter()
  133. for psinfo in ps:
  134. if psinfo.name() == 'redis-server':
  135. pslist.append(psutil.Process(psinfo.pid))
  136. return pslist
  137. def write_mongodb(redis_key, redis_value, type, isindex):
  138. if type == 'stats':
  139. client = MongoClient(mongodb_stats)
  140. elif type == 'info':
  141. client = MongoClient(mongodb_info)
  142. dbname = 'redis_stats' + str(redis_value['time'] // (60 * 60 * 24 * 30))
  143. collection_name = 'info' + str(redis_value['time'] // (60 * 60 * 24))
  144. redis_value.update({'instance': redis_key})
  145. json_data = redis_value
  146. db = eval('%s.%s' % ("client", dbname))
  147. collection = eval('%s.%s' % ("db", collection_name))
  148. if isindex:
  149. if "instance_1" in collection.index_information().keys():
  150. collection.ensure_index([("instance", pymongo.ASCENDING)])
  151. if "time_1" in collection.index_information().keys():
  152. collection.ensure_index([("time", pymongo.ASCENDING)])
  153. collection.insert_one(json_data)
  154. return collection_name
  155. def run(redis_report_ip, redis_report_port, last_collection_name, last_time, param):
  156. if param:
  157. loop = get_container()
  158. else:
  159. loop = get_instance_ps()
  160. try:
  161. for contianer in loop:
  162. if param:
  163. contianer_port = int(contianer.split('_')[-1])
  164. stats = DockerStats(redis_report_ip, redis_report_port, contianer_port, contianer)
  165. else:
  166. stats = RedisStats(redis_report_ip, redis_report_port, contianer)
  167. stats_key, stats_val = stats.write_redis()
  168. collection_name = 'info' + str(stats_val['time'] // (60 * 60 * 24))
  169. if int(time.time()) // 3600 > last_time:
  170. issharptime = True
  171. info_key, info_val = stats.redis_info()
  172. if collection_name == last_collection_name:
  173. last_collection_name = write_mongodb(stats_key, stats_val, 'stats', 0)
  174. last_time = int(time.time()) // 3600
  175. if issharptime:
  176. last_collection_name = write_mongodb(info_key, info_val, 'info', 0)
  177. else:
  178. last_collection_name = write_mongodb(stats_key, stats_val, 'stats', 1)
  179. last_time = int(time.time()) // 3600
  180. if issharptime:
  181. last_collection_name = write_mongodb(info_key, info_val, 'info', 1)
  182. except:
  183. pass
  184. return last_collection_name, last_time
  185. if __name__ == '__main__':
  186. last_collection_name = ""
  187. last_time = 0
  188. try:
  189. from docker import Client
  190. except:
  191. sys_env = 0
  192. else:
  193. sys_env = 1
  194. while 1:
  195. last_collection_name, last_time = run(redis_report_ip, redis_report_port, last_collection_name, last_time,
  196. sys_env)
  197. time.sleep(3)