comm_tools.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # coding:utf-8
  2. import os
  3. import sys
  4. import yaml
  5. import redis
  6. import subprocess
  7. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  8. def _get_config_dir():
  9. config_dir = os.path.join(BASE_DIR, 'supervisord/config/production_env')
  10. return config_dir
  11. def _load_ymal(path):
  12. with open(path, 'r') as fr:
  13. data = yaml.load(fr, yaml.FullLoader)
  14. if data is None:
  15. data = {}
  16. return data
  17. def get_monitor_config():
  18. '''获取监控配置'''
  19. _config_dir = _get_config_dir()
  20. monitor_path = os.path.join(_config_dir, 'monitor.yml')
  21. monitor_data = _load_ymal(monitor_path)
  22. build_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'build_monitor')
  23. monitor_data[build_dir] = {
  24. 'name': 'build',
  25. 'executable': sys.executable,
  26. 'filter': ['*_monitor.py'],
  27. 'exclude': []
  28. }
  29. return monitor_data
  30. def get_redis_connection():
  31. '''获取redis连接'''
  32. _config_dir = _get_config_dir()
  33. redis_path = os.path.join(_config_dir, 'redis.yml')
  34. result = _load_ymal(redis_path)
  35. data = result['connection']
  36. host, port, db = data['host'], int(data['port']), int(data['db'])
  37. try:
  38. password = data['password']
  39. except KeyError as e:
  40. password = None
  41. connection = redis.Redis(host=host, port=port, db=db, password=password, decode_responses=True)
  42. return connection
  43. def get_dingding_config():
  44. _config_dir = _get_config_dir()
  45. path = os.path.join(_config_dir, 'dingding.yml')
  46. data = _load_ymal(path)
  47. return data
  48. def shell_cmd(cmd, is_wait=True):
  49. '''执行shell命令
  50. :param is_wait 是否阻塞等待命令运行结束,Ture 表示阻塞模式
  51. :return
  52. code, stdout, stderr
  53. code 命令运行状态码,0表示运行成功
  54. stdout 命令运行输出结果
  55. stderr 命令运行错误信息
  56. '''
  57. code, stdout, stderr = 0, '', ''
  58. proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  59. if is_wait:
  60. stdout, stderr = proc.communicate()
  61. code = proc.returncode
  62. stdout = stdout.decode('utf-8').strip()
  63. stderr = stderr.decode('utf-8').strip()
  64. return code, stdout, stderr
  65. if __name__ == "__main__":
  66. con = get_redis_connection()
  67. print(con)