event_processor.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import traceback
  4. import json
  5. import time
  6. from IPy import IP
  7. import jimit as ji
  8. from models import Database as db, Config, GuestCPUMemory, GuestTraffic, GuestDiskIO, SSHKeyGuestMapping
  9. from models import Guest
  10. from models import Disk
  11. from models import Snapshot, SnapshotDiskMapping, OSTemplateImage
  12. from models import Log
  13. from models import Utils
  14. from models import EmitKind
  15. from models import ResponseState, GuestState, DiskState
  16. from models.guest import GuestMigrateInfo
  17. from models.initialize import app, logger
  18. from models.status import GuestCollectionPerformanceDataKind, HostCollectionPerformanceDataKind
  19. from models import HostCPUMemory, HostTraffic, HostDiskUsageIO
  20. __author__ = 'James Iter'
  21. __date__ = '2017/4/15'
  22. __contact__ = 'james.iter.cn@gmail.com'
  23. __copyright__ = '(c) 2017 by James Iter.'
  24. class EventProcessor(object):
  25. message = None
  26. log = Log()
  27. guest = Guest()
  28. guest_migrate_info = GuestMigrateInfo()
  29. disk = Disk()
  30. snapshot = Snapshot()
  31. snapshot_disk_mapping = SnapshotDiskMapping()
  32. os_template_image = OSTemplateImage()
  33. config = Config()
  34. config.id = 1
  35. guest_cpu_memory = GuestCPUMemory()
  36. guest_traffic = GuestTraffic()
  37. guest_disk_io = GuestDiskIO()
  38. host_cpu_memory = HostCPUMemory()
  39. host_traffic = HostTraffic()
  40. host_disk_usage_io = HostDiskUsageIO()
  41. @classmethod
  42. def log_processor(cls):
  43. cls.log.set(type=cls.message['type'], timestamp=cls.message['timestamp'], host=cls.message['host'],
  44. message=cls.message['message'],
  45. full_message='' if cls.message['message'].__len__() < 255 else cls.message['message'])
  46. cls.log.create()
  47. @classmethod
  48. def guest_event_processor(cls):
  49. cls.guest.uuid = cls.message['message']['uuid']
  50. cls.guest.get_by('uuid')
  51. cls.guest.node_id = cls.message['node_id']
  52. last_status = cls.guest.status
  53. cls.guest.status = cls.message['type']
  54. if cls.message['type'] == GuestState.update.value:
  55. # 更新事件不改变 Guest 的状态
  56. cls.guest.status = last_status
  57. cls.guest.xml = cls.message['message']['xml']
  58. elif cls.guest.status == GuestState.migrating.value:
  59. try:
  60. cls.guest_migrate_info.uuid = cls.guest.uuid
  61. cls.guest_migrate_info.get_by('uuid')
  62. cls.guest_migrate_info.type = cls.message['message']['migrating_info']['type']
  63. cls.guest_migrate_info.time_elapsed = cls.message['message']['migrating_info']['time_elapsed']
  64. cls.guest_migrate_info.time_remaining = cls.message['message']['migrating_info']['time_remaining']
  65. cls.guest_migrate_info.data_total = cls.message['message']['migrating_info']['data_total']
  66. cls.guest_migrate_info.data_processed = cls.message['message']['migrating_info']['data_processed']
  67. cls.guest_migrate_info.data_remaining = cls.message['message']['migrating_info']['data_remaining']
  68. cls.guest_migrate_info.mem_total = cls.message['message']['migrating_info']['mem_total']
  69. cls.guest_migrate_info.mem_processed = cls.message['message']['migrating_info']['mem_processed']
  70. cls.guest_migrate_info.mem_remaining = cls.message['message']['migrating_info']['mem_remaining']
  71. cls.guest_migrate_info.file_total = cls.message['message']['migrating_info']['file_total']
  72. cls.guest_migrate_info.file_processed = cls.message['message']['migrating_info']['file_processed']
  73. cls.guest_migrate_info.file_remaining = cls.message['message']['migrating_info']['file_remaining']
  74. cls.guest_migrate_info.update()
  75. except ji.PreviewingError as e:
  76. ret = json.loads(e.message)
  77. if ret['state']['code'] == '404':
  78. cls.guest_migrate_info.type = cls.message['message']['migrating_info']['type']
  79. cls.guest_migrate_info.time_elapsed = cls.message['message']['migrating_info']['time_elapsed']
  80. cls.guest_migrate_info.time_remaining = cls.message['message']['migrating_info']['time_remaining']
  81. cls.guest_migrate_info.data_total = cls.message['message']['migrating_info']['data_total']
  82. cls.guest_migrate_info.data_processed = cls.message['message']['migrating_info']['data_processed']
  83. cls.guest_migrate_info.data_remaining = cls.message['message']['migrating_info']['data_remaining']
  84. cls.guest_migrate_info.mem_total = cls.message['message']['migrating_info']['mem_total']
  85. cls.guest_migrate_info.mem_processed = cls.message['message']['migrating_info']['mem_processed']
  86. cls.guest_migrate_info.mem_remaining = cls.message['message']['migrating_info']['mem_remaining']
  87. cls.guest_migrate_info.file_total = cls.message['message']['migrating_info']['file_total']
  88. cls.guest_migrate_info.file_processed = cls.message['message']['migrating_info']['file_processed']
  89. cls.guest_migrate_info.file_remaining = cls.message['message']['migrating_info']['file_remaining']
  90. cls.guest_migrate_info.create()
  91. elif cls.guest.status == GuestState.creating.value:
  92. if cls.message['message']['progress'] <= cls.guest.progress:
  93. return
  94. cls.guest.progress = cls.message['message']['progress']
  95. elif cls.guest.status == GuestState.snapshot_converting.value:
  96. print cls.message
  97. cls.os_template_image.id = cls.message['message']['os_template_image_id']
  98. cls.os_template_image.get()
  99. if cls.message['message']['progress'] <= cls.os_template_image.progress:
  100. return
  101. cls.os_template_image.progress = cls.message['message']['progress']
  102. cls.os_template_image.update()
  103. return
  104. cls.guest.update()
  105. # 限定特殊情况下更新磁盘所属 Guest,避免迁移、创建时频繁被无意义的更新
  106. if cls.guest.status in [GuestState.running.value, GuestState.shutoff.value]:
  107. cls.disk.update_by_filter({'node_id': cls.guest.node_id}, filter_str='guest_uuid:eq:' + cls.guest.uuid)
  108. @classmethod
  109. def host_event_processor(cls):
  110. key = cls.message['message']['node_id']
  111. value = {
  112. 'hostname': cls.message['host'],
  113. 'cpu': cls.message['message']['cpu'],
  114. 'system_load': cls.message['message']['system_load'],
  115. 'memory': cls.message['message']['memory'],
  116. 'memory_available': cls.message['message']['memory_available'],
  117. 'interfaces': cls.message['message']['interfaces'],
  118. 'disks': cls.message['message']['disks'],
  119. 'boot_time': cls.message['message']['boot_time'],
  120. 'nonrandom': False,
  121. 'threads_status': cls.message['message']['threads_status'],
  122. 'timestamp': ji.Common.ts()
  123. }
  124. db.r.hset(app.config['hosts_info'], key=key, value=json.dumps(value, ensure_ascii=False))
  125. @classmethod
  126. def response_processor(cls):
  127. _object = cls.message['message']['_object']
  128. action = cls.message['message']['action']
  129. uuid = cls.message['message']['uuid']
  130. state = cls.message['type']
  131. data = cls.message['message']['data']
  132. node_id = cls.message['node_id']
  133. if _object == 'guest':
  134. if action == 'create':
  135. if state == ResponseState.success.value:
  136. # 系统盘的 UUID 与其 Guest 的 UUID 相同
  137. cls.disk.uuid = uuid
  138. cls.disk.get_by('uuid')
  139. cls.disk.guest_uuid = uuid
  140. cls.disk.state = DiskState.mounted.value
  141. # disk_info['virtual-size'] 的单位为Byte,需要除以 1024 的 3 次方,换算成单位为 GB 的值
  142. cls.disk.size = data['disk_info']['virtual-size'] / (1024 ** 3)
  143. cls.disk.update()
  144. else:
  145. cls.guest.uuid = uuid
  146. cls.guest.get_by('uuid')
  147. cls.guest.status = GuestState.dirty.value
  148. cls.guest.update()
  149. elif action == 'migrate':
  150. pass
  151. elif action == 'delete':
  152. if state == ResponseState.success.value:
  153. cls.config.get()
  154. cls.guest.uuid = uuid
  155. cls.guest.get_by('uuid')
  156. if IP(cls.config.start_ip).int() <= IP(cls.guest.ip).int() <= IP(cls.config.end_ip).int():
  157. if db.r.srem(app.config['ip_used_set'], cls.guest.ip):
  158. db.r.sadd(app.config['ip_available_set'], cls.guest.ip)
  159. if (cls.guest.vnc_port - cls.config.start_vnc_port) <= \
  160. (IP(cls.config.end_ip).int() - IP(cls.config.start_ip).int()):
  161. if db.r.srem(app.config['vnc_port_used_set'], cls.guest.vnc_port):
  162. db.r.sadd(app.config['vnc_port_available_set'], cls.guest.vnc_port)
  163. cls.guest.delete()
  164. # TODO: 加入是否删除使用的数据磁盘开关,如果为True,则顺便删除使用的磁盘。否则解除该磁盘被使用的状态。
  165. cls.disk.uuid = uuid
  166. cls.disk.get_by('uuid')
  167. cls.disk.delete()
  168. cls.disk.update_by_filter({'guest_uuid': '', 'sequence': -1, 'state': DiskState.idle.value},
  169. filter_str='guest_uuid:eq:' + cls.guest.uuid)
  170. SSHKeyGuestMapping.delete_by_filter(filter_str=':'.join(['guest_uuid', 'eq', cls.guest.uuid]))
  171. elif action == 'reset_password':
  172. if state == ResponseState.success.value:
  173. cls.guest.uuid = uuid
  174. cls.guest.get_by('uuid')
  175. cls.guest.password = cls.message['message']['passback_parameters']['password']
  176. cls.guest.update()
  177. elif action == 'attach_disk':
  178. cls.disk.uuid = cls.message['message']['passback_parameters']['disk_uuid']
  179. cls.disk.get_by('uuid')
  180. if state == ResponseState.success.value:
  181. cls.disk.guest_uuid = uuid
  182. cls.disk.sequence = cls.message['message']['passback_parameters']['sequence']
  183. cls.disk.state = DiskState.mounted.value
  184. cls.disk.update()
  185. elif action == 'detach_disk':
  186. cls.disk.uuid = cls.message['message']['passback_parameters']['disk_uuid']
  187. cls.disk.get_by('uuid')
  188. if state == ResponseState.success.value:
  189. cls.disk.guest_uuid = ''
  190. cls.disk.sequence = -1
  191. cls.disk.state = DiskState.idle.value
  192. cls.disk.update()
  193. elif action == 'boot':
  194. if state == ResponseState.success.value:
  195. pass
  196. elif _object == 'disk':
  197. if action == 'create':
  198. cls.disk.uuid = uuid
  199. cls.disk.get_by('uuid')
  200. cls.disk.node_id = node_id
  201. if state == ResponseState.success.value:
  202. cls.disk.state = DiskState.idle.value
  203. else:
  204. cls.disk.state = DiskState.dirty.value
  205. cls.disk.update()
  206. elif action == 'resize':
  207. if state == ResponseState.success.value:
  208. cls.config.get()
  209. cls.disk.uuid = uuid
  210. cls.disk.get_by('uuid')
  211. cls.disk.size = cls.message['message']['passback_parameters']['size']
  212. cls.disk.quota(config=cls.config)
  213. cls.disk.update()
  214. elif action == 'delete':
  215. cls.disk.uuid = uuid
  216. cls.disk.get_by('uuid')
  217. cls.disk.delete()
  218. elif _object == 'snapshot':
  219. if action == 'create':
  220. cls.snapshot.id = cls.message['message']['passback_parameters']['id']
  221. cls.snapshot.get()
  222. if state == ResponseState.success.value:
  223. cls.snapshot.snapshot_id = data['snapshot_id']
  224. cls.snapshot.parent_id = data['parent_id']
  225. cls.snapshot.xml = data['xml']
  226. cls.snapshot.progress = 100
  227. cls.snapshot.update()
  228. disks, _ = Disk.get_by_filter(filter_str='guest_uuid:eq:' + cls.snapshot.guest_uuid)
  229. for disk in disks:
  230. cls.snapshot_disk_mapping.snapshot_id = cls.snapshot.snapshot_id
  231. cls.snapshot_disk_mapping.disk_uuid = disk['uuid']
  232. cls.snapshot_disk_mapping.create()
  233. else:
  234. cls.snapshot.progress = 255
  235. cls.snapshot.update()
  236. if action == 'delete':
  237. if state == ResponseState.success.value:
  238. cls.snapshot.id = cls.message['message']['passback_parameters']['id']
  239. cls.snapshot.get()
  240. # 更新子快照的 parent_id 为,当前快照的 parent_id。因为当前快照已被删除。
  241. Snapshot.update_by_filter({'parent_id': cls.snapshot.parent_id},
  242. filter_str='parent_id:eq:' + cls.snapshot.snapshot_id)
  243. SnapshotDiskMapping.delete_by_filter(
  244. filter_str=':'.join(['snapshot_id', 'eq', cls.snapshot.snapshot_id]))
  245. cls.snapshot.delete()
  246. else:
  247. pass
  248. if action == 'revert':
  249. # 不论恢复成功与否,都使快照恢复至正常状态。
  250. cls.snapshot.id = cls.message['message']['passback_parameters']['id']
  251. cls.snapshot.get()
  252. cls.snapshot.progress = 100
  253. cls.snapshot.update()
  254. if action == 'convert':
  255. cls.os_template_image.id = cls.message['message']['passback_parameters']['id']
  256. cls.os_template_image.get()
  257. if state == ResponseState.success.value:
  258. cls.os_template_image.progress = 100
  259. else:
  260. cls.os_template_image.progress = 255
  261. cls.os_template_image.update()
  262. else:
  263. pass
  264. @classmethod
  265. def guest_collection_performance_processor(cls):
  266. data_kind = cls.message['type']
  267. timestamp = ji.Common.ts()
  268. timestamp -= (timestamp % 60)
  269. data = cls.message['message']['data']
  270. if data_kind == GuestCollectionPerformanceDataKind.cpu_memory.value:
  271. for item in data:
  272. cls.guest_cpu_memory.guest_uuid = item['guest_uuid']
  273. cls.guest_cpu_memory.cpu_load = item['cpu_load']
  274. cls.guest_cpu_memory.memory_available = item['memory_available']
  275. cls.guest_cpu_memory.memory_unused = item['memory_unused']
  276. cls.guest_cpu_memory.timestamp = timestamp
  277. cls.guest_cpu_memory.create()
  278. if data_kind == GuestCollectionPerformanceDataKind.traffic.value:
  279. for item in data:
  280. cls.guest_traffic.guest_uuid = item['guest_uuid']
  281. cls.guest_traffic.name = item['name']
  282. cls.guest_traffic.rx_bytes = item['rx_bytes']
  283. cls.guest_traffic.rx_packets = item['rx_packets']
  284. cls.guest_traffic.rx_errs = item['rx_errs']
  285. cls.guest_traffic.rx_drop = item['rx_drop']
  286. cls.guest_traffic.tx_bytes = item['tx_bytes']
  287. cls.guest_traffic.tx_packets = item['tx_packets']
  288. cls.guest_traffic.tx_errs = item['tx_errs']
  289. cls.guest_traffic.tx_drop = item['tx_drop']
  290. cls.guest_traffic.timestamp = timestamp
  291. cls.guest_traffic.create()
  292. if data_kind == GuestCollectionPerformanceDataKind.disk_io.value:
  293. for item in data:
  294. cls.guest_disk_io.disk_uuid = item['disk_uuid']
  295. cls.guest_disk_io.rd_req = item['rd_req']
  296. cls.guest_disk_io.rd_bytes = item['rd_bytes']
  297. cls.guest_disk_io.wr_req = item['wr_req']
  298. cls.guest_disk_io.wr_bytes = item['wr_bytes']
  299. cls.guest_disk_io.timestamp = timestamp
  300. cls.guest_disk_io.create()
  301. else:
  302. pass
  303. @classmethod
  304. def host_collection_performance_processor(cls):
  305. data_kind = cls.message['type']
  306. timestamp = ji.Common.ts()
  307. timestamp -= (timestamp % 60)
  308. data = cls.message['message']['data']
  309. if data_kind == HostCollectionPerformanceDataKind.cpu_memory.value:
  310. cls.host_cpu_memory.node_id = data['node_id']
  311. cls.host_cpu_memory.cpu_load = data['cpu_load']
  312. cls.host_cpu_memory.memory_available = data['memory_available']
  313. cls.host_cpu_memory.timestamp = timestamp
  314. cls.host_cpu_memory.create()
  315. if data_kind == HostCollectionPerformanceDataKind.traffic.value:
  316. for item in data:
  317. cls.host_traffic.node_id = item['node_id']
  318. cls.host_traffic.name = item['name']
  319. cls.host_traffic.rx_bytes = item['rx_bytes']
  320. cls.host_traffic.rx_packets = item['rx_packets']
  321. cls.host_traffic.rx_errs = item['rx_errs']
  322. cls.host_traffic.rx_drop = item['rx_drop']
  323. cls.host_traffic.tx_bytes = item['tx_bytes']
  324. cls.host_traffic.tx_packets = item['tx_packets']
  325. cls.host_traffic.tx_errs = item['tx_errs']
  326. cls.host_traffic.tx_drop = item['tx_drop']
  327. cls.host_traffic.timestamp = timestamp
  328. cls.host_traffic.create()
  329. if data_kind == HostCollectionPerformanceDataKind.disk_usage_io.value:
  330. for item in data:
  331. cls.host_disk_usage_io.node_id = item['node_id']
  332. cls.host_disk_usage_io.mountpoint = item['mountpoint']
  333. cls.host_disk_usage_io.used = item['used']
  334. cls.host_disk_usage_io.rd_req = item['rd_req']
  335. cls.host_disk_usage_io.rd_bytes = item['rd_bytes']
  336. cls.host_disk_usage_io.wr_req = item['wr_req']
  337. cls.host_disk_usage_io.wr_bytes = item['wr_bytes']
  338. cls.host_disk_usage_io.timestamp = timestamp
  339. cls.host_disk_usage_io.create()
  340. else:
  341. pass
  342. @classmethod
  343. def launch(cls):
  344. logger.info(msg='Thread EventProcessor is launched.')
  345. while True:
  346. if Utils.exit_flag:
  347. msg = 'Thread EventProcessor say bye-bye'
  348. print msg
  349. logger.info(msg=msg)
  350. return
  351. try:
  352. report = db.r.lpop(app.config['upstream_queue'])
  353. if report is None:
  354. time.sleep(1)
  355. continue
  356. cls.message = json.loads(report)
  357. if cls.message['kind'] == EmitKind.log.value:
  358. cls.log_processor()
  359. elif cls.message['kind'] == EmitKind.guest_event.value:
  360. cls.guest_event_processor()
  361. elif cls.message['kind'] == EmitKind.host_event.value:
  362. cls.host_event_processor()
  363. elif cls.message['kind'] == EmitKind.response.value:
  364. cls.response_processor()
  365. elif cls.message['kind'] == EmitKind.guest_collection_performance.value:
  366. cls.guest_collection_performance_processor()
  367. elif cls.message['kind'] == EmitKind.host_collection_performance.value:
  368. cls.host_collection_performance_processor()
  369. else:
  370. pass
  371. except Exception as e:
  372. logger.error(traceback.format_exc())
  373. time.sleep(1)