main.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __author__ = 'James Iter'
  4. __date__ = '2018/9/30'
  5. __contact__ = 'james.iter.cn@gmail.com'
  6. __copyright__ = '(c) 2018 by James Iter.'
  7. import traceback
  8. import signal
  9. import time
  10. import os
  11. import threading
  12. from jimvc.models import app_config, logger
  13. from jimvc.models import EventProcessor, Init
  14. from jimvc.models import Utils
  15. from jimvc import app
  16. from jimvc import ws_engine_for_vnc
  17. threads = []
  18. # noinspection PyBroadException
  19. try:
  20. signal.signal(signal.SIGTERM, Utils.signal_handle)
  21. signal.signal(signal.SIGINT, Utils.signal_handle)
  22. pid = os.fork()
  23. if pid == 0:
  24. ws_engine_for_vnc()
  25. else:
  26. # 父进程退出时,会清理所有提前退出的子进程的环境。所以这里无需对子进程做等待操作。
  27. # 即:即使子进程提前退出,且因父进程没有做wait处理,使其变成了僵尸进程。但当父进程退出时,会对因其所产生的僵尸进程做统一清理操作。
  28. from jimvc.models import Database as db
  29. if db.r.hincrby(app.config['global_lock'], 'EventProcessor') == 1:
  30. # 避免该进程奔溃,重启后无法再次启动如下线程。故对该 key 设定 10 秒生存周期。
  31. # 即 10 秒钟后奔溃,被 gunicorn 重启后的进程,依然可以启动如下线程。
  32. db.r.expire(app.config['global_lock'], 10)
  33. t_ = threading.Thread(target=EventProcessor.launch, args=())
  34. threads.append(t_)
  35. t_ = threading.Thread(target=Init.clear_expire_monitor_log, args=())
  36. threads.append(t_)
  37. t_ = threading.Thread(target=Init.pub_sub_ping_pong, args=())
  38. threads.append(t_)
  39. for t in threads:
  40. t.start()
  41. except:
  42. logger.error(traceback.format_exc())
  43. exit(-1)
  44. if __name__ == '__main__':
  45. # noinspection PyBroadException
  46. try:
  47. app.run(host=app_config['listen'], port=app_config['port'], use_reloader=False, threaded=True)
  48. while True:
  49. if Utils.exit_flag:
  50. # 主线程即将结束
  51. break
  52. time.sleep(1)
  53. # 等待子线程结束
  54. for t in threads:
  55. t.join()
  56. print 'Main say bye-bye!'
  57. except:
  58. logger.error(traceback.format_exc())
  59. exit(-1)