import subprocess import time import socket import os import logging from datetime import datetime from pathlib import Path from src.My_Logger.project_logger import LoggerClass LOG_PATH = Path(__file__).parent / 'logs' def is_port_in_use(port: int) -> bool: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(('192.168.195.194', port)) == 0 def start_server(): """ launch a micro service using gunicorn :return: """ launch_file_name = 'run_service_backend' # file name of the entrance point pid_path = LOG_PATH / 'pid.txt' IP = '192.168.195.194' PORT = 59001 WORKER = 1 TIME_OUT = 60 THREADS = 5 logger = LoggerClass().get_log(logging.INFO) if is_port_in_use(PORT): logger.error(f'Port {PORT} already in use') return now = datetime.now() cmd = [ "nohup", "/home/armor/anaconda3/envs/py311/bin/gunicorn", "--threads", str(THREADS), "--workers", str(WORKER), "--bind", f"{IP}:{PORT}", f"{launch_file_name}:app", "--timeout", str(TIME_OUT), "--pid", pid_path ] stdout_file = LOG_PATH / f"console_{now.year}-{now.month}-{now.day}.log" pid = subprocess.Popen(cmd, stdout=stdout_file.open('a'), stderr=subprocess.STDOUT, close_fds=True, start_new_session=True).pid time.sleep(5) if not is_port_in_use(PORT) or not os.path.exists(pid_path) or str(pid) != pid_path.read_text().strip(): logger.error(f'Failed to start server, check {stdout_file} and {pid_path}') print(f">> tail {stdout_file}") subprocess.run(["tail", str(stdout_file)]) return info_str = f"Server started" logger.info(info_str) logger.info(f"server running at {IP}:{PORT} with pid {pid}") if __name__ == "__main__": start_server()