guest.py 34 KB

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