guest.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import json
  4. import random
  5. from flask import Blueprint, render_template, url_for, request
  6. import requests
  7. from math import ceil
  8. import re
  9. import socket
  10. import time
  11. from werkzeug.datastructures import ImmutableMultiDict
  12. from models import Database as db
  13. from models.initialize import config
  14. __author__ = 'James Iter'
  15. __date__ = '2017/5/30'
  16. __contact__ = 'james.iter.cn@gmail.com'
  17. __copyright__ = '(c) 2017 by James Iter.'
  18. blueprint = Blueprint(
  19. 'v_guest',
  20. __name__,
  21. url_prefix='/guest'
  22. )
  23. blueprints = Blueprint(
  24. 'v_guests',
  25. __name__,
  26. url_prefix='/guests'
  27. )
  28. def show():
  29. url = url_for('api_guests.r_show', _external=True)
  30. if request.args.__len__() >= 1:
  31. args = list()
  32. for k, v in request.args.items():
  33. args.append('='.join([k, v]))
  34. url += '?' + '&'.join(args)
  35. ret = requests.get(url=url, cookies=request.cookies)
  36. ret = json.loads(ret.content)
  37. return render_template('guests_show.html', guests_ret=ret['data']['guests_ret'],
  38. resource_path=request.path,
  39. os_templates_image_mapping_by_id=ret['data']['os_templates_image_mapping_by_id'],
  40. os_templates_profile_mapping_by_id=ret['data']['os_templates_profile_mapping_by_id'],
  41. hosts_mapping_by_node_id=ret['data']['hosts_mapping_by_node_id'], page=ret['data']['page'],
  42. page_size=ret['data']['page_size'], keyword=ret['data']['keyword'],
  43. pages=ret['data']['pages'], last_page=ret['data']['last_page'])
  44. def create():
  45. host_url = request.host_url.rstrip('/')
  46. if request.method == 'POST':
  47. ability = request.form.get('ability')
  48. bandwidth = request.form.get('bandwidth', 0)
  49. bandwidth_unit = request.form.get('bandwidth_unit', 'm')
  50. os_template_image_id = request.form.get('os_template_image_id')
  51. quantity = request.form.get('quantity')
  52. password = request.form.get('password')
  53. remark = request.form.get('remark')
  54. allocation_by_random = 'allocation_by_random' in request.form
  55. node_id = request.form.get('node_id')
  56. ssh_keys_id = request.form.getlist('ssh_keys_id')
  57. if not isinstance(ability, basestring):
  58. pass
  59. m = re.search('^(\d+)c(\d+)g$', ability.lower())
  60. if m is None:
  61. pass
  62. cpu = m.groups()[0]
  63. memory = m.groups()[1]
  64. payload = {
  65. "cpu": int(cpu),
  66. "memory": int(memory),
  67. "bandwidth": int(bandwidth),
  68. "bandwidth_unit": bandwidth_unit,
  69. "os_template_image_id": int(os_template_image_id),
  70. "quantity": int(quantity),
  71. "remark": remark,
  72. "password": password,
  73. "ssh_keys_id": ssh_keys_id,
  74. "lease_term": 100
  75. }
  76. if not allocation_by_random:
  77. payload['node_id'] = node_id
  78. url = host_url + '/api/guest'
  79. headers = {'content-type': 'application/json'}
  80. r = requests.post(url, data=json.dumps(payload), headers=headers, cookies=request.cookies)
  81. j_r = json.loads(r.content)
  82. if j_r['state']['code'] != '200':
  83. return render_template('failure.html',
  84. go_back_url='/guests',
  85. timeout=10000, title='创建失败',
  86. message_title='创建实例失败',
  87. message=j_r['state']['sub']['zh-cn'])
  88. guests_url = host_url + url_for('api_guests.r_get_by_filter')
  89. guests_ret = requests.get(url=guests_url, cookies=request.cookies)
  90. guests_ret = json.loads(guests_ret.content)
  91. page_size = 10
  92. last_page = int(ceil(guests_ret['paging']['total'] / float(page_size)))
  93. return render_template('success.html',
  94. go_back_url='/guests?page={0}&page_size={1}'.format(last_page, page_size),
  95. timeout=10000, title='提交成功',
  96. message_title='创建实例的请求已被接受',
  97. message='您所提交的资源正在创建中。根据所提交资源的大小,需要等待几到十几分钟。页面将在10秒钟后自动跳转到实例列表页面!')
  98. else:
  99. hosts_url = host_url + url_for('api_hosts.r_get_by_filter', alive=True)
  100. hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
  101. hosts_ret = json.loads(hosts_ret.content)
  102. return render_template('guest_create.html', hosts_ret=hosts_ret)
  103. def port_is_opened(port):
  104. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  105. result = s.connect_ex(('0.0.0.0', port))
  106. if result == 0:
  107. return True
  108. else:
  109. return False
  110. def vnc(uuid):
  111. host_url = request.host_url.rstrip('/')
  112. hosts_url = host_url + url_for('api_hosts.r_get_by_filter')
  113. guest_url = host_url + url_for('api_guests.r_get', uuids=uuid)
  114. guest_ret = requests.get(url=guest_url, cookies=request.cookies)
  115. guest_ret = json.loads(guest_ret.content)
  116. hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
  117. hosts_ret = json.loads(hosts_ret.content)
  118. hosts_mapping_by_node_id = dict()
  119. for host in hosts_ret['data']:
  120. hosts_mapping_by_node_id[int(host['node_id'])] = host
  121. port = random.randrange(50000, 60000)
  122. while True:
  123. if not port_is_opened(port=port):
  124. break
  125. port = random.randrange(50000, 60000)
  126. payload = {'listen_port': port, 'target_host': hosts_mapping_by_node_id[guest_ret['data']['node_id']]['hostname'],
  127. 'target_port': guest_ret['data']['vnc_port']}
  128. db.r.rpush(config['ipc_queue'], json.dumps(payload, ensure_ascii=False))
  129. time.sleep(1)
  130. return render_template('vnc_lite.html', port=port, password=guest_ret['data']['vnc_password'])
  131. def detail(uuid):
  132. host_url = request.host_url.rstrip('/')
  133. hosts_url = host_url + url_for('api_hosts.r_get_by_filter')
  134. guest_url = host_url + url_for('api_guests.r_get', uuids=uuid)
  135. hosts_ret = requests.get(url=hosts_url, cookies=request.cookies)
  136. hosts_ret = json.loads(hosts_ret.content)
  137. hosts_mapping_by_node_id = dict()
  138. for host in hosts_ret['data']:
  139. hosts_mapping_by_node_id[int(host['node_id'])] = host
  140. guest_ret = requests.get(url=guest_url, cookies=request.cookies)
  141. guest_ret = json.loads(guest_ret.content)
  142. os_template_image_url = host_url + url_for('api_os_templates_image.r_get',
  143. ids=guest_ret['data']['os_template_image_id'].__str__())
  144. os_templates_profile_url = host_url + url_for('api_os_templates_profile.r_get_by_filter')
  145. os_template_image_ret = requests.get(url=os_template_image_url, cookies=request.cookies)
  146. os_template_image_ret = json.loads(os_template_image_ret.content)
  147. os_templates_profile_ret = requests.get(url=os_templates_profile_url, cookies=request.cookies)
  148. os_templates_profile_ret = json.loads(os_templates_profile_ret.content)
  149. os_templates_profile_mapping_by_id = dict()
  150. for os_template_profile in os_templates_profile_ret['data']:
  151. os_templates_profile_mapping_by_id[os_template_profile['id']] = os_template_profile
  152. disks_url = host_url + url_for('api_disks.r_get_by_filter', filter='guest_uuid:in:' + guest_ret['data']['uuid'])
  153. disks_ret = requests.get(url=disks_url, cookies=request.cookies)
  154. disks_ret = json.loads(disks_ret.content)
  155. url = host_url + '/api/config'
  156. config_ret = requests.get(url=url, cookies=request.cookies)
  157. config_ret = json.loads(config_ret.content)
  158. return render_template('guest_detail.html', uuid=uuid, guest_ret=guest_ret,
  159. os_template_image_ret=os_template_image_ret,
  160. os_templates_profile_mapping_by_id=os_templates_profile_mapping_by_id,
  161. hosts_mapping_by_node_id=hosts_mapping_by_node_id,
  162. disks_ret=disks_ret, config_ret=config_ret)
  163. def success():
  164. return render_template('success.html', go_back_url='/guests', timeout=10000, title='提交成功',
  165. message_title='创建实例的请求已被接受',
  166. message='您所提交的资源正在创建中。根据所提交资源的大小,需要等待几到十几分钟。页面将在10秒钟后自动跳转到实例列表页面!')