2018-03-19 03:26:51 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# coding: utf-8
|
|
|
|
|
|
|
|
import os
|
|
|
|
import subprocess
|
|
|
|
import threading
|
2019-10-08 10:17:48 +00:00
|
|
|
import datetime
|
2019-08-21 12:27:21 +00:00
|
|
|
import logging
|
|
|
|
import logging.handlers
|
2020-03-12 08:24:38 +00:00
|
|
|
import psutil
|
2018-03-19 03:26:51 +00:00
|
|
|
import time
|
|
|
|
import argparse
|
|
|
|
import sys
|
2019-10-08 10:17:48 +00:00
|
|
|
import shutil
|
2018-03-19 03:26:51 +00:00
|
|
|
import signal
|
2019-08-21 12:27:21 +00:00
|
|
|
from collections import defaultdict
|
|
|
|
import daemon
|
|
|
|
from daemon import pidfile
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
2019-02-22 08:14:50 +00:00
|
|
|
sys.path.insert(0, BASE_DIR)
|
2018-03-19 03:26:51 +00:00
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
|
2019-12-05 07:09:25 +00:00
|
|
|
|
2019-02-22 08:14:50 +00:00
|
|
|
try:
|
2019-03-27 09:46:35 +00:00
|
|
|
from apps.jumpserver import const
|
|
|
|
__version__ = const.VERSION
|
2019-02-22 08:14:50 +00:00
|
|
|
except ImportError as e:
|
2019-12-05 07:09:25 +00:00
|
|
|
print("Not found __version__: {}".format(e))
|
|
|
|
print("Python is: ")
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info(subprocess.call('which python', shell=True))
|
2019-02-22 08:14:50 +00:00
|
|
|
__version__ = 'Unknown'
|
2019-12-05 07:09:25 +00:00
|
|
|
sys.exit(1)
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
try:
|
2019-12-05 07:09:25 +00:00
|
|
|
from apps.jumpserver.const import CONFIG
|
2019-02-22 08:33:27 +00:00
|
|
|
except ImportError as e:
|
2019-12-05 07:09:25 +00:00
|
|
|
print("Import error: {}".format(e))
|
|
|
|
print("Could not find config file, `cp config_example.yml config.yml`")
|
2018-03-19 03:26:51 +00:00
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
os.environ["PYTHONIOENCODING"] = "UTF-8"
|
|
|
|
APPS_DIR = os.path.join(BASE_DIR, 'apps')
|
|
|
|
LOG_DIR = os.path.join(BASE_DIR, 'logs')
|
|
|
|
TMP_DIR = os.path.join(BASE_DIR, 'tmp')
|
|
|
|
HTTP_HOST = CONFIG.HTTP_BIND_HOST or '127.0.0.1'
|
|
|
|
HTTP_PORT = CONFIG.HTTP_LISTEN_PORT or 8080
|
2019-09-27 02:20:20 +00:00
|
|
|
WS_PORT = CONFIG.WS_LISTEN_PORT or 8082
|
2018-12-17 02:21:16 +00:00
|
|
|
DEBUG = CONFIG.DEBUG or False
|
|
|
|
LOG_LEVEL = CONFIG.LOG_LEVEL or 'INFO'
|
2018-03-19 03:26:51 +00:00
|
|
|
|
2018-11-26 02:22:17 +00:00
|
|
|
START_TIMEOUT = 40
|
2018-03-19 03:26:51 +00:00
|
|
|
WORKERS = 4
|
|
|
|
DAEMON = False
|
2019-10-08 10:17:48 +00:00
|
|
|
LOG_KEEP_DAYS = 7
|
|
|
|
logging.basicConfig(
|
|
|
|
format='%(asctime)s %(message)s', level=logging.INFO,
|
|
|
|
datefmt='%Y-%m-%d %H:%M:%S'
|
|
|
|
)
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
EXIT_EVENT = threading.Event()
|
2019-08-21 12:27:21 +00:00
|
|
|
LOCK = threading.Lock()
|
2019-10-08 10:17:48 +00:00
|
|
|
files_preserve = []
|
2019-10-22 08:09:21 +00:00
|
|
|
STOP_TIMEOUT = 10
|
2019-08-21 12:27:21 +00:00
|
|
|
|
2019-10-08 10:17:48 +00:00
|
|
|
logger = logging.getLogger()
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
os.makedirs(os.path.join(BASE_DIR, "data", "static"))
|
|
|
|
os.makedirs(os.path.join(BASE_DIR, "data", "media"))
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
|
2018-10-24 02:53:00 +00:00
|
|
|
def check_database_connection():
|
|
|
|
os.chdir(os.path.join(BASE_DIR, 'apps'))
|
|
|
|
for i in range(60):
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("Check database connection ...")
|
2018-10-24 02:53:00 +00:00
|
|
|
code = subprocess.call("python manage.py showmigrations users ", shell=True)
|
|
|
|
if code == 0:
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("Database connect success")
|
2018-10-24 02:53:00 +00:00
|
|
|
return
|
|
|
|
time.sleep(1)
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("Connection database failed, exist")
|
2018-10-24 02:53:00 +00:00
|
|
|
sys.exit(10)
|
|
|
|
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
def make_migrations():
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("Check database structure change ...")
|
2018-03-19 03:26:51 +00:00
|
|
|
os.chdir(os.path.join(BASE_DIR, 'apps'))
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("Migrate model change to database ...")
|
2018-03-19 03:26:51 +00:00
|
|
|
subprocess.call('python3 manage.py migrate', shell=True)
|
|
|
|
|
|
|
|
|
|
|
|
def collect_static():
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("Collect static files")
|
2018-03-19 03:26:51 +00:00
|
|
|
os.chdir(os.path.join(BASE_DIR, 'apps'))
|
2019-10-08 10:17:48 +00:00
|
|
|
command = 'python3 manage.py collectstatic --no-input -c &> /dev/null '
|
2019-08-21 12:27:21 +00:00
|
|
|
subprocess.call(command, shell=True)
|
2019-10-08 11:14:23 +00:00
|
|
|
logging.info("Collect static files done")
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
def prepare():
|
2018-10-24 02:53:00 +00:00
|
|
|
check_database_connection()
|
2018-03-19 03:26:51 +00:00
|
|
|
make_migrations()
|
|
|
|
collect_static()
|
|
|
|
|
|
|
|
|
|
|
|
def check_pid(pid):
|
|
|
|
""" Check For the existence of a unix pid. """
|
|
|
|
try:
|
|
|
|
os.kill(pid, 0)
|
2019-11-20 03:57:53 +00:00
|
|
|
except (OSError, ProcessLookupError):
|
2018-03-19 03:26:51 +00:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def get_pid_file_path(s):
|
2019-10-22 08:09:21 +00:00
|
|
|
return os.path.join(TMP_DIR, '{}.pid'.format(s))
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def get_log_file_path(s):
|
|
|
|
return os.path.join(LOG_DIR, '{}.log'.format(s))
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def get_pid_from_file(path):
|
|
|
|
if os.path.isfile(path):
|
|
|
|
with open(path) as f:
|
2018-03-25 13:47:29 +00:00
|
|
|
try:
|
|
|
|
return int(f.read().strip())
|
|
|
|
except ValueError:
|
|
|
|
return 0
|
2018-03-19 03:26:51 +00:00
|
|
|
return 0
|
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def get_pid(s):
|
|
|
|
pid_file = get_pid_file_path(s)
|
|
|
|
return get_pid_from_file(pid_file)
|
|
|
|
|
|
|
|
|
2018-03-19 03:26:51 +00:00
|
|
|
def is_running(s, unlink=True):
|
|
|
|
pid_file = get_pid_file_path(s)
|
|
|
|
|
|
|
|
if os.path.isfile(pid_file):
|
2019-01-10 02:21:05 +00:00
|
|
|
pid = get_pid(s)
|
2019-08-21 12:27:21 +00:00
|
|
|
if pid == 0:
|
|
|
|
return False
|
|
|
|
elif check_pid(pid):
|
2018-03-19 03:26:51 +00:00
|
|
|
return True
|
|
|
|
|
|
|
|
if unlink:
|
|
|
|
os.unlink(pid_file)
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def parse_service(s):
|
2019-09-19 13:21:05 +00:00
|
|
|
all_services = [
|
2019-09-26 11:22:17 +00:00
|
|
|
'gunicorn', 'celery_ansible', 'celery_default',
|
|
|
|
'beat', 'flower', 'daphne',
|
2019-09-19 13:21:05 +00:00
|
|
|
]
|
2018-03-19 03:26:51 +00:00
|
|
|
if s == 'all':
|
|
|
|
return all_services
|
2019-09-25 06:40:19 +00:00
|
|
|
elif s == "web":
|
2019-09-26 11:22:17 +00:00
|
|
|
return ['gunicorn', 'flower', 'daphne']
|
|
|
|
elif s == 'ws':
|
|
|
|
return ['daphne']
|
2019-09-25 06:40:19 +00:00
|
|
|
elif s == "task":
|
|
|
|
return ["celery_ansible", "celery_default", "beat"]
|
2019-08-21 12:27:21 +00:00
|
|
|
elif s == "celery":
|
|
|
|
return ["celery_ansible", "celery_default"]
|
2019-01-19 11:29:38 +00:00
|
|
|
elif "," in s:
|
2019-08-21 12:27:21 +00:00
|
|
|
services = set()
|
|
|
|
for i in s.split(','):
|
|
|
|
services.update(parse_service(i))
|
|
|
|
return services
|
2018-03-19 03:26:51 +00:00
|
|
|
else:
|
|
|
|
return [s]
|
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def get_start_gunicorn_kwargs():
|
2018-03-19 03:26:51 +00:00
|
|
|
print("\n- Start Gunicorn WSGI HTTP Server")
|
2019-01-24 03:25:13 +00:00
|
|
|
prepare()
|
2018-03-19 03:26:51 +00:00
|
|
|
bind = '{}:{}'.format(HTTP_HOST, HTTP_PORT)
|
|
|
|
log_format = '%(h)s %(t)s "%(r)s" %(s)s %(b)s '
|
|
|
|
|
|
|
|
cmd = [
|
|
|
|
'gunicorn', 'jumpserver.wsgi',
|
|
|
|
'-b', bind,
|
2018-09-11 04:42:49 +00:00
|
|
|
'-k', 'gthread',
|
|
|
|
'--threads', '10',
|
2018-03-19 03:26:51 +00:00
|
|
|
'-w', str(WORKERS),
|
2018-09-14 03:29:26 +00:00
|
|
|
'--max-requests', '4096',
|
2018-03-19 03:26:51 +00:00
|
|
|
'--access-logformat', log_format,
|
2019-08-21 12:27:21 +00:00
|
|
|
'--access-logfile', '-'
|
2018-03-19 03:26:51 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
if DEBUG:
|
|
|
|
cmd.append('--reload')
|
2019-08-21 12:27:21 +00:00
|
|
|
return {'cmd': cmd, 'cwd': APPS_DIR}
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
2019-09-26 11:22:17 +00:00
|
|
|
def get_start_daphne_kwargs():
|
|
|
|
print("\n- Start Daphne ASGI WS Server")
|
|
|
|
cmd = [
|
|
|
|
'daphne', 'jumpserver.asgi:application',
|
|
|
|
'-b', HTTP_HOST,
|
|
|
|
'-p', str(WS_PORT),
|
|
|
|
]
|
|
|
|
return {'cmd': cmd, 'cwd': APPS_DIR}
|
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def get_start_celery_ansible_kwargs():
|
2019-09-19 13:21:05 +00:00
|
|
|
print("\n- Start Celery as Distributed Task Queue: Ansible")
|
2019-08-21 12:27:21 +00:00
|
|
|
return get_start_worker_kwargs('ansible', 4)
|
|
|
|
|
|
|
|
|
|
|
|
def get_start_celery_default_kwargs():
|
2019-09-19 13:21:05 +00:00
|
|
|
print("\n- Start Celery as Distributed Task Queue: Celery")
|
2019-08-21 12:27:21 +00:00
|
|
|
return get_start_worker_kwargs('celery', 2)
|
|
|
|
|
|
|
|
|
|
|
|
def get_start_worker_kwargs(queue, num):
|
2018-03-19 03:26:51 +00:00
|
|
|
# Todo: Must set this environment, otherwise not no ansible result return
|
|
|
|
os.environ.setdefault('PYTHONOPTIMIZE', '1')
|
2019-09-19 13:21:05 +00:00
|
|
|
os.environ.setdefault('ANSIBLE_FORCE_COLOR', 'True')
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
if os.getuid() == 0:
|
|
|
|
os.environ.setdefault('C_FORCE_ROOT', '1')
|
2019-11-20 03:57:53 +00:00
|
|
|
server_hostname = os.environ.get("SERVER_HOSTNAME")
|
|
|
|
if not server_hostname:
|
|
|
|
server_hostname = '%h'
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
cmd = [
|
|
|
|
'celery', 'worker',
|
2019-08-21 12:27:21 +00:00
|
|
|
'-A', 'ops',
|
2019-02-13 07:55:11 +00:00
|
|
|
'-l', 'INFO',
|
2019-08-21 12:27:21 +00:00
|
|
|
'-c', str(num),
|
|
|
|
'-Q', queue,
|
2019-11-20 03:57:53 +00:00
|
|
|
'-n', '{}@{}'.format(queue, server_hostname)
|
2019-09-19 13:21:05 +00:00
|
|
|
]
|
|
|
|
return {"cmd": cmd, "cwd": APPS_DIR}
|
|
|
|
|
|
|
|
|
|
|
|
def get_start_flower_kwargs():
|
|
|
|
print("\n- Start Flower as Task Monitor")
|
|
|
|
if os.getuid() == 0:
|
|
|
|
os.environ.setdefault('C_FORCE_ROOT', '1')
|
|
|
|
|
|
|
|
cmd = [
|
|
|
|
'celery', 'flower',
|
|
|
|
'-A', 'ops',
|
|
|
|
'-l', 'INFO',
|
|
|
|
'--url_prefix=flower',
|
|
|
|
'--auto_refresh=False',
|
|
|
|
'--max_tasks=1000',
|
|
|
|
'--tasks_columns=uuid,name,args,state,received,started,runtime,worker'
|
2018-03-19 03:26:51 +00:00
|
|
|
]
|
2019-08-21 12:27:21 +00:00
|
|
|
return {"cmd": cmd, "cwd": APPS_DIR}
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def get_start_beat_kwargs():
|
2018-03-19 03:26:51 +00:00
|
|
|
print("\n- Start Beat as Periodic Task Scheduler")
|
|
|
|
os.environ.setdefault('PYTHONOPTIMIZE', '1')
|
|
|
|
if os.getuid() == 0:
|
|
|
|
os.environ.setdefault('C_FORCE_ROOT', '1')
|
|
|
|
|
|
|
|
scheduler = "django_celery_beat.schedulers:DatabaseScheduler"
|
|
|
|
cmd = [
|
2019-08-21 12:27:21 +00:00
|
|
|
'celery', 'beat',
|
2018-04-02 05:19:31 +00:00
|
|
|
'-A', 'ops',
|
2019-08-21 12:27:21 +00:00
|
|
|
'-l', 'INFO',
|
2018-03-19 03:26:51 +00:00
|
|
|
'--scheduler', scheduler,
|
|
|
|
'--max-interval', '60'
|
|
|
|
]
|
2019-08-21 12:27:21 +00:00
|
|
|
return {"cmd": cmd, 'cwd': APPS_DIR}
|
|
|
|
|
|
|
|
|
|
|
|
processes = {}
|
|
|
|
|
|
|
|
|
|
|
|
def watch_services():
|
|
|
|
max_retry = 3
|
|
|
|
services_retry = defaultdict(int)
|
|
|
|
stopped_services = {}
|
|
|
|
|
|
|
|
def check_services():
|
2019-10-08 10:17:48 +00:00
|
|
|
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
2019-08-21 12:27:21 +00:00
|
|
|
for s, p in processes.items():
|
2019-10-08 10:17:48 +00:00
|
|
|
print("{} Check service status: {} -> ".format(now, s), end='')
|
2019-08-21 12:27:21 +00:00
|
|
|
try:
|
|
|
|
p.wait(timeout=1)
|
|
|
|
except subprocess.TimeoutExpired:
|
2019-10-08 10:17:48 +00:00
|
|
|
pass
|
2019-10-08 11:14:23 +00:00
|
|
|
ok = is_running(s)
|
|
|
|
if not ok:
|
2019-10-08 10:17:48 +00:00
|
|
|
stopped_services[s] = ''
|
2019-10-08 11:14:23 +00:00
|
|
|
print("stopped with code: {}({})".format(p.returncode, p.pid))
|
2019-10-08 10:17:48 +00:00
|
|
|
else:
|
2019-10-08 11:14:23 +00:00
|
|
|
print("running at {}".format(p.pid))
|
2019-08-21 12:27:21 +00:00
|
|
|
stopped_services.pop(s, None)
|
|
|
|
services_retry.pop(s, None)
|
|
|
|
|
|
|
|
def retry_start_stopped_services():
|
|
|
|
for s in stopped_services:
|
|
|
|
if services_retry[s] > max_retry:
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("Service start failed, exit: ", s)
|
2019-08-21 12:27:21 +00:00
|
|
|
EXIT_EVENT.set()
|
|
|
|
break
|
|
|
|
|
|
|
|
p = start_service(s)
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info("> Find {} stopped, retry {}, {}".format(
|
|
|
|
s, services_retry[s] + 1, p.pid)
|
|
|
|
)
|
2019-08-21 12:27:21 +00:00
|
|
|
processes[s] = p
|
|
|
|
services_retry[s] += 1
|
|
|
|
|
2019-10-08 10:17:48 +00:00
|
|
|
def rotate_log_if_need():
|
|
|
|
now = datetime.datetime.now()
|
|
|
|
tm = now.strftime('%H:%M')
|
|
|
|
if tm != '23:59':
|
|
|
|
return
|
|
|
|
suffix = now.strftime('%Y-%m-%d')
|
2019-10-08 11:14:23 +00:00
|
|
|
services = list(processes.keys())
|
|
|
|
services.append('jms')
|
|
|
|
|
|
|
|
for s in services:
|
2019-10-08 10:17:48 +00:00
|
|
|
log_path = get_log_file_path(s)
|
|
|
|
log_dir = os.path.dirname(log_path)
|
|
|
|
filename = os.path.basename(log_path)
|
|
|
|
pre_log_dir = os.path.join(log_dir, suffix)
|
|
|
|
if not os.path.exists(pre_log_dir):
|
|
|
|
os.mkdir(pre_log_dir)
|
|
|
|
|
|
|
|
pre_log_path = os.path.join(pre_log_dir, filename)
|
|
|
|
if os.path.isfile(log_path) and not os.path.isfile(pre_log_path):
|
|
|
|
logging.info("Rotate log file: {} => {}".format(log_path, pre_log_path))
|
|
|
|
shutil.copy(log_path, pre_log_path)
|
|
|
|
with open(log_path, 'w') as f:
|
|
|
|
pass
|
|
|
|
some_days_ago = now - datetime.timedelta(days=LOG_KEEP_DAYS)
|
|
|
|
days_ago_dir = os.path.join(LOG_DIR, some_days_ago.strftime('%Y-%m-%d'))
|
|
|
|
if os.path.exists(days_ago_dir):
|
|
|
|
logger.info("Remove old log: {}".format(days_ago_dir))
|
|
|
|
shutil.rmtree(days_ago_dir, ignore_errors=True)
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
while not EXIT_EVENT.is_set():
|
|
|
|
try:
|
|
|
|
with LOCK:
|
|
|
|
check_services()
|
|
|
|
retry_start_stopped_services()
|
2019-10-08 10:17:48 +00:00
|
|
|
rotate_log_if_need()
|
|
|
|
time.sleep(30)
|
2019-08-21 12:27:21 +00:00
|
|
|
except KeyboardInterrupt:
|
2020-03-12 08:24:38 +00:00
|
|
|
print("Start stop service")
|
2019-08-21 12:27:21 +00:00
|
|
|
time.sleep(1)
|
|
|
|
break
|
|
|
|
clean_up()
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
def start_service(s):
|
2019-08-21 12:27:21 +00:00
|
|
|
services_kwargs = {
|
|
|
|
"gunicorn": get_start_gunicorn_kwargs,
|
|
|
|
"celery_ansible": get_start_celery_ansible_kwargs,
|
|
|
|
"celery_default": get_start_celery_default_kwargs,
|
|
|
|
"beat": get_start_beat_kwargs,
|
2019-09-19 13:21:05 +00:00
|
|
|
"flower": get_start_flower_kwargs,
|
2019-09-26 11:22:17 +00:00
|
|
|
"daphne": get_start_daphne_kwargs,
|
2019-08-21 12:27:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
kwargs = services_kwargs.get(s)()
|
|
|
|
pid_file = get_pid_file_path(s)
|
|
|
|
|
|
|
|
if os.path.isfile(pid_file):
|
|
|
|
os.unlink(pid_file)
|
|
|
|
cmd = kwargs.pop('cmd')
|
|
|
|
|
2019-10-08 10:17:48 +00:00
|
|
|
log_file_path = get_log_file_path(s)
|
|
|
|
log_file_f = open(log_file_path, 'a')
|
|
|
|
files_preserve.append(log_file_f)
|
|
|
|
kwargs['stderr'] = log_file_f
|
|
|
|
kwargs['stdout'] = log_file_f
|
2019-08-21 12:27:21 +00:00
|
|
|
p = subprocess.Popen(cmd, **kwargs)
|
|
|
|
with open(pid_file, 'w') as f:
|
|
|
|
f.write(str(p.pid))
|
|
|
|
return p
|
|
|
|
|
|
|
|
|
|
|
|
def start_services_and_watch(s):
|
2019-10-08 10:17:48 +00:00
|
|
|
logging.info(time.ctime())
|
|
|
|
logging.info('Jumpserver version {}, more see https://www.jumpserver.org'.format(
|
2019-08-21 12:27:21 +00:00
|
|
|
__version__)
|
|
|
|
)
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
services_set = parse_service(s)
|
|
|
|
for i in services_set:
|
|
|
|
if is_running(i):
|
|
|
|
show_service_status(i)
|
|
|
|
continue
|
2019-08-21 12:27:21 +00:00
|
|
|
p = start_service(i)
|
|
|
|
time.sleep(2)
|
|
|
|
processes[i] = p
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
if not DAEMON:
|
2019-08-21 12:27:21 +00:00
|
|
|
watch_services()
|
2018-03-19 03:26:51 +00:00
|
|
|
else:
|
|
|
|
show_service_status(s)
|
2019-10-08 10:17:48 +00:00
|
|
|
context = get_daemon_context()
|
2019-08-21 12:27:21 +00:00
|
|
|
with context:
|
|
|
|
watch_services()
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
2019-10-08 10:17:48 +00:00
|
|
|
def get_daemon_context():
|
|
|
|
daemon_pid_file = get_pid_file_path('jms')
|
|
|
|
daemon_log_f = open(get_log_file_path('jms'), 'a')
|
|
|
|
files_preserve.append(daemon_log_f)
|
|
|
|
context = daemon.DaemonContext(
|
|
|
|
pidfile=pidfile.TimeoutPIDLockFile(daemon_pid_file),
|
2019-10-09 02:43:51 +00:00
|
|
|
signal_map={
|
|
|
|
signal.SIGTERM: lambda x, y: clean_up(),
|
|
|
|
signal.SIGHUP: 'terminate',
|
|
|
|
},
|
2019-10-08 10:17:48 +00:00
|
|
|
stdout=daemon_log_f,
|
|
|
|
stderr=daemon_log_f,
|
|
|
|
files_preserve=files_preserve,
|
|
|
|
detach_process=True,
|
|
|
|
)
|
|
|
|
return context
|
|
|
|
|
|
|
|
|
|
|
|
def stop_service(srv, sig=15):
|
|
|
|
services_set = parse_service(srv)
|
2018-03-19 03:26:51 +00:00
|
|
|
for s in services_set:
|
|
|
|
if not is_running(s):
|
|
|
|
show_service_status(s)
|
|
|
|
continue
|
2019-10-22 08:09:21 +00:00
|
|
|
print("Stop service: {}".format(s), end='')
|
2018-03-19 03:26:51 +00:00
|
|
|
pid = get_pid(s)
|
|
|
|
os.kill(pid, sig)
|
2019-11-20 03:57:53 +00:00
|
|
|
with LOCK:
|
|
|
|
process = processes.pop(s, None)
|
2020-03-12 08:24:38 +00:00
|
|
|
if process is None:
|
|
|
|
try:
|
|
|
|
process = psutil.Process(pid)
|
|
|
|
except:
|
|
|
|
pass
|
2019-11-20 03:57:53 +00:00
|
|
|
if process is None:
|
|
|
|
print("\033[31m No process found\033[0m")
|
|
|
|
continue
|
2019-12-05 07:09:25 +00:00
|
|
|
try:
|
|
|
|
process.wait(1)
|
|
|
|
except:
|
|
|
|
pass
|
2019-10-22 08:09:21 +00:00
|
|
|
for i in range(STOP_TIMEOUT):
|
|
|
|
if i == STOP_TIMEOUT - 1:
|
|
|
|
print("\033[31m Error\033[0m")
|
|
|
|
if not is_running(s):
|
|
|
|
print("\033[32m Ok\033[0m")
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
time.sleep(1)
|
|
|
|
continue
|
|
|
|
|
2019-10-08 10:17:48 +00:00
|
|
|
if srv == "all":
|
|
|
|
stop_daemon_service()
|
|
|
|
|
|
|
|
|
|
|
|
def stop_daemon_service():
|
|
|
|
pid = get_pid('jms')
|
2019-10-14 03:37:13 +00:00
|
|
|
if pid and check_pid(pid):
|
2019-10-08 10:17:48 +00:00
|
|
|
os.kill(pid, 15)
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
def stop_multi_services(services):
|
|
|
|
for s in services:
|
|
|
|
stop_service(s, sig=9)
|
|
|
|
|
|
|
|
|
|
|
|
def stop_service_force(s):
|
|
|
|
stop_service(s, sig=9)
|
|
|
|
|
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def clean_up():
|
|
|
|
if not EXIT_EVENT.is_set():
|
|
|
|
EXIT_EVENT.set()
|
|
|
|
processes_dump = {k: v for k, v in processes.items()}
|
|
|
|
for s1, p1 in processes_dump.items():
|
|
|
|
stop_service(s1)
|
|
|
|
p1.wait()
|
|
|
|
|
|
|
|
|
2018-03-19 03:26:51 +00:00
|
|
|
def show_service_status(s):
|
|
|
|
services_set = parse_service(s)
|
|
|
|
for ns in services_set:
|
|
|
|
if is_running(ns):
|
|
|
|
pid = get_pid(ns)
|
2019-10-22 08:09:21 +00:00
|
|
|
print("{} is running: {}".format(ns, pid))
|
2018-03-19 03:26:51 +00:00
|
|
|
else:
|
2019-10-22 08:09:21 +00:00
|
|
|
print("{} is stopped".format(ns))
|
2018-03-19 03:26:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
description="""
|
|
|
|
Jumpserver service control tools;
|
2018-03-25 13:47:29 +00:00
|
|
|
|
|
|
|
Example: \r\n
|
|
|
|
|
2018-03-19 03:26:51 +00:00
|
|
|
%(prog)s start all -d;
|
|
|
|
"""
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
'action', type=str,
|
|
|
|
choices=("start", "stop", "restart", "status"),
|
|
|
|
help="Action to run"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"service", type=str, default="all", nargs="?",
|
2019-10-08 10:17:48 +00:00
|
|
|
choices=("all", "web", "task", "gunicorn", "celery", "beat", "celery,beat", "flower", "ws"),
|
2018-03-19 03:26:51 +00:00
|
|
|
help="The service to start",
|
|
|
|
)
|
|
|
|
parser.add_argument('-d', '--daemon', nargs="?", const=1)
|
|
|
|
parser.add_argument('-w', '--worker', type=int, nargs="?", const=4)
|
2019-10-22 08:09:21 +00:00
|
|
|
parser.add_argument('-f', '--force', nargs="?", const=1)
|
2018-03-19 03:26:51 +00:00
|
|
|
args = parser.parse_args()
|
|
|
|
if args.daemon:
|
|
|
|
DAEMON = True
|
|
|
|
|
|
|
|
if args.worker:
|
|
|
|
WORKERS = args.worker
|
|
|
|
|
|
|
|
action = args.action
|
|
|
|
srv = args.service
|
|
|
|
|
|
|
|
if action == "start":
|
2019-08-21 12:27:21 +00:00
|
|
|
start_services_and_watch(srv)
|
|
|
|
os._exit(0)
|
2018-03-19 03:26:51 +00:00
|
|
|
elif action == "stop":
|
2020-03-12 08:24:38 +00:00
|
|
|
print("Stop service")
|
2019-10-22 08:09:21 +00:00
|
|
|
if args.force:
|
|
|
|
stop_service_force(srv)
|
|
|
|
else:
|
|
|
|
stop_service(srv)
|
2018-03-19 03:26:51 +00:00
|
|
|
elif action == "restart":
|
|
|
|
DAEMON = True
|
|
|
|
stop_service(srv)
|
|
|
|
time.sleep(5)
|
2019-08-21 12:27:21 +00:00
|
|
|
start_services_and_watch(srv)
|
2018-03-19 03:26:51 +00:00
|
|
|
else:
|
|
|
|
show_service_status(srv)
|