initialize.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. }
  27. @classmethod
  28. def load_config(cls):
  29. def usage():
  30. print "Usage:%s [-c] [--config]" % sys.argv[0]
  31. opts = None
  32. try:
  33. opts, args = getopt.getopt(sys.argv[1:], 'hc:',
  34. ['help', 'config='])
  35. except getopt.GetoptError as e:
  36. print str(e)
  37. usage()
  38. exit(e.message.__len__())
  39. for k, v in opts:
  40. if k in ("-h", "--help"):
  41. usage()
  42. exit()
  43. elif k in ("-c", "--config"):
  44. cls.config['config_file'] = v
  45. else:
  46. print "unhandled option"
  47. if not os.path.isfile(cls.config['config_file']):
  48. raise PathNotExist(u'配置文件不存在, 请配置 --> ', cls.config['config_file'])
  49. with open(cls.config['config_file'], 'r') as f:
  50. cls.config.update(json.load(f))
  51. return cls.config
  52. @classmethod
  53. def init_logger(cls):
  54. cls.config['log_file_base'] = '/'.join([sys.path[0], cls.config['log_file_dir'], 'log'])
  55. log_dir = os.path.dirname(cls.config['log_file_base'])
  56. if not os.path.isdir(log_dir):
  57. os.makedirs(log_dir, 0755)
  58. process_title = 'JimV-C'
  59. log_file_path = '.'.join([cls.config['log_file_base'], process_title])
  60. _logger = logging.getLogger(log_file_path)
  61. if cls.config['debug']:
  62. cls.config['DEBUG'] = True
  63. _logger.setLevel(logging.DEBUG)
  64. else:
  65. cls.config['DEBUG'] = False
  66. _logger.setLevel(logging.INFO)
  67. fh = TimedRotatingFileHandler(log_file_path, when=cls.config['log_cycle'], interval=1, backupCount=7)
  68. formatter = logging.Formatter(
  69. '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(lineno)s - %(message)s')
  70. fh.setFormatter(formatter)
  71. _logger.addHandler(fh)
  72. return _logger
  73. @staticmethod
  74. def pub_sub_ping_pong():
  75. from models import Database as db
  76. from models import Utils
  77. while True:
  78. if Utils.exit_flag:
  79. print 'Thread pub_sub_ping_pong say bye-bye'
  80. return
  81. time.sleep(10)
  82. db.r.publish(app.config['instruction_channel'], message=json.dumps({'action': 'ping'}))
  83. q_ws = JoinableQueue()
  84. # 预编译效率更高
  85. regex_sql_str = re.compile('\\\+"')
  86. regex_dsl_str = re.compile('^\w+:\w+:[\S| ]+$')
  87. config = Init.load_config()
  88. logger = Init.init_logger()
  89. app.config = dict(app.config, **config)
  90. ji.index_state['branch'] = dict(ji.index_state['branch'], **own_state_branch)
  91. # sequence_device_node_mapping = ['vda', 'vdb', 'vdc', 'vdd']
  92. dev_table = list()
  93. for i in range(26):
  94. dev_table.append('vd' + chr(97 + i))