добавлены команды observability и state в cli.

This commit is contained in:
Ilgiz Kalmetyev 2026-04-19 10:08:52 +05:00
parent 826e01ae15
commit 63c19d4543
8 changed files with 191 additions and 56 deletions

View File

@ -33,6 +33,16 @@ For the quickest smoke run, use the file polling JSON example:
3. For the single-adapter smoke path, you can still import and run the runtime
directly from Python as before.
The CLI also supports a read-only status view:
```bash
wf-agent3 status
wf-agent3 observability --config /etc/wf-agent3/app.yaml
```
If neither `--config` nor `WF_AGENT3_CONFIG` is provided, the CLI falls back to
`/etc/wf-agent3/app.yaml`.
What to feed as input:
- For the JSON polling example, put one JSON object into the input file.
@ -86,6 +96,9 @@ wf-agent3 cache clear --config src/app/application/examples/daemon_multi_adapter
For backward compatibility, `wf-agent3 --config ...` still maps to `serve`.
The same default config path is used by `status` and `cache` commands when no
explicit config argument or environment variable is provided.
See [`ARCHITECTURE.md`](ARCHITECTURE.md) for package boundaries and module
responsibilities.

View File

@ -1,11 +1,11 @@
[Unit]
[Unit]
Description=wf-agent3 multi-adapter daemon
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
Environment=WF_AGENT3_CONFIG=/etc/wf-agent3/application.yaml
Environment=WF_AGENT3_CONFIG=/etc/wf-agent3/app.yaml
WorkingDirectory=/var/lib/wf-agent3
ExecStart=/usr/bin/env wf-agent3 serve --config ${WF_AGENT3_CONFIG}
Restart=always

View File

@ -97,7 +97,7 @@ python -m pip install -e .[dev]
Copy the daemon example configuration and adjust paths for the target host:
```bash
cp /opt/wf-agent3/src/app/application/examples/daemon_multi_adapter.yaml /etc/wf-agent3/application.yaml
cp /opt/wf-agent3/src/app/application/examples/daemon_multi_adapter.yaml /etc/wf-agent3/app.yaml
```
Update the configuration so it points to the correct input files, sockets, or
@ -112,7 +112,7 @@ When using a virtual environment, the service should execute the binary from
the venv explicitly, for example:
```ini
ExecStart=/opt/wf-agent3/venv/bin/wf-agent3 serve --config /etc/wf-agent3/application.yaml
ExecStart=/opt/wf-agent3/venv/bin/wf-agent3 serve --config /etc/wf-agent3/app.yaml
```
Keep the working directory aligned with the application checkout:
@ -134,7 +134,7 @@ After installation, verify that the daemon starts and reads the intended
configuration:
```bash
/opt/wf-agent3/venv/bin/wf-agent3 serve --config /etc/wf-agent3/application.yaml
/opt/wf-agent3/venv/bin/wf-agent3 serve --config /etc/wf-agent3/app.yaml
```
If the service is expected to run in the background, confirm its journal

View File

@ -24,21 +24,22 @@ The daemon expects a YAML configuration file.
You can provide it in one of two ways:
- `--config /path/to/application.yaml`
- `WF_AGENT3_CONFIG=/path/to/application.yaml`
- `--config /path/to/app.yaml`
- `WF_AGENT3_CONFIG=/path/to/app.yaml`
The explicit `--config` argument wins over the environment variable.
If neither is provided, the CLI uses `/etc/wf-agent3/app.yaml`.
Example:
```bash
wf-agent3 serve --config /etc/wf-agent3/application.yaml
wf-agent3 serve --config /etc/wf-agent3/app.yaml
```
Equivalent form using the environment variable:
```bash
export WF_AGENT3_CONFIG=/etc/wf-agent3/application.yaml
export WF_AGENT3_CONFIG=/etc/wf-agent3/app.yaml
wf-agent3 serve
```
@ -58,7 +59,25 @@ The configured director controls where exported messages go:
- `stdout_json` is the compatibility sink used by the daemon example.
- `stdout_proto` is available when the protobuf wire format is desired.
## 4. Smoke run
## 4. Status and observability
Use `status` to print the current application status snapshot as JSON.
`observability` is an alias for the same command.
Examples:
```bash
wf-agent3 status
wf-agent3 observability --config /etc/wf-agent3/app.yaml
```
The output includes:
- application lifecycle state;
- active and failed adapters;
- snapshot details for cache, derivator, and configured adapter workers.
## 5. Smoke run
For a quick local smoke run, use the file polling example that already ships
with the repository.
@ -82,7 +101,7 @@ foreground output or the configured director sink.
For line-oriented scenarios, write one event per line.
For D-Bus and WPA supplicant adapters, the transport channel is not a local file.
## 5. Cache control
## 6. Cache control
The `cache` subcommand exposes read-only and admin operations through the local
Unix control socket.
@ -94,19 +113,19 @@ The relevant config requirements are:
If either condition is missing, cache commands fail fast.
### 5.1 Check cache status
### 6.1 Check cache status
```bash
wf-agent3 cache status --config src/app/application/examples/daemon_multi_adapter.yaml
```
### 5.2 List messages
### 6.2 List messages
```bash
wf-agent3 cache list --config src/app/application/examples/daemon_multi_adapter.yaml --limit 100
```
### 5.3 Filter messages
### 6.3 Filter messages
```bash
wf-agent3 cache filter --config src/app/application/examples/daemon_multi_adapter.yaml --adapter-id file-polling-json --source .tmp/file_polling_input.json --time-from 2026-04-19T00:00:00+00:00 --time-to 2026-04-20T00:00:00+00:00 --limit 50
@ -115,13 +134,13 @@ wf-agent3 cache filter --config src/app/application/examples/daemon_multi_adapte
The time filters accept ISO 8601 timestamps. If no timezone is supplied,
UTC is assumed.
### 5.4 Clear cache
### 6.4 Clear cache
```bash
wf-agent3 cache clear --config src/app/application/examples/daemon_multi_adapter.yaml
```
## 6. Service behavior
## 7. Service behavior
When the application runs under `systemd`, the unit usually starts the same
`serve` command in the foreground.
@ -130,7 +149,7 @@ The daemon writes its output to the configured director sink.
For journald-based deployments, the systemd unit can capture stdout and stderr
without extra log files.
## 7. Troubleshooting
## 8. Troubleshooting
Common startup issues:

View File

@ -23,6 +23,7 @@ from .config import ApplicationConfigLoader
from .supervisor import ApplicationSupervisorBuilder
DEFAULT_CONFIG_ENV = "WF_AGENT3_CONFIG"
DEFAULT_CONFIG_PATH = Path("/etc/wf-agent3/app.yaml")
def build_parser() -> argparse.ArgumentParser:
@ -34,6 +35,13 @@ def build_parser() -> argparse.ArgumentParser:
serve_parser = subparsers.add_parser("serve")
_add_config_argument(serve_parser)
status_parser = subparsers.add_parser(
"status",
aliases=["observability"],
help="Show the application status snapshot.",
)
_add_config_argument(status_parser)
cache_parser = subparsers.add_parser("cache")
cache_subparsers = cache_parser.add_subparsers(dest="cache_command", required=True)
@ -75,7 +83,7 @@ def resolve_config_path(args: argparse.Namespace) -> Path:
env_value = os.environ.get(DEFAULT_CONFIG_ENV)
if env_value:
return Path(env_value)
raise SystemExit(f"missing config path: pass --config or set {DEFAULT_CONFIG_ENV}")
return DEFAULT_CONFIG_PATH
def normalize_argv(argv: Iterable[str] | None) -> list[str]:
@ -84,7 +92,7 @@ def normalize_argv(argv: Iterable[str] | None) -> list[str]:
arguments = list(argv) if argv is not None else sys.argv[1:]
if not arguments:
return ["serve"]
if arguments[0] in {"serve", "cache", "-h", "--help"}:
if arguments[0] in {"serve", "status", "observability", "cache", "-h", "--help"}:
return arguments
return ["serve", *arguments]
@ -96,6 +104,8 @@ def main(argv: Iterable[str] | None = None) -> int:
args = parser.parse_args(normalize_argv(argv))
if args.command == "cache":
return _run_cache_command(args)
if args.command in {"status", "observability"}:
return _run_status_command(args)
return _run_serve_command(args)
@ -112,6 +122,13 @@ def _run_serve_command(args: argparse.Namespace) -> int:
return supervisor.run_forever()
def _run_status_command(args: argparse.Namespace) -> int:
config_path = resolve_config_path(args)
config = ApplicationConfigLoader().load_path(config_path)
supervisor = ApplicationSupervisorBuilder().build(config)
return _print_json_payload(_status_snapshot_payload(supervisor.snapshot()))
def _run_cache_command(args: argparse.Namespace) -> int:
config = ApplicationConfigLoader().load_path(resolve_config_path(args))
socket_path = config.service.control_socket_path
@ -125,44 +142,44 @@ def _run_cache_command(args: argparse.Namespace) -> int:
response = cast(
Any,
client.request(
wire.CacheControlRequest(status_request=wire.CacheStatusRequest())
wire.CacheControlRequest(status_request=wire.CacheStatusRequest())
),
)
return _print_json_response(response.status_response)
return _print_json_payload(response.status_response)
if args.cache_command == "list":
response = cast(
Any,
client.request(
wire.CacheControlRequest(
list_request=wire.CacheListRequest(limit=args.limit or 0)
)
wire.CacheControlRequest(
list_request=wire.CacheListRequest(limit=args.limit or 0)
)
),
)
return _print_json_response(response.list_response)
return _print_json_payload(response.list_response)
if args.cache_command == "filter":
response = cast(
Any,
client.request(
wire.CacheControlRequest(
filter_request=wire.CacheFilterRequest(
adapter_id=args.adapter_id or "",
source=args.source or "",
time_from=_timestamp_from_text(args.time_from),
time_to=_timestamp_from_text(args.time_to),
limit=args.limit or 0,
wire.CacheControlRequest(
filter_request=wire.CacheFilterRequest(
adapter_id=args.adapter_id or "",
source=args.source or "",
time_from=_timestamp_from_text(args.time_from),
time_to=_timestamp_from_text(args.time_to),
limit=args.limit or 0,
)
)
)
),
)
return _print_json_response(response.filter_response)
return _print_json_payload(response.filter_response)
if args.cache_command == "clear":
response = cast(
Any,
client.request(
wire.CacheControlRequest(clear_request=wire.CacheClearRequest())
wire.CacheControlRequest(clear_request=wire.CacheClearRequest())
),
)
return _print_json_response(response.clear_response)
return _print_json_payload(response.clear_response)
raise SystemExit(f"unsupported cache command: {args.cache_command}")
@ -177,11 +194,22 @@ def _timestamp_from_text(value: str | None) -> timestamp_pb2.Timestamp:
return timestamp
def _print_json_response(message: ProtobufMessage) -> int:
payload: Any = json_format.MessageToDict(
message,
preserving_proto_field_name=True,
)
def _status_snapshot_payload(snapshot: Any) -> dict[str, Any]:
return {
"state": snapshot.state.value,
"active_adapters": list(snapshot.active_adapters),
"failed_adapters": list(snapshot.failed_adapters),
"details": snapshot.details,
}
def _print_json_payload(message: Any) -> int:
payload: Any = message
if isinstance(message, ProtobufMessage):
payload = json_format.MessageToDict(
message,
preserving_proto_field_name=True,
)
print(json.dumps(payload, ensure_ascii=False, sort_keys=True))
return 0

View File

@ -172,6 +172,29 @@ class ApplicationSupervisor:
state = ApplicationState.RUNNING
else:
state = self._state
if self._workers:
adapters = [
{
"adapter_id": worker.adapter_id,
"kind": worker.adapter.kind.value,
"failure_count": worker.failure_count,
"last_error": worker.last_error,
"running": worker.thread is not None
and worker.thread.is_alive(),
}
for worker in self._workers.values()
]
else:
adapters = [
{
"adapter_id": adapter.adapter_id,
"kind": adapter.kind.value,
"failure_count": 0,
"last_error": None,
"running": False,
}
for adapter in self.config.adapters
]
return ApplicationStatus(
state=state,
active_adapters=active,
@ -189,17 +212,7 @@ class ApplicationSupervisor:
if self._derivator is None
else self._derivator.snapshot_details()
),
"adapters": [
{
"adapter_id": worker.adapter_id,
"kind": worker.adapter.kind.value,
"failure_count": worker.failure_count,
"last_error": worker.last_error,
"running": worker.thread is not None
and worker.thread.is_alive(),
}
for worker in self._workers.values()
],
"adapters": adapters,
},
)

View File

@ -1,13 +1,21 @@
"""Tests for the daemon CLI."""
"""Tests for the daemon CLI."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import pytest
from app.application.cli import DEFAULT_CONFIG_ENV, normalize_argv, resolve_config_path
from app.application import cli
from app.application.cli import (
DEFAULT_CONFIG_ENV,
DEFAULT_CONFIG_PATH,
normalize_argv,
resolve_config_path,
)
from app.application.models import ApplicationState, ApplicationStatus
def test_resolve_config_path_prefers_explicit_argument(
@ -26,8 +34,19 @@ def test_resolve_config_path_uses_environment(monkeypatch: pytest.MonkeyPatch) -
assert resolve_config_path(args) == Path("/tmp/daemon.yaml")
def test_resolve_config_path_falls_back_to_default_path(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv(DEFAULT_CONFIG_ENV, raising=False)
args = argparse.Namespace(config=None)
assert resolve_config_path(args) == DEFAULT_CONFIG_PATH
def test_normalize_argv_defaults_to_serve() -> None:
assert normalize_argv([]) == ["serve"]
assert normalize_argv(["status"]) == ["status"]
assert normalize_argv(["observability"]) == ["observability"]
assert normalize_argv(["--config", "daemon.yaml"]) == [
"serve",
"--config",
@ -39,3 +58,46 @@ def test_normalize_argv_defaults_to_serve() -> None:
"--config",
"daemon.yaml",
]
def test_main_status_command_prints_snapshot_and_uses_default_config(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
loaded_paths: list[Path] = []
class FakeLoader:
def load_path(self, path: str | Path) -> object:
loaded_paths.append(Path(path))
return object()
snapshot = ApplicationStatus(
state=ApplicationState.RUNNING,
active_adapters=("file-adapter",),
failed_adapters=("dbus-adapter",),
details={"service": "wf-agent3"},
)
class FakeSupervisor:
def snapshot(self) -> ApplicationStatus:
return snapshot
class FakeBuilder:
def build(self, config: object) -> FakeSupervisor:
return FakeSupervisor()
monkeypatch.delenv(DEFAULT_CONFIG_ENV, raising=False)
monkeypatch.setattr(cli, "ApplicationConfigLoader", FakeLoader)
monkeypatch.setattr(cli, "ApplicationSupervisorBuilder", FakeBuilder)
exit_code = cli.main(["status"])
assert exit_code == 0
assert loaded_paths == [DEFAULT_CONFIG_PATH]
payload = json.loads(capsys.readouterr().out)
assert payload == {
"state": "running",
"active_adapters": ["file-adapter"],
"failed_adapters": ["dbus-adapter"],
"details": {"service": "wf-agent3"},
}

View File

@ -1,4 +1,4 @@
"""Tests for the systemd service unit template."""
"""Tests for the systemd service unit template."""
from __future__ import annotations
@ -9,7 +9,7 @@ def test_systemd_unit_contains_expected_service_wiring() -> None:
unit = Path("deploy/systemd/wf-agent3.service").read_text(encoding="utf-8")
assert "Type=simple" in unit
assert "WF_AGENT3_CONFIG=/etc/wf-agent3/application.yaml" in unit
assert "WF_AGENT3_CONFIG=/etc/wf-agent3/app.yaml" in unit
assert "ExecStart=/usr/bin/env wf-agent3 serve --config ${WF_AGENT3_CONFIG}" in unit
assert "StandardOutput=journal" in unit
assert "StandardError=journal" in unit