host.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import json
  4. import requests
  5. from flask import Blueprint, request, url_for
  6. import jimit as ji
  7. from jimvc.models import app_config, Guest
  8. from jimvc.models import Database as db
  9. from jimvc.models import Utils, Rules, Host
  10. from jimvc.models import GuestState
  11. __author__ = 'James Iter'
  12. __date__ = '2017/5/30'
  13. __contact__ = 'james.iter.cn@gmail.com'
  14. __copyright__ = '(c) 2017 by James Iter.'
  15. blueprint = Blueprint(
  16. 'api_host',
  17. __name__,
  18. url_prefix='/api/host'
  19. )
  20. blueprints = Blueprint(
  21. 'api_hosts',
  22. __name__,
  23. url_prefix='/api/hosts'
  24. )
  25. @Utils.dumps2response
  26. def r_nonrandom(hosts_name, random):
  27. args_rules = [
  28. Rules.HOSTS_NAME.value
  29. ]
  30. try:
  31. ji.Check.previewing(args_rules, {args_rules[0][1]: hosts_name})
  32. if str(random).lower() in ['false', '0']:
  33. random = False
  34. else:
  35. random = True
  36. ret = dict()
  37. ret['state'] = ji.Common.exchange_state(20000)
  38. Host.set_allocation_mode(hosts_name=hosts_name.split(','), random=random)
  39. ret['data'] = Host.get_all()
  40. return ret
  41. except ji.PreviewingError, e:
  42. return json.loads(e.message)
  43. @Utils.dumps2response
  44. def r_get(nodes_id):
  45. args_rules = [
  46. Rules.IDS.value
  47. ]
  48. try:
  49. ji.Check.previewing(args_rules, {args_rules[0][1]: nodes_id})
  50. ret = dict()
  51. ret['state'] = ji.Common.exchange_state(20000)
  52. ret['data'] = list()
  53. if -1 == nodes_id.find(','):
  54. node_id = nodes_id
  55. if db.r.hexists(app_config['hosts_info'], node_id):
  56. v = json.loads(db.r.hget(app_config['hosts_info'], node_id))
  57. v = Host.alive_check(v)
  58. v['node_id'] = node_id
  59. ret['data'] = v
  60. else:
  61. for node_id in nodes_id.split(','):
  62. if db.r.hexists(app_config['hosts_info'], node_id):
  63. v = json.loads(db.r.hget(app_config['hosts_info'], node_id))
  64. v = Host.alive_check(v)
  65. v['node_id'] = node_id
  66. ret['data'].append(v)
  67. if ret['data'].__len__() > 1:
  68. ret['data'].sort(key=lambda _k: _k['boot_time'])
  69. return ret
  70. except ji.PreviewingError, e:
  71. return json.loads(e.message)
  72. @Utils.dumps2response
  73. def r_get_by_filter():
  74. try:
  75. ret = dict()
  76. ret['state'] = ji.Common.exchange_state(20000)
  77. ret['data'] = list()
  78. alive = None
  79. if 'alive' in request.args:
  80. alive = request.args['alive']
  81. if str(alive).lower() in ['false', '0']:
  82. alive = False
  83. else:
  84. alive = True
  85. for host in Host.get_all():
  86. if alive is not None and alive is not host['alive']:
  87. continue
  88. ret['data'].append(host)
  89. return ret
  90. except ji.PreviewingError, e:
  91. return json.loads(e.message)
  92. @Utils.dumps2response
  93. def r_content_search():
  94. keyword = request.args.get('keyword', '')
  95. args_rules = [
  96. Rules.KEYWORD.value
  97. ]
  98. try:
  99. ji.Check.previewing(args_rules, {'keyword': keyword})
  100. ret = dict()
  101. ret['state'] = ji.Common.exchange_state(20000)
  102. ret['data'] = list()
  103. for host in Host.get_all():
  104. if -1 != host['hostname'].lower().find(keyword.lower()):
  105. ret['data'].append(host)
  106. return ret
  107. except ji.PreviewingError, e:
  108. return json.loads(e.message)
  109. @Utils.dumps2response
  110. def r_delete(nodes_id):
  111. args_rules = [
  112. Rules.IDS.value
  113. ]
  114. try:
  115. ji.Check.previewing(args_rules, {args_rules[0][1]: nodes_id})
  116. ret = dict()
  117. ret['state'] = ji.Common.exchange_state(20000)
  118. ret['data'] = list()
  119. if -1 == nodes_id.find(','):
  120. node_id = nodes_id
  121. if db.r.hexists(app_config['hosts_info'], node_id):
  122. v = json.loads(db.r.hget(app_config['hosts_info'], node_id))
  123. v['node_id'] = node_id
  124. ret['data'] = v
  125. db.r.hdel(app_config['hosts_info'], node_id)
  126. else:
  127. for node_id in nodes_id.split(','):
  128. if db.r.hexists(app_config['hosts_info'], node_id):
  129. v = json.loads(db.r.hget(app_config['hosts_info'], node_id))
  130. v['node_id'] = node_id
  131. ret['data'].append(v)
  132. db.r.hdel(app_config['hosts_info'], node_id)
  133. if ret['data'].__len__() > 1:
  134. ret['data'].sort(key=lambda _k: _k['boot_time'])
  135. return ret
  136. except ji.PreviewingError, e:
  137. return json.loads(e.message)
  138. @Utils.dumps2response
  139. def r_show():
  140. args = list()
  141. page = int(request.args.get('page', 1))
  142. page_size = int(request.args.get('page_size', 100))
  143. keyword = request.args.get('keyword', None)
  144. if page is not None:
  145. args.append('page=' + page.__str__())
  146. if page_size is not None:
  147. args.append('page_size=' + page_size.__str__())
  148. if keyword is not None:
  149. args.append('keyword=' + keyword.__str__())
  150. hosts_url = url_for('api_hosts.r_get_by_filter', _external=True)
  151. if keyword is not None:
  152. hosts_url = url_for('api_hosts.r_content_search', _external=True)
  153. if args.__len__() > 0:
  154. hosts_url = hosts_url + '?' + '&'.join(args)
  155. hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
  156. hosts_ret = json.loads(hosts_ret.content)
  157. node_id_amd_state_with_guests_count = dict()
  158. rows, _ = Guest.get_all()
  159. for i, host in enumerate(hosts_ret['data']):
  160. hosts_ret['data'][i]['analysis'] = {
  161. 'all_instance': 0,
  162. 'running_instance': 0,
  163. 'all_vcpu': 0,
  164. 'using_vcpu': 0,
  165. 'all_memory': 0,
  166. 'using_memory': 0
  167. }
  168. for row in rows:
  169. node_id = row['node_id'].__str__()
  170. if node_id not in node_id_amd_state_with_guests_count:
  171. node_id_amd_state_with_guests_count[node_id] = {
  172. 'all_instance': 0,
  173. 'running_instance': 0,
  174. 'all_vcpu': 0,
  175. 'using_vcpu': 0,
  176. 'all_memory': 0,
  177. 'using_memory': 0
  178. }
  179. node_id_amd_state_with_guests_count[node_id]['all_instance'] += 1
  180. node_id_amd_state_with_guests_count[node_id]['all_vcpu'] += row['cpu']
  181. node_id_amd_state_with_guests_count[node_id]['all_memory'] += row['memory']
  182. if row['status'] in [GuestState.running.value, GuestState.booting.value, GuestState.migrating.value]:
  183. node_id_amd_state_with_guests_count[node_id]['running_instance'] += 1
  184. node_id_amd_state_with_guests_count[node_id]['using_vcpu'] += row['cpu']
  185. node_id_amd_state_with_guests_count[node_id]['using_memory'] += row['memory']
  186. for i, host in enumerate(hosts_ret['data']):
  187. if host['node_id'] in node_id_amd_state_with_guests_count:
  188. hosts_ret['data'][i]['analysis'] = node_id_amd_state_with_guests_count[host['node_id']]
  189. ret = dict()
  190. ret['state'] = ji.Common.exchange_state(20000)
  191. ret['data'] = {
  192. 'hosts': hosts_ret['data'],
  193. 'keyword': keyword
  194. }
  195. return ret