Skip to content

Commit

Permalink
better boolean args, fixxing some issues
Browse files Browse the repository at this point in the history
moved args to it's own settings class
  • Loading branch information
tebben committed Aug 15, 2024
1 parent 42d8c03 commit a19a3ee
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 99 deletions.
45 changes: 0 additions & 45 deletions ctod/args.py

This file was deleted.

57 changes: 15 additions & 42 deletions ctod/server/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
from ctod.server.handlers.status import get_server_status
from ctod.core import utils
from ctod.server.helpers import get_extensions
from ctod.args import parse_args, get_value
from ctod.core.cog.cog_reader_pool import CogReaderPool
from ctod.core.factory.terrain_factory import TerrainFactory
from ctod.server.handlers.layer import get_layer_json
from ctod.server.handlers.terrain import TerrainHandler
from ctod.server.settings import Settings
from ctod.server.startup import patch_occlusion, setup_logging, log_ctod_start
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager

Expand All @@ -29,65 +29,38 @@

@asynccontextmanager
async def lifespan(app: FastAPI):
args = parse_args()
unsafe = get_value(args, "unsafe", os.environ.get(
"CTOD_UNSAFE", False), False)
settings = Settings()

no_dynamic = get_value(args, "no_dynamic", os.environ.get(
"CTOD_NO_DYNAMIC", False), False)

tile_cache_path = get_value(
args, "tile_cache_path", os.environ.get(
"CTOD_TILE_CACHE_PATH", None), None
)

port = get_value(args, "port", int(
os.environ.get("CTOD_PORT", 5000)), 5000)

logging_level = get_value(
args, "logging_level", os.environ.get(
"CTOD_LOGGING_LEVEL", "info"), "info"
)

db_name = get_value(
args, "db_name", os.environ.get(
"CTOD_DB_NAME", "factory_cache.db"), "factory_cache.db"
)
patch_occlusion()
setup_logging(log_level=getattr(logging, settings.logging_level.upper()))
log_ctod_start(settings)
await setup_globals(settings)

factory_cache_ttl = 15
yield

dataset_config_path = get_value(
args, "dataset_config_path", os.environ.get(
"CTOD_DATASET_CONFIG_PATH", "./config/datasets.json"), "./config/datasets.json"
)

patch_occlusion()
setup_logging(log_level=getattr(logging, logging_level.upper()))
log_ctod_start(port, tile_cache_path)

dataset_config = DatasetConfig(dataset_config_path)
async def setup_globals(settings: Settings):
dataset_config = DatasetConfig(settings.dataset_config_path)
terrain_factory = TerrainFactory(
tile_cache_path, db_name, factory_cache_ttl)
settings.tile_cache_path, settings.db_name, settings.factory_cache_ttl)
await terrain_factory.cache.initialize()

globals["terrain_factory"] = terrain_factory
globals["terrain_factory"].start_periodic_check()
globals["cog_reader_pool"] = CogReaderPool(unsafe)
globals["tile_cache_path"] = tile_cache_path
globals["no_dynamic"] = no_dynamic
globals["cog_reader_pool"] = CogReaderPool(settings.unsafe)
globals["tile_cache_path"] = settings.tile_cache_path
globals["no_dynamic"] = settings.no_dynamic
globals["dataset_config"] = dataset_config
globals["tms"] = utils.get_tms()
globals["start_time"] = datetime.now(timezone.utc)

yield


app = FastAPI(
lifespan=lifespan,
title="CTOD",
description="Cesium Terrain On Demand",
summary="CTOD fetches Cesium terrain tiles from Cloud Optimized GeoTIFFs dynamically, avoiding extensive caching to save time and storage space. By generating tiles on demand, it optimizes efficiency and reduces resource consumption compared to traditional caching methods.",
version="0.9.0",
version="1.0.1",
debug=False,
)

Expand Down
51 changes: 51 additions & 0 deletions ctod/server/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import os
import argparse


class Settings:
"""
Class representing the settings for the CTOD application.
Args:
args (argparse.Namespace, optional): Command-line arguments. If not provided, the arguments will be parsed from the command line.
"""

def __init__(self, args=None):
# If args is not provided, parse from command line
if args is None:
parser = argparse.ArgumentParser(description="CTOD Application")
parser.add_argument("--tile-cache-path",
help="Path to the tile cache")
parser.add_argument(
"--dataset-config-path", help="Path to the dataset config, default ./config/datasets.json")
parser.add_argument("--logging-level", choices=[
"debug", "info", "warning", "error", "critical"], help="Logging level")
parser.add_argument("--db-name", help="Name of the caching db")
parser.add_argument("--port", help="Port to run the application o")
parser.add_argument("--dev", action="store_true",
help="Start in dev mode")
parser.add_argument("--unsafe", action="store_true",
help="When unsafe all tiles will be loaded, even if there are not enough overviews")
parser.add_argument("--no-dynamic", action="store_true",
help="Disable the endpoints for dynamic terrain based on query parameters")
args = parser.parse_args()

# Get values from command-line arguments or environment variables
self.tile_cache_path = args.tile_cache_path or os.getenv(
"CTOD_TILE_CACHE_PATH", None)
self.dataset_config_path = args.dataset_config_path or os.getenv(
"CTOD_DATASET_CONFIG_PATH", "./config/datasets.json")
self.logging_level = args.logging_level or os.getenv(
"CTOD_LOGGING_LEVEL", "info")
self.db_name = args.db_name or os.getenv(
"CTOD_DB_NAME", "factory_cache.db")
self.port = args.port or int(os.getenv("CTOD_PORT", 5000))

# Handle boolean flags
self.dev = args.dev if args.dev else os.getenv(
"CTOD_DEV", "False").lower() in ("true", "1", "t")
self.unsafe = args.unsafe if args.unsafe else os.getenv(
"CTOD_UNSAFE", "False").lower() in ("true", "1", "t")
self.no_dynamic = args.no_dynamic if args.no_dynamic else os.getenv(
"CTOD_NO_DYNAMIC", "False").lower() in ("true", "1", "t")
self.factory_cache_ttl = 15
21 changes: 14 additions & 7 deletions ctod/server/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import quantized_mesh_encoder.occlusion

from ctod.core.math import compute_magnitude
from ctod.server.settings import Settings


def patch_occlusion():
Expand All @@ -24,19 +25,25 @@ def setup_logging(log_level=logging.INFO):
)


def log_ctod_start(port: int, tile_cache_path: str):
def log_ctod_start(settings: Settings):
"""Log message when starting the service
Args:
port (int): Port the service is running on
tile_cache_path (str): Path to the tile cache
settings (Settings): CTOD settings loaded from args or environment variables
"""

logging.info("-----------------------")
logging.info(f"CTOD Started")
logging.info("-----------------------")
logging.info(f"Port: {port}")
logging.info(f"Caching: {'enabled' if tile_cache_path else 'disabled'}")
if tile_cache_path:
logging.info(f"Caching Path: {tile_cache_path}")
logging.info(f"Port:\t\t {settings.port}")
logging.info(
f"Caching:\t\t {'enabled' if settings.tile_cache_path else 'disabled'}")
if settings.tile_cache_path:
logging.info(f"Caching Path:\t {settings.tile_cache_path}")
logging.info(f"Dataset Config:\t {settings.dataset_config_path}")
logging.info(f"Logging Level:\t {settings.logging_level}")
logging.info(f"DB Name:\t\t {settings.db_name}")
logging.info(f"Dev Mode:\t\t {settings.dev}")
logging.info(f"Unsafe:\t\t {settings.unsafe}")
logging.info(f"No Dynamic:\t\t {settings.no_dynamic}")
logging.info("-----------------------")
11 changes: 6 additions & 5 deletions start_server.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import os
import uvicorn
from ctod.args import parse_args, get_value

from ctod.server.settings import Settings


def get_port() -> int:
args = parse_args()
port = get_value(args, "port", int(os.environ.get("CTOD_PORT", 5000)), 5000)
settings = Settings()
port = settings.port

return port

Expand All @@ -29,5 +29,6 @@ def main_dev():
workers=1,
)


if __name__ == "__main__":
main()
main()

0 comments on commit a19a3ee

Please sign in to comment.