2020-02-23 18:52:41 +00:00
|
|
|
"""passbook management command to bootstrap"""
|
|
|
|
from argparse import REMAINDER
|
|
|
|
from subprocess import Popen # nosec
|
2020-03-05 16:28:03 +00:00
|
|
|
from sys import exit as _exit
|
2020-04-10 19:52:03 +00:00
|
|
|
from sys import stderr, stdin, stdout
|
2020-02-23 18:52:41 +00:00
|
|
|
from time import sleep
|
2020-03-05 16:28:03 +00:00
|
|
|
from typing import List
|
2020-02-23 18:52:41 +00:00
|
|
|
|
|
|
|
from django.core.management.base import BaseCommand
|
|
|
|
from django.db import connection
|
|
|
|
from django.db.utils import OperationalError
|
|
|
|
from django_redis import get_redis_connection
|
|
|
|
from redis.exceptions import ConnectionError as RedisConnectionError
|
|
|
|
from structlog import get_logger
|
|
|
|
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
"""Bootstrap passbook, ensure Database and Cache are
|
|
|
|
reachable, and directories are writeable"""
|
|
|
|
|
|
|
|
help = """Bootstrap passbook, ensure Database and Cache are
|
|
|
|
reachable, and directories are writeable"""
|
|
|
|
|
|
|
|
def add_arguments(self, parser):
|
|
|
|
parser.add_argument("command", nargs=REMAINDER)
|
|
|
|
|
|
|
|
def check_database(self) -> bool:
|
|
|
|
"""Return true if database is reachable, false otherwise"""
|
|
|
|
try:
|
|
|
|
connection.cursor()
|
|
|
|
LOGGER.info("Database reachable")
|
|
|
|
return True
|
|
|
|
except OperationalError:
|
|
|
|
LOGGER.info("Database unreachable")
|
|
|
|
return False
|
|
|
|
|
|
|
|
def check_cache(self) -> bool:
|
|
|
|
"""Return true if cache is reachable, false otherwise"""
|
|
|
|
try:
|
|
|
|
con = get_redis_connection("default")
|
|
|
|
con.ping()
|
|
|
|
LOGGER.info("Cache reachable")
|
|
|
|
return True
|
|
|
|
except RedisConnectionError:
|
|
|
|
LOGGER.info("Cache unreachable")
|
|
|
|
return False
|
|
|
|
|
|
|
|
def handle(self, *args, **options):
|
|
|
|
LOGGER.info("passbook bootstrapping...")
|
|
|
|
should_check = True
|
|
|
|
while should_check:
|
|
|
|
should_check = not (self.check_database() and self.check_cache())
|
|
|
|
sleep(1)
|
|
|
|
LOGGER.info("Dependencies are up, starting command...")
|
2020-03-05 16:28:03 +00:00
|
|
|
commands: List[str] = options.get("command", ["exit", "1"])
|
|
|
|
proc = Popen(args=commands, stdout=stdout, stderr=stderr, stdin=stdin) # nosec
|
2020-02-23 18:52:41 +00:00
|
|
|
try:
|
|
|
|
proc.wait()
|
2020-03-05 16:28:03 +00:00
|
|
|
_exit(proc.returncode)
|
2020-02-23 18:52:41 +00:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
LOGGER.info("Killing process")
|
|
|
|
proc.kill()
|
2020-03-05 16:28:03 +00:00
|
|
|
_exit(254)
|