diff --git a/api/main.py b/api/main.py index d6994d19..7c2b4b26 100644 --- a/api/main.py +++ b/api/main.py @@ -11,7 +11,6 @@ import os import re from typing import List, Union, Optional -import threading from contextlib import asynccontextmanager from fastapi import ( Depends, @@ -54,6 +53,7 @@ UserUpdate, UserGroup, ) +from .metrics import Metrics @asynccontextmanager @@ -69,53 +69,7 @@ async def lifespan(app: FastAPI): # pylint: disable=redefined-outer-name # models etc. API_VERSIONS = ['v0'] - -class Metrics(): - ''' - Class to store and update various metrics - ''' - def __init__(self): - ''' - Initialize metrics dictionary and lock - ''' - self.metrics = {} - self.metrics['http_requests_total'] = 0 - self.lock = threading.Lock() - - # Various internal metrics - def update(self): - ''' - Update metrics (reserved for future use) - ''' - - def add(self, key, value): - ''' - Add a value to a metric - ''' - with self.lock: - if key not in self.metrics: - self.metrics[key] = 0 - self.metrics[key] += value - - def get(self, key): - ''' - Get the value of a metric - ''' - self.update() - with self.lock: - return self.metrics.get(key, 0) - - def all(self): - ''' - Get all the metrics - ''' - self.update() - with self.lock: - return self.metrics - - metrics = Metrics() - app = FastAPI(lifespan=lifespan, debug=True) db = Database(service=(os.getenv('MONGO_SERVICE') or 'mongodb://db:27017')) auth = Authentication(token_url="user/login") diff --git a/api/metrics.py b/api/metrics.py new file mode 100644 index 00000000..150db54a --- /dev/null +++ b/api/metrics.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# Copyright (C) 2024 Collabora Limited +# Author: enys Fedoryshchenko + +"""KernelCI API metrics module""" + +import threading + + +class Metrics(): + ''' + Class to store and update various metrics + ''' + def __init__(self): + ''' + Initialize metrics dictionary and lock + ''' + self.metrics = {} + self.metrics['http_requests_total'] = 0 + self.lock = threading.Lock() + + # Various internal metrics + def update(self): + ''' + Update metrics (reserved for future use) + ''' + + def add(self, key, value): + ''' + Add a value to a metric + ''' + with self.lock: + if key not in self.metrics: + self.metrics[key] = 0 + self.metrics[key] += value + + def get(self, key): + ''' + Get the value of a metric + ''' + self.update() + with self.lock: + return self.metrics.get(key, 0) + + def all(self): + ''' + Get all the metrics + ''' + self.update() + with self.lock: + return self.metrics