utils.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from functools import wraps
  4. import socket
  5. import commands
  6. import jimit as ji
  7. import json
  8. import time
  9. from flask import make_response, g, request
  10. from flask.wrappers import Response
  11. from werkzeug.utils import import_string, cached_property
  12. import jwt
  13. from jimvc.models import app_config, logger, dev_table
  14. from database import Database as db
  15. from jimvc import app
  16. __author__ = 'James Iter'
  17. __date__ = '2017/03/01'
  18. __contact__ = 'james.iter.cn@gmail.com'
  19. __copyright__ = '(c) 2017 by James Iter.'
  20. class Utils(object):
  21. exit_flag = False
  22. thread_counter = 0
  23. @staticmethod
  24. def shell_cmd(cmd):
  25. try:
  26. exit_status, output = commands.getstatusoutput(cmd)
  27. return exit_status, str(output)
  28. except Exception as e:
  29. return -1, e.message
  30. @classmethod
  31. def signal_handle(cls, signum=0, frame=None):
  32. cls.exit_flag = True
  33. raise RuntimeError('Shutdown app!')
  34. @staticmethod
  35. def dumps2response(func):
  36. """
  37. 视图装饰器
  38. http://dormousehole.readthedocs.org/en/latest/patterns/viewdecorators.html
  39. """
  40. @wraps(func)
  41. def _dumps2response(*args, **kwargs):
  42. ret = func(*args, **kwargs)
  43. if func.func_name != 'r_before_request' and ret is None:
  44. ret = dict()
  45. ret['state'] = ji.Common.exchange_state(20000)
  46. if isinstance(ret, dict) and 'state' in ret:
  47. response = make_response()
  48. response.set_data(json.dumps(ret, ensure_ascii=False))
  49. response.status_code = int(ret['state']['code'])
  50. if 'redirect' in ret and request.args.get('auto_redirect', 'True') == 'True':
  51. response.status_code = int(ret['redirect'].get('code', ret['state']['code']))
  52. response.headers['location'] = ret['redirect'].get('location', request.host_url)
  53. # 参考链接:
  54. # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.autocorrect_location_header
  55. # 变量操纵位置 werkzeug/wrappers.py
  56. response.autocorrect_location_header = False
  57. return response
  58. if isinstance(ret, Response):
  59. return ret
  60. return _dumps2response
  61. @staticmethod
  62. def superuser(func):
  63. @wraps(func)
  64. def _superuser(*args, **kwargs):
  65. if not g.superuser:
  66. ret = dict()
  67. ret['state'] = ji.Common.exchange_state(40301)
  68. return ret
  69. return func(*args, **kwargs)
  70. return _superuser
  71. @staticmethod
  72. def generate_token(uid, ttl=app_config['token_ttl'], audience=None):
  73. payload = {
  74. 'iat': ji.Common.ts(), # 创建于
  75. 'nbf': ji.Common.ts(), # 在此之前不可用
  76. 'exp': ji.Common.ts() + ttl, # 过期时间
  77. 'uid': uid
  78. }
  79. if audience is not None:
  80. payload['aud'] = audience
  81. return jwt.encode(payload=payload, key=app_config['jwt_secret'], algorithm=app_config['jwt_algorithm'])
  82. @staticmethod
  83. def verify_token(token, audience=None):
  84. ret = dict()
  85. ret['state'] = ji.Common.exchange_state(20000)
  86. try:
  87. if audience is None:
  88. payload = jwt.decode(jwt=token, key=app_config['jwt_secret'], algorithms=app_config['jwt_algorithm'])
  89. else:
  90. payload = jwt.decode(jwt=token, key=app_config['jwt_secret'], algorithms=app_config['jwt_algorithm'],
  91. audience=audience)
  92. return payload
  93. except jwt.InvalidTokenError, e:
  94. logger.error(e.message)
  95. ret['state'] = ji.Common.exchange_state(41208)
  96. raise ji.JITError(json.dumps(ret))
  97. @staticmethod
  98. def emit_instruction(message):
  99. db.r.publish(app_config['instruction_channel'], message=message)
  100. @staticmethod
  101. def port_is_opened(port):
  102. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  103. result = s.connect_ex(('0.0.0.0', port))
  104. if result == 0:
  105. return True
  106. else:
  107. return False
  108. class LazyView(object):
  109. """
  110. 惰性载入视图
  111. http://dormousehole.readthedocs.org/en/latest/patterns/lazyloading.html
  112. """
  113. def __init__(self, import_name):
  114. self.__module__, self.__name__ = import_name.rsplit('.', 1)
  115. self.import_name = import_name
  116. @cached_property
  117. def view(self):
  118. return import_string(self.import_name)
  119. def __call__(self, *args, **kwargs):
  120. return self.view(*args, **kwargs)
  121. def add_rule_api(blueprint, rule, api_func=None, **options):
  122. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['jimvc.api.', api_func])), **options)
  123. def add_rule_views(blueprint, rule, views_func=None, **options):
  124. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['jimvc.views.', views_func])), **options)
  125. @app.context_processor
  126. def utility_processor():
  127. def format_price(amount, currency=u'¥'):
  128. return u'{0:.2f}{1}'.format(amount, currency)
  129. def format_datetime_by_ts(ts, fmt='%Y-%m-%d %H:%M'):
  130. return time.strftime(fmt, time.localtime(ts))
  131. def format_datetime_by_tus(tus, fmt='%y-%m-%d %H:%M'):
  132. return time.strftime(fmt, time.localtime(tus / 1000 / 1000))
  133. def format_guest_status(_status, progress):
  134. from jimvc.models import GuestState
  135. color = 'FF645B'
  136. icon = 'glyph-icon icon-bolt'
  137. desc = '未知状态'
  138. if _status == GuestState.booting.value:
  139. color = '00BBBB'
  140. icon = 'glyph-icon icon-circle'
  141. desc = '启动中'
  142. elif _status == GuestState.running.value:
  143. color = '00BB00'
  144. icon = 'glyph-icon icon-circle'
  145. desc = '运行中'
  146. elif _status == GuestState.creating.value:
  147. color = 'FFC543'
  148. icon = 'glyph-icon icon-spinner'
  149. desc = ' '.join(['创建中', str(progress) + '%'])
  150. elif _status == GuestState.blocked.value:
  151. color = '3D4245'
  152. icon = 'glyph-icon icon-minus-square'
  153. desc = '被阻塞'
  154. elif _status == GuestState.paused.value:
  155. color = 'B7B904'
  156. icon = 'glyph-icon icon-pause'
  157. desc = '暂停'
  158. elif _status == GuestState.shutdown.value:
  159. color = '4E5356'
  160. icon = 'glyph-icon icon-terminal'
  161. desc = '关闭'
  162. elif _status == GuestState.shutoff.value:
  163. color = 'FFC543'
  164. icon = 'glyph-icon icon-plug'
  165. desc = '断电'
  166. elif _status == GuestState.crashed.value:
  167. color = '9E2927'
  168. icon = 'glyph-icon icon-question'
  169. desc = '已崩溃'
  170. elif _status == GuestState.pm_suspended.value:
  171. color = 'FCFF07'
  172. icon = 'glyph-icon icon-anchor'
  173. desc = '悬挂'
  174. elif _status == GuestState.migrating.value:
  175. color = '1CF5E7'
  176. icon = 'glyph-icon icon-space-shuttle'
  177. desc = '迁移中'
  178. elif _status == GuestState.dirty.value:
  179. color = 'FF0707'
  180. icon = 'glyph-icon icon-remove'
  181. desc = '创建失败,待清理'
  182. else:
  183. pass
  184. return '<span class="{icon}" style="color: #{color};">&nbsp;&nbsp;{desc}</span>'.format(
  185. icon=icon, color=color, desc=desc)
  186. def format_sequence_to_device_name(sequence):
  187. # sequence 不能大于 25。dev_table 序数从 0 开始。
  188. if sequence == -1:
  189. return u'无'
  190. if sequence >= dev_table.__len__():
  191. return 'Unknown'
  192. return dev_table[sequence]
  193. def format_disk_state(state):
  194. from jimvc.models import DiskState
  195. color = 'FF645B'
  196. icon = 'glyph-icon icon-bolt'
  197. desc = '未知状态'
  198. if state == DiskState.pending.value:
  199. color = 'FFC543'
  200. icon = 'glyph-icon icon-spinner'
  201. desc = '创建中'
  202. elif state == DiskState.idle.value:
  203. color = '0077BB'
  204. icon = 'glyph-icon icon-unlink'
  205. desc = '待挂载'
  206. elif state == DiskState.mounted.value:
  207. color = '00BB00'
  208. icon = 'glyph-icon icon-link'
  209. desc = '使用中'
  210. elif state == DiskState.mounting.value:
  211. color = '00BBBB'
  212. icon = 'glyph-icon icon-elusive-upload'
  213. desc = '挂载中'
  214. elif state == DiskState.unloading.value:
  215. color = '93969B'
  216. icon = 'glyph-icon icon-elusive-download'
  217. desc = '卸载中'
  218. elif state == DiskState.dirty.value:
  219. color = 'FF0707'
  220. icon = 'glyph-icon icon-remove'
  221. desc = '创建失败,待清理'
  222. else:
  223. pass
  224. return '<span class="{icon}" style="color: #{color};">&nbsp;&nbsp;{desc}</span>'.format(
  225. icon=icon, color=color, desc=desc)
  226. return dict(format_price=format_price, format_datetime_by_tus=format_datetime_by_tus,
  227. format_datetime_by_ts=format_datetime_by_ts, format_guest_status=format_guest_status,
  228. format_sequence_to_device_name=format_sequence_to_device_name, format_disk_state=format_disk_state)