1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00
Files
checktheroads-hyperglass/hyperglass/api/events.py

101 lines
2.4 KiB
Python
Raw Normal View History

2020-01-21 17:27:57 -07:00
"""API Events."""
2020-02-03 02:34:50 -07:00
# Third Party
2020-01-21 17:27:57 -07:00
from starlette.exceptions import HTTPException
2020-02-03 02:34:50 -07:00
# Project
from hyperglass.util import (
log,
check_redis,
check_python,
build_frontend,
clear_redis_cache,
)
2020-03-22 11:41:51 -07:00
from hyperglass.constants import MIN_PYTHON_VERSION, __version__
2020-01-21 17:27:57 -07:00
from hyperglass.exceptions import HyperglassError
2020-02-03 02:34:50 -07:00
from hyperglass.configuration import (
URL_DEV,
URL_PROD,
CONFIG_PATH,
2020-02-03 02:34:50 -07:00
REDIS_CONFIG,
params,
frontend_params,
)
2020-01-21 17:27:57 -07:00
2020-03-22 11:41:51 -07:00
async def log_hyperglass_version():
"""Log the hyperglass version on startup."""
log.info(f"hyperglass version is {__version__}")
return True
2020-01-21 17:27:57 -07:00
async def check_python_version():
"""Ensure Python version meets minimum requirement.
Raises:
HyperglassError: Raised if Python version is invalid.
"""
try:
python_version = check_python()
2020-02-16 00:52:51 -07:00
required = ".".join(tuple(str(v) for v in MIN_PYTHON_VERSION))
log.info(f"Python {python_version} detected ({required} required)")
except RuntimeError as e:
raise HyperglassError(str(e), level="danger") from None
2020-01-21 17:27:57 -07:00
async def check_redis_instance():
"""Ensure Redis is running before starting server.
Raises:
HyperglassError: Raised if Redis is not running.
Returns:
{bool} -- True if Redis is running.
"""
try:
2020-01-28 09:52:54 -07:00
await check_redis(db=params.cache.database, config=REDIS_CONFIG)
2020-01-21 17:27:57 -07:00
except RuntimeError as e:
2020-01-21 20:03:47 -07:00
raise HyperglassError(str(e), level="danger") from None
2020-01-21 17:27:57 -07:00
log.debug(f"Redis is running at: {REDIS_CONFIG['host']}:{REDIS_CONFIG['port']}")
return True
async def build_ui():
"""Perform a UI build prior to starting the application.
Raises:
HTTPException: Raised if any build errors occur.
Returns:
{bool} -- True if successful.
"""
try:
await build_frontend(
2020-01-28 08:59:27 -07:00
dev_mode=params.developer_mode,
2020-01-21 17:27:57 -07:00
dev_url=URL_DEV,
prod_url=URL_PROD,
params=frontend_params,
app_path=CONFIG_PATH,
2020-01-21 17:27:57 -07:00
)
except RuntimeError as e:
raise HTTPException(detail=str(e), status_code=500)
return True
async def clear_cache():
"""Clear the Redis cache on shutdown."""
try:
2020-01-28 09:52:54 -07:00
await clear_redis_cache(db=params.cache.database, config=REDIS_CONFIG)
2020-01-21 17:27:57 -07:00
except RuntimeError as e:
log.error(str(e))
pass
2020-03-22 11:41:51 -07:00
on_startup = [
log_hyperglass_version,
check_python_version,
check_redis_instance,
build_ui,
]
2020-01-21 17:27:57 -07:00
on_shutdown = [clear_cache]