guest.py 27 KB

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