utils.py 9.3 KB

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