initialize.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from multiprocessing import JoinableQueue
  4. from flask import Flask
  5. import logging
  6. from logging.handlers import TimedRotatingFileHandler
  7. import json
  8. import os
  9. import sys
  10. import re
  11. import getopt
  12. import jimit as ji
  13. import time
  14. from jimvc_exception import PathNotExist
  15. from state_code import own_state_branch
  16. reload(sys)
  17. sys.setdefaultencoding('utf8')
  18. __author__ = 'James Iter'
  19. __date__ = '2017/3/21'
  20. __contact__ = 'james.iter.cn@gmail.com'
  21. __copyright__ = '(c) 2017 by James Iter.'
  22. app = Flask(__name__, template_folder='../templates', static_folder='../static')
  23. class Init(object):
  24. config = {
  25. 'config_file': '/etc/jimvc.conf',
  26. 'log_cycle': 'D',
  27. 'instruction_channel': 'C:Instruction',
  28. 'ip_available_set': 'S:IP:Available',
  29. 'ip_used_set': 'S:IP:Used',
  30. 'vnc_port_available_set': 'S:VNCPort:Available',
  31. 'vnc_port_used_set': 'S:VNCPort:Used',
  32. 'downstream_queue': 'Q:Downstream',
  33. 'upstream_queue': 'Q:Upstream',
  34. 'hosts_info': 'H:HostsInfo',
  35. 'guest_boot_jobs': 'S:GuestBootJobs',
  36. 'guest_boot_jobs_wait_time': 600,
  37. 'db_charset': 'utf8',
  38. 'db_pool_size': 10,
  39. 'DEBUG': False,
  40. 'jwt_algorithm': 'HS512',
  41. 'token_ttl': 604800,
  42. 'SESSION_TYPE': 'filesystem',
  43. 'SESSION_PERMANENT': True,
  44. 'SESSION_USE_SIGNER': True,
  45. 'SESSION_FILE_DIR': '/tmp/jimv',
  46. 'SESSION_FILE_THRESHOLD': 5000,
  47. 'SESSION_COOKIE_NAME': 'sid',
  48. 'SESSION_COOKIE_SECURE': False,
  49. 'PERMANENT_SESSION_LIFETIME': 604800
  50. }
  51. @classmethod
  52. def load_config(cls):
  53. def usage():
  54. print "Usage:%s [-c] [--config]" % sys.argv[0]
  55. opts = None
  56. try:
  57. opts, args = getopt.getopt(sys.argv[1:], 'hc:',
  58. ['help', 'config='])
  59. except getopt.GetoptError as e:
  60. print str(e)
  61. usage()
  62. exit(e.message.__len__())
  63. for k, v in opts:
  64. if k in ("-h", "--help"):
  65. usage()
  66. exit()
  67. elif k in ("-c", "--config"):
  68. cls.config['config_file'] = v
  69. else:
  70. print "unhandled option"
  71. if not os.path.isfile(cls.config['config_file']):
  72. raise PathNotExist(u'配置文件不存在, 请配置 --> ', cls.config['config_file'])
  73. with open(cls.config['config_file'], 'r') as f:
  74. cls.config.update(json.load(f))
  75. return cls.config
  76. @classmethod
  77. def init_logger(cls):
  78. log_dir = os.path.dirname(cls.config['log_file_path'])
  79. if not os.path.isdir(log_dir):
  80. os.makedirs(log_dir, 0755)
  81. _logger = logging.getLogger(cls.config['log_file_path'])
  82. if cls.config['DEBUG']:
  83. _logger.setLevel(logging.DEBUG)
  84. else:
  85. _logger.setLevel(logging.INFO)
  86. fh = TimedRotatingFileHandler(cls.config['log_file_path'], when=cls.config['log_cycle'],
  87. interval=1, backupCount=7)
  88. formatter = logging.Formatter(
  89. '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(lineno)s - %(message)s')
  90. fh.setFormatter(formatter)
  91. _logger.addHandler(fh)
  92. return _logger
  93. @staticmethod
  94. def pub_sub_ping_pong():
  95. from models import Database as db
  96. from models import Utils
  97. while True:
  98. if Utils.exit_flag:
  99. print 'Thread pub_sub_ping_pong say bye-bye'
  100. return
  101. time.sleep(10)
  102. db.r.publish(app.config['instruction_channel'], message=json.dumps({'action': 'ping'}))
  103. q_ws = JoinableQueue()
  104. # 预编译效率更高
  105. regex_sql_str = re.compile('\\\+"')
  106. regex_dsl_str = re.compile('^\w+:\w+:[\S| ]+$')
  107. config = Init.load_config()
  108. logger = Init.init_logger()
  109. app.config = dict(app.config, **config)
  110. ji.index_state['branch'] = dict(ji.index_state['branch'], **own_state_branch)
  111. # sequence_device_node_mapping = ['vda', 'vdb', 'vdc', 'vdd']
  112. dev_table = list()
  113. for i in range(26):
  114. dev_table.append('vd' + chr(97 + i))
  115. app.jinja_env.add_extension('jinja2.ext.loopcontrols')