LAS.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #!/usr/bin/env python3.9
  2. from threading import Thread
  3. import configparser
  4. import os
  5. import time
  6. import traceback
  7. import sys
  8. import json
  9. import common.sys_comm as sys_comm
  10. from common.sys_comm import (
  11. LOGDBG, LOGINFO, LOGWARN, LOGERR, EC,
  12. get_utc_time_ms
  13. )
  14. from mqtt import mqtt_process
  15. from mqtt.mqtt_process import MQTTClientThread, MQTTConsumerThread, mqtt_client, mqtt_consumer
  16. import db.db_process as db_process
  17. from db.db_process import db_req_que
  18. from db.db_process import DBRequest_Async
  19. from db.db_process import (db_execute_sync, db_execute_async)
  20. import db.db_sqls as sqls
  21. import device.dev_mng as g_Dev
  22. from device.dev_mng import (
  23. Device, g_dev_mgr, init_dev_mng
  24. )
  25. import core.alarm_plan_manager as ap_mgr
  26. from core.alarm_plan_manager import (
  27. AlarmPlanManager,
  28. init_alarm_plan_mgr,
  29. start_alarm_plan_mgr,
  30. cb_handle_query_all_alarm_plan_info
  31. )
  32. from core.alarm_plan_dispatcher import (
  33. init_alarm_plan_disp,
  34. start_alarm_plan_dispatcher
  35. )
  36. import core.g_LAS as g_las
  37. # 系统初始化
  38. def sys_init():
  39. try:
  40. # 创建日志目录
  41. if not os.path.exists("./log/"):
  42. os.makedirs("./log/")
  43. print("create log dir succeed !")
  44. LOGDBG(f" ================ system init ...")
  45. print(f" ================ system init ...")
  46. # 读取配置文件
  47. config = configparser.ConfigParser()
  48. with open('./conf.ini', 'r', encoding='utf-8') as f:
  49. config.read_file(f)
  50. if not (config.has_option('conf', 'module_name') and
  51. config.has_option('conf', 'platform') and
  52. config.has_option('conf', 'db_host') and
  53. config.has_option('conf', 'log_lvl') and
  54. config.has_option('conf', 'max_log_files') and
  55. config.has_option('conf', 'max_log_files')):
  56. LOGDBG("sys_init failed, invalid conf.ini param")
  57. return 0
  58. if not (config.has_option('conf', 'db_host')):
  59. LOGDBG("sys_init failed, invalid db param")
  60. return 0
  61. if not (config.has_option('linux', 'host_ip') and
  62. config.has_option('windows', 'host_ip') and
  63. config.has_option('windows', 'server_ip') and
  64. config.has_option('windows', 'ssh_host') and
  65. config.has_option('windows', 'ssh_port')):
  66. LOGDBG("sys_init failed, invalid host_ip param")
  67. return 0
  68. LOGDBG("read conf.ini succeed !")
  69. # 初始化日志配置
  70. with sys_comm.g_log_conf_mtx:
  71. sys_comm.g_log_conf["module_name"] = str(config["conf"]["module_name"])
  72. sys_comm.g_log_conf["log_lvl"] = int(config["conf"]["log_lvl"])
  73. sys_comm.g_log_conf["max_log_size"] = int(config["conf"]["max_log_size"]) * 1024 * 1024
  74. sys_comm.g_log_conf["max_log_files"] = int(config["conf"]["max_log_files"])
  75. LOGDBG("log init succeed")
  76. # 初始化系统配置
  77. with sys_comm.g_sys_conf_mtx:
  78. sys_comm.g_sys_conf["module_name"] = str(config["conf"]["module_name"])
  79. sys_comm.g_sys_conf["platform"] = int(config["conf"]["platform"])
  80. sys_comm.g_sys_conf["db_host"] = str(config["conf"]["db_host"])
  81. sys_comm.g_sys_conf["log_lvl"] = int(config["conf"]["log_lvl"])
  82. sys_comm.g_sys_conf["max_log_size"] = int(config["conf"]["max_log_size"]) * 1024 * 1024
  83. sys_comm.g_sys_conf["max_log_files"] = int(config["conf"]["max_log_files"])
  84. # windows 本地
  85. if sys_comm.g_sys_conf["platform"] == 0:
  86. sys_comm.g_sys_conf["host_ip"] = str(config["windows"]["host_ip"])
  87. sys_comm.g_sys_conf["server_ip"] = str(config["windows"]["server_ip"])
  88. sys_comm.g_sys_conf["ssh_host"] = str(config["windows"]["ssh_host"])
  89. sys_comm.g_sys_conf["ssh_port"] = int(config["windows"]["ssh_port"])
  90. mqtt_process.MQTT_BROKER = sys_comm.g_sys_conf["server_ip"]
  91. # linux 服务器
  92. elif sys_comm.g_sys_conf["platform"] == 1:
  93. sys_comm.g_sys_conf["host_ip"] = str(config["linux"]["host_ip"])
  94. mqtt_process.MQTT_BROKER = sys_comm.g_sys_conf["host_ip"]
  95. sys_comm.g_sys_conf["sp_id"] = int(get_utc_time_ms())
  96. # 报警配置
  97. sys_comm.g_sys_conf["alarm_conf"] = sys_comm.alarm_conf
  98. # 启动成功,打印系统信息
  99. module_name = sys_comm.g_sys_conf["module_name"]
  100. platform = sys_comm.g_sys_conf["platform"]
  101. host_ip = sys_comm.g_sys_conf["host_ip"]
  102. max_log_files = sys_comm.g_sys_conf["max_log_files"]
  103. max_log_size = sys_comm.g_sys_conf["max_log_size"]
  104. log_lvl = sys_comm.g_sys_conf["log_lvl"]
  105. sp_id = sys_comm.g_sys_conf["sp_id"]
  106. print(f" ================ system init succeed !")
  107. print(f" ================ module : {module_name}")
  108. print(f" ================ platform : {platform}")
  109. print(f" ================ host_ip : {host_ip}")
  110. print(f" ================ max_log_files : {max_log_files}")
  111. print(f" ================ max_log_size : {max_log_size}")
  112. print(f" ================ log_lvl : {log_lvl}")
  113. print(f" ================ sp_id : {sp_id}")
  114. print(f" ================ version : v B1.0")
  115. LOGINFO(f" ================ system init succeed !")
  116. LOGINFO(f" ================ module : {module_name}")
  117. LOGINFO(f" ================ platform : {platform}")
  118. LOGINFO(f" ================ host_ip : {host_ip}")
  119. LOGINFO(f" ================ max_log_files : {max_log_files}")
  120. LOGINFO(f" ================ max_log_size : {max_log_size}")
  121. LOGINFO(f" ================ log_lvl : {log_lvl}")
  122. LOGINFO(f" ================ sp_id : {sp_id}")
  123. LOGINFO(f" ================ version : v B1.0")
  124. return 0
  125. except json.JSONDecodeError as e:
  126. tb_info = traceback.extract_tb(e.__traceback__)
  127. for frame in tb_info:
  128. LOGERR(f"[{frame.filename}:{frame.lineno}] @{frame.name}(), error:{e}, {e.doc}")
  129. return EC.EC_FAILED
  130. except Exception as e:
  131. tb_info = traceback.extract_tb(e.__traceback__)
  132. for frame in tb_info:
  133. LOGERR(f"[{frame.filename}:{frame.lineno}] @{frame.name}(), error: {e}")
  134. return EC.EC_FAILED
  135. # 轮循执行一些任务
  136. def run():
  137. # 轮循处理任务
  138. while True:
  139. time.sleep(1)
  140. def query_events_expire_range():
  141. event_save_range = 90
  142. try:
  143. result = db_execute_sync(sql=sqls.sql_event_save_range, timeout=15)
  144. if result and len(result) == 1:
  145. row = result[0]
  146. param_value = row.get("param_value")
  147. if param_value is not None: # 只要不是 None,就用数据库的值
  148. event_save_range = param_value
  149. else:
  150. LOGWARN("found invalid event_save_range, use default 90")
  151. return event_save_range
  152. except Exception as e:
  153. LOGERR(f"query event_save_range failed: {e}, use default 90")
  154. return EC.EC_FAILED
  155. # 创建事件过期计划
  156. def create_events_expire_plan():
  157. event_save_range = query_events_expire_range()
  158. if not event_save_range:
  159. return EC.EC_FAILED
  160. g_las.g_alarm_plan_mgr.create_clean_expire_events_task(event_save_range)
  161. return 0
  162. # 主线程
  163. def main_process():
  164. if not g_las.g_alarm_plan_mgr:
  165. LOGERR(f"error: g_alarm_plan_mgr not init")
  166. return EC.EC_FAILED
  167. if not g_las.g_alarm_plan_disp:
  168. LOGERR(f"error: g_alarm_plan_disp not init")
  169. return EC.EC_FAILED
  170. # 查询所有设备信息
  171. db_req_que.put(DBRequest_Async(sql=sqls.sql_query_all_dev_info,
  172. callback=g_Dev.g_dev_mgr.cb_handle_query_all_dev_info))
  173. # 查询所有告警计划
  174. db_req_que.put(DBRequest_Async(sql=sqls.sql_query_all_alarm_plan,
  175. callback=cb_handle_query_all_alarm_plan_info))
  176. # 创建任务:创建事件过期计划
  177. iRet = create_events_expire_plan()
  178. if iRet:
  179. LOGERR(f"create_events_expire_plan failed, process termination")
  180. return iRet
  181. # 轮循任务
  182. run()
  183. def main():
  184. # 初始化
  185. if (0 != sys_init()):
  186. sys.exit(EC.EC_FAILED)
  187. # 初始化 dev_mng
  188. init_dev_mng()
  189. g_Dev.g_dev_mgr.start()
  190. # 初始化LAS
  191. init_alarm_plan_mgr()
  192. init_alarm_plan_disp()
  193. start_alarm_plan_dispatcher() # 事件分发器
  194. start_alarm_plan_mgr() # 告警计划管理器
  195. # 数据库线程
  196. db_thread = db_process.create_db_process()
  197. db_thread.start()
  198. # MQTT 消息线程
  199. mqtt_client = MQTTClientThread()
  200. mqtt_client.start()
  201. mqtt_consumer = MQTTConsumerThread()
  202. mqtt_consumer.start()
  203. # 主线程
  204. if not main_process():
  205. LOGERR(f"main_process error, process termination")
  206. sys.exit(EC.EC_FAILED)
  207. main()