guest.py 46 KB

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