guest.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import copy
  4. from math import ceil
  5. from IPy import IP
  6. import requests
  7. import json
  8. from uuid import uuid4
  9. import random
  10. import time
  11. import jimit as ji
  12. from flask import Blueprint, url_for, request
  13. from jimvc.api.base import Base
  14. from jimvc.models.initialize import dev_table
  15. from jimvc.models import app_config
  16. from jimvc.models import DiskState, Host
  17. from jimvc.models import Database as db
  18. from jimvc.models import Config
  19. from jimvc.models import Disk
  20. from jimvc.models import Rules
  21. from jimvc.models import Utils
  22. from jimvc.models import Guest
  23. from jimvc.models import OSTemplateImage
  24. from jimvc.models import OSTemplateProfile
  25. from jimvc.models import OSTemplateInitializeOperate
  26. from jimvc.models import GuestXML
  27. from jimvc.models import SSHKeyGuestMapping
  28. from jimvc.models import SSHKey
  29. from jimvc.models import Snapshot
  30. from jimvc.models import status
  31. __author__ = 'James Iter'
  32. __date__ = '2017/3/22'
  33. __contact__ = 'james.iter.cn@gmail.com'
  34. __copyright__ = '(c) 2017 by James Iter.'
  35. blueprint = Blueprint(
  36. 'api_guest',
  37. __name__,
  38. url_prefix='/api/guest'
  39. )
  40. blueprints = Blueprint(
  41. 'api_guests',
  42. __name__,
  43. url_prefix='/api/guests'
  44. )
  45. guest_base = Base(the_class=Guest, the_blueprint=blueprint, the_blueprints=blueprints)
  46. os_template_image_base = Base(the_class=OSTemplateImage, the_blueprint=blueprint, the_blueprints=blueprints)
  47. os_template_profile_base = Base(the_class=OSTemplateProfile, the_blueprint=blueprint, the_blueprints=blueprints)
  48. @Utils.dumps2response
  49. def r_create():
  50. args_rules = [
  51. Rules.CPU.value,
  52. Rules.MEMORY.value,
  53. Rules.BANDWIDTH.value,
  54. Rules.BANDWIDTH_UNIT.value,
  55. Rules.OS_TEMPLATE_IMAGE_ID.value,
  56. Rules.QUANTITY.value,
  57. Rules.REMARK.value,
  58. Rules.PASSWORD.value,
  59. Rules.LEASE_TERM.value
  60. ]
  61. if 'node_id' in request.json:
  62. args_rules.append(
  63. Rules.NODE_ID.value
  64. )
  65. if 'ssh_keys_id' in request.json:
  66. args_rules.append(
  67. Rules.SSH_KEYS_ID.value
  68. )
  69. try:
  70. ret = dict()
  71. ret['state'] = ji.Common.exchange_state(20000)
  72. ji.Check.previewing(args_rules, request.json)
  73. config = Config()
  74. config.id = 1
  75. config.get()
  76. os_template_image = OSTemplateImage()
  77. os_template_profile = OSTemplateProfile()
  78. os_template_image.id = request.json.get('os_template_image_id')
  79. if not os_template_image.exist():
  80. ret['state'] = ji.Common.exchange_state(40450)
  81. ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', os_template_image.id.__str__()])
  82. return ret
  83. os_template_image.get()
  84. os_template_profile.id = os_template_image.os_template_profile_id
  85. os_template_profile.get()
  86. os_template_initialize_operates, os_template_initialize_operates_count = \
  87. OSTemplateInitializeOperate.get_by_filter(
  88. filter_str='os_template_initialize_operate_set_id:eq:' +
  89. os_template_profile.os_template_initialize_operate_set_id.__str__())
  90. if db.r.scard(app_config['ip_available_set']) < 1:
  91. ret['state'] = ji.Common.exchange_state(50350)
  92. return ret
  93. node_id = request.json.get('node_id', None)
  94. # 默认只取可随机分配虚拟机的 hosts
  95. available_hosts = Host.get_available_hosts(nonrandom=False)
  96. # 当指定了 host 时,取全部活着的 hosts
  97. if node_id is not None:
  98. available_hosts = Host.get_available_hosts(nonrandom=None)
  99. if available_hosts.__len__() == 0:
  100. ret['state'] = ji.Common.exchange_state(50351)
  101. return ret
  102. available_hosts_mapping_by_node_id = dict()
  103. for host in available_hosts:
  104. if host['node_id'] not in available_hosts_mapping_by_node_id:
  105. available_hosts_mapping_by_node_id[host['node_id']] = host
  106. if node_id is not None and node_id not in available_hosts_mapping_by_node_id:
  107. ret['state'] = ji.Common.exchange_state(50351)
  108. return ret
  109. ssh_keys_id = request.json.get('ssh_keys_id', list())
  110. ssh_keys = list()
  111. ssh_key_guest_mapping = SSHKeyGuestMapping()
  112. if ssh_keys_id.__len__() > 0:
  113. rows, _ = SSHKey.get_by_filter(
  114. filter_str=':'.join(['id', 'in', ','.join(_id.__str__() for _id in ssh_keys_id)]))
  115. for row in rows:
  116. ssh_keys.append(row['public_key'])
  117. bandwidth = request.json.get('bandwidth')
  118. bandwidth_unit = request.json.get('bandwidth_unit')
  119. if bandwidth_unit == 'k':
  120. bandwidth = bandwidth * 1000
  121. elif bandwidth_unit == 'm':
  122. bandwidth = bandwidth * 1000 ** 2
  123. elif bandwidth_unit == 'g':
  124. bandwidth = bandwidth * 1000 ** 3
  125. else:
  126. ret = dict()
  127. ret['state'] = ji.Common.exchange_state(41203)
  128. raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
  129. # http://man7.org/linux/man-pages/man8/tc.8.html
  130. # 如果带宽大于 tc 所控最大速率,则置其为无限带宽
  131. # 34359738360 等于 tc 最大可控字节速率,换算出的比特位
  132. if bandwidth > 34359738360:
  133. bandwidth = 0
  134. quantity = request.json.get('quantity')
  135. while quantity:
  136. quantity -= 1
  137. guest = Guest()
  138. guest.uuid = uuid4().__str__()
  139. guest.cpu = request.json.get('cpu')
  140. # 虚拟机内存单位,模板生成方法中已置其为GiB
  141. guest.memory = request.json.get('memory')
  142. guest.bandwidth = bandwidth
  143. guest.os_template_image_id = request.json.get('os_template_image_id')
  144. guest.label = ji.Common.generate_random_code(length=8)
  145. guest.remark = request.json.get('remark', '')
  146. guest.password = request.json.get('password')
  147. if guest.password is None or guest.password.__len__() < 1:
  148. guest.password = ji.Common.generate_random_code(length=16)
  149. guest.ip = db.r.spop(app_config['ip_available_set'])
  150. db.r.sadd(app_config['ip_used_set'], guest.ip)
  151. guest.network = config.vm_network
  152. guest.manage_network = config.vm_manage_network
  153. guest.vnc_port = db.r.spop(app_config['vnc_port_available_set'])
  154. db.r.sadd(app_config['vnc_port_used_set'], guest.vnc_port)
  155. guest.vnc_password = ji.Common.generate_random_code(length=16)
  156. disk = Disk()
  157. disk.uuid = guest.uuid
  158. disk.remark = guest.label.__str__() + '_SystemImage'
  159. disk.format = 'qcow2'
  160. disk.sequence = 0
  161. disk.size = 0
  162. disk.path = config.storage_path + '/' + disk.uuid + '.' + disk.format
  163. disk.guest_uuid = ''
  164. # disk.node_id 由 guest 事件处理机更新。涉及迁移时,其所属 node_id 会变更。参见 @models/event_processory.py:111 附近。
  165. disk.node_id = 0
  166. disk.quota(config=config)
  167. disk.create()
  168. if node_id is None:
  169. # 在可用计算节点中平均分配任务
  170. chosen_host = available_hosts[quantity % available_hosts.__len__()]
  171. else:
  172. chosen_host = available_hosts_mapping_by_node_id[node_id]
  173. guest.node_id = chosen_host['node_id']
  174. guest_xml = GuestXML(host=chosen_host, guest=guest, disk=disk, config=config,
  175. os_type=os_template_profile.os_type)
  176. guest.xml = guest_xml.get_domain()
  177. guest.node_id = int(guest.node_id)
  178. guest.create()
  179. ssh_key_guest_mapping.guest_uuid = guest.uuid
  180. if ssh_keys_id.__len__() > 0:
  181. for ssh_key_id in ssh_keys_id:
  182. ssh_key_guest_mapping.ssh_key_id = ssh_key_id
  183. ssh_key_guest_mapping.create()
  184. if os_template_profile.os_distro == 'coreos':
  185. config.netmask = IP(guest.ip).make_net(config.netmask).prefixlen().__str__()
  186. # 替换占位符为有效内容
  187. _os_template_initialize_operates = copy.deepcopy(os_template_initialize_operates)
  188. for k, v in enumerate(_os_template_initialize_operates):
  189. _os_template_initialize_operates[k]['content'] = v['content'].replace('{IP}', guest.ip).\
  190. replace('{HOSTNAME}', guest.label). \
  191. replace('{PASSWORD}', guest.password). \
  192. replace('{NETMASK}', config.netmask).\
  193. replace('{GATEWAY}', config.gateway).\
  194. replace('{DNS1}', config.dns1).\
  195. replace('{DNS2}', config.dns2). \
  196. replace('{SSH-KEY}', '\n'.join(ssh_keys))
  197. _os_template_initialize_operates[k]['command'] = v['command'].replace('{IP}', guest.ip). \
  198. replace('{HOSTNAME}', guest.label). \
  199. replace('{PASSWORD}', guest.password). \
  200. replace('{NETMASK}', config.netmask). \
  201. replace('{GATEWAY}', config.gateway). \
  202. replace('{DNS1}', config.dns1). \
  203. replace('{DNS2}', config.dns2). \
  204. replace('{SSH-KEY}', '\n'.join(ssh_keys))
  205. message = {
  206. '_object': 'guest',
  207. 'action': 'create',
  208. 'uuid': guest.uuid,
  209. 'storage_mode': config.storage_mode,
  210. 'dfs_volume': config.dfs_volume,
  211. 'node_id': guest.node_id,
  212. 'name': guest.label,
  213. 'template_path': os_template_image.path,
  214. 'os_type': os_template_profile.os_type,
  215. 'disks': [disk.__dict__],
  216. 'xml': guest_xml.get_domain(),
  217. 'os_template_initialize_operates': _os_template_initialize_operates,
  218. 'passback_parameters': {}
  219. }
  220. Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  221. return ret
  222. except ji.PreviewingError, e:
  223. return json.loads(e.message)
  224. @Utils.dumps2response
  225. def r_reboot(uuids):
  226. args_rules = [
  227. Rules.UUIDS.value
  228. ]
  229. try:
  230. ji.Check.previewing(args_rules, {'uuids': uuids})
  231. guest = Guest()
  232. for uuid in uuids.split(','):
  233. guest.uuid = uuid
  234. guest.get_by('uuid')
  235. for uuid in uuids.split(','):
  236. guest.uuid = uuid
  237. guest.get_by('uuid')
  238. message = {
  239. '_object': 'guest',
  240. 'action': 'reboot',
  241. 'uuid': uuid,
  242. 'node_id': guest.node_id
  243. }
  244. Utils.emit_instruction(message=json.dumps(message))
  245. ret = dict()
  246. ret['state'] = ji.Common.exchange_state(20000)
  247. return ret
  248. except ji.PreviewingError, e:
  249. return json.loads(e.message)
  250. @Utils.dumps2response
  251. def r_force_reboot(uuids):
  252. args_rules = [
  253. Rules.UUIDS.value
  254. ]
  255. try:
  256. ji.Check.previewing(args_rules, {'uuids': uuids})
  257. guest = Guest()
  258. for uuid in uuids.split(','):
  259. guest.uuid = uuid
  260. guest.get_by('uuid')
  261. for uuid in uuids.split(','):
  262. guest.uuid = uuid
  263. guest.get_by('uuid')
  264. disks, _ = Disk.get_by_filter(filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))
  265. message = {
  266. '_object': 'guest',
  267. 'action': 'force_reboot',
  268. 'uuid': uuid,
  269. 'node_id': guest.node_id,
  270. 'disks': disks
  271. }
  272. Utils.emit_instruction(message=json.dumps(message))
  273. ret = dict()
  274. ret['state'] = ji.Common.exchange_state(20000)
  275. return ret
  276. except ji.PreviewingError, e:
  277. return json.loads(e.message)
  278. @Utils.dumps2response
  279. def r_shutdown(uuids):
  280. args_rules = [
  281. Rules.UUIDS.value
  282. ]
  283. try:
  284. ji.Check.previewing(args_rules, {'uuids': uuids})
  285. guest = Guest()
  286. for uuid in uuids.split(','):
  287. guest.uuid = uuid
  288. guest.get_by('uuid')
  289. for uuid in uuids.split(','):
  290. guest.uuid = uuid
  291. guest.get_by('uuid')
  292. message = {
  293. '_object': 'guest',
  294. 'action': 'shutdown',
  295. 'uuid': uuid,
  296. 'node_id': guest.node_id
  297. }
  298. Utils.emit_instruction(message=json.dumps(message))
  299. ret = dict()
  300. ret['state'] = ji.Common.exchange_state(20000)
  301. return ret
  302. except ji.PreviewingError, e:
  303. return json.loads(e.message)
  304. @Utils.dumps2response
  305. def r_force_shutdown(uuids):
  306. args_rules = [
  307. Rules.UUIDS.value
  308. ]
  309. try:
  310. ji.Check.previewing(args_rules, {'uuids': uuids})
  311. guest = Guest()
  312. for uuid in uuids.split(','):
  313. guest.uuid = uuid
  314. guest.get_by('uuid')
  315. for uuid in uuids.split(','):
  316. guest.uuid = uuid
  317. guest.get_by('uuid')
  318. message = {
  319. '_object': 'guest',
  320. 'action': 'force_shutdown',
  321. 'uuid': uuid,
  322. 'node_id': guest.node_id
  323. }
  324. Utils.emit_instruction(message=json.dumps(message))
  325. ret = dict()
  326. ret['state'] = ji.Common.exchange_state(20000)
  327. return ret
  328. except ji.PreviewingError, e:
  329. return json.loads(e.message)
  330. @Utils.dumps2response
  331. def r_boot(uuids):
  332. # TODO: 做好关系依赖判断,比如boot不可以对suspend的实例操作。
  333. args_rules = [
  334. Rules.UUIDS.value
  335. ]
  336. try:
  337. ji.Check.previewing(args_rules, {'uuids': uuids})
  338. guest = Guest()
  339. for uuid in uuids.split(','):
  340. guest.uuid = uuid
  341. guest.get_by('uuid')
  342. config = Config()
  343. config.id = 1
  344. config.get()
  345. for uuid in uuids.split(','):
  346. guest.uuid = uuid
  347. guest.get_by('uuid')
  348. disks, _ = Disk.get_by_filter(filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))
  349. message = {
  350. '_object': 'guest',
  351. 'action': 'boot',
  352. 'uuid': uuid,
  353. 'node_id': guest.node_id,
  354. 'passback_parameters': {},
  355. 'disks': disks
  356. }
  357. Utils.emit_instruction(message=json.dumps(message))
  358. ret = dict()
  359. ret['state'] = ji.Common.exchange_state(20000)
  360. return ret
  361. except ji.PreviewingError, e:
  362. return json.loads(e.message)
  363. @Utils.dumps2response
  364. def r_suspend(uuids):
  365. args_rules = [
  366. Rules.UUIDS.value
  367. ]
  368. try:
  369. ji.Check.previewing(args_rules, {'uuids': uuids})
  370. guest = Guest()
  371. for uuid in uuids.split(','):
  372. guest.uuid = uuid
  373. guest.get_by('uuid')
  374. for uuid in uuids.split(','):
  375. guest.uuid = uuid
  376. guest.get_by('uuid')
  377. message = {
  378. '_object': 'guest',
  379. 'action': 'suspend',
  380. 'uuid': uuid,
  381. 'node_id': guest.node_id
  382. }
  383. Utils.emit_instruction(message=json.dumps(message))
  384. ret = dict()
  385. ret['state'] = ji.Common.exchange_state(20000)
  386. return ret
  387. except ji.PreviewingError, e:
  388. return json.loads(e.message)
  389. @Utils.dumps2response
  390. def r_resume(uuids):
  391. args_rules = [
  392. Rules.UUIDS.value
  393. ]
  394. try:
  395. ji.Check.previewing(args_rules, {'uuids': uuids})
  396. guest = Guest()
  397. for uuid in uuids.split(','):
  398. guest.uuid = uuid
  399. guest.get_by('uuid')
  400. for uuid in uuids.split(','):
  401. guest.uuid = uuid
  402. guest.get_by('uuid')
  403. message = {
  404. '_object': 'guest',
  405. 'action': 'resume',
  406. 'uuid': uuid,
  407. 'node_id': guest.node_id
  408. }
  409. Utils.emit_instruction(message=json.dumps(message))
  410. ret = dict()
  411. ret['state'] = ji.Common.exchange_state(20000)
  412. return ret
  413. except ji.PreviewingError, e:
  414. return json.loads(e.message)
  415. @Utils.dumps2response
  416. def r_delete(uuids):
  417. args_rules = [
  418. Rules.UUIDS.value
  419. ]
  420. # TODO: 加入是否删除使用的数据磁盘开关,如果为True,则顺便删除使用的磁盘。否则解除该磁盘被使用的状态。
  421. try:
  422. ji.Check.previewing(args_rules, {'uuids': uuids})
  423. guest = Guest()
  424. # 检测所指定的 UUDIs 实例都存在
  425. for uuid in uuids.split(','):
  426. guest.uuid = uuid
  427. guest.get_by('uuid')
  428. config = Config()
  429. config.id = 1
  430. config.get()
  431. # 执行删除操作
  432. for uuid in uuids.split(','):
  433. guest.uuid = uuid
  434. guest.get_by('uuid')
  435. message = {
  436. '_object': 'guest',
  437. 'action': 'delete',
  438. 'uuid': uuid,
  439. 'storage_mode': config.storage_mode,
  440. 'dfs_volume': config.dfs_volume,
  441. 'node_id': guest.node_id
  442. }
  443. Utils.emit_instruction(message=json.dumps(message))
  444. # 删除创建失败的 Guest
  445. if guest.status == status.GuestState.dirty.value:
  446. disk = Disk()
  447. disk.uuid = guest.uuid
  448. disk.get_by('uuid')
  449. if disk.state == status.DiskState.pending.value:
  450. disk.delete()
  451. guest.delete()
  452. SSHKeyGuestMapping.delete_by_filter(filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))
  453. ret = dict()
  454. ret['state'] = ji.Common.exchange_state(20000)
  455. return ret
  456. except ji.PreviewingError, e:
  457. return json.loads(e.message)
  458. @Utils.dumps2response
  459. def r_attach_disk(uuid, disk_uuid):
  460. args_rules = [
  461. Rules.UUID.value,
  462. Rules.DISK_UUID.value
  463. ]
  464. try:
  465. ji.Check.previewing(args_rules, {'uuid': uuid, 'disk_uuid': disk_uuid})
  466. guest = Guest()
  467. guest.uuid = uuid
  468. guest.get_by('uuid')
  469. disk = Disk()
  470. disk.uuid = disk_uuid
  471. disk.get_by('uuid')
  472. config = Config()
  473. config.id = 1
  474. config.get()
  475. ret = dict()
  476. ret['state'] = ji.Common.exchange_state(20000)
  477. # 判断欲挂载的磁盘是否空闲
  478. if disk.guest_uuid.__len__() > 0 or disk.state != DiskState.idle.value:
  479. ret['state'] = ji.Common.exchange_state(41258)
  480. return ret
  481. # 判断 Guest 是否处于可用状态
  482. if guest.status in (status.GuestState.no_state.value, status.GuestState.dirty.value):
  483. ret['state'] = ji.Common.exchange_state(41259)
  484. return ret
  485. # 判断 Guest 与 磁盘是否在同一宿主机上
  486. if config.storage_mode in [status.StorageMode.local.value, status.StorageMode.shared_mount.value]:
  487. if guest.node_id != disk.node_id:
  488. ret['state'] = ji.Common.exchange_state(41260)
  489. return ret
  490. # 通过检测未被使用的序列,来确定当前磁盘在目标 Guest 身上的序列
  491. disk.guest_uuid = guest.uuid
  492. disks, count = disk.get_by_filter(filter_str='guest_uuid:in:' + guest.uuid)
  493. already_used_sequence = list()
  494. for _disk in disks:
  495. already_used_sequence.append(_disk['sequence'])
  496. for sequence in range(0, dev_table.__len__()):
  497. if sequence not in already_used_sequence:
  498. disk.sequence = sequence
  499. break
  500. disk.state = DiskState.mounting.value
  501. guest_xml = GuestXML(guest=guest, disk=disk, config=config)
  502. message = {
  503. '_object': 'guest',
  504. 'action': 'attach_disk',
  505. 'uuid': uuid,
  506. 'node_id': guest.node_id,
  507. 'xml': guest_xml.get_disk(),
  508. 'passback_parameters': {'disk_uuid': disk.uuid, 'sequence': disk.sequence},
  509. 'disks': [disk.__dict__]
  510. }
  511. Utils.emit_instruction(message=json.dumps(message))
  512. disk.update()
  513. return ret
  514. except ji.PreviewingError, e:
  515. return json.loads(e.message)
  516. @Utils.dumps2response
  517. def r_detach_disk(disk_uuid):
  518. args_rules = [
  519. Rules.DISK_UUID.value
  520. ]
  521. try:
  522. ji.Check.previewing(args_rules, {'disk_uuid': disk_uuid})
  523. disk = Disk()
  524. disk.uuid = disk_uuid
  525. disk.get_by('uuid')
  526. ret = dict()
  527. ret['state'] = ji.Common.exchange_state(20000)
  528. if disk.state != DiskState.mounted.value or disk.sequence == 0:
  529. # 表示未被任何实例使用,已被分离
  530. # 序列为 0 的表示实例系统盘,系统盘不可以被分离
  531. # TODO: 系统盘单独范围其它状态
  532. return ret
  533. guest = Guest()
  534. guest.uuid = disk.guest_uuid
  535. guest.get_by('uuid')
  536. # 判断 Guest 是否处于可用状态
  537. if guest.status in (status.GuestState.no_state.value, status.GuestState.dirty.value):
  538. ret['state'] = ji.Common.exchange_state(41259)
  539. return ret
  540. config = Config()
  541. config.id = 1
  542. config.get()
  543. guest_xml = GuestXML(guest=guest, disk=disk, config=config)
  544. message = {
  545. '_object': 'guest',
  546. 'action': 'detach_disk',
  547. 'uuid': disk.guest_uuid,
  548. 'node_id': guest.node_id,
  549. 'xml': guest_xml.get_disk(),
  550. 'passback_parameters': {'disk_uuid': disk.uuid}
  551. }
  552. Utils.emit_instruction(message=json.dumps(message))
  553. disk.state = DiskState.unloading.value
  554. disk.update()
  555. return ret
  556. except ji.PreviewingError, e:
  557. return json.loads(e.message)
  558. @Utils.dumps2response
  559. def r_migrate(uuids, destination_host):
  560. args_rules = [
  561. Rules.UUIDS.value,
  562. Rules.DESTINATION_HOST.value
  563. ]
  564. try:
  565. ji.Check.previewing(args_rules, {'uuids': uuids, 'destination_host': destination_host})
  566. ret = dict()
  567. ret['state'] = ji.Common.exchange_state(20000)
  568. # 取全部活着的 hosts
  569. available_hosts = Host.get_available_hosts(nonrandom=None)
  570. if available_hosts.__len__() == 0:
  571. ret['state'] = ji.Common.exchange_state(50351)
  572. return ret
  573. available_hosts_mapping_by_node_id = dict()
  574. for host in available_hosts:
  575. if host['node_id'] not in available_hosts_mapping_by_node_id:
  576. available_hosts_mapping_by_node_id[host['node_id']] = host
  577. guest = Guest()
  578. for uuid in uuids.split(','):
  579. guest.uuid = uuid
  580. guest.get_by('uuid')
  581. config = Config()
  582. config.id = 1
  583. config.get()
  584. for uuid in uuids.split(','):
  585. guest.uuid = uuid
  586. guest.get_by('uuid')
  587. # 忽略宕机计算节点 上面的 虚拟机 迁移请求
  588. # 忽略目标计算节点 等于 当前所在 计算节点 的虚拟机 迁移请求
  589. if guest.node_id not in available_hosts_mapping_by_node_id or \
  590. available_hosts_mapping_by_node_id[guest.node_id]['hostname'] == destination_host:
  591. continue
  592. message = {
  593. '_object': 'guest',
  594. 'action': 'migrate',
  595. 'uuid': uuid,
  596. 'node_id': guest.node_id,
  597. 'storage_mode': config.storage_mode,
  598. 'duri': 'qemu+ssh://' + destination_host + '/system'
  599. }
  600. Utils.emit_instruction(message=json.dumps(message))
  601. return ret
  602. except ji.PreviewingError, e:
  603. return json.loads(e.message)
  604. @Utils.dumps2response
  605. def r_get(uuids):
  606. ret = guest_base.get(ids=uuids, ids_rule=Rules.UUIDS.value, by_field='uuid')
  607. if '200' != ret['state']['code']:
  608. return ret
  609. rows, _ = SSHKeyGuestMapping.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', uuids]))
  610. guest_uuid_ssh_key_id_mapping = dict()
  611. ssh_keys_id = list()
  612. for row in rows:
  613. if row['ssh_key_id'] not in ssh_keys_id:
  614. ssh_keys_id.append(row['ssh_key_id'].__str__())
  615. if row['guest_uuid'] not in guest_uuid_ssh_key_id_mapping:
  616. guest_uuid_ssh_key_id_mapping[row['guest_uuid']] = list()
  617. guest_uuid_ssh_key_id_mapping[row['guest_uuid']].append(row['ssh_key_id'])
  618. rows, _ = SSHKey.get_by_filter(filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
  619. ssh_key_id_mapping = dict()
  620. for row in rows:
  621. row['url'] = url_for('v_ssh_keys.show')
  622. ssh_key_id_mapping[row['id']] = row
  623. if -1 == uuids.find(','):
  624. if 'ssh_keys' not in ret['data']:
  625. ret['data']['ssh_keys'] = list()
  626. if ret['data']['uuid'] in guest_uuid_ssh_key_id_mapping:
  627. for ssh_key_id in guest_uuid_ssh_key_id_mapping[ret['data']['uuid']]:
  628. if ssh_key_id not in ssh_key_id_mapping:
  629. continue
  630. ret['data']['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  631. else:
  632. for i, guest in enumerate(ret['data']):
  633. if 'ssh_keys' not in ret['data'][i]:
  634. ret['data'][i]['ssh_keys'] = list()
  635. if ret['data'][i]['uuid'] in guest_uuid_ssh_key_id_mapping:
  636. for ssh_key_id in guest_uuid_ssh_key_id_mapping[ret['data'][i]['uuid']]:
  637. if ssh_key_id not in ssh_key_id_mapping:
  638. continue
  639. ret['data'][i]['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  640. return ret
  641. @Utils.dumps2response
  642. def r_get_by_filter():
  643. ret = guest_base.get_by_filter()
  644. uuids = list()
  645. for guest in ret['data']:
  646. uuids.append(guest['uuid'])
  647. rows, _ = SSHKeyGuestMapping.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  648. guest_uuid_ssh_key_id_mapping = dict()
  649. ssh_keys_id = list()
  650. for row in rows:
  651. if row['ssh_key_id'] not in ssh_keys_id:
  652. ssh_keys_id.append(row['ssh_key_id'].__str__())
  653. if row['guest_uuid'] not in guest_uuid_ssh_key_id_mapping:
  654. guest_uuid_ssh_key_id_mapping[row['guest_uuid']] = list()
  655. guest_uuid_ssh_key_id_mapping[row['guest_uuid']].append(row['ssh_key_id'])
  656. rows, _ = SSHKey.get_by_filter(filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
  657. ssh_key_id_mapping = dict()
  658. for row in rows:
  659. row['url'] = url_for('v_ssh_keys.show')
  660. ssh_key_id_mapping[row['id']] = row
  661. rows, _ = Snapshot.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  662. snapshots_guest_uuid_mapping = dict()
  663. for row in rows:
  664. guest_uuid = row['guest_uuid']
  665. if guest_uuid not in snapshots_guest_uuid_mapping:
  666. snapshots_guest_uuid_mapping[guest_uuid] = list()
  667. snapshots_guest_uuid_mapping[guest_uuid].append(row)
  668. for i, guest in enumerate(ret['data']):
  669. guest_uuid = ret['data'][i]['uuid']
  670. if 'ssh_keys' not in ret['data'][i]:
  671. ret['data'][i]['ssh_keys'] = list()
  672. if guest_uuid in guest_uuid_ssh_key_id_mapping:
  673. for ssh_key_id in guest_uuid_ssh_key_id_mapping[guest_uuid]:
  674. if ssh_key_id not in ssh_key_id_mapping:
  675. continue
  676. ret['data'][i]['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  677. if 'snapshot' not in ret['data'][i]:
  678. ret['data'][i]['snapshot'] = {
  679. 'creatable': True,
  680. 'mapping': list()
  681. }
  682. if guest_uuid in snapshots_guest_uuid_mapping:
  683. ret['data'][i]['snapshot']['mapping'] = snapshots_guest_uuid_mapping[guest_uuid]
  684. for snapshot in snapshots_guest_uuid_mapping[guest_uuid]:
  685. if snapshot['progress'] == 100:
  686. continue
  687. else:
  688. ret['data'][i]['snapshot']['creatable'] = False
  689. return ret
  690. @Utils.dumps2response
  691. def r_content_search():
  692. ret = guest_base.content_search()
  693. uuids = list()
  694. for guest in ret['data']:
  695. uuids.append(guest['uuid'])
  696. rows, _ = SSHKeyGuestMapping.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  697. guest_uuid_ssh_key_id_mapping = dict()
  698. ssh_keys_id = list()
  699. for row in rows:
  700. if row['ssh_key_id'] not in ssh_keys_id:
  701. ssh_keys_id.append(row['ssh_key_id'].__str__())
  702. if row['guest_uuid'] not in guest_uuid_ssh_key_id_mapping:
  703. guest_uuid_ssh_key_id_mapping[row['guest_uuid']] = list()
  704. guest_uuid_ssh_key_id_mapping[row['guest_uuid']].append(row['ssh_key_id'])
  705. rows, _ = SSHKey.get_by_filter(filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
  706. ssh_key_id_mapping = dict()
  707. for row in rows:
  708. row['url'] = url_for('v_ssh_keys.show')
  709. ssh_key_id_mapping[row['id']] = row
  710. rows, _ = Snapshot.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  711. snapshots_guest_uuid_mapping = dict()
  712. for row in rows:
  713. guest_uuid = row['guest_uuid']
  714. if guest_uuid not in snapshots_guest_uuid_mapping:
  715. snapshots_guest_uuid_mapping[guest_uuid] = list()
  716. snapshots_guest_uuid_mapping[guest_uuid].append(row)
  717. for i, guest in enumerate(ret['data']):
  718. guest_uuid = ret['data'][i]['uuid']
  719. if 'ssh_keys' not in ret['data'][i]:
  720. ret['data'][i]['ssh_keys'] = list()
  721. if guest_uuid in guest_uuid_ssh_key_id_mapping:
  722. for ssh_key_id in guest_uuid_ssh_key_id_mapping[guest_uuid]:
  723. if ssh_key_id not in ssh_key_id_mapping:
  724. continue
  725. ret['data'][i]['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  726. if 'snapshot' not in ret['data'][i]:
  727. ret['data'][i]['snapshot'] = {
  728. 'creatable': True,
  729. 'mapping': list()
  730. }
  731. if guest_uuid in snapshots_guest_uuid_mapping:
  732. ret['data'][i]['snapshot']['mapping'] = snapshots_guest_uuid_mapping[guest_uuid]
  733. for snapshot in snapshots_guest_uuid_mapping[guest_uuid]:
  734. if snapshot['progress'] == 100:
  735. continue
  736. else:
  737. ret['data'][i]['snapshot']['creatable'] = False
  738. return ret
  739. @Utils.dumps2response
  740. def r_distribute_count():
  741. from jimvc.models import Guest
  742. rows, count = Guest.get_all()
  743. ret = dict()
  744. ret['state'] = ji.Common.exchange_state(20000)
  745. ret['data'] = {
  746. 'os_template_image_id': dict(),
  747. 'status': dict(),
  748. 'node_id': dict(),
  749. 'cpu_memory': dict(),
  750. 'cpu': 0,
  751. 'memory': 0,
  752. 'guests': rows.__len__()
  753. }
  754. for guest in rows:
  755. if guest['os_template_image_id'] not in ret['data']['os_template_image_id']:
  756. ret['data']['os_template_image_id'][guest['os_template_image_id']] = 0
  757. if guest['status'] not in ret['data']['status']:
  758. ret['data']['status'][guest['status']] = 0
  759. if guest['node_id'] not in ret['data']['node_id']:
  760. ret['data']['node_id'][guest['node_id']] = 0
  761. cpu_memory = '_'.join([str(guest['cpu']), str(guest['memory'])])
  762. if cpu_memory not in ret['data']['cpu_memory']:
  763. ret['data']['cpu_memory'][cpu_memory] = 0
  764. ret['data']['os_template_image_id'][guest['os_template_image_id']] += 1
  765. ret['data']['status'][guest['status']] += 1
  766. ret['data']['node_id'][guest['node_id']] += 1
  767. ret['data']['cpu_memory'][cpu_memory] += 1
  768. ret['data']['cpu'] += guest['cpu']
  769. ret['data']['memory'] += guest['memory']
  770. return ret
  771. @Utils.dumps2response
  772. def r_update(uuid):
  773. args_rules = [
  774. Rules.UUID.value
  775. ]
  776. if 'remark' in request.json:
  777. args_rules.append(
  778. Rules.REMARK.value,
  779. )
  780. if args_rules.__len__() < 2:
  781. ret = dict()
  782. ret['state'] = ji.Common.exchange_state(20000)
  783. return ret
  784. request.json['uuid'] = uuid
  785. try:
  786. ji.Check.previewing(args_rules, request.json)
  787. guest = Guest()
  788. guest.uuid = uuid
  789. guest.get_by('uuid')
  790. guest.remark = request.json.get('remark', guest.label)
  791. guest.update()
  792. guest.get()
  793. ret = dict()
  794. ret['state'] = ji.Common.exchange_state(20000)
  795. ret['data'] = guest.__dict__
  796. return ret
  797. except ji.PreviewingError, e:
  798. return json.loads(e.message)
  799. @Utils.dumps2response
  800. def r_reset_password(uuids, password):
  801. args_rules = [
  802. Rules.UUIDS.value,
  803. Rules.PASSWORD.value
  804. ]
  805. try:
  806. ji.Check.previewing(args_rules, {'uuids': uuids, 'password': password})
  807. guest = Guest()
  808. os_template_image = OSTemplateImage()
  809. os_template_profile = OSTemplateProfile()
  810. # 检测所指定的 UUDIs 实例都存在
  811. for uuid in uuids.split(','):
  812. guest.uuid = uuid
  813. guest.get_by('uuid')
  814. for uuid in uuids.split(','):
  815. guest.uuid = uuid
  816. guest.get_by('uuid')
  817. os_template_image.id = guest.os_template_image_id
  818. os_template_image.get()
  819. os_template_profile.id = os_template_image.os_template_profile_id
  820. os_template_profile.get()
  821. user = 'root'
  822. if os_template_profile.os_type == 'windows':
  823. user = 'administrator'
  824. # guest.password 由 guest 事件处理机更新。参见 @models/event_processory.py:189 附近。
  825. message = {
  826. '_object': 'guest',
  827. 'action': 'reset_password',
  828. 'uuid': guest.uuid,
  829. 'node_id': guest.node_id,
  830. 'os_type': os_template_profile.os_type,
  831. 'user': user,
  832. 'password': password,
  833. 'passback_parameters': {'password': password}
  834. }
  835. Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  836. ret = dict()
  837. ret['state'] = ji.Common.exchange_state(20000)
  838. return ret
  839. except ji.PreviewingError, e:
  840. return json.loads(e.message)
  841. @Utils.dumps2response
  842. def r_allocate_bandwidth(uuids, bandwidth, bandwidth_unit):
  843. args_rules = [
  844. Rules.UUIDS.value,
  845. Rules.BANDWIDTH_IN_URL.value,
  846. Rules.BANDWIDTH_UNIT.value,
  847. ]
  848. try:
  849. ji.Check.previewing(args_rules, {'uuids': uuids, 'bandwidth': bandwidth, 'bandwidth_unit': bandwidth_unit})
  850. ret = dict()
  851. ret['state'] = ji.Common.exchange_state(20000)
  852. bandwidth = int(bandwidth)
  853. if bandwidth_unit == 'k':
  854. bandwidth = bandwidth * 1000
  855. elif bandwidth_unit == 'm':
  856. bandwidth = bandwidth * 1000 ** 2
  857. elif bandwidth_unit == 'g':
  858. bandwidth = bandwidth * 1000 ** 3
  859. else:
  860. ret['state'] = ji.Common.exchange_state(41203)
  861. return ret
  862. # http://man7.org/linux/man-pages/man8/tc.8.html
  863. # 如果带宽大于 tc 所控最大速率,则置其为无限带宽
  864. # 34359738360 等于 tc 最大可控字节速率,换算出的比特位
  865. if bandwidth > 34359738360:
  866. bandwidth = 0
  867. guest = Guest()
  868. # 检测所指定的 UUDIs 实例都存在
  869. for uuid in uuids.split(','):
  870. guest.uuid = uuid
  871. guest.get_by('uuid')
  872. for uuid in uuids.split(','):
  873. guest.uuid = uuid
  874. guest.get_by('uuid')
  875. guest.bandwidth = bandwidth
  876. message = {
  877. '_object': 'guest',
  878. 'action': 'allocate_bandwidth',
  879. 'uuid': guest.uuid,
  880. 'node_id': guest.node_id,
  881. 'bandwidth': guest.bandwidth,
  882. 'passback_parameters': {'bandwidth': guest.bandwidth}
  883. }
  884. Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  885. return ret
  886. except ji.PreviewingError, e:
  887. return json.loads(e.message)
  888. @Utils.dumps2response
  889. def r_adjust_ability(uuids, cpu, memory):
  890. args_rules = [
  891. Rules.UUIDS.value,
  892. Rules.CPU.value,
  893. Rules.MEMORY.value,
  894. ]
  895. try:
  896. ret = dict()
  897. ret['state'] = ji.Common.exchange_state(20000)
  898. cpu = int(cpu)
  899. memory = int(memory)
  900. ji.Check.previewing(args_rules, {'uuids': uuids, 'cpu': cpu, 'memory': memory})
  901. not_ready_yet_of_guests = list()
  902. guest = Guest()
  903. # 检测所指定的 UUDIs 实例都存在。且状态都为可以操作状态(即关闭状态)。
  904. for uuid in uuids.split(','):
  905. guest.uuid = uuid
  906. guest.get_by('uuid')
  907. if guest.status != status.GuestState.shutoff.value:
  908. not_ready_yet_of_guests.append(guest.__dict__)
  909. if not_ready_yet_of_guests.__len__() > 0:
  910. ret['state'] = ji.Common.exchange_state(41261)
  911. ret['data'] = not_ready_yet_of_guests
  912. return ret
  913. for uuid in uuids.split(','):
  914. guest.uuid = uuid
  915. guest.get_by('uuid')
  916. guest.cpu = cpu
  917. guest.memory = memory
  918. message = {
  919. '_object': 'guest',
  920. 'action': 'adjust_ability',
  921. 'uuid': guest.uuid,
  922. 'node_id': guest.node_id,
  923. 'cpu': guest.cpu,
  924. 'memory': guest.memory,
  925. 'passback_parameters': {'cpu': guest.cpu, 'memory': guest.memory}
  926. }
  927. Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  928. return ret
  929. except ji.PreviewingError, e:
  930. return json.loads(e.message)
  931. @Utils.dumps2response
  932. def r_refresh_guest_state():
  933. try:
  934. ret = dict()
  935. ret['state'] = ji.Common.exchange_state(20000)
  936. # 取全部活着的 hosts
  937. available_hosts = Host.get_available_hosts(nonrandom=None)
  938. if available_hosts.__len__() == 0:
  939. ret['state'] = ji.Common.exchange_state(50351)
  940. return ret
  941. for host in available_hosts:
  942. message = {
  943. '_object': 'global',
  944. 'action': 'refresh_guest_state',
  945. 'node_id': host['node_id']
  946. }
  947. Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  948. except ji.PreviewingError, e:
  949. return json.loads(e.message)
  950. @Utils.dumps2response
  951. def r_show():
  952. args = list()
  953. page = int(request.args.get('page', 1))
  954. page_size = int(request.args.get('page_size', 10))
  955. keyword = request.args.get('keyword', None)
  956. if page is not None:
  957. args.append('page=' + page.__str__())
  958. if page_size is not None:
  959. args.append('page_size=' + page_size.__str__())
  960. if keyword is not None:
  961. args.append('keyword=' + keyword.__str__())
  962. hosts_url = url_for('api_hosts.r_get_by_filter', _external=True)
  963. guests_url = url_for('api_guests.r_get_by_filter', _external=True)
  964. if keyword is not None:
  965. guests_url = url_for('api_guests.r_content_search', _external=True)
  966. if args.__len__() > 0:
  967. guests_url = guests_url + '?' + '&'.join(args)
  968. hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
  969. hosts_ret = json.loads(hosts_ret.content)
  970. hosts_mapping_by_node_id = dict()
  971. for host in hosts_ret['data']:
  972. hosts_mapping_by_node_id[int(host['node_id'])] = host
  973. guests_ret = requests.get(url=guests_url, cookies=request.cookies)
  974. guests_ret = json.loads(guests_ret.content)
  975. os_templates_image, _ = OSTemplateImage.get_by_filter()
  976. os_templates_image_mapping_by_id = dict()
  977. for os_template_image in os_templates_image:
  978. os_templates_image_mapping_by_id[os_template_image['id']] = os_template_image
  979. os_templates_profile, _ = OSTemplateProfile.get_by_filter()
  980. os_templates_profile_mapping_by_id = dict()
  981. for os_template_profile in os_templates_profile:
  982. os_templates_profile_mapping_by_id[os_template_profile['id']] = os_template_profile
  983. last_page = int(ceil(guests_ret['paging']['total'] / float(page_size)))
  984. page_length = 5
  985. pages = list()
  986. if page < int(ceil(page_length / 2.0)):
  987. for i in range(1, page_length + 1):
  988. pages.append(i)
  989. if i == last_page or last_page == 0:
  990. break
  991. elif last_page - page < page_length / 2:
  992. for i in range(last_page - page_length + 1, last_page + 1):
  993. if i < 1:
  994. continue
  995. pages.append(i)
  996. else:
  997. for i in range(page - page_length / 2, page + int(ceil(page_length / 2.0))):
  998. pages.append(i)
  999. if i == last_page or last_page == 0:
  1000. break
  1001. ret = dict()
  1002. ret['state'] = ji.Common.exchange_state(20000)
  1003. ret['data'] = {
  1004. 'guests': guests_ret['data'],
  1005. 'os_templates_image_mapping_by_id': os_templates_image_mapping_by_id,
  1006. 'os_templates_profile_mapping_by_id': os_templates_profile_mapping_by_id,
  1007. 'hosts_mapping_by_node_id': hosts_mapping_by_node_id,
  1008. 'paging': guests_ret['paging'],
  1009. 'page': page,
  1010. 'page_size': page_size,
  1011. 'keyword': keyword,
  1012. 'pages': pages,
  1013. 'last_page': last_page
  1014. }
  1015. return ret
  1016. @Utils.dumps2response
  1017. def r_vnc(uuid):
  1018. guest_ret = guest_base.get(ids=uuid, ids_rule=Rules.UUID.value, by_field='uuid')
  1019. if '200' != guest_ret['state']['code']:
  1020. return guest_ret
  1021. hosts_url = url_for('api_hosts.r_get_by_filter', _external=True)
  1022. hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
  1023. hosts_ret = json.loads(hosts_ret.content)
  1024. hosts_mapping_by_node_id = dict()
  1025. for host in hosts_ret['data']:
  1026. hosts_mapping_by_node_id[int(host['node_id'])] = host
  1027. port = random.randrange(50000, 60000)
  1028. while True:
  1029. if not Utils.port_is_opened(port=port):
  1030. break
  1031. port = random.randrange(50000, 60000)
  1032. payload = {'listen_port': port, 'target_host': hosts_mapping_by_node_id[guest_ret['data']['node_id']]['hostname'],
  1033. 'target_port': guest_ret['data']['vnc_port']}
  1034. db.r.rpush(app_config['ipc_queue'], json.dumps(payload, ensure_ascii=False))
  1035. time.sleep(1)
  1036. ret = dict()
  1037. ret['state'] = ji.Common.exchange_state(20000)
  1038. ret['data'] = {
  1039. 'port': port,
  1040. 'vnc_password': guest_ret['data']['vnc_password']
  1041. }
  1042. return ret
  1043. @Utils.dumps2response
  1044. def r_detail(uuid):
  1045. hosts_url = url_for('api_hosts.r_get_by_filter', _external=True)
  1046. hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
  1047. hosts_ret = json.loads(hosts_ret.content)
  1048. hosts_mapping_by_node_id = dict()
  1049. for host in hosts_ret['data']:
  1050. hosts_mapping_by_node_id[int(host['node_id'])] = host
  1051. guest = Guest()
  1052. guest.uuid = uuid
  1053. guest.get_by(field='uuid')
  1054. guest.ssh_keys = list()
  1055. rows, _ = SSHKeyGuestMapping.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', guest.uuid]))
  1056. ssh_keys_id = list()
  1057. for row in rows:
  1058. if row['ssh_key_id'] not in ssh_keys_id:
  1059. ssh_keys_id.append(row['ssh_key_id'].__str__())
  1060. rows, _ = SSHKey.get_by_filter(filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
  1061. for row in rows:
  1062. row['url'] = url_for('v_ssh_keys.show')
  1063. guest.ssh_keys.append(row)
  1064. os_template_image = OSTemplateImage()
  1065. os_template_image.id = guest.os_template_image_id.__str__()
  1066. os_template_image.get()
  1067. os_template_profiles, _ = OSTemplateProfile.get_by_filter()
  1068. os_templates_profile_mapping_by_id = dict()
  1069. for os_template_profile in os_template_profiles:
  1070. os_templates_profile_mapping_by_id[os_template_profile['id']] = os_template_profile
  1071. disks_url = url_for('api_disks.r_get_by_filter', filter='guest_uuid:in:' + guest.uuid, _external=True)
  1072. disks_ret = requests.get(url=disks_url, cookies=request.cookies)
  1073. disks = json.loads(disks_ret.content)['data']
  1074. config = Config()
  1075. config.id = 1
  1076. config.get()
  1077. ret = dict()
  1078. ret['state'] = ji.Common.exchange_state(20000)
  1079. ret['data'] = {
  1080. 'uuid': uuid,
  1081. 'guest': guest.__dict__,
  1082. 'os_template_image': os_template_image.__dict__,
  1083. 'os_templates_profile_mapping_by_id': os_templates_profile_mapping_by_id,
  1084. 'hosts_mapping_by_node_id': hosts_mapping_by_node_id,
  1085. 'disks': disks,
  1086. 'config': config.__dict__
  1087. }
  1088. return ret