utils.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. __author__ = 'James Iter'
  11. __date__ = '2017/03/01'
  12. __contact__ = 'james.iter.cn@gmail.com'
  13. __copyright__ = '(c) 2017 by James Iter.'
  14. class Utils(object):
  15. exit_flag = False
  16. thread_counter = 0
  17. @staticmethod
  18. def shell_cmd(cmd):
  19. try:
  20. exit_status, output = commands.getstatusoutput(cmd)
  21. return exit_status, str(output)
  22. except Exception as e:
  23. return -1, e.message
  24. @classmethod
  25. def signal_handle(cls, signum=0, frame=None):
  26. cls.exit_flag = True
  27. raise RuntimeError('Shutdown app!')
  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, ttl=app.config['token_ttl'], audience=None):
  67. payload = {
  68. 'iat': ji.Common.ts(), # 创建于
  69. 'nbf': ji.Common.ts(), # 在此之前不可用
  70. 'exp': ji.Common.ts() + ttl, # 过期时间
  71. 'uid': uid
  72. }
  73. if audience is not None:
  74. payload['aud'] = audience
  75. return jwt.encode(payload=payload, key=app.config['jwt_secret'], algorithm=app.config['jwt_algorithm'])
  76. @staticmethod
  77. def verify_token(token, audience=None):
  78. ret = dict()
  79. ret['state'] = ji.Common.exchange_state(20000)
  80. try:
  81. if audience is None:
  82. payload = jwt.decode(jwt=token, key=app.config['jwt_secret'], algorithms=app.config['jwt_algorithm'])
  83. else:
  84. payload = jwt.decode(jwt=token, key=app.config['jwt_secret'], algorithms=app.config['jwt_algorithm'],
  85. audience=audience)
  86. return payload
  87. except jwt.InvalidTokenError, e:
  88. logger.error(e.message)
  89. ret['state'] = ji.Common.exchange_state(41208)
  90. raise ji.JITError(json.dumps(ret))
  91. class LazyView(object):
  92. """
  93. 惰性载入视图
  94. http://dormousehole.readthedocs.org/en/latest/patterns/lazyloading.html
  95. """
  96. def __init__(self, import_name):
  97. self.__module__, self.__name__ = import_name.rsplit('.', 1)
  98. self.import_name = import_name
  99. @cached_property
  100. def view(self):
  101. return import_string(self.import_name)
  102. def __call__(self, *args, **kwargs):
  103. return self.view(*args, **kwargs)
  104. def add_rule_api(blueprint, rule, api_func=None, **options):
  105. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['api.', api_func])), **options)
  106. def add_rule_views(blueprint, rule, views_func=None, **options):
  107. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['views.', views_func])), **options)
  108. @app.context_processor
  109. def utility_processor():
  110. def format_price(amount, currency=u'¥'):
  111. return u'{0:.2f}{1}'.format(amount, currency)
  112. def format_datetime_by_ts(ts, fmt='%Y-%m-%d %H:%M'):
  113. return time.strftime(fmt, time.localtime(ts))
  114. def format_datetime_by_tus(tus, fmt='%y-%m-%d %H:%M'):
  115. return time.strftime(fmt, time.localtime(tus/1000/1000))
  116. def format_guest_status(_status, progress):
  117. from status import GuestState
  118. color = 'FF645B'
  119. icon = 'glyph-icon icon-bolt'
  120. desc = '未知状态'
  121. if _status == GuestState.running.value:
  122. color = '00BB00'
  123. icon = 'glyph-icon icon-circle'
  124. desc = '运行中'
  125. elif _status in [GuestState.no_state.value, GuestState.creating.value]:
  126. color = 'FFC543'
  127. icon = 'glyph-icon icon-spinner'
  128. desc = ' '.join(['创建中', str(progress)+'%'])
  129. elif _status == GuestState.blocked.value:
  130. color = '3D4245'
  131. icon = 'glyph-icon icon-minus-square'
  132. desc = '被阻塞'
  133. elif _status == GuestState.paused.value:
  134. color = 'B7B904'
  135. icon = 'glyph-icon icon-pause'
  136. desc = '暂停'
  137. elif _status == GuestState.shutdown.value:
  138. color = '4E5356'
  139. icon = 'glyph-icon icon-terminal'
  140. desc = '关闭'
  141. elif _status == GuestState.shutoff.value:
  142. color = 'FFC543'
  143. icon = 'glyph-icon icon-plug'
  144. desc = '断电'
  145. elif _status == GuestState.crashed.value:
  146. color = '9E2927'
  147. icon = 'glyph-icon icon-question'
  148. desc = '已崩溃'
  149. elif _status == GuestState.pm_suspended.value:
  150. color = 'FCFF07'
  151. icon = 'glyph-icon icon-anchor'
  152. desc = '悬挂'
  153. elif _status == GuestState.migrating.value:
  154. color = '1CF5E7'
  155. icon = 'glyph-icon icon-space-shuttle'
  156. desc = '迁移中'
  157. elif _status == GuestState.dirty.value:
  158. color = 'FF0707'
  159. icon = 'glyph-icon icon-remove'
  160. desc = '创建失败,待清理'
  161. else:
  162. pass
  163. return '<span class="{icon}" style="color: #{color};">&nbsp;&nbsp;{desc}</span>'.format(
  164. icon=icon, color=color, desc=desc)
  165. def format_sequence_to_device_name(sequence):
  166. # sequence 不能大于 25。dev_table 序数从 0 开始。
  167. if sequence == -1:
  168. return u'无'
  169. if sequence >= dev_table.__len__():
  170. return 'Unknown'
  171. return dev_table[sequence]
  172. def format_disk_state(state):
  173. from status import DiskState
  174. color = 'FF645B'
  175. icon = 'glyph-icon icon-bolt'
  176. desc = '未知状态'
  177. if state == DiskState.pending.value:
  178. color = 'FFC543'
  179. icon = 'glyph-icon icon-spinner'
  180. desc = '创建中'
  181. elif state == DiskState.idle.value:
  182. color = '0077BB'
  183. icon = 'glyph-icon icon-unlink'
  184. desc = '待挂载'
  185. elif state == DiskState.mounted.value:
  186. color = '00BB00'
  187. icon = 'glyph-icon icon-link'
  188. desc = '使用中'
  189. elif state == DiskState.mounting.value:
  190. color = '00BBBB'
  191. icon = 'glyph-icon icon-elusive-upload'
  192. desc = '挂载中'
  193. elif state == DiskState.unloading.value:
  194. color = '93969B'
  195. icon = 'glyph-icon icon-elusive-download'
  196. desc = '卸载中'
  197. elif state == DiskState.dirty.value:
  198. color = 'FF0707'
  199. icon = 'glyph-icon icon-remove'
  200. desc = '创建失败,待清理'
  201. else:
  202. pass
  203. return '<span class="{icon}" style="color: #{color};">&nbsp;&nbsp;{desc}</span>'.format(
  204. icon=icon, color=color, desc=desc)
  205. def format_os_type_id_to_name(os_type):
  206. from models import OSType
  207. if os_type == OSType.linux.value:
  208. return u'Linux'
  209. elif os_type == OSType.windows.value:
  210. return u'Windows'
  211. elif os_type == OSType.bsd.value:
  212. return u'BSD'
  213. elif os_type == OSType.aix.value:
  214. return u'AIX'
  215. elif os_type == OSType.hp_unix.value:
  216. return u'HP-UNIX'
  217. elif os_type == OSType.unknown.value:
  218. return u'Unknown'
  219. else:
  220. return u'Unknown'
  221. return dict(format_price=format_price, format_datetime_by_tus=format_datetime_by_tus,
  222. format_datetime_by_ts=format_datetime_by_ts, format_guest_status=format_guest_status,
  223. format_sequence_to_device_name=format_sequence_to_device_name, format_disk_state=format_disk_state,
  224. format_os_type_id_to_name=format_os_type_id_to_name)