From 14df05a20cdc911ab6a793a6fcd34214bba68641 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Sun, 29 Nov 2026 21:41:27 +1300 Subject: [PATCH 1/3] feat(nodes): add NodeWriter.WakeOnLanAsync and `node wake` POST /nodes/{node}/wakeonlan, sent to whichever node the adapter points at (the method has no proxyto, so that node sends the packet). Hoists the form send shared by QemuWriter/PctWriter into ProxmoxForm now a third writer uses it. Library 0.2.3, CLI 0.1.1. --- README.md | 5 ++ src/ProxmoxSharp.Cli/Program.cs | 27 ++++++++- src/ProxmoxSharp.Cli/ProxmoxSharp.Cli.csproj | 2 +- src/ProxmoxSharp/Lxc/PctWriter.cs | 52 +++-------------- src/ProxmoxSharp/Nodes/NodeWriter.cs | 44 ++++++++++++++ src/ProxmoxSharp/ProxmoxForm.cs | 61 ++++++++++++++++++++ src/ProxmoxSharp/ProxmoxSharp.csproj | 2 +- src/ProxmoxSharp/Vm/QemuWriter.cs | 46 +-------------- 8 files changed, 147 insertions(+), 92 deletions(-) create mode 100644 src/ProxmoxSharp/Nodes/NodeWriter.cs create mode 100644 src/ProxmoxSharp/ProxmoxForm.cs diff --git a/README.md b/README.md index bc9ddfb..1d3d9cd 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,10 @@ from nuget.org with no credentials. CI (`.github/workflows/ci.yml`) runs var client = ProxmoxApi.Create(options); // token auth + base URL + TLS handling var version = await client.Version.GetAsVersionGetResponseAsync(); var nodes = await client.Nodes.GetAsNodesGetResponseAsync(); + +// Wake-on-LAN: the node behind options.BaseUrl SENDS the packet; "desktop-01" is the target. +// Needs Sys.PowerMgmt on /nodes/desktop-01. Returns the MAC Proxmox used. +var mac = await NodeWriter.Create(options).WakeOnLanAsync("desktop-01"); ``` ## CLI (`proxmoxsharp`) @@ -94,6 +98,7 @@ export PROXMOX_VERIFY_TLS=false proxmoxsharp version # PVE version proxmoxsharp nodes # list nodes proxmoxsharp discover # structured ClusterSnapshot as JSON +proxmoxsharp node wake desktop-01 # WoL desktop-01, sent by the node PROXMOX_BASE_URL points at ``` ## Refresh the schema (new Proxmox release) diff --git a/src/ProxmoxSharp.Cli/Program.cs b/src/ProxmoxSharp.Cli/Program.cs index 867ff5d..6b0546e 100644 --- a/src/ProxmoxSharp.Cli/Program.cs +++ b/src/ProxmoxSharp.Cli/Program.cs @@ -1,11 +1,12 @@ using System.Text.Json; using ProxmoxSharp; using ProxmoxSharp.Lxc; +using ProxmoxSharp.Nodes; using ProxmoxSharp.Vm; // proxmoxsharp — a thin CLI over the ProxmoxSharp library. // -// Commands: discover | nodes | version | vm <…> | lxc +// Commands: discover | nodes | version | vm <…> | lxc | node wake // Config (env): PROXMOX_BASE_URL, PROXMOX_TOKEN_ID, PROXMOX_TOKEN_SECRET, // PROXMOX_VERIFY_TLS (optional, 'false' for self-signed nodes) @@ -35,6 +36,9 @@ lxc start Start a container lxc shutdown Graceful shutdown (hard-stop fallback) lxc delete --confirm [--force] [--no-purge] Destroy a container + node wake Wake-on-LAN ; the packet is sent by the node + PROXMOX_BASE_URL points at (never itself) + Config (env): PROXMOX_BASE_URL, PROXMOX_TOKEN_ID, PROXMOX_TOKEN_SECRET, PROXMOX_VERIFY_TLS (optional, 'false' for self-signed) """); @@ -82,8 +86,11 @@ lxc delete --confirm [--force] [--no-purge] Destroy a containe case "lxc": return await RunLxc(args, options); + case "node": + return await RunNode(args, options); + default: - Console.Error.WriteLine($"Unknown command '{command}'. Try: discover | nodes | version | vm | lxc"); + Console.Error.WriteLine($"Unknown command '{command}'. Try: discover | nodes | version | vm | lxc | node"); return 1; } @@ -213,6 +220,22 @@ static async Task RunLxc(string[] args, ProxmoxClientOptions options) } } +// node wake — wake-on-LAN through the Proxmox API. +static async Task RunNode(string[] args, ProxmoxClientOptions options) +{ + var sub = args.Length > 1 ? args[1].ToLowerInvariant() : ""; + if (sub != "wake" || args.Length < 3) + { + Console.Error.WriteLine("usage: proxmoxsharp node wake "); + return 2; + } + + var node = args[2]; + var mac = await NodeWriter.Create(options).WakeOnLanAsync(node); + Console.WriteLine($"Wake-on-LAN sent for {node} via {options.BaseUrl.Host} (MAC {mac ?? "(not reported)"})."); + return 0; +} + static bool TryNodeVmid(string[] args, out string node, out int vmid) { node = ""; vmid = 0; diff --git a/src/ProxmoxSharp.Cli/ProxmoxSharp.Cli.csproj b/src/ProxmoxSharp.Cli/ProxmoxSharp.Cli.csproj index 32566ab..46cf577 100644 --- a/src/ProxmoxSharp.Cli/ProxmoxSharp.Cli.csproj +++ b/src/ProxmoxSharp.Cli/ProxmoxSharp.Cli.csproj @@ -13,7 +13,7 @@ proxmoxsharp Chrison.ProxmoxSharp.Cli - 0.1.0 + 0.1.1 CLI for ProxmoxSharp — read and discover Proxmox VE from the shell. diff --git a/src/ProxmoxSharp/Lxc/PctWriter.cs b/src/ProxmoxSharp/Lxc/PctWriter.cs index 45810ac..3b898ea 100644 --- a/src/ProxmoxSharp/Lxc/PctWriter.cs +++ b/src/ProxmoxSharp/Lxc/PctWriter.cs @@ -1,10 +1,7 @@ using System.Globalization; -using System.Text; -using System.Text.Json; using Microsoft.Kiota.Abstractions; -using Microsoft.Kiota.Abstractions.Serialization; using ProxmoxSharp.Api; -using ProxmoxSharp.Vm; // ProxmoxApiError (internal, same assembly) +using ProxmoxSharp.Vm; // QemuWriter (doc cref) namespace ProxmoxSharp.Lxc; @@ -17,8 +14,8 @@ namespace ProxmoxSharp.Lxc; /// like — they go over the shared Kiota adapter as /// raw form requests (same token-auth + TLS as the read client) rather than the typed /// builders. All mutating ops return Proxmox's task UPID; poll it with -/// . The form-send + task-poll helpers intentionally mirror -/// QemuWriter; hoist a shared base if a third writer ever appears. +/// . The form send is shared with the other writers +/// (); task polling still mirrors QemuWriter. /// /// public sealed class PctWriter @@ -102,13 +99,7 @@ public static string ShutdownQuery(bool forceStop, int timeout) => } } - // --- internals (mirror QemuWriter) ------------------------------------- - - private static readonly Dictionary> ErrorMapping = new() - { - ["4XX"] = static _ => new ProxmoxApiError(), - ["5XX"] = static _ => new ProxmoxApiError(), - }; + // --- internals --------------------------------------------------------- private Dictionary PathParams(string node, int vmid) => new() { @@ -117,37 +108,8 @@ public static string ShutdownQuery(bool forceStop, int timeout) => ["vmid"] = vmid.ToString(CultureInfo.InvariantCulture), }; - private async Task SendFormAsync( + private Task SendFormAsync( Method method, string urlTemplate, Dictionary pathParams, - IReadOnlyDictionary? form, CancellationToken ct) - { - var ri = new RequestInformation(method, urlTemplate, pathParams); - ri.Headers.TryAdd("Accept", "application/json"); - if (form is not null) - { - var body = string.Join("&", form.Select(kv => - $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}")); - ri.SetStreamContent(new MemoryStream(Encoding.UTF8.GetBytes(body)), "application/x-www-form-urlencoded"); - } - - Stream? stream; - try - { - stream = await _adapter.SendPrimitiveAsync(ri, ErrorMapping, cancellationToken: ct).ConfigureAwait(false); - } - catch (ProxmoxApiError err) - { - var detail = err.AdditionalData.Count > 0 - ? string.Join("; ", err.AdditionalData.Select(kv => $"{kv.Key}={kv.Value}")) - : "(empty body)"; - throw new InvalidOperationException( - $"Proxmox {method} {urlTemplate} failed (HTTP {err.ResponseStatusCode}): {detail}", err); - } - if (stream is null) return null; - await using var _ = stream.ConfigureAwait(false); - using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: ct).ConfigureAwait(false); - return doc.RootElement.TryGetProperty("data", out var d) && d.ValueKind == JsonValueKind.String - ? d.GetString() - : null; - } + IReadOnlyDictionary? form, CancellationToken ct) => + ProxmoxForm.SendAsync(_adapter, method, urlTemplate, pathParams, form, ct); } diff --git a/src/ProxmoxSharp/Nodes/NodeWriter.cs b/src/ProxmoxSharp/Nodes/NodeWriter.cs new file mode 100644 index 0000000..d3c6adc --- /dev/null +++ b/src/ProxmoxSharp/Nodes/NodeWriter.cs @@ -0,0 +1,44 @@ +using Microsoft.Kiota.Abstractions; + +namespace ProxmoxSharp.Nodes; + +/// +/// Node-level write path. Today this is wake-on-LAN only (POST /nodes/{node}/wakeonlan). +/// +/// The Proxmox method has no proxyto: the node the request is SENT TO builds and +/// broadcasts the magic packet, using the MAC from the target's +/// /etc/pve/nodes/{node}/config (wakeonlan: …) and its own broadcast/bind +/// settings. So the adapter's base URL picks the sender and picks the +/// target; a node refuses to wake itself. Needs Sys.PowerMgmt on /nodes/{node}. +/// +/// +public sealed class NodeWriter +{ + private readonly IRequestAdapter _adapter; + + public NodeWriter(IRequestAdapter adapter) + { + ArgumentNullException.ThrowIfNull(adapter); + _adapter = adapter; + } + + /// Build a writer with the same auth/TLS wiring as . + public static NodeWriter Create(ProxmoxClientOptions options) => new(ProxmoxApi.CreateAdapter(options)); + + private string BaseUrl => _adapter.BaseUrl ?? throw new InvalidOperationException("Adapter has no BaseUrl."); + + /// + /// Ask the node behind this writer's base URL to send a wake-on-LAN packet to + /// (POST /nodes/{node}/wakeonlan). Returns the MAC address Proxmox + /// built the packet for, or null if the response carried no MAC. A sent packet is no + /// proof the node wakes; poll the node's state for that. Throws + /// with Proxmox's error text on an HTTP error + /// (no wakeonlan MAC configured, target is the local node, missing privilege). + /// + public Task WakeOnLanAsync(string node, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(node); + return ProxmoxForm.SendAsync(_adapter, Method.POST, "{+baseurl}/nodes/{node}/wakeonlan", + new Dictionary { ["baseurl"] = BaseUrl, ["node"] = node }, form: null, ct); + } +} diff --git a/src/ProxmoxSharp/ProxmoxForm.cs b/src/ProxmoxSharp/ProxmoxForm.cs new file mode 100644 index 0000000..871da42 --- /dev/null +++ b/src/ProxmoxSharp/ProxmoxForm.cs @@ -0,0 +1,61 @@ +using System.Text; +using System.Text.Json; +using Microsoft.Kiota.Abstractions; +using Microsoft.Kiota.Abstractions.Serialization; +using ProxmoxSharp.Vm; // ProxmoxApiError (internal, same assembly) + +namespace ProxmoxSharp; + +/// +/// The raw form-send shared by the writers (, , +/// ). Hoisted out of QemuWriter/PctWriter when the third writer +/// appeared. Sends over the caller's Kiota adapter (same token-auth + TLS as the read client) and +/// returns Proxmox's data field when it is a string — a task UPID for lifecycle ops, a MAC +/// for wakeonlan — or null when the response carried none. +/// +internal static class ProxmoxForm +{ + // Catch-all error mapping: parse ANY error status into ProxmoxApiError, whose + // IAdditionalDataHolder grabs every JSON field Proxmox returned (data/errors/message). + private static readonly Dictionary> ErrorMapping = new() + { + ["4XX"] = static _ => new ProxmoxApiError(), + ["5XX"] = static _ => new ProxmoxApiError(), + }; + + public static async Task SendAsync( + IRequestAdapter adapter, Method method, string urlTemplate, Dictionary pathParams, + IReadOnlyDictionary? form, CancellationToken ct) + { + var ri = new RequestInformation(method, urlTemplate, pathParams); + ri.Headers.TryAdd("Accept", "application/json"); + if (form is not null) + { + var body = string.Join("&", form.Select(kv => + $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}")); + ri.SetStreamContent(new MemoryStream(Encoding.UTF8.GetBytes(body)), "application/x-www-form-urlencoded"); + } + + Stream? stream; + try + { + stream = await adapter.SendPrimitiveAsync(ri, ErrorMapping, cancellationToken: ct).ConfigureAwait(false); + } + catch (ProxmoxApiError err) + { + // Surface Proxmox's actual error body — the generated client otherwise + // throws a bare "no error factory for " and discards the message. + var detail = err.AdditionalData.Count > 0 + ? string.Join("; ", err.AdditionalData.Select(kv => $"{kv.Key}={kv.Value}")) + : "(empty body)"; + throw new InvalidOperationException( + $"Proxmox {method} {urlTemplate} failed (HTTP {err.ResponseStatusCode}): {detail}", err); + } + if (stream is null) return null; + await using var _ = stream.ConfigureAwait(false); + using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: ct).ConfigureAwait(false); + return doc.RootElement.TryGetProperty("data", out var d) && d.ValueKind == JsonValueKind.String + ? d.GetString() + : null; + } +} diff --git a/src/ProxmoxSharp/ProxmoxSharp.csproj b/src/ProxmoxSharp/ProxmoxSharp.csproj index ab66b1f..c92d31b 100644 --- a/src/ProxmoxSharp/ProxmoxSharp.csproj +++ b/src/ProxmoxSharp/ProxmoxSharp.csproj @@ -10,7 +10,7 @@ Bumped to 0.2.0 so the active 0.2.0-preview.N line outranks the earlier 0.1.0 stable in NuGet ordering — a `0.1.0-preview.*` float would otherwise resolve the stale 0.1.0 stable (prereleases sort below their release). --> - 0.2.2 + 0.2.3