#!/usr/bin/env python3 # coding: utf-8 import os import logging import logging.handlers import time import argparse import sys import django from django.core import management from django.db.utils import OperationalError BASE_DIR = os.path.dirname(os.path.abspath(__file__)) APP_DIR = os.path.join(BASE_DIR, 'apps') os.chdir(APP_DIR) sys.path.insert(0, APP_DIR) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jumpserver.settings") django.setup() logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S") try: from jumpserver import const __version__ = const.VERSION except ImportError as e: print("Not found __version__: {}".format(e)) print("Python is: ") logging.info(sys.executable) __version__ = 'Unknown' sys.exit(1) try: from jumpserver.const import CONFIG except ImportError as e: print("Import error: {}".format(e)) print("Could not find config file, `cp config_example.yml config.yml`") sys.exit(1) os.environ["PYTHONIOENCODING"] = "UTF-8" logging.basicConfig( format='%(asctime)s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S' ) logger = logging.getLogger() try: os.makedirs(os.path.join(BASE_DIR, "data", "static")) os.makedirs(os.path.join(BASE_DIR, "data", "media")) except: pass def check_database_connection(): for i in range(60): logging.info(f"Check database connection: {i}") try: management.call_command('check', '--database', 'default') logging.info("Database connect success") return except OperationalError: logging.info('Database not setup, retry') except Exception as e: logging.error('Unexpect error occur: {}'.format(str(e))) time.sleep(1) logging.error("Connection database failed, exit") sys.exit(10) def expire_caches(): try: management.call_command('expire_caches') except: pass def perform_db_migrate(): logging.info("Check database structure change ...") logging.info("Migrate model change to database ...") try: management.call_command('migrate') except Exception: logging.error('Perform migrate failed, exit') sys.exit(11) def collect_static(): logging.info("Collect static files") try: management.call_command('collectstatic', '--no-input', '-c', verbosity=0, interactive=False) logging.info("Collect static files done") except: pass def compile_i81n_file(): django_mo_file = os.path.join(BASE_DIR, 'apps', 'locale', 'zh', 'LC_MESSAGES', 'django.mo') if os.path.exists(django_mo_file): return os.chdir(os.path.join(BASE_DIR, 'apps')) management.call_command('compilemessages', verbosity=0, interactive=False) logging.info("Compile i18n files done") def upgrade_db(): collect_static() perform_db_migrate() def prepare(): check_database_connection() upgrade_db() expire_caches() def start_services(): services = args.services if isinstance(args.services, list) else [args.services] if action == 'start' and {'all', 'web'} & set(services): prepare() start_args = [] if args.daemon: start_args.append('--daemon') if args.worker: start_args.extend(['--worker', str(args.worker)]) if args.force: start_args.append('--force') try: management.call_command(action, *services, *start_args) except KeyboardInterrupt: logging.info('Cancel ...') time.sleep(2) except Exception as e: logging.error("Start service error {}: {}".format(services, e)) time.sleep(2) if __name__ == '__main__': parser = argparse.ArgumentParser( description=""" Jumpserver service control tools; Example: \r\n %(prog)s start all -d; """ ) parser.add_argument( 'action', type=str, choices=("start", "stop", "restart", "status", "upgrade_db", "collect_static"), help="Action to run" ) parser.add_argument( "services", type=str, default='all', nargs="*", choices=("all", "web", "task"), help="The service to start", ) parser.add_argument('-d', '--daemon', nargs="?", const=True) parser.add_argument('-w', '--worker', type=int, nargs="?", default=4) parser.add_argument('-f', '--force', nargs="?", const=True) args = parser.parse_args() action = args.action if action == "upgrade_db": upgrade_db() elif action == "collect_static": collect_static() else: start_services()