feat: add events rotation trigger to remove old events

This commit is contained in:
arcanis committed 2026-11-26 18:12:27 +02:00
1 parent c70640c492
commit 1fcb4cdb84
25 files changed
+427 -5

No files matched your search

@@ -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
@@ -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
@@ -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)
@@ -18,4 +18,5 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
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
@@ -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 <http://www.gnu.org/licenses/>.
#
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)
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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() == []
@@ -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:
"""
@@ -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)
@@ -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
@@ -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
@@ -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
@@ -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