guest.py 57 KB

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