initialize.py 4.7 KB

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