guest.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import copy
  4. from flask import Blueprint, url_for
  5. from flask import request
  6. import json
  7. from uuid import uuid4
  8. import jimit as ji
  9. from api.base import Base
  10. from models import DiskState, Host
  11. from models.initialize import app, dev_table
  12. from models import Database as db
  13. from models import Config
  14. from models import Disk
  15. from models import Rules
  16. from models import Utils
  17. from models import Guest
  18. from models import OSTemplateImage
  19. from models import OSTemplateProfile
  20. from models import OSTemplateInitializeOperate
  21. from models import GuestXML
  22. from models import SSHKeyGuestMapping
  23. from models import SSHKey
  24. from models import Snapshot
  25. from models import status
  26. __author__ = 'James Iter'
  27. __date__ = '2017/3/22'
  28. __contact__ = 'james.iter.cn@gmail.com'
  29. __copyright__ = '(c) 2017 by James Iter.'
  30. blueprint = Blueprint(
  31. 'api_guest',
  32. __name__,
  33. url_prefix='/api/guest'
  34. )
  35. blueprints = Blueprint(
  36. 'api_guests',
  37. __name__,
  38. url_prefix='/api/guests'
  39. )
  40. guest_base = Base(the_class=Guest, the_blueprint=blueprint, the_blueprints=blueprints)
  41. @Utils.dumps2response
  42. def r_create():
  43. args_rules = [
  44. Rules.CPU.value,
  45. Rules.MEMORY.value,
  46. Rules.BANDWIDTH.value,
  47. Rules.BANDWIDTH_UNIT.value,
  48. Rules.OS_TEMPLATE_IMAGE_ID.value,
  49. Rules.QUANTITY.value,
  50. Rules.REMARK.value,
  51. Rules.PASSWORD.value,
  52. Rules.LEASE_TERM.value
  53. ]
  54. if 'node_id' in request.json:
  55. args_rules.append(
  56. Rules.NODE_ID.value
  57. )
  58. if 'ssh_keys_id' in request.json:
  59. args_rules.append(
  60. Rules.SSH_KEYS_ID.value
  61. )
  62. try:
  63. ret = dict()
  64. ret['state'] = ji.Common.exchange_state(20000)
  65. ji.Check.previewing(args_rules, request.json)
  66. config = Config()
  67. config.id = 1
  68. config.get()
  69. os_template_image = OSTemplateImage()
  70. os_template_profile = OSTemplateProfile()
  71. os_template_image.id = request.json.get('os_template_image_id')
  72. if not os_template_image.exist():
  73. ret['state'] = ji.Common.exchange_state(40450)
  74. ret['state']['sub']['zh-cn'] = ''.join([ret['state']['sub']['zh-cn'], ': ', os_template_image.id.__str__()])
  75. return ret
  76. os_template_image.get()
  77. os_template_profile.id = os_template_image.os_template_profile_id
  78. os_template_profile.get()
  79. os_template_initialize_operates, os_template_initialize_operates_count = \
  80. OSTemplateInitializeOperate.get_by_filter(
  81. filter_str='os_template_initialize_operate_set_id:eq:' +
  82. os_template_profile.os_template_initialize_operate_set_id.__str__())
  83. if db.r.scard(app.config['ip_available_set']) < 1:
  84. ret['state'] = ji.Common.exchange_state(50350)
  85. return ret
  86. node_id = request.json.get('node_id', None)
  87. # 默认只取可随机分配虚拟机的 hosts
  88. available_hosts = Host.get_available_hosts(nonrandom=False)
  89. # 当指定了 host 时,取全部活着的 hosts
  90. if node_id is not None:
  91. available_hosts = Host.get_available_hosts(nonrandom=None)
  92. if available_hosts.__len__() == 0:
  93. ret['state'] = ji.Common.exchange_state(50351)
  94. return ret
  95. if node_id is not None and node_id not in [host['node_id'] for host in available_hosts]:
  96. ret['state'] = ji.Common.exchange_state(50351)
  97. return ret
  98. ssh_keys_id = request.json.get('ssh_keys_id', list())
  99. ssh_keys = list()
  100. ssh_key_guest_mapping = SSHKeyGuestMapping()
  101. if ssh_keys_id.__len__() > 0:
  102. rows, _ = SSHKey.get_by_filter(
  103. filter_str=':'.join(['id', 'in', ','.join(_id.__str__() for _id in ssh_keys_id)]))
  104. for row in rows:
  105. ssh_keys.append(row['public_key'])
  106. bandwidth = request.json.get('bandwidth')
  107. bandwidth_unit = request.json.get('bandwidth_unit')
  108. if bandwidth_unit == 'k':
  109. bandwidth = bandwidth * 1000
  110. elif bandwidth_unit == 'm':
  111. bandwidth = bandwidth * 1000 ** 2
  112. elif bandwidth_unit == 'g':
  113. bandwidth = bandwidth * 1000 ** 3
  114. else:
  115. ret = dict()
  116. ret['state'] = ji.Common.exchange_state(41203)
  117. raise ji.PreviewingError(json.dumps(ret, ensure_ascii=False))
  118. quantity = request.json.get('quantity')
  119. while quantity:
  120. quantity -= 1
  121. guest = Guest()
  122. guest.uuid = uuid4().__str__()
  123. guest.cpu = request.json.get('cpu')
  124. # 虚拟机内存单位,模板生成方法中已置其为GiB
  125. guest.memory = request.json.get('memory')
  126. guest.bandwidth = bandwidth
  127. guest.os_template_image_id = request.json.get('os_template_image_id')
  128. guest.label = ji.Common.generate_random_code(length=8)
  129. guest.remark = request.json.get('remark', '')
  130. guest.password = request.json.get('password')
  131. if guest.password is None or guest.password.__len__() < 1:
  132. guest.password = ji.Common.generate_random_code(length=16)
  133. guest.ip = db.r.spop(app.config['ip_available_set'])
  134. db.r.sadd(app.config['ip_used_set'], guest.ip)
  135. guest.network = config.vm_network
  136. guest.manage_network = config.vm_manage_network
  137. guest.vnc_port = db.r.spop(app.config['vnc_port_available_set'])
  138. db.r.sadd(app.config['vnc_port_used_set'], guest.vnc_port)
  139. guest.vnc_password = ji.Common.generate_random_code(length=16)
  140. disk = Disk()
  141. disk.uuid = guest.uuid
  142. disk.remark = guest.label.__str__() + '_SystemImage'
  143. disk.format = 'qcow2'
  144. disk.sequence = 0
  145. disk.size = 0
  146. disk.path = config.storage_path + '/' + disk.uuid + '.' + disk.format
  147. disk.guest_uuid = ''
  148. # disk.node_id 由 guest 事件处理机更新。涉及迁移时,其所属 node_id 会变更。参见 @models/event_processory.py:111 附近。
  149. disk.node_id = 0
  150. disk.quota(config=config)
  151. disk.create()
  152. guest_xml = GuestXML(guest=guest, disk=disk, config=config, os_type=os_template_profile.os_type)
  153. guest.xml = guest_xml.get_domain()
  154. # 在可用计算节点中平均分配任务
  155. chosen_host = available_hosts[quantity % available_hosts.__len__()]
  156. guest.node_id = chosen_host['node_id']
  157. if node_id is not None:
  158. guest.node_id = node_id
  159. guest.node_id = int(guest.node_id)
  160. guest.create()
  161. ssh_key_guest_mapping.guest_uuid = guest.uuid
  162. if ssh_keys_id.__len__() > 0:
  163. for ssh_key_id in ssh_keys_id:
  164. ssh_key_guest_mapping.ssh_key_id = ssh_key_id
  165. ssh_key_guest_mapping.create()
  166. # 替换占位符为有效内容
  167. _os_template_initialize_operates = copy.deepcopy(os_template_initialize_operates)
  168. for k, v in enumerate(_os_template_initialize_operates):
  169. _os_template_initialize_operates[k]['content'] = v['content'].replace('{IP}', guest.ip).\
  170. replace('{HOSTNAME}', guest.label). \
  171. replace('{PASSWORD}', guest.password). \
  172. replace('{NETMASK}', config.netmask).\
  173. replace('{GATEWAY}', config.gateway).\
  174. replace('{DNS1}', config.dns1).\
  175. replace('{DNS2}', config.dns2). \
  176. replace('{SSH-KEY}', '\n'.join(ssh_keys))
  177. _os_template_initialize_operates[k]['command'] = v['command'].replace('{IP}', guest.ip). \
  178. replace('{HOSTNAME}', guest.label). \
  179. replace('{PASSWORD}', guest.password). \
  180. replace('{NETMASK}', config.netmask). \
  181. replace('{GATEWAY}', config.gateway). \
  182. replace('{DNS1}', config.dns1). \
  183. replace('{DNS2}', config.dns2). \
  184. replace('{SSH-KEY}', '\n'.join(ssh_keys))
  185. message = {
  186. '_object': 'guest',
  187. 'action': 'create',
  188. 'uuid': guest.uuid,
  189. 'storage_mode': config.storage_mode,
  190. 'dfs_volume': config.dfs_volume,
  191. 'node_id': guest.node_id,
  192. 'name': guest.label,
  193. 'template_path': os_template_image.path,
  194. 'os_type': os_template_profile.os_type,
  195. 'disks': [disk.__dict__],
  196. 'xml': guest_xml.get_domain(),
  197. 'os_template_initialize_operates': _os_template_initialize_operates,
  198. 'passback_parameters': {}
  199. }
  200. Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  201. return ret
  202. except ji.PreviewingError, e:
  203. return json.loads(e.message)
  204. @Utils.dumps2response
  205. def r_reboot(uuids):
  206. args_rules = [
  207. Rules.UUIDS.value
  208. ]
  209. try:
  210. ji.Check.previewing(args_rules, {'uuids': uuids})
  211. guest = Guest()
  212. for uuid in uuids.split(','):
  213. guest.uuid = uuid
  214. guest.get_by('uuid')
  215. for uuid in uuids.split(','):
  216. guest.uuid = uuid
  217. guest.get_by('uuid')
  218. message = {
  219. '_object': 'guest',
  220. 'action': 'reboot',
  221. 'uuid': uuid,
  222. 'node_id': guest.node_id
  223. }
  224. Utils.emit_instruction(message=json.dumps(message))
  225. ret = dict()
  226. ret['state'] = ji.Common.exchange_state(20000)
  227. return ret
  228. except ji.PreviewingError, e:
  229. return json.loads(e.message)
  230. @Utils.dumps2response
  231. def r_force_reboot(uuids):
  232. args_rules = [
  233. Rules.UUIDS.value
  234. ]
  235. try:
  236. ji.Check.previewing(args_rules, {'uuids': uuids})
  237. guest = Guest()
  238. for uuid in uuids.split(','):
  239. guest.uuid = uuid
  240. guest.get_by('uuid')
  241. for uuid in uuids.split(','):
  242. guest.uuid = uuid
  243. guest.get_by('uuid')
  244. disks, _ = Disk.get_by_filter(filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))
  245. message = {
  246. '_object': 'guest',
  247. 'action': 'force_reboot',
  248. 'uuid': uuid,
  249. 'node_id': guest.node_id,
  250. 'disks': disks
  251. }
  252. Utils.emit_instruction(message=json.dumps(message))
  253. ret = dict()
  254. ret['state'] = ji.Common.exchange_state(20000)
  255. return ret
  256. except ji.PreviewingError, e:
  257. return json.loads(e.message)
  258. @Utils.dumps2response
  259. def r_shutdown(uuids):
  260. args_rules = [
  261. Rules.UUIDS.value
  262. ]
  263. try:
  264. ji.Check.previewing(args_rules, {'uuids': uuids})
  265. guest = Guest()
  266. for uuid in uuids.split(','):
  267. guest.uuid = uuid
  268. guest.get_by('uuid')
  269. for uuid in uuids.split(','):
  270. guest.uuid = uuid
  271. guest.get_by('uuid')
  272. message = {
  273. '_object': 'guest',
  274. 'action': 'shutdown',
  275. 'uuid': uuid,
  276. 'node_id': guest.node_id
  277. }
  278. Utils.emit_instruction(message=json.dumps(message))
  279. ret = dict()
  280. ret['state'] = ji.Common.exchange_state(20000)
  281. return ret
  282. except ji.PreviewingError, e:
  283. return json.loads(e.message)
  284. @Utils.dumps2response
  285. def r_force_shutdown(uuids):
  286. args_rules = [
  287. Rules.UUIDS.value
  288. ]
  289. try:
  290. ji.Check.previewing(args_rules, {'uuids': uuids})
  291. guest = Guest()
  292. for uuid in uuids.split(','):
  293. guest.uuid = uuid
  294. guest.get_by('uuid')
  295. for uuid in uuids.split(','):
  296. guest.uuid = uuid
  297. guest.get_by('uuid')
  298. message = {
  299. '_object': 'guest',
  300. 'action': 'force_shutdown',
  301. 'uuid': uuid,
  302. 'node_id': guest.node_id
  303. }
  304. Utils.emit_instruction(message=json.dumps(message))
  305. ret = dict()
  306. ret['state'] = ji.Common.exchange_state(20000)
  307. return ret
  308. except ji.PreviewingError, e:
  309. return json.loads(e.message)
  310. @Utils.dumps2response
  311. def r_boot(uuids):
  312. # TODO: 做好关系依赖判断,比如boot不可以对suspend的实例操作。
  313. args_rules = [
  314. Rules.UUIDS.value
  315. ]
  316. try:
  317. ji.Check.previewing(args_rules, {'uuids': uuids})
  318. guest = Guest()
  319. for uuid in uuids.split(','):
  320. guest.uuid = uuid
  321. guest.get_by('uuid')
  322. config = Config()
  323. config.id = 1
  324. config.get()
  325. for uuid in uuids.split(','):
  326. guest.uuid = uuid
  327. guest.get_by('uuid')
  328. disks, _ = Disk.get_by_filter(filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))
  329. message = {
  330. '_object': 'guest',
  331. 'action': 'boot',
  332. 'uuid': uuid,
  333. 'node_id': guest.node_id,
  334. 'passback_parameters': {},
  335. 'disks': disks
  336. }
  337. Utils.emit_instruction(message=json.dumps(message))
  338. ret = dict()
  339. ret['state'] = ji.Common.exchange_state(20000)
  340. return ret
  341. except ji.PreviewingError, e:
  342. return json.loads(e.message)
  343. @Utils.dumps2response
  344. def r_suspend(uuids):
  345. args_rules = [
  346. Rules.UUIDS.value
  347. ]
  348. try:
  349. ji.Check.previewing(args_rules, {'uuids': uuids})
  350. guest = Guest()
  351. for uuid in uuids.split(','):
  352. guest.uuid = uuid
  353. guest.get_by('uuid')
  354. for uuid in uuids.split(','):
  355. guest.uuid = uuid
  356. guest.get_by('uuid')
  357. message = {
  358. '_object': 'guest',
  359. 'action': 'suspend',
  360. 'uuid': uuid,
  361. 'node_id': guest.node_id
  362. }
  363. Utils.emit_instruction(message=json.dumps(message))
  364. ret = dict()
  365. ret['state'] = ji.Common.exchange_state(20000)
  366. return ret
  367. except ji.PreviewingError, e:
  368. return json.loads(e.message)
  369. @Utils.dumps2response
  370. def r_resume(uuids):
  371. args_rules = [
  372. Rules.UUIDS.value
  373. ]
  374. try:
  375. ji.Check.previewing(args_rules, {'uuids': uuids})
  376. guest = Guest()
  377. for uuid in uuids.split(','):
  378. guest.uuid = uuid
  379. guest.get_by('uuid')
  380. for uuid in uuids.split(','):
  381. guest.uuid = uuid
  382. guest.get_by('uuid')
  383. message = {
  384. '_object': 'guest',
  385. 'action': 'resume',
  386. 'uuid': uuid,
  387. 'node_id': guest.node_id
  388. }
  389. Utils.emit_instruction(message=json.dumps(message))
  390. ret = dict()
  391. ret['state'] = ji.Common.exchange_state(20000)
  392. return ret
  393. except ji.PreviewingError, e:
  394. return json.loads(e.message)
  395. @Utils.dumps2response
  396. def r_delete(uuids):
  397. args_rules = [
  398. Rules.UUIDS.value
  399. ]
  400. # TODO: 加入是否删除使用的数据磁盘开关,如果为True,则顺便删除使用的磁盘。否则解除该磁盘被使用的状态。
  401. try:
  402. ji.Check.previewing(args_rules, {'uuids': uuids})
  403. guest = Guest()
  404. # 检测所指定的 UUDIs 实例都存在
  405. for uuid in uuids.split(','):
  406. guest.uuid = uuid
  407. guest.get_by('uuid')
  408. config = Config()
  409. config.id = 1
  410. config.get()
  411. # 执行删除操作
  412. for uuid in uuids.split(','):
  413. guest.uuid = uuid
  414. guest.get_by('uuid')
  415. message = {
  416. '_object': 'guest',
  417. 'action': 'delete',
  418. 'uuid': uuid,
  419. 'storage_mode': config.storage_mode,
  420. 'dfs_volume': config.dfs_volume,
  421. 'node_id': guest.node_id
  422. }
  423. Utils.emit_instruction(message=json.dumps(message))
  424. # 删除创建失败的 Guest
  425. if guest.status == status.GuestState.dirty.value:
  426. disk = Disk()
  427. disk.uuid = guest.uuid
  428. disk.get_by('uuid')
  429. if disk.state == status.DiskState.pending.value:
  430. disk.delete()
  431. guest.delete()
  432. SSHKeyGuestMapping.delete_by_filter(filter_str=':'.join(['guest_uuid', 'eq', guest.uuid]))
  433. ret = dict()
  434. ret['state'] = ji.Common.exchange_state(20000)
  435. return ret
  436. except ji.PreviewingError, e:
  437. return json.loads(e.message)
  438. @Utils.dumps2response
  439. def r_attach_disk(uuid, disk_uuid):
  440. args_rules = [
  441. Rules.UUID.value,
  442. Rules.DISK_UUID.value
  443. ]
  444. try:
  445. ji.Check.previewing(args_rules, {'uuid': uuid, 'disk_uuid': disk_uuid})
  446. guest = Guest()
  447. guest.uuid = uuid
  448. guest.get_by('uuid')
  449. disk = Disk()
  450. disk.uuid = disk_uuid
  451. disk.get_by('uuid')
  452. config = Config()
  453. config.id = 1
  454. config.get()
  455. ret = dict()
  456. ret['state'] = ji.Common.exchange_state(20000)
  457. # 判断欲挂载的磁盘是否空闲
  458. if disk.guest_uuid.__len__() > 0 or disk.state != DiskState.idle.value:
  459. ret['state'] = ji.Common.exchange_state(41258)
  460. return ret
  461. # 判断 Guest 是否处于可用状态
  462. if guest.status in (status.GuestState.no_state.value, status.GuestState.dirty.value):
  463. ret['state'] = ji.Common.exchange_state(41259)
  464. return ret
  465. # 判断 Guest 与 磁盘是否在同一宿主机上
  466. if config.storage_mode in [status.StorageMode.local.value, status.StorageMode.shared_mount.value]:
  467. if guest.node_id != disk.node_id:
  468. ret['state'] = ji.Common.exchange_state(41260)
  469. return ret
  470. # 通过检测未被使用的序列,来确定当前磁盘在目标 Guest 身上的序列
  471. disk.guest_uuid = guest.uuid
  472. disks, count = disk.get_by_filter(filter_str='guest_uuid:in:' + guest.uuid)
  473. already_used_sequence = list()
  474. for _disk in disks:
  475. already_used_sequence.append(_disk['sequence'])
  476. for sequence in range(0, dev_table.__len__()):
  477. if sequence not in already_used_sequence:
  478. disk.sequence = sequence
  479. break
  480. disk.state = DiskState.mounting.value
  481. guest_xml = GuestXML(guest=guest, disk=disk, config=config)
  482. message = {
  483. '_object': 'guest',
  484. 'action': 'attach_disk',
  485. 'uuid': uuid,
  486. 'node_id': guest.node_id,
  487. 'xml': guest_xml.get_disk(),
  488. 'passback_parameters': {'disk_uuid': disk.uuid, 'sequence': disk.sequence},
  489. 'disks': [disk.__dict__]
  490. }
  491. Utils.emit_instruction(message=json.dumps(message))
  492. disk.update()
  493. return ret
  494. except ji.PreviewingError, e:
  495. return json.loads(e.message)
  496. @Utils.dumps2response
  497. def r_detach_disk(disk_uuid):
  498. args_rules = [
  499. Rules.DISK_UUID.value
  500. ]
  501. try:
  502. ji.Check.previewing(args_rules, {'disk_uuid': disk_uuid})
  503. disk = Disk()
  504. disk.uuid = disk_uuid
  505. disk.get_by('uuid')
  506. ret = dict()
  507. ret['state'] = ji.Common.exchange_state(20000)
  508. if disk.state != DiskState.mounted.value or disk.sequence == 0:
  509. # 表示未被任何实例使用,已被分离
  510. # 序列为 0 的表示实例系统盘,系统盘不可以被分离
  511. # TODO: 系统盘单独范围其它状态
  512. return ret
  513. guest = Guest()
  514. guest.uuid = disk.guest_uuid
  515. guest.get_by('uuid')
  516. # 判断 Guest 是否处于可用状态
  517. if guest.status in (status.GuestState.no_state.value, status.GuestState.dirty.value):
  518. ret['state'] = ji.Common.exchange_state(41259)
  519. return ret
  520. config = Config()
  521. config.id = 1
  522. config.get()
  523. guest_xml = GuestXML(guest=guest, disk=disk, config=config)
  524. message = {
  525. '_object': 'guest',
  526. 'action': 'detach_disk',
  527. 'uuid': disk.guest_uuid,
  528. 'node_id': guest.node_id,
  529. 'xml': guest_xml.get_disk(),
  530. 'passback_parameters': {'disk_uuid': disk.uuid}
  531. }
  532. Utils.emit_instruction(message=json.dumps(message))
  533. disk.state = DiskState.unloading.value
  534. disk.update()
  535. return ret
  536. except ji.PreviewingError, e:
  537. return json.loads(e.message)
  538. @Utils.dumps2response
  539. def r_migrate(uuids, destination_host):
  540. args_rules = [
  541. Rules.UUIDS.value,
  542. Rules.DESTINATION_HOST.value
  543. ]
  544. try:
  545. ji.Check.previewing(args_rules, {'uuids': uuids, 'destination_host': destination_host})
  546. guest = Guest()
  547. for uuid in uuids.split(','):
  548. guest.uuid = uuid
  549. guest.get_by('uuid')
  550. config = Config()
  551. config.id = 1
  552. config.get()
  553. for uuid in uuids.split(','):
  554. guest.uuid = uuid
  555. guest.get_by('uuid')
  556. message = {
  557. '_object': 'guest',
  558. 'action': 'migrate',
  559. 'uuid': uuid,
  560. 'node_id': guest.node_id,
  561. 'storage_mode': config.storage_mode,
  562. 'duri': 'qemu+ssh://' + destination_host + '/system'
  563. }
  564. Utils.emit_instruction(message=json.dumps(message))
  565. ret = dict()
  566. ret['state'] = ji.Common.exchange_state(20000)
  567. return ret
  568. except ji.PreviewingError, e:
  569. return json.loads(e.message)
  570. @Utils.dumps2response
  571. def r_get(uuids):
  572. ret = guest_base.get(ids=uuids, ids_rule=Rules.UUIDS.value, by_field='uuid')
  573. if '200' != ret['state']['code']:
  574. return ret
  575. rows, _ = SSHKeyGuestMapping.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', uuids]))
  576. guest_uuid_ssh_key_id_mapping = dict()
  577. ssh_keys_id = list()
  578. for row in rows:
  579. if row['ssh_key_id'] not in ssh_keys_id:
  580. ssh_keys_id.append(row['ssh_key_id'].__str__())
  581. if row['guest_uuid'] not in guest_uuid_ssh_key_id_mapping:
  582. guest_uuid_ssh_key_id_mapping[row['guest_uuid']] = list()
  583. guest_uuid_ssh_key_id_mapping[row['guest_uuid']].append(row['ssh_key_id'])
  584. rows, _ = SSHKey.get_by_filter(filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
  585. ssh_key_id_mapping = dict()
  586. for row in rows:
  587. row['url'] = url_for('v_ssh_keys.show')
  588. ssh_key_id_mapping[row['id']] = row
  589. if -1 == uuids.find(','):
  590. if 'ssh_keys' not in ret['data']:
  591. ret['data']['ssh_keys'] = list()
  592. if ret['data']['uuid'] in guest_uuid_ssh_key_id_mapping:
  593. for ssh_key_id in guest_uuid_ssh_key_id_mapping[ret['data']['uuid']]:
  594. if ssh_key_id not in ssh_key_id_mapping:
  595. continue
  596. ret['data']['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  597. else:
  598. for i, guest in enumerate(ret['data']):
  599. if 'ssh_keys' not in ret['data'][i]:
  600. ret['data'][i]['ssh_keys'] = list()
  601. if ret['data'][i]['uuid'] in guest_uuid_ssh_key_id_mapping:
  602. for ssh_key_id in guest_uuid_ssh_key_id_mapping[ret['data'][i]['uuid']]:
  603. if ssh_key_id not in ssh_key_id_mapping:
  604. continue
  605. ret['data'][i]['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  606. return ret
  607. @Utils.dumps2response
  608. def r_get_by_filter():
  609. ret = guest_base.get_by_filter()
  610. uuids = list()
  611. for guest in ret['data']:
  612. uuids.append(guest['uuid'])
  613. rows, _ = SSHKeyGuestMapping.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  614. guest_uuid_ssh_key_id_mapping = dict()
  615. ssh_keys_id = list()
  616. for row in rows:
  617. if row['ssh_key_id'] not in ssh_keys_id:
  618. ssh_keys_id.append(row['ssh_key_id'].__str__())
  619. if row['guest_uuid'] not in guest_uuid_ssh_key_id_mapping:
  620. guest_uuid_ssh_key_id_mapping[row['guest_uuid']] = list()
  621. guest_uuid_ssh_key_id_mapping[row['guest_uuid']].append(row['ssh_key_id'])
  622. rows, _ = SSHKey.get_by_filter(filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
  623. ssh_key_id_mapping = dict()
  624. for row in rows:
  625. row['url'] = url_for('v_ssh_keys.show')
  626. ssh_key_id_mapping[row['id']] = row
  627. rows, _ = Snapshot.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  628. snapshots_guest_uuid_mapping = dict()
  629. for row in rows:
  630. guest_uuid = row['guest_uuid']
  631. if guest_uuid not in snapshots_guest_uuid_mapping:
  632. snapshots_guest_uuid_mapping[guest_uuid] = list()
  633. snapshots_guest_uuid_mapping[guest_uuid].append(row)
  634. for i, guest in enumerate(ret['data']):
  635. guest_uuid = ret['data'][i]['uuid']
  636. if 'ssh_keys' not in ret['data'][i]:
  637. ret['data'][i]['ssh_keys'] = list()
  638. if guest_uuid in guest_uuid_ssh_key_id_mapping:
  639. for ssh_key_id in guest_uuid_ssh_key_id_mapping[guest_uuid]:
  640. if ssh_key_id not in ssh_key_id_mapping:
  641. continue
  642. ret['data'][i]['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  643. if 'snapshot' not in ret['data'][i]:
  644. ret['data'][i]['snapshot'] = {
  645. 'creatable': True,
  646. 'mapping': list()
  647. }
  648. if guest_uuid in snapshots_guest_uuid_mapping:
  649. ret['data'][i]['snapshot']['mapping'] = snapshots_guest_uuid_mapping[guest_uuid]
  650. for snapshot in snapshots_guest_uuid_mapping[guest_uuid]:
  651. if snapshot['progress'] == 100:
  652. continue
  653. else:
  654. ret['data'][i]['snapshot']['creatable'] = False
  655. return ret
  656. @Utils.dumps2response
  657. def r_content_search():
  658. ret = guest_base.content_search()
  659. uuids = list()
  660. for guest in ret['data']:
  661. uuids.append(guest['uuid'])
  662. rows, _ = SSHKeyGuestMapping.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  663. guest_uuid_ssh_key_id_mapping = dict()
  664. ssh_keys_id = list()
  665. for row in rows:
  666. if row['ssh_key_id'] not in ssh_keys_id:
  667. ssh_keys_id.append(row['ssh_key_id'].__str__())
  668. if row['guest_uuid'] not in guest_uuid_ssh_key_id_mapping:
  669. guest_uuid_ssh_key_id_mapping[row['guest_uuid']] = list()
  670. guest_uuid_ssh_key_id_mapping[row['guest_uuid']].append(row['ssh_key_id'])
  671. rows, _ = SSHKey.get_by_filter(filter_str=':'.join(['id', 'in', ','.join(ssh_keys_id)]))
  672. ssh_key_id_mapping = dict()
  673. for row in rows:
  674. row['url'] = url_for('v_ssh_keys.show')
  675. ssh_key_id_mapping[row['id']] = row
  676. rows, _ = Snapshot.get_by_filter(filter_str=':'.join(['guest_uuid', 'in', ','.join(uuids)]))
  677. snapshots_guest_uuid_mapping = dict()
  678. for row in rows:
  679. guest_uuid = row['guest_uuid']
  680. if guest_uuid not in snapshots_guest_uuid_mapping:
  681. snapshots_guest_uuid_mapping[guest_uuid] = list()
  682. snapshots_guest_uuid_mapping[guest_uuid].append(row)
  683. for i, guest in enumerate(ret['data']):
  684. guest_uuid = ret['data'][i]['uuid']
  685. if 'ssh_keys' not in ret['data'][i]:
  686. ret['data'][i]['ssh_keys'] = list()
  687. if guest_uuid in guest_uuid_ssh_key_id_mapping:
  688. for ssh_key_id in guest_uuid_ssh_key_id_mapping[guest_uuid]:
  689. if ssh_key_id not in ssh_key_id_mapping:
  690. continue
  691. ret['data'][i]['ssh_keys'].append(ssh_key_id_mapping[ssh_key_id])
  692. if 'snapshot' not in ret['data'][i]:
  693. ret['data'][i]['snapshot'] = {
  694. 'creatable': True,
  695. 'mapping': list()
  696. }
  697. if guest_uuid in snapshots_guest_uuid_mapping:
  698. ret['data'][i]['snapshot']['mapping'] = snapshots_guest_uuid_mapping[guest_uuid]
  699. for snapshot in snapshots_guest_uuid_mapping[guest_uuid]:
  700. if snapshot['progress'] == 100:
  701. continue
  702. else:
  703. ret['data'][i]['snapshot']['creatable'] = False
  704. return ret
  705. @Utils.dumps2response
  706. def r_distribute_count():
  707. from models import Guest
  708. rows, count = Guest.get_all()
  709. ret = dict()
  710. ret['state'] = ji.Common.exchange_state(20000)
  711. ret['data'] = {
  712. 'os_template_image_id': dict(),
  713. 'status': dict(),
  714. 'node_id': dict(),
  715. 'cpu_memory': dict(),
  716. 'cpu': 0,
  717. 'memory': 0,
  718. 'guests': rows.__len__()
  719. }
  720. for guest in rows:
  721. if guest['os_template_image_id'] not in ret['data']['os_template_image_id']:
  722. ret['data']['os_template_image_id'][guest['os_template_image_id']] = 0
  723. if guest['status'] not in ret['data']['status']:
  724. ret['data']['status'][guest['status']] = 0
  725. if guest['node_id'] not in ret['data']['node_id']:
  726. ret['data']['node_id'][guest['node_id']] = 0
  727. cpu_memory = '_'.join([str(guest['cpu']), str(guest['memory'])])
  728. if cpu_memory not in ret['data']['cpu_memory']:
  729. ret['data']['cpu_memory'][cpu_memory] = 0
  730. ret['data']['os_template_image_id'][guest['os_template_image_id']] += 1
  731. ret['data']['status'][guest['status']] += 1
  732. ret['data']['node_id'][guest['node_id']] += 1
  733. ret['data']['cpu_memory'][cpu_memory] += 1
  734. ret['data']['cpu'] += guest['cpu']
  735. ret['data']['memory'] += guest['memory']
  736. return ret
  737. @Utils.dumps2response
  738. def r_update(uuid):
  739. args_rules = [
  740. Rules.UUID.value
  741. ]
  742. if 'remark' in request.json:
  743. args_rules.append(
  744. Rules.REMARK.value,
  745. )
  746. if args_rules.__len__() < 2:
  747. ret = dict()
  748. ret['state'] = ji.Common.exchange_state(20000)
  749. return ret
  750. request.json['uuid'] = uuid
  751. try:
  752. ji.Check.previewing(args_rules, request.json)
  753. guest = Guest()
  754. guest.uuid = uuid
  755. guest.get_by('uuid')
  756. guest.remark = request.json.get('remark', guest.label)
  757. guest.update()
  758. guest.get()
  759. ret = dict()
  760. ret['state'] = ji.Common.exchange_state(20000)
  761. ret['data'] = guest.__dict__
  762. return ret
  763. except ji.PreviewingError, e:
  764. return json.loads(e.message)
  765. @Utils.dumps2response
  766. def r_reset_password(uuids, password):
  767. args_rules = [
  768. Rules.UUIDS.value,
  769. Rules.PASSWORD.value
  770. ]
  771. try:
  772. ji.Check.previewing(args_rules, {'uuids': uuids, 'password': password})
  773. guest = Guest()
  774. os_template_image = OSTemplateImage()
  775. os_template_profile = OSTemplateProfile()
  776. # 检测所指定的 UUDIs 实例都存在
  777. for uuid in uuids.split(','):
  778. guest.uuid = uuid
  779. guest.get_by('uuid')
  780. for uuid in uuids.split(','):
  781. guest.uuid = uuid
  782. guest.get_by('uuid')
  783. os_template_image.id = guest.os_template_image_id
  784. os_template_image.get()
  785. os_template_profile.id = os_template_image.os_template_profile_id
  786. os_template_profile.get()
  787. user = 'root'
  788. if os_template_profile.os_type == 'windows':
  789. user = 'administrator'
  790. # guest.password 由 guest 事件处理机更新。参见 @models/event_processory.py:189 附近。
  791. message = {
  792. '_object': 'guest',
  793. 'action': 'reset_password',
  794. 'uuid': guest.uuid,
  795. 'node_id': guest.node_id,
  796. 'os_type': os_template_profile.os_type,
  797. 'user': user,
  798. 'password': password,
  799. 'passback_parameters': {'password': password}
  800. }
  801. Utils.emit_instruction(message=json.dumps(message, ensure_ascii=False))
  802. ret = dict()
  803. ret['state'] = ji.Common.exchange_state(20000)
  804. return ret
  805. except ji.PreviewingError, e:
  806. return json.loads(e.message)