guest.py 57 KB

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