guest.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. from models.initialize import q_ws
  11. __author__ = 'James Iter'
  12. __date__ = '2017/5/30'
  13. __contact__ = 'james.iter.cn@gmail.com'
  14. __copyright__ = '(c) 2017 by James Iter.'
  15. blueprint = Blueprint(
  16. 'v_guest',
  17. __name__,
  18. url_prefix='/guest'
  19. )
  20. blueprints = Blueprint(
  21. 'v_guests',
  22. __name__,
  23. url_prefix='/guests'
  24. )
  25. def show():
  26. args = list()
  27. page = int(request.args.get('page', 1))
  28. page_size = int(request.args.get('page_size', 10))
  29. keyword = request.args.get('keyword', None)
  30. resource_path = request.path
  31. if page is not None:
  32. args.append('page=' + page.__str__())
  33. if page_size is not None:
  34. args.append('page_size=' + page_size.__str__())
  35. if keyword is not None:
  36. args.append('keyword=' + keyword.__str__())
  37. host_url = request.host_url.rstrip('/')
  38. guests_url = host_url + url_for('api_guests.r_get_by_filter')
  39. if keyword is not None:
  40. guests_url = host_url + url_for('api_guests.r_content_search')
  41. os_template_url = host_url + url_for('api_os_templates.r_get_by_filter')
  42. if args.__len__() > 0:
  43. guests_url = guests_url + '?' + '&'.join(args)
  44. guests_ret = requests.get(url=guests_url)
  45. guests_ret = json.loads(guests_ret.content)
  46. os_template_ret = requests.get(url=os_template_url)
  47. os_template_ret = json.loads(os_template_ret.content)
  48. os_template_mapping_by_id = dict()
  49. for os_template in os_template_ret['data']:
  50. os_template_mapping_by_id[os_template['id']] = os_template
  51. last_page = int(ceil(guests_ret['paging']['total'] / float(page_size)))
  52. page_length = 5
  53. pages = list()
  54. if page < int(ceil(page_length / 2.0)):
  55. for i in range(1, page_length + 1):
  56. pages.append(i)
  57. if i == last_page:
  58. break
  59. elif last_page - page < page_length / 2:
  60. for i in range(last_page - page_length + 1, last_page + 1):
  61. if i < 1:
  62. continue
  63. pages.append(i)
  64. else:
  65. for i in range(page - page_length / 2, page + int(ceil(page_length / 2.0))):
  66. pages.append(i)
  67. if i == last_page:
  68. break
  69. return render_template('guest_show.html', guests_ret=guests_ret, resource_path=resource_path,
  70. os_template_mapping_by_id=os_template_mapping_by_id, page=page,
  71. page_size=page_size, keyword=keyword, pages=pages, last_page=last_page)
  72. def create():
  73. host_url = request.host_url.rstrip('/')
  74. if request.method == 'POST':
  75. ability = request.form.get('ability')
  76. os_template_id = request.form.get('os_template_id')
  77. quantity = request.form.get('quantity')
  78. password = request.form.get('password')
  79. remark = request.form.get('remark')
  80. if not isinstance(ability, basestring):
  81. pass
  82. m = re.search('^(\d)c(\d)g$', ability.lower())
  83. if m is None:
  84. pass
  85. cpu = m.groups()[0]
  86. memory = m.groups()[1]
  87. payload = {
  88. "cpu": int(cpu),
  89. "memory": int(memory),
  90. "os_template_id": int(os_template_id),
  91. "quantity": int(quantity),
  92. "remark": remark,
  93. "password": password,
  94. "lease_term": 100
  95. }
  96. url = host_url + '/api/guest'
  97. headers = {'content-type': 'application/json'}
  98. r = requests.post(url, data=json.dumps(payload), headers=headers)
  99. j_r = json.loads(r.content)
  100. return render_template('success.html', go_back_url='/guests', timeout=10000, title='提交成功',
  101. message_title='创建实例的请求已被接受',
  102. message='您所提交的资源正在创建中。根据所提交资源的大小,需要等待几到十几分钟。页面将在10秒钟后自动跳转到实例列表页面!')
  103. else:
  104. os_template_url = host_url + url_for('api_os_templates.r_get_by_filter')
  105. os_template_ret = requests.get(url=os_template_url)
  106. os_template_ret = json.loads(os_template_ret.content)
  107. return render_template('guest_create.html', os_template_data=os_template_ret['data'])
  108. def port_is_opened(port):
  109. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  110. result = s.connect_ex(('0.0.0.0', port))
  111. if result == 0:
  112. return True
  113. else:
  114. return False
  115. def vnc(uuid):
  116. host_url = request.host_url.rstrip('/')
  117. guest_url = host_url + url_for('api_guests.r_get', uuids=uuid)
  118. guest_ret = requests.get(url=guest_url)
  119. guest_ret = json.loads(guest_ret.content)
  120. port = random.randrange(50000, 60000)
  121. while True:
  122. if not port_is_opened(port=port):
  123. break
  124. port = random.randrange(50000, 60000)
  125. payload = {'listen_port': port, 'target_host': '103.47.139.194', 'target_port': guest_ret['data']['vnc_port']}
  126. q_ws.put(json.dumps(payload, ensure_ascii=False))
  127. q_ws.join()
  128. return render_template('vnc_lite.html', port=port, password=guest_ret['data']['vnc_password'])
  129. def detail(uuid):
  130. host_url = request.host_url.rstrip('/')
  131. guest_url = host_url + url_for('api_guests.r_get', uuids=uuid)
  132. guest_ret = requests.get(url=guest_url)
  133. guest_ret = json.loads(guest_ret.content)
  134. os_template_url = host_url + url_for('api_os_templates.r_get', ids=guest_ret['data']['os_template_id'].__str__())
  135. os_template_ret = requests.get(url=os_template_url)
  136. os_template_ret = json.loads(os_template_ret.content)
  137. return render_template('guest_detail.html', uuid=uuid, guest_ret=guest_ret, os_template_ret=os_template_ret)
  138. def success():
  139. return render_template('success.html', go_back_url='/guests', timeout=10000, title='提交成功',
  140. message_title='创建实例的请求已被接受',
  141. message='您所提交的资源正在创建中。根据所提交资源的大小,需要等待几到十几分钟。页面将在10秒钟后自动跳转到实例列表页面!')