Newer
Older
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
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))