Compare commits
7 Commits
9d12045b81
...
GET/aggreg
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b60383071a | ||
| 58f7c5c393 | |||
|
|
5dfba7416b | ||
|
|
fc3f39c6ae | ||
| 1ee40b6647 | |||
|
|
60008fa947 | ||
|
|
767f43551e |
11
.env
11
.env
@@ -1,8 +1,3 @@
|
||||
# Environment variables for NetApp ONTAP clusters
|
||||
CLUSTER1_HOSTNAME=172.16.57.2
|
||||
CLUSTER1_USERNAME=admin
|
||||
CLUSTER1_PASSWORD=Netapp12
|
||||
|
||||
CLUSTER2_HOSTNAME=172.16.56.2
|
||||
CLUSTER2_USERNAME=admin
|
||||
CLUSTER2_PASSWORD=Netapp12
|
||||
cluster_inventory_path = config/inventory.yml
|
||||
redis_host = '172.16.0.208'
|
||||
redis_port = '6379'
|
||||
@@ -1,8 +1,6 @@
|
||||
- 1:
|
||||
hostname: '172.16.57.2'
|
||||
username: 'admin'
|
||||
password: 'Netapp12'
|
||||
- 2:
|
||||
hostname: '172.16.56.2'
|
||||
username: 'admin'
|
||||
password: 'Netapp12'
|
||||
- hostname: "172.16.57.2"
|
||||
username: "admin"
|
||||
password: "Netapp12"
|
||||
- hostname: "172.16.56.2"
|
||||
username: "admin"
|
||||
password: "Netapp12"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from src.example.router import router as example_router
|
||||
|
||||
from .aggregate_router import router as aggregate_router
|
||||
from src.aggregate.aggregate_router import router as aggregate_router
|
||||
|
||||
__all__ = ["example_router", "aggregate_router"]
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
from typing import List
|
||||
|
||||
from fastapi import Request
|
||||
from .aggregate_schema import AggregateSchema, MetricEnum
|
||||
from src.aggregate.aggregate_schema import AggregateSchema, MetricEnum
|
||||
from logging import getLogger
|
||||
from ..utils import round_bytes, get_data_from_ontap
|
||||
from src.utils import round_bytes, get_data_from_ontap
|
||||
|
||||
logger = getLogger("uvicorn")
|
||||
logger.setLevel("DEBUG")
|
||||
@@ -16,8 +16,7 @@ async def get_aggregates(request: Request, metric: str = "relative") -> List[Agg
|
||||
# You can use the metric parameter to filter or modify results as needed
|
||||
# For now, just return the same data and show metric usage
|
||||
logger.debug(f"Metric used: {metric}")
|
||||
client = request.app.requests_client
|
||||
__aggregates = await get_data_from_ontap(client, logger, "172.16.57.2", "admin", "Netapp12", "storage/aggregates", "fields=name,uuid,space,node,home_node")
|
||||
__aggregates = await get_data_from_ontap(request, logger, "172.16.57.2", "admin", "Netapp12", "storage/aggregates", "fields=name,uuid,space,node,home_node")
|
||||
logger.debug(__aggregates)
|
||||
__aggregates = __aggregates.get("records")
|
||||
if metric == MetricEnum.relative:
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
from src.config.router import router as config_router
|
||||
|
||||
__all__ = ["config_router"]
|
||||
@@ -1,2 +0,0 @@
|
||||
# contains the business logic for the config service
|
||||
async def save_config() -> None: ...
|
||||
3
src/config_upload/__init__.py
Normal file
3
src/config_upload/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from src.config_upload.router import router as config_router
|
||||
|
||||
__all__ = ["config_router"]
|
||||
@@ -3,10 +3,12 @@ import logging
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .schema import ConfigReturnSchema, ConfigSchema
|
||||
from src.database import get_config_from_db
|
||||
from src.main import shared_redis_conn
|
||||
|
||||
logger = logging.getLogger("uvicorn")
|
||||
|
||||
router = APIRouter(tags=["config"])
|
||||
router = APIRouter(tags=["config_upload"])
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -20,3 +22,4 @@ async def create_config(config: ConfigSchema) -> ConfigSchema:
|
||||
"""
|
||||
logger.info("Received configuration data")
|
||||
return config
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# contains the schema definitions for the config service
|
||||
# contains the schema definitions for the config_upload service
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
2
src/config_upload/service.py
Normal file
2
src/config_upload/service.py
Normal file
@@ -0,0 +1,2 @@
|
||||
# contains the business logic for the config_upload service
|
||||
async def save_config() -> None: ...
|
||||
@@ -3,7 +3,7 @@ import logging
|
||||
from redis import Redis, ConnectionError
|
||||
from typing import List
|
||||
from pydantic import TypeAdapter
|
||||
from schema import ConfigSchema
|
||||
from src.schema import ConfigSchema
|
||||
|
||||
|
||||
def setup_db_conn(redishost, redisport: str):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# contains the router for the aggregate endpoint
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .schema import ExampleSchema
|
||||
from src.example.schema import ExampleSchema
|
||||
|
||||
router = APIRouter(tags=["aggregate"])
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
# contains the schema definitions for the aggregate service
|
||||
from pydantic import BaseModel
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class ExampleSchema(BaseModel):
|
||||
example_field: str
|
||||
another_field: int
|
||||
|
||||
|
||||
class ClusterCreds(BaseModel):
|
||||
"""A structure to hold basic auth cluster credentials for a cluster"""
|
||||
|
||||
username: str
|
||||
password: str
|
||||
hostname: str = None
|
||||
|
||||
@@ -5,35 +5,36 @@ import yaml
|
||||
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
from database import setup_db_conn
|
||||
from schema import ConfigSchema
|
||||
from src.database import setup_db_conn
|
||||
from src.schema import ConfigSchema
|
||||
from typing import List
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
|
||||
def initialize_config():
|
||||
load_dotenv()
|
||||
log = logging.getLogger('uvicorn')
|
||||
ENV_INVENTORYPATH = os.getenv('cluster_inventory_path')
|
||||
ENV_REDISHOST = os.getenv('redis_host')
|
||||
ENV_REDISPORT = os.getenv('redis_port')
|
||||
log = logging.getLogger("uvicorn")
|
||||
ENV_INVENTORYPATH = os.getenv("cluster_inventory_path")
|
||||
ENV_REDISHOST = os.getenv("redis_host")
|
||||
ENV_REDISPORT = os.getenv("redis_port")
|
||||
|
||||
log.info(f"Found Cluster Inventory file at: {ENV_INVENTORYPATH}")
|
||||
if not ENV_INVENTORYPATH or not Path(ENV_INVENTORYPATH).is_file():
|
||||
print(f"FATAL: Inventory file {ENV_INVENTORYPATH} is missing or not a file.")
|
||||
return False
|
||||
try:
|
||||
with open(ENV_INVENTORYPATH, 'r') as f:
|
||||
with open(ENV_INVENTORYPATH, "r") as f:
|
||||
inv = yaml.safe_load(f)
|
||||
inventory = json.dumps(inv)
|
||||
except Exception as e:
|
||||
print(f"FATAL: Cannot read inventory file {ENV_INVENTORYPATH}. Err: {e}")
|
||||
return False
|
||||
|
||||
print(f'[INFO] Importing configuration to DB...')
|
||||
print(f"[INFO] Importing configuration to DB...")
|
||||
try:
|
||||
GLOBAL_INVENTORY_VALID = TypeAdapter(List[ConfigSchema]).validate_python(inv)
|
||||
redis_conn = setup_db_conn(ENV_REDISHOST, ENV_REDISPORT)
|
||||
redis_conn.hset('cluster_inventory', mapping={'inventory': inventory})
|
||||
redis_conn.hset("cluster_inventory", mapping={"inventory": inventory})
|
||||
redis_conn.close()
|
||||
|
||||
log.info("Configuration has been loaded.")
|
||||
|
||||
24
src/main.py
24
src/main.py
@@ -1,28 +1,29 @@
|
||||
import os
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import FastAPI
|
||||
|
||||
shared_redis_conn = None
|
||||
requests_client = None
|
||||
|
||||
from src.aggregate import aggregate_router
|
||||
from src.config import config_router
|
||||
from src.config_upload import config_router
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from database import setup_db_conn, get_config_from_db
|
||||
from .database import setup_db_conn, get_config_from_db
|
||||
from src.initialize import initialize_config
|
||||
from utils import setup_logging
|
||||
from .utils import setup_logging
|
||||
|
||||
logger = logging.getLogger("uvicorn")
|
||||
logger.setLevel("DEBUG")
|
||||
logger.info("Starting application")
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(aggregate_router)
|
||||
app.include_router(config_router)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""make loading it async"""
|
||||
global shared_redis_conn, requests_client
|
||||
log = logging.getLogger("uvicorn")
|
||||
cfg_init_result = initialize_config()
|
||||
|
||||
@@ -36,8 +37,9 @@ async def lifespan(app: FastAPI):
|
||||
if not cfg_init_result:
|
||||
log.error("Configuration initialization failed. Exiting...")
|
||||
# exit(1)
|
||||
|
||||
yield
|
||||
requests_client = httpx.AsyncClient(verify=False)
|
||||
yield {"redis_conn": shared_redis_conn, "requests_client": requests_client}
|
||||
await requests_client.aclose()
|
||||
log.info("Shutting down FastAPI app...")
|
||||
|
||||
|
||||
@@ -46,3 +48,5 @@ log = logging.getLogger("uvicorn")
|
||||
|
||||
log.info("Starting FastAPI app...")
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.include_router(aggregate_router)
|
||||
app.include_router(config_router)
|
||||
|
||||
12
src/utils.py
12
src/utils.py
@@ -1,6 +1,8 @@
|
||||
import logging
|
||||
from fastapi import Request
|
||||
import httpx
|
||||
|
||||
|
||||
def round_bytes(size_in_bytes: int) -> str:
|
||||
# Helper function to convert bytes to a human-readable format
|
||||
for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]:
|
||||
@@ -10,11 +12,11 @@ def round_bytes(size_in_bytes: int) -> str:
|
||||
return f"{size_in_bytes:.2f}EB"
|
||||
|
||||
|
||||
async def get_data_from_ontap(client, logger, hostname: str, username: str, password: str, endpoint: str, query_string: str = ""):
|
||||
async def get_data_from_ontap(request: Request, logger, hostname: str, username: str, password: str, endpoint: str, query_string: str = ""):
|
||||
url = f"https://{hostname}/api/{endpoint}"
|
||||
if query_string:
|
||||
url += f"?{query_string}"
|
||||
async with client as _client:
|
||||
async with request.state.requests_client as _client:
|
||||
try:
|
||||
logger.debug(f"Fetching data from ONTAP: {url}")
|
||||
response = await _client.get(url, auth=(username, password))
|
||||
@@ -24,10 +26,8 @@ async def get_data_from_ontap(client, logger, hostname: str, username: str, pass
|
||||
logger.error(f"HTTP error occurred: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def setup_logging() -> None:
|
||||
"""Configure logging for the application"""
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG,
|
||||
format="[%(asctime)s] [%(levelname)5s] %(message)s"
|
||||
)
|
||||
logging.basicConfig(level=logging.DEBUG, format="[%(asctime)s] [%(levelname)5s] %(message)s")
|
||||
print(f"Logger is initialized.")
|
||||
|
||||
Reference in New Issue
Block a user