bootstrap

This commit is contained in:
Ilgiz Kalmetyev 2026-04-05 17:54:51 +05:00
commit 9b0b4d7c0c
26 changed files with 1979 additions and 0 deletions

1
.codex/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
tmp/

37
.gitignore vendored Normal file
View File

@ -0,0 +1,37 @@
# Python bytecode and caches
__pycache__/
*.py[cod]
*$py.class
# Test and tool caches
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
htmlcov/
# Packaging and build outputs
build/
dist/
*.egg-info/
# Virtual environments
.venv/
venv/
env/
# Runtime state and logs
/state/
*.sqlite
*.sqlite3
*.db
*.log
*.pid
# Repo-local temporary files
.codex/tmp/
write-test.txt
# Editor settings
.idea/
.vscode/

104
README.md Normal file
View File

@ -0,0 +1,104 @@
# Journal Event Collector
## Summary
`journal-event-collector` is a Linux application that reads journal messages from configured process names, turns them into events, caches them with expiry, and exposes the shared core through a REST API and a CLI.
The project is built around one core layer with thin adapters for the daemon runtime, API, and CLI. Active events live in memory, while persisted snapshots are stored in SQLite so local and remote inspection can read the same state.
## Architecture
The application follows a `core + adapters` layout:
1. `ApplicationCore` manages lifecycle, cache, collector loop, cleanup, and persistence.
2. `JournalctlReader` reads JSON journal entries from `journalctl` and feeds them into the core.
3. `EventCache` stores active events in memory and removes expired entries.
4. `StateStore` persists snapshots in SQLite and migrates legacy JSON state to SQLite when needed.
5. REST API and CLI are thin adapters over the same core.
Data flow:
`journalctl -> journal reader -> event builder -> in-memory cache -> SQLite snapshot -> REST/CLI`
## Structure
```text
.
├── deployment-guide.md
├── journal-event-collector/
│ └── example-config.toml
├── README.md
├── src/
│ └── journal_event_collector/
│ ├── api.py
│ ├── cache.py
│ ├── cli.py
│ ├── config.py
│ ├── journal.py
│ ├── models.py
│ ├── runtime.py
│ ├── service.py
│ └── state.py
├── systemd/
│ └── journal-event-collector.service
├── tests/
│ └── ...
└── usage-guide.md
```
## Components
### `config.py`
- Loads TOML configuration.
- Validates required fields.
- Normalizes monitored process names, cache timing, API settings, and SQLite state file path.
### `journal.py`
- Launches `journalctl`.
- Reads JSON journal records.
- Filters entries by configured process names.
- Builds domain events from journal entries.
### `models.py`
- Defines `JournalEvent` and `ServiceStatus`.
- Keeps the shared data shape used by API, CLI, and persistence.
### `cache.py`
- Stores active events in memory.
- Removes expired events by TTL.
- Produces snapshots for publication and persistence.
### `state.py`
- Writes persisted snapshots to SQLite.
- Reads persisted snapshots for CLI and REST.
- Migrates legacy JSON state files to SQLite.
### `service.py`
- Orchestrates collector, cleanup, and persistence.
- Exposes `status()`, `events()`, and `persisted_snapshot()`.
### `runtime.py`
- Starts the REST API with `uvicorn`.
- Binds daemon lifecycle to the core.
### `api.py`
- Exposes `/health`, `/status`, `/events`, and `/state`.
- Returns live status and persisted snapshot data.
### `cli.py`
- Provides `run`, `status`, `events`, and `state`.
- Can read local persisted state or query a remote REST API.
## Key Decisions
1. One core for all interfaces. This avoids logic drift between daemon, REST, and CLI.
2. In-memory cache for live data. This keeps event handling simple and fast.
3. SQLite for persisted snapshots. This lets API and CLI read the same state without an external service.
4. Legacy JSON migration to SQLite. Old files are converted in place on startup.
5. Explicit virtualenv execution for `systemd`. The unit points directly to `.venv/bin/journal-event-collector`.
6. `GET /state` returns persisted snapshot directly rather than a copy of live cache.
## References
- [Deployment Guide](./deployment-guide.md)
- [Usage Guide](./usage-guide.md)

96
deployment-guide.md Normal file
View File

@ -0,0 +1,96 @@
# Deployment Guide
## Overview
This guide describes how to deploy `journal-event-collector` on Linux with Python virtualenv support and `systemd`.
The recommended layout is:
1. Application checkout: `/opt/journal-event-collector`
2. Virtual environment: `/opt/journal-event-collector/.venv`
3. Configuration file: `/etc/journal-event-collector/config.toml`
4. SQLite persisted state: `/var/lib/journal-event-collector/journal-event-collector.sqlite`
## Prerequisites
1. Linux host with `systemd`
2. Python 3.12 or newer
3. Access to `journalctl`
4. A user account with permission to read the journal and manage the service
## Install
1. Create the application directory and place the repository there.
2. Create a virtual environment in the repository root.
3. Install the project into the virtual environment.
```bash
cd /opt/journal-event-collector
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e .
```
## Configure
1. Create the service config directory.
2. Copy or adapt the example config from `journal-event-collector/example-config.toml`.
3. Set monitored process names, REST binding, journal command, and the SQLite state file.
Example:
```toml
[application]
monitored_process_names = ["sshd", "cron"]
event_ttl_seconds = 300
cleanup_interval_seconds = 30
log_level = "info"
[api]
host = "127.0.0.1"
port = 8000
[journal]
command = ["journalctl", "-f", "-o", "json"]
[storage]
state_file = "/var/lib/journal-event-collector/journal-event-collector.sqlite"
```
4. Ensure the state directory exists and is writable by the service account.
```bash
sudo mkdir -p /etc/journal-event-collector
sudo mkdir -p /var/lib/journal-event-collector
```
## Install systemd Unit
1. Copy the unit file into `/etc/systemd/system`.
2. Adjust `WorkingDirectory`, `VIRTUAL_ENV`, `PATH`, and `ExecStart` if your deployment path differs from `/opt/journal-event-collector`.
3. Reload `systemd` and enable the service.
```bash
sudo cp systemd/journal-event-collector.service /etc/systemd/system/journal-event-collector.service
sudo systemctl daemon-reload
sudo systemctl enable --now journal-event-collector
```
## Verify
1. Check service status.
2. Inspect logs if the service does not start.
3. Confirm the REST API is listening on the configured host and port.
```bash
systemctl status journal-event-collector
journalctl -u journal-event-collector -f
```
## Notes
1. The sample unit runs the application from `/opt/journal-event-collector/.venv/bin/journal-event-collector`.
2. `systemd` does not activate a Python virtualenv automatically, so the unit must point directly to the venv binary.
3. If a legacy JSON state file exists at the configured `state_file` path, the application migrates it in place to SQLite on startup.
4. If you run the service as a non-root user, make sure that user can read the journal and write the configured SQLite file.

View File

@ -0,0 +1,15 @@
[application]
monitored_process_names = ["sshd", "cron"]
event_ttl_seconds = 300
cleanup_interval_seconds = 30
log_level = "info"
[api]
host = "127.0.0.1"
port = 8000
[journal]
command = ["journalctl", "-f", "-o", "json"]
[storage]
state_file = "./state/journal-event-collector.sqlite"

View File

@ -0,0 +1,87 @@
# Requirements Document
## Introduction
This feature defines a Linux daemon that monitors configured journal sources by process name, turns matching journal messages into application events, caches those events for a configurable retention period, and exposes the shared functionality through both a REST API and a CLI. The application is intended to run under `systemd` and uses a common application core for all interfaces.
## Requirements
### Requirement 1: Configure monitored journal sources
**User Story:** As an operator, I want to configure which process names are monitored, so that the daemon collects only relevant journal messages.
#### Acceptance Criteria
1. WHEN the application starts with a valid configuration file or equivalent configuration source THEN the system SHALL load the configured process names and journal settings before starting event collection.
2. IF the configuration is missing required values or contains invalid values THEN the system SHALL fail startup with a clear error that identifies the invalid setting.
3. WHEN the monitored process-name list is updated and the application is restarted THEN the system SHALL use the updated configuration for subsequent journal collection.
4. WHERE configuration values affect both the REST API and CLI THEN the system SHALL resolve them through the same shared application core.
### Requirement 2: Run as a Linux daemon under systemd
**User Story:** As an operator, I want the application to run as a Linux daemon managed by `systemd`, so that it can start automatically and remain available continuously.
#### Acceptance Criteria
1. WHEN the service is started by `systemd` THEN the application SHALL run in a long-lived daemon mode suitable for process supervision.
2. WHEN the application exits normally or abnormally THEN the system SHALL provide a non-interactive exit status that `systemd` can use to determine service health.
3. WHEN the service is stopped THEN the application SHALL shut down gracefully and stop journal collection and cache activity in an orderly manner.
4. IF the runtime environment is not Linux or does not provide `systemd` integration support THEN the system SHALL report that the daemon deployment target is unsupported.
### Requirement 3: Collect matching journal messages as events
**User Story:** As a user, I want matching journal messages to be captured as application events, so that relevant process activity is available for later retrieval.
#### Acceptance Criteria
1. WHEN a journal message is received from a configured process name THEN the system SHALL create an event record from the message.
2. WHEN a journal message does not match any configured process name THEN the system SHALL ignore the message for event creation.
3. WHEN an event is created THEN the system SHALL preserve at least the source process name, message payload, and capture timestamp.
4. WHILE journal collection is running THEN the system SHALL continue processing new messages without requiring manual restart after each event.
5. IF a journal entry cannot be parsed or read THEN the system SHALL log the failure and continue processing subsequent journal messages.
### Requirement 4: Cache collected events with configurable expiry
**User Story:** As a user, I want collected events to be cached and removed on a configurable schedule, so that stored data stays current and bounded.
#### Acceptance Criteria
1. WHEN an event is created THEN the system SHALL store it in the cache before making it available to API or CLI consumers.
2. WHEN an event reaches its configured expiration time THEN the system SHALL remove it from the cache.
3. IF the expiration schedule is configured THEN the system SHALL apply the configured retention and cleanup timing to cached events.
4. WHEN the cache cleanup process runs THEN the system SHALL not remove events that have not yet reached expiration.
5. IF cache storage is unavailable or fails THEN the system SHALL report an error and preserve the integrity of already cached events where possible.
### Requirement 5: Expose cached events through a REST API
**User Story:** As a consumer, I want to query cached events through a REST API, so that other systems can read collected journal data programmatically.
#### Acceptance Criteria
1. WHEN the REST API receives a request for cached events THEN the system SHALL return the currently retained events from the shared cache.
2. WHEN the REST API receives a request for application status THEN the system SHALL return the daemon and collection status from the shared application core.
3. WHEN the REST API receives a request with invalid parameters THEN the system SHALL respond with a client error that describes the validation problem.
4. WHEN cached events are expired or removed THEN the REST API SHALL no longer return those events in retrieval responses.
5. WHERE REST API behavior depends on event data or cache state THEN the system SHALL use the same core logic as the daemon and CLI interfaces.
### Requirement 6: Provide CLI access to shared application functions
**User Story:** As an operator, I want to use a CLI to access the same application functions, so that the system can be managed and inspected without the REST API.
#### Acceptance Criteria
1. WHEN the CLI invokes a supported command THEN the system SHALL perform the command by calling the shared application core.
2. WHEN the CLI receives invalid arguments or options THEN the system SHALL display a usage error and exit with a non-zero status.
3. WHEN the CLI requests event or status information THEN the system SHALL return the same underlying data that the REST API exposes.
4. WHERE the CLI and REST API share a function THEN the system SHALL implement the function once in the application core and reuse it from both interfaces.
### Requirement 7: Handle operational failures safely
**User Story:** As an operator, I want the application to handle runtime failures safely, so that transient issues do not corrupt event data or stop the daemon unnecessarily.
#### Acceptance Criteria
1. WHEN a transient journal access failure occurs THEN the system SHALL log the error and continue running if recovery is possible.
2. WHEN a fatal configuration or startup error occurs THEN the system SHALL stop startup and return a clear failure reason.
3. IF repeated collection or cache failures occur THEN the system SHALL surface the problem through logs and status responses.
4. WHEN the application encounters recoverable errors THEN the system SHALL continue serving unaffected API and CLI requests where possible.

27
pyproject.toml Normal file
View File

@ -0,0 +1,27 @@
[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "journal-event-collector"
version = "0.1.0"
description = "Linux journal event collector with REST API and CLI"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"typer>=0.12",
"uvicorn[standard]>=0.30",
]
[project.scripts]
journal-event-collector = "journal_event_collector.cli:app"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]

View File

@ -0,0 +1,6 @@
"""Journal event collector application package."""
from .config import AppConfig, ConfigError
from .models import JournalEvent, ServiceStatus
__all__ = ["AppConfig", "ConfigError", "JournalEvent", "ServiceStatus"]

View File

@ -0,0 +1,82 @@
from __future__ import annotations
from contextlib import asynccontextmanager
from datetime import datetime
from typing import Any, Iterable
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ConfigDict
from .models import JournalEvent
from .service import ApplicationCore
class EventResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
process_name: str
message: str
captured_at: datetime
payload: dict[str, Any]
class StatusResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
running: bool
started_at: datetime | None
monitored_process_names: list[str]
cached_events: int
event_ttl_seconds: int
cleanup_interval_seconds: int
last_error: str | None
class StateSnapshotResponse(BaseModel):
status: dict[str, Any]
events: list[EventResponse]
updated_at: str
def create_app(core: ApplicationCore, manage_lifecycle: bool = False) -> FastAPI:
@asynccontextmanager
async def lifespan(_: FastAPI):
if manage_lifecycle:
core.start()
try:
yield
finally:
if manage_lifecycle:
core.stop()
app = FastAPI(title="journal-event-collector", lifespan=lifespan if manage_lifecycle else None)
@app.get("/health")
def health() -> dict[str, str]:
return {"status": "ok" if core.last_error is None else "degraded"}
@app.get("/status", response_model=StatusResponse)
def status() -> StatusResponse:
return StatusResponse.model_validate(core.status().to_dict())
@app.get("/events", response_model=list[EventResponse])
def events() -> list[EventResponse]:
return [EventResponse.model_validate(event.to_dict()) for event in core.events()]
@app.get("/state", response_model=StateSnapshotResponse)
def state() -> StateSnapshotResponse:
snapshot = core.persisted_snapshot()
if snapshot is None:
raise HTTPException(status_code=404, detail="state snapshot is not available")
return StateSnapshotResponse(
status=snapshot.status,
events=[EventResponse.model_validate(event) for event in snapshot.events],
updated_at=snapshot.updated_at,
)
return app
def serialize_events(events: Iterable[JournalEvent]) -> list[dict[str, Any]]:
return [event.to_dict() for event in events]

View File

@ -0,0 +1,52 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from threading import RLock
from typing import Callable, Iterable
from .models import JournalEvent, utc_now
@dataclass(slots=True)
class CacheRecord:
event: JournalEvent
expires_at: datetime
class EventCache:
def __init__(self) -> None:
self._records: dict[str, CacheRecord] = {}
self._lock = RLock()
def put(
self,
event: JournalEvent,
ttl_seconds: int,
now: Callable[[], datetime] = utc_now,
) -> None:
expires_at = now() + timedelta(seconds=ttl_seconds)
with self._lock:
self._records[event.id] = CacheRecord(event=event, expires_at=expires_at)
def purge_expired(self, now: Callable[[], datetime] = utc_now) -> int:
current = now()
removed = 0
with self._lock:
expired_ids = [event_id for event_id, record in self._records.items() if record.expires_at <= current]
for event_id in expired_ids:
removed += 1
self._records.pop(event_id, None)
return removed
def list_events(self, now: Callable[[], datetime] = utc_now) -> list[JournalEvent]:
self.purge_expired(now=now)
with self._lock:
events = [record.event for record in self._records.values()]
return sorted(events, key=lambda event: event.captured_at, reverse=True)
def count(self, now: Callable[[], datetime] = utc_now) -> int:
return len(self.list_events(now=now))
def snapshot(self, now: Callable[[], datetime] = utc_now) -> list[dict]:
return [event.to_dict() for event in self.list_events(now=now)]

View File

@ -0,0 +1,144 @@
from __future__ import annotations
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import urlopen
import json
import typer
from .config import AppConfig, ConfigError
from .journal import NullJournalReader
from .runtime import ApplicationRuntime
from .service import ApplicationCore
from .state import StateStore
app = typer.Typer(help="Journal event collector")
def _load_config(config: Path) -> AppConfig:
try:
return AppConfig.from_file(config)
except (OSError, ConfigError) as exc:
raise typer.BadParameter(str(exc)) from exc
def _print_json(payload) -> None:
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2, default=str))
def _fetch_json(url: str):
try:
with urlopen(url) as response:
return json.load(response)
except (HTTPError, URLError) as exc:
raise typer.Exit(code=2) from exc
def _print_local_state(settings: AppConfig, fallback: str) -> bool:
if settings.state_file is None:
return False
snapshot = StateStore(settings.state_file).read()
if snapshot is None:
return False
if fallback == "status":
_print_json(snapshot.status)
return True
if fallback == "events":
_print_json(snapshot.events)
return True
if fallback == "state":
_print_json(
{
"status": snapshot.status,
"events": snapshot.events,
"updated_at": snapshot.updated_at,
}
)
return True
return False
@app.command()
def run(config: Path = typer.Option(..., exists=True, readable=True, help="Path to the TOML config file")) -> None:
"""Run the collector and REST API as a daemon."""
settings = _load_config(config)
runtime = ApplicationRuntime(settings)
raise typer.Exit(code=runtime.run())
@app.command()
def status(
config: Path | None = typer.Option(None, exists=True, readable=True, help="Optional config for local status"),
api_base_url: str | None = typer.Option(None, help="REST API base URL"),
) -> None:
"""Show the current service status."""
if api_base_url:
payload = _fetch_json(f"{api_base_url.rstrip('/')}/status")
_print_json(payload)
return
if config is None:
raise typer.BadParameter("either --config or --api-base-url is required")
settings = _load_config(config)
if _print_local_state(settings, "status"):
return
core = ApplicationCore(settings, reader=NullJournalReader())
_print_json(core.status().to_dict())
@app.command()
def events(
config: Path | None = typer.Option(None, exists=True, readable=True, help="Optional config for local events"),
api_base_url: str | None = typer.Option(None, help="REST API base URL"),
) -> None:
"""Show collected events."""
if api_base_url:
payload = _fetch_json(f"{api_base_url.rstrip('/')}/events")
_print_json(payload)
return
if config is None:
raise typer.BadParameter("either --config or --api-base-url is required")
settings = _load_config(config)
if _print_local_state(settings, "events"):
return
core = ApplicationCore(settings, reader=NullJournalReader())
_print_json(core.cache.snapshot())
@app.command()
def state(
config: Path | None = typer.Option(None, exists=True, readable=True, help="Optional config for local state"),
api_base_url: str | None = typer.Option(None, help="REST API base URL"),
) -> None:
"""Show the persisted snapshot."""
if api_base_url:
payload = _fetch_json(f"{api_base_url.rstrip('/')}/state")
_print_json(payload)
return
if config is None:
raise typer.BadParameter("either --config or --api-base-url is required")
settings = _load_config(config)
if _print_local_state(settings, "state"):
return
core = ApplicationCore(settings, reader=NullJournalReader())
snapshot = core.persisted_snapshot()
if snapshot is None:
raise typer.Exit(code=1)
_print_json(
{
"status": snapshot.status,
"events": snapshot.events,
"updated_at": snapshot.updated_at,
}
)

View File

@ -0,0 +1,123 @@
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Mapping
import tomllib
class ConfigError(ValueError):
"""Raised when the application configuration is invalid."""
def _require_str_list(value: Any, field_name: str) -> list[str]:
if not isinstance(value, list) or not value:
raise ConfigError(f"{field_name} must be a non-empty list of process names")
result: list[str] = []
seen: set[str] = set()
for item in value:
if not isinstance(item, str) or not item.strip():
raise ConfigError(f"{field_name} must contain only non-empty strings")
normalized = item.strip()
key = normalized.casefold()
if key in seen:
continue
seen.add(key)
result.append(normalized)
if not result:
raise ConfigError(f"{field_name} must contain at least one process name")
return result
def _require_positive_int(value: Any, field_name: str) -> int:
try:
parsed = int(value)
except (TypeError, ValueError) as exc:
raise ConfigError(f"{field_name} must be a positive integer") from exc
if parsed <= 0:
raise ConfigError(f"{field_name} must be a positive integer")
return parsed
@dataclass(slots=True)
class AppConfig:
monitored_process_names: list[str]
event_ttl_seconds: int = 300
cleanup_interval_seconds: int = 60
api_host: str = "127.0.0.1"
api_port: int = 8000
journal_command: list[str] = field(default_factory=lambda: ["journalctl", "-f", "-o", "json"])
log_level: str = "info"
state_file: Path | None = None
@classmethod
def from_mapping(cls, raw: Mapping[str, Any], *, base_path: Path | None = None) -> "AppConfig":
app_section = raw.get("application", raw)
api_section = raw.get("api", {})
journal_section = raw.get("journal", {})
storage_section = raw.get("storage", {})
if not isinstance(app_section, Mapping):
raise ConfigError("application section must be a mapping")
if not isinstance(api_section, Mapping):
raise ConfigError("api section must be a mapping")
if not isinstance(journal_section, Mapping):
raise ConfigError("journal section must be a mapping")
if storage_section and not isinstance(storage_section, Mapping):
raise ConfigError("storage section must be a mapping")
monitored_process_names = _require_str_list(
app_section.get("monitored_process_names"), "monitored_process_names"
)
event_ttl_seconds = _require_positive_int(
app_section.get("event_ttl_seconds", 300), "event_ttl_seconds"
)
cleanup_interval_seconds = _require_positive_int(
app_section.get("cleanup_interval_seconds", 60), "cleanup_interval_seconds"
)
api_host = str(api_section.get("host", "127.0.0.1")).strip() or "127.0.0.1"
api_port = _require_positive_int(api_section.get("port", 8000), "api.port")
if not 1 <= api_port <= 65535:
raise ConfigError("api.port must be between 1 and 65535")
journal_command_value = journal_section.get("command", ["journalctl", "-f", "-o", "json"])
if not isinstance(journal_command_value, list) or not journal_command_value:
raise ConfigError("journal.command must be a non-empty list")
journal_command: list[str] = []
for item in journal_command_value:
if not isinstance(item, str) or not item.strip():
raise ConfigError("journal.command must contain only non-empty strings")
journal_command.append(item.strip())
log_level = str(app_section.get("log_level", "info")).strip() or "info"
state_file_value = storage_section.get("state_file") if isinstance(storage_section, Mapping) else None
state_file: Path | None = None
if state_file_value is not None:
if not isinstance(state_file_value, str) or not state_file_value.strip():
raise ConfigError("storage.state_file must be a non-empty string")
state_file = Path(state_file_value.strip())
if not state_file.is_absolute() and base_path is not None:
state_file = (base_path / state_file).resolve()
return cls(
monitored_process_names=monitored_process_names,
event_ttl_seconds=event_ttl_seconds,
cleanup_interval_seconds=cleanup_interval_seconds,
api_host=api_host,
api_port=api_port,
journal_command=journal_command,
log_level=log_level,
state_file=state_file,
)
@classmethod
def from_file(cls, path: str | Path) -> "AppConfig":
config_path = Path(path)
with config_path.open("rb") as handle:
raw = tomllib.load(handle)
if not isinstance(raw, Mapping):
raise ConfigError("configuration file must contain a mapping")
return cls.from_mapping(raw, base_path=config_path.parent)

View File

@ -0,0 +1,148 @@
from __future__ import annotations
from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass
from datetime import datetime, timezone
import json
import logging
import selectors
import subprocess
import sys
import threading
from typing import Any, Protocol
from .models import JournalEvent
class JournalReader(Protocol):
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]:
...
class NullJournalReader:
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]:
while not stop_event.is_set():
stop_event.wait(0.5)
if stop_event.is_set():
break
yield from ()
@dataclass(slots=True)
class JournalctlReader:
command: list[str]
logger: logging.Logger | None = None
def stream(self, stop_event: threading.Event) -> Iterator[Mapping[str, Any]]:
if sys.platform != "linux":
raise RuntimeError("journal daemon mode is only supported on Linux")
log = self.logger or logging.getLogger(__name__)
try:
process = subprocess.Popen(
self.command,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
bufsize=1,
)
except FileNotFoundError as exc:
raise RuntimeError("journalctl command was not found") from exc
if process.stdout is None:
raise RuntimeError("journalctl did not provide stdout")
selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ)
try:
while not stop_event.is_set():
ready = selector.select(timeout=0.5)
if not ready:
if process.poll() is not None:
break
continue
line = process.stdout.readline()
if line == "":
if process.poll() is not None:
break
continue
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
except json.JSONDecodeError as exc:
log.warning("Skipping unparsable journal entry: %s", exc)
continue
if isinstance(entry, Mapping):
yield entry
finally:
selector.close()
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
def extract_process_name(entry: Mapping[str, Any]) -> str | None:
for key in ("_COMM", "COMM", "SYSLOG_IDENTIFIER", "process_name", "process", "name"):
value = entry.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def extract_message(entry: Mapping[str, Any]) -> str:
value = entry.get("MESSAGE")
if value is None:
value = entry.get("message")
if value is None:
return ""
if isinstance(value, str):
return value
return str(value)
def extract_timestamp(entry: Mapping[str, Any]) -> datetime:
raw_value = entry.get("__REALTIME_TIMESTAMP")
if raw_value is None:
raw_value = entry.get("timestamp")
if isinstance(raw_value, datetime):
return raw_value if raw_value.tzinfo else raw_value.replace(tzinfo=timezone.utc)
if isinstance(raw_value, (int, float)):
seconds = float(raw_value)
if seconds > 1_000_000_000_000:
seconds = seconds / 1_000_000
return datetime.fromtimestamp(seconds, tz=timezone.utc)
if isinstance(raw_value, str) and raw_value.strip():
text = raw_value.strip().replace("Z", "+00:00")
try:
parsed = datetime.fromisoformat(text)
except ValueError:
return datetime.now(timezone.utc)
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
return datetime.now(timezone.utc)
def build_event(
entry: Mapping[str, Any],
monitored_process_names: Iterable[str],
) -> JournalEvent | None:
process_name = extract_process_name(entry)
if process_name is None:
return None
allowed_names = {name.casefold() for name in monitored_process_names}
if process_name.casefold() not in allowed_names:
return None
message = extract_message(entry)
captured_at = extract_timestamp(entry)
return JournalEvent.create(
process_name=process_name,
message=message,
captured_at=captured_at,
payload=entry,
)

View File

@ -0,0 +1,62 @@
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from typing import Any, Mapping
import uuid
def utc_now() -> datetime:
return datetime.now(timezone.utc)
@dataclass(slots=True)
class JournalEvent:
id: str
process_name: str
message: str
captured_at: datetime
payload: dict[str, Any] = field(default_factory=dict)
@classmethod
def create(
cls,
process_name: str,
message: str,
captured_at: datetime | None = None,
payload: Mapping[str, Any] | None = None,
) -> "JournalEvent":
return cls(
id=str(uuid.uuid4()),
process_name=process_name,
message=message,
captured_at=captured_at or utc_now(),
payload=dict(payload or {}),
)
def to_dict(self) -> dict[str, Any]:
data = asdict(self)
data["captured_at"] = self.captured_at.isoformat()
return data
@dataclass(slots=True)
class ServiceStatus:
running: bool
started_at: datetime | None
monitored_process_names: list[str]
cached_events: int
event_ttl_seconds: int
cleanup_interval_seconds: int
last_error: str | None = None
def to_dict(self) -> dict[str, Any]:
return {
"running": self.running,
"started_at": self.started_at.isoformat() if self.started_at else None,
"monitored_process_names": list(self.monitored_process_names),
"cached_events": self.cached_events,
"event_ttl_seconds": self.event_ttl_seconds,
"cleanup_interval_seconds": self.cleanup_interval_seconds,
"last_error": self.last_error,
}

View File

@ -0,0 +1,30 @@
from __future__ import annotations
import logging
import uvicorn
from .api import create_app
from .config import AppConfig
from .journal import JournalctlReader
from .service import ApplicationCore
class ApplicationRuntime:
def __init__(self, config: AppConfig, reader=None) -> None:
self.config = config
self.logger = logging.getLogger(__name__)
self.core = ApplicationCore(config, reader=reader or JournalctlReader(config.journal_command, logger=self.logger), logger=self.logger)
def run(self) -> int:
self.core.start()
try:
uvicorn.run(
create_app(self.core, manage_lifecycle=False),
host=self.config.api_host,
port=self.config.api_port,
log_level=self.config.log_level.lower(),
)
finally:
self.core.stop()
return 1 if self.core.last_error else 0

View File

@ -0,0 +1,154 @@
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from datetime import datetime, timezone
import logging
import threading
from typing import Any
from .cache import EventCache
from .config import AppConfig
from .journal import JournalReader, JournalctlReader, NullJournalReader, build_event
from .models import JournalEvent, ServiceStatus
from .state import StateStore
def utc_now() -> datetime:
return datetime.now(timezone.utc)
@dataclass(slots=True)
class ApplicationCore:
config: AppConfig
reader: JournalReader | None = None
clock: Callable[[], datetime] = utc_now
logger: logging.Logger | None = None
cache: EventCache = field(init=False)
state_store: StateStore | None = field(init=False, default=None, repr=False)
_stop_event: threading.Event = field(init=False, repr=False)
_started_at: datetime | None = field(init=False, default=None)
_last_error: str | None = field(init=False, default=None)
_threads: list[threading.Thread] = field(init=False, default_factory=list)
_running: bool = field(init=False, default=False)
def __post_init__(self) -> None:
self.logger = self.logger or logging.getLogger(__name__)
self.cache = EventCache()
self.state_store = StateStore(self.config.state_file) if self.config.state_file else None
self._stop_event = threading.Event()
@classmethod
def from_config_file(cls, path: str, reader: JournalReader | None = None) -> "ApplicationCore":
return cls(AppConfig.from_file(path), reader=reader)
def _default_reader(self) -> JournalReader:
if self.reader is not None:
return self.reader
return JournalctlReader(self.config.journal_command, logger=self.logger)
def start(self) -> None:
if self._running:
return
self._stop_event.clear()
self._started_at = self.clock()
self._running = True
self._persist_state()
self._threads = [
threading.Thread(target=self._collector_loop, name="journal-collector", daemon=True),
threading.Thread(target=self._cleanup_loop, name="cache-cleanup", daemon=True),
]
for thread in self._threads:
thread.start()
def stop(self) -> None:
self._stop_event.set()
for thread in self._threads:
thread.join(timeout=5)
self._running = False
self._persist_state()
def run_forever(self) -> int:
self.start()
try:
while not self._stop_event.wait(0.5):
if self._threads and not any(thread.is_alive() for thread in self._threads):
break
finally:
self.stop()
return 1 if self._last_error else 0
def _collector_loop(self) -> None:
try:
for entry in self._default_reader().stream(self._stop_event):
if self._stop_event.is_set():
break
self.ingest(entry)
except Exception as exc: # pragma: no cover - exercised in failure tests
self._record_error(f"collector failed: {exc}")
self._stop_event.set()
def _cleanup_loop(self) -> None:
while not self._stop_event.wait(self.config.cleanup_interval_seconds):
try:
if self.cache.purge_expired(now=self.clock):
self._persist_state()
except Exception as exc: # pragma: no cover - defensive
self._record_error(f"cache cleanup failed: {exc}")
def ingest(self, entry: Mapping[str, Any]) -> JournalEvent | None:
event = build_event(entry, self.config.monitored_process_names)
if event is None:
return None
self.cache.put(event, ttl_seconds=self.config.event_ttl_seconds, now=self.clock)
self._persist_state()
return event
def events(self) -> list[JournalEvent]:
return self.cache.list_events(now=self.clock)
def persisted_snapshot(self):
if self.state_store is None:
return None
return self.state_store.read()
def status(self) -> ServiceStatus:
removed = self.cache.purge_expired(now=self.clock)
status = self._status_snapshot(purge_expired=False)
if removed and self.state_store is not None:
self._persist_state(status=status)
return status
def _status_snapshot(self, *, purge_expired: bool) -> ServiceStatus:
if purge_expired:
self.cache.purge_expired(now=self.clock)
return ServiceStatus(
running=self._running and not self._stop_event.is_set(),
started_at=self._started_at,
monitored_process_names=list(self.config.monitored_process_names),
cached_events=self.cache.count(now=self.clock),
event_ttl_seconds=self.config.event_ttl_seconds,
cleanup_interval_seconds=self.config.cleanup_interval_seconds,
last_error=self._last_error,
)
@property
def last_error(self) -> str | None:
return self._last_error
def _record_error(self, message: str) -> None:
self._last_error = message
if self.logger is not None:
self.logger.error(message)
self._persist_state()
def _persist_state(self, status: ServiceStatus | None = None) -> None:
if self.state_store is None:
return
try:
current_status = status or self._status_snapshot(purge_expired=False)
self.state_store.write(current_status, self.cache.snapshot(now=self.clock))
except Exception as exc: # pragma: no cover - defensive
self._last_error = f"state persistence failed: {exc}"
if self.logger is not None:
self.logger.error(self._last_error)

View File

@ -0,0 +1,212 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
import json
import sqlite3
from pathlib import Path
from threading import RLock
from typing import Any
from .models import ServiceStatus
@dataclass(slots=True)
class StateSnapshot:
status: dict[str, Any]
events: list[dict[str, Any]]
updated_at: str
class StateStore:
def __init__(self, path: str | Path) -> None:
self.path = Path(path)
self._lock = RLock()
self._migrate_legacy_json_if_needed()
def write(self, status: ServiceStatus, events: list[dict[str, Any]]) -> None:
with self._lock:
self.path.parent.mkdir(parents=True, exist_ok=True)
with sqlite3.connect(self.path) as conn:
self._ensure_schema(conn)
self._replace_snapshot(
conn,
updated_at=datetime.now(timezone.utc).isoformat(),
status=status,
events=events,
)
def read(self) -> StateSnapshot | None:
with self._lock:
if not self.path.exists():
return None
try:
with sqlite3.connect(self.path) as conn:
self._ensure_schema(conn)
snapshot_row = conn.execute(
"SELECT updated_at, status_json FROM snapshot WHERE id = 1"
).fetchone()
if snapshot_row is None:
return None
updated_at, status_json = snapshot_row
events: list[dict[str, Any]] = []
for event_row in conn.execute(
"""
SELECT id, process_name, message, captured_at, payload_json
FROM events
ORDER BY captured_at DESC, id ASC
"""
):
event_id, process_name, message, captured_at, payload_json = event_row
try:
payload = json.loads(payload_json) if payload_json else {}
except json.JSONDecodeError:
payload = {}
if not isinstance(payload, dict):
payload = {}
events.append(
{
"id": event_id,
"process_name": process_name,
"message": message,
"captured_at": captured_at,
"payload": payload,
}
)
except sqlite3.DatabaseError:
return None
try:
status = json.loads(status_json)
except json.JSONDecodeError:
return None
if not isinstance(status, dict) or not isinstance(updated_at, str):
return None
return StateSnapshot(status=status, events=events, updated_at=updated_at)
def _migrate_legacy_json_if_needed(self) -> None:
if not self.path.exists() or self._is_sqlite_file():
return
legacy_raw = json.loads(self.path.read_text(encoding="utf-8"))
if not isinstance(legacy_raw, dict):
raise ValueError(f"Unsupported legacy state file format: {self.path}")
status_mapping = legacy_raw.get("status", {})
events = legacy_raw.get("events", [])
updated_at = legacy_raw.get("updated_at") or datetime.now(timezone.utc).isoformat()
if not isinstance(status_mapping, dict) or not isinstance(events, list):
raise ValueError(f"Unsupported legacy state file format: {self.path}")
temp_path = self.path.with_suffix(self.path.suffix + ".migrating")
try:
if temp_path.exists():
temp_path.unlink()
conn = sqlite3.connect(temp_path)
try:
self._ensure_schema(conn)
self._replace_snapshot(
conn,
updated_at=str(updated_at),
status=self._status_from_legacy(status_mapping),
events=[event for event in events if isinstance(event, dict)],
)
finally:
conn.close()
temp_path.replace(self.path)
finally:
if temp_path.exists():
temp_path.unlink()
def _is_sqlite_file(self) -> bool:
try:
with self.path.open("rb") as handle:
return handle.read(16) == b"SQLite format 3\x00"
except OSError:
return False
def _ensure_schema(self, conn: sqlite3.Connection) -> None:
conn.execute("PRAGMA foreign_keys = ON")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS snapshot (
id INTEGER PRIMARY KEY CHECK (id = 1),
updated_at TEXT NOT NULL,
status_json TEXT NOT NULL
)
"""
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS events (
id TEXT PRIMARY KEY,
process_name TEXT NOT NULL,
message TEXT NOT NULL,
captured_at TEXT NOT NULL,
payload_json TEXT NOT NULL
)
"""
)
def _replace_snapshot(
self,
conn: sqlite3.Connection,
*,
updated_at: str,
status: ServiceStatus,
events: list[dict[str, Any]],
) -> None:
status_payload = json.dumps(status.to_dict(), ensure_ascii=False, default=str)
conn.execute("DELETE FROM snapshot")
conn.execute(
"INSERT INTO snapshot (id, updated_at, status_json) VALUES (1, ?, ?)",
(updated_at, status_payload),
)
conn.execute("DELETE FROM events")
conn.executemany(
"""
INSERT INTO events (
id,
process_name,
message,
captured_at,
payload_json
) VALUES (?, ?, ?, ?, ?)
""",
[
(
str(event.get("id", "")),
str(event.get("process_name", "")),
str(event.get("message", "")),
str(event.get("captured_at", "")),
json.dumps(event.get("payload", {}), ensure_ascii=False, default=str),
)
for event in events
],
)
conn.commit()
def _status_from_legacy(self, status: dict[str, Any]) -> ServiceStatus:
started_at_value = status.get("started_at")
started_at: datetime | None
if isinstance(started_at_value, str) and started_at_value.strip():
try:
started_at = datetime.fromisoformat(started_at_value.replace("Z", "+00:00"))
except ValueError:
started_at = None
else:
started_at = None
monitored_process_names = status.get("monitored_process_names", [])
if not isinstance(monitored_process_names, list):
monitored_process_names = []
return ServiceStatus(
running=bool(status.get("running", False)),
started_at=started_at,
monitored_process_names=[str(name) for name in monitored_process_names if isinstance(name, str)],
cached_events=int(status.get("cached_events", 0) or 0),
event_ttl_seconds=int(status.get("event_ttl_seconds", 300) or 300),
cleanup_interval_seconds=int(status.get("cleanup_interval_seconds", 60) or 60),
last_error=status.get("last_error") if isinstance(status.get("last_error"), str) else None,
)

View File

@ -0,0 +1,15 @@
[Unit]
Description=Journal Event Collector
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/journal-event-collector
Environment="VIRTUAL_ENV=/opt/journal-event-collector/.venv"
Environment="PATH=/opt/journal-event-collector/.venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
ExecStart=/opt/journal-event-collector/.venv/bin/journal-event-collector run --config /etc/journal-event-collector/config.toml
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target

76
tests/test_api.py Normal file
View File

@ -0,0 +1,76 @@
from __future__ import annotations
from datetime import datetime, timezone
from fastapi.testclient import TestClient
from journal_event_collector.api import create_app
from journal_event_collector.config import AppConfig
from journal_event_collector.service import ApplicationCore
from journal_event_collector.state import StateStore
def test_api_exposes_events_and_status() -> None:
config = AppConfig(monitored_process_names=["sshd"], event_ttl_seconds=60, cleanup_interval_seconds=5)
core = ApplicationCore(config)
core.ingest(
{
"_COMM": "sshd",
"MESSAGE": "accepted",
"__REALTIME_TIMESTAMP": int(datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() * 1_000_000),
}
)
app = create_app(core)
client = TestClient(app)
status = client.get("/status")
assert status.status_code == 200
assert status.json()["cached_events"] == 1
events = client.get("/events")
assert events.status_code == 200
assert events.json()[0]["process_name"] == "sshd"
def test_api_health_reports_ok() -> None:
config = AppConfig(monitored_process_names=["sshd"])
client = TestClient(create_app(ApplicationCore(config)))
assert client.get("/health").json() == {"status": "ok"}
def test_api_state_returns_persisted_snapshot(tmp_path) -> None:
state_path = tmp_path / "state.sqlite"
config = AppConfig(monitored_process_names=["sshd"], state_file=state_path)
store = StateStore(state_path)
store.write(
status=ApplicationCore(config).status(),
events=[
{
"id": "1",
"process_name": "sshd",
"message": "accepted",
"captured_at": "2026-01-01T00:00:00+00:00",
"payload": {"MESSAGE": "accepted"},
}
],
)
client = TestClient(create_app(ApplicationCore(config)))
response = client.get("/state")
assert response.status_code == 200
payload = response.json()
assert payload["updated_at"]
assert payload["status"]["running"] is False
assert payload["events"][0]["message"] == "accepted"
def test_api_state_returns_404_when_snapshot_missing() -> None:
config = AppConfig(monitored_process_names=["sshd"])
client = TestClient(create_app(ApplicationCore(config)))
response = client.get("/state")
assert response.status_code == 404
assert response.json()["detail"] == "state snapshot is not available"

29
tests/test_cache.py Normal file
View File

@ -0,0 +1,29 @@
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from journal_event_collector.cache import EventCache
from journal_event_collector.models import JournalEvent
def test_cache_expires_events() -> None:
cache = EventCache()
base = datetime(2026, 1, 1, tzinfo=timezone.utc)
event = JournalEvent.create("sshd", "connected", captured_at=base)
cache.put(event, ttl_seconds=60, now=lambda: base)
assert cache.count(now=lambda: base + timedelta(seconds=30)) == 1
assert cache.count(now=lambda: base + timedelta(seconds=61)) == 0
def test_cache_snapshot_sorts_latest_first() -> None:
cache = EventCache()
base = datetime(2026, 1, 1, tzinfo=timezone.utc)
old = JournalEvent.create("sshd", "old", captured_at=base)
new = JournalEvent.create("cron", "new", captured_at=base + timedelta(seconds=10))
cache.put(old, ttl_seconds=60, now=lambda: base)
cache.put(new, ttl_seconds=60, now=lambda: base)
snapshot = cache.snapshot(now=lambda: base)
assert [item["message"] for item in snapshot] == ["new", "old"]

149
tests/test_cli.py Normal file
View File

@ -0,0 +1,149 @@
from __future__ import annotations
import io
import json
from pathlib import Path
from fastapi.testclient import TestClient
from typer.testing import CliRunner
from journal_event_collector import cli
from journal_event_collector.api import create_app
from journal_event_collector.config import AppConfig
from journal_event_collector.models import JournalEvent
from journal_event_collector.service import ApplicationCore
from journal_event_collector.state import StateStore
runner = CliRunner()
class _ResponseStream(io.BytesIO):
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
self.close()
return False
def test_cli_run_invokes_runtime(monkeypatch, tmp_path: Path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text(
"""
[application]
monitored_process_names = ["sshd"]
""".strip(),
encoding="utf-8",
)
captured = {}
class FakeRuntime:
def __init__(self, config):
captured["config"] = config
def run(self):
captured["run"] = True
return 0
monkeypatch.setattr(cli, "ApplicationRuntime", FakeRuntime)
result = runner.invoke(cli.app, ["run", "--config", str(config_path)])
assert result.exit_code == 0
assert captured["config"].monitored_process_names == ["sshd"]
assert captured["run"] is True
def test_cli_status_and_events_can_query_api(monkeypatch) -> None:
config = AppConfig(monitored_process_names=["sshd"])
core = ApplicationCore(config)
core.ingest(
{
"_COMM": "sshd",
"MESSAGE": "accepted",
"__REALTIME_TIMESTAMP": 1_700_000_000_000_000,
}
)
client = TestClient(create_app(core))
def fake_urlopen(url: str):
path = url.split("http://api.local", 1)[-1]
response = client.get(path)
return _ResponseStream(response.content)
monkeypatch.setattr(cli, "urlopen", fake_urlopen)
status_result = runner.invoke(cli.app, ["status", "--api-base-url", "http://api.local"])
events_result = runner.invoke(cli.app, ["events", "--api-base-url", "http://api.local"])
assert status_result.exit_code == 0
assert json.loads(status_result.output)["cached_events"] == 1
assert events_result.exit_code == 0
assert json.loads(events_result.output)[0]["process_name"] == "sshd"
def test_cli_reads_persisted_state_without_api(tmp_path: Path) -> None:
config_path = tmp_path / "config.toml"
state_path = tmp_path / "state.sqlite"
config_path.write_text(
f"""
[application]
monitored_process_names = ["sshd"]
[storage]
state_file = "{state_path.name}"
""".strip(),
encoding="utf-8",
)
settings = AppConfig.from_file(config_path)
store = StateStore(settings.state_file)
store.write(
status=ApplicationCore(settings).status(),
events=[{"id": "1", "process_name": "sshd", "message": "accepted", "captured_at": "2026-01-01T00:00:00+00:00"}],
)
status_result = runner.invoke(cli.app, ["status", "--config", str(config_path)])
events_result = runner.invoke(cli.app, ["events", "--config", str(config_path)])
assert status_result.exit_code == 0
assert json.loads(status_result.output)["running"] is False
assert events_result.exit_code == 0
assert json.loads(events_result.output)[0]["message"] == "accepted"
def test_cli_state_reads_persisted_snapshot(tmp_path: Path) -> None:
config_path = tmp_path / "config.toml"
state_path = tmp_path / "state.sqlite"
config_path.write_text(
f"""
[application]
monitored_process_names = ["sshd"]
[storage]
state_file = "{state_path.name}"
""".strip(),
encoding="utf-8",
)
settings = AppConfig.from_file(config_path)
StateStore(settings.state_file).write(
status=ApplicationCore(settings).status(),
events=[
{
"id": "1",
"process_name": "sshd",
"message": "accepted",
"captured_at": "2026-01-01T00:00:00+00:00",
"payload": {"MESSAGE": "accepted"},
}
],
)
result = runner.invoke(cli.app, ["state", "--config", str(config_path)])
assert result.exit_code == 0
payload = json.loads(result.output)
assert payload["updated_at"]
assert payload["events"][0]["message"] == "accepted"

65
tests/test_config.py Normal file
View File

@ -0,0 +1,65 @@
from __future__ import annotations
from pathlib import Path
import pytest
from journal_event_collector.config import AppConfig, ConfigError
def test_app_config_from_file(tmp_path: Path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text(
"""
[application]
monitored_process_names = ["sshd", "cron"]
event_ttl_seconds = 120
cleanup_interval_seconds = 15
log_level = "debug"
[api]
host = "0.0.0.0"
port = 9000
[journal]
command = ["journalctl", "-f", "-o", "json"]
""".strip(),
encoding="utf-8",
)
config = AppConfig.from_file(config_path)
assert config.monitored_process_names == ["sshd", "cron"]
assert config.event_ttl_seconds == 120
assert config.cleanup_interval_seconds == 15
assert config.api_host == "0.0.0.0"
assert config.api_port == 9000
assert config.log_level == "debug"
def test_app_config_rejects_missing_process_names() -> None:
with pytest.raises(ConfigError):
AppConfig.from_mapping({"application": {}})
def test_app_config_deduplicates_process_names() -> None:
config = AppConfig.from_mapping({"application": {"monitored_process_names": ["sshd", "SSHD", "cron"]}})
assert config.monitored_process_names == ["sshd", "cron"]
def test_app_config_resolves_state_file_relative_to_config_dir(tmp_path: Path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text(
"""
[application]
monitored_process_names = ["sshd"]
[storage]
state_file = "./state/state.sqlite"
""".strip(),
encoding="utf-8",
)
config = AppConfig.from_file(config_path)
assert config.state_file == (tmp_path / "state" / "state.sqlite").resolve()

26
tests/test_journal.py Normal file
View File

@ -0,0 +1,26 @@
from __future__ import annotations
from datetime import datetime, timezone
from journal_event_collector.journal import build_event
def test_build_event_uses_matching_process_name() -> None:
entry = {
"_COMM": "sshd",
"MESSAGE": "login accepted",
"__REALTIME_TIMESTAMP": 1_700_000_000_000_000,
}
event = build_event(entry, ["sshd", "cron"])
assert event is not None
assert event.process_name == "sshd"
assert event.message == "login accepted"
assert event.captured_at.tzinfo == timezone.utc
def test_build_event_ignores_non_matching_process_name() -> None:
entry = {"_COMM": "kernel", "MESSAGE": "ignored"}
assert build_event(entry, ["sshd"]) is None

55
tests/test_service.py Normal file
View File

@ -0,0 +1,55 @@
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from journal_event_collector.config import AppConfig
from journal_event_collector.service import ApplicationCore
class FiniteReader:
def __init__(self, entries):
self.entries = entries
def stream(self, stop_event):
for entry in self.entries:
yield entry
while not stop_event.is_set():
stop_event.wait(0.05)
class FailingReader:
def stream(self, stop_event):
raise RuntimeError("boom")
def test_application_core_collects_and_reports_status() -> None:
base = datetime(2026, 1, 1, tzinfo=timezone.utc)
config = AppConfig(monitored_process_names=["sshd"], event_ttl_seconds=60, cleanup_interval_seconds=1)
core = ApplicationCore(
config,
reader=FiniteReader([
{"_COMM": "sshd", "MESSAGE": "accepted", "__REALTIME_TIMESTAMP": int(base.timestamp() * 1_000_000)},
]),
clock=lambda: base,
)
core.start()
try:
for _ in range(20):
if core.events():
break
finally:
core.stop()
assert core.events()[0].message == "accepted"
assert core.status().cached_events == 1
def test_application_core_records_fatal_reader_error() -> None:
config = AppConfig(monitored_process_names=["sshd"])
core = ApplicationCore(config, reader=FailingReader())
exit_code = core.run_forever()
assert exit_code == 1
assert core.last_error is not None

68
tests/test_state.py Normal file
View File

@ -0,0 +1,68 @@
from __future__ import annotations
import json
import sqlite3
from pathlib import Path
from journal_event_collector.models import ServiceStatus
from journal_event_collector.state import StateStore
def test_state_store_round_trip(tmp_path: Path) -> None:
store = StateStore(tmp_path / "state.sqlite")
status = ServiceStatus(
running=True,
started_at=None,
monitored_process_names=["sshd"],
cached_events=1,
event_ttl_seconds=60,
cleanup_interval_seconds=5,
)
store.write(status, [{"id": "1", "message": "hello"}])
snapshot = store.read()
assert snapshot is not None
assert snapshot.status["running"] is True
assert snapshot.events[0]["message"] == "hello"
with sqlite3.connect(tmp_path / "state.sqlite") as conn:
tables = {
row[0]
for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
}
assert {"snapshot", "events"}.issubset(tables)
def test_state_store_migrates_legacy_json_to_sqlite(tmp_path: Path) -> None:
state_path = tmp_path / "state.json"
legacy_snapshot = {
"status": {
"running": True,
"started_at": None,
"monitored_process_names": ["sshd"],
"cached_events": 1,
"event_ttl_seconds": 60,
"cleanup_interval_seconds": 5,
"last_error": None,
},
"events": [
{
"id": "1",
"process_name": "sshd",
"message": "hello",
"captured_at": "2026-01-01T00:00:00+00:00",
"payload": {"MESSAGE": "hello"},
}
],
"updated_at": "2026-01-01T00:00:00+00:00",
}
state_path.write_text(json.dumps(legacy_snapshot), encoding="utf-8")
store = StateStore(state_path)
snapshot = store.read()
assert snapshot is not None
assert snapshot.status["running"] is True
assert snapshot.events[0]["message"] == "hello"
assert state_path.read_bytes().startswith(b"SQLite format 3\x00")

116
usage-guide.md Normal file
View File

@ -0,0 +1,116 @@
# Usage Guide
## Overview
`journal-event-collector` runs as a daemon, exposes a REST API, and offers a CLI for local and remote inspection.
## CLI
The CLI is available through the installed entry point:
```bash
journal-event-collector --help
```
### Run the daemon
```bash
journal-event-collector run --config /etc/journal-event-collector/config.toml
```
This command starts the collector, cache cleaner, and REST API in one process.
### Inspect live status
```bash
journal-event-collector status --config /etc/journal-event-collector/config.toml
```
### Inspect current cached events
```bash
journal-event-collector events --config /etc/journal-event-collector/config.toml
```
### Inspect persisted snapshot
```bash
journal-event-collector state --config /etc/journal-event-collector/config.toml
```
If the daemon is running and `storage.state_file` is configured, `state` reads the persisted SQLite snapshot directly.
### Query a remote API
```bash
journal-event-collector status --api-base-url http://127.0.0.1:8000
journal-event-collector events --api-base-url http://127.0.0.1:8000
journal-event-collector state --api-base-url http://127.0.0.1:8000
```
## REST API
The REST API is served by the daemon.
### Health
```bash
GET /health
```
Returns:
```json
{"status":"ok"}
```
or:
```json
{"status":"degraded"}
```
### Service status
```bash
GET /status
```
Returns the live daemon state, configured process names, cache size, TTL, cleanup interval, and the last error if any.
### Cached events
```bash
GET /events
```
Returns the current in-memory cache contents that have not expired.
### Persisted snapshot
```bash
GET /state
```
Returns the persisted SQLite snapshot directly:
```json
{
"status": { "...": "..." },
"events": [ { "...": "..." } ],
"updated_at": "2026-01-01T00:00:00+00:00"
}
```
## Configuration Notes
1. `monitored_process_names` controls which journal sources become events.
2. `event_ttl_seconds` controls how long events remain in cache and in the persisted snapshot.
3. `cleanup_interval_seconds` controls how often expired events are purged.
4. `storage.state_file` should point to the SQLite database used for persisted state.
## Common Issues
1. If `run` exits immediately, check the config file path and the `journalctl` command.
2. If `state` returns nothing locally, make sure `storage.state_file` is configured and writable.
3. If the service cannot start under `systemd`, confirm that the venv path in the unit file matches the deployment layout.