From 1fcb4cdb840cc7c3580b0160361abd66ef6b915d Mon Sep 17 00:00:00 2001 From: Evgenii Alekseev Date: Thu, 26 Nov 2026 01:54:22 +0200 Subject: [PATCH] feat: add events rotation trigger to remove old events --- .../share/ahriman/settings/ahriman.ini | 2 + .../ahriman.ini.d/00-housekeeping.ini | 5 ++ .../database/operations/event_operations.py | 30 +++++++ .../src/ahriman/core/housekeeping/__init__.py | 1 + .../housekeeping/events_rotation_trigger.py | 85 +++++++++++++++++++ .../src/ahriman/core/status/client.py | 12 +++ .../src/ahriman/core/status/local_client.py | 9 ++ .../src/ahriman/core/status/watcher.py | 9 ++ .../src/ahriman/core/status/web_client.py | 12 +++ .../operations/test_event_operations.py | 32 +++++++ .../ahriman/core/housekeeping/conftest.py | 18 +++- .../test_events_rotation_trigger.py | 26 ++++++ .../tests/ahriman/core/status/test_client.py | 8 ++ .../ahriman/core/status/test_local_client.py | 9 ++ .../tests/ahriman/core/status/test_watcher.py | 9 ++ .../ahriman/core/status/test_web_client.py | 31 +++++++ .../src/ahriman/web/schemas/__init__.py | 1 + .../web/schemas/events_rotate_schema.py | 30 +++++++ .../ahriman/web/views/v1/auditlog/events.py | 36 +++++++- .../web/schemas/test_events_rotate_schema.py | 1 + .../auditlog/test_view_v1_auditlog_events.py | 37 +++++++- docs/ahriman.core.housekeeping.rst | 8 ++ docs/ahriman.web.schemas.rst | 8 ++ docs/configuration.rst | 8 ++ docs/triggers.rst | 5 ++ 25 files changed, 427 insertions(+), 5 deletions(-) create mode 100644 ahriman-core/src/ahriman/core/housekeeping/events_rotation_trigger.py create mode 100644 ahriman-core/tests/ahriman/core/housekeeping/test_events_rotation_trigger.py create mode 100644 ahriman-web/src/ahriman/web/schemas/events_rotate_schema.py create mode 100644 ahriman-web/tests/ahriman/web/schemas/test_events_rotate_schema.py diff --git a/ahriman-core/package/share/ahriman/settings/ahriman.ini b/ahriman-core/package/share/ahriman/settings/ahriman.ini index fd00f754..ffdad78e 100644 --- a/ahriman-core/package/share/ahriman/settings/ahriman.ini +++ b/ahriman-core/package/share/ahriman/settings/ahriman.ini @@ -60,12 +60,14 @@ triggers[] = ahriman.core.gitremote.RemotePullTrigger triggers[] = ahriman.core.report.ReportTrigger triggers[] = ahriman.core.upload.UploadTrigger triggers[] = ahriman.core.gitremote.RemotePushTrigger +triggers[] = ahriman.core.housekeeping.EventsRotationTrigger triggers[] = ahriman.core.housekeeping.LogsRotationTrigger triggers[] = ahriman.core.housekeeping.ArchiveRotationTrigger ; List of well-known triggers. Used only for configuration purposes. triggers_known[] = ahriman.core.gitremote.RemotePullTrigger triggers_known[] = ahriman.core.gitremote.RemotePushTrigger triggers_known[] = ahriman.core.housekeeping.ArchiveRotationTrigger +triggers_known[] = ahriman.core.housekeeping.EventsRotationTrigger triggers_known[] = ahriman.core.housekeeping.LogsRotationTrigger triggers_known[] = ahriman.core.report.ReportTrigger triggers_known[] = ahriman.core.upload.UploadTrigger diff --git a/ahriman-core/package/share/ahriman/settings/ahriman.ini.d/00-housekeeping.ini b/ahriman-core/package/share/ahriman/settings/ahriman.ini.d/00-housekeeping.ini index a677f3fa..955ae1e8 100644 --- a/ahriman-core/package/share/ahriman/settings/ahriman.ini.d/00-housekeeping.ini +++ b/ahriman-core/package/share/ahriman/settings/ahriman.ini.d/00-housekeeping.ini @@ -2,6 +2,11 @@ ; Keep amount of last built packages in archive. 0 means keep all packages keep_built_packages = 1 +[events-rotation] +; Keep the most recent audit events for each object. 0 removes all events. +keep_last_events = 1000 + [logs-rotation] ; Keep last build logs for each package keep_last_logs = 5 + diff --git a/ahriman-core/src/ahriman/core/database/operations/event_operations.py b/ahriman-core/src/ahriman/core/database/operations/event_operations.py index 5627b7e1..92506c81 100644 --- a/ahriman-core/src/ahriman/core/database/operations/event_operations.py +++ b/ahriman-core/src/ahriman/core/database/operations/event_operations.py @@ -106,3 +106,33 @@ class EventOperations(Operations): }) return self.with_connection(run, commit=True) + + def events_rotate(self, keep_last_records: int, repository_id: RepositoryId | None = None) -> None: + """ + rotate events in storage, keeping only the last N records for each object + + Args: + keep_last_records(int): number of last records to keep + repository_id(RepositoryId | None, optional): repository unique identifier override (Default value = None) + """ + repository_id = repository_id or self._repository_id + + def run(connection: Connection) -> None: + connection.execute( + """ + delete from auditlog + where rowid in ( + select rowid from ( + select rowid, row_number() over ( + partition by object_id order by created desc, rowid desc + ) as rn + from auditlog + where repository = :repository + ) + where rn > :keep_last_records + ) + """, + {"keep_last_records": keep_last_records, "repository": repository_id.id}, + ) + + self.with_connection(run, commit=True) diff --git a/ahriman-core/src/ahriman/core/housekeeping/__init__.py b/ahriman-core/src/ahriman/core/housekeeping/__init__.py index 4bc7500f..2f2d5221 100644 --- a/ahriman-core/src/ahriman/core/housekeeping/__init__.py +++ b/ahriman-core/src/ahriman/core/housekeeping/__init__.py @@ -18,4 +18,5 @@ # along with this program. If not, see . # from ahriman.core.housekeeping.archive_rotation_trigger import ArchiveRotationTrigger +from ahriman.core.housekeeping.events_rotation_trigger import EventsRotationTrigger from ahriman.core.housekeeping.logs_rotation_trigger import LogsRotationTrigger diff --git a/ahriman-core/src/ahriman/core/housekeeping/events_rotation_trigger.py b/ahriman-core/src/ahriman/core/housekeeping/events_rotation_trigger.py new file mode 100644 index 00000000..1ce335d0 --- /dev/null +++ b/ahriman-core/src/ahriman/core/housekeeping/events_rotation_trigger.py @@ -0,0 +1,85 @@ +# +# Copyright (c) 2021-2026 ahriman team. +# +# This file is part of ahriman +# (see https://github.com/arcan1s/ahriman). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +from ahriman.core import context +from ahriman.core.configuration import Configuration +from ahriman.core.status import Client +from ahriman.core.triggers import Trigger +from ahriman.models.package import Package +from ahriman.models.repository_id import RepositoryId +from ahriman.models.result import Result + + +class EventsRotationTrigger(Trigger): + """ + rotate events after build processes + + Attributes: + keep_last_records(int): number of last records to keep + """ + + CONFIGURATION_SCHEMA = { + "events-rotation": { + "type": "dict", + "schema": { + "keep_last_events": { + "type": "integer", + "required": True, + "coerce": "integer", + "min": 0, + }, + }, + }, + } + + def __init__(self, repository_id: RepositoryId, configuration: Configuration) -> None: + """ + Args: + repository_id(RepositoryId): repository unique identifier + configuration(Configuration): configuration instance + """ + Trigger.__init__(self, repository_id, configuration) + + section = next(iter(self.configuration_sections(configuration))) + self.keep_last_records = configuration.getint(section, "keep_last_events") + + @classmethod + def configuration_sections(cls, configuration: Configuration) -> list[str]: + """ + extract configuration sections from configuration + + Args: + configuration(Configuration): configuration instance + + Returns: + list[str]: read configuration sections belong to this trigger + """ + return list(cls.CONFIGURATION_SCHEMA.keys()) + + def on_result(self, result: Result, packages: list[Package]) -> None: + """ + run trigger + + Args: + result(Result): build result + packages(list[Package]): list of all available packages + """ + ctx = context.get() + reporter = ctx.get(Client) + reporter.events_rotate(self.keep_last_records) diff --git a/ahriman-core/src/ahriman/core/status/client.py b/ahriman-core/src/ahriman/core/status/client.py index 7b01b0de..7a60a16d 100644 --- a/ahriman-core/src/ahriman/core/status/client.py +++ b/ahriman-core/src/ahriman/core/status/client.py @@ -118,6 +118,18 @@ class Client: """ raise NotImplementedError + def events_rotate(self, keep_last_records: int) -> None: + """ + remove older events from storage + + Args: + keep_last_records(int): number of last records to keep + + Raises: + NotImplementedError: not implemented method + """ + raise NotImplementedError + def logs_rotate(self, keep_last_records: int) -> None: """ remove older logs from storage diff --git a/ahriman-core/src/ahriman/core/status/local_client.py b/ahriman-core/src/ahriman/core/status/local_client.py index 82370ce2..50d076af 100644 --- a/ahriman-core/src/ahriman/core/status/local_client.py +++ b/ahriman-core/src/ahriman/core/status/local_client.py @@ -75,6 +75,15 @@ class LocalClient(Client): """ return self.database.event_get(event, object_id, from_date, to_date, limit, offset, self.repository_id) + def events_rotate(self, keep_last_records: int) -> None: + """ + remove older events from storage + + Args: + keep_last_records(int): number of last records to keep + """ + self.database.events_rotate(keep_last_records, self.repository_id) + def logs_rotate(self, keep_last_records: int) -> None: """ remove older logs from storage diff --git a/ahriman-core/src/ahriman/core/status/watcher.py b/ahriman-core/src/ahriman/core/status/watcher.py index 485a8dde..d0237157 100644 --- a/ahriman-core/src/ahriman/core/status/watcher.py +++ b/ahriman-core/src/ahriman/core/status/watcher.py @@ -90,6 +90,15 @@ class Watcher(LazyLogging): """ return self.client.event_get(event, object_id, from_date, to_date, limit, offset) + async def events_rotate(self, keep_last_records: int) -> None: + """ + remove older events from storage + + Args: + keep_last_records(int): number of last records to keep + """ + self.client.events_rotate(keep_last_records) + async def load(self) -> None: """ load packages from local database diff --git a/ahriman-core/src/ahriman/core/status/web_client.py b/ahriman-core/src/ahriman/core/status/web_client.py index 6e6d2bf4..8c84d52d 100644 --- a/ahriman-core/src/ahriman/core/status/web_client.py +++ b/ahriman-core/src/ahriman/core/status/web_client.py @@ -218,6 +218,18 @@ class WebClient(Client, SyncAhrimanClient): return [] + def events_rotate(self, keep_last_records: int) -> None: + """ + remove older events from storage + + Args: + keep_last_records(int): number of last records to keep + """ + query = self.repository_id.query() + [("keep_last_records", str(keep_last_records))] + + with contextlib.suppress(Exception): + self.make_request("DELETE", self._events_url(), params=query) + def logs_rotate(self, keep_last_records: int) -> None: """ remove older logs from storage diff --git a/ahriman-core/tests/ahriman/core/database/operations/test_event_operations.py b/ahriman-core/tests/ahriman/core/database/operations/test_event_operations.py index 373ba29e..65004c40 100644 --- a/ahriman-core/tests/ahriman/core/database/operations/test_event_operations.py +++ b/ahriman-core/tests/ahriman/core/database/operations/test_event_operations.py @@ -38,3 +38,35 @@ def test_event_insert_get_pagination(database: SQLite) -> None: database.event_insert(Event("1", "1")) database.event_insert(Event("2", "2")) assert all(event.event == "1" for event in database.event_get(limit=1, offset=1)) + + +def test_events_rotate(database: SQLite) -> None: + """ + must keep last events for each object in repository + """ + repository_id = RepositoryId("i686", database._repository_id.name) + events = [ + Event("event 1", "object 1", created=1), + Event("event 2", "object 1", created=2), + Event("event 3", "object 2", created=3), + Event("event 4", "object 2", created=4), + ] + for event in events[:2]: + database.event_insert(event) + for event in events[2:]: + database.event_insert(event, repository_id) + + database.events_rotate(1) + assert database.event_get() == [events[1]] + assert database.event_get(repository_id=repository_id) == events[2:] + + +def test_events_rotate_remove_all(database: SQLite) -> None: + """ + must remove all events when keeping zero records + """ + database.event_insert(Event("event 1", "object 1")) + database.event_insert(Event("event 2", "object 2")) + + database.events_rotate(0) + assert database.event_get() == [] diff --git a/ahriman-core/tests/ahriman/core/housekeeping/conftest.py b/ahriman-core/tests/ahriman/core/housekeeping/conftest.py index c809f3d4..726e056a 100644 --- a/ahriman-core/tests/ahriman/core/housekeeping/conftest.py +++ b/ahriman-core/tests/ahriman/core/housekeeping/conftest.py @@ -1,7 +1,7 @@ import pytest from ahriman.core.configuration import Configuration -from ahriman.core.housekeeping import ArchiveRotationTrigger, LogsRotationTrigger +from ahriman.core.housekeeping import ArchiveRotationTrigger, EventsRotationTrigger, LogsRotationTrigger @pytest.fixture @@ -19,6 +19,22 @@ def archive_rotation_trigger(configuration: Configuration) -> ArchiveRotationTri return ArchiveRotationTrigger(repository_id, configuration) +@pytest.fixture +def events_rotation_trigger(configuration: Configuration) -> EventsRotationTrigger: + """ + events rotation trigger fixture + + Args: + configuration(Configuration): configuration fixture + + Returns: + EventsRotationTrigger: events rotation trigger test instance + """ + configuration.set_option("events-rotation", "keep_last_events", "1000") + _, repository_id = configuration.check_loaded() + return EventsRotationTrigger(repository_id, configuration) + + @pytest.fixture def logs_rotation_trigger(configuration: Configuration) -> LogsRotationTrigger: """ diff --git a/ahriman-core/tests/ahriman/core/housekeeping/test_events_rotation_trigger.py b/ahriman-core/tests/ahriman/core/housekeeping/test_events_rotation_trigger.py new file mode 100644 index 00000000..5e0f2d9d --- /dev/null +++ b/ahriman-core/tests/ahriman/core/housekeeping/test_events_rotation_trigger.py @@ -0,0 +1,26 @@ +from pytest_mock import MockerFixture +from unittest.mock import MagicMock + +from ahriman.core.configuration import Configuration +from ahriman.core.housekeeping import EventsRotationTrigger +from ahriman.core.status import Client +from ahriman.models.result import Result + + +def test_configuration_sections(configuration: Configuration) -> None: + """ + must correctly parse target list + """ + assert EventsRotationTrigger.configuration_sections(configuration) == ["events-rotation"] + + +def test_on_result(events_rotation_trigger: EventsRotationTrigger, mocker: MockerFixture) -> None: + """ + must rotate events + """ + client_mock = MagicMock() + context_mock = mocker.patch("ahriman.core._Context.get", return_value=client_mock) + + events_rotation_trigger.on_result(Result(), []) + context_mock.assert_called_once_with(Client) + client_mock.events_rotate.assert_called_once_with(events_rotation_trigger.keep_last_records) diff --git a/ahriman-core/tests/ahriman/core/status/test_client.py b/ahriman-core/tests/ahriman/core/status/test_client.py index a413e312..a4fba64a 100644 --- a/ahriman-core/tests/ahriman/core/status/test_client.py +++ b/ahriman-core/tests/ahriman/core/status/test_client.py @@ -120,6 +120,14 @@ def test_event_get(client: Client) -> None: client.event_get(None, None) +def test_events_rotate(client: Client) -> None: + """ + must raise not implemented on events rotation call + """ + with pytest.raises(NotImplementedError): + client.events_rotate(1) + + def test_logs_rotate(client: Client) -> None: """ must do not raise exception on logs rotation call diff --git a/ahriman-core/tests/ahriman/core/status/test_local_client.py b/ahriman-core/tests/ahriman/core/status/test_local_client.py index d88a9e2e..90448661 100644 --- a/ahriman-core/tests/ahriman/core/status/test_local_client.py +++ b/ahriman-core/tests/ahriman/core/status/test_local_client.py @@ -35,6 +35,15 @@ def test_event_get(local_client: LocalClient, package_ahriman: Package, mocker: local_client.repository_id) +def test_events_rotate(local_client: LocalClient, mocker: MockerFixture) -> None: + """ + must rotate events + """ + rotate_mock = mocker.patch("ahriman.core.database.SQLite.events_rotate") + local_client.events_rotate(42) + rotate_mock.assert_called_once_with(42, local_client.repository_id) + + def test_logs_rotate(local_client: LocalClient, mocker: MockerFixture) -> None: """ must rotate logs diff --git a/ahriman-core/tests/ahriman/core/status/test_watcher.py b/ahriman-core/tests/ahriman/core/status/test_watcher.py index 68ab2ce3..fc072c14 100644 --- a/ahriman-core/tests/ahriman/core/status/test_watcher.py +++ b/ahriman-core/tests/ahriman/core/status/test_watcher.py @@ -64,6 +64,15 @@ async def test_load_known(watcher: Watcher, package_ahriman: Package, mocker: Mo assert status.status == BuildStatusEnum.SUCCESS +async def test_events_rotate(watcher: Watcher, mocker: MockerFixture) -> None: + """ + must rotate events + """ + cache_mock = mocker.patch("ahriman.core.status.local_client.LocalClient.events_rotate") + await watcher.events_rotate(42) + cache_mock.assert_called_once_with(42) + + async def test_logs_rotate(watcher: Watcher, mocker: MockerFixture) -> None: """ must rotate logs diff --git a/ahriman-core/tests/ahriman/core/status/test_web_client.py b/ahriman-core/tests/ahriman/core/status/test_web_client.py index ce951deb..01b58c58 100644 --- a/ahriman-core/tests/ahriman/core/status/test_web_client.py +++ b/ahriman-core/tests/ahriman/core/status/test_web_client.py @@ -307,6 +307,37 @@ def test_event_get_failed_http_error_suppress(web_client: WebClient, mocker: Moc logging_mock.assert_not_called() +def test_events_rotate(web_client: WebClient, mocker: MockerFixture) -> None: + """ + must rotate events + """ + requests_mock = mocker.patch("ahriman.core.status.web_client.WebClient.make_request") + + web_client.events_rotate(42) + requests_mock.assert_called_once_with("DELETE", pytest.helpers.anyvar(str, True), + params=web_client.repository_id.query() + [("keep_last_records", "42")]) + + +def test_events_rotate_failed(web_client: WebClient, mocker: MockerFixture) -> None: + """ + must suppress any exception happened during events rotation + """ + mocker.patch("requests.Session.request", side_effect=Exception) + web_client.events_rotate(42) + + +def test_events_rotate_failed_suppress(web_client: WebClient, mocker: MockerFixture) -> None: + """ + must suppress any exception happened during events rotation and don't log + """ + web_client.suppress_errors = True + mocker.patch("requests.Session.request", side_effect=Exception) + logging_mock = mocker.patch("logging.exception") + + web_client.events_rotate(42) + logging_mock.assert_not_called() + + def test_logs_rotate(web_client: WebClient, mocker: MockerFixture) -> None: """ must rotate logs diff --git a/ahriman-web/src/ahriman/web/schemas/__init__.py b/ahriman-web/src/ahriman/web/schemas/__init__.py index e9de4369..8215f74c 100644 --- a/ahriman-web/src/ahriman/web/schemas/__init__.py +++ b/ahriman-web/src/ahriman/web/schemas/__init__.py @@ -31,6 +31,7 @@ from ahriman.web.schemas.error_schema import ErrorSchema from ahriman.web.schemas.event_bus_filter_schema import EventBusFilterSchema from ahriman.web.schemas.event_schema import EventSchema from ahriman.web.schemas.event_search_schema import EventSearchSchema +from ahriman.web.schemas.events_rotate_schema import EventsRotateSchema from ahriman.web.schemas.file_schema import FileSchema from ahriman.web.schemas.hold_schema import HoldSchema from ahriman.web.schemas.info_schema import InfoSchema diff --git a/ahriman-web/src/ahriman/web/schemas/events_rotate_schema.py b/ahriman-web/src/ahriman/web/schemas/events_rotate_schema.py new file mode 100644 index 00000000..92ed6c15 --- /dev/null +++ b/ahriman-web/src/ahriman/web/schemas/events_rotate_schema.py @@ -0,0 +1,30 @@ +# +# Copyright (c) 2021-2026 ahriman team. +# +# This file is part of ahriman +# (see https://github.com/arcan1s/ahriman). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +from ahriman.web.apispec import Schema, fields + + +class EventsRotateSchema(Schema): + """ + request events rotate schema + """ + + keep_last_records = fields.Integer(metadata={ + "description": "Keep the specified amount of events for each object", + }) diff --git a/ahriman-web/src/ahriman/web/views/v1/auditlog/events.py b/ahriman-web/src/ahriman/web/views/v1/auditlog/events.py index 9d76b731..e7b7a1f8 100644 --- a/ahriman-web/src/ahriman/web/views/v1/auditlog/events.py +++ b/ahriman-web/src/ahriman/web/views/v1/auditlog/events.py @@ -23,7 +23,7 @@ from typing import ClassVar from ahriman.models.event import Event from ahriman.models.user_access import UserAccess from ahriman.web.apispec.decorators import apidocs -from ahriman.web.schemas import EventSchema, EventSearchSchema +from ahriman.web.schemas import EventSchema, EventSearchSchema, EventsRotateSchema from ahriman.web.views.base import BaseView @@ -32,13 +32,40 @@ class EventsView(BaseView): audit log view Attributes: + DELETE_PERMISSION(UserAccess): (class attribute) delete permissions of self GET_PERMISSION(UserAccess): (class attribute) get permissions of self POST_PERMISSION(UserAccess): (class attribute) post permissions of self """ - GET_PERMISSION = POST_PERMISSION = UserAccess.FULL # type: ClassVar[UserAccess] + DELETE_PERMISSION = GET_PERMISSION = POST_PERMISSION = UserAccess.FULL # type: ClassVar[UserAccess] ROUTES = ["/api/v1/events"] + @apidocs( + tags=["Audit log"], + summary="Rotate audit events", + description="Remove older events from the selected repository", + permission=DELETE_PERMISSION, + error_400_enabled=True, + error_404_description="Repository is unknown", + query_schema=EventsRotateSchema, + ) + async def delete(self) -> None: + """ + rotate events in storage + + Raises: + HTTPBadRequest: if bad data is supplied + HTTPNoContent: on success response + """ + try: + keep_last_records = int(self.request.query.get("keep_last_records", 0)) + except Exception as ex: + raise HTTPBadRequest(reason=str(ex)) + + await self.service().events_rotate(keep_last_records) + + raise HTTPNoContent + @apidocs( tags=["Audit log"], summary="Get events", @@ -53,7 +80,10 @@ class EventsView(BaseView): get events list Returns: - Response: 200 with workers list on success + Response: 200 with events list on success + + Raises: + HTTPBadRequest: if bad data is supplied """ limit, offset = self.page() event = self.request.query.get("event") or None diff --git a/ahriman-web/tests/ahriman/web/schemas/test_events_rotate_schema.py b/ahriman-web/tests/ahriman/web/schemas/test_events_rotate_schema.py new file mode 100644 index 00000000..1982fb6b --- /dev/null +++ b/ahriman-web/tests/ahriman/web/schemas/test_events_rotate_schema.py @@ -0,0 +1 @@ +# schema testing goes in view class tests diff --git a/ahriman-web/tests/ahriman/web/views/v1/auditlog/test_view_v1_auditlog_events.py b/ahriman-web/tests/ahriman/web/views/v1/auditlog/test_view_v1_auditlog_events.py index 026ea3fa..27bd8627 100644 --- a/ahriman-web/tests/ahriman/web/views/v1/auditlog/test_view_v1_auditlog_events.py +++ b/ahriman-web/tests/ahriman/web/views/v1/auditlog/test_view_v1_auditlog_events.py @@ -11,7 +11,7 @@ async def test_get_permission() -> None: """ must return correct permission for the request """ - for method in ("GET", "POST"): + for method in ("GET", "POST", "DELETE"): request = pytest.helpers.request("", "", method) assert await EventsView.get_permission(request) == UserAccess.FULL @@ -23,6 +23,41 @@ def test_routes() -> None: assert EventsView.ROUTES == ["/api/v1/events"] +async def test_delete(client: TestClient) -> None: + """ + must rotate events keeping last record for each object + """ + events = [ + Event("event1", "object1", created=1), + Event("event2", "object1", created=2), + Event("event3", "object2", created=3), + Event("event4", "object2", created=4), + ] + for event in events: + await client.post("/api/v1/events", json=event.view()) + + request_schema = pytest.helpers.schema_request(EventsView.delete, location="querystring") + payload = {"keep_last_records": 1} + assert not request_schema.validate(payload) + + response = await client.delete("/api/v1/events", params=payload) + assert response.status == 204 + + response = await client.get("/api/v1/events") + assert [Event.from_json(event) for event in await response.json()] == [events[1], events[3]] + + +async def test_delete_bad_request(client: TestClient) -> None: + """ + must return bad request for invalid query parameters + """ + response_schema = pytest.helpers.schema_response(EventsView.delete, code=400) + + response = await client.delete("/api/v1/events", params={"keep_last_records": "invalid"}) + assert response.status == 400 + assert not response_schema.validate(await response.json()) + + async def test_get(client: TestClient) -> None: """ must return all events diff --git a/docs/ahriman.core.housekeeping.rst b/docs/ahriman.core.housekeeping.rst index 5b69d920..bae0dc55 100644 --- a/docs/ahriman.core.housekeeping.rst +++ b/docs/ahriman.core.housekeeping.rst @@ -12,6 +12,14 @@ ahriman.core.housekeeping.archive\_rotation\_trigger module :no-undoc-members: :show-inheritance: +ahriman.core.housekeeping.events\_rotation\_trigger module +---------------------------------------------------------- + +.. automodule:: ahriman.core.housekeeping.events_rotation_trigger + :members: + :no-undoc-members: + :show-inheritance: + ahriman.core.housekeeping.logs\_rotation\_trigger module -------------------------------------------------------- diff --git a/docs/ahriman.web.schemas.rst b/docs/ahriman.web.schemas.rst index 4c2f4399..2af1fe14 100644 --- a/docs/ahriman.web.schemas.rst +++ b/docs/ahriman.web.schemas.rst @@ -116,6 +116,14 @@ ahriman.web.schemas.event\_search\_schema module :no-undoc-members: :show-inheritance: +ahriman.web.schemas.events\_rotate\_schema module +------------------------------------------------- + +.. automodule:: ahriman.web.schemas.events_rotate_schema + :members: + :no-undoc-members: + :show-inheritance: + ahriman.web.schemas.file\_schema module --------------------------------------- diff --git a/docs/configuration.rst b/docs/configuration.rst index fc5fa643..dff193a9 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -209,6 +209,14 @@ Describes settings for packages archives management extensions. * ``keep_built_packages`` - keep this amount of additional built package versions alongside the version currently published in the repository, integer, required. ``0`` will effectively disable archives removal. +``events-rotation`` group +------------------------- + +This section describes settings for the ``ahriman.core.housekeeping.EventsRotationTrigger`` plugin. + +* ``keep_last_events`` - amount of audit events to keep for each object, integer, required. Older events are removed at the end of each process; ``0`` removes all events. + + ``keyring`` group ----------------- diff --git a/docs/triggers.rst b/docs/triggers.rst index 6f60ae5f..0f02e0e4 100644 --- a/docs/triggers.rst +++ b/docs/triggers.rst @@ -51,6 +51,11 @@ This trigger removes old package versions from the archive directory. It impleme Simple trigger to rotate build logs. It implements ``on_result`` and removes old log records after each build process, keeping only the last N records as configured by ``keep_last_logs`` option. +``ahriman.core.housekeeping.EventsRotationTrigger`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Trigger to rotate audit events. It implements ``on_result`` and keeps the last N events for each object, as configured by ``keep_last_events``. + ``ahriman.core.report.ReportTrigger`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^