utils.py 8.3 KB

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