comm_tools.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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__))), 'supervisord/build_monitor')
  23. monitor_data[build_dir] = {
  24. 'name': 'build',
  25. 'user': 'root',
  26. 'executable': sys.executable,
  27. 'filter': ['*_monitor.py'],
  28. 'exclude': []
  29. }
  30. return monitor_data
  31. def get_redis_connection():
  32. '''获取redis连接'''
  33. _config_dir = _get_config_dir()
  34. redis_path = os.path.join(_config_dir, 'redis.yml')
  35. result = _load_ymal(redis_path)
  36. data = result['connection']
  37. host, port, db = data['host'], int(data['port']), int(data['db'])
  38. try:
  39. password = data['password']
  40. except KeyError as e:
  41. password = None
  42. connection = redis.Redis(host=host, port=port, db=db, password=password, decode_responses=True)
  43. return connection
  44. def get_dingding_config():
  45. _config_dir = _get_config_dir()
  46. path = os.path.join(_config_dir, 'dingding.yml')
  47. data = _load_ymal(path)
  48. return data
  49. def shell_cmd(cmd, is_wait=True):
  50. '''执行shell命令
  51. :param is_wait 是否阻塞等待命令运行结束,Ture 表示阻塞模式
  52. :return
  53. code, stdout, stderr
  54. code 命令运行状态码,0表示运行成功
  55. stdout 命令运行输出结果
  56. stderr 命令运行错误信息
  57. '''
  58. code, stdout, stderr = 0, '', ''
  59. proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  60. if is_wait:
  61. stdout, stderr = proc.communicate()
  62. code = proc.returncode
  63. stdout = stdout.decode('utf-8').strip()
  64. stderr = stderr.decode('utf-8').strip()
  65. return code, stdout, stderr
  66. if __name__ == "__main__":
  67. con = get_redis_connection()
  68. print(con)