import logging, os, time from typing import List LOGGER = logging.getLogger(__name__) DEFAULT_RESTART_DELAY = 5.0 # seconds def wait_for_environment_variables( required_environment_variables : List[str] = [], wait_delay_seconds : float = DEFAULT_RESTART_DELAY ): if 'KUBERNETES_PORT' not in os.environ: return # We're not running in Kubernetes, nothing to wait for missing_variables = set(required_environment_variables).difference(set(os.environ.keys())) if len(missing_variables) == 0: return # We have all environment variables defined msg = 'Variables({:s}) are missing in Environment({:s}), restarting in {:f} seconds...' LOGGER.error(msg.format(str(missing_variables), str(os.environ), wait_delay_seconds)) time.sleep(wait_delay_seconds) raise Exception('Restarting...') def get_setting(name, **kwargs): value = os.environ.get(name) if 'settings' in kwargs: value = kwargs['settings'].pop(name, value) if value is not None: return value if 'default' in kwargs: return kwargs['default'] raise Exception('Setting({}) not specified in environment or configuration'.format(name))