Compare commits
21
Commits
v0.2.0
..
d91b3dab77
No files matched your search
+6
-2
@@ -1,8 +1,8 @@
|
||||
[target.armv7-unknown-linux-musleabihf]
|
||||
linker = "rust-lld"
|
||||
|
||||
[target.aarch64-unknown-linux-gnu]
|
||||
linker = "aarch64-linux-gnu-gcc"
|
||||
# [target.aarch64-unknown-linux-gnu]
|
||||
# linker = "aarch64-linux-gnu-gcc"
|
||||
|
||||
[build]
|
||||
# target = "armv7-unknown-linux-musleabihf"
|
||||
@@ -20,3 +20,7 @@ tw = "t --target=x86_64-pc-windows-msvc"
|
||||
ldabr = "b -r --target=armv7-unknown-linux-musleabihf"
|
||||
t = "test -- --nocapture --test-threads=1"
|
||||
tdebug = "test -- --nocapture --test-threads=1 --show-output"
|
||||
|
||||
|
||||
[registries.gitea]
|
||||
index = "sparse+https://git.ldlda.com/api/packages/lda/cargo/" # Sparse index
|
||||
@@ -0,0 +1 @@
|
||||
SQLX_OFFLINE=true
|
||||
@@ -7,6 +7,10 @@ on:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
# When using cargo-zigbuild for *-gnu targets, link against this glibc baseline (wider VPS compatibility).
|
||||
WAKEY_CC_GLIBC_VERSION: "2.28"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
# My Machine has arm-musl stuff - or else i have to use cross :(
|
||||
@@ -43,17 +47,32 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ui
|
||||
# corepack enable # no no no
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build
|
||||
|
||||
- name: Build control-plane (linux gnu)
|
||||
- name: Build control-plane (linux-gnu; zig + older glibc when available)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for target in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu; do
|
||||
cargo build --release --target "$target" -p wakey-control-plane
|
||||
GLIBC_VER="${WAKEY_CC_GLIBC_VERSION:-2.28}"
|
||||
GNU_TARGETS=(x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu)
|
||||
|
||||
use_zig=false
|
||||
if command -v zig >/dev/null 2>&1 && cargo zigbuild -h >/dev/null 2>&1; then
|
||||
use_zig=true
|
||||
fi
|
||||
|
||||
if [ "$use_zig" = true ]; then
|
||||
echo "cargo-zigbuild + zig found: building control-plane with glibc ${GLIBC_VER}"
|
||||
for base in "${GNU_TARGETS[@]}"; do
|
||||
cargo zigbuild --release --target "${base}.${GLIBC_VER}" -p wakey-control-plane
|
||||
done
|
||||
else
|
||||
echo "zig or cargo zigbuild not available: using plain cargo build (binary needs glibc >= host)"
|
||||
for base in "${GNU_TARGETS[@]}"; do
|
||||
cargo build --release --target "$base" -p wakey-control-plane
|
||||
done
|
||||
fi
|
||||
|
||||
- name: Package rootfs tarball
|
||||
shell: pwsh
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -2,3 +2,4 @@ We work towards clean, modular, maintainable design, clear documentation... im n
|
||||
|
||||
DRY: spawn subagents.
|
||||
Context: break those files out.
|
||||
Test: make functions easy to test.
|
||||
@@ -0,0 +1,184 @@
|
||||
# Plan: Observation Store And Sync V1
|
||||
|
||||
## Summary
|
||||
|
||||
Build device observation support in layers:
|
||||
|
||||
1. Local router observations are captured by `wakey observe ...` from OpenWrt hotplug.
|
||||
2. `wakey-linux` stores current observed DHCP/neigh state locally.
|
||||
3. `wakey-agent` forwards compact observations to the control plane.
|
||||
4. The control plane stores observations per agent and later joins them to known devices through `device_identifiers`.
|
||||
|
||||
This is separate from durable identity. Observations are facts an agent saw at a time; known devices are manual/user-approved identity records.
|
||||
|
||||
## Network/API Boundary
|
||||
|
||||
The control plane has two route classes:
|
||||
|
||||
- Public agent routes: intended to be reachable by agents.
|
||||
- Protected control routes: intended to sit behind Cloudflare Access/admin auth.
|
||||
|
||||
Observation upload belongs on the public agent route surface because routers/agents must call it:
|
||||
|
||||
```text
|
||||
POST /api/v1/agents/observations
|
||||
```
|
||||
|
||||
The endpoint must require normal agent authentication, using the same persistent `agent_id`/`agent_token` trust model as WebSocket auth. It must not be a Cloudflare Access-only admin endpoint.
|
||||
|
||||
Admin/UI read APIs belong under protected control routes:
|
||||
|
||||
```text
|
||||
GET /api/v1/control/observations
|
||||
GET /api/v1/control/devices
|
||||
```
|
||||
|
||||
## Step 1: Local Observation Store
|
||||
|
||||
Replace the narrow `/tmp/wakey_mac_names.json` cache with a local observation store owned by `wakey-linux`.
|
||||
|
||||
Minimum local tables/state:
|
||||
|
||||
```text
|
||||
observed_dhcp_clients:
|
||||
mac
|
||||
ip
|
||||
hostname
|
||||
first_seen_unix
|
||||
last_seen_unix
|
||||
last_action
|
||||
|
||||
observed_neighbors:
|
||||
key
|
||||
mac
|
||||
ip
|
||||
first_seen_unix
|
||||
last_seen_unix
|
||||
last_action
|
||||
```
|
||||
|
||||
Behavior:
|
||||
|
||||
- Hotplug scripts stay minimal and call `wakey-agent observe ...`.
|
||||
- `wakey-agent observe ...` delegates to `wakey observe ...`.
|
||||
- `wakey observe dhcp ...` writes DHCP observations.
|
||||
- `wakey observe neigh ...` writes neighbor observations.
|
||||
- Existing `wakey leases` and `wakey inventory` still read live sources first, then enrich from the local observation store.
|
||||
- Do not make local queries depend exclusively on hotplug events yet.
|
||||
|
||||
## Step 2: Control-Plane Observation Tables
|
||||
|
||||
Add observation tables early so future API/UI work does not need another major state refactor.
|
||||
|
||||
Control-plane schema:
|
||||
|
||||
```text
|
||||
agent_device_observations:
|
||||
observation_key TEXT PRIMARY KEY
|
||||
agent_id TEXT NOT NULL
|
||||
kind TEXT NOT NULL
|
||||
mac TEXT
|
||||
ip TEXT
|
||||
hostname TEXT
|
||||
first_seen_unix INTEGER NOT NULL
|
||||
last_seen_unix INTEGER NOT NULL
|
||||
last_action TEXT NOT NULL
|
||||
|
||||
agent_device_observation_events:
|
||||
event_id TEXT PRIMARY KEY
|
||||
agent_id TEXT NOT NULL
|
||||
kind TEXT NOT NULL
|
||||
action TEXT NOT NULL
|
||||
mac TEXT
|
||||
ip TEXT
|
||||
hostname TEXT
|
||||
ts_unix INTEGER NOT NULL
|
||||
```
|
||||
|
||||
Keep `agent_device_observation_events` optional in behavior if needed, but create it in schema early. Current-state rows are the primary path; event history is for debugging/audit.
|
||||
|
||||
Indexes:
|
||||
|
||||
```text
|
||||
agent_device_observations(agent_id)
|
||||
agent_device_observations(mac)
|
||||
agent_device_observations(ip)
|
||||
agent_device_observations(hostname)
|
||||
agent_device_observations(last_seen_unix)
|
||||
agent_device_observation_events(agent_id, ts_unix)
|
||||
agent_device_observation_events(mac)
|
||||
```
|
||||
|
||||
## Step 3: Agent Upload
|
||||
|
||||
Add agent upload payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"observations": [
|
||||
{
|
||||
"kind": "dhcp",
|
||||
"action": "update",
|
||||
"mac": "04:7c:16:79:6d:ee",
|
||||
"ip": "192.168.100.94",
|
||||
"hostname": "lda",
|
||||
"first_seen_unix": 1770000000,
|
||||
"last_seen_unix": 1770000123
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Agent may send snapshots periodically and after local observe events.
|
||||
- Control plane upserts current-state rows by stable observation key.
|
||||
- Observation keys should be deterministic from `agent_id`, `kind`, and the best available identifier:
|
||||
- DHCP with MAC: `agent:{agent_id}:dhcp:mac:{mac}`
|
||||
- Neigh with MAC: `agent:{agent_id}:neigh:mac:{mac}`
|
||||
- Neigh without MAC: `agent:{agent_id}:neigh:ip:{ip}`
|
||||
- Uploads must not create known devices automatically.
|
||||
|
||||
## Step 4: Join Observations To Known Devices
|
||||
|
||||
Known devices already have durable IDs and manual identifiers:
|
||||
|
||||
```text
|
||||
known_devices
|
||||
device_identifiers
|
||||
```
|
||||
|
||||
Join rule:
|
||||
|
||||
```text
|
||||
agent_device_observations.mac
|
||||
-> device_identifiers(kind = 'mac', value = mac)
|
||||
-> known_devices.device_id
|
||||
```
|
||||
|
||||
Unknown observations are rows that do not match any manual `device_identifiers` row.
|
||||
|
||||
This enables:
|
||||
|
||||
- same known device observed by multiple agents;
|
||||
- same known device with multiple MACs;
|
||||
- UI flow to attach an unknown observed MAC to an existing known device;
|
||||
- wake flows that choose agent-local observed IP/MAC context for a known device.
|
||||
|
||||
## Step 5: UI/API Later
|
||||
|
||||
After storage and upload exist:
|
||||
|
||||
- show known devices with all matching observations grouped by agent;
|
||||
- show unknown observations;
|
||||
- add action: attach observation identifier to known device;
|
||||
- add action: create known device from observation;
|
||||
- add wake action from known device using a selected agent/observation.
|
||||
|
||||
## Defaults
|
||||
|
||||
- `wakey` remains the local router/debugging CLI.
|
||||
- `wakey-agent` is the sync bridge to the control plane.
|
||||
- `wakey-control-plane` is durable identity and multi-agent view.
|
||||
- Local observation store is not authoritative; live sources still matter.
|
||||
- Control-plane observations are not durable identity; only manual known-device identifiers are.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Plan: SQLx Query Macro Adoption
|
||||
|
||||
## Summary
|
||||
|
||||
Move control-plane SQL from unchecked `sqlx::query(...)` calls toward `sqlx::query!` / `query_as!` where the SQL shape is static.
|
||||
|
||||
This gives compile-time checking for table/column names and Rust value types. Dynamic filter builders can stay on `QueryBuilder`.
|
||||
|
||||
## Offline Setup
|
||||
|
||||
Normal builds should not need a live database:
|
||||
|
||||
```text
|
||||
SQLX_OFFLINE=true
|
||||
```
|
||||
|
||||
`.env` is ignored, so copy:
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
SQLx query metadata should be generated into `.sqlx/` and committed.
|
||||
|
||||
Prepare metadata with:
|
||||
|
||||
```sh
|
||||
cargo install sqlx-cli --no-default-features --features sqlite
|
||||
./scripts/prepare_sqlx_sqlite.sh
|
||||
```
|
||||
|
||||
The script:
|
||||
|
||||
- creates a temporary SQLite database;
|
||||
- runs `wakey-control-plane/migrations`;
|
||||
- runs `cargo sqlx prepare --workspace -- -p wakey-control-plane --all-targets --all-features`;
|
||||
- writes `.sqlx/`.
|
||||
|
||||
## Conversion Rules
|
||||
|
||||
Use `query!` / `query_as!` for static SQL:
|
||||
|
||||
- inserts;
|
||||
- deletes;
|
||||
- simple selects by primary key;
|
||||
- fixed update statements;
|
||||
- count queries.
|
||||
|
||||
Keep non-macro SQL for genuinely dynamic SQL:
|
||||
|
||||
- audit event filters built with `QueryBuilder`;
|
||||
- observation listing with optional filters, unless split into fixed branches;
|
||||
- any SQL where table/column names are intentionally generated.
|
||||
|
||||
## Test/CI
|
||||
|
||||
After query macros are introduced, CI should add:
|
||||
|
||||
```sh
|
||||
cargo install sqlx-cli --no-default-features --features sqlite
|
||||
./scripts/prepare_sqlx_sqlite.sh
|
||||
cargo sqlx prepare --check --workspace -- --all-targets --all-features
|
||||
```
|
||||
|
||||
Do not add the CI check until the first `.sqlx/` metadata is committed, otherwise it adds dependency install cost without catching anything.
|
||||
|
||||
## Notes
|
||||
|
||||
The SQLx docs say offline mode needs `cargo sqlx prepare` output checked into version control, and that `DATABASE_URL` takes precedence unless `SQLX_OFFLINE=true` is set. Keep `.env` local; commit `.env.example` and `.sqlx/`.
|
||||
@@ -0,0 +1,57 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
jobs:
|
||||
rust:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
|
||||
- name: cargo fmt
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
- name: cargo clippy
|
||||
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
|
||||
|
||||
- name: cargo test
|
||||
run: cargo test --workspace --all-features
|
||||
|
||||
# Operator UI (`ui/`): same checks you’d run locally before a control-plane bundle.
|
||||
ui:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ui
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: pnpm
|
||||
cache-dependency-path: ui/pnpm-lock.yaml
|
||||
|
||||
- name: pnpm install
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: TypeScript (no emit)
|
||||
run: pnpm run typecheck
|
||||
|
||||
- name: Prettier
|
||||
run: pnpm run format:check
|
||||
|
||||
- name: Vite production build
|
||||
run: pnpm run build
|
||||
@@ -0,0 +1,104 @@
|
||||
name: release
|
||||
run-name: Release ${{ github.ref_name }}
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: x86_64-unknown-linux-gnu,aarch64-unknown-linux-gnu
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: pnpm
|
||||
cache-dependency-path: ui/pnpm-lock.yaml
|
||||
|
||||
- name: Install cross
|
||||
run: cargo install cross --locked
|
||||
|
||||
- name: Cache cargo
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
target
|
||||
key: linux-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||
|
||||
- name: Build (armv7-musl with cross)
|
||||
run: |
|
||||
cross build --release --target armv7-unknown-linux-musleabihf -p wakey -p wakey-agent
|
||||
|
||||
- name: Build UI dist
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd ui
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build
|
||||
|
||||
- name: Build control-plane (linux-gnu)
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# x86_64 builds natively; aarch64 needs cross
|
||||
echo "Building control-plane x86_64-unknown-linux-gnu (native)"
|
||||
cargo build --release --target x86_64-unknown-linux-gnu -p wakey-control-plane
|
||||
|
||||
echo "Building control-plane aarch64-unknown-linux-gnu (cross)"
|
||||
cross build --release --target aarch64-unknown-linux-gnu -p wakey-control-plane
|
||||
|
||||
- name: Package rootfs tarball
|
||||
shell: pwsh
|
||||
run: |
|
||||
./scripts/package_rootfs.ps1 -Version "${{ github.ref_name }}" -Target armv7-unknown-linux-musleabihf
|
||||
|
||||
- name: Package control-plane bundles
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
chmod +x scripts/update_wakey_cc.sh scripts/package_wakey_cc_bundle.sh
|
||||
for target in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu; do
|
||||
./scripts/package_wakey_cc_bundle.sh --version "${{ github.ref_name }}" --target "$target"
|
||||
done
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wakey-rootfs
|
||||
path: dist/wakey-rootfs-*armv7-unknown-linux-musleabihf.tgz
|
||||
|
||||
- name: Upload control-plane bundles
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wakey-cc-bundles
|
||||
path: dist/wakey-cc-*unknown-linux-gnu.tgz
|
||||
|
||||
- name: Publish Release to GitHub
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
files: |
|
||||
dist/wakey-rootfs-*armv7-unknown-linux-musleabihf.tgz
|
||||
dist/wakey-cc-*unknown-linux-gnu.tgz
|
||||
@@ -18,3 +18,5 @@ target/
|
||||
#.idea/
|
||||
|
||||
.env
|
||||
|
||||
.codex
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agents (agent_id, agent_token) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "020b33576bfc2d171a051f903d40ccc78c972fa9d5d983a5678f03abbc8b8488"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT OR REPLACE INTO enroll_tokens (token, expires_at_unix) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "07d7f283daba2742e5522abf99074171ed484c03f70138be611e0c4b17e311b8"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO audit_events\n (event_key, event_id, ts_unix, actor_type, actor_id, agent_id, request_id,\n event_type, outcome, latency_ms, message, metadata_json)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 12
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "0c47aade9d5c71d6c7e2023c6ff66c6ab4b3a0dd2b78af3a600dedc89da508f2"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT COUNT(*) as \"count!: i64\" FROM enroll_tokens",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "count!: i64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "0ca58d0cbc25c59d2c956222d41c02eb0c76a135f29a56a7570b750f7378738d"
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT device_id as \"device_id!\", display_name as \"display_name!\",\n pinned, created_at_unix, updated_at_unix, notes\n FROM known_devices\n ORDER BY pinned DESC, display_name, device_id",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "device_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 2,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "created_at_unix",
|
||||
"ordinal": 3,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "updated_at_unix",
|
||||
"ordinal": 4,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "notes",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "15da60f9e43fa7098edf7c9fb5becfb518e9b30c5139fdb23283ed302e3da00f"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_meta (agent_id, nickname) VALUES (?1, ?2)\n ON CONFLICT(agent_id) DO UPDATE SET nickname = excluded.nickname",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "181992e554afdd8f21bd5df71bfb7880a5a9de28af8cd0c766d8d4aa649b3c90"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT COUNT(*) as \"count!: i64\" FROM agents",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "count!: i64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "21e5986ad3e8efd3393f2bc4929ee79e664cbc2b55948c276d52ca2a6fdc6a48"
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT identifier_key as \"identifier_key!\", device_id as \"device_id!\",\n kind as \"kind!\", value as \"value!\", created_at_unix\n FROM device_identifiers\n WHERE device_id = ?1\n ORDER BY kind, value",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "identifier_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "device_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "value!",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "created_at_unix",
|
||||
"ordinal": 4,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "2a7abe4d0ba22f991f490b45e2edcc980586116e92bac2c5394387b7052abe65"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO known_devices\n (device_id, display_name, pinned, created_at_unix, updated_at_unix, notes)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 6
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "2bff8b8b070f5b5dd946e754c5e15ea405f6c29baa4c2c31347f455227437ae2"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT 1 as \"ok!\"",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "ok!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "2c0dd5d9be90cc716da219c75c2d3b75dae8c0902c64ef5baa96c902f23abc5d"
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observation_key as \"observation_key!\", agent_id as \"agent_id!\",\n kind as \"kind!\", mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action as \"last_action!\"\n FROM agent_device_observations\n WHERE agent_id = ?1\n ORDER BY last_seen_unix DESC\n LIMIT ?2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "305f50ab2691e12c74e8a222ef12a16f14a65edd7b7c5400a196fd57a9788dcf"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT COUNT(*) as \"count!: i64\" FROM enroll_tokens WHERE expires_at_unix <= ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "count!: i64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5083fd5878c57f4d54e8b24ad0cef2771f7cac36afb7c370c65137fc0784f093"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agents WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "51cb6ec47368803af60114a39dd9e70ba9d31946bc39980c9e85dbc4e842a2c8"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_device_observations\n (observation_key, agent_id, kind, mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)\n ON CONFLICT(observation_key) DO UPDATE SET\n mac = excluded.mac,\n ip = excluded.ip,\n hostname = excluded.hostname,\n first_seen_unix = MIN(agent_device_observations.first_seen_unix, excluded.first_seen_unix),\n last_seen_unix = MAX(agent_device_observations.last_seen_unix, excluded.last_seen_unix),\n last_action = excluded.last_action",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 9
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "52d22161e936b39b57d119aab592426e88f60387ccba58888cc7d440012777ed"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT expires_at_unix FROM enroll_tokens WHERE token = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "expires_at_unix",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "540f57604aa987b97930bb0bcfe440094d97b769fd758fd5cffc32f6d5716bb4"
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT observation_key as \"observation_key!\", agent_id as \"agent_id!\",\n kind as \"kind!\", mac, ip, hostname,\n first_seen_unix, last_seen_unix, last_action as \"last_action!\"\n FROM agent_device_observations\n ORDER BY last_seen_unix DESC\n LIMIT ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "observation_key!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "mac",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ip",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "hostname",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "first_seen_unix",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_action!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5a0f37b5da194e432c795972d5b3bf67c2d2a00f379143d1ae5871ea790d1bf2"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT COUNT(*) as \"count!: i64\" FROM agents WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "count!: i64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "60c6631ace995d7ca109d1bee1d878c823edd40f15f8571b42e00680a120ad74"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM active_alerts",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "72afd48584f822116318c623f7dd42ddf4c82b337d8a3d52ed5973d52e08c163"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO device_identifiers\n (identifier_key, device_id, kind, value, created_at_unix)\n VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 5
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "7dc7edbbe5539f89783cbccb0475e676cb6d369b676b0c5aaedf99854ffbd760"
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT token as \"token!\", expires_at_unix FROM enroll_tokens ORDER BY expires_at_unix, token",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "token!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "expires_at_unix",
|
||||
"ordinal": 1,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "7f6c5c108953cd4eda8f4e1d4f4db6b3b88270d3d7087b2948362d0ea94ad246"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM agent_meta WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "8bf8470846bd228d2ea9b243f70f946f002915b9b1983bce818abc0ae3dd97f0"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM enroll_tokens WHERE token = ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "8f3499a2f461f738711b9942a9c9d6254c1f7ed0db54db8b3d65e10fa8dadfc9"
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agents.agent_id as \"agent_id!\", agent_meta.nickname\n FROM agents\n LEFT JOIN agent_meta ON agent_meta.agent_id = agents.agent_id\n ORDER BY agents.agent_id",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "nickname",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "977adb8bdfb9e031a738055fb81c02c6180ca9c37c90e39b3e4efb9168bd1944"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT COUNT(*) as \"count!: i64\" FROM meta WHERE key = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "count!: i64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "9f5d340530083d040794bed2a45b01522f57dc4132184dab0eb32d1b6811992d"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT device_id FROM device_identifiers WHERE identifier_key = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "device_id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "a1bca2de4e1328fa066d5a8703ef5b8bda560b234b9f1e75093827efeac10eec"
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT transition_id as \"transition_id!\", ts_unix, alert_id as \"alert_id!\",\n kind as \"kind!\", agent_id, from_status, to_status as \"to_status!\",\n message as \"message!\", metadata_json as \"metadata_json!\"\n FROM alert_transitions\n ORDER BY transition_key DESC\n LIMIT ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "transition_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ts_unix",
|
||||
"ordinal": 1,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "alert_id!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "from_status",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "to_status!",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "message!",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "metadata_json!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "a34accb5d8ef1fc90e1029b808956c85fa7cb00c0e879f27bbb99b5a76b5e151"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_id as \"agent_id!\" FROM agents ORDER BY agent_id",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "a5baac2d2f6dc38946ff15f6cba46ac085780e6521ba23a605a78b4b92a62073"
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT alert_id as \"alert_id!\", kind as \"kind!\", severity as \"severity!\",\n status as \"status!\", agent_id, message as \"message!\",\n value, threshold, last_seen_unix, metadata_json as \"metadata_json!\"\n FROM active_alerts",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "alert_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "severity!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "status!",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "message!",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "value",
|
||||
"ordinal": 6,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "threshold",
|
||||
"ordinal": 7,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "last_seen_unix",
|
||||
"ordinal": 8,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "metadata_json!",
|
||||
"ordinal": 9,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "b031d0fa0f9d0640555fc78b400b7bb951a3f013715fb5be51030c2be63e864d"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM known_devices WHERE device_id = ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "b1c6150ef7bd67ce78f8934fc5d451b36f5bed834d39bdde01356e331c5e5ddb"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT value FROM meta WHERE key = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "value",
|
||||
"ordinal": 0,
|
||||
"type_info": "Blob"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "b805f8dada38af1c79a7b3bbc063fd949bf81757705ace7173658de9f185868b"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO enroll_tokens (token, expires_at_unix) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "bee62978a2ce59095f9bc679258b5747e074a55d52c43b982ea019c79aff1479"
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT transition_id as \"transition_id!\", ts_unix, alert_id as \"alert_id!\",\n kind as \"kind!\", agent_id, from_status, to_status as \"to_status!\",\n message as \"message!\", metadata_json as \"metadata_json!\"\n FROM alert_transitions\n WHERE ts_unix >= ?1\n ORDER BY transition_key DESC\n LIMIT ?2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "transition_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "ts_unix",
|
||||
"ordinal": 1,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "alert_id!",
|
||||
"ordinal": 2,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "kind!",
|
||||
"ordinal": 3,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "agent_id",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "from_status",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "to_status!",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "message!",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "metadata_json!",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "ca117e134d45464a8930d0483ff8670d2798f38718c67f49adce06f74656bf2c"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "UPDATE known_devices SET updated_at_unix = ?1 WHERE device_id = ?2",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "d2c2ce1761d22477164b3e5cfde9718877b3b472886ae1dc7e64dc36ad75b2ea"
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT device_id as \"device_id!\", display_name as \"display_name!\",\n pinned, created_at_unix, updated_at_unix, notes\n FROM known_devices\n WHERE device_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "device_id!",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "display_name!",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "pinned",
|
||||
"ordinal": 2,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "created_at_unix",
|
||||
"ordinal": 3,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "updated_at_unix",
|
||||
"ordinal": 4,
|
||||
"type_info": "Integer"
|
||||
},
|
||||
{
|
||||
"name": "notes",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "db255767f7f0aae53f685a88a6127a80b89601cdf1163881c5ec07160fbaeeab"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT agent_token FROM agents WHERE agent_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "agent_token",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "e0def02317412d21994af8d7770a9e717f4be97e022c0f2022983d59391c775b"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM enroll_tokens WHERE expires_at_unix <= ?1",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "ee6d28dc501f6bb8cf1249ad03b82e3554f1167d5056f02a0cc823601f480e53"
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT COUNT(*) as \"count!: i64\" FROM known_devices WHERE device_id = ?1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "count!: i64",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "f18ab386ab1961e938ae7fec3e752bdd958118aa4ca81cab3421ac5827b04029"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO agent_device_observation_events\n (event_id, agent_id, kind, action, mac, ip, hostname, ts_unix)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 8
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "f94cb699c0b4202bc5611799c931ed5d566b3215fcaebdf564e614a417317871"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO meta (key, value) VALUES (?1, ?2)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 2
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "ffed939cfeecca1d46bdf77b67aca2919b34d496e729ad08f87ac9782fb8e382"
|
||||
}
|
||||
Generated
+723
-13
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "wakey"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
edition = "2024"
|
||||
publish = ["gitea"]
|
||||
|
||||
|
||||
@@ -23,13 +23,20 @@ service-first project with:
|
||||
In practice that means commands like:
|
||||
|
||||
```sh
|
||||
wakey status bedroom-pc
|
||||
wakey inventory bedroom-pc
|
||||
wakey leases --include-state
|
||||
wakey devs
|
||||
wakey wake bedroom-pc
|
||||
wakey wake --mac aa:bb:cc:dd:ee:ff
|
||||
```
|
||||
|
||||
(`inventory` is the canonical subcommand; `status` is a visible alias for the same behavior.)
|
||||
|
||||
## Architecture at a glance
|
||||
|
||||
- **On-router (local):** run `wakey` for `inventory`, `leases`, `devs`, and `wake` against live Linux neighbor/DHCP/interface data.
|
||||
- **Fleet (remote):** `wakey-agent` on each router enrolls with `wakey-control-plane`, keeps an authenticated WebSocket, and executes relayed commands using the same service logic as the local CLI.
|
||||
|
||||
## Workspace layout
|
||||
|
||||
- `wakey-core`
|
||||
@@ -54,7 +61,7 @@ Inside the `wakey` crate:
|
||||
|
||||
- `src/service`
|
||||
- the real use-case layer
|
||||
- status, leases, inventory, interfaces, wake, and query resolution
|
||||
- inventory, leases, interfaces, wake, and query resolution
|
||||
|
||||
The long-term direction is:
|
||||
|
||||
@@ -118,7 +125,7 @@ Example:
|
||||
data_dir = "/var/lib/wakey-control-plane"
|
||||
bind = "0.0.0.0:8080"
|
||||
public_url = "https://cp.example.com"
|
||||
state_file = "state.db"
|
||||
state_file = "state.sqlite3"
|
||||
pid_file = "wakey-control-plane.pid"
|
||||
ui_dist_dir = "/opt/wakey/ui/dist"
|
||||
command_timeout_ms = 30000
|
||||
@@ -133,9 +140,14 @@ json_logs = false
|
||||
If `telemetry.otlp_endpoint` is omitted, logs still work normally and only local
|
||||
structured logs are emitted.
|
||||
|
||||
State is persisted in an embedded `sled` database (default
|
||||
`/var/lib/wakey-control-plane/state.db`).
|
||||
State is persisted in an embedded SQLite database (default
|
||||
`/var/lib/wakey-control-plane/state.sqlite3`).
|
||||
Relative paths in config are resolved under `data_dir`.
|
||||
Legacy sled state can be imported explicitly:
|
||||
|
||||
```sh
|
||||
wakey-control-plane import-sled-state --from-sled-state /var/lib/wakey-control-plane/state.db --to-state-file /var/lib/wakey-control-plane/state.sqlite3
|
||||
```
|
||||
|
||||
Enroll tokens are now expiring and revocable. Issuance returns `expires_at_unix`.
|
||||
Expired tokens are rejected on enroll and can be garbage-collected periodically
|
||||
@@ -214,7 +226,7 @@ agent enrollment and websocket endpoints reachable.
|
||||
|
||||
An example Caddy config is provided at:
|
||||
|
||||
- `deploy/Caddyfile.control-plane.example`
|
||||
- `deploy/control-plane.Caddyfile`
|
||||
|
||||
Expected exposure model:
|
||||
|
||||
@@ -285,22 +297,24 @@ The update tarball is expected to contain:
|
||||
|
||||
`wakey` is usable as a local/operator CLI.
|
||||
|
||||
### Status
|
||||
### Inventory
|
||||
|
||||
Show device status rows using a free-form selector:
|
||||
Show merged device inventory rows using a free-form selector:
|
||||
|
||||
```sh
|
||||
wakey status bedroom-pc
|
||||
wakey inventory bedroom-pc
|
||||
```
|
||||
|
||||
Or use explicit filters:
|
||||
|
||||
```sh
|
||||
wakey status --dev br-lan --nud reachable
|
||||
wakey status --mac aa:bb:cc:dd:ee:ff
|
||||
wakey status --json
|
||||
wakey inventory --dev br-lan --nud reachable
|
||||
wakey inventory --mac aa:bb:cc:dd:ee:ff
|
||||
wakey inventory --json
|
||||
```
|
||||
|
||||
The `status` subcommand is an alias for `inventory` (same flags and output).
|
||||
|
||||
### Leases
|
||||
|
||||
Show DHCP leases:
|
||||
@@ -359,6 +373,10 @@ cargo test --no-run
|
||||
cargo clippy --all-targets --all-features -- -D warnings
|
||||
```
|
||||
|
||||
On GitHub Actions (`.github/workflows/ci.yml`), the same Rust checks run on
|
||||
`ubuntu-latest`, plus a separate **`ui`** job: `pnpm install --frozen-lockfile`
|
||||
in `ui/`, then `typecheck`, `format:check`, and `vite build`.
|
||||
|
||||
Focused control-plane state tests:
|
||||
|
||||
```sh
|
||||
|
||||
@@ -6,13 +6,13 @@
|
||||
#
|
||||
# Replace cp.example.com with your public control-plane domain.
|
||||
|
||||
cp.example.com {
|
||||
wakey.ldlda.com {
|
||||
encode zstd gzip
|
||||
|
||||
# Public agent-facing endpoints.
|
||||
@public path /healthz /api/v1/agents/enroll /api/v1/agent/ws
|
||||
handle @public {
|
||||
reverse_proxy 127.0.0.1:8787
|
||||
reverse_proxy 127.0.0.1:6767
|
||||
}
|
||||
|
||||
# Admin surface requires Cloudflare Access headers.
|
||||
@@ -21,7 +21,7 @@ cp.example.com {
|
||||
|
||||
handle @admin {
|
||||
handle @cf_access {
|
||||
reverse_proxy 127.0.0.1:8787
|
||||
reverse_proxy 127.0.0.1:6767
|
||||
}
|
||||
respond "forbidden" 403
|
||||
}
|
||||
@@ -5,8 +5,8 @@ Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=wakey
|
||||
Group=wakey
|
||||
User=lda
|
||||
Group=lda
|
||||
WorkingDirectory=/opt/wakey
|
||||
ExecStart=/opt/wakey/bin/wakey-control-plane serve --config-file /etc/wakey-control-plane/config.toml
|
||||
Restart=on-failure
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "lda-ipjs"
|
||||
description = "ip -j show schemas"
|
||||
version = "0.0.3"
|
||||
version = "0.0.4"
|
||||
edition = "2024"
|
||||
publish = ["gitea"]
|
||||
|
||||
|
||||
@@ -65,11 +65,11 @@ pub async fn get_with_handle(
|
||||
|
||||
for attr in msg.attributes {
|
||||
match attr {
|
||||
AddressAttribute::Address(addr) | AddressAttribute::Local(addr) => {
|
||||
if local.is_none() {
|
||||
AddressAttribute::Address(addr) | AddressAttribute::Local(addr)
|
||||
if local.is_none() =>
|
||||
{
|
||||
local = addr.to_string().parse().ok();
|
||||
}
|
||||
}
|
||||
AddressAttribute::Broadcast(addr) => {
|
||||
broadcast = addr.to_string().parse().ok();
|
||||
}
|
||||
|
||||
@@ -146,7 +146,9 @@ mod tests {
|
||||
|
||||
assert_eq!(link.operstate, Some(OperState::Up));
|
||||
assert_eq!(
|
||||
link.address.map(|mac| mac.to_string()).as_deref(),
|
||||
link.address
|
||||
.map(|mac| mac.to_string().to_ascii_lowercase())
|
||||
.as_deref(),
|
||||
Some("aa:bb:cc:dd:ee:ff")
|
||||
);
|
||||
}
|
||||
|
||||
+32
-4
@@ -45,6 +45,7 @@ This folder has small helpers for build, CI, and router install. Keep it simple;
|
||||
- Uploads to `<RemotePath>.tmp` then atomically moves into place; `-Restart` restarts the service; `-Quiet` silences MOTD.
|
||||
- `package_rootfs.ps1` — Produces `dist/wakey-rootfs-<version>-<target>.tgz` with `/root/.bin/wakey` and `/etc/init.d/*`.
|
||||
- `update_wakey_cc.sh` — Linux VPS updater for control-plane bundles; extracts into the selected directory (default: current directory) and restarts `wakey-cc.service`.
|
||||
- `update_wakey_cc_from_repo.sh` — Linux VPS source updater; clones repo to temp dir, builds UI + control-plane locally, packages bundle tgz, installs into selected directory, and restarts `wakey-cc.service`.
|
||||
- `package_wakey_cc_bundle.sh` — Produces `dist/wakey-cc-<version>-<target>.tgz` with `bin/wakey-control-plane`, `ui/dist/*`, updater script, and systemd template.
|
||||
- `publish.ps1` — Optional version bump + build + tag (and `cargo publish` only if you pass `-Publish`).
|
||||
- `test_remote.ps1` — Build ARM Linux test binaries locally, upload them to the router, and run them there.
|
||||
@@ -61,6 +62,20 @@ WAKEY_CC_VERSION=v0.2.0 WAKEY_CC_TARGET=x86_64-unknown-linux-gnu \
|
||||
sudo -E ./scripts/update_wakey_cc.sh
|
||||
```
|
||||
|
||||
## VPS source updater (control-plane)
|
||||
|
||||
Build-and-install locally on the VPS (avoids glibc mismatch from prebuilt binaries):
|
||||
|
||||
```sh
|
||||
chmod +x ./scripts/update_wakey_cc_from_repo.sh
|
||||
cd /opt/wakey
|
||||
sudo -E /path/to/repo/scripts/update_wakey_cc_from_repo.sh
|
||||
|
||||
# optional: pin ref/target and skip restart
|
||||
WAKEY_CC_REF=main WAKEY_CC_TARGET=x86_64-unknown-linux-gnu WAKEY_CC_NO_RESTART=1 \
|
||||
sudo -E /path/to/repo/scripts/update_wakey_cc_from_repo.sh
|
||||
```
|
||||
|
||||
Expected tarball layout:
|
||||
|
||||
- `bin/wakey-control-plane`
|
||||
@@ -79,7 +94,7 @@ Basic examples:
|
||||
```powershell
|
||||
./scripts/test_remote.ps1 -Package wakey
|
||||
./scripts/test_remote.ps1 -Package wakey -BinaryFilter integration_live_services -Ignored -NoCapture
|
||||
./scripts/test_remote.ps1 -Package wakey -BinaryFilter integration_live_services -Filter status_real_router_default_query_succeeds -Ignored -NoCapture
|
||||
./scripts/test_remote.ps1 -Package wakey -BinaryFilter integration_live_services -Filter inventory_real_router_default_query_returns_rows_or_empty_cleanly -Ignored -NoCapture
|
||||
./scripts/test_remote.ps1 -AllPackages
|
||||
```
|
||||
|
||||
@@ -113,13 +128,26 @@ Implementation notes:
|
||||
- each package run gets a unique remote temp directory for safer concurrent use
|
||||
- packages with no test executables are skipped instead of treated as failures
|
||||
|
||||
## Release checklist (tag push)
|
||||
|
||||
1. **Version:** bump crate versions / changelog as you prefer; tag `v*` and push.
|
||||
2. **Runner:** Fedora/WSL self-hosted labels `self-hosted`, `linux`, `fedora`, `wsl`, `release` online (see [`WSL_RUNNER.md`](./WSL_RUNNER.md)).
|
||||
3. **Control-plane bundle:** release job builds `ui/dist`, then `wakey-control-plane` for `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`. With **zig** + **cargo-zigbuild** on the runner, gnu builds use workflow env `WAKEY_CC_GLIBC_VERSION` (default `2.28`) for a predictable glibc floor; without them, binaries match the host glibc.
|
||||
4. **Artifacts:** expect `dist/wakey-rootfs-*-armv7-unknown-linux-musleabihf.tgz` and `dist/wakey-cc-*-unknown-linux-gnu.tgz` attached to the Gitea release.
|
||||
5. **Secret:** `GITEA_TOKEN` must be set for the publish step.
|
||||
|
||||
## CI (Gitea)
|
||||
|
||||
- Defined in `.gitea/workflows/release.yml`.
|
||||
- Release job now targets your Fedora/WSL runner labels: `self-hosted`, `linux`, `fedora`, `wsl`, `release`.
|
||||
- Steps: Linux-native build of `wakey` + `wakey-agent` → package rootfs → upload artifact (v3) → publish a release and attach tgz.
|
||||
- Defined in `.gitea/workflows/release.yml` (tag / manual dispatch): router rootfs + control-plane bundles and Gitea release attach.
|
||||
- Release job targets your Fedora/WSL runner labels: `self-hosted`, `linux`, `fedora`, `wsl`, `release`.
|
||||
- Requires `secrets.GITEA_TOKEN` in the repo to publish the release.
|
||||
|
||||
## CI (GitHub)
|
||||
|
||||
- Defined in `.github/workflows/ci.yml` on pushes/PRs to `main` or `master`:
|
||||
- **`rust` job:** `cargo fmt --check`, `clippy -D warnings`, `cargo test --workspace` on `ubuntu-latest`.
|
||||
- **`ui` job:** under `ui/`, `pnpm install --frozen-lockfile`, then `pnpm run typecheck`, `format:check`, and `build` (mirrors what you need before packaging the control-plane bundle). GitHub sets `CI=true` for the runner; pnpm uses lockfile `ui/pnpm-lock.yaml` for cache.
|
||||
|
||||
## Runner migration
|
||||
|
||||
- Fedora/WSL is now the intended release-builder path.
|
||||
|
||||
@@ -68,8 +68,12 @@ try {
|
||||
$initDestTmp = "$User@${HostName}:$initTmp"
|
||||
$localDeploy = Join-Path $repoRoot 'scripts/remote_deploy_wakey.sh'
|
||||
$localInit = Join-Path $repoRoot 'scripts/init/openwrt/wakey'
|
||||
$localDhcpHotplug = Join-Path $repoRoot 'scripts/hotplug/openwrt/dhcp/95-wakey'
|
||||
$localNeighHotplug = Join-Path $repoRoot 'scripts/hotplug/openwrt/neigh/95-wakey'
|
||||
$deployTmp = '/var/tmp/remote_deploy_wakey.sh'
|
||||
$deployPreferred = '/root/.bin/remote_deploy_wakey.sh'
|
||||
$dhcpHotplugTmp = '/var/tmp/wakey.hotplug.dhcp.tmp'
|
||||
$neighHotplugTmp = '/var/tmp/wakey.hotplug.neigh.tmp'
|
||||
|
||||
# Push binaries
|
||||
Invoke-Scp -Local $localBin -Dest $destTmp -Pass $Pass -HostKey $HostKey -Port $Port -Quiet:$Quiet -ForcePassword:$ForcePassword
|
||||
@@ -79,6 +83,12 @@ try {
|
||||
if (-not $SkipInitScript -and (Test-Path $localInit)) {
|
||||
Invoke-Scp -Local $localInit -Dest $initDestTmp -Pass $Pass -HostKey $HostKey -Port $Port -Quiet:$Quiet -ForcePassword:$ForcePassword
|
||||
}
|
||||
if (Test-Path $localDhcpHotplug) {
|
||||
Invoke-Scp -Local $localDhcpHotplug -Dest "$User@${HostName}:$dhcpHotplugTmp" -Pass $Pass -HostKey $HostKey -Port $Port -Quiet:$Quiet -ForcePassword:$ForcePassword
|
||||
}
|
||||
if (Test-Path $localNeighHotplug) {
|
||||
Invoke-Scp -Local $localNeighHotplug -Dest "$User@${HostName}:$neighHotplugTmp" -Pass $Pass -HostKey $HostKey -Port $Port -Quiet:$Quiet -ForcePassword:$ForcePassword
|
||||
}
|
||||
|
||||
# Push deploy helper if exists
|
||||
if (Test-Path $localDeploy) {
|
||||
@@ -103,6 +113,16 @@ if [ -f $initTmp ]; then
|
||||
fi
|
||||
"@
|
||||
})
|
||||
if [ -f $dhcpHotplugTmp ]; then
|
||||
sed -i "s/\r$//" $dhcpHotplugTmp 2>/dev/null || true
|
||||
mkdir -p /etc/hotplug.d/dhcp
|
||||
cp -f $dhcpHotplugTmp /etc/hotplug.d/dhcp/95-wakey
|
||||
fi
|
||||
if [ -f $neighHotplugTmp ]; then
|
||||
sed -i "s/\r$//" $neighHotplugTmp 2>/dev/null || true
|
||||
mkdir -p /etc/hotplug.d/neigh
|
||||
cp -f $neighHotplugTmp /etc/hotplug.d/neigh/95-wakey
|
||||
fi
|
||||
"@
|
||||
$remoteCmd = "sh -lc '$($script -replace "`r",'')'"
|
||||
if ($Quiet) { $remoteCmd += " >/dev/null 2>&1" }
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
|
||||
BIN="/root/.bin/wakey-agent"
|
||||
[ -x "$BIN" ] || BIN="$(command -v wakey-agent 2>/dev/null)"
|
||||
[ -n "$BIN" ] || exit 0
|
||||
[ -n "$ACTION" ] || exit 0
|
||||
[ -n "$MACADDR" ] || exit 0
|
||||
|
||||
if [ -n "$IPADDR" ] && [ -n "$HOSTNAME" ]; then
|
||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" --hostname "$HOSTNAME" >/dev/null 2>&1 || true
|
||||
elif [ -n "$IPADDR" ]; then
|
||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" >/dev/null 2>&1 || true
|
||||
elif [ -n "$HOSTNAME" ]; then
|
||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" --hostname "$HOSTNAME" >/dev/null 2>&1 || true
|
||||
else
|
||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" >/dev/null 2>&1 || true
|
||||
fi
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
|
||||
BIN="/root/.bin/wakey-agent"
|
||||
[ -x "$BIN" ] || BIN="$(command -v wakey-agent 2>/dev/null)"
|
||||
[ -n "$BIN" ] || exit 0
|
||||
[ -n "$ACTION" ] || exit 0
|
||||
|
||||
if [ -n "$MACADDR" ] && [ -n "$IPADDR" ]; then
|
||||
"$BIN" observe neigh --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" >/dev/null 2>&1 || true
|
||||
elif [ -n "$MACADDR" ]; then
|
||||
"$BIN" observe neigh --action "$ACTION" --mac "$MACADDR" >/dev/null 2>&1 || true
|
||||
elif [ -n "$IPADDR" ]; then
|
||||
"$BIN" observe neigh --action "$ACTION" --ip "$IPADDR" >/dev/null 2>&1 || true
|
||||
else
|
||||
"$BIN" observe neigh --action "$ACTION" >/dev/null 2>&1 || true
|
||||
fi
|
||||
@@ -71,6 +71,21 @@ Get-ChildItem (Join-Path $root 'scripts/init/openwrt') -File | ForEach-Object {
|
||||
Set-Content -NoNewline -LiteralPath $dest -Value $content -Encoding UTF8
|
||||
}
|
||||
|
||||
# Copy OpenWrt hotplug hooks.
|
||||
$hotplugSrc = Join-Path $root 'scripts/hotplug/openwrt'
|
||||
if (Test-Path $hotplugSrc) {
|
||||
Get-ChildItem $hotplugSrc -Directory | ForEach-Object {
|
||||
$hotplugTypeDir = Join-Path $staging ("etc/hotplug.d/" + $_.Name)
|
||||
New-Item -ItemType Directory -Force -Path $hotplugTypeDir | Out-Null
|
||||
Get-ChildItem $_.FullName -File | ForEach-Object {
|
||||
$dest = Join-Path $hotplugTypeDir $_.Name
|
||||
$content = Get-Content -Raw -LiteralPath $_.FullName
|
||||
$content = $content -replace "`r`n", "`n"
|
||||
Set-Content -NoNewline -LiteralPath $dest -Value $content -Encoding UTF8
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Copy helper scripts intended for /etc/ldlda_help
|
||||
$helpSrc = Join-Path $root 'scripts/ldlda_help'
|
||||
if (Test-Path $helpSrc) {
|
||||
|
||||
@@ -62,8 +62,9 @@ fi
|
||||
|
||||
[ -f "$BINARY" ] || { echo "missing binary: $BINARY" >&2; exit 1; }
|
||||
[ -f "$UI_DIST/index.html" ] || { echo "missing UI dist index: $UI_DIST/index.html" >&2; exit 1; }
|
||||
[ -f "scripts/update_wakey_cc.sh" ] || { echo "missing updater script" >&2; exit 1; }
|
||||
[ -f "scripts/update_wakey_cc.sh" ] && [ -f "scripts/update_wakey_cc_from_repo.sh" ] || { echo "missing updater scripts" >&2; exit 1; }
|
||||
[ -f "deploy/systemd/wakey-cc.service" ] || { echo "missing systemd template" >&2; exit 1; }
|
||||
[ -f "deploy/control-plane.Caddyfile" ] || { echo "missing Caddyfile" >&2; exit 1; }
|
||||
|
||||
mkdir -p "$OUT_DIR"
|
||||
STAGING="$OUT_DIR/wakey-cc-stage.$$"
|
||||
@@ -75,9 +76,11 @@ mkdir -p "$STAGING/bin" "$STAGING/ui" "$STAGING/scripts" "$STAGING/deploy/system
|
||||
cp "$BINARY" "$STAGING/bin/wakey-control-plane"
|
||||
cp -a "$UI_DIST" "$STAGING/ui/dist"
|
||||
cp "scripts/update_wakey_cc.sh" "$STAGING/scripts/update_wakey_cc.sh"
|
||||
cp "scripts/update_wakey_cc_from_repo.sh" "$STAGING/scripts/update_wakey_cc_from_repo.sh"
|
||||
cp "deploy/systemd/wakey-cc.service" "$STAGING/deploy/systemd/wakey-cc.service"
|
||||
cp "deploy/control-plane.Caddyfile" "$STAGING/deploy/control-plane.Caddyfile"
|
||||
|
||||
chmod +x "$STAGING/bin/wakey-control-plane" "$STAGING/scripts/update_wakey_cc.sh"
|
||||
chmod +x "$STAGING/bin/wakey-control-plane" "$STAGING/scripts/update_wakey_cc.sh" "$STAGING/scripts/update_wakey_cc_from_repo.sh" "$STAGING/deploy/control-plane.Caddyfile"
|
||||
|
||||
(
|
||||
cd "$STAGING"
|
||||
@@ -87,4 +90,4 @@ chmod +x "$STAGING/bin/wakey-control-plane" "$STAGING/scripts/update_wakey_cc.sh
|
||||
rm -rf "$STAGING"
|
||||
|
||||
echo "Bundle package: $OUT_DIR/$PKG"
|
||||
echo "Contains: bin/wakey-control-plane, ui/dist, scripts/update_wakey_cc.sh, deploy/systemd/wakey-cc.service"
|
||||
echo "Contains: bin/wakey-control-plane, ui/dist, scripts/update_wakey_cc.sh, scripts/update_wakey_cc_from_repo.sh, deploy/systemd/wakey-cc.service, deploy/control-plane.Caddyfile"
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
ROOT="$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
DB="${SQLX_PREPARE_DB:-/tmp/wakey-sqlx-prepare.sqlite3}"
|
||||
DATABASE_URL="sqlite://$DB"
|
||||
|
||||
if ! cargo sqlx --version >/dev/null 2>&1; then
|
||||
echo "cargo-sqlx is not installed." >&2
|
||||
echo "Install it with: cargo install sqlx-cli --no-default-features --features sqlite" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rm -f "$DB" "$DB-shm" "$DB-wal"
|
||||
|
||||
cd "$ROOT"
|
||||
DATABASE_URL="$DATABASE_URL" cargo sqlx database create
|
||||
DATABASE_URL="$DATABASE_URL" cargo sqlx migrate run --source wakey-control-plane/migrations
|
||||
DATABASE_URL="$DATABASE_URL" cargo sqlx prepare --workspace -- -p wakey-control-plane --all-targets --all-features
|
||||
|
||||
echo "SQLx metadata prepared in $ROOT/.sqlx"
|
||||
Executable
+155
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env sh
|
||||
# Build and install wakey-control-plane from repository source on the target host.
|
||||
# This avoids glibc baseline mismatches from prebuilt artifacts by building locally,
|
||||
# then packaging the same bundle format and installing it.
|
||||
#
|
||||
# Simplest use:
|
||||
# sudo -E ./scripts/update_wakey_cc_from_repo.sh
|
||||
#
|
||||
# Env options:
|
||||
# WAKEY_CC_REPO_URL Git URL (default: https://git.ldlda.com/lda/wakey.git)
|
||||
# WAKEY_CC_REF Git ref/branch/tag (default: main)
|
||||
# WAKEY_CC_TARGET Rust target triple (default from uname)
|
||||
# WAKEY_CC_ROOT Install root (default: current directory)
|
||||
# WAKEY_CC_SERVICE systemd unit name (default: wakey-cc.service)
|
||||
# WAKEY_CC_VERSION Bundle version label (default: v0.0.0-local-<short_sha>)
|
||||
# WAKEY_CC_NO_RESTART If set, skip systemd restart
|
||||
# WAKEY_CC_KEEP_TMP If set, keep temp checkout/build dir for debugging
|
||||
# SUDO Privilege escalation command/path (default: sudo when needed)
|
||||
#
|
||||
# Requires: git, cargo, tar, pnpm, systemctl (optional for restart)
|
||||
|
||||
set -eu
|
||||
|
||||
log() { printf '[update_wakey_cc_from_repo] %s\n' "$*"; }
|
||||
fail() {
|
||||
printf '[update_wakey_cc_from_repo] ERROR: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
default_target() {
|
||||
arch=$(uname -m)
|
||||
case "$arch" in
|
||||
x86_64)
|
||||
printf '%s' 'x86_64-unknown-linux-gnu'
|
||||
;;
|
||||
aarch64|arm64)
|
||||
printf '%s' 'aarch64-unknown-linux-gnu'
|
||||
;;
|
||||
*)
|
||||
fail "unsupported arch for default target mapping: $arch (set WAKEY_CC_TARGET explicitly)"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
require_cmd() {
|
||||
command -v "$1" >/dev/null 2>&1 || fail "required command not found: $1"
|
||||
}
|
||||
|
||||
sudo_cmd() {
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [ -n "${SUDO:-}" ]; then
|
||||
printf '%s' "$SUDO"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if command -v sudo >/dev/null 2>&1; then
|
||||
printf '%s' sudo
|
||||
return 0
|
||||
fi
|
||||
|
||||
fail 'root privileges are required for install/restart steps; set SUDO or run as root'
|
||||
}
|
||||
|
||||
main() {
|
||||
REPO_URL="${WAKEY_CC_REPO_URL:-https://git.ldlda.com/lda/wakey.git}"
|
||||
REF="${WAKEY_CC_REF:-main}"
|
||||
TARGET="${WAKEY_CC_TARGET:-$(default_target)}"
|
||||
ROOT="${WAKEY_CC_ROOT:-$PWD}"
|
||||
SERVICE="${WAKEY_CC_SERVICE:-wakey-cc.service}"
|
||||
SUDO_BIN=$(sudo_cmd)
|
||||
|
||||
require_cmd git
|
||||
require_cmd cargo
|
||||
require_cmd tar
|
||||
require_cmd pnpm
|
||||
|
||||
TMPBASE="${TMPDIR:-/tmp}"
|
||||
WORKDIR="$TMPBASE/wakey-cc-src.$$"
|
||||
STAGING="$TMPBASE/wakey-cc-stage.$$"
|
||||
|
||||
cleanup() {
|
||||
if [ -z "${WAKEY_CC_KEEP_TMP:-}" ]; then
|
||||
rm -rf "$WORKDIR" "$STAGING"
|
||||
else
|
||||
log "keeping temp dir: $WORKDIR"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
log "cloning $REPO_URL (ref: $REF)"
|
||||
git clone --depth 1 --branch "$REF" "$REPO_URL" "$WORKDIR" ||
|
||||
fail 'git clone failed'
|
||||
|
||||
cd "$WORKDIR"
|
||||
|
||||
log 'building UI dist'
|
||||
(
|
||||
cd ui
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build
|
||||
)
|
||||
|
||||
log "building control-plane target $TARGET"
|
||||
cargo build --release --target "$TARGET" -p wakey-control-plane ||
|
||||
fail 'cargo build failed'
|
||||
|
||||
SHA=$(git rev-parse --short HEAD)
|
||||
VERSION="${WAKEY_CC_VERSION:-v0.0.0-local-$SHA}"
|
||||
|
||||
log "packaging bundle version $VERSION"
|
||||
./scripts/package_wakey_cc_bundle.sh --version "$VERSION" --target "$TARGET" ||
|
||||
fail 'bundle packaging failed'
|
||||
|
||||
PKG="dist/wakey-cc-$VERSION-$TARGET.tgz"
|
||||
[ -f "$PKG" ] || fail "bundle not found: $PKG"
|
||||
|
||||
rm -rf "$STAGING"
|
||||
mkdir -p "$STAGING"
|
||||
tar -xzf "$PKG" -C "$STAGING" || fail 'bundle extract failed'
|
||||
|
||||
[ -f "$STAGING/bin/wakey-control-plane" ] || fail 'bundle missing bin/wakey-control-plane'
|
||||
[ -f "$STAGING/ui/dist/index.html" ] || fail 'bundle missing ui/dist/index.html'
|
||||
|
||||
if [ "$(id -u)" -ne 0 ] && [ -n "$SUDO_BIN" ]; then
|
||||
$SUDO_BIN mkdir -p "$ROOT"
|
||||
$SUDO_BIN cp -a "$STAGING/." "$ROOT/"
|
||||
else
|
||||
mkdir -p "$ROOT"
|
||||
cp -a "$STAGING/." "$ROOT/"
|
||||
fi
|
||||
|
||||
if [ -z "${WAKEY_CC_NO_RESTART:-}" ] && command -v systemctl >/dev/null 2>&1; then
|
||||
if systemctl list-unit-files "$SERVICE" >/dev/null 2>&1; then
|
||||
log "restarting $SERVICE"
|
||||
if [ "$(id -u)" -ne 0 ] && [ -n "$SUDO_BIN" ]; then
|
||||
$SUDO_BIN systemctl daemon-reload
|
||||
$SUDO_BIN systemctl restart "$SERVICE"
|
||||
$SUDO_BIN systemctl --no-pager --full status "$SERVICE" | sed -n '1,16p'
|
||||
else
|
||||
systemctl daemon-reload
|
||||
systemctl restart "$SERVICE"
|
||||
systemctl --no-pager --full status "$SERVICE" | sed -n '1,16p'
|
||||
fi
|
||||
else
|
||||
log "service $SERVICE not installed; skipped restart"
|
||||
fi
|
||||
fi
|
||||
|
||||
log "done: installed into $ROOT"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -25,6 +25,7 @@ pub struct Cli {
|
||||
#[derive(Subcommand)]
|
||||
pub enum Command {
|
||||
/// Show merged device inventory rows.
|
||||
#[command(visible_alias = "status")]
|
||||
Inventory(InventoryArgs),
|
||||
/// Show DHCP leases, optionally enriched with current neighbor state.
|
||||
Leases(LeasesArgs),
|
||||
@@ -32,6 +33,8 @@ pub enum Command {
|
||||
Wake(WakeArgs),
|
||||
/// Show condensed network interface summaries.
|
||||
Devs(DevsArgs),
|
||||
/// Record local hotplug observations.
|
||||
Observe(ObserveArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -115,6 +118,42 @@ pub struct DevsArgs {
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ObserveArgs {
|
||||
#[command(subcommand)]
|
||||
pub command: ObserveCommand,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum ObserveCommand {
|
||||
/// Observe a dnsmasq DHCP lease event.
|
||||
Dhcp(ObserveDhcpArgs),
|
||||
/// Observe a neighbor-table event.
|
||||
Neigh(ObserveNeighArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ObserveDhcpArgs {
|
||||
#[arg(long)]
|
||||
pub action: String,
|
||||
#[arg(long)]
|
||||
pub mac: macaddr::MacAddr,
|
||||
#[arg(long)]
|
||||
pub ip: Option<IpAddr>,
|
||||
#[arg(long)]
|
||||
pub hostname: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ObserveNeighArgs {
|
||||
#[arg(long)]
|
||||
pub action: String,
|
||||
#[arg(long)]
|
||||
pub mac: Option<macaddr::MacAddr>,
|
||||
#[arg(long)]
|
||||
pub ip: Option<IpAddr>,
|
||||
}
|
||||
|
||||
pub fn init_tracing(verbose: u8) {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.or_else(|_| EnvFilter::try_new(default_filter_for_verbosity(verbose)))
|
||||
@@ -205,6 +244,23 @@ pub async fn run(cli: Cli) -> Result<()> {
|
||||
println!("{}", table::render_devs_table(&devs));
|
||||
}
|
||||
}
|
||||
Command::Observe(args) => match args.command {
|
||||
ObserveCommand::Dhcp(args) => {
|
||||
let changed = wakey::observe_dhcp_event(
|
||||
&args.action,
|
||||
args.mac,
|
||||
args.ip,
|
||||
args.hostname.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
println!("observed=dhcp changed={changed}");
|
||||
}
|
||||
ObserveCommand::Neigh(args) => {
|
||||
let changed =
|
||||
wakey::observe_neighbor_event(&args.action, args.mac, args.ip).await?;
|
||||
println!("observed=neigh changed={changed}");
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+6
-3
@@ -1,12 +1,15 @@
|
||||
//! Operator-facing service API: inventory, leases, interfaces, wake, and query resolution.
|
||||
//! The `wakey` binary is Linux-only; use `wakey-agent` / `wakey-control-plane` for remote control.
|
||||
|
||||
pub mod service;
|
||||
pub mod utils;
|
||||
|
||||
pub use service::{
|
||||
broadcast_wake_targets, get_interface_summaries, get_interface_summary, get_ips, get_leases,
|
||||
inventory, leases_without_state, merge_devices, query_to_inventory_query, resolve_devices,
|
||||
resolve_query, resolve_selector, resolve_wake_targets, wake_explicit, wake_from_query,
|
||||
wake_targets,
|
||||
inventory, leases_without_state, merge_devices, resolve_devices, resolve_query,
|
||||
resolve_selector, resolve_wake_targets, wake_explicit, wake_from_query, wake_targets,
|
||||
};
|
||||
pub use wakey_linux::dhcp::{list_local_observations, observe_dhcp_event, observe_neighbor_event};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ use clap::Parser;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
Err(anyhow::anyhow!(
|
||||
"OS not supported! run this on your ahh router!"
|
||||
"wakey only runs on Linux (router/OpenWrt-style targets)."
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
+30
-28
@@ -59,8 +59,8 @@ pub fn merge_devices(
|
||||
.map(|(neighbors, leases)| Device::from_parts(neighbors, leases))
|
||||
.collect();
|
||||
|
||||
let mut texts: Vec<&str> = Vec::new();
|
||||
let mut devs: Vec<&str> = Vec::new();
|
||||
let mut texts = Vec::new();
|
||||
let mut devs = Vec::new();
|
||||
let mut ips = Vec::new();
|
||||
let mut macs = Vec::new();
|
||||
let mut nuds = Vec::new();
|
||||
@@ -72,35 +72,16 @@ pub fn merge_devices(
|
||||
Query::Ip(v) => ips.push(*v),
|
||||
Query::Mac(v) => macs.push(*v),
|
||||
Query::NeighborState(v) => nuds.push(*v),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if !texts.is_empty() {
|
||||
devices.retain(|device| device.names.iter().any(|n| texts.iter().any(|t| n == t)));
|
||||
}
|
||||
if !devs.is_empty() {
|
||||
devices.retain(|device| {
|
||||
device
|
||||
.interfaces
|
||||
.iter()
|
||||
.any(|iface| devs.iter().any(|d| iface == d))
|
||||
(texts.is_empty() || device.names.iter().any(|n| texts.contains(&n.as_str())))
|
||||
&& (devs.is_empty() || device.interfaces.iter().any(|i| devs.contains(&i.as_str()))) // same pattern as iter().any
|
||||
&& (ips.is_empty() || device.ips.iter().any(|ip| ips.contains(ip)))
|
||||
&& (macs.is_empty() || device.macs.iter().any(|mac| macs.contains(mac)))
|
||||
&& (nuds.is_empty() || device.neighbors.iter().any(|n| nuds.contains(&n.state)))
|
||||
});
|
||||
}
|
||||
if !ips.is_empty() {
|
||||
devices.retain(|device| device.ips.iter().any(|ip| ips.contains(ip)));
|
||||
}
|
||||
if !macs.is_empty() {
|
||||
devices.retain(|device| device.macs.iter().any(|mac| macs.contains(mac)));
|
||||
}
|
||||
if !nuds.is_empty() {
|
||||
devices.retain(|device| {
|
||||
device
|
||||
.neighbors
|
||||
.iter()
|
||||
.any(|neighbor| nuds.contains(&neighbor.state))
|
||||
});
|
||||
}
|
||||
|
||||
devices.sort_by(|a, b| {
|
||||
presence_rank(b.presence)
|
||||
.cmp(&presence_rank(a.presence))
|
||||
@@ -122,7 +103,7 @@ const fn presence_rank(presence: Presence) -> u8 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use wakey_core::{DhcpLease, InventoryQueryBuilder, NeighborState};
|
||||
use wakey_core::{DeviceId, DhcpLease, InventoryQueryBuilder, NeighborState};
|
||||
|
||||
fn sample_neighbors() -> Vec<NeighborEntry> {
|
||||
vec![NeighborEntry {
|
||||
@@ -173,4 +154,25 @@ mod tests {
|
||||
let out = merge_devices(sample_neighbors(), sample_leases(), &query);
|
||||
assert_eq!(out.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_devices_uses_ip_observed_id_when_mac_is_absent() {
|
||||
let query = InventoryQueryBuilder::new().build();
|
||||
let out = merge_devices(
|
||||
vec![NeighborEntry {
|
||||
ip: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20)),
|
||||
dev: Some("br-lan".to_string()),
|
||||
mac: None,
|
||||
state: NeighborState::Stale,
|
||||
}],
|
||||
Vec::new(),
|
||||
&query,
|
||||
);
|
||||
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(
|
||||
out[0].id,
|
||||
Some(DeviceId::Ip(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20))))
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ pub mod wake;
|
||||
pub use interfaces::{get_interface_summaries, get_interface_summary, get_ips};
|
||||
pub use inventory::{inventory, merge_devices, resolve_devices};
|
||||
pub use leases::{get_leases, leases_without_state};
|
||||
pub use query::{query_to_inventory_query, resolve_query, resolve_selector};
|
||||
pub use query::{resolve_query, resolve_selector};
|
||||
pub use wake::{
|
||||
broadcast_wake_targets, resolve_wake_targets, wake_explicit, wake_from_query, wake_targets,
|
||||
};
|
||||
+1
-12
@@ -2,11 +2,8 @@ use anyhow::Result;
|
||||
use wakey_core::{InventoryQuery, Query, QueryInput};
|
||||
|
||||
/// Resolve free-form user input into an `InventoryQuery` filter shape.
|
||||
///
|
||||
/// This is the compatibility entrypoint used by CLI and HTTP paths that still
|
||||
/// speak in terms of query/filter payloads.
|
||||
pub async fn resolve_query(input: impl Into<String>) -> Result<InventoryQuery> {
|
||||
query_to_inventory_query(resolve_selector(input).await?)
|
||||
Ok(vec![resolve_selector(input).await?])
|
||||
}
|
||||
|
||||
/// Classify one piece of free-form user input into a typed selector.
|
||||
@@ -24,11 +21,3 @@ pub async fn resolve_selector(input: impl Into<String>) -> Result<Query> {
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Convert the newer selector-oriented `Query` model into an `InventoryQuery`.
|
||||
///
|
||||
/// This keeps the old filter-based service and HTTP surfaces working while the
|
||||
/// internals migrate toward selector- and device-oriented APIs.
|
||||
pub fn query_to_inventory_query(query: Query) -> Result<InventoryQuery> {
|
||||
Ok(vec![query])
|
||||
}
|
||||
+9
-7
@@ -6,6 +6,7 @@ use wakey_core::{InterfaceSummary, WakeResult, WakeTarget};
|
||||
|
||||
use crate::service::interfaces::get_interface_summaries;
|
||||
use crate::service::inventory::resolve_devices;
|
||||
use crate::utils::product;
|
||||
|
||||
/// Send Wake-on-LAN packets for already-concrete wake targets.
|
||||
#[instrument(skip_all, fields(targets = targets.len()))]
|
||||
@@ -50,14 +51,15 @@ pub async fn wake_explicit(mac: MacAddr, ip: Option<IpAddr>) -> Result<WakeResul
|
||||
#[instrument(skip_all)]
|
||||
pub async fn resolve_wake_targets(input: impl Into<String>) -> Result<Vec<WakeTarget>> {
|
||||
let devices = resolve_devices(input).await?;
|
||||
|
||||
let targets: Vec<WakeTarget> = devices
|
||||
.into_iter()
|
||||
.flat_map(|device| {
|
||||
let mac = device.macs.first().copied();
|
||||
device
|
||||
.ips
|
||||
.into_iter()
|
||||
.map(move |ip| WakeTarget { ip: Some(ip), mac })
|
||||
// TRY EVERYTHING some has to work
|
||||
product(device.ips, device.macs).map(|(i, m)| WakeTarget {
|
||||
ip: Some(i),
|
||||
mac: Some(m),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
debug!(targets = targets.len(), "resolved wake targets");
|
||||
@@ -79,8 +81,8 @@ fn broadcast_wake_targets_from_interfaces(
|
||||
.iter()
|
||||
.flat_map(|iface| iface.addrs.iter())
|
||||
.filter_map(|addr| addr.broadcast)
|
||||
.map(|ip| WakeTarget {
|
||||
ip: Some(IpAddr::V4(ip)),
|
||||
.map(|br| WakeTarget {
|
||||
ip: Some(IpAddr::V4(br)), // some will hit eventually AHHH logic
|
||||
mac: Some(mac),
|
||||
})
|
||||
.collect();
|
||||
|
||||
+15
-1
@@ -1 +1,15 @@
|
||||
// Intentionally left empty.
|
||||
//! rare fns that belong nowhere
|
||||
|
||||
/// absolute dih cheese
|
||||
/// took some inspo from itertools
|
||||
pub fn product<A, B, T1, T2>(i1: T1, i2: T2) -> impl Iterator<Item = (A, B)>
|
||||
where
|
||||
A: Clone,
|
||||
T1: IntoIterator<Item = A>,
|
||||
T2: IntoIterator<Item = B>,
|
||||
T2::IntoIter: Clone,
|
||||
{
|
||||
let i2 = i2.into_iter();
|
||||
i1.into_iter()
|
||||
.flat_map(move |i1i| i2.clone().map(move |i2i| (i1i.clone(), i2i)))
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import * as React from "react";
|
||||
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
||||
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
}
|
||||
|
||||
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Backdrop.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Backdrop
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: DialogPrimitive.Popup.Props & {
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Popup
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-1/2 start-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 rtl:translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-2 end-2"
|
||||
size="icon-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Popup>
|
||||
</DialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close render={<Button variant="outline" />}>
|
||||
Close
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn(
|
||||
"font-heading text-base leading-none font-medium",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: DialogPrimitive.Description.Props) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
};
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
SelectTrigger,
|
||||
} from "@/components/ui/select";
|
||||
import { DeviceInventoryTable } from "@/pages/devices/DeviceInventoryTable";
|
||||
import { DeviceDetailsDialog } from "@/pages/devices/DeviceDetailsDialog";
|
||||
import { WakeHistoryCard } from "@/pages/devices/WakeHistoryCard";
|
||||
import type {
|
||||
DeviceRow,
|
||||
@@ -112,6 +113,7 @@ export function DevicesPage({
|
||||
const [bulkWakeBusy, setBulkWakeBusy] = useState(false);
|
||||
const [quickWake, setQuickWake] = useState("");
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([]);
|
||||
const [detailsDevice, setDetailsDevice] = useState<DeviceRow | null>(null);
|
||||
const [copyStatus, setCopyStatus] = useState("");
|
||||
const [recentWakes, setRecentWakes] = useState<WakeEvent[]>([]);
|
||||
function appendWakeEvent(event: WakeEvent) {
|
||||
@@ -288,9 +290,17 @@ export function DevicesPage({
|
||||
);
|
||||
}
|
||||
// Sort
|
||||
if (sort.key === "name") {
|
||||
result = [...result].sort((a, b) => {
|
||||
if (a.isUnnamed !== b.isUnnamed) return a.isUnnamed ? 1 : -1;
|
||||
const cmp = a.name.localeCompare(b.name);
|
||||
return sort.dir === "desc" ? -cmp : cmp;
|
||||
});
|
||||
} else {
|
||||
const sorter = sorters[sort.key];
|
||||
result = [...result].sort(sorter);
|
||||
if (sort.dir === "desc") result.reverse();
|
||||
}
|
||||
return result;
|
||||
}, [rows, query, sort, presenceFilter]);
|
||||
|
||||
@@ -342,7 +352,7 @@ export function DevicesPage({
|
||||
<span>Agent</span>
|
||||
<Select
|
||||
value={selectedAgentId}
|
||||
onValueChange={(value) => {
|
||||
onValueChange={(value: string | null) => {
|
||||
if (value) onSelectAgent(value);
|
||||
}}
|
||||
>
|
||||
@@ -505,6 +515,14 @@ export function DevicesPage({
|
||||
onSortChange={setSort}
|
||||
onWakeDevice={(device) => void wakeDevice(device)}
|
||||
onCopyValue={(label, value) => void copyValue(label, value)}
|
||||
onOpenDetails={setDetailsDevice}
|
||||
/>
|
||||
<DeviceDetailsDialog
|
||||
device={detailsDevice}
|
||||
open={Boolean(detailsDevice)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDetailsDevice(null);
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import type { DeviceRow } from "@/pages/devices/types";
|
||||
|
||||
type Props = {
|
||||
device: DeviceRow | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
};
|
||||
|
||||
function summarizeAll(values: string[]): string {
|
||||
if (!values.length) return "-";
|
||||
return values.join(", ");
|
||||
}
|
||||
|
||||
export function DeviceDetailsDialog({ device, open, onOpenChange }: Props) {
|
||||
if (!device) return null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl p-0">
|
||||
<div className="grid gap-4 p-4 text-sm">
|
||||
<DialogHeader className="pr-8">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<DialogTitle className="truncate">{device.name}</DialogTitle>
|
||||
<DialogDescription>Device details</DialogDescription>
|
||||
</div>
|
||||
<Badge variant="outline">{device.presence}</Badge>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 font-medium">IP addresses</p>
|
||||
<p className="text-muted-foreground">{summarizeAll(device.ips)}</p>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-1 font-medium">MAC addresses</p>
|
||||
<p className="text-muted-foreground">{summarizeAll(device.macs)}</p>
|
||||
</div>
|
||||
<Separator />
|
||||
<div>
|
||||
<p className="mb-1 font-medium">Interfaces</p>
|
||||
<p className="text-muted-foreground">
|
||||
{summarizeAll(device.interfaces)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Close
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ type Props = {
|
||||
onSortChange: (next: { key: SortKey; dir: SortDir }) => void;
|
||||
onWakeDevice: (device: DeviceRow) => void;
|
||||
onCopyValue: (label: string, value: string) => void;
|
||||
onOpenDetails: (device: DeviceRow) => void;
|
||||
};
|
||||
|
||||
function sortArrow(active: boolean, dir: SortDir) {
|
||||
@@ -48,7 +49,13 @@ export function DeviceInventoryTable({
|
||||
onSortChange,
|
||||
onWakeDevice,
|
||||
onCopyValue,
|
||||
onOpenDetails,
|
||||
}: Props) {
|
||||
function shouldIgnoreRowClick(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof Element)) return false;
|
||||
return Boolean(target.closest("button, input, a, [role='menuitem']"));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="device-list grid gap-2">
|
||||
<div className="device-row device-header rounded-md border bg-muted/60 px-3 py-2 text-sm">
|
||||
@@ -85,14 +92,26 @@ export function DeviceInventoryTable({
|
||||
>
|
||||
Presence {sortArrow(sort.key === "presence", sort.dir)}
|
||||
</span>
|
||||
<span className="device-cell">Interfaces</span>
|
||||
<span className="device-cell device-action">Actions</span>
|
||||
</div>
|
||||
|
||||
{rows.map((row) => (
|
||||
<div
|
||||
className="device-row rounded-md border bg-card px-3 py-2 text-sm"
|
||||
className="device-row cursor-pointer rounded-md border bg-card px-3 py-2 text-sm transition-colors hover:bg-accent/30"
|
||||
key={row.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(event) => {
|
||||
if (shouldIgnoreRowClick(event.target)) return;
|
||||
onOpenDetails(row);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (shouldIgnoreRowClick(event.target)) return;
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onOpenDetails(row);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="device-cell device-select" data-label="Pick">
|
||||
<input
|
||||
@@ -122,13 +141,6 @@ export function DeviceInventoryTable({
|
||||
<span className="device-cell" data-label="Presence">
|
||||
<Badge variant="outline">{row.presence}</Badge>
|
||||
</span>
|
||||
<span
|
||||
className="device-cell"
|
||||
data-label="Interfaces"
|
||||
title={row.interfaces.join(", ") || "-"}
|
||||
>
|
||||
{summarize(row.interfaces)}
|
||||
</span>
|
||||
<span className="device-cell device-action" data-label="">
|
||||
<Button
|
||||
onClick={() => onWakeDevice(row)}
|
||||
|
||||
@@ -52,11 +52,11 @@
|
||||
display: grid;
|
||||
grid-template-columns:
|
||||
36px minmax(110px, 1.1fr) minmax(160px, 2fr) minmax(130px, 1.5fr)
|
||||
minmax(100px, 0.85fr) minmax(100px, 0.9fr) minmax(170px, max-content);
|
||||
minmax(100px, 0.85fr) minmax(170px, max-content);
|
||||
align-items: center;
|
||||
column-gap: 0.4rem;
|
||||
row-gap: 0.55rem;
|
||||
min-width: 980px;
|
||||
min-width: 860px;
|
||||
}
|
||||
|
||||
.device-header {
|
||||
@@ -111,8 +111,7 @@
|
||||
"name name"
|
||||
"presence presence"
|
||||
"ip ip"
|
||||
"mac mac"
|
||||
"interfaces interfaces";
|
||||
"mac mac";
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -162,10 +161,6 @@
|
||||
grid-area: mac;
|
||||
}
|
||||
|
||||
.device-row .device-cell[data-label="Interfaces"] {
|
||||
grid-area: interfaces;
|
||||
}
|
||||
|
||||
.device-row .device-action {
|
||||
grid-area: action;
|
||||
justify-self: end;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export type DeviceRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
isUnnamed: boolean;
|
||||
ips: string[];
|
||||
macs: string[];
|
||||
interfaces: string[];
|
||||
|
||||
@@ -50,11 +50,13 @@ export function parseInventoryRows(payload: unknown): DeviceRow[] {
|
||||
: [];
|
||||
const presence =
|
||||
typeof device.presence === "string" ? device.presence : "unknown";
|
||||
const isUnnamed = names.length === 0;
|
||||
|
||||
const id = macs[0] || ips[0] || names[0] || `row-${idx}`;
|
||||
return {
|
||||
id,
|
||||
name: names[0] || "(unnamed)",
|
||||
isUnnamed,
|
||||
ips,
|
||||
macs,
|
||||
interfaces,
|
||||
@@ -122,9 +124,7 @@ export function parseWakeSummary(response: unknown): {
|
||||
}
|
||||
|
||||
export function chooseWakeTarget(device: DeviceRow): string {
|
||||
return device.name !== "(unnamed)"
|
||||
? device.name
|
||||
: device.macs[0] || device.ips[0] || "";
|
||||
return device.isUnnamed ? device.macs[0] || device.ips[0] || "" : device.name;
|
||||
}
|
||||
|
||||
export function summarize(values: string[]): string {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "wakey-agent"
|
||||
version = "0.0.1"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = ["gitea"]
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ pub enum Command {
|
||||
InitConfig(InitConfigArgs),
|
||||
/// Reload a running agent daemon by sending SIGHUP.
|
||||
Reload(ReloadArgs),
|
||||
/// Pass local hotplug observations through to the wakey CLI.
|
||||
Observe(ObserveArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -101,3 +103,39 @@ pub struct ReloadArgs {
|
||||
#[arg(long, default_value = DEFAULT_PID_FILE)]
|
||||
pub pid_file: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ObserveArgs {
|
||||
#[command(subcommand)]
|
||||
pub command: ObserveCommand,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum ObserveCommand {
|
||||
/// Observe a dnsmasq DHCP lease event.
|
||||
Dhcp(ObserveDhcpArgs),
|
||||
/// Observe a neighbor-table event.
|
||||
Neigh(ObserveNeighArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ObserveDhcpArgs {
|
||||
#[arg(long)]
|
||||
pub action: String,
|
||||
#[arg(long)]
|
||||
pub mac: String,
|
||||
#[arg(long)]
|
||||
pub ip: Option<String>,
|
||||
#[arg(long)]
|
||||
pub hostname: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ObserveNeighArgs {
|
||||
#[arg(long)]
|
||||
pub action: String,
|
||||
#[arg(long)]
|
||||
pub mac: Option<String>,
|
||||
#[arg(long)]
|
||||
pub ip: Option<String>,
|
||||
}
|
||||
@@ -1 +1,3 @@
|
||||
//! Outbound router agent: enrollment, websocket session, and dispatch into local wakey services.
|
||||
|
||||
pub mod protocol;
|
||||
+57
-2
@@ -9,7 +9,7 @@ mod tracing;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use cli::{Cli, Command, InitConfigArgs};
|
||||
use cli::{Cli, Command, InitConfigArgs, ObserveCommand};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
@@ -86,11 +86,66 @@ async fn main() -> Result<()> {
|
||||
::tracing::info!(pid_file = %args.pid_file.display(), "wakey-agent command: reload");
|
||||
serve::reload_daemon(&args.pid_file)?
|
||||
}
|
||||
Command::Observe(args) => observe(args)?,
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn observe(args: cli::ObserveArgs) -> Result<()> {
|
||||
let mut cmd = std::process::Command::new(resolve_wakey_binary());
|
||||
cmd.arg("observe");
|
||||
|
||||
match args.command {
|
||||
ObserveCommand::Dhcp(args) => {
|
||||
cmd.arg("dhcp")
|
||||
.arg("--action")
|
||||
.arg(args.action)
|
||||
.arg("--mac")
|
||||
.arg(args.mac);
|
||||
if let Some(ip) = args.ip {
|
||||
cmd.arg("--ip").arg(ip);
|
||||
}
|
||||
if let Some(hostname) = args.hostname {
|
||||
cmd.arg("--hostname").arg(hostname);
|
||||
}
|
||||
}
|
||||
ObserveCommand::Neigh(args) => {
|
||||
cmd.arg("neigh").arg("--action").arg(args.action);
|
||||
if let Some(mac) = args.mac {
|
||||
cmd.arg("--mac").arg(mac);
|
||||
}
|
||||
if let Some(ip) = args.ip {
|
||||
cmd.arg("--ip").arg(ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let status = cmd.status()?;
|
||||
if !status.success() {
|
||||
anyhow::bail!("wakey observe exited with {status}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_wakey_binary() -> std::path::PathBuf {
|
||||
if let Ok(current) = std::env::current_exe()
|
||||
&& let Some(dir) = current.parent()
|
||||
{
|
||||
let sibling = dir.join("wakey");
|
||||
if sibling.exists() {
|
||||
return sibling;
|
||||
}
|
||||
}
|
||||
|
||||
let root_bin = std::path::PathBuf::from("/root/.bin/wakey");
|
||||
if root_bin.exists() {
|
||||
return root_bin;
|
||||
}
|
||||
|
||||
"wakey".into()
|
||||
}
|
||||
|
||||
fn init_config(args: InitConfigArgs) -> Result<()> {
|
||||
if args.stdout && args.config.is_some() {
|
||||
anyhow::bail!("--stdout cannot be used with --config");
|
||||
@@ -109,7 +164,7 @@ fn init_config(args: InitConfigArgs) -> Result<()> {
|
||||
let cfg = config::AgentConfig {
|
||||
server_url: args
|
||||
.server_url
|
||||
.unwrap_or_else(|| "https://control-plane.example.com".to_string()),
|
||||
.unwrap_or_else(|| "https://wakey.ldlda.com".to_string()),
|
||||
agent_id: args
|
||||
.agent_id
|
||||
.unwrap_or_else(|| "REPLACE_ME_AGENT_ID".to_string()),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use anyhow::{Context, Result};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::Serialize;
|
||||
use std::net::IpAddr;
|
||||
use std::time::Instant;
|
||||
use tokio::time::{Duration, MissedTickBehavior, interval, sleep};
|
||||
@@ -36,7 +37,7 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
.unwrap_or_default()
|
||||
);
|
||||
let span = info_span!("agent_session", session_id = %session_id, agent_id = %config.agent_id);
|
||||
let _span_guard = span.enter();
|
||||
let _span_guard = span.enter(); // the ENTIRETY of below is agent_session.
|
||||
|
||||
let ws_url = websocket_url(&config.server_url)?;
|
||||
info!(%ws_url, agent_id = %config.agent_id, "connecting agent websocket");
|
||||
@@ -84,8 +85,11 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
.await?;
|
||||
info!(agent_id = %config.agent_id, "agent websocket session authenticated");
|
||||
|
||||
let http_client = reqwest::Client::new();
|
||||
let mut heartbeat = interval(Duration::from_secs(30));
|
||||
heartbeat.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let mut observation_sync = interval(Duration::from_secs(60));
|
||||
observation_sync.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
@@ -95,6 +99,11 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
}).await?;
|
||||
debug!(agent_id = %config.agent_id, "heartbeat sent");
|
||||
}
|
||||
_ = observation_sync.tick() => {
|
||||
if let Err(err) = send_agent_observations(&http_client, config).await {
|
||||
warn!(agent_id = %config.agent_id, error = %err, "failed to sync local observations");
|
||||
}
|
||||
}
|
||||
maybe_msg = source.next() => {
|
||||
let msg = match maybe_msg {
|
||||
Some(msg) => msg.context("websocket frame failed")?,
|
||||
@@ -135,6 +144,72 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct UploadAgentObservationsRequest {
|
||||
agent_id: String,
|
||||
agent_token: String,
|
||||
observations: Vec<AgentObservationRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct AgentObservationRequest {
|
||||
kind: String,
|
||||
action: String,
|
||||
mac: Option<String>,
|
||||
ip: Option<IpAddr>,
|
||||
hostname: Option<String>,
|
||||
first_seen_unix: u64,
|
||||
last_seen_unix: u64,
|
||||
}
|
||||
|
||||
async fn send_agent_observations(client: &reqwest::Client, config: &AgentConfig) -> Result<()> {
|
||||
let observations = wakey::list_local_observations()
|
||||
.await
|
||||
.context("failed to read local observations")?;
|
||||
if observations.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let url = observations_url(&config.server_url)?;
|
||||
let payload = UploadAgentObservationsRequest {
|
||||
agent_id: config.agent_id.clone(),
|
||||
agent_token: config.agent_token.clone(),
|
||||
observations: observations
|
||||
.into_iter()
|
||||
.map(|observation| AgentObservationRequest {
|
||||
kind: observation.kind,
|
||||
action: observation.action,
|
||||
mac: observation.mac,
|
||||
ip: observation.ip,
|
||||
hostname: observation.hostname,
|
||||
first_seen_unix: observation.first_seen_unix,
|
||||
last_seen_unix: observation.last_seen_unix,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
let response = client
|
||||
.post(url.clone())
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("failed to call observation endpoint {url}"))?;
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.unwrap_or_else(|_| "<unreadable error body>".to_string());
|
||||
anyhow::bail!("observation upload failed with {status}: {body}");
|
||||
}
|
||||
debug!(
|
||||
agent_id = %config.agent_id,
|
||||
observations = payload.observations.len(),
|
||||
"synced local observations"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn next_backoff_ms(current_ms: u64, max_ms: u64) -> u64 {
|
||||
let cap = max_ms.max(current_ms);
|
||||
current_ms.saturating_mul(2).min(cap)
|
||||
@@ -273,6 +348,14 @@ pub fn websocket_url(server_url: &str) -> Result<url::Url> {
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
pub fn observations_url(server_url: &str) -> Result<url::Url> {
|
||||
let mut url = url::Url::parse(server_url).context("invalid server_url")?;
|
||||
url.set_path("/api/v1/agents/observations");
|
||||
url.set_query(None);
|
||||
url.set_fragment(None);
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
async fn dns_resolution_diagnostics(ws_url: &url::Url) -> Option<(u64, usize)> {
|
||||
let host = ws_url.host_str()?;
|
||||
if host.parse::<IpAddr>().is_ok() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "wakey-control-plane"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
edition = "2024"
|
||||
publish = ["gitea"]
|
||||
|
||||
@@ -20,6 +20,14 @@ reqwest = { version = "0.13", default-features = false, features = [
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sled = "0.34"
|
||||
sqlx = { version = "0.8", features = [
|
||||
"runtime-tokio",
|
||||
"sqlite",
|
||||
"macros",
|
||||
"migrate",
|
||||
"uuid",
|
||||
"json",
|
||||
] }
|
||||
toml = "1.1"
|
||||
tokio = { version = "1", features = [
|
||||
"macros",
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
CREATE TABLE meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value BLOB NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE enroll_tokens (
|
||||
token TEXT PRIMARY KEY,
|
||||
expires_at_unix INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE agents (
|
||||
agent_id TEXT PRIMARY KEY,
|
||||
agent_token TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE agent_meta (
|
||||
agent_id TEXT PRIMARY KEY REFERENCES agents(agent_id) ON DELETE CASCADE,
|
||||
nickname TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE known_devices (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
pinned INTEGER NOT NULL,
|
||||
created_at_unix INTEGER NOT NULL,
|
||||
updated_at_unix INTEGER NOT NULL,
|
||||
notes TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE device_identifiers (
|
||||
identifier_key TEXT PRIMARY KEY,
|
||||
device_id TEXT NOT NULL REFERENCES known_devices(device_id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
created_at_unix INTEGER NOT NULL,
|
||||
UNIQUE(kind, value)
|
||||
);
|
||||
|
||||
CREATE INDEX device_identifiers_device_id_idx ON device_identifiers(device_id);
|
||||
|
||||
CREATE TABLE agent_device_observations (
|
||||
observation_key TEXT PRIMARY KEY,
|
||||
agent_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
mac TEXT,
|
||||
ip TEXT,
|
||||
hostname TEXT,
|
||||
first_seen_unix INTEGER NOT NULL,
|
||||
last_seen_unix INTEGER NOT NULL,
|
||||
last_action TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX agent_device_observations_agent_id_idx ON agent_device_observations(agent_id);
|
||||
CREATE INDEX agent_device_observations_mac_idx ON agent_device_observations(mac);
|
||||
CREATE INDEX agent_device_observations_ip_idx ON agent_device_observations(ip);
|
||||
CREATE INDEX agent_device_observations_hostname_idx ON agent_device_observations(hostname);
|
||||
CREATE INDEX agent_device_observations_last_seen_unix_idx ON agent_device_observations(last_seen_unix);
|
||||
|
||||
CREATE TABLE agent_device_observation_events (
|
||||
event_id TEXT PRIMARY KEY,
|
||||
agent_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
mac TEXT,
|
||||
ip TEXT,
|
||||
hostname TEXT,
|
||||
ts_unix INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX agent_device_observation_events_agent_ts_idx ON agent_device_observation_events(agent_id, ts_unix);
|
||||
CREATE INDEX agent_device_observation_events_mac_idx ON agent_device_observation_events(mac);
|
||||
|
||||
CREATE TABLE audit_events (
|
||||
event_key TEXT PRIMARY KEY,
|
||||
event_id TEXT NOT NULL UNIQUE,
|
||||
ts_unix INTEGER NOT NULL,
|
||||
actor_type TEXT NOT NULL,
|
||||
actor_id TEXT,
|
||||
agent_id TEXT,
|
||||
request_id TEXT,
|
||||
event_type TEXT NOT NULL,
|
||||
outcome TEXT NOT NULL,
|
||||
latency_ms INTEGER,
|
||||
message TEXT NOT NULL,
|
||||
metadata_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX audit_events_ts_unix_idx ON audit_events(ts_unix);
|
||||
CREATE INDEX audit_events_agent_id_idx ON audit_events(agent_id);
|
||||
CREATE INDEX audit_events_request_id_idx ON audit_events(request_id);
|
||||
CREATE INDEX audit_events_event_type_outcome_idx ON audit_events(event_type, outcome);
|
||||
|
||||
CREATE TABLE active_alerts (
|
||||
alert_id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
severity TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
agent_id TEXT,
|
||||
message TEXT NOT NULL,
|
||||
value INTEGER NOT NULL,
|
||||
threshold INTEGER NOT NULL,
|
||||
last_seen_unix INTEGER NOT NULL,
|
||||
metadata_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE alert_transitions (
|
||||
transition_key TEXT PRIMARY KEY,
|
||||
transition_id TEXT NOT NULL UNIQUE,
|
||||
ts_unix INTEGER NOT NULL,
|
||||
alert_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
agent_id TEXT,
|
||||
from_status TEXT,
|
||||
to_status TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
metadata_json TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX alert_transitions_ts_unix_idx ON alert_transitions(ts_unix);
|
||||
@@ -7,7 +7,10 @@ use tracing::{info, warn};
|
||||
|
||||
use crate::api::json_error;
|
||||
use crate::runtime::{AppState, SessionEvent};
|
||||
use crate::state::AuditEventInput;
|
||||
use crate::state::{
|
||||
AgentDeviceObservation, AgentDeviceObservationInput, AuditEventInput, DeviceIdentifierInput,
|
||||
KnownDeviceInput,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct EnrollRequest {
|
||||
@@ -72,6 +75,78 @@ pub struct StateStatsResponse {
|
||||
pub expired_enroll_token_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateKnownDeviceRequest {
|
||||
pub display_name: String,
|
||||
#[serde(default)]
|
||||
pub pinned: bool,
|
||||
pub notes: Option<String>,
|
||||
#[serde(default)]
|
||||
pub identifiers: Vec<DeviceIdentifierRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct DeviceIdentifierRequest {
|
||||
pub kind: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct KnownDeviceResponse {
|
||||
pub device_id: String,
|
||||
pub display_name: String,
|
||||
pub pinned: bool,
|
||||
pub created_at_unix: u64,
|
||||
pub updated_at_unix: u64,
|
||||
pub notes: Option<String>,
|
||||
pub identifiers: Vec<DeviceIdentifierResponse>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct DeviceIdentifierResponse {
|
||||
pub identifier_key: String,
|
||||
pub device_id: String,
|
||||
pub kind: String,
|
||||
pub value: String,
|
||||
pub created_at_unix: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ForgetKnownDeviceResponse {
|
||||
pub device_id: String,
|
||||
pub forgotten: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UploadAgentObservationsRequest {
|
||||
pub agent_id: String,
|
||||
pub agent_token: String,
|
||||
#[serde(default)]
|
||||
pub observations: Vec<AgentObservationRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AgentObservationRequest {
|
||||
pub kind: String,
|
||||
pub action: String,
|
||||
pub mac: Option<String>,
|
||||
pub ip: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
pub first_seen_unix: u64,
|
||||
pub last_seen_unix: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct UploadAgentObservationsResponse {
|
||||
pub accepted: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ListObservationsQuery {
|
||||
pub agent_id: Option<String>,
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
pub async fn healthz() -> &'static str {
|
||||
"ok"
|
||||
}
|
||||
@@ -407,6 +482,195 @@ pub async fn set_agent_nickname(
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_known_device(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<CreateKnownDeviceRequest>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
let input = KnownDeviceInput {
|
||||
display_name: req.display_name,
|
||||
pinned: req.pinned,
|
||||
notes: req.notes,
|
||||
identifiers: req
|
||||
.identifiers
|
||||
.into_iter()
|
||||
.map(|identifier| DeviceIdentifierInput {
|
||||
kind: identifier.kind,
|
||||
value: identifier.value,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
match state.store.create_known_device(input).await {
|
||||
Ok(device) => Ok((StatusCode::CREATED, Json(known_device_response(device)))),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to create known device");
|
||||
Err(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"create_known_device_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_known_devices(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
match state.store.list_known_devices().await {
|
||||
Ok(devices) => Ok((
|
||||
StatusCode::OK,
|
||||
Json(
|
||||
devices
|
||||
.into_iter()
|
||||
.map(known_device_response)
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to list known devices");
|
||||
Err(json_error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"list_known_devices_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn forget_known_device(
|
||||
State(state): State<AppState>,
|
||||
AxumPath(device_id): AxumPath<String>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
match state.store.forget_known_device(&device_id).await {
|
||||
Ok(forgotten) => Ok((
|
||||
StatusCode::OK,
|
||||
Json(ForgetKnownDeviceResponse {
|
||||
device_id,
|
||||
forgotten,
|
||||
}),
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to forget known device");
|
||||
Err(json_error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"forget_known_device_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn attach_device_identifier(
|
||||
State(state): State<AppState>,
|
||||
AxumPath(device_id): AxumPath<String>,
|
||||
Json(req): Json<DeviceIdentifierRequest>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
let input = DeviceIdentifierInput {
|
||||
kind: req.kind,
|
||||
value: req.value,
|
||||
};
|
||||
|
||||
match state
|
||||
.store
|
||||
.attach_device_identifier(&device_id, input)
|
||||
.await
|
||||
{
|
||||
Ok(Some(device)) => Ok((StatusCode::OK, Json(known_device_response(device)))),
|
||||
Ok(None) => Err(json_error(
|
||||
StatusCode::NOT_FOUND,
|
||||
"known_device_not_found",
|
||||
"known device not found",
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to attach device identifier");
|
||||
Err(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"attach_device_identifier_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn upload_agent_observations(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<UploadAgentObservationsRequest>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
if !state
|
||||
.store
|
||||
.verify_agent_token(&req.agent_id, &req.agent_token)
|
||||
.await
|
||||
{
|
||||
return Err(json_error(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"agent_auth_rejected",
|
||||
"agent credentials rejected",
|
||||
));
|
||||
}
|
||||
|
||||
let observations = req
|
||||
.observations
|
||||
.into_iter()
|
||||
.map(|observation| AgentDeviceObservationInput {
|
||||
kind: observation.kind,
|
||||
action: observation.action,
|
||||
mac: observation.mac,
|
||||
ip: observation.ip,
|
||||
hostname: observation.hostname,
|
||||
first_seen_unix: observation.first_seen_unix,
|
||||
last_seen_unix: observation.last_seen_unix,
|
||||
})
|
||||
.collect();
|
||||
|
||||
match state
|
||||
.store
|
||||
.upsert_agent_observations(&req.agent_id, observations)
|
||||
.await
|
||||
{
|
||||
Ok(accepted) => Ok((
|
||||
StatusCode::OK,
|
||||
Json(UploadAgentObservationsResponse { accepted }),
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, agent_id = %req.agent_id, "failed to upload agent observations");
|
||||
Err(json_error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"upload_observations_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_agent_observations(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<ListObservationsQuery>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
match state
|
||||
.store
|
||||
.list_agent_observations(query.agent_id.as_deref(), query.limit.unwrap_or(500))
|
||||
.await
|
||||
{
|
||||
Ok(observations) => Ok((
|
||||
StatusCode::OK,
|
||||
Json(
|
||||
observations
|
||||
.into_iter()
|
||||
.map(agent_observation_response) // no-op premium
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
)),
|
||||
Err(err) => {
|
||||
warn!(error = %err, "failed to list agent observations");
|
||||
Err(json_error(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"list_observations_failed",
|
||||
&err.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn state_stats(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||
@@ -431,3 +695,29 @@ pub async fn state_stats(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn agent_observation_response(observation: AgentDeviceObservation) -> AgentDeviceObservation {
|
||||
observation
|
||||
}
|
||||
|
||||
fn known_device_response(device: crate::state::KnownDevice) -> KnownDeviceResponse {
|
||||
KnownDeviceResponse {
|
||||
device_id: device.device_id,
|
||||
display_name: device.display_name,
|
||||
pinned: device.pinned,
|
||||
created_at_unix: device.created_at_unix,
|
||||
updated_at_unix: device.updated_at_unix,
|
||||
notes: device.notes,
|
||||
identifiers: device
|
||||
.identifiers
|
||||
.into_iter()
|
||||
.map(|identifier| DeviceIdentifierResponse {
|
||||
identifier_key: identifier.identifier_key,
|
||||
device_id: identifier.device_id,
|
||||
kind: identifier.kind,
|
||||
value: identifier.value,
|
||||
created_at_unix: identifier.created_at_unix,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,9 @@ pub use audit::list_audit_events;
|
||||
pub use commands::{list_agents, run_command};
|
||||
pub use control::{
|
||||
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
|
||||
StateStatsResponse, enroll, healthz, issue_enroll_token, list_enroll_tokens, revoke_agent,
|
||||
revoke_enroll_token, set_agent_nickname, state_stats,
|
||||
StateStatsResponse, attach_device_identifier, create_known_device, enroll, forget_known_device,
|
||||
healthz, issue_enroll_token, list_agent_observations, list_enroll_tokens, list_known_devices,
|
||||
revoke_agent, revoke_enroll_token, set_agent_nickname, state_stats, upload_agent_observations,
|
||||
};
|
||||
|
||||
pub fn json_error(
|
||||
|
||||
@@ -43,6 +43,8 @@ pub enum Command {
|
||||
RevokeAgent(RevokeAgentArgs),
|
||||
/// Print state backend stats.
|
||||
StateStats(StateStatsArgs),
|
||||
/// Import a legacy sled state directory into a SQLite state file.
|
||||
ImportSledState(ImportSledStateArgs),
|
||||
/// Send SIGHUP to an already-running daemon.
|
||||
Reload(ReloadArgs),
|
||||
}
|
||||
@@ -236,6 +238,18 @@ pub struct StateStatsArgs {
|
||||
pub target: AdminTargetArgs,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ImportSledStateArgs {
|
||||
#[arg(long)]
|
||||
pub from_sled_state: PathBuf,
|
||||
|
||||
#[arg(long)]
|
||||
pub to_state_file: PathBuf,
|
||||
|
||||
#[arg(long)]
|
||||
pub force: bool,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ReloadArgs {
|
||||
#[arg(long, default_value = DEFAULT_PID_FILE)]
|
||||
|
||||
@@ -40,7 +40,7 @@ pub fn write_init_config(args: &InitConfigArgs) -> Result<Option<PathBuf>> {
|
||||
let state_file_raw = args
|
||||
.state_file
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("state.db"));
|
||||
.unwrap_or_else(|| PathBuf::from("state.sqlite3"));
|
||||
let state_file = resolve_path(&data_dir, state_file_raw);
|
||||
|
||||
let pid_file_raw = args
|
||||
|
||||
@@ -49,7 +49,7 @@ impl DaemonConfig {
|
||||
.state_file
|
||||
.clone()
|
||||
.or(file.state_file)
|
||||
.unwrap_or_else(|| PathBuf::from("state.db"));
|
||||
.unwrap_or_else(|| PathBuf::from("state.sqlite3"));
|
||||
let state_file = resolve_path(&data_dir, state_file_raw);
|
||||
|
||||
let command_timeout = Duration::from_millis(
|
||||
@@ -255,7 +255,7 @@ fn resolve_state_access(
|
||||
&data_dir,
|
||||
cli_state_file
|
||||
.or(file.state_file)
|
||||
.unwrap_or_else(|| PathBuf::from("state.db")),
|
||||
.unwrap_or_else(|| PathBuf::from("state.sqlite3")),
|
||||
);
|
||||
|
||||
let resolved_public_url = cli_public_url
|
||||
@@ -288,8 +288,11 @@ mod tests {
|
||||
fn resolve_path_joins_relative_path() {
|
||||
let out = resolve_path(
|
||||
Path::new("/var/lib/wakey-control-plane"),
|
||||
PathBuf::from("state.db"),
|
||||
PathBuf::from("state.sqlite3"),
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
PathBuf::from("/var/lib/wakey-control-plane/state.sqlite3")
|
||||
);
|
||||
assert_eq!(out, PathBuf::from("/var/lib/wakey-control-plane/state.db"));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
//! HTTP + WebSocket control plane: agent enrollment, registry, command relay, and operator UI hosting.
|
||||
|
||||
mod api;
|
||||
mod cli;
|
||||
mod config;
|
||||
@@ -59,6 +61,10 @@ async fn main() -> Result<()> {
|
||||
tracing::init(cli.verbose, &config::TelemetryConfig::default())?;
|
||||
runtime::state_stats(args).await
|
||||
}
|
||||
Command::ImportSledState(args) => {
|
||||
tracing::init(cli.verbose, &config::TelemetryConfig::default())?;
|
||||
runtime::import_sled_state(args).await
|
||||
}
|
||||
Command::Reload(args) => {
|
||||
tracing::init(cli.verbose, &config::TelemetryConfig::default())?;
|
||||
runtime::reload_daemon(&args.pid_file)
|
||||
|
||||
@@ -4,8 +4,8 @@ use anyhow::{Context, Result};
|
||||
|
||||
use crate::api;
|
||||
use crate::cli::{
|
||||
IssueEnrollTokenArgs, ListEnrollTokensArgs, RevokeAgentArgs, RevokeEnrollTokenArgs,
|
||||
StateStatsArgs,
|
||||
ImportSledStateArgs, IssueEnrollTokenArgs, ListEnrollTokensArgs, RevokeAgentArgs,
|
||||
RevokeEnrollTokenArgs, StateStatsArgs,
|
||||
};
|
||||
use crate::config;
|
||||
use crate::state;
|
||||
@@ -276,3 +276,11 @@ pub async fn state_stats(args: StateStatsArgs) -> Result<()> {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn import_sled_state(args: ImportSledStateArgs) -> Result<()> {
|
||||
state::Store::import_sled_state(&args.from_sled_state, &args.to_state_file, args.force).await?;
|
||||
println!("from_sled_state={}", args.from_sled_state.display());
|
||||
println!("to_state_file={}", args.to_state_file.display());
|
||||
println!("imported=true");
|
||||
Ok(())
|
||||
}
|
||||
@@ -26,7 +26,9 @@ use crate::ws;
|
||||
mod admin;
|
||||
mod process;
|
||||
pub use admin::revoke_agent;
|
||||
pub use admin::{issue_enroll_token, list_enroll_tokens, revoke_enroll_token, state_stats};
|
||||
pub use admin::{
|
||||
import_sled_state, issue_enroll_token, list_enroll_tokens, revoke_enroll_token, state_stats,
|
||||
};
|
||||
pub use process::reload_daemon;
|
||||
use process::{remove_pid_file, write_pid_file};
|
||||
|
||||
@@ -62,12 +64,17 @@ fn public_api_routes(ui_dist_dir: std::path::PathBuf) -> Router<AppState> {
|
||||
|
||||
Router::new()
|
||||
.route("/ui", get(|| async { Redirect::temporary("/ui/") }))
|
||||
.route("/", get(|| async { Redirect::temporary("/ui/") })) // same as caddyfile
|
||||
.nest_service(
|
||||
"/ui/",
|
||||
get_service(ServeDir::new(ui_dist_dir).not_found_service(ServeFile::new(index_file))),
|
||||
)
|
||||
.route("/healthz", get(api::healthz))
|
||||
.route("/api/v1/agents/enroll", post(api::enroll))
|
||||
.route(
|
||||
"/api/v1/agents/observations",
|
||||
post(api::upload_agent_observations),
|
||||
)
|
||||
.route("/api/v1/agent/ws", get(ws::agent_ws))
|
||||
}
|
||||
|
||||
@@ -86,6 +93,22 @@ fn control_api_routes() -> Router<AppState> {
|
||||
axum::routing::delete(api::revoke_enroll_token),
|
||||
)
|
||||
.route("/api/v1/control/state-stats", get(api::state_stats))
|
||||
.route(
|
||||
"/api/v1/control/observations",
|
||||
get(api::list_agent_observations),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/control/devices",
|
||||
get(api::list_known_devices).post(api::create_known_device),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/control/devices/{device_id}",
|
||||
axum::routing::delete(api::forget_known_device),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/control/devices/{device_id}/identifiers",
|
||||
post(api::attach_device_identifier),
|
||||
)
|
||||
.route("/api/v1/control/audit/events", get(api::list_audit_events))
|
||||
.route("/api/v1/control/alerts", get(api::active_alerts))
|
||||
.route("/api/v1/control/alerts/history", get(api::alert_history))
|
||||
|
||||
@@ -2,4 +2,7 @@ mod store;
|
||||
mod types;
|
||||
|
||||
pub use store::Store;
|
||||
pub use types::{AlertState, AuditEvent, AuditEventFilter, AuditEventInput};
|
||||
pub use types::{
|
||||
AgentDeviceObservation, AgentDeviceObservationInput, AlertState, AuditEvent, AuditEventFilter,
|
||||
AuditEventInput, DeviceIdentifierInput, KnownDevice, KnownDeviceInput,
|
||||
};
|
||||
+1524
-375
File diff suppressed because it is too large.
Load diff
@@ -30,6 +30,64 @@ pub struct StateStats {
|
||||
pub expired_enroll_token_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KnownDevice {
|
||||
pub device_id: String,
|
||||
pub display_name: String,
|
||||
pub pinned: bool,
|
||||
pub created_at_unix: u64,
|
||||
pub updated_at_unix: u64,
|
||||
pub notes: Option<String>,
|
||||
pub identifiers: Vec<DeviceIdentifier>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DeviceIdentifier {
|
||||
pub identifier_key: String,
|
||||
pub device_id: String,
|
||||
pub kind: String,
|
||||
pub value: String,
|
||||
pub created_at_unix: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct KnownDeviceInput {
|
||||
pub display_name: String,
|
||||
pub pinned: bool,
|
||||
pub notes: Option<String>,
|
||||
pub identifiers: Vec<DeviceIdentifierInput>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DeviceIdentifierInput {
|
||||
pub kind: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AgentDeviceObservation {
|
||||
pub observation_key: String,
|
||||
pub agent_id: String,
|
||||
pub kind: String,
|
||||
pub mac: Option<String>,
|
||||
pub ip: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
pub first_seen_unix: u64,
|
||||
pub last_seen_unix: u64,
|
||||
pub last_action: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AgentDeviceObservationInput {
|
||||
pub kind: String,
|
||||
pub action: String,
|
||||
pub mac: Option<String>,
|
||||
pub ip: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
pub first_seen_unix: u64,
|
||||
pub last_seen_unix: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AuditEvent {
|
||||
pub event_id: String,
|
||||
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user