Newer
Older
# Copyright 2022-2024 ETSI OSG/SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# 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.
Alberto Gonzalez Barneo
committed
import logging
import signal
import sys
import threading
Alberto Gonzalez Barneo
committed
from prometheus_client import start_http_server
from common.Settings import get_log_level, get_metrics_port
Alberto Gonzalez Barneo
committed
from qkd_app.service.QKDAppService import AppService
from qkd_app.service.database.Engine import Engine
from qkd_app.service.database.models._Base import rebuild_database
Alberto Gonzalez Barneo
committed
# Set up logging
LOG_LEVEL = get_log_level()
logging.basicConfig(level=LOG_LEVEL, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s")
LOGGER = logging.getLogger(__name__)
#LOGGER.addHandler(logging.StreamHandler(stream=sys.stderr))
#LOGGER.setLevel(logging.WARNING)
Alberto Gonzalez Barneo
committed
# Event for terminating the service gracefully
Alberto Gonzalez Barneo
committed
terminate = threading.Event()
Alberto Gonzalez Barneo
committed
def signal_handler(signum, frame):
"""
Handle termination signals like SIGINT and SIGTERM to ensure graceful shutdown.
"""
LOGGER.warning('Termination signal received')
Alberto Gonzalez Barneo
committed
terminate.set()
def main():
Alberto Gonzalez Barneo
committed
# Register signal handlers for graceful shutdown
signal.signal(signal.SIGINT, signal_handler)
Alberto Gonzalez Barneo
committed
signal.signal(signal.SIGTERM, signal_handler)
Alberto Gonzalez Barneo
committed
# Start Prometheus metrics server
Alberto Gonzalez Barneo
committed
metrics_port = get_metrics_port()
start_http_server(metrics_port)
Alberto Gonzalez Barneo
committed
LOGGER.info(f'Metrics server started on port {metrics_port}')
Alberto Gonzalez Barneo
committed
Alberto Gonzalez Barneo
committed
# Initialize the SQLAlchemy database engine
Alberto Gonzalez Barneo
committed
LOGGER.info('Getting SQLAlchemy DB Engine...')
db_engine = Engine.get_engine()
if db_engine is None:
Alberto Gonzalez Barneo
committed
LOGGER.error('Unable to get SQLAlchemy DB Engine. Exiting...')
Alberto Gonzalez Barneo
committed
return -1
Alberto Gonzalez Barneo
committed
# Try creating the database or log any issues
Alberto Gonzalez Barneo
committed
try:
Engine.create_database(db_engine)
Alberto Gonzalez Barneo
committed
except Exception as e: # More specific exception handling
LOGGER.exception(f'Failed to check/create the database: {db_engine.url}. Error: {str(e)}')
return -1
Alberto Gonzalez Barneo
committed
Alberto Gonzalez Barneo
committed
# Rebuild the database schema if necessary
Alberto Gonzalez Barneo
committed
rebuild_database(db_engine)
Alberto Gonzalez Barneo
committed
# Initialize the message broker (if needed)
messagebroker = None # Disabled until further notice, can be re-enabled when necessary
# messagebroker = MessageBroker(get_messagebroker_backend())
Alberto Gonzalez Barneo
committed
Alberto Gonzalez Barneo
committed
# Start the gRPC App Service
Alberto Gonzalez Barneo
committed
grpc_service = AppService(db_engine, messagebroker)
grpc_service.start()
Alberto Gonzalez Barneo
committed
LOGGER.info('Services started. Waiting for termination signal...')
# Wait for Ctrl+C or termination signal
Alberto Gonzalez Barneo
committed
# Keep the process running until a termination signal is received
while not terminate.wait(timeout=1.0):
pass
Alberto Gonzalez Barneo
committed
Alberto Gonzalez Barneo
committed
# Shutdown services gracefully on termination
LOGGER.info('Terminating services...')
Alberto Gonzalez Barneo
committed
grpc_service.stop()
Alberto Gonzalez Barneo
committed
LOGGER.info('Shutdown complete. Exiting...')
Alberto Gonzalez Barneo
committed
return 0
if __name__ == '__main__':
sys.exit(main())