guest.py 53 KB

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