utils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from functools import wraps
  4. import commands
  5. from flask import make_response, g, request
  6. from flask.wrappers import Response
  7. from werkzeug.utils import import_string, cached_property
  8. import jwt
  9. from models.initialize import *
  10. from database import Database as db
  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. @staticmethod
  93. def emit_instruction(message):
  94. db.r.publish(app.config['instruction_channel'], message=message)
  95. class LazyView(object):
  96. """
  97. 惰性载入视图
  98. http://dormousehole.readthedocs.org/en/latest/patterns/lazyloading.html
  99. """
  100. def __init__(self, import_name):
  101. self.__module__, self.__name__ = import_name.rsplit('.', 1)
  102. self.import_name = import_name
  103. @cached_property
  104. def view(self):
  105. return import_string(self.import_name)
  106. def __call__(self, *args, **kwargs):
  107. return self.view(*args, **kwargs)
  108. def add_rule_api(blueprint, rule, api_func=None, **options):
  109. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['api.', api_func])), **options)
  110. def add_rule_views(blueprint, rule, views_func=None, **options):
  111. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['views.', views_func])), **options)
  112. @app.context_processor
  113. def utility_processor():
  114. def format_price(amount, currency=u'¥'):
  115. return u'{0:.2f}{1}'.format(amount, currency)
  116. def format_datetime_by_ts(ts, fmt='%Y-%m-%d %H:%M'):
  117. return time.strftime(fmt, time.localtime(ts))
  118. def format_datetime_by_tus(tus, fmt='%y-%m-%d %H:%M'):
  119. return time.strftime(fmt, time.localtime(tus/1000/1000))
  120. def format_guest_status(_status, progress):
  121. from status import GuestState
  122. color = 'FF645B'
  123. icon = 'glyph-icon icon-bolt'
  124. desc = '未知状态'
  125. if _status == GuestState.running.value:
  126. color = '00BB00'
  127. icon = 'glyph-icon icon-circle'
  128. desc = '运行中'
  129. elif _status in [GuestState.no_state.value, GuestState.creating.value]:
  130. color = 'FFC543'
  131. icon = 'glyph-icon icon-spinner'
  132. desc = ' '.join(['创建中', str(progress)+'%'])
  133. elif _status == GuestState.blocked.value:
  134. color = '3D4245'
  135. icon = 'glyph-icon icon-minus-square'
  136. desc = '被阻塞'
  137. elif _status == GuestState.paused.value:
  138. color = 'B7B904'
  139. icon = 'glyph-icon icon-pause'
  140. desc = '暂停'
  141. elif _status == GuestState.shutdown.value:
  142. color = '4E5356'
  143. icon = 'glyph-icon icon-terminal'
  144. desc = '关闭'
  145. elif _status == GuestState.shutoff.value:
  146. color = 'FFC543'
  147. icon = 'glyph-icon icon-plug'
  148. desc = '断电'
  149. elif _status == GuestState.crashed.value:
  150. color = '9E2927'
  151. icon = 'glyph-icon icon-question'
  152. desc = '已崩溃'
  153. elif _status == GuestState.pm_suspended.value:
  154. color = 'FCFF07'
  155. icon = 'glyph-icon icon-anchor'
  156. desc = '悬挂'
  157. elif _status == GuestState.migrating.value:
  158. color = '1CF5E7'
  159. icon = 'glyph-icon icon-space-shuttle'
  160. desc = '迁移中'
  161. elif _status == GuestState.dirty.value:
  162. color = 'FF0707'
  163. icon = 'glyph-icon icon-remove'
  164. desc = '创建失败,待清理'
  165. else:
  166. pass
  167. return '<span class="{icon}" style="color: #{color};">&nbsp;&nbsp;{desc}</span>'.format(
  168. icon=icon, color=color, desc=desc)
  169. def format_sequence_to_device_name(sequence):
  170. # sequence 不能大于 25。dev_table 序数从 0 开始。
  171. if sequence == -1:
  172. return u'无'
  173. if sequence >= dev_table.__len__():
  174. return 'Unknown'
  175. return dev_table[sequence]
  176. def format_disk_state(state):
  177. from status import DiskState
  178. color = 'FF645B'
  179. icon = 'glyph-icon icon-bolt'
  180. desc = '未知状态'
  181. if state == DiskState.pending.value:
  182. color = 'FFC543'
  183. icon = 'glyph-icon icon-spinner'
  184. desc = '创建中'
  185. elif state == DiskState.idle.value:
  186. color = '0077BB'
  187. icon = 'glyph-icon icon-unlink'
  188. desc = '待挂载'
  189. elif state == DiskState.mounted.value:
  190. color = '00BB00'
  191. icon = 'glyph-icon icon-link'
  192. desc = '使用中'
  193. elif state == DiskState.mounting.value:
  194. color = '00BBBB'
  195. icon = 'glyph-icon icon-elusive-upload'
  196. desc = '挂载中'
  197. elif state == DiskState.unloading.value:
  198. color = '93969B'
  199. icon = 'glyph-icon icon-elusive-download'
  200. desc = '卸载中'
  201. elif state == DiskState.dirty.value:
  202. color = 'FF0707'
  203. icon = 'glyph-icon icon-remove'
  204. desc = '创建失败,待清理'
  205. else:
  206. pass
  207. return '<span class="{icon}" style="color: #{color};">&nbsp;&nbsp;{desc}</span>'.format(
  208. icon=icon, color=color, desc=desc)
  209. return dict(format_price=format_price, format_datetime_by_tus=format_datetime_by_tus,
  210. format_datetime_by_ts=format_datetime_by_ts, format_guest_status=format_guest_status,
  211. format_sequence_to_device_name=format_sequence_to_device_name, format_disk_state=format_disk_state)