utils.py 8.7 KB

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