monitor.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # time: 2024/4/11 9:07
  4. # file: monitor.py
  5. # author: David
  6. # company: shenyang JY
  7. import json
  8. import os
  9. import subprocess
  10. from pathlib import Path
  11. script_path = str(Path.cwd().resolve().parent.parent.parent / 'bin' / 'restart-forecast.sh')
  12. config_folder = Path.cwd().resolve().parent
  13. class Monitor(object):
  14. def __init__(self, logger, args):
  15. self.args = args
  16. self.logger = logger
  17. def update_config(self):
  18. files = list(config_folder.rglob("ModelCDQ_*"))
  19. files.sort(key=lambda x: (str(x)[str(x).index("ModelCDQ_")+9:-1]))
  20. if len(files) > 0:
  21. try:
  22. opt = vars(self.args.parse_args_and_yaml())
  23. file = files[-1]
  24. with open(file, 'r', encoding='utf-8') as f:
  25. lines = f.readlines() # 读取第一行参数
  26. if "ModelCDQ" in lines[0].strip():
  27. content = lines[0].strip()
  28. else:
  29. content = lines[1].strip()
  30. content = eval(content[content.index("ModelCDQ")+11:])
  31. content = content[0]['str']
  32. update_opt = json.loads(content)
  33. for key, value in update_opt.items():
  34. opt[key] = value
  35. print("key:", key, "value:", value)
  36. self.logger.info("下发配置文件,更新后的参数为:{}".format(opt))
  37. self.args.save_args_yml(opt, isdict=True)
  38. self.delete_file(files)
  39. if opt['reset_sys'] is True:
  40. self.logger.info("-----重启超短期算法包-----")
  41. subprocess.run(["sh", script_path])
  42. except Exception as e:
  43. self.logger.critical("超短期monitor任务出错:{}".format(e.args))
  44. self.delete_file(files)
  45. def delete_file(self, files):
  46. for filename in files:
  47. if os.path.exists(filename):
  48. os.remove(filename)
  49. self.logger.info(f"文件 {filename} 删除成功!")
  50. else:
  51. self.logger.info(f"文件 {filename} 不存在。")
  52. if __name__ == '__main__':
  53. from config import myargparse
  54. from logs import Log
  55. args = myargparse(discription="场站端配置", add_help=False)
  56. log = Log()
  57. mo = Monitor(log.logger, args)
  58. mo.update_config()