Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand All @@ -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)
Expand Down
27 changes: 25 additions & 2 deletions src/ProxmoxSharp.Cli/Program.cs
Original file line number Diff line number Diff line change
@@ -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 <start|stop|shutdown|delete>
// Commands: discover | nodes | version | vm <…> | lxc <start|stop|shutdown|delete> | node wake
// Config (env): PROXMOX_BASE_URL, PROXMOX_TOKEN_ID, PROXMOX_TOKEN_SECRET,
// PROXMOX_VERIFY_TLS (optional, 'false' for self-signed nodes)

Expand Down Expand Up @@ -35,6 +36,9 @@ lxc start <node> <vmid> Start a container
lxc shutdown <node> <vmid> Graceful shutdown (hard-stop fallback)
lxc delete <node> <vmid> --confirm [--force] [--no-purge] Destroy a container

node wake <node> Wake-on-LAN <node>; the packet is sent by the node
PROXMOX_BASE_URL points at (never <node> itself)

Config (env): PROXMOX_BASE_URL, PROXMOX_TOKEN_ID, PROXMOX_TOKEN_SECRET,
PROXMOX_VERIFY_TLS (optional, 'false' for self-signed)
""");
Expand Down Expand Up @@ -82,8 +86,11 @@ lxc delete <node> <vmid> --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;
}

Expand Down Expand Up @@ -213,6 +220,22 @@ static async Task<int> RunLxc(string[] args, ProxmoxClientOptions options)
}
}

// node wake <node> — wake-on-LAN through the Proxmox API.
static async Task<int> 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 <node>");
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;
Expand Down
2 changes: 1 addition & 1 deletion src/ProxmoxSharp.Cli/ProxmoxSharp.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<ToolCommandName>proxmoxsharp</ToolCommandName>
<PackageId>Chrison.ProxmoxSharp.Cli</PackageId>
<!-- Co-versioned with the library (SemVer); CI appends -preview.N. -->
<VersionPrefix>0.1.0</VersionPrefix>
<VersionPrefix>0.1.1</VersionPrefix>
<Description>CLI for ProxmoxSharp — read and discover Proxmox VE from the shell.</Description>
</PropertyGroup>

Expand Down
52 changes: 7 additions & 45 deletions src/ProxmoxSharp/Lxc/PctWriter.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -17,8 +14,8 @@ namespace ProxmoxSharp.Lxc;
/// like <see cref="QemuWriter.DeleteAsync"/> — 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
/// <see cref="WaitForTaskAsync"/>. The form-send + task-poll helpers intentionally mirror
/// QemuWriter; hoist a shared base if a third writer ever appears.
/// <see cref="WaitForTaskAsync"/>. The form send is shared with the other writers
/// (<see cref="ProxmoxForm"/>); task polling still mirrors QemuWriter.
/// </para>
/// </summary>
public sealed class PctWriter
Expand Down Expand Up @@ -102,13 +99,7 @@ public static string ShutdownQuery(bool forceStop, int timeout) =>
}
}

// --- internals (mirror QemuWriter) -------------------------------------

private static readonly Dictionary<string, ParsableFactory<IParsable>> ErrorMapping = new()
{
["4XX"] = static _ => new ProxmoxApiError(),
["5XX"] = static _ => new ProxmoxApiError(),
};
// --- internals ---------------------------------------------------------

private Dictionary<string, object> PathParams(string node, int vmid) => new()
{
Expand All @@ -117,37 +108,8 @@ public static string ShutdownQuery(bool forceStop, int timeout) =>
["vmid"] = vmid.ToString(CultureInfo.InvariantCulture),
};

private async Task<string?> SendFormAsync(
private Task<string?> SendFormAsync(
Method method, string urlTemplate, Dictionary<string, object> pathParams,
IReadOnlyDictionary<string, string>? 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<Stream>(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<string, string>? form, CancellationToken ct) =>
ProxmoxForm.SendAsync(_adapter, method, urlTemplate, pathParams, form, ct);
}
44 changes: 44 additions & 0 deletions src/ProxmoxSharp/Nodes/NodeWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Microsoft.Kiota.Abstractions;

namespace ProxmoxSharp.Nodes;

/// <summary>
/// Node-level write path. Today this is wake-on-LAN only (POST /nodes/{node}/wakeonlan).
/// <para>
/// The Proxmox method has no <c>proxyto</c>: the node the request is SENT TO builds and
/// broadcasts the magic packet, using the MAC from the target's
/// <c>/etc/pve/nodes/{node}/config</c> (<c>wakeonlan: …</c>) and its own broadcast/bind
/// settings. So the adapter's base URL picks the sender and <paramref name="node"/> picks the
/// target; a node refuses to wake itself. Needs <c>Sys.PowerMgmt</c> on <c>/nodes/{node}</c>.
/// </para>
/// </summary>
public sealed class NodeWriter
{
private readonly IRequestAdapter _adapter;

public NodeWriter(IRequestAdapter adapter)
{
ArgumentNullException.ThrowIfNull(adapter);
_adapter = adapter;
}

/// <summary>Build a writer with the same auth/TLS wiring as <see cref="ProxmoxApi.Create"/>.</summary>
public static NodeWriter Create(ProxmoxClientOptions options) => new(ProxmoxApi.CreateAdapter(options));

private string BaseUrl => _adapter.BaseUrl ?? throw new InvalidOperationException("Adapter has no BaseUrl.");

/// <summary>
/// Ask the node behind this writer's base URL to send a wake-on-LAN packet to
/// <paramref name="node"/> (POST /nodes/{node}/wakeonlan). Returns the MAC address Proxmox
/// built the packet for, or <c>null</c> if the response carried no MAC. A sent packet is no
/// proof the node wakes; poll the node's state for that. Throws
/// <see cref="InvalidOperationException"/> with Proxmox's error text on an HTTP error
/// (no <c>wakeonlan</c> MAC configured, target is the local node, missing privilege).
/// </summary>
public Task<string?> WakeOnLanAsync(string node, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(node);
return ProxmoxForm.SendAsync(_adapter, Method.POST, "{+baseurl}/nodes/{node}/wakeonlan",
new Dictionary<string, object> { ["baseurl"] = BaseUrl, ["node"] = node }, form: null, ct);
}
}
79 changes: 79 additions & 0 deletions src/ProxmoxSharp/ProxmoxForm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
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;

/// <summary>
/// The raw form-send shared by the writers (<see cref="QemuWriter"/>, <see cref="Lxc.PctWriter"/>,
/// <see cref="Nodes.NodeWriter"/>). 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 <c>data</c> field when it is a string — a task UPID for lifecycle ops, a MAC
/// for wakeonlan — or <c>null</c> when the response carried none.
/// </summary>
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<string, ParsableFactory<IParsable>> ErrorMapping = new()
{
["4XX"] = static _ => new ProxmoxApiError(),
["5XX"] = static _ => new ProxmoxApiError(),
};

public static async Task<string?> SendAsync(
IRequestAdapter adapter, Method method, string urlTemplate, Dictionary<string, object> pathParams,
IReadOnlyDictionary<string, string>? 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<Stream>(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 <code>" and discards the message.
var detail = err.AdditionalData.Count > 0
? string.Join("; ", err.AdditionalData.Select(kv => $"{kv.Key}={Render(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;
}

// Kiota keeps a nested error field (Proxmox's per-parameter `errors` object) as an
// UntypedNode, whose ToString() is only the type name. Render it so the detail survives.
private static string Render(object? value) => value switch
{
null => "null",
UntypedObject o => "{" + string.Join(", ", o.GetValue().Select(kv => $"{kv.Key}={Render(kv.Value)}")) + "}",
UntypedArray a => "[" + string.Join(", ", a.GetValue().Select(Render)) + "]",
UntypedNull => "null",
UntypedString v => v.GetValue() ?? "null",
UntypedBoolean v => v.GetValue() ? "true" : "false",
UntypedInteger v => v.GetValue().ToString(System.Globalization.CultureInfo.InvariantCulture),
UntypedLong v => v.GetValue().ToString(System.Globalization.CultureInfo.InvariantCulture),
UntypedDouble v => v.GetValue().ToString(System.Globalization.CultureInfo.InvariantCulture),
UntypedFloat v => v.GetValue().ToString(System.Globalization.CultureInfo.InvariantCulture),
UntypedDecimal v => v.GetValue().ToString(System.Globalization.CultureInfo.InvariantCulture),
_ => value.ToString() ?? "",
};
}
2 changes: 1 addition & 1 deletion src/ProxmoxSharp/ProxmoxSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -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). -->
<VersionPrefix>0.2.2</VersionPrefix>
<VersionPrefix>0.2.3</VersionPrefix>
<!-- Public nuget.org ID uses the reserved Chrison.* prefix (the bare
'ProxmoxSharp' ID is taken on nuget.org by an unrelated project).
AssemblyName/RootNamespace stay 'ProxmoxSharp' (project name) so
Expand Down
46 changes: 3 additions & 43 deletions src/ProxmoxSharp/Vm/QemuWriter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Text;
using System.Text.Json;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Serialization;
Expand Down Expand Up @@ -147,14 +146,6 @@ public async Task<IReadOnlyList<PciDevice>> ListPciAsync(string node, Cancellati

// --- internals ---------------------------------------------------------

// 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<string, ParsableFactory<IParsable>> ErrorMapping = new()
{
["4XX"] = static _ => new ProxmoxApiError(),
["5XX"] = static _ => new ProxmoxApiError(),
};

private Dictionary<string, object> PathParams(string node, int vmid) => new()
{
["baseurl"] = BaseUrl,
Expand All @@ -164,41 +155,10 @@ public async Task<IReadOnlyList<PciDevice>> ListPciAsync(string node, Cancellati

private static string Id(int vmid) => vmid.ToString(System.Globalization.CultureInfo.InvariantCulture);

private async Task<string?> SendFormAsync(
private Task<string?> SendFormAsync(
Method method, string urlTemplate, Dictionary<string, object> pathParams,
IReadOnlyDictionary<string, string>? 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<Stream>(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 <code>" 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;
}
IReadOnlyDictionary<string, string>? form, CancellationToken ct) =>
ProxmoxForm.SendAsync(_adapter, method, urlTemplate, pathParams, form, ct);
}

/// <summary>A PCI device reported by a node (subset relevant to passthrough).</summary>
Expand Down
Loading
Loading