Compare commits
10
Commits
v0.2.2
..
eb83feaf97
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
/cache
|
||||||
|
/project.local.yml
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Completion Checklist
|
||||||
|
|
||||||
|
Before handing back code changes, run the smallest checks covering the changed area:
|
||||||
|
- Rust formatting: `cargo fmt`.
|
||||||
|
- For control-plane SQLx/state/API work: `cargo test -p wakey-control-plane` and `SQLX_OFFLINE=true cargo test -p wakey-control-plane`.
|
||||||
|
- For SQLx query macro changes: run `scripts/prepare_sqlx_sqlite.sh` and include the `.sqlx` metadata changes.
|
||||||
|
- For wakey-linux/core inventory/observation work: `cargo test -p wakey-linux -p wakey-core`.
|
||||||
|
- For agent session/config/protocol work: `cargo test -p wakey-agent`.
|
||||||
|
- For UI work: `pnpm --dir ui typecheck` and `pnpm --dir ui build`; use `pnpm --dir ui format` when touching TS/TSX/CSS formatting.
|
||||||
|
- Run relevant `cargo clippy -p <crate> --all-targets --all-features` when behavior or API shape changes.
|
||||||
|
|
||||||
|
Always check `git status --short` and mention unrelated dirty files or generated metadata in the final summary.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Wakey Project Overview
|
||||||
|
|
||||||
|
Wakey is a Wake-on-LAN and LAN observability workspace for Linux/OpenWrt routers. It includes:
|
||||||
|
- `wakey-core`: shared model and parsing types for devices, neighbors, DHCP, interfaces, wake results.
|
||||||
|
- `wakey-linux`: Linux/OpenWrt adapter layer for DHCP lease files, neighbor lookup, interface data, WoL sending, and local observation storage.
|
||||||
|
- root `wakey` crate: service layer and operator CLI for inventory, leases, devs, wake, and observe.
|
||||||
|
- `wakey-agent`: outbound router daemon. Enrolls with control plane, maintains authenticated websocket, executes relayed commands, syncs observations.
|
||||||
|
- `wakey-control-plane`: Axum control plane, SQLx SQLite state, agent registry, command relay, known devices, observations, audit/alerts, fleet APIs, static UI hosting.
|
||||||
|
- `ipjs`: typed wrappers around Linux `ip -j` data.
|
||||||
|
- `ui`: React/Vite operator UI using shadcn/base-ui style components.
|
||||||
|
|
||||||
|
Current persistence direction: control plane uses SQLx SQLite with migrations in `wakey-control-plane/migrations` and offline query metadata in `.sqlx` plus `wakey-control-plane/.sqlx`. Legacy sled import exists as explicit command.
|
||||||
|
|
||||||
|
Current product direction: fleet-first device UI and backend. Known device identity is manual. Observations/inventory provide suggestions/current state but should not automatically promote or delete durable identifiers.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Style And Conventions
|
||||||
|
|
||||||
|
Rust:
|
||||||
|
- Edition 2024.
|
||||||
|
- Prefer explicit, small service/API functions over large abstractions.
|
||||||
|
- Use `anyhow::Context` for fallible operations in application layers.
|
||||||
|
- Use `tracing` for logs.
|
||||||
|
- Shared domain types live in `wakey-core`; Linux/OpenWrt I/O in `wakey-linux`; root crate owns service/CLI behavior; agent/control-plane should reuse service/domain types where possible.
|
||||||
|
- SQLx query macros are used in control-plane state. Regenerate `.sqlx` metadata after query string changes.
|
||||||
|
- Device identity is manual: observations and inventory may suggest, but should not silently pin, merge, promote, or delete known identifiers.
|
||||||
|
- Hotplug observation actions should stay event-shaped (`add`, `update`, `remove`). Do not store NUD state as the action. NUD belongs to live neighbor/inventory data.
|
||||||
|
|
||||||
|
Frontend:
|
||||||
|
- React + Vite + TypeScript.
|
||||||
|
- Use existing component/style conventions; shadcn/base-ui/lucide are available.
|
||||||
|
- Main operator UI is fleet-first: common path is find device, inspect current IP/MAC/agent, wake, copy, remember/merge.
|
||||||
|
- Admin/debug pages stay available but should not dominate the primary nav.
|
||||||
|
|
||||||
|
Editing:
|
||||||
|
- Keep changes scoped.
|
||||||
|
- Preserve user edits in dirty worktrees.
|
||||||
|
- Use `apply_patch` for manual file edits.
|
||||||
|
- Default to ASCII unless files already use non-ASCII for a reason.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Suggested Commands
|
||||||
|
|
||||||
|
Rust formatting and checks:
|
||||||
|
- `cargo fmt`
|
||||||
|
- `cargo test -p wakey-control-plane`
|
||||||
|
- `SQLX_OFFLINE=true cargo test -p wakey-control-plane`
|
||||||
|
- `cargo test -p wakey-linux -p wakey-core`
|
||||||
|
- `cargo test -p wakey-agent` (may need elevated permissions if tests bind local sockets)
|
||||||
|
- `cargo clippy -p wakey-control-plane --all-targets --all-features`
|
||||||
|
- `cargo clippy -p wakey-linux -p wakey-core --all-targets --all-features`
|
||||||
|
|
||||||
|
SQLx metadata after query macro changes:
|
||||||
|
- `scripts/prepare_sqlx_sqlite.sh`
|
||||||
|
|
||||||
|
UI checks:
|
||||||
|
- `pnpm --dir ui typecheck`
|
||||||
|
- `pnpm --dir ui build`
|
||||||
|
- `pnpm --dir ui format`
|
||||||
|
|
||||||
|
Local run examples:
|
||||||
|
- `cargo run -- inventory <query>`
|
||||||
|
- `cargo run -- leases`
|
||||||
|
- `cargo run -- devs`
|
||||||
|
- `cargo run -- wake --mac aa:bb:cc:dd:ee:ff`
|
||||||
|
- `cargo run -p wakey-agent -- serve --config /etc/wakey-agent/config.toml`
|
||||||
|
- `cargo run -p wakey-control-plane -- serve --config-file /etc/wakey-control-plane/config.toml`
|
||||||
|
|
||||||
|
Useful shell tools:
|
||||||
|
- Prefer `rg` and `rg --files` for search.
|
||||||
|
- Use `git status --short`, `git diff --stat`, and focused `git diff -- <path>` before edits.
|
||||||
|
- Avoid destructive git commands unless explicitly requested.
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
# the name by which the project can be referenced within Serena
|
||||||
|
project_name: "wakey"
|
||||||
|
|
||||||
|
|
||||||
|
# list of languages for which language servers are started; choose from:
|
||||||
|
# al bash clojure cpp csharp
|
||||||
|
# csharp_omnisharp dart elixir elm erlang
|
||||||
|
# fortran fsharp go groovy haskell
|
||||||
|
# haxe java julia kotlin lua
|
||||||
|
# markdown
|
||||||
|
# matlab nix pascal perl php
|
||||||
|
# php_phpactor powershell python python_jedi r
|
||||||
|
# rego ruby ruby_solargraph rust scala
|
||||||
|
# swift terraform toml typescript typescript_vts
|
||||||
|
# vue yaml zig
|
||||||
|
# (This list may be outdated. For the current list, see values of Language enum here:
|
||||||
|
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
|
||||||
|
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
|
||||||
|
# Note:
|
||||||
|
# - For C, use cpp
|
||||||
|
# - For JavaScript, use typescript
|
||||||
|
# - For Free Pascal/Lazarus, use pascal
|
||||||
|
# Special requirements:
|
||||||
|
# Some languages require additional setup/installations.
|
||||||
|
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
|
||||||
|
# When using multiple languages, the first language server that supports a given file will be used for that file.
|
||||||
|
# The first language is the default language and the respective language server will be used as a fallback.
|
||||||
|
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
|
||||||
|
languages:
|
||||||
|
- rust
|
||||||
|
- typescript
|
||||||
|
|
||||||
|
# the encoding used by text files in the project
|
||||||
|
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
|
||||||
|
encoding: "utf-8"
|
||||||
|
|
||||||
|
# line ending convention to use when writing source files.
|
||||||
|
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
|
||||||
|
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
|
||||||
|
line_ending:
|
||||||
|
|
||||||
|
# The language backend to use for this project.
|
||||||
|
# If not set, the global setting from serena_config.yml is used.
|
||||||
|
# Valid values: LSP, JetBrains
|
||||||
|
# Note: the backend is fixed at startup. If a project with a different backend
|
||||||
|
# is activated post-init, an error will be returned.
|
||||||
|
language_backend:
|
||||||
|
|
||||||
|
# whether to use project's .gitignore files to ignore files
|
||||||
|
ignore_all_files_in_gitignore: true
|
||||||
|
|
||||||
|
# advanced configuration option allowing to configure language server-specific options.
|
||||||
|
# Maps the language key to the options.
|
||||||
|
# Have a look at the docstring of the constructors of the LS implementations within solidlsp (e.g., for C# or PHP) to see which options are available.
|
||||||
|
# No documentation on options means no options are available.
|
||||||
|
ls_specific_settings: {}
|
||||||
|
|
||||||
|
# list of additional paths to ignore in this project.
|
||||||
|
# Same syntax as gitignore, so you can use * and **.
|
||||||
|
# Note: global ignored_paths from serena_config.yml are also applied additively.
|
||||||
|
ignored_paths: []
|
||||||
|
|
||||||
|
# whether the project is in read-only mode
|
||||||
|
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||||
|
# Added on 2025-04-18
|
||||||
|
read_only: false
|
||||||
|
|
||||||
|
# list of tool names to exclude.
|
||||||
|
# This extends the existing exclusions (e.g. from the global configuration)
|
||||||
|
#
|
||||||
|
# Below is the complete list of tools for convenience.
|
||||||
|
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||||
|
# execute `uv run scripts/print_tool_overview.py`.
|
||||||
|
#
|
||||||
|
# * `activate_project`: Activates a project based on the project name or path.
|
||||||
|
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||||
|
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||||
|
# * `delete_memory`: Delete a memory file. Should only happen if a user asks for it explicitly,
|
||||||
|
# for example by saying that the information retrieved from a memory file is no longer correct
|
||||||
|
# or no longer relevant for the project.
|
||||||
|
# * `edit_memory`: Replaces content matching a regular expression in a memory.
|
||||||
|
# * `execute_shell_command`: Executes a shell command.
|
||||||
|
# * `find_file`: Finds files in the given relative paths
|
||||||
|
# * `find_referencing_symbols`: Finds symbols that reference the given symbol using the language server backend
|
||||||
|
# * `find_symbol`: Performs a global (or local) search using the language server backend.
|
||||||
|
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||||
|
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||||
|
# * `initial_instructions`: Provides instructions Serena usage (i.e. the 'Serena Instructions Manual')
|
||||||
|
# for clients that do not read the initial instructions when the MCP server is connected.
|
||||||
|
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||||
|
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||||
|
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||||
|
# * `list_memories`: List available memories. Any memory can be read using the `read_memory` tool.
|
||||||
|
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||||
|
# * `read_file`: Reads a file within the project directory.
|
||||||
|
# * `read_memory`: Read the content of a memory file. This tool should only be used if the information
|
||||||
|
# is relevant to the current task. You can infer whether the information
|
||||||
|
# is relevant from the memory file name.
|
||||||
|
# You should not read the same memory file multiple times in the same conversation.
|
||||||
|
# * `rename_memory`: Renames or moves a memory. Moving between project and global scope is supported
|
||||||
|
# (e.g., renaming "global/foo" to "bar" moves it from global to project scope).
|
||||||
|
# * `rename_symbol`: Renames a symbol throughout the codebase using language server refactoring capabilities.
|
||||||
|
# For JB, we use a separate tool.
|
||||||
|
# * `replace_content`: Replaces content in a file (optionally using regular expressions).
|
||||||
|
# * `replace_symbol_body`: Replaces the full definition of a symbol using the language server backend.
|
||||||
|
# * `safe_delete_symbol`:
|
||||||
|
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||||
|
# * `write_memory`: Write some information (utf-8-encoded) about this project that can be useful for future tasks to a memory in md format.
|
||||||
|
# The memory name should be meaningful.
|
||||||
|
excluded_tools: []
|
||||||
|
|
||||||
|
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
|
||||||
|
# This extends the existing inclusions (e.g. from the global configuration).
|
||||||
|
included_optional_tools: []
|
||||||
|
|
||||||
|
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
|
||||||
|
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
|
||||||
|
fixed_tools: []
|
||||||
|
|
||||||
|
# list of mode names to that are always to be included in the set of active modes
|
||||||
|
# The full set of modes to be activated is base_modes + default_modes.
|
||||||
|
# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
|
||||||
|
# Otherwise, this setting overrides the global configuration.
|
||||||
|
# Set this to [] to disable base modes for this project.
|
||||||
|
# Set this to a list of mode names to always include the respective modes for this project.
|
||||||
|
base_modes:
|
||||||
|
|
||||||
|
# list of mode names that are to be activated by default.
|
||||||
|
# The full set of modes to be activated is base_modes + default_modes.
|
||||||
|
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
|
||||||
|
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
|
||||||
|
# This setting can, in turn, be overridden by CLI parameters (--mode).
|
||||||
|
default_modes:
|
||||||
|
|
||||||
|
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||||
|
# (contrary to the memories, which are loaded on demand).
|
||||||
|
initial_prompt: ""
|
||||||
|
|
||||||
|
# time budget (seconds) per tool call for the retrieval of additional symbol information
|
||||||
|
# such as docstrings or parameter information.
|
||||||
|
# This overrides the corresponding setting in the global configuration; see the documentation there.
|
||||||
|
# If null or missing, use the setting from the global configuration.
|
||||||
|
symbol_info_budget:
|
||||||
|
|
||||||
|
# list of regex patterns which, when matched, mark a memory entry as read‑only.
|
||||||
|
# Extends the list from the global configuration, merging the two lists.
|
||||||
|
read_only_memory_patterns: []
|
||||||
|
|
||||||
|
# list of regex patterns for memories to completely ignore.
|
||||||
|
# Matching memories will not appear in list_memories or activate_project output
|
||||||
|
# and cannot be accessed via read_memory or write_memory.
|
||||||
|
# To access ignored memory files, use the read_file tool on the raw file path.
|
||||||
|
# Extends the list from the global configuration, merging the two lists.
|
||||||
|
# Example: ["_archive/.*", "_episodes/.*"]
|
||||||
|
ignored_memory_patterns: []
|
||||||
+86
@@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT events.event_id as \"event_id!\",\n ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) as \"observation_key!\",\n events.agent_id as \"agent_id!\",\n events.kind as \"kind!\",\n events.action as \"action!\",\n events.mac,\n events.ip,\n events.hostname,\n events.ts_unix,\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observation_events events\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE (?1 IS NULL OR events.agent_id = ?1)\n AND (?2 IS NULL OR events.kind = ?2)\n AND (?3 IS NULL OR events.mac = ?3)\n AND (?4 IS NULL OR events.ip = ?4)\n AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) = ?5)\n ORDER BY events.ts_unix DESC\n LIMIT ?6",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "event_id!",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "observation_key!",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "agent_id!",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "kind!",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "action!",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "mac",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ip",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "hostname",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ts_unix",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "device_id",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "display_name",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pinned",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 6
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "3bc141cecd0ba7c9ca937036b310728dff57c69ed7b74529fd81fa6a3c0e40cf"
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "UPDATE device_identifiers SET device_id = ?1 WHERE device_id = ?2",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "7247cc488921de2313a602697590502771a231bde7d03cd9ccac55a70971da45"
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM device_identifiers WHERE device_id = ?1 AND identifier_key = ?2",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "72aadefca9851a8becdd2dcce54b646aff095b64cef9837f5e8e4ea8dde71d02"
|
||||||
|
}
|
||||||
-86
@@ -1,86 +0,0 @@
|
|||||||
{
|
|
||||||
"db_name": "SQLite",
|
|
||||||
"query": "SELECT events.event_id as \"event_id!\",\n ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) as \"observation_key!\",\n events.agent_id as \"agent_id!\",\n events.kind as \"kind!\",\n events.action as \"action!\",\n events.mac,\n events.ip,\n events.hostname,\n events.ts_unix,\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observation_events events\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE (?1 IS NULL OR events.agent_id = ?1)\n AND (?2 IS NULL OR events.kind = ?2)\n AND (?3 IS NULL OR events.mac = ?3)\n AND (?4 IS NULL OR events.ip = ?4)\n AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) = ?5)\n ORDER BY events.ts_unix DESC\n LIMIT ?6",
|
|
||||||
"describe": {
|
|
||||||
"columns": [
|
|
||||||
{
|
|
||||||
"name": "event_id!",
|
|
||||||
"ordinal": 0,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "observation_key!",
|
|
||||||
"ordinal": 1,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "agent_id!",
|
|
||||||
"ordinal": 2,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "kind!",
|
|
||||||
"ordinal": 3,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "action!",
|
|
||||||
"ordinal": 4,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "mac",
|
|
||||||
"ordinal": 5,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "ip",
|
|
||||||
"ordinal": 6,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "hostname",
|
|
||||||
"ordinal": 7,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "ts_unix",
|
|
||||||
"ordinal": 8,
|
|
||||||
"type_info": "Integer"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "device_id",
|
|
||||||
"ordinal": 9,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "display_name",
|
|
||||||
"ordinal": 10,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "pinned",
|
|
||||||
"ordinal": 11,
|
|
||||||
"type_info": "Integer"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"parameters": {
|
|
||||||
"Right": 6
|
|
||||||
},
|
|
||||||
"nullable": [
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
false,
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
true
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"hash": "908d763909c76fb6170b818784e360372c02295523ef9970c91199db7d4f535a"
|
|
||||||
}
|
|
||||||
Generated
+5
-5
@@ -3701,7 +3701,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wakey"
|
name = "wakey"
|
||||||
version = "0.2.2"
|
version = "0.2.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chrono",
|
"chrono",
|
||||||
@@ -3722,7 +3722,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wakey-agent"
|
name = "wakey-agent"
|
||||||
version = "0.1.2"
|
version = "0.2.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -3746,7 +3746,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wakey-control-plane"
|
name = "wakey-control-plane"
|
||||||
version = "0.1.2"
|
version = "0.2.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"axum",
|
"axum",
|
||||||
@@ -3774,7 +3774,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wakey-core"
|
name = "wakey-core"
|
||||||
version = "0.2.2"
|
version = "0.2.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"macaddr",
|
"macaddr",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -3785,7 +3785,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wakey-linux"
|
name = "wakey-linux"
|
||||||
version = "0.2.2"
|
version = "0.2.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"futures",
|
"futures",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wakey"
|
name = "wakey"
|
||||||
version = "0.2.2"
|
version = "0.2.3"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = ["gitea"]
|
publish = ["gitea"]
|
||||||
|
|
||||||
|
|||||||
@@ -25,3 +25,11 @@ $remote = $files.ForEach({ "/etc/init.d/$_" })
|
|||||||
$remote | ForEach-Object {
|
$remote | ForEach-Object {
|
||||||
pscp.exe -l root -scp -pw $PASSWD "192.168.100.1:$_" "$initDir\"
|
pscp.exe -l root -scp -pw $PASSWD "192.168.100.1:$_" "$initDir\"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$files = "dhcp/95-wakey", "neigh/95-wakey"
|
||||||
|
$remote = $files.ForEach({ "/etc/hotplug.d/$_" })
|
||||||
|
$hotplugDir = Join-Path $PSScriptRoot 'hotplug.d'
|
||||||
|
|
||||||
|
$remote | ForEach-Object {
|
||||||
|
pscp.exe -l root -scp -pw $PASSWD "192.168.100.1:$_" "$hotplugDir\"
|
||||||
|
}
|
||||||
Regular → Executable
+23
-8
@@ -6,12 +6,27 @@ BIN="/root/.bin/wakey-agent"
|
|||||||
[ -n "$ACTION" ] || exit 0
|
[ -n "$ACTION" ] || exit 0
|
||||||
[ -n "$MACADDR" ] || exit 0
|
[ -n "$MACADDR" ] || exit 0
|
||||||
|
|
||||||
if [ -n "$IPADDR" ] && [ -n "$HOSTNAME" ]; then
|
run_wakey_agent() {
|
||||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" --hostname "$HOSTNAME" >/dev/null 2>&1 || true
|
if [ -n "$WAKEY_AGENT_CONFIG" ]; then
|
||||||
elif [ -n "$IPADDR" ]; then
|
set -- --config "$WAKEY_AGENT_CONFIG" "$@"
|
||||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" >/dev/null 2>&1 || true
|
fi
|
||||||
elif [ -n "$HOSTNAME" ]; then
|
if [ "$WAKEY_HOTPLUG_VERBOSE" = "1" ]; then
|
||||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" --hostname "$HOSTNAME" >/dev/null 2>&1 || true
|
set -- -v "$@"
|
||||||
else
|
fi
|
||||||
"$BIN" observe dhcp --action "$ACTION" --mac "$MACADDR" >/dev/null 2>&1 || true
|
# [ "$WAKEY_HOTPLUG_LOG" = "1" ] &&
|
||||||
|
if command -v logger >/dev/null 2>&1; then
|
||||||
|
"$BIN" "$@" 2>&1 | logger -t wakey-hotplug
|
||||||
|
else
|
||||||
|
"$BIN" "$@" >/dev/null 2>&1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ -n "$IPADDR" ] && [ -n "$HOSTNAME" ]; then
|
||||||
|
run_wakey_agent observe dhcp --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" --hostname "$HOSTNAME" || true
|
||||||
|
elif [ -n "$IPADDR" ]; then
|
||||||
|
run_wakey_agent observe dhcp --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" || true
|
||||||
|
elif [ -n "$HOSTNAME" ]; then
|
||||||
|
run_wakey_agent observe dhcp --action "$ACTION" --mac "$MACADDR" --hostname "$HOSTNAME" || true
|
||||||
|
else
|
||||||
|
run_wakey_agent observe dhcp --action "$ACTION" --mac "$MACADDR" || true
|
||||||
fi
|
fi
|
||||||
Regular → Executable
+23
-8
@@ -5,12 +5,27 @@ BIN="/root/.bin/wakey-agent"
|
|||||||
[ -n "$BIN" ] || exit 0
|
[ -n "$BIN" ] || exit 0
|
||||||
[ -n "$ACTION" ] || exit 0
|
[ -n "$ACTION" ] || exit 0
|
||||||
|
|
||||||
if [ -n "$MACADDR" ] && [ -n "$IPADDR" ]; then
|
run_wakey_agent() {
|
||||||
"$BIN" observe neigh --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" >/dev/null 2>&1 || true
|
if [ -n "$WAKEY_AGENT_CONFIG" ]; then
|
||||||
elif [ -n "$MACADDR" ]; then
|
set -- --config "$WAKEY_AGENT_CONFIG" "$@"
|
||||||
"$BIN" observe neigh --action "$ACTION" --mac "$MACADDR" >/dev/null 2>&1 || true
|
fi
|
||||||
elif [ -n "$IPADDR" ]; then
|
if [ "$WAKEY_HOTPLUG_VERBOSE" = "1" ]; then
|
||||||
"$BIN" observe neigh --action "$ACTION" --ip "$IPADDR" >/dev/null 2>&1 || true
|
set -- -v "$@"
|
||||||
else
|
fi
|
||||||
"$BIN" observe neigh --action "$ACTION" >/dev/null 2>&1 || true
|
# [ "$WAKEY_HOTPLUG_LOG" = "1" ] &&
|
||||||
|
if command -v logger >/dev/null 2>&1; then
|
||||||
|
"$BIN" "$@" 2>&1 | logger -t wakey-hotplug
|
||||||
|
else
|
||||||
|
"$BIN" "$@" >/dev/null 2>&1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ -n "$MACADDR" ] && [ -n "$IPADDR" ]; then
|
||||||
|
run_wakey_agent observe neigh --action "$ACTION" --mac "$MACADDR" --ip "$IPADDR" || true
|
||||||
|
elif [ -n "$MACADDR" ]; then
|
||||||
|
run_wakey_agent observe neigh --action "$ACTION" --mac "$MACADDR" || true
|
||||||
|
elif [ -n "$IPADDR" ]; then
|
||||||
|
run_wakey_agent observe neigh --action "$ACTION" --ip "$IPADDR" || true
|
||||||
|
else
|
||||||
|
run_wakey_agent observe neigh --action "$ACTION" || true
|
||||||
fi
|
fi
|
||||||
@@ -104,8 +104,10 @@ main() {
|
|||||||
# Ensure execute bits on staged files we know should be executable
|
# Ensure execute bits on staged files we know should be executable
|
||||||
for f in \
|
for f in \
|
||||||
"$STAGING/etc/init.d/"* \
|
"$STAGING/etc/init.d/"* \
|
||||||
|
"$STAGING/etc/hotplug.d/"*/* \
|
||||||
"$STAGING/etc/ldlda_help/"*.sh \
|
"$STAGING/etc/ldlda_help/"*.sh \
|
||||||
"$STAGING/root/.bin/wakey" \
|
"$STAGING/root/.bin/wakey" \
|
||||||
|
"$STAGING/root/.bin/wakey-agent" \
|
||||||
"$STAGING/root/.bin/kill_wakey.sh" \
|
"$STAGING/root/.bin/kill_wakey.sh" \
|
||||||
"$STAGING/root/.bin/remote_deploy_wakey.sh"; do
|
"$STAGING/root/.bin/remote_deploy_wakey.sh"; do
|
||||||
[ -e "$f" ] && chmod +x "$f" 2>/dev/null || true
|
[ -e "$f" ] && chmod +x "$f" 2>/dev/null || true
|
||||||
@@ -114,11 +116,14 @@ main() {
|
|||||||
# Normalize line endings for shell scripts (avoid CRLF issues on OpenWrt)
|
# Normalize line endings for shell scripts (avoid CRLF issues on OpenWrt)
|
||||||
for f in \
|
for f in \
|
||||||
"$STAGING/etc/init.d/"* \
|
"$STAGING/etc/init.d/"* \
|
||||||
|
"$STAGING/etc/hotplug.d/"*/* \
|
||||||
"$STAGING/etc/ldlda_help/"*.sh \
|
"$STAGING/etc/ldlda_help/"*.sh \
|
||||||
"$STAGING/root/.bin/"*.sh; do
|
"$STAGING/root/.bin/"*.sh; do
|
||||||
[ -f "$f" ] && sed -i 's/\r$//' "$f" 2>/dev/null || true
|
[ -f "$f" ] && sed -i 's/\r$//' "$f" 2>/dev/null || true
|
||||||
done
|
done
|
||||||
|
|
||||||
|
chown -R root:root "$STAGING" 2>/dev/null || true
|
||||||
|
|
||||||
# Copy staged tree into /
|
# Copy staged tree into /
|
||||||
tar -C "$STAGING" -cf - . | tar -C / -xpf - || fail "install copy failed"
|
tar -C "$STAGING" -cf - . | tar -C / -xpf - || fail "install copy failed"
|
||||||
|
|
||||||
|
|||||||
@@ -82,6 +82,9 @@ if (Test-Path $hotplugSrc) {
|
|||||||
$content = Get-Content -Raw -LiteralPath $_.FullName
|
$content = Get-Content -Raw -LiteralPath $_.FullName
|
||||||
$content = $content -replace "`r`n", "`n"
|
$content = $content -replace "`r`n", "`n"
|
||||||
Set-Content -NoNewline -LiteralPath $dest -Value $content -Encoding UTF8
|
Set-Content -NoNewline -LiteralPath $dest -Value $content -Encoding UTF8
|
||||||
|
if (Get-Command chmod -ErrorAction SilentlyContinue) {
|
||||||
|
chmod +x $dest
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -86,7 +86,7 @@ if ($Publish) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($Tag -and $Version) {
|
if ($Tag -and $Version) {
|
||||||
git tag -f "v$Version"
|
git tag -f -a "v$Version" -m "Release $Version"
|
||||||
git push -f origin "v$Version"
|
git push -f origin "v$Version"
|
||||||
Write-Host "Pushed tag: v$Version"
|
Write-Host "Pushed tag: v$Version"
|
||||||
|
|
||||||
|
|||||||
@@ -4,21 +4,30 @@
|
|||||||
# then packaging the same bundle format and installing it.
|
# then packaging the same bundle format and installing it.
|
||||||
#
|
#
|
||||||
# Simplest use:
|
# Simplest use:
|
||||||
# sudo -E ./scripts/update_wakey_cc_from_repo.sh
|
# ./scripts/update_wakey_cc_from_repo.sh
|
||||||
#
|
#
|
||||||
# Env options:
|
# Env options:
|
||||||
|
# WAKEY_CC_REPO_DIR Existing checkout to update/build instead of cloning
|
||||||
# WAKEY_CC_REPO_URL Git URL (default: https://git.ldlda.com/lda/wakey.git)
|
# 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_REF Git ref/branch/tag (default: main)
|
||||||
# WAKEY_CC_TARGET Rust target triple (default from uname)
|
# WAKEY_CC_TARGET Rust target triple (default from uname)
|
||||||
# WAKEY_CC_ROOT Install root (default: current directory)
|
# WAKEY_CC_ROOT Install root (default: current directory)
|
||||||
# WAKEY_CC_SERVICE systemd unit name (default: wakey-cc.service)
|
# WAKEY_CC_SERVICE systemd unit name (default: wakey-cc.service)
|
||||||
|
# WAKEY_CC_USER Owner for installed files/temp dirs (default: current user)
|
||||||
# WAKEY_CC_VERSION Bundle version label (default: v0.0.0-local-<short_sha>)
|
# WAKEY_CC_VERSION Bundle version label (default: v0.0.0-local-<short_sha>)
|
||||||
# WAKEY_CC_NO_RESTART If set, skip systemd restart
|
# WAKEY_CC_NO_RESTART If set, skip systemd restart
|
||||||
# WAKEY_CC_KEEP_TMP If set, keep temp checkout/build dir for debugging
|
# WAKEY_CC_KEEP_TMP If set, keep temp checkout/build dir for debugging
|
||||||
# SUDO Privilege escalation command/path (default: sudo when needed)
|
# SUDO Privilege escalation command/path for install steps (default: sudo)
|
||||||
#
|
#
|
||||||
# Requires: git, cargo, tar, pnpm, systemctl (optional for restart)
|
# Requires: git, cargo, tar, pnpm, systemctl (optional for restart)
|
||||||
|
|
||||||
|
# Common existing-checkout use:
|
||||||
|
: <<'USE CASE'
|
||||||
|
WAKEY_CC_REPO_DIR="$HOME/dev/wakey" \
|
||||||
|
WAKEY_CC_USER=lda \
|
||||||
|
WAKEY_CC_KEEP_TMP=1 \
|
||||||
|
scripts/update_wakey_cc_from_repo.sh
|
||||||
|
USE CASE
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
log() { printf '[update_wakey_cc_from_repo] %s\n' "$*"; }
|
log() { printf '[update_wakey_cc_from_repo] %s\n' "$*"; }
|
||||||
@@ -64,14 +73,83 @@ sudo_cmd() {
|
|||||||
fail 'root privileges are required for install/restart steps; set SUDO or run as root'
|
fail 'root privileges are required for install/restart steps; set SUDO or run as root'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
priv() {
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
$SUDO_BIN "$@"
|
||||||
|
else
|
||||||
|
"$@"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
restore_label() {
|
||||||
|
path=$1
|
||||||
|
if command -v restorecon >/dev/null 2>&1; then
|
||||||
|
priv restorecon "$path" || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
chown_if_requested() {
|
||||||
|
[ -n "${OWNER:-}" ] || return 0
|
||||||
|
priv chown -R "$OWNER:$OWNER" "$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
chmod_user_rw_if_requested() {
|
||||||
|
[ -n "${OWNER:-}" ] || return 0
|
||||||
|
priv chmod -R u+rwX "$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
update_existing_repo() {
|
||||||
|
repo_dir=$1
|
||||||
|
ref=$2
|
||||||
|
|
||||||
|
[ -d "$repo_dir/.git" ] || fail "WAKEY_CC_REPO_DIR is not a git checkout: $repo_dir"
|
||||||
|
|
||||||
|
log "using existing checkout $repo_dir (ref: $ref)"
|
||||||
|
git -C "$repo_dir" fetch --prune origin "$ref" || fail 'git fetch failed'
|
||||||
|
git -C "$repo_dir" checkout "$ref" || fail "git checkout failed: $ref"
|
||||||
|
git -C "$repo_dir" pull --ff-only origin "$ref" || fail 'git pull --ff-only failed'
|
||||||
|
}
|
||||||
|
|
||||||
|
install_executable_force() {
|
||||||
|
src=$1
|
||||||
|
dst=$2
|
||||||
|
dir=$(dirname "$dst")
|
||||||
|
tmp="$dst.new.$$"
|
||||||
|
old="$dst.old.$$"
|
||||||
|
|
||||||
|
priv mkdir -p "$dir"
|
||||||
|
priv rm -f "$tmp"
|
||||||
|
priv cp -f "$src" "$tmp"
|
||||||
|
priv chmod 0755 "$tmp"
|
||||||
|
chown_if_requested "$tmp"
|
||||||
|
if [ -e "$dst" ]; then
|
||||||
|
priv mv -f "$dst" "$old" || true
|
||||||
|
fi
|
||||||
|
priv mv -f "$tmp" "$dst"
|
||||||
|
priv rm -f "$old"
|
||||||
|
restore_label "$dst"
|
||||||
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
|
REPO_DIR="${WAKEY_CC_REPO_DIR:-}"
|
||||||
REPO_URL="${WAKEY_CC_REPO_URL:-https://git.ldlda.com/lda/wakey.git}"
|
REPO_URL="${WAKEY_CC_REPO_URL:-https://git.ldlda.com/lda/wakey.git}"
|
||||||
REF="${WAKEY_CC_REF:-main}"
|
REF="${WAKEY_CC_REF:-main}"
|
||||||
TARGET="${WAKEY_CC_TARGET:-$(default_target)}"
|
TARGET="${WAKEY_CC_TARGET:-$(default_target)}"
|
||||||
ROOT="${WAKEY_CC_ROOT:-$PWD}"
|
ROOT="${WAKEY_CC_ROOT:-$PWD}"
|
||||||
SERVICE="${WAKEY_CC_SERVICE:-wakey-cc.service}"
|
SERVICE="${WAKEY_CC_SERVICE:-wakey-cc.service}"
|
||||||
|
if [ -n "${WAKEY_CC_USER:-}" ]; then
|
||||||
|
OWNER="$WAKEY_CC_USER"
|
||||||
|
elif [ "$(id -u)" -eq 0 ]; then
|
||||||
|
OWNER=
|
||||||
|
else
|
||||||
|
OWNER=$(id -un)
|
||||||
|
fi
|
||||||
SUDO_BIN=$(sudo_cmd)
|
SUDO_BIN=$(sudo_cmd)
|
||||||
|
|
||||||
|
if [ -n "$OWNER" ] && ! id "$OWNER" >/dev/null 2>&1; then
|
||||||
|
fail "WAKEY_CC_USER does not exist: $OWNER"
|
||||||
|
fi
|
||||||
|
|
||||||
require_cmd git
|
require_cmd git
|
||||||
require_cmd cargo
|
require_cmd cargo
|
||||||
require_cmd tar
|
require_cmd tar
|
||||||
@@ -80,19 +158,34 @@ main() {
|
|||||||
TMPBASE="${TMPDIR:-/tmp}"
|
TMPBASE="${TMPDIR:-/tmp}"
|
||||||
WORKDIR="$TMPBASE/wakey-cc-src.$$"
|
WORKDIR="$TMPBASE/wakey-cc-src.$$"
|
||||||
STAGING="$TMPBASE/wakey-cc-stage.$$"
|
STAGING="$TMPBASE/wakey-cc-stage.$$"
|
||||||
|
CLONED_WORKDIR=1
|
||||||
|
|
||||||
cleanup() {
|
cleanup() {
|
||||||
if [ -z "${WAKEY_CC_KEEP_TMP:-}" ]; then
|
if [ -z "${WAKEY_CC_KEEP_TMP:-}" ]; then
|
||||||
rm -rf "$WORKDIR" "$STAGING"
|
[ "$CLONED_WORKDIR" = "0" ] || rm -rf "$WORKDIR"
|
||||||
|
rm -rf "$STAGING"
|
||||||
else
|
else
|
||||||
|
if [ "$CLONED_WORKDIR" != "0" ]; then
|
||||||
|
chown_if_requested "$WORKDIR"
|
||||||
|
chmod_user_rw_if_requested "$WORKDIR"
|
||||||
log "keeping temp dir: $WORKDIR"
|
log "keeping temp dir: $WORKDIR"
|
||||||
fi
|
fi
|
||||||
|
chown_if_requested "$STAGING"
|
||||||
|
chmod_user_rw_if_requested "$STAGING"
|
||||||
|
log "keeping temp dir: $STAGING"
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
trap cleanup EXIT INT TERM
|
trap cleanup EXIT INT TERM
|
||||||
|
|
||||||
|
if [ -n "$REPO_DIR" ]; then
|
||||||
|
WORKDIR=$REPO_DIR
|
||||||
|
CLONED_WORKDIR=0
|
||||||
|
update_existing_repo "$WORKDIR" "$REF"
|
||||||
|
else
|
||||||
log "cloning $REPO_URL (ref: $REF)"
|
log "cloning $REPO_URL (ref: $REF)"
|
||||||
git clone --depth 1 --branch "$REF" "$REPO_URL" "$WORKDIR" ||
|
git clone --depth 1 --branch "$REF" "$REPO_URL" "$WORKDIR" ||
|
||||||
fail 'git clone failed'
|
fail 'git clone failed'
|
||||||
|
fi
|
||||||
|
|
||||||
cd "$WORKDIR"
|
cd "$WORKDIR"
|
||||||
|
|
||||||
@@ -124,26 +217,29 @@ main() {
|
|||||||
[ -f "$STAGING/bin/wakey-control-plane" ] || fail 'bundle missing bin/wakey-control-plane'
|
[ -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'
|
[ -f "$STAGING/ui/dist/index.html" ] || fail 'bundle missing ui/dist/index.html'
|
||||||
|
|
||||||
if [ "$(id -u)" -ne 0 ] && [ -n "$SUDO_BIN" ]; then
|
priv mkdir -p "$ROOT"
|
||||||
$SUDO_BIN mkdir -p "$ROOT"
|
install_executable_force \
|
||||||
$SUDO_BIN cp -a "$STAGING/." "$ROOT/"
|
"$STAGING/bin/wakey-control-plane" \
|
||||||
else
|
"$ROOT/bin/wakey-control-plane"
|
||||||
mkdir -p "$ROOT"
|
priv cp -a "$STAGING/ui" "$ROOT/"
|
||||||
cp -a "$STAGING/." "$ROOT/"
|
priv cp -a "$STAGING/scripts" "$ROOT/"
|
||||||
fi
|
priv cp -a "$STAGING/deploy" "$ROOT/"
|
||||||
|
chown_if_requested \
|
||||||
|
"$ROOT/bin/wakey-control-plane" \
|
||||||
|
"$ROOT/ui" \
|
||||||
|
"$ROOT/scripts" \
|
||||||
|
"$ROOT/deploy"
|
||||||
|
chmod_user_rw_if_requested \
|
||||||
|
"$ROOT/ui" \
|
||||||
|
"$ROOT/scripts" \
|
||||||
|
"$ROOT/deploy"
|
||||||
|
|
||||||
if [ -z "${WAKEY_CC_NO_RESTART:-}" ] && command -v systemctl >/dev/null 2>&1; then
|
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
|
if systemctl list-unit-files "$SERVICE" >/dev/null 2>&1; then
|
||||||
log "restarting $SERVICE"
|
log "restarting $SERVICE"
|
||||||
if [ "$(id -u)" -ne 0 ] && [ -n "$SUDO_BIN" ]; then
|
priv systemctl daemon-reload
|
||||||
$SUDO_BIN systemctl daemon-reload
|
priv systemctl restart "$SERVICE"
|
||||||
$SUDO_BIN systemctl restart "$SERVICE"
|
priv systemctl --no-pager --full status "$SERVICE" | sed -n '1,16p'
|
||||||
$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
|
else
|
||||||
log "service $SERVICE not installed; skipped restart"
|
log "service $SERVICE not installed; skipped restart"
|
||||||
fi
|
fi
|
||||||
|
|||||||
+5
-5
@@ -46,7 +46,7 @@ pub struct LeasesArgs {
|
|||||||
)]
|
)]
|
||||||
pub include_state: bool,
|
pub include_state: bool,
|
||||||
/// Print machine-readable JSON instead of a table.
|
/// Print machine-readable JSON instead of a table.
|
||||||
#[arg(long)]
|
#[arg(long, short)]
|
||||||
pub json: bool,
|
pub json: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ pub struct WakeArgs {
|
|||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
pub ip: Option<IpAddr>,
|
pub ip: Option<IpAddr>,
|
||||||
/// Print machine-readable JSON instead of a table.
|
/// Print machine-readable JSON instead of a table.
|
||||||
#[arg(long)]
|
#[arg(short, long)]
|
||||||
pub json: bool,
|
pub json: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ pub struct InventoryArgs {
|
|||||||
#[arg(long = "mac")]
|
#[arg(long = "mac")]
|
||||||
pub macs: Vec<macaddr::MacAddr>,
|
pub macs: Vec<macaddr::MacAddr>,
|
||||||
/// Print machine-readable JSON instead of a table.
|
/// Print machine-readable JSON instead of a table.
|
||||||
#[arg(long)]
|
#[arg(short, long)]
|
||||||
pub json: bool,
|
pub json: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,10 +114,10 @@ pub struct DevsArgs {
|
|||||||
/// Optional interface name to show.
|
/// Optional interface name to show.
|
||||||
pub dev: Option<String>,
|
pub dev: Option<String>,
|
||||||
/// Show only interfaces whose operstate is `up`.
|
/// Show only interfaces whose operstate is `up`.
|
||||||
#[arg(long)]
|
#[arg(short, long)]
|
||||||
pub up: bool,
|
pub up: bool,
|
||||||
/// Print machine-readable JSON instead of a table.
|
/// Print machine-readable JSON instead of a table.
|
||||||
#[arg(long)]
|
#[arg(short, long)]
|
||||||
pub json: bool,
|
pub json: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+134
@@ -122,6 +122,63 @@ export type AgentDeviceObservationEvent = {
|
|||||||
known_device: KnownDeviceSummary | null;
|
known_device: KnownDeviceSummary | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type FleetDeviceAgent = {
|
||||||
|
agent_id: string;
|
||||||
|
nickname?: string | null;
|
||||||
|
connected: boolean;
|
||||||
|
last_seen_unix: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FleetWakeRoute = {
|
||||||
|
route_id: string;
|
||||||
|
agent_id: string;
|
||||||
|
nickname?: string | null;
|
||||||
|
connected: boolean;
|
||||||
|
mac: string | null;
|
||||||
|
ip: string | null;
|
||||||
|
hostname: string | null;
|
||||||
|
source: string;
|
||||||
|
last_seen_unix: number;
|
||||||
|
wakeable: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FleetDevice = {
|
||||||
|
device_key: string;
|
||||||
|
display_name: string;
|
||||||
|
known_device: KnownDeviceSummary | null;
|
||||||
|
pinned: boolean;
|
||||||
|
ips: string[];
|
||||||
|
macs: string[];
|
||||||
|
hostnames: string[];
|
||||||
|
agents: FleetDeviceAgent[];
|
||||||
|
sources: string[];
|
||||||
|
first_seen_unix: number | null;
|
||||||
|
last_seen_unix: number | null;
|
||||||
|
presence: string;
|
||||||
|
route_candidates: FleetWakeRoute[];
|
||||||
|
recommended_route: FleetWakeRoute | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RefreshFleetDevicesResponse = {
|
||||||
|
total_accepted: number;
|
||||||
|
agents: {
|
||||||
|
agent_id: string;
|
||||||
|
status: string;
|
||||||
|
accepted: number;
|
||||||
|
error: string | null;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WakeFleetDeviceResponse = {
|
||||||
|
route: FleetWakeRoute;
|
||||||
|
command: {
|
||||||
|
request_id: string;
|
||||||
|
status: string;
|
||||||
|
result?: unknown;
|
||||||
|
error?: { code: string; message: string; retryable?: boolean | null };
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
const res = await fetch(path, {
|
const res = await fetch(path, {
|
||||||
...init,
|
...init,
|
||||||
@@ -208,6 +265,57 @@ export function fetchKnownDevices(): Promise<KnownDevice[]> {
|
|||||||
return request<KnownDevice[]>("/api/v1/control/devices");
|
return request<KnownDevice[]>("/api/v1/control/devices");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function fetchFleetDevices(opts?: {
|
||||||
|
query?: string;
|
||||||
|
presence?: string;
|
||||||
|
known?: string;
|
||||||
|
agentId?: string;
|
||||||
|
limit?: number;
|
||||||
|
}): Promise<FleetDevice[]> {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (opts?.query) params.set("query", opts.query);
|
||||||
|
if (opts?.presence && opts.presence !== "all") {
|
||||||
|
params.set("presence", opts.presence);
|
||||||
|
}
|
||||||
|
if (opts?.known && opts.known !== "all") params.set("known", opts.known);
|
||||||
|
if (opts?.agentId) params.set("agent_id", opts.agentId);
|
||||||
|
params.set("limit", String(opts?.limit ?? 500));
|
||||||
|
return request<FleetDevice[]>(
|
||||||
|
`/api/v1/control/fleet/devices?${params.toString()}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function refreshFleetDevices(input?: {
|
||||||
|
agentIds?: string[];
|
||||||
|
timeoutMs?: number;
|
||||||
|
}): Promise<RefreshFleetDevicesResponse> {
|
||||||
|
return request<RefreshFleetDevicesResponse>(
|
||||||
|
"/api/v1/control/fleet/devices/refresh",
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
agent_ids: input?.agentIds ?? [],
|
||||||
|
timeout_ms: input?.timeoutMs ?? null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wakeFleetDevice(input: {
|
||||||
|
deviceKey: string;
|
||||||
|
routeId?: string | null;
|
||||||
|
timeoutMs?: number;
|
||||||
|
}): Promise<WakeFleetDeviceResponse> {
|
||||||
|
return request<WakeFleetDeviceResponse>("/api/v1/control/fleet/wake", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
device_key: input.deviceKey,
|
||||||
|
route_id: input.routeId ?? null,
|
||||||
|
timeout_ms: input.timeoutMs ?? null,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function fetchObservations(opts?: {
|
export function fetchObservations(opts?: {
|
||||||
agentId?: string;
|
agentId?: string;
|
||||||
limit?: number;
|
limit?: number;
|
||||||
@@ -270,6 +378,32 @@ export function attachObservationIdentifier(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function attachDeviceIdentifier(
|
||||||
|
deviceId: string,
|
||||||
|
identifier: { kind: string; value: string },
|
||||||
|
): Promise<KnownDevice> {
|
||||||
|
return request<KnownDevice>(
|
||||||
|
`/api/v1/control/devices/${encodeURIComponent(deviceId)}/identifiers`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(identifier),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mergeKnownDevice(
|
||||||
|
targetDeviceId: string,
|
||||||
|
sourceDeviceId: string,
|
||||||
|
): Promise<KnownDevice> {
|
||||||
|
return request<KnownDevice>(
|
||||||
|
`/api/v1/control/devices/${encodeURIComponent(targetDeviceId)}/merge`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ source_device_id: sourceDeviceId }),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function runCommand(
|
export function runCommand(
|
||||||
agentId: string,
|
agentId: string,
|
||||||
kind: CommandKind,
|
kind: CommandKind,
|
||||||
|
|||||||
+33
-11
@@ -1,18 +1,27 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { NavLink, Outlet } from "react-router-dom";
|
import { NavLink, Outlet } from "react-router-dom";
|
||||||
import { Moon, Sun } from "lucide-react";
|
import { ChevronDown, Moon, Sun } from "lucide-react";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
["/", "Devices"],
|
["/", "Devices"],
|
||||||
["/observations", "Observed"],
|
|
||||||
["/commands", "Wake Tools"],
|
|
||||||
["/dashboard", "Fleet Health"],
|
["/dashboard", "Fleet Health"],
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const adminItems = [
|
||||||
["/agents", "Agents"],
|
["/agents", "Agents"],
|
||||||
["/audit", "Audit"],
|
|
||||||
["/alerts", "Alerts"],
|
|
||||||
["/tokens", "Tokens"],
|
["/tokens", "Tokens"],
|
||||||
|
["/alerts", "Alerts"],
|
||||||
|
["/observations", "Raw Observations"],
|
||||||
|
["/commands", "Command Runner"],
|
||||||
|
["/audit", "Audit"],
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
type Theme = "light" | "dark";
|
type Theme = "light" | "dark";
|
||||||
@@ -41,11 +50,9 @@ export function AppLayout() {
|
|||||||
<div className="mx-auto max-w-7xl p-4">
|
<div className="mx-auto max-w-7xl p-4">
|
||||||
<header className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
<header className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-semibold tracking-tight">
|
<h1 className="text-2xl font-semibold tracking-tight">Wakey</h1>
|
||||||
Wakey Operator UI
|
|
||||||
</h1>
|
|
||||||
<p className="mt-1 text-sm text-muted-foreground">
|
<p className="mt-1 text-sm text-muted-foreground">
|
||||||
Find devices fast and wake them reliably
|
Fleet devices, presence, and wake controls
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
@@ -70,7 +77,7 @@ export function AppLayout() {
|
|||||||
</Button>
|
</Button>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<nav className="mb-3 flex flex-wrap gap-2">
|
<nav className="mb-3 flex flex-wrap items-center gap-2">
|
||||||
{navItems.map(([to, label]) => (
|
{navItems.map(([to, label]) => (
|
||||||
<NavLink
|
<NavLink
|
||||||
key={to}
|
key={to}
|
||||||
@@ -78,7 +85,7 @@ export function AppLayout() {
|
|||||||
end={to === "/"}
|
end={to === "/"}
|
||||||
className={({ isActive }) =>
|
className={({ isActive }) =>
|
||||||
[
|
[
|
||||||
"rounded-full border px-3 py-1.5 text-sm transition-colors",
|
"rounded-md border px-3 py-1.5 text-sm transition-colors",
|
||||||
isActive
|
isActive
|
||||||
? "border-primary/60 bg-primary/10 text-foreground"
|
? "border-primary/60 bg-primary/10 text-foreground"
|
||||||
: "border-border bg-card text-muted-foreground hover:text-foreground",
|
: "border-border bg-card text-muted-foreground hover:text-foreground",
|
||||||
@@ -88,6 +95,21 @@ export function AppLayout() {
|
|||||||
{label}
|
{label}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
))}
|
))}
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger className="inline-flex items-center gap-1 rounded-md border border-border bg-card px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground">
|
||||||
|
Admin / Debug
|
||||||
|
<ChevronDown className="size-4" aria-hidden />
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent className="w-48">
|
||||||
|
{adminItems.map(([to, label]) => (
|
||||||
|
<DropdownMenuItem key={to}>
|
||||||
|
<NavLink className="w-full" to={to}>
|
||||||
|
{label}
|
||||||
|
</NavLink>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<main>
|
<main>
|
||||||
|
|||||||
+750
-447
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wakey-agent"
|
name = "wakey-agent"
|
||||||
version = "0.1.2"
|
version = "0.2.3"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = ["gitea"]
|
publish = ["gitea"]
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ pub enum Command {
|
|||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub struct ServeArgs {
|
pub struct ServeArgs {
|
||||||
/// Path to the agent config file.
|
/// Path to the agent config file.
|
||||||
#[arg(long, default_value = config::DEFAULT_CONFIG_PATH)]
|
#[arg(long, short = 'c', default_value = config::DEFAULT_CONFIG_PATH)]
|
||||||
pub config: PathBuf,
|
pub config: PathBuf,
|
||||||
|
|
||||||
/// Path to pid file for reload signaling.
|
/// Path to pid file for reload signaling.
|
||||||
@@ -80,11 +80,11 @@ pub struct EnrollArgs {
|
|||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub struct InitConfigArgs {
|
pub struct InitConfigArgs {
|
||||||
/// Path to the agent config file to write. If omitted, config is printed to stdout.
|
/// Path to the agent config file to write. If omitted, config is printed to stdout.
|
||||||
#[arg(long)]
|
#[arg(long, short, visible_alias = "to", visible_short_alias = 't')]
|
||||||
pub config: Option<PathBuf>,
|
pub config: Option<PathBuf>,
|
||||||
|
|
||||||
/// Existing agent config to use as a base before applying explicit overrides.
|
/// Existing agent config to use as a base before applying explicit overrides.
|
||||||
#[arg(long)]
|
#[arg(long, short = 'f', visible_alias = "from")]
|
||||||
pub from_config: Option<PathBuf>,
|
pub from_config: Option<PathBuf>,
|
||||||
|
|
||||||
/// Print config to stdout.
|
/// Print config to stdout.
|
||||||
@@ -118,14 +118,14 @@ pub struct ReloadArgs {
|
|||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub struct SyncObservationsArgs {
|
pub struct SyncObservationsArgs {
|
||||||
/// Path to the agent config file.
|
/// Path to the agent config file.
|
||||||
#[arg(long, default_value = config::DEFAULT_CONFIG_PATH)]
|
#[arg(long, short, default_value = config::DEFAULT_CONFIG_PATH)]
|
||||||
pub config: PathBuf,
|
pub config: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub struct ObserveArgs {
|
pub struct ObserveArgs {
|
||||||
/// Path to the agent config file. If present, local path settings are passed through.
|
/// Path to the agent config file. If present, local path settings are passed through.
|
||||||
#[arg(long, global = true, default_value = config::DEFAULT_CONFIG_PATH)]
|
#[arg(long, short, global = true, default_value = config::DEFAULT_CONFIG_PATH)]
|
||||||
pub config: PathBuf,
|
pub config: PathBuf,
|
||||||
|
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
|
|||||||
@@ -124,12 +124,21 @@ async fn main() -> Result<()> {
|
|||||||
fn observe(args: cli::ObserveArgs) -> Result<()> {
|
fn observe(args: cli::ObserveArgs) -> Result<()> {
|
||||||
let mut cmd = std::process::Command::new(resolve_wakey_binary());
|
let mut cmd = std::process::Command::new(resolve_wakey_binary());
|
||||||
cmd.arg("observe");
|
cmd.arg("observe");
|
||||||
|
let config_path = args.config.clone();
|
||||||
if let Ok(config) = config::load_config(&args.config) {
|
if let Ok(config) = config::load_config(&args.config) {
|
||||||
config::apply_local_path_env_to_command(&mut cmd, &config);
|
config::apply_local_path_env_to_command(&mut cmd, &config);
|
||||||
}
|
}
|
||||||
|
|
||||||
match args.command {
|
match args.command {
|
||||||
ObserveCommand::Dhcp(args) => {
|
ObserveCommand::Dhcp(args) => {
|
||||||
|
::tracing::debug!(
|
||||||
|
action = %args.action,
|
||||||
|
mac = %args.mac,
|
||||||
|
ip = ?args.ip,
|
||||||
|
hostname = ?args.hostname,
|
||||||
|
config = %config_path.display(),
|
||||||
|
"forwarding dhcp observation to wakey"
|
||||||
|
);
|
||||||
cmd.arg("dhcp")
|
cmd.arg("dhcp")
|
||||||
.arg("--action")
|
.arg("--action")
|
||||||
.arg(args.action)
|
.arg(args.action)
|
||||||
@@ -143,6 +152,13 @@ fn observe(args: cli::ObserveArgs) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ObserveCommand::Neigh(args) => {
|
ObserveCommand::Neigh(args) => {
|
||||||
|
::tracing::debug!(
|
||||||
|
action = %args.action,
|
||||||
|
mac = ?args.mac,
|
||||||
|
ip = ?args.ip,
|
||||||
|
config = %config_path.display(),
|
||||||
|
"forwarding neighbor observation to wakey"
|
||||||
|
);
|
||||||
cmd.arg("neigh").arg("--action").arg(args.action);
|
cmd.arg("neigh").arg("--action").arg(args.action);
|
||||||
if let Some(mac) = args.mac {
|
if let Some(mac) = args.mac {
|
||||||
cmd.arg("--mac").arg(mac);
|
cmd.arg("--mac").arg(mac);
|
||||||
@@ -154,6 +170,7 @@ fn observe(args: cli::ObserveArgs) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let status = cmd.status()?;
|
let status = cmd.status()?;
|
||||||
|
::tracing::debug!(%status, "wakey observe exited");
|
||||||
if !status.success() {
|
if !status.success() {
|
||||||
anyhow::bail!("wakey observe exited with {status}");
|
anyhow::bail!("wakey observe exited with {status}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,6 +130,17 @@ pub struct WakeRequest {
|
|||||||
pub ip: Option<IpAddr>,
|
pub ip: Option<IpAddr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AgentObservation {
|
||||||
|
pub kind: String,
|
||||||
|
pub action: String,
|
||||||
|
pub mac: Option<String>,
|
||||||
|
pub ip: Option<IpAddr>,
|
||||||
|
pub hostname: Option<String>,
|
||||||
|
pub first_seen_unix: u64,
|
||||||
|
pub last_seen_unix: u64,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||||
pub enum AgentCommand {
|
pub enum AgentCommand {
|
||||||
@@ -161,6 +172,10 @@ pub enum ClientMessage {
|
|||||||
Heartbeat {
|
Heartbeat {
|
||||||
agent_id: String,
|
agent_id: String,
|
||||||
},
|
},
|
||||||
|
Observations {
|
||||||
|
agent_id: String,
|
||||||
|
observations: Vec<AgentObservation>,
|
||||||
|
},
|
||||||
Result {
|
Result {
|
||||||
request_id: RequestId,
|
request_id: RequestId,
|
||||||
result: CommandResult,
|
result: CommandResult,
|
||||||
@@ -178,6 +193,7 @@ pub enum ServerMessage {
|
|||||||
request_id: RequestId,
|
request_id: RequestId,
|
||||||
command: AgentCommand,
|
command: AgentCommand,
|
||||||
},
|
},
|
||||||
|
SyncObservations,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -215,4 +231,24 @@ mod tests {
|
|||||||
assert!(json.contains("\"type\":\"result\""));
|
assert!(json.contains("\"type\":\"result\""));
|
||||||
assert!(json.contains("\"kind\":\"devs\""));
|
assert!(json.contains("\"kind\":\"devs\""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn observations_message_serializes() {
|
||||||
|
let msg = ClientMessage::Observations {
|
||||||
|
agent_id: "agent-a".into(),
|
||||||
|
observations: vec![AgentObservation {
|
||||||
|
kind: "dhcp".into(),
|
||||||
|
action: "update".into(),
|
||||||
|
mac: Some("aa:bb:cc:dd:ee:ff".into()),
|
||||||
|
ip: Some("192.168.1.10".parse().expect("ip")),
|
||||||
|
hostname: Some("lda".into()),
|
||||||
|
first_seen_unix: 10,
|
||||||
|
last_seen_unix: 20,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
let json = serde_json::to_string(&msg).expect("serialize");
|
||||||
|
assert!(json.contains("\"type\":\"observations\""));
|
||||||
|
assert!(json.contains("\"kind\":\"dhcp\""));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+55
-32
@@ -9,7 +9,7 @@ use tracing::{debug, error, info, info_span, warn};
|
|||||||
|
|
||||||
use crate::config::AgentConfig;
|
use crate::config::AgentConfig;
|
||||||
use crate::dispatch::dispatch_command;
|
use crate::dispatch::dispatch_command;
|
||||||
use crate::protocol::{AgentCommand, ClientMessage, ErrorPayload, ServerMessage};
|
use crate::protocol::{AgentCommand, AgentObservation, ClientMessage, ErrorPayload, ServerMessage};
|
||||||
|
|
||||||
pub async fn run(config: AgentConfig) -> Result<()> {
|
pub async fn run(config: AgentConfig) -> Result<()> {
|
||||||
let mut backoff = config.reconnect_base_ms.max(100);
|
let mut backoff = config.reconnect_base_ms.max(100);
|
||||||
@@ -85,13 +85,13 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
|||||||
.await?;
|
.await?;
|
||||||
info!(agent_id = %config.agent_id, "agent websocket session authenticated");
|
info!(agent_id = %config.agent_id, "agent websocket session authenticated");
|
||||||
|
|
||||||
let http_client = reqwest::Client::new();
|
|
||||||
let mut heartbeat = interval(Duration::from_secs(30));
|
let mut heartbeat = interval(Duration::from_secs(30));
|
||||||
heartbeat.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
heartbeat.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||||
let mut observation_sync = interval(Duration::from_secs(
|
let mut observation_sync = interval(Duration::from_secs(
|
||||||
config.observation_sync_interval_seconds.max(1),
|
config.observation_sync_interval_seconds.max(1),
|
||||||
));
|
));
|
||||||
observation_sync.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
observation_sync.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||||
|
observation_sync.reset();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
@@ -102,7 +102,7 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
|||||||
debug!(agent_id = %config.agent_id, "heartbeat sent");
|
debug!(agent_id = %config.agent_id, "heartbeat sent");
|
||||||
}
|
}
|
||||||
_ = observation_sync.tick() => {
|
_ = observation_sync.tick() => {
|
||||||
if let Err(err) = send_agent_observations(&http_client, config).await {
|
if let Err(err) = send_agent_observations_ws(&mut sink, config).await {
|
||||||
warn!(agent_id = %config.agent_id, error = %err, "failed to sync local observations");
|
warn!(agent_id = %config.agent_id, error = %err, "failed to sync local observations");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,7 +119,7 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
|||||||
Message::Text(text) => {
|
Message::Text(text) => {
|
||||||
match serde_json::from_str::<ServerMessage>(&text) {
|
match serde_json::from_str::<ServerMessage>(&text) {
|
||||||
Ok(message) => {
|
Ok(message) => {
|
||||||
handle_server_message(config, &mut sink, message).await?;
|
handle_server_message(config, &mut sink, &mut observation_sync, message).await?;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
// Allow the server to introduce extra frame types without
|
// Allow the server to introduce extra frame types without
|
||||||
@@ -150,18 +150,7 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
|
|||||||
struct UploadAgentObservationsRequest {
|
struct UploadAgentObservationsRequest {
|
||||||
agent_id: String,
|
agent_id: String,
|
||||||
agent_token: String,
|
agent_token: String,
|
||||||
observations: Vec<AgentObservationRequest>,
|
observations: Vec<AgentObservation>,
|
||||||
}
|
|
||||||
|
|
||||||
#[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,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn sync_observations_once(config: &AgentConfig) -> Result<usize> {
|
pub async fn sync_observations_once(config: &AgentConfig) -> Result<usize> {
|
||||||
@@ -170,10 +159,7 @@ pub async fn sync_observations_once(config: &AgentConfig) -> Result<usize> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn send_agent_observations(client: &reqwest::Client, config: &AgentConfig) -> Result<usize> {
|
async fn send_agent_observations(client: &reqwest::Client, config: &AgentConfig) -> Result<usize> {
|
||||||
let observations =
|
let observations = load_agent_observations(config).await?;
|
||||||
wakey::wakey_linux::dhcp::list_local_observations_from_path(&config.observation_store_path)
|
|
||||||
.await
|
|
||||||
.context("failed to read local observations")?;
|
|
||||||
if observations.is_empty() {
|
if observations.is_empty() {
|
||||||
return Ok(0);
|
return Ok(0);
|
||||||
}
|
}
|
||||||
@@ -182,18 +168,7 @@ async fn send_agent_observations(client: &reqwest::Client, config: &AgentConfig)
|
|||||||
let payload = UploadAgentObservationsRequest {
|
let payload = UploadAgentObservationsRequest {
|
||||||
agent_id: config.agent_id.clone(),
|
agent_id: config.agent_id.clone(),
|
||||||
agent_token: config.agent_token.clone(),
|
agent_token: config.agent_token.clone(),
|
||||||
observations: 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
|
let response = client
|
||||||
@@ -218,6 +193,47 @@ async fn send_agent_observations(client: &reqwest::Client, config: &AgentConfig)
|
|||||||
Ok(payload.observations.len())
|
Ok(payload.observations.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn send_agent_observations_ws<S>(sink: &mut S, config: &AgentConfig) -> Result<usize>
|
||||||
|
where
|
||||||
|
S: SinkExt<Message> + Unpin,
|
||||||
|
<S as futures_util::Sink<Message>>::Error: std::error::Error + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
let observations = load_agent_observations(config).await?;
|
||||||
|
if observations.is_empty() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
let count = observations.len();
|
||||||
|
send_json(
|
||||||
|
sink,
|
||||||
|
&ClientMessage::Observations {
|
||||||
|
agent_id: config.agent_id.clone(),
|
||||||
|
observations,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
debug!(agent_id = %config.agent_id, observations = count, "sent observations over websocket");
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn load_agent_observations(config: &AgentConfig) -> Result<Vec<AgentObservation>> {
|
||||||
|
let observations =
|
||||||
|
wakey::wakey_linux::dhcp::list_local_observations_from_path(&config.observation_store_path)
|
||||||
|
.await
|
||||||
|
.context("failed to read local observations")?;
|
||||||
|
Ok(observations
|
||||||
|
.into_iter()
|
||||||
|
.map(|observation| AgentObservation {
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn next_backoff_ms(current_ms: u64, max_ms: u64) -> u64 {
|
pub fn next_backoff_ms(current_ms: u64, max_ms: u64) -> u64 {
|
||||||
let cap = max_ms.max(current_ms);
|
let cap = max_ms.max(current_ms);
|
||||||
current_ms.saturating_mul(2).min(cap)
|
current_ms.saturating_mul(2).min(cap)
|
||||||
@@ -226,6 +242,7 @@ pub fn next_backoff_ms(current_ms: u64, max_ms: u64) -> u64 {
|
|||||||
async fn handle_server_message<S>(
|
async fn handle_server_message<S>(
|
||||||
config: &AgentConfig,
|
config: &AgentConfig,
|
||||||
sink: &mut S,
|
sink: &mut S,
|
||||||
|
observation_sync: &mut tokio::time::Interval,
|
||||||
message: ServerMessage,
|
message: ServerMessage,
|
||||||
) -> Result<()>
|
) -> Result<()>
|
||||||
where
|
where
|
||||||
@@ -261,6 +278,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ServerMessage::SyncObservations => {
|
||||||
|
info!("received observation sync request from control-plane");
|
||||||
|
send_agent_observations_ws(sink, config).await?;
|
||||||
|
observation_sync.reset();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -336,6 +358,7 @@ fn client_message_kind(message: &ClientMessage) -> &'static str {
|
|||||||
ClientMessage::Hello { .. } => "hello",
|
ClientMessage::Hello { .. } => "hello",
|
||||||
ClientMessage::Auth { .. } => "auth",
|
ClientMessage::Auth { .. } => "auth",
|
||||||
ClientMessage::Heartbeat { .. } => "heartbeat",
|
ClientMessage::Heartbeat { .. } => "heartbeat",
|
||||||
|
ClientMessage::Observations { .. } => "observations",
|
||||||
ClientMessage::Result { .. } => "result",
|
ClientMessage::Result { .. } => "result",
|
||||||
ClientMessage::Error { .. } => "error",
|
ClientMessage::Error { .. } => "error",
|
||||||
}
|
}
|
||||||
|
|||||||
+86
@@ -0,0 +1,86 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT events.event_id as \"event_id!\",\n ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) as \"observation_key!\",\n events.agent_id as \"agent_id!\",\n events.kind as \"kind!\",\n events.action as \"action!\",\n events.mac,\n events.ip,\n events.hostname,\n events.ts_unix,\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observation_events events\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE (?1 IS NULL OR events.agent_id = ?1)\n AND (?2 IS NULL OR events.kind = ?2)\n AND (?3 IS NULL OR events.mac = ?3)\n AND (?4 IS NULL OR events.ip = ?4)\n AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL\n THEN 'mac:' || events.mac || ':ip:' || events.ip\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) = ?5)\n ORDER BY events.ts_unix DESC\n LIMIT ?6",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "event_id!",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "observation_key!",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "agent_id!",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "kind!",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "action!",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "mac",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ip",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "hostname",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ts_unix",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "device_id",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "display_name",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pinned",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 6
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "3bc141cecd0ba7c9ca937036b310728dff57c69ed7b74529fd81fa6a3c0e40cf"
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "UPDATE device_identifiers SET device_id = ?1 WHERE device_id = ?2",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "7247cc488921de2313a602697590502771a231bde7d03cd9ccac55a70971da45"
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM device_identifiers WHERE device_id = ?1 AND identifier_key = ?2",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "72aadefca9851a8becdd2dcce54b646aff095b64cef9837f5e8e4ea8dde71d02"
|
||||||
|
}
|
||||||
-86
@@ -1,86 +0,0 @@
|
|||||||
{
|
|
||||||
"db_name": "SQLite",
|
|
||||||
"query": "SELECT events.event_id as \"event_id!\",\n ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) as \"observation_key!\",\n events.agent_id as \"agent_id!\",\n events.kind as \"kind!\",\n events.action as \"action!\",\n events.mac,\n events.ip,\n events.hostname,\n events.ts_unix,\n known_devices.device_id,\n known_devices.display_name,\n known_devices.pinned\n FROM agent_device_observation_events events\n LEFT JOIN device_identifiers identifiers\n ON identifiers.identifier_key =\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n END\n LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id\n WHERE (?1 IS NULL OR events.agent_id = ?1)\n AND (?2 IS NULL OR events.kind = ?2)\n AND (?3 IS NULL OR events.mac = ?3)\n AND (?4 IS NULL OR events.ip = ?4)\n AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||\n CASE\n WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac\n WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip\n ELSE ''\n END) = ?5)\n ORDER BY events.ts_unix DESC\n LIMIT ?6",
|
|
||||||
"describe": {
|
|
||||||
"columns": [
|
|
||||||
{
|
|
||||||
"name": "event_id!",
|
|
||||||
"ordinal": 0,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "observation_key!",
|
|
||||||
"ordinal": 1,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "agent_id!",
|
|
||||||
"ordinal": 2,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "kind!",
|
|
||||||
"ordinal": 3,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "action!",
|
|
||||||
"ordinal": 4,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "mac",
|
|
||||||
"ordinal": 5,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "ip",
|
|
||||||
"ordinal": 6,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "hostname",
|
|
||||||
"ordinal": 7,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "ts_unix",
|
|
||||||
"ordinal": 8,
|
|
||||||
"type_info": "Integer"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "device_id",
|
|
||||||
"ordinal": 9,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "display_name",
|
|
||||||
"ordinal": 10,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "pinned",
|
|
||||||
"ordinal": 11,
|
|
||||||
"type_info": "Integer"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"parameters": {
|
|
||||||
"Right": 6
|
|
||||||
},
|
|
||||||
"nullable": [
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
false,
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
true
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"hash": "908d763909c76fb6170b818784e360372c02295523ef9970c91199db7d4f535a"
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wakey-control-plane"
|
name = "wakey-control-plane"
|
||||||
version = "0.1.2"
|
version = "0.2.3"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = ["gitea"]
|
publish = ["gitea"]
|
||||||
|
|
||||||
|
|||||||
@@ -58,14 +58,26 @@ pub async fn run_command(
|
|||||||
AxumPath(agent_id): AxumPath<String>,
|
AxumPath(agent_id): AxumPath<String>,
|
||||||
Json(req): Json<RelayCommandRequest>,
|
Json(req): Json<RelayCommandRequest>,
|
||||||
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||||
|
match relay_agent_command(&state, &agent_id, req.command, req.timeout_ms).await {
|
||||||
|
Ok(response) => Ok((StatusCode::OK, Json(response))),
|
||||||
|
Err(err) => Err(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn relay_agent_command(
|
||||||
|
state: &AppState,
|
||||||
|
agent_id: &str,
|
||||||
|
command: AgentCommand,
|
||||||
|
timeout_ms: Option<u64>,
|
||||||
|
) -> Result<RelayCommandResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||||
let request_id_string = format!("req-{}", Uuid::new_v4());
|
let request_id_string = format!("req-{}", Uuid::new_v4());
|
||||||
let command = command_kind(&req.command);
|
let command_kind = command_kind(&command);
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
let span = info_span!(
|
let span = info_span!(
|
||||||
"relay_command",
|
"relay_command",
|
||||||
agent_id = %agent_id,
|
agent_id = %agent_id,
|
||||||
request_id = %request_id_string,
|
request_id = %request_id_string,
|
||||||
command = %command,
|
command = %command_kind,
|
||||||
);
|
);
|
||||||
let _span_guard = span.enter();
|
let _span_guard = span.enter();
|
||||||
|
|
||||||
@@ -79,7 +91,7 @@ pub async fn run_command(
|
|||||||
|
|
||||||
let tx = {
|
let tx = {
|
||||||
let sessions = state.sessions.read().await;
|
let sessions = state.sessions.read().await;
|
||||||
sessions.get(&agent_id).map(|session| session.tx.clone())
|
sessions.get(agent_id).map(|session| session.tx.clone())
|
||||||
}
|
}
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
warn!("command rejected: agent not connected");
|
warn!("command rejected: agent not connected");
|
||||||
@@ -103,13 +115,13 @@ pub async fn run_command(
|
|||||||
.append_audit_event(AuditEventInput {
|
.append_audit_event(AuditEventInput {
|
||||||
actor_type: "admin_api".into(),
|
actor_type: "admin_api".into(),
|
||||||
actor_id: None,
|
actor_id: None,
|
||||||
agent_id: Some(agent_id.clone()),
|
agent_id: Some(agent_id.to_string()),
|
||||||
request_id: Some(request_id_string.clone()),
|
request_id: Some(request_id_string.clone()),
|
||||||
event_type: "command_dispatch".into(),
|
event_type: "command_dispatch".into(),
|
||||||
outcome: "sent".into(),
|
outcome: "sent".into(),
|
||||||
latency_ms: None,
|
latency_ms: None,
|
||||||
message: "dispatched command to connected agent".into(),
|
message: "dispatched command to connected agent".into(),
|
||||||
metadata: serde_json::json!({ "command": command }),
|
metadata: serde_json::json!({ "command": command_kind }),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
@@ -118,7 +130,7 @@ pub async fn run_command(
|
|||||||
|
|
||||||
if let Err(err) = tx.send(SessionEvent::Message(ServerMessage::Command {
|
if let Err(err) = tx.send(SessionEvent::Message(ServerMessage::Command {
|
||||||
request_id,
|
request_id,
|
||||||
command: req.command,
|
command,
|
||||||
})) {
|
})) {
|
||||||
state.pending.lock().await.remove(&request_id_string);
|
state.pending.lock().await.remove(&request_id_string);
|
||||||
warn!(error = %err, "failed sending command to agent session");
|
warn!(error = %err, "failed sending command to agent session");
|
||||||
@@ -127,13 +139,13 @@ pub async fn run_command(
|
|||||||
.append_audit_event(AuditEventInput {
|
.append_audit_event(AuditEventInput {
|
||||||
actor_type: "admin_api".into(),
|
actor_type: "admin_api".into(),
|
||||||
actor_id: None,
|
actor_id: None,
|
||||||
agent_id: Some(agent_id.clone()),
|
agent_id: Some(agent_id.to_string()),
|
||||||
request_id: Some(request_id_string.clone()),
|
request_id: Some(request_id_string.clone()),
|
||||||
event_type: "command_dispatch".into(),
|
event_type: "command_dispatch".into(),
|
||||||
outcome: "send_failed".into(),
|
outcome: "send_failed".into(),
|
||||||
latency_ms: Some(started.elapsed().as_millis() as u64),
|
latency_ms: Some(started.elapsed().as_millis() as u64),
|
||||||
message: err.to_string(),
|
message: err.to_string(),
|
||||||
metadata: serde_json::json!({ "command": command }),
|
metadata: serde_json::json!({ "command": command_kind }),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
@@ -147,7 +159,7 @@ pub async fn run_command(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let timeout = std::time::Duration::from_millis(
|
let timeout = std::time::Duration::from_millis(
|
||||||
req.timeout_ms
|
timeout_ms
|
||||||
.unwrap_or(state.command_timeout.as_millis() as u64)
|
.unwrap_or(state.command_timeout.as_millis() as u64)
|
||||||
.max(1),
|
.max(1),
|
||||||
);
|
);
|
||||||
@@ -160,13 +172,13 @@ pub async fn run_command(
|
|||||||
.append_audit_event(AuditEventInput {
|
.append_audit_event(AuditEventInput {
|
||||||
actor_type: "admin_api".into(),
|
actor_type: "admin_api".into(),
|
||||||
actor_id: None,
|
actor_id: None,
|
||||||
agent_id: Some(agent_id.clone()),
|
agent_id: Some(agent_id.to_string()),
|
||||||
request_id: Some(request_id_string.clone()),
|
request_id: Some(request_id_string.clone()),
|
||||||
event_type: "command_result".into(),
|
event_type: "command_result".into(),
|
||||||
outcome: "ok".into(),
|
outcome: "ok".into(),
|
||||||
latency_ms: Some(started.elapsed().as_millis() as u64),
|
latency_ms: Some(started.elapsed().as_millis() as u64),
|
||||||
message: "agent command completed".into(),
|
message: "agent command completed".into(),
|
||||||
metadata: serde_json::json!({ "command": command }),
|
metadata: serde_json::json!({ "command": command_kind }),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
@@ -186,13 +198,13 @@ pub async fn run_command(
|
|||||||
.append_audit_event(AuditEventInput {
|
.append_audit_event(AuditEventInput {
|
||||||
actor_type: "admin_api".into(),
|
actor_type: "admin_api".into(),
|
||||||
actor_id: None,
|
actor_id: None,
|
||||||
agent_id: Some(agent_id.clone()),
|
agent_id: Some(agent_id.to_string()),
|
||||||
request_id: Some(request_id_string.clone()),
|
request_id: Some(request_id_string.clone()),
|
||||||
event_type: "command_result".into(),
|
event_type: "command_result".into(),
|
||||||
outcome: "error".into(),
|
outcome: "error".into(),
|
||||||
latency_ms: Some(started.elapsed().as_millis() as u64),
|
latency_ms: Some(started.elapsed().as_millis() as u64),
|
||||||
message: error.message.clone(),
|
message: error.message.clone(),
|
||||||
metadata: serde_json::json!({ "command": command, "code": error.code }),
|
metadata: serde_json::json!({ "command": command_kind, "code": error.code }),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
@@ -212,13 +224,13 @@ pub async fn run_command(
|
|||||||
.append_audit_event(AuditEventInput {
|
.append_audit_event(AuditEventInput {
|
||||||
actor_type: "admin_api".into(),
|
actor_type: "admin_api".into(),
|
||||||
actor_id: None,
|
actor_id: None,
|
||||||
agent_id: Some(agent_id.clone()),
|
agent_id: Some(agent_id.to_string()),
|
||||||
request_id: Some(request_id_string.clone()),
|
request_id: Some(request_id_string.clone()),
|
||||||
event_type: "command_result".into(),
|
event_type: "command_result".into(),
|
||||||
outcome: "response_dropped".into(),
|
outcome: "response_dropped".into(),
|
||||||
latency_ms: Some(started.elapsed().as_millis() as u64),
|
latency_ms: Some(started.elapsed().as_millis() as u64),
|
||||||
message: "agent response channel dropped".into(),
|
message: "agent response channel dropped".into(),
|
||||||
metadata: serde_json::json!({ "command": command }),
|
metadata: serde_json::json!({ "command": command_kind }),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
@@ -241,13 +253,13 @@ pub async fn run_command(
|
|||||||
.append_audit_event(AuditEventInput {
|
.append_audit_event(AuditEventInput {
|
||||||
actor_type: "admin_api".into(),
|
actor_type: "admin_api".into(),
|
||||||
actor_id: None,
|
actor_id: None,
|
||||||
agent_id: Some(agent_id.clone()),
|
agent_id: Some(agent_id.to_string()),
|
||||||
request_id: Some(request_id_string.clone()),
|
request_id: Some(request_id_string.clone()),
|
||||||
event_type: "command_result".into(),
|
event_type: "command_result".into(),
|
||||||
outcome: "timeout".into(),
|
outcome: "timeout".into(),
|
||||||
latency_ms: Some(started.elapsed().as_millis() as u64),
|
latency_ms: Some(started.elapsed().as_millis() as u64),
|
||||||
message: "agent command timed out".into(),
|
message: "agent command timed out".into(),
|
||||||
metadata: serde_json::json!({ "command": command, "timeout_ms": timeout.as_millis() as u64 }),
|
metadata: serde_json::json!({ "command": command_kind, "timeout_ms": timeout.as_millis() as u64 }),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
@@ -261,7 +273,7 @@ pub async fn run_command(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(response)))
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn command_kind(command: &AgentCommand) -> &'static str {
|
fn command_kind(command: &AgentCommand) -> &'static str {
|
||||||
|
|||||||
@@ -1,18 +1,21 @@
|
|||||||
mod devices;
|
mod devices;
|
||||||
mod enroll;
|
mod enroll;
|
||||||
|
mod fleet;
|
||||||
mod observations;
|
mod observations;
|
||||||
mod stats;
|
mod stats;
|
||||||
|
|
||||||
pub use devices::{
|
pub use devices::{
|
||||||
attach_device_identifier, attach_observation_identifier, create_known_device,
|
attach_device_identifier, attach_observation_identifier, create_known_device,
|
||||||
forget_known_device, list_known_devices,
|
detach_device_identifier, forget_known_device, list_known_devices, merge_known_device,
|
||||||
};
|
};
|
||||||
pub use enroll::{
|
pub use enroll::{
|
||||||
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
|
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
|
||||||
enroll, healthz, issue_enroll_token, list_enroll_tokens, revoke_agent, revoke_enroll_token,
|
enroll, healthz, issue_enroll_token, list_enroll_tokens, revoke_agent, revoke_enroll_token,
|
||||||
set_agent_nickname,
|
set_agent_nickname,
|
||||||
};
|
};
|
||||||
|
pub use fleet::{list_fleet_devices, refresh_fleet_devices, wake_fleet_device};
|
||||||
pub use observations::{
|
pub use observations::{
|
||||||
list_agent_observation_history, list_agent_observations, upload_agent_observations,
|
list_agent_observation_history, list_agent_observations, request_agent_observation_sync,
|
||||||
|
upload_agent_observations,
|
||||||
};
|
};
|
||||||
pub use stats::{StateStatsResponse, state_stats};
|
pub use stats::{StateStatsResponse, state_stats};
|
||||||
@@ -56,6 +56,11 @@ pub struct ForgetKnownDeviceResponse {
|
|||||||
pub forgotten: bool,
|
pub forgotten: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct MergeKnownDeviceRequest {
|
||||||
|
pub source_device_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn create_known_device(
|
pub async fn create_known_device(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Json(req): Json<CreateKnownDeviceRequest>,
|
Json(req): Json<CreateKnownDeviceRequest>,
|
||||||
@@ -193,6 +198,59 @@ pub async fn attach_observation_identifier(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn detach_device_identifier(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
AxumPath((device_id, identifier_key)): AxumPath<(String, String)>,
|
||||||
|
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||||
|
match state
|
||||||
|
.store
|
||||||
|
.detach_device_identifier(&device_id, &identifier_key)
|
||||||
|
.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 detach device identifier");
|
||||||
|
Err(json_error(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"detach_device_identifier_failed",
|
||||||
|
&err.to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn merge_known_device(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
AxumPath(device_id): AxumPath<String>,
|
||||||
|
Json(req): Json<MergeKnownDeviceRequest>,
|
||||||
|
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||||
|
match state
|
||||||
|
.store
|
||||||
|
.merge_known_devices(&device_id, &req.source_device_id)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(device)) => Ok((StatusCode::OK, Json(known_device_response(device)))),
|
||||||
|
Ok(None) => Err(json_error(
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
"known_device_not_found",
|
||||||
|
"target or source known device not found",
|
||||||
|
)),
|
||||||
|
Err(err) => {
|
||||||
|
warn!(error = %err, "failed to merge known devices");
|
||||||
|
Err(json_error(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"merge_known_device_failed",
|
||||||
|
&err.to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn known_device_response(device: crate::state::KnownDevice) -> KnownDeviceResponse {
|
fn known_device_response(device: crate::state::KnownDevice) -> KnownDeviceResponse {
|
||||||
KnownDeviceResponse {
|
KnownDeviceResponse {
|
||||||
device_id: device.device_id,
|
device_id: device.device_id,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,13 @@
|
|||||||
use axum::Json;
|
use axum::Json;
|
||||||
use axum::extract::{Query, State};
|
use axum::extract::{Path as AxumPath, Query, State};
|
||||||
use axum::http::StatusCode;
|
use axum::http::StatusCode;
|
||||||
use axum::response::IntoResponse;
|
use axum::response::IntoResponse;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tracing::warn;
|
use tracing::warn;
|
||||||
|
use wakey_agent::protocol::ServerMessage;
|
||||||
|
|
||||||
use crate::api::json_error;
|
use crate::api::json_error;
|
||||||
use crate::runtime::AppState;
|
use crate::runtime::{AppState, SessionEvent};
|
||||||
use crate::state::{
|
use crate::state::{
|
||||||
AgentDeviceObservationEvent, AgentDeviceObservationInput, AgentDeviceObservationView,
|
AgentDeviceObservationEvent, AgentDeviceObservationInput, AgentDeviceObservationView,
|
||||||
};
|
};
|
||||||
@@ -35,6 +36,12 @@ pub struct UploadAgentObservationsResponse {
|
|||||||
pub accepted: usize,
|
pub accepted: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct RequestAgentObservationSyncResponse {
|
||||||
|
pub agent_id: String,
|
||||||
|
pub requested: bool,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct ListObservationsQuery {
|
pub struct ListObservationsQuery {
|
||||||
pub agent_id: Option<String>,
|
pub agent_id: Option<String>,
|
||||||
@@ -130,6 +137,43 @@ pub async fn list_agent_observations(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn request_agent_observation_sync(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
AxumPath(agent_id): AxumPath<String>,
|
||||||
|
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
|
||||||
|
let tx = {
|
||||||
|
let sessions = state.sessions.read().await;
|
||||||
|
sessions.get(&agent_id).map(|session| session.tx.clone())
|
||||||
|
};
|
||||||
|
let Some(tx) = tx else {
|
||||||
|
return Ok((
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
Json(RequestAgentObservationSyncResponse {
|
||||||
|
agent_id,
|
||||||
|
requested: false,
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
match tx.send(SessionEvent::Message(ServerMessage::SyncObservations)) {
|
||||||
|
Ok(()) => Ok((
|
||||||
|
StatusCode::OK,
|
||||||
|
Json(RequestAgentObservationSyncResponse {
|
||||||
|
agent_id,
|
||||||
|
requested: true,
|
||||||
|
}),
|
||||||
|
)),
|
||||||
|
Err(err) => {
|
||||||
|
warn!(error = %err, "failed to request agent observation sync");
|
||||||
|
Err(json_error(
|
||||||
|
StatusCode::BAD_GATEWAY,
|
||||||
|
"agent_observation_sync_request_failed",
|
||||||
|
&err.to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_agent_observation_history(
|
pub async fn list_agent_observation_history(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Query(query): Query<ListObservationHistoryQuery>,
|
Query(query): Query<ListObservationHistoryQuery>,
|
||||||
|
|||||||
@@ -12,10 +12,11 @@ pub use commands::{list_agents, run_command};
|
|||||||
pub use control::{
|
pub use control::{
|
||||||
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
|
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
|
||||||
StateStatsResponse, attach_device_identifier, attach_observation_identifier,
|
StateStatsResponse, attach_device_identifier, attach_observation_identifier,
|
||||||
create_known_device, enroll, forget_known_device, healthz, issue_enroll_token,
|
create_known_device, detach_device_identifier, enroll, forget_known_device, healthz,
|
||||||
list_agent_observation_history, list_agent_observations, list_enroll_tokens,
|
issue_enroll_token, list_agent_observation_history, list_agent_observations,
|
||||||
list_known_devices, revoke_agent, revoke_enroll_token, set_agent_nickname, state_stats,
|
list_enroll_tokens, list_fleet_devices, list_known_devices, merge_known_device,
|
||||||
upload_agent_observations,
|
refresh_fleet_devices, request_agent_observation_sync, revoke_agent, revoke_enroll_token,
|
||||||
|
set_agent_nickname, state_stats, upload_agent_observations, wake_fleet_device,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn json_error(
|
pub fn json_error(
|
||||||
|
|||||||
@@ -87,9 +87,18 @@ pub struct ServeArgs {
|
|||||||
|
|
||||||
#[derive(Args, Clone)]
|
#[derive(Args, Clone)]
|
||||||
pub struct InitConfigArgs {
|
pub struct InitConfigArgs {
|
||||||
#[arg(long = "config-file", alias = "config")]
|
#[arg(
|
||||||
|
long = "config-file",
|
||||||
|
short,
|
||||||
|
visible_alias = "config",
|
||||||
|
visible_alias = "to",
|
||||||
|
visible_short_alias = 't'
|
||||||
|
)]
|
||||||
pub config_file: Option<PathBuf>,
|
pub config_file: Option<PathBuf>,
|
||||||
|
|
||||||
|
#[arg(long, short, visible_alias = "from")]
|
||||||
|
pub from_config: Option<PathBuf>,
|
||||||
|
|
||||||
#[arg(long, conflicts_with = "config_file")]
|
#[arg(long, conflicts_with = "config_file")]
|
||||||
pub stdout: bool,
|
pub stdout: bool,
|
||||||
|
|
||||||
@@ -126,8 +135,8 @@ pub struct InitConfigArgs {
|
|||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
pub telemetry_service_name: Option<String>,
|
pub telemetry_service_name: Option<String>,
|
||||||
|
|
||||||
#[arg(long)]
|
#[arg(long, num_args = 0..=1, default_missing_value = "true")]
|
||||||
pub telemetry_json_logs: bool,
|
pub telemetry_json_logs: Option<bool>,
|
||||||
|
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
pub force: bool,
|
pub force: bool,
|
||||||
@@ -135,7 +144,7 @@ pub struct InitConfigArgs {
|
|||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub struct IssueEnrollTokenArgs {
|
pub struct IssueEnrollTokenArgs {
|
||||||
#[arg(long, default_value = DEFAULT_CONFIG_FILE)]
|
#[arg(long, visible_alias = "config", default_value = DEFAULT_CONFIG_FILE)]
|
||||||
pub config_file: PathBuf,
|
pub config_file: PathBuf,
|
||||||
|
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
@@ -156,7 +165,7 @@ pub struct IssueEnrollTokenArgs {
|
|||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub struct ListEnrollTokensArgs {
|
pub struct ListEnrollTokensArgs {
|
||||||
#[arg(long, default_value = DEFAULT_CONFIG_FILE)]
|
#[arg(long, visible_alias = "config", default_value = DEFAULT_CONFIG_FILE)]
|
||||||
pub config_file: PathBuf,
|
pub config_file: PathBuf,
|
||||||
|
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
@@ -238,12 +247,13 @@ pub struct StateStatsArgs {
|
|||||||
pub target: AdminTargetArgs,
|
pub target: AdminTargetArgs,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// not the greatest thing ive used, this and the migration code gets deleted shortly anyways
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
pub struct ImportSledStateArgs {
|
pub struct ImportSledStateArgs {
|
||||||
#[arg(long)]
|
#[arg(long, visible_alias = "from")]
|
||||||
pub from_sled_state: PathBuf,
|
pub from_sled_state: PathBuf,
|
||||||
|
|
||||||
#[arg(long)]
|
#[arg(long, visible_alias = "to")]
|
||||||
pub to_state_file: PathBuf,
|
pub to_state_file: PathBuf,
|
||||||
|
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::path::PathBuf;
|
|||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
|
|
||||||
use crate::cli::{InitConfigArgs, ServeArgs};
|
use crate::cli::{InitConfigArgs, ServeArgs};
|
||||||
use crate::config::resolve::{normalize_public_url, resolve_path};
|
use crate::config::resolve::{load_file_config, normalize_public_url, resolve_path};
|
||||||
use crate::config::types::{WritableConfig, WritableTelemetry};
|
use crate::config::types::{WritableConfig, WritableTelemetry};
|
||||||
|
|
||||||
pub fn write_init_config(args: &InitConfigArgs) -> Result<Option<PathBuf>> {
|
pub fn write_init_config(args: &InitConfigArgs) -> Result<Option<PathBuf>> {
|
||||||
@@ -21,56 +21,104 @@ pub fn write_init_config(args: &InitConfigArgs) -> Result<Option<PathBuf>> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let bind = args.bind.unwrap_or_else(|| {
|
let base = if let Some(from_config) = &args.from_config {
|
||||||
"0.0.0.0:8080"
|
if !from_config.exists() {
|
||||||
|
anyhow::bail!("base config {} does not exist", from_config.display());
|
||||||
|
}
|
||||||
|
load_file_config(from_config)?
|
||||||
|
} else {
|
||||||
|
Default::default()
|
||||||
|
};
|
||||||
|
let base_telemetry = base.telemetry.unwrap_or_default();
|
||||||
|
|
||||||
|
let bind = match args.bind {
|
||||||
|
Some(bind) => bind,
|
||||||
|
None => match base.bind {
|
||||||
|
Some(ref bind) => bind.parse().with_context(|| {
|
||||||
|
format!(
|
||||||
|
"invalid bind address `{bind}` in base config {}",
|
||||||
|
args.from_config
|
||||||
|
.as_ref()
|
||||||
|
.map(|path| path.display().to_string())
|
||||||
|
.unwrap_or_else(|| "<defaults>".to_string())
|
||||||
|
)
|
||||||
|
})?,
|
||||||
|
None => "0.0.0.0:8080"
|
||||||
.parse()
|
.parse()
|
||||||
.expect("static default bind should parse")
|
.expect("static default bind should parse"),
|
||||||
});
|
},
|
||||||
|
};
|
||||||
let public_url = normalize_public_url(
|
let public_url = normalize_public_url(
|
||||||
args.public_url
|
args.public_url
|
||||||
.as_deref()
|
.as_deref()
|
||||||
|
.or(base.public_url.as_deref())
|
||||||
.unwrap_or("http://127.0.0.1:8080"),
|
.unwrap_or("http://127.0.0.1:8080"),
|
||||||
);
|
);
|
||||||
|
|
||||||
let data_dir = args
|
let data_dir = args
|
||||||
.data_dir
|
.data_dir
|
||||||
.clone()
|
.clone()
|
||||||
|
.or(base.data_dir)
|
||||||
.unwrap_or_else(|| PathBuf::from(crate::cli::DEFAULT_DATA_DIR));
|
.unwrap_or_else(|| PathBuf::from(crate::cli::DEFAULT_DATA_DIR));
|
||||||
|
|
||||||
let state_file_raw = args
|
let state_file_raw = args
|
||||||
.state_file
|
.state_file
|
||||||
.clone()
|
.clone()
|
||||||
|
.or(base.state_file)
|
||||||
.unwrap_or_else(|| PathBuf::from("state.sqlite3"));
|
.unwrap_or_else(|| PathBuf::from("state.sqlite3"));
|
||||||
let state_file = resolve_path(&data_dir, state_file_raw);
|
let state_file = resolve_path(&data_dir, state_file_raw);
|
||||||
|
|
||||||
let pid_file_raw = args
|
let pid_file_raw = args
|
||||||
.pid_file
|
.pid_file
|
||||||
.clone()
|
.clone()
|
||||||
|
.or(base.pid_file)
|
||||||
.unwrap_or_else(|| PathBuf::from("wakey-control-plane.pid"));
|
.unwrap_or_else(|| PathBuf::from("wakey-control-plane.pid"));
|
||||||
let pid_file = resolve_path(&data_dir, pid_file_raw);
|
let pid_file = resolve_path(&data_dir, pid_file_raw);
|
||||||
|
|
||||||
let ui_dist_dir = args
|
let ui_dist_dir = args
|
||||||
.ui_dist_dir
|
.ui_dist_dir
|
||||||
.clone()
|
.clone()
|
||||||
|
.or(base.ui_dist_dir)
|
||||||
.unwrap_or_else(|| PathBuf::from("ui/dist"));
|
.unwrap_or_else(|| PathBuf::from("ui/dist"));
|
||||||
|
|
||||||
|
let bootstrap_enroll_tokens = if args.bootstrap_enroll_tokens.is_empty() {
|
||||||
|
base.bootstrap_enroll_tokens.unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
args.bootstrap_enroll_tokens.clone()
|
||||||
|
};
|
||||||
|
|
||||||
let body = WritableConfig {
|
let body = WritableConfig {
|
||||||
data_dir,
|
data_dir,
|
||||||
bind: bind.to_string(),
|
bind: bind.to_string(),
|
||||||
public_url,
|
public_url,
|
||||||
state_file,
|
state_file,
|
||||||
command_timeout_ms: args.command_timeout_ms.unwrap_or(30_000).max(1),
|
command_timeout_ms: args
|
||||||
enroll_token_ttl_seconds: args.enroll_token_ttl_seconds.unwrap_or(86_400).max(1),
|
.command_timeout_ms
|
||||||
|
.or(base.command_timeout_ms)
|
||||||
|
.unwrap_or(30_000)
|
||||||
|
.max(1),
|
||||||
|
enroll_token_ttl_seconds: args
|
||||||
|
.enroll_token_ttl_seconds
|
||||||
|
.or(base.enroll_token_ttl_seconds)
|
||||||
|
.unwrap_or(86_400)
|
||||||
|
.max(1),
|
||||||
pid_file,
|
pid_file,
|
||||||
ui_dist_dir,
|
ui_dist_dir,
|
||||||
bootstrap_enroll_tokens: args.bootstrap_enroll_tokens.clone(),
|
bootstrap_enroll_tokens,
|
||||||
telemetry: WritableTelemetry {
|
telemetry: WritableTelemetry {
|
||||||
otlp_endpoint: args.telemetry_otlp_endpoint.clone(),
|
otlp_endpoint: args
|
||||||
|
.telemetry_otlp_endpoint
|
||||||
|
.clone()
|
||||||
|
.or(base_telemetry.otlp_endpoint),
|
||||||
service_name: args
|
service_name: args
|
||||||
.telemetry_service_name
|
.telemetry_service_name
|
||||||
.clone()
|
.clone()
|
||||||
|
.or(base_telemetry.service_name)
|
||||||
.unwrap_or_else(|| "wakey-control-plane".to_string()),
|
.unwrap_or_else(|| "wakey-control-plane".to_string()),
|
||||||
json_logs: args.telemetry_json_logs,
|
json_logs: args
|
||||||
|
.telemetry_json_logs
|
||||||
|
.or(base_telemetry.json_logs)
|
||||||
|
.unwrap_or(false),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -108,12 +156,93 @@ pub fn bootstrap_config_if_missing(args: &ServeArgs) -> Result<bool> {
|
|||||||
command_timeout_ms: args.command_timeout_ms,
|
command_timeout_ms: args.command_timeout_ms,
|
||||||
enroll_token_ttl_seconds: args.enroll_token_ttl_seconds,
|
enroll_token_ttl_seconds: args.enroll_token_ttl_seconds,
|
||||||
bootstrap_enroll_tokens: args.bootstrap_enroll_tokens.clone(),
|
bootstrap_enroll_tokens: args.bootstrap_enroll_tokens.clone(),
|
||||||
|
from_config: None,
|
||||||
telemetry_otlp_endpoint: None,
|
telemetry_otlp_endpoint: None,
|
||||||
telemetry_service_name: None,
|
telemetry_service_name: None,
|
||||||
telemetry_json_logs: false,
|
telemetry_json_logs: None,
|
||||||
force: false,
|
force: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
write_init_config(&init)?;
|
write_init_config(&init)?;
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::write_init_config;
|
||||||
|
use crate::cli::InitConfigArgs;
|
||||||
|
|
||||||
|
fn temp_test_dir(name: &str) -> std::path::PathBuf {
|
||||||
|
std::env::temp_dir().join(format!(
|
||||||
|
"wakey-cc-init-config-{name}-{}",
|
||||||
|
std::process::id()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn init_config_from_config_preserves_base_and_applies_overrides() {
|
||||||
|
let dir = temp_test_dir("from-config");
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).expect("create temp dir");
|
||||||
|
let base = dir.join("base.toml");
|
||||||
|
let out = dir.join("out.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&base,
|
||||||
|
r#"
|
||||||
|
data_dir = "/tmp/wakey-base"
|
||||||
|
bind = "127.0.0.1:9090"
|
||||||
|
public_url = "https://old.example/"
|
||||||
|
state_file = "old.sqlite3"
|
||||||
|
command_timeout_ms = 1234
|
||||||
|
enroll_token_ttl_seconds = 5678
|
||||||
|
pid_file = "old.pid"
|
||||||
|
ui_dist_dir = "/opt/wakey/ui"
|
||||||
|
bootstrap_enroll_tokens = ["old-token"]
|
||||||
|
|
||||||
|
[telemetry]
|
||||||
|
otlp_endpoint = "http://otel.example"
|
||||||
|
service_name = "old-service"
|
||||||
|
json_logs = true
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("write base config");
|
||||||
|
|
||||||
|
write_init_config(&InitConfigArgs {
|
||||||
|
config_file: Some(out.clone()),
|
||||||
|
from_config: Some(base),
|
||||||
|
stdout: false,
|
||||||
|
data_dir: None,
|
||||||
|
bind: None,
|
||||||
|
public_url: Some("https://new.example/".to_string()),
|
||||||
|
state_file: None,
|
||||||
|
pid_file: None,
|
||||||
|
ui_dist_dir: None,
|
||||||
|
command_timeout_ms: Some(999),
|
||||||
|
enroll_token_ttl_seconds: None,
|
||||||
|
bootstrap_enroll_tokens: Vec::new(),
|
||||||
|
telemetry_otlp_endpoint: None,
|
||||||
|
telemetry_service_name: None,
|
||||||
|
telemetry_json_logs: None,
|
||||||
|
force: false,
|
||||||
|
})
|
||||||
|
.expect("write derived config");
|
||||||
|
|
||||||
|
let rendered = std::fs::read_to_string(&out).expect("read derived config");
|
||||||
|
let parsed: toml::Value = toml::from_str(&rendered).expect("parse derived config");
|
||||||
|
assert_eq!(parsed["public_url"].as_str(), Some("https://new.example"));
|
||||||
|
assert_eq!(parsed["bind"].as_str(), Some("127.0.0.1:9090"));
|
||||||
|
assert_eq!(parsed["command_timeout_ms"].as_integer(), Some(999));
|
||||||
|
assert_eq!(parsed["enroll_token_ttl_seconds"].as_integer(), Some(5678));
|
||||||
|
assert_eq!(
|
||||||
|
parsed["state_file"].as_str(),
|
||||||
|
Some("/tmp/wakey-base/old.sqlite3")
|
||||||
|
);
|
||||||
|
assert_eq!(parsed["telemetry"]["json_logs"].as_bool(), Some(true));
|
||||||
|
assert_eq!(
|
||||||
|
parsed["telemetry"]["service_name"].as_str(),
|
||||||
|
Some("old-service")
|
||||||
|
);
|
||||||
|
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -93,6 +93,15 @@ fn control_api_routes() -> Router<AppState> {
|
|||||||
axum::routing::delete(api::revoke_enroll_token),
|
axum::routing::delete(api::revoke_enroll_token),
|
||||||
)
|
)
|
||||||
.route("/api/v1/control/state-stats", get(api::state_stats))
|
.route("/api/v1/control/state-stats", get(api::state_stats))
|
||||||
|
.route(
|
||||||
|
"/api/v1/control/fleet/devices",
|
||||||
|
get(api::list_fleet_devices),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/control/fleet/devices/refresh",
|
||||||
|
post(api::refresh_fleet_devices),
|
||||||
|
)
|
||||||
|
.route("/api/v1/control/fleet/wake", post(api::wake_fleet_device))
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/control/observations",
|
"/api/v1/control/observations",
|
||||||
get(api::list_agent_observations),
|
get(api::list_agent_observations),
|
||||||
@@ -101,6 +110,10 @@ fn control_api_routes() -> Router<AppState> {
|
|||||||
"/api/v1/control/observations/history",
|
"/api/v1/control/observations/history",
|
||||||
get(api::list_agent_observation_history),
|
get(api::list_agent_observation_history),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/control/agents/{agent_id}/observations/sync",
|
||||||
|
post(api::request_agent_observation_sync),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/control/devices",
|
"/api/v1/control/devices",
|
||||||
get(api::list_known_devices).post(api::create_known_device),
|
get(api::list_known_devices).post(api::create_known_device),
|
||||||
@@ -109,10 +122,18 @@ fn control_api_routes() -> Router<AppState> {
|
|||||||
"/api/v1/control/devices/{device_id}",
|
"/api/v1/control/devices/{device_id}",
|
||||||
axum::routing::delete(api::forget_known_device),
|
axum::routing::delete(api::forget_known_device),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/control/devices/{device_id}/merge",
|
||||||
|
post(api::merge_known_device),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/control/devices/{device_id}/identifiers",
|
"/api/v1/control/devices/{device_id}/identifiers",
|
||||||
post(api::attach_device_identifier),
|
post(api::attach_device_identifier),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/api/v1/control/devices/{device_id}/identifiers/{identifier_key}",
|
||||||
|
axum::routing::delete(api::detach_device_identifier),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/api/v1/control/devices/{device_id}/identifiers/from-observation",
|
"/api/v1/control/devices/{device_id}/identifiers/from-observation",
|
||||||
post(api::attach_observation_identifier),
|
post(api::attach_observation_identifier),
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ mod types;
|
|||||||
|
|
||||||
pub use store::Store;
|
pub use store::Store;
|
||||||
pub use types::{
|
pub use types::{
|
||||||
AgentDeviceObservationEvent, AgentDeviceObservationInput, AgentDeviceObservationView,
|
AgentDeviceObservation, AgentDeviceObservationEvent, AgentDeviceObservationInput,
|
||||||
AlertState, AuditEvent, AuditEventFilter, AuditEventInput, DeviceIdentifierInput, KnownDevice,
|
AgentDeviceObservationView, AlertState, AuditEvent, AuditEventFilter, AuditEventInput,
|
||||||
KnownDeviceInput,
|
DeviceIdentifier, DeviceIdentifierInput, KnownDevice, KnownDeviceInput, KnownDeviceSummary,
|
||||||
};
|
};
|
||||||
@@ -337,6 +337,105 @@ mod tests {
|
|||||||
cleanup_dir(&dir);
|
cleanup_dir(&dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn device_identifier_can_be_detached_manually() {
|
||||||
|
let (store, dir) = make_store().await;
|
||||||
|
let created = store
|
||||||
|
.create_known_device(KnownDeviceInput {
|
||||||
|
display_name: "lda".into(),
|
||||||
|
pinned: true,
|
||||||
|
notes: None,
|
||||||
|
identifiers: vec![
|
||||||
|
DeviceIdentifierInput {
|
||||||
|
kind: "mac".into(),
|
||||||
|
value: "aa:bb:cc:dd:ee:ff".into(),
|
||||||
|
},
|
||||||
|
DeviceIdentifierInput {
|
||||||
|
kind: "ip".into(),
|
||||||
|
value: "192.168.1.2".into(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("known device should create");
|
||||||
|
|
||||||
|
let updated = store
|
||||||
|
.detach_device_identifier(&created.device_id, "ip:192.168.1.2")
|
||||||
|
.await
|
||||||
|
.expect("identifier detach should succeed")
|
||||||
|
.expect("device should exist");
|
||||||
|
|
||||||
|
assert_eq!(updated.identifiers.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
updated.identifiers[0].identifier_key,
|
||||||
|
"mac:aa:bb:cc:dd:ee:ff"
|
||||||
|
);
|
||||||
|
|
||||||
|
let unmatched = store
|
||||||
|
.lookup_known_device_by_identifier(DeviceIdentifierInput {
|
||||||
|
kind: "ip".into(),
|
||||||
|
value: "192.168.1.2".into(),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("lookup should succeed");
|
||||||
|
assert!(unmatched.is_none());
|
||||||
|
|
||||||
|
cleanup_dir(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn merge_known_devices_moves_identifiers_and_deletes_source() {
|
||||||
|
let (store, dir) = make_store().await;
|
||||||
|
let target = store
|
||||||
|
.create_known_device(KnownDeviceInput {
|
||||||
|
display_name: "lda".into(),
|
||||||
|
pinned: true,
|
||||||
|
notes: None,
|
||||||
|
identifiers: vec![DeviceIdentifierInput {
|
||||||
|
kind: "mac".into(),
|
||||||
|
value: "aa:bb:cc:dd:ee:01".into(),
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("target should create");
|
||||||
|
let source = store
|
||||||
|
.create_known_device(KnownDeviceInput {
|
||||||
|
display_name: "lda duplicate".into(),
|
||||||
|
pinned: false,
|
||||||
|
notes: None,
|
||||||
|
identifiers: vec![DeviceIdentifierInput {
|
||||||
|
kind: "mac".into(),
|
||||||
|
value: "aa:bb:cc:dd:ee:02".into(),
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("source should create");
|
||||||
|
|
||||||
|
let merged = store
|
||||||
|
.merge_known_devices(&target.device_id, &source.device_id)
|
||||||
|
.await
|
||||||
|
.expect("merge should succeed")
|
||||||
|
.expect("target should remain");
|
||||||
|
|
||||||
|
assert_eq!(merged.device_id, target.device_id);
|
||||||
|
assert_eq!(merged.identifiers.len(), 2);
|
||||||
|
assert!(
|
||||||
|
merged
|
||||||
|
.identifiers
|
||||||
|
.iter()
|
||||||
|
.any(|identifier| identifier.value == "aa:bb:cc:dd:ee:02")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
store
|
||||||
|
.get_known_device(&source.device_id)
|
||||||
|
.await
|
||||||
|
.expect("source lookup should work")
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
|
||||||
|
cleanup_dir(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn agent_observations_upsert_current_state_and_events() {
|
async fn agent_observations_upsert_current_state_and_events() {
|
||||||
let (store, dir) = make_store().await;
|
let (store, dir) = make_store().await;
|
||||||
|
|||||||
@@ -73,6 +73,75 @@ impl Store {
|
|||||||
Ok(result.rows_affected() > 0)
|
Ok(result.rows_affected() > 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn merge_known_devices(
|
||||||
|
&self,
|
||||||
|
target_device_id: &str,
|
||||||
|
source_device_id: &str,
|
||||||
|
) -> Result<Option<KnownDevice>> {
|
||||||
|
if target_device_id == source_device_id {
|
||||||
|
return self.get_known_device(target_device_id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = now_unix();
|
||||||
|
let now_i64 = i64::try_from(now).context("known device timestamp overflow")?;
|
||||||
|
let mut tx = self
|
||||||
|
.pool
|
||||||
|
.begin()
|
||||||
|
.await
|
||||||
|
.context("failed starting known device merge transaction")?;
|
||||||
|
|
||||||
|
let target_exists = sqlx::query_scalar!(
|
||||||
|
r#"SELECT COUNT(*) as "count!: i64" FROM known_devices WHERE device_id = ?1"#,
|
||||||
|
target_device_id
|
||||||
|
)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed checking target known device existence")?;
|
||||||
|
if target_exists == 0 {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let source_exists = sqlx::query_scalar!(
|
||||||
|
r#"SELECT COUNT(*) as "count!: i64" FROM known_devices WHERE device_id = ?1"#,
|
||||||
|
source_device_id
|
||||||
|
)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed checking source known device existence")?;
|
||||||
|
if source_exists == 0 {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlx::query!(
|
||||||
|
"UPDATE device_identifiers SET device_id = ?1 WHERE device_id = ?2",
|
||||||
|
target_device_id,
|
||||||
|
source_device_id
|
||||||
|
)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed moving source identifiers to target device")?;
|
||||||
|
sqlx::query!(
|
||||||
|
"DELETE FROM known_devices WHERE device_id = ?1",
|
||||||
|
source_device_id
|
||||||
|
)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed deleting merged source known device")?;
|
||||||
|
sqlx::query!(
|
||||||
|
"UPDATE known_devices SET updated_at_unix = ?1 WHERE device_id = ?2",
|
||||||
|
now_i64,
|
||||||
|
target_device_id
|
||||||
|
)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed updating merged target known device timestamp")?;
|
||||||
|
|
||||||
|
tx.commit()
|
||||||
|
.await
|
||||||
|
.context("failed committing known device merge transaction")?;
|
||||||
|
self.get_known_device(target_device_id).await
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn attach_device_identifier(
|
pub async fn attach_device_identifier(
|
||||||
&self,
|
&self,
|
||||||
device_id: &str,
|
device_id: &str,
|
||||||
@@ -127,6 +196,51 @@ impl Store {
|
|||||||
self.attach_device_identifier(device_id, input).await
|
self.attach_device_identifier(device_id, input).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn detach_device_identifier(
|
||||||
|
&self,
|
||||||
|
device_id: &str,
|
||||||
|
identifier_key: &str,
|
||||||
|
) -> Result<Option<KnownDevice>> {
|
||||||
|
let now = now_unix();
|
||||||
|
let now_i64 = i64::try_from(now).context("known device timestamp overflow")?;
|
||||||
|
let mut tx = self
|
||||||
|
.pool
|
||||||
|
.begin()
|
||||||
|
.await
|
||||||
|
.context("failed starting device identifier detach transaction")?;
|
||||||
|
let exists = sqlx::query_scalar!(
|
||||||
|
r#"SELECT COUNT(*) as "count!: i64" FROM known_devices WHERE device_id = ?1"#,
|
||||||
|
device_id
|
||||||
|
)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed checking known device existence")?;
|
||||||
|
if exists == 0 {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlx::query!(
|
||||||
|
"DELETE FROM device_identifiers WHERE device_id = ?1 AND identifier_key = ?2",
|
||||||
|
device_id,
|
||||||
|
identifier_key
|
||||||
|
)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed detaching device identifier")?;
|
||||||
|
sqlx::query!(
|
||||||
|
"UPDATE known_devices SET updated_at_unix = ?1 WHERE device_id = ?2",
|
||||||
|
now_i64,
|
||||||
|
device_id
|
||||||
|
)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("failed updating known device timestamp")?;
|
||||||
|
tx.commit()
|
||||||
|
.await
|
||||||
|
.context("failed committing device identifier detach transaction")?;
|
||||||
|
self.get_known_device(device_id).await
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg_attr(not(test), allow(dead_code))]
|
#[cfg_attr(not(test), allow(dead_code))]
|
||||||
pub async fn lookup_known_device_by_identifier(
|
pub async fn lookup_known_device_by_identifier(
|
||||||
&self,
|
&self,
|
||||||
|
|||||||
@@ -259,10 +259,7 @@ pub(in crate::state::store) fn normalize_agent_observation(
|
|||||||
let mac = normalize_optional_text(input.mac.as_deref()).map(|value| value.to_ascii_lowercase());
|
let mac = normalize_optional_text(input.mac.as_deref()).map(|value| value.to_ascii_lowercase());
|
||||||
let ip = normalize_optional_text(input.ip.as_deref());
|
let ip = normalize_optional_text(input.ip.as_deref());
|
||||||
let hostname = normalize_optional_text(input.hostname.as_deref());
|
let hostname = normalize_optional_text(input.hostname.as_deref());
|
||||||
let identifier = mac
|
let identifier = observation_identifier(&kind, mac.as_deref(), ip.as_deref())
|
||||||
.as_ref()
|
|
||||||
.map(|value| format!("mac:{value}"))
|
|
||||||
.or_else(|| ip.as_ref().map(|value| format!("ip:{value}")))
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("observation requires mac or ip"))?;
|
.ok_or_else(|| anyhow::anyhow!("observation requires mac or ip"))?;
|
||||||
let observation_key = format!("agent:{agent_id}:{kind}:{identifier}");
|
let observation_key = format!("agent:{agent_id}:{kind}:{identifier}");
|
||||||
Ok(AgentDeviceObservation {
|
Ok(AgentDeviceObservation {
|
||||||
@@ -278,6 +275,15 @@ pub(in crate::state::store) fn normalize_agent_observation(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn observation_identifier(kind: &str, mac: Option<&str>, ip: Option<&str>) -> Option<String> {
|
||||||
|
match (kind, mac, ip) {
|
||||||
|
("neigh" | "inventory", Some(mac), Some(ip)) => Some(format!("mac:{mac}:ip:{ip}")),
|
||||||
|
(_, Some(mac), _) => Some(format!("mac:{mac}")),
|
||||||
|
(_, None, Some(ip)) => Some(format!("ip:{ip}")),
|
||||||
|
(_, None, None) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(in crate::state::store) async fn insert_device_identifier_tx(
|
pub(in crate::state::store) async fn insert_device_identifier_tx(
|
||||||
tx: &mut Transaction<'_, Sqlite>,
|
tx: &mut Transaction<'_, Sqlite>,
|
||||||
device_id: &str,
|
device_id: &str,
|
||||||
|
|||||||
@@ -211,6 +211,8 @@ impl Store {
|
|||||||
r#"SELECT events.event_id as "event_id!",
|
r#"SELECT events.event_id as "event_id!",
|
||||||
('agent:' || events.agent_id || ':' || events.kind || ':' ||
|
('agent:' || events.agent_id || ':' || events.kind || ':' ||
|
||||||
CASE
|
CASE
|
||||||
|
WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL
|
||||||
|
THEN 'mac:' || events.mac || ':ip:' || events.ip
|
||||||
WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac
|
WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac
|
||||||
WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip
|
WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip
|
||||||
ELSE ''
|
ELSE ''
|
||||||
@@ -239,6 +241,8 @@ impl Store {
|
|||||||
AND (?4 IS NULL OR events.ip = ?4)
|
AND (?4 IS NULL OR events.ip = ?4)
|
||||||
AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||
|
AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||
|
||||||
CASE
|
CASE
|
||||||
|
WHEN events.kind IN ('neigh', 'inventory') AND events.mac IS NOT NULL AND events.ip IS NOT NULL
|
||||||
|
THEN 'mac:' || events.mac || ':ip:' || events.ip
|
||||||
WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac
|
WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac
|
||||||
WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip
|
WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip
|
||||||
ELSE ''
|
ELSE ''
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use std::time::Instant;
|
|||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use tracing::{debug, info, info_span, warn};
|
use tracing::{debug, info, info_span, warn};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use wakey_agent::protocol::{ErrorPayload, RequestId};
|
use wakey_agent::protocol::{AgentObservation, ErrorPayload, RequestId, ServerMessage};
|
||||||
|
|
||||||
use crate::runtime::{AgentReply, AgentSession, AppState, SessionEvent};
|
use crate::runtime::{AgentReply, AgentSession, AppState, SessionEvent};
|
||||||
use crate::state::AuditEventInput;
|
use crate::state::AuditEventInput;
|
||||||
@@ -26,6 +26,10 @@ enum IncomingClientMessage {
|
|||||||
Heartbeat {
|
Heartbeat {
|
||||||
agent_id: String,
|
agent_id: String,
|
||||||
},
|
},
|
||||||
|
Observations {
|
||||||
|
agent_id: String,
|
||||||
|
observations: Vec<AgentObservation>,
|
||||||
|
},
|
||||||
Result {
|
Result {
|
||||||
request_id: RequestId,
|
request_id: RequestId,
|
||||||
result: serde_json::Value,
|
result: serde_json::Value,
|
||||||
@@ -238,6 +242,7 @@ async fn process_agent_text(
|
|||||||
{
|
{
|
||||||
warn!(error = %err, "failed to append audit event for auth success");
|
warn!(error = %err, "failed to append audit event for auth success");
|
||||||
}
|
}
|
||||||
|
let _ = tx.send(SessionEvent::Message(ServerMessage::SyncObservations));
|
||||||
}
|
}
|
||||||
IncomingClientMessage::Heartbeat { agent_id } => {
|
IncomingClientMessage::Heartbeat { agent_id } => {
|
||||||
if authed_agent_id.as_deref() != Some(agent_id.as_str()) {
|
if authed_agent_id.as_deref() != Some(agent_id.as_str()) {
|
||||||
@@ -246,6 +251,40 @@ async fn process_agent_text(
|
|||||||
ensure_current_session(state, &agent_id, connection_id).await?;
|
ensure_current_session(state, &agent_id, connection_id).await?;
|
||||||
debug!(agent_id = %agent_id, "heartbeat received");
|
debug!(agent_id = %agent_id, "heartbeat received");
|
||||||
}
|
}
|
||||||
|
IncomingClientMessage::Observations {
|
||||||
|
agent_id,
|
||||||
|
observations,
|
||||||
|
} => {
|
||||||
|
if authed_agent_id.as_deref() != Some(agent_id.as_str()) {
|
||||||
|
anyhow::bail!("observations for unauthenticated or mismatched agent");
|
||||||
|
}
|
||||||
|
ensure_current_session(state, &agent_id, connection_id).await?;
|
||||||
|
let inputs = observations
|
||||||
|
.into_iter()
|
||||||
|
.map(|observation| crate::state::AgentDeviceObservationInput {
|
||||||
|
kind: observation.kind,
|
||||||
|
action: observation.action,
|
||||||
|
mac: observation.mac,
|
||||||
|
ip: observation.ip.map(|ip| ip.to_string()),
|
||||||
|
hostname: observation.hostname,
|
||||||
|
first_seen_unix: observation.first_seen_unix,
|
||||||
|
last_seen_unix: observation.last_seen_unix,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
match state
|
||||||
|
.store
|
||||||
|
.upsert_agent_observations(&agent_id, inputs)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(accepted) => {
|
||||||
|
debug!(agent_id = %agent_id, accepted, "agent websocket observations accepted");
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!(agent_id = %agent_id, error = %err, "failed to store websocket observations");
|
||||||
|
anyhow::bail!("failed to store observations: {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
IncomingClientMessage::Result { request_id, result } => {
|
IncomingClientMessage::Result { request_id, result } => {
|
||||||
let agent_id = authed_agent_id
|
let agent_id = authed_agent_id
|
||||||
.as_deref()
|
.as_deref()
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wakey-core"
|
name = "wakey-core"
|
||||||
version = "0.2.2"
|
version = "0.2.3"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = ["gitea"]
|
publish = ["gitea"]
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "wakey-linux"
|
name = "wakey-linux"
|
||||||
version = "0.2.2"
|
version = "0.2.3"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = ["gitea"]
|
publish = ["gitea"]
|
||||||
|
|
||||||
|
|||||||
@@ -136,4 +136,47 @@ mod tests {
|
|||||||
let _ = tokio::fs::remove_file(observation_path).await;
|
let _ = tokio::fs::remove_file(observation_path).await;
|
||||||
let _ = tokio::fs::remove_file(cache_path).await;
|
let _ = tokio::fs::remove_file(cache_path).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[serial]
|
||||||
|
async fn neighbor_observations_are_keyed_by_mac_ip_pair() {
|
||||||
|
let observation_path = temp_file("neighbor-observations");
|
||||||
|
let _observation_guard = EnvGuard::set(OBSERVATION_STORE_ENV, &observation_path);
|
||||||
|
let mac = "aa:bb:cc:dd:ee:ff".parse().expect("mac should parse");
|
||||||
|
|
||||||
|
observe_neighbor_event(
|
||||||
|
"add",
|
||||||
|
Some(mac),
|
||||||
|
Some("192.168.1.2".parse().expect("ip should parse")),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("first observation should write");
|
||||||
|
observe_neighbor_event(
|
||||||
|
"update",
|
||||||
|
Some(mac),
|
||||||
|
Some("192.168.1.3".parse().expect("ip should parse")),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("second observation should write");
|
||||||
|
|
||||||
|
let store = load_observation_store()
|
||||||
|
.await
|
||||||
|
.expect("observation store should read");
|
||||||
|
assert!(
|
||||||
|
store
|
||||||
|
.neighbors
|
||||||
|
.contains_key("mac:aa:bb:cc:dd:ee:ff:ip:192.168.1.2")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
store
|
||||||
|
.neighbors
|
||||||
|
.contains_key("mac:aa:bb:cc:dd:ee:ff:ip:192.168.1.3")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
store.neighbors["mac:aa:bb:cc:dd:ee:ff:ip:192.168.1.2"].last_action,
|
||||||
|
"remove"
|
||||||
|
);
|
||||||
|
|
||||||
|
let _ = tokio::fs::remove_file(observation_path).await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -218,14 +218,11 @@ pub async fn observe_neighbor_event(
|
|||||||
mac: Option<MacAddr>,
|
mac: Option<MacAddr>,
|
||||||
ip: Option<IpAddr>,
|
ip: Option<IpAddr>,
|
||||||
) -> io::Result<bool> {
|
) -> io::Result<bool> {
|
||||||
if !matches!(action, "add" | "update" | "old" | "remove") {
|
let action = normalize_neighbor_action(action);
|
||||||
// update and remove not emitted by hotplug
|
if !is_neighbor_observation_action(&action) {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
let Some(key) = mac
|
let Some(key) = neighbor_observation_key(mac, ip) else {
|
||||||
.map(|value| format!("mac:{}", value.to_string().to_ascii_lowercase()))
|
|
||||||
.or_else(|| ip.map(|value| format!("ip:{}", value)))
|
|
||||||
else {
|
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -244,7 +241,7 @@ pub async fn observe_neighbor_event(
|
|||||||
{
|
{
|
||||||
row.mac = mac.clone();
|
row.mac = mac.clone();
|
||||||
row.ip = ip;
|
row.ip = ip;
|
||||||
row.last_action = action.to_string();
|
row.last_action = action.clone();
|
||||||
row.last_seen_unix = now;
|
row.last_seen_unix = now;
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
@@ -253,15 +250,78 @@ pub async fn observe_neighbor_event(
|
|||||||
changed = true;
|
changed = true;
|
||||||
ObservedNeighbor {
|
ObservedNeighbor {
|
||||||
key,
|
key,
|
||||||
mac,
|
mac: mac.clone(),
|
||||||
ip,
|
ip,
|
||||||
first_seen_unix: now,
|
first_seen_unix: now,
|
||||||
last_seen_unix: now,
|
last_seen_unix: now,
|
||||||
last_action: action.to_string(),
|
last_action: action.clone(),
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if let (Some(mac), Some(ip)) = (mac.as_deref(), ip)
|
||||||
|
&& !is_offline_neighbor_action(&action)
|
||||||
|
{
|
||||||
|
mark_replaced_neighbor_ips_removed(&mut store, mac, ip, now, &mut changed);
|
||||||
|
}
|
||||||
if changed {
|
if changed {
|
||||||
save_observation_store(&store).await?;
|
save_observation_store(&store).await?;
|
||||||
}
|
}
|
||||||
Ok(changed)
|
Ok(changed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn normalize_neighbor_action(action: &str) -> String {
|
||||||
|
match action.trim().to_ascii_lowercase().as_str() {
|
||||||
|
"del" => "remove".into(),
|
||||||
|
"old" => "update".into(),
|
||||||
|
other => other.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_neighbor_observation_action(action: &str) -> bool {
|
||||||
|
matches!(action, "add" | "update" | "remove")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_offline_neighbor_action(action: &str) -> bool {
|
||||||
|
action == "remove"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn neighbor_observation_key(mac: Option<MacAddr>, ip: Option<IpAddr>) -> Option<String> {
|
||||||
|
match (mac, ip) {
|
||||||
|
(Some(mac), Some(ip)) => Some(format!(
|
||||||
|
"mac:{}:ip:{ip}",
|
||||||
|
mac.to_string().to_ascii_lowercase()
|
||||||
|
)),
|
||||||
|
(Some(mac), None) => Some(format!("mac:{}", mac.to_string().to_ascii_lowercase())),
|
||||||
|
(None, Some(ip)) => Some(format!("ip:{ip}")),
|
||||||
|
(None, None) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mark_replaced_neighbor_ips_removed(
|
||||||
|
store: &mut LocalObservationStore,
|
||||||
|
mac: &str,
|
||||||
|
current_ip: IpAddr,
|
||||||
|
now: u64,
|
||||||
|
changed: &mut bool,
|
||||||
|
) {
|
||||||
|
for row in store.neighbors.values_mut() {
|
||||||
|
let Some(row_ip) = row.ip else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if row.mac.as_deref() == Some(mac)
|
||||||
|
&& row_ip != current_ip
|
||||||
|
&& same_ip_family(row_ip, current_ip)
|
||||||
|
&& !is_offline_neighbor_action(&row.last_action)
|
||||||
|
{
|
||||||
|
row.last_action = "remove".into();
|
||||||
|
row.last_seen_unix = now;
|
||||||
|
*changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same_ip_family(a: IpAddr, b: IpAddr) -> bool {
|
||||||
|
matches!(
|
||||||
|
(a, b),
|
||||||
|
(IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
|
||||||
|
)
|
||||||
|
}
|
||||||
Reference in new issue
Block a user