monitor_process.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import logging
  2. import os
  3. import re
  4. import psutil
  5. convert_port_list = ["15010"]
  6. # ocr_port_list = ["15011", "15013", "15015"]
  7. ocr_port_list = ["15011", "15013"]
  8. otr_port_list = ["15012", "15014"]
  9. soffice_port_list = ["16000", "16001", "16002", "16003"]
  10. python_path = "/home/python/anaconda3/envs/convert/bin/python"
  11. interface_path = "/data/fangjiasheng/format_conversion_maxcompute"
  12. std_out = " >>/convert.out 2>&1 &"
  13. convert_comm = "nohup " + python_path + " " + interface_path + "/format_convert/convert.py #" + std_out
  14. ocr_comm = "nohup " + python_path + " " + interface_path + "/ocr/ocr_interface.py #" + std_out
  15. otr_comm = "nohup " + python_path + " " + interface_path + "/otr/otr_interface.py #" + std_out
  16. soffice_comm = "docker run -itd -p #:16000 soffice:v1 bash"
  17. def get_port():
  18. net_conn = psutil.net_connections()
  19. current_port_list = []
  20. for conn in net_conn:
  21. current_port_list.append(str(conn.laddr.port))
  22. current_port_list = list(set(current_port_list))
  23. current_port_list.sort(key=lambda x: x)
  24. # print(current_port_list)
  25. return current_port_list
  26. def restart(process_type, port):
  27. if process_type == "convert":
  28. _comm = re.sub("#", port, convert_comm)
  29. elif process_type == "ocr":
  30. _comm = re.sub("#", port, ocr_comm)
  31. elif process_type == "otr":
  32. _comm = re.sub("#", port, otr_comm)
  33. elif process_type == "soffice":
  34. _comm = re.sub("#", port, soffice_comm)
  35. else:
  36. _comm = "netstat -nltp"
  37. print("no process_type", process_type)
  38. print(_comm)
  39. # os.system("netstat -nltp")
  40. os.system(_comm)
  41. def kill_soffice(limit_sec=12):
  42. pid_list = psutil.pids()
  43. for pid in pid_list:
  44. process = psutil.Process(pid)
  45. if re.search("soffice", process.exe()):
  46. run_time = process.cpu_times().user
  47. if run_time >= limit_sec:
  48. comm = "kill -9 " + str(pid)
  49. print("kill process ", str(pid), str(process.exe()), str(run_time), ">", limit_sec)
  50. os.system(comm)
  51. def monitor():
  52. current_port_list = get_port()
  53. for p in convert_port_list:
  54. if p not in current_port_list:
  55. restart("convert", p)
  56. for p in ocr_port_list:
  57. if p not in current_port_list:
  58. restart("ocr", p)
  59. for p in otr_port_list:
  60. if p not in current_port_list:
  61. restart("otr", p)
  62. for p in soffice_port_list:
  63. if p not in current_port_list:
  64. restart("soffice", p)
  65. kill_soffice()
  66. if __name__ == "__main__":
  67. monitor()