event_processor.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. cls.os_template_image.id = cls.message['message']['os_template_image_id']
  97. cls.os_template_image.get()
  98. if cls.message['message']['progress'] <= cls.os_template_image.progress:
  99. return
  100. cls.os_template_image.progress = cls.message['message']['progress']
  101. cls.os_template_image.update()
  102. return
  103. cls.guest.update()
  104. # 限定特殊情况下更新磁盘所属 Guest,避免迁移、创建时频繁被无意义的更新
  105. if cls.guest.status in [GuestState.running.value, GuestState.shutoff.value]:
  106. cls.disk.update_by_filter({'node_id': cls.guest.node_id}, filter_str='guest_uuid:eq:' + cls.guest.uuid)
  107. @classmethod
  108. def host_event_processor(cls):
  109. key = cls.message['message']['node_id']
  110. value = {
  111. 'hostname': cls.message['host'],
  112. 'cpu': cls.message['message']['cpu'],
  113. 'system_load': cls.message['message']['system_load'],
  114. 'memory': cls.message['message']['memory'],
  115. 'memory_available': cls.message['message']['memory_available'],
  116. 'interfaces': cls.message['message']['interfaces'],
  117. 'disks': cls.message['message']['disks'],
  118. 'boot_time': cls.message['message']['boot_time'],
  119. 'nonrandom': False,
  120. 'threads_status': cls.message['message']['threads_status'],
  121. 'timestamp': ji.Common.ts()
  122. }
  123. db.r.hset(app.config['hosts_info'], key=key, value=json.dumps(value, ensure_ascii=False))
  124. @classmethod
  125. def response_processor(cls):
  126. _object = cls.message['message']['_object']
  127. action = cls.message['message']['action']
  128. uuid = cls.message['message']['uuid']
  129. state = cls.message['type']
  130. data = cls.message['message']['data']
  131. node_id = cls.message['node_id']
  132. if _object == 'guest':
  133. if action == 'create':
  134. if state == ResponseState.success.value:
  135. # 系统盘的 UUID 与其 Guest 的 UUID 相同
  136. cls.disk.uuid = uuid
  137. cls.disk.get_by('uuid')
  138. cls.disk.guest_uuid = uuid
  139. cls.disk.state = DiskState.mounted.value
  140. # disk_info['virtual-size'] 的单位为Byte,需要除以 1024 的 3 次方,换算成单位为 GB 的值
  141. cls.disk.size = data['disk_info']['virtual-size'] / (1024 ** 3)
  142. cls.disk.update()
  143. else:
  144. cls.guest.uuid = uuid
  145. cls.guest.get_by('uuid')
  146. cls.guest.status = GuestState.dirty.value
  147. cls.guest.update()
  148. elif action == 'migrate':
  149. pass
  150. elif action == 'delete':
  151. if state == ResponseState.success.value:
  152. cls.config.get()
  153. cls.guest.uuid = uuid
  154. cls.guest.get_by('uuid')
  155. if IP(cls.config.start_ip).int() <= IP(cls.guest.ip).int() <= IP(cls.config.end_ip).int():
  156. if db.r.srem(app.config['ip_used_set'], cls.guest.ip):
  157. db.r.sadd(app.config['ip_available_set'], cls.guest.ip)
  158. if (cls.guest.vnc_port - cls.config.start_vnc_port) <= \
  159. (IP(cls.config.end_ip).int() - IP(cls.config.start_ip).int()):
  160. if db.r.srem(app.config['vnc_port_used_set'], cls.guest.vnc_port):
  161. db.r.sadd(app.config['vnc_port_available_set'], cls.guest.vnc_port)
  162. cls.guest.delete()
  163. # TODO: 加入是否删除使用的数据磁盘开关,如果为True,则顺便删除使用的磁盘。否则解除该磁盘被使用的状态。
  164. cls.disk.uuid = uuid
  165. cls.disk.get_by('uuid')
  166. cls.disk.delete()
  167. cls.disk.update_by_filter({'guest_uuid': '', 'sequence': -1, 'state': DiskState.idle.value},
  168. filter_str='guest_uuid:eq:' + cls.guest.uuid)
  169. SSHKeyGuestMapping.delete_by_filter(filter_str=':'.join(['guest_uuid', 'eq', cls.guest.uuid]))
  170. elif action == 'reset_password':
  171. if state == ResponseState.success.value:
  172. cls.guest.uuid = uuid
  173. cls.guest.get_by('uuid')
  174. cls.guest.password = cls.message['message']['passback_parameters']['password']
  175. cls.guest.update()
  176. elif action == 'attach_disk':
  177. cls.disk.uuid = cls.message['message']['passback_parameters']['disk_uuid']
  178. cls.disk.get_by('uuid')
  179. if state == ResponseState.success.value:
  180. cls.disk.guest_uuid = uuid
  181. cls.disk.sequence = cls.message['message']['passback_parameters']['sequence']
  182. cls.disk.state = DiskState.mounted.value
  183. cls.disk.update()
  184. elif action == 'detach_disk':
  185. cls.disk.uuid = cls.message['message']['passback_parameters']['disk_uuid']
  186. cls.disk.get_by('uuid')
  187. if state == ResponseState.success.value:
  188. cls.disk.guest_uuid = ''
  189. cls.disk.sequence = -1
  190. cls.disk.state = DiskState.idle.value
  191. cls.disk.update()
  192. elif action == 'boot':
  193. if state == ResponseState.success.value:
  194. pass
  195. elif action == 'allocate_bandwidth':
  196. if state == ResponseState.success.value:
  197. cls.guest.uuid = uuid
  198. cls.guest.get_by('uuid')
  199. cls.guest.bandwidth = cls.message['message']['passback_parameters']['bandwidth']
  200. cls.guest.update()
  201. elif _object == 'disk':
  202. if action == 'create':
  203. cls.disk.uuid = uuid
  204. cls.disk.get_by('uuid')
  205. cls.disk.node_id = node_id
  206. if state == ResponseState.success.value:
  207. cls.disk.state = DiskState.idle.value
  208. else:
  209. cls.disk.state = DiskState.dirty.value
  210. cls.disk.update()
  211. elif action == 'resize':
  212. if state == ResponseState.success.value:
  213. cls.config.get()
  214. cls.disk.uuid = uuid
  215. cls.disk.get_by('uuid')
  216. cls.disk.size = cls.message['message']['passback_parameters']['size']
  217. cls.disk.quota(config=cls.config)
  218. cls.disk.update()
  219. elif action == 'delete':
  220. cls.disk.uuid = uuid
  221. cls.disk.get_by('uuid')
  222. cls.disk.delete()
  223. elif _object == 'snapshot':
  224. if action == 'create':
  225. cls.snapshot.id = cls.message['message']['passback_parameters']['id']
  226. cls.snapshot.get()
  227. if state == ResponseState.success.value:
  228. cls.snapshot.snapshot_id = data['snapshot_id']
  229. cls.snapshot.parent_id = data['parent_id']
  230. cls.snapshot.xml = data['xml']
  231. cls.snapshot.progress = 100
  232. cls.snapshot.update()
  233. disks, _ = Disk.get_by_filter(filter_str='guest_uuid:eq:' + cls.snapshot.guest_uuid)
  234. for disk in disks:
  235. cls.snapshot_disk_mapping.snapshot_id = cls.snapshot.snapshot_id
  236. cls.snapshot_disk_mapping.disk_uuid = disk['uuid']
  237. cls.snapshot_disk_mapping.create()
  238. else:
  239. cls.snapshot.progress = 255
  240. cls.snapshot.update()
  241. if action == 'delete':
  242. if state == ResponseState.success.value:
  243. cls.snapshot.id = cls.message['message']['passback_parameters']['id']
  244. cls.snapshot.get()
  245. # 更新子快照的 parent_id 为,当前快照的 parent_id。因为当前快照已被删除。
  246. Snapshot.update_by_filter({'parent_id': cls.snapshot.parent_id},
  247. filter_str='parent_id:eq:' + cls.snapshot.snapshot_id)
  248. SnapshotDiskMapping.delete_by_filter(
  249. filter_str=':'.join(['snapshot_id', 'eq', cls.snapshot.snapshot_id]))
  250. cls.snapshot.delete()
  251. else:
  252. pass
  253. if action == 'revert':
  254. # 不论恢复成功与否,都使快照恢复至正常状态。
  255. cls.snapshot.id = cls.message['message']['passback_parameters']['id']
  256. cls.snapshot.get()
  257. cls.snapshot.progress = 100
  258. cls.snapshot.update()
  259. if action == 'convert':
  260. cls.snapshot.snapshot_id = cls.message['message']['passback_parameters']['id']
  261. cls.snapshot.get_by('snapshot_id')
  262. cls.snapshot.progress = 100
  263. cls.snapshot.update()
  264. cls.os_template_image.id = cls.message['message']['passback_parameters']['os_template_image_id']
  265. cls.os_template_image.get()
  266. if state == ResponseState.success.value:
  267. cls.os_template_image.progress = 100
  268. else:
  269. cls.os_template_image.progress = 255
  270. cls.os_template_image.update()
  271. elif _object == 'os_template_image':
  272. if action == 'delete':
  273. cls.os_template_image.id = cls.message['message']['passback_parameters']['id']
  274. cls.os_template_image.get()
  275. if state == ResponseState.success.value:
  276. cls.os_template_image.delete()
  277. else:
  278. pass
  279. else:
  280. pass
  281. @classmethod
  282. def guest_collection_performance_processor(cls):
  283. data_kind = cls.message['type']
  284. timestamp = ji.Common.ts()
  285. timestamp -= (timestamp % 60)
  286. data = cls.message['message']['data']
  287. if data_kind == GuestCollectionPerformanceDataKind.cpu_memory.value:
  288. for item in data:
  289. cls.guest_cpu_memory.guest_uuid = item['guest_uuid']
  290. cls.guest_cpu_memory.cpu_load = item['cpu_load']
  291. cls.guest_cpu_memory.memory_available = item['memory_available']
  292. cls.guest_cpu_memory.memory_unused = item['memory_unused']
  293. cls.guest_cpu_memory.timestamp = timestamp
  294. cls.guest_cpu_memory.create()
  295. if data_kind == GuestCollectionPerformanceDataKind.traffic.value:
  296. for item in data:
  297. cls.guest_traffic.guest_uuid = item['guest_uuid']
  298. cls.guest_traffic.name = item['name']
  299. cls.guest_traffic.rx_bytes = item['rx_bytes']
  300. cls.guest_traffic.rx_packets = item['rx_packets']
  301. cls.guest_traffic.rx_errs = item['rx_errs']
  302. cls.guest_traffic.rx_drop = item['rx_drop']
  303. cls.guest_traffic.tx_bytes = item['tx_bytes']
  304. cls.guest_traffic.tx_packets = item['tx_packets']
  305. cls.guest_traffic.tx_errs = item['tx_errs']
  306. cls.guest_traffic.tx_drop = item['tx_drop']
  307. cls.guest_traffic.timestamp = timestamp
  308. cls.guest_traffic.create()
  309. if data_kind == GuestCollectionPerformanceDataKind.disk_io.value:
  310. for item in data:
  311. cls.guest_disk_io.disk_uuid = item['disk_uuid']
  312. cls.guest_disk_io.rd_req = item['rd_req']
  313. cls.guest_disk_io.rd_bytes = item['rd_bytes']
  314. cls.guest_disk_io.wr_req = item['wr_req']
  315. cls.guest_disk_io.wr_bytes = item['wr_bytes']
  316. cls.guest_disk_io.timestamp = timestamp
  317. cls.guest_disk_io.create()
  318. else:
  319. pass
  320. @classmethod
  321. def host_collection_performance_processor(cls):
  322. data_kind = cls.message['type']
  323. timestamp = ji.Common.ts()
  324. timestamp -= (timestamp % 60)
  325. data = cls.message['message']['data']
  326. if data_kind == HostCollectionPerformanceDataKind.cpu_memory.value:
  327. cls.host_cpu_memory.node_id = data['node_id']
  328. cls.host_cpu_memory.cpu_load = data['cpu_load']
  329. cls.host_cpu_memory.memory_available = data['memory_available']
  330. cls.host_cpu_memory.timestamp = timestamp
  331. cls.host_cpu_memory.create()
  332. if data_kind == HostCollectionPerformanceDataKind.traffic.value:
  333. for item in data:
  334. cls.host_traffic.node_id = item['node_id']
  335. cls.host_traffic.name = item['name']
  336. cls.host_traffic.rx_bytes = item['rx_bytes']
  337. cls.host_traffic.rx_packets = item['rx_packets']
  338. cls.host_traffic.rx_errs = item['rx_errs']
  339. cls.host_traffic.rx_drop = item['rx_drop']
  340. cls.host_traffic.tx_bytes = item['tx_bytes']
  341. cls.host_traffic.tx_packets = item['tx_packets']
  342. cls.host_traffic.tx_errs = item['tx_errs']
  343. cls.host_traffic.tx_drop = item['tx_drop']
  344. cls.host_traffic.timestamp = timestamp
  345. cls.host_traffic.create()
  346. if data_kind == HostCollectionPerformanceDataKind.disk_usage_io.value:
  347. for item in data:
  348. cls.host_disk_usage_io.node_id = item['node_id']
  349. cls.host_disk_usage_io.mountpoint = item['mountpoint']
  350. cls.host_disk_usage_io.used = item['used']
  351. cls.host_disk_usage_io.rd_req = item['rd_req']
  352. cls.host_disk_usage_io.rd_bytes = item['rd_bytes']
  353. cls.host_disk_usage_io.wr_req = item['wr_req']
  354. cls.host_disk_usage_io.wr_bytes = item['wr_bytes']
  355. cls.host_disk_usage_io.timestamp = timestamp
  356. cls.host_disk_usage_io.create()
  357. else:
  358. pass
  359. @classmethod
  360. def launch(cls):
  361. logger.info(msg='Thread EventProcessor is launched.')
  362. while True:
  363. if Utils.exit_flag:
  364. msg = 'Thread EventProcessor say bye-bye'
  365. print msg
  366. logger.info(msg=msg)
  367. return
  368. try:
  369. report = db.r.lpop(app.config['upstream_queue'])
  370. if report is None:
  371. time.sleep(1)
  372. continue
  373. cls.message = json.loads(report)
  374. if cls.message['kind'] == EmitKind.log.value:
  375. cls.log_processor()
  376. elif cls.message['kind'] == EmitKind.guest_event.value:
  377. cls.guest_event_processor()
  378. elif cls.message['kind'] == EmitKind.host_event.value:
  379. cls.host_event_processor()
  380. elif cls.message['kind'] == EmitKind.response.value:
  381. cls.response_processor()
  382. elif cls.message['kind'] == EmitKind.guest_collection_performance.value:
  383. cls.guest_collection_performance_processor()
  384. elif cls.message['kind'] == EmitKind.host_collection_performance.value:
  385. cls.host_collection_performance_processor()
  386. else:
  387. pass
  388. except Exception as e:
  389. logger.error(traceback.format_exc())
  390. time.sleep(1)