mirror of
https://github.com/GoodOlClint/PSProxmoxVE.git
synced 2026-07-27 08:18:56 +00:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3a50dd2fb7 | |||
| ee69c699b1 | |||
| 5cb5c90db8 | |||
| 56dcf22cea | |||
| bc71ed4a12 | |||
| 5266accfae | |||
| e959fbb9b8 | |||
| 80b70cdaf6 | |||
| 63ee16a9e7 | |||
| dd5739046e | |||
| c1714048b4 | |||
| 3fd770d84c |
@@ -7,6 +7,18 @@ and this project adheres to [Conventional Commits](https://www.conventionalcommi
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.2.0] - 2026-05-22
|
||||
|
||||
### Added
|
||||
|
||||
- `New-PveVm` disk controller / IO options: `-DiskBus` (virtio/scsi/sata/ide), `-ScsiHardware` (scsihw), `-DiskIoThread`, `-DiskAio`, `-DiskSsd`, `-DiskDiscard`, `-DiskCache`. Invalid combinations (e.g. `ssd` on virtio, `iothread` on sata/ide or scsi without `virtio-scsi-single`) are rejected up front with a clear error. (#65)
|
||||
- `Get-PveVmConfig` now surfaces `scsihw`, `efidisk0`, and `tpmstate0` as typed properties, plus an `AdditionalProperties` dictionary capturing any other config key (e.g. `hostpci0`) as native .NET values instead of silently dropping it. (#65)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Form values containing `;` were split into bogus fields by PVE's parser, so a multi-device boot order set via `Set-PveVmConfig -AdditionalConfig @{ boot = 'order=scsi0;ide2' }` failed with `unable to parse drive options`. Semicolons are now percent-encoded. (#64)
|
||||
- `Invoke-PveVmGuestExec -Args` were delivered to the guest as JSON on STDIN instead of as argv, so commands ran with no/garbage arguments. Arguments are now sent as the PVE `command` array (repeated keys), reaching the process as real argv. (#68)
|
||||
|
||||
## [0.1.3] - 2026-05-20
|
||||
|
||||
### Added
|
||||
|
||||
+126
-4
@@ -1,15 +1,15 @@
|
||||
{
|
||||
"_schema_version": "1.0",
|
||||
"_description": "PSProxmoxVE stable findings ledger. IDs are permanent (F001, F002...). Resolved findings are never deleted — they are marked resolved with evidence. If a finding reappears, it is marked regressed and retains its original ID.",
|
||||
"last_updated": "2026-03-26",
|
||||
"last_updated": "2026-05-22",
|
||||
"last_scan_date": "2026-03-26",
|
||||
"counters": {
|
||||
"next_id": 86,
|
||||
"next_id": 92,
|
||||
"total_open": 7,
|
||||
"total_resolved": 77,
|
||||
"total_resolved": 83,
|
||||
"total_regressed": 0,
|
||||
"open": 7,
|
||||
"resolved": 77,
|
||||
"resolved": 83,
|
||||
"regressed": 0,
|
||||
"wont_fix": 1
|
||||
},
|
||||
@@ -2881,6 +2881,128 @@
|
||||
"evidence": "Added PveSession.Timeout (default 100s) and a TimeSpan? override on PveHttpClient. Connect-PveServer exposes -TimeoutSeconds to set the session-default; Send-PveFile and Invoke-PveStorageDownload expose -TimeoutSeconds with a 30-minute implicit default so large uploads/downloads do not trip the 100s HttpClient default. -TimeoutSeconds 0 means Timeout.InfiniteTimeSpan. PveHttpClient.SendAsync now catches the TimeoutException-wrapped TaskCanceledException and rethrows it as PveApiException(RequestTimeout) with the resource path.",
|
||||
"verified_by": "dotnet build + dotnet test (passed including new SendAsync_TimeoutFires xUnit test) + Pester (-TimeoutSeconds coverage on all three cmdlets)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "F088",
|
||||
"title": "Form values containing ';' are split into bogus fields (boot order breaks Set-PveVmConfig)",
|
||||
"category": "api_contract",
|
||||
"severity": "high",
|
||||
"status": "resolved",
|
||||
"first_detected": "2026-05-22",
|
||||
"github_issue": 64,
|
||||
"files": [
|
||||
"src/PSProxmoxVE.Core/Client/PveHttpClient.cs"
|
||||
],
|
||||
"description": "PveHttpClient.EncodeFormValue percent-encoded &, =, +, space, and % but not ';'. PVE's application/x-www-form-urlencoded parser treats a raw ';' as a field separator, so a value like boot=order=scsi0;ide2 was split into 'boot=order=scsi0' plus an empty 'ide2' field, which PVE rejected with 'ide2: unable to parse drive options'. Affected any config value containing ';' (boot order, hookscript, some args).",
|
||||
"scan_history": [
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "new"
|
||||
},
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "fixed"
|
||||
}
|
||||
],
|
||||
"resolution": {
|
||||
"scan_date": "2026-05-22",
|
||||
"evidence": "Added ';' -> %3B to EncodeFormValue. Safe under the minimal-encoding policy (cluster-join values never contain ';' and PVE url-decodes config form values). Verified the colon/comma minimal-encoding behavior is preserved.",
|
||||
"verified_by": "dotnet build + dotnet test (3 new PveHttpClientFormEncodingTests: semicolon encoded on POST/PUT, comma/colon remain literal)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "F089",
|
||||
"title": "New-PveVm cannot set disk controller or IO options at create time",
|
||||
"category": "enhancement",
|
||||
"severity": "medium",
|
||||
"status": "resolved",
|
||||
"first_detected": "2026-05-22",
|
||||
"github_issue": 65,
|
||||
"files": [
|
||||
"src/PSProxmoxVE/Cmdlets/Vms/NewPveVmCmdlet.cs"
|
||||
],
|
||||
"description": "New-PveVm only emitted a plain virtio0 from -DiskStorage/-DiskSize/-DiskFormat. There was no way to choose the controller (virtio-scsi-single) or set performance/IO options (iothread, aio, ssd, discard, cache) at create time, forcing callers to create the VM diskless and then hand-build a raw scsi0 string via Set-PveVmConfig.",
|
||||
"scan_history": [
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "new"
|
||||
},
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "fixed"
|
||||
}
|
||||
],
|
||||
"resolution": {
|
||||
"scan_date": "2026-05-22",
|
||||
"evidence": "Added -DiskBus (virtio/scsi/sata/ide, default virtio), -ScsiHardware (scsihw), -DiskIoThread, -DiskAio, -DiskSsd, -DiskDiscard, -DiskCache. The disk spec is built via a BuildDiskSpec helper; ValidateDiskOptions enforces (before ShouldProcess) that ssd is not used on virtio and that iothread is only used on virtio or scsi+virtio-scsi-single, surfacing clear errors at create time instead of at VM start.",
|
||||
"verified_by": "dotnet build (0 warnings) + Pester (47 New-PveVm tests incl. disk-option validation matrix)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "F090",
|
||||
"title": "Get-PveVmConfig silently drops config keys not in the typed allow-list",
|
||||
"category": "completeness",
|
||||
"severity": "medium",
|
||||
"status": "resolved",
|
||||
"first_detected": "2026-05-22",
|
||||
"github_issue": 65,
|
||||
"files": [
|
||||
"src/PSProxmoxVE.Core/Models/Vms/PveVmConfig.cs"
|
||||
],
|
||||
"description": "PveVmConfig was a fixed allow-list of [JsonProperty] fields with no catch-all, so keys like scsihw, efidisk0, tpmstate0, hostpci0, and additional disk buses were silently dropped on deserialize — making the F089 workaround unverifiable by reading the config back.",
|
||||
"scan_history": [
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "new"
|
||||
},
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "fixed"
|
||||
}
|
||||
],
|
||||
"resolution": {
|
||||
"scan_date": "2026-05-22",
|
||||
"evidence": "Added typed scsihw/efidisk0/tpmstate0 properties plus a private [JsonExtensionData] landing field exposed as AdditionalProperties (Dictionary<string, object?> via JsonHelper.ToNative, so values are native .NET types per D013 — no JToken leakage). Typed keys do not duplicate into the catch-all.",
|
||||
"verified_by": "dotnet build + dotnet test (586 passed, new VmModelTests for scsihw/efidisk/tpm, native-typed AdditionalProperties, and no typed-key leakage)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "F091",
|
||||
"title": "Invoke-PveVmGuestExec -Args delivered as JSON STDIN instead of argv",
|
||||
"category": "api_contract",
|
||||
"severity": "high",
|
||||
"status": "resolved",
|
||||
"first_detected": "2026-05-22",
|
||||
"github_issue": 68,
|
||||
"files": [
|
||||
"src/PSProxmoxVE.Core/Services/VmService.cs",
|
||||
"src/PSProxmoxVE.Core/Client/PveHttpClient.cs",
|
||||
"src/PSProxmoxVE.Core/Client/IPveHttpClient.cs"
|
||||
],
|
||||
"description": "VmService.ExecuteGuestCommand JSON-serialized the args array into the agent/exec 'input-data' field (the process's STDIN) instead of passing them as argv. PVE's agent/exec 'command' parameter is itself an array (element 0 = executable, rest = arguments) and must be sent as repeated form keys. The result: guest commands ran with no/garbage arguments (cmd.exe started interactively, the JSON blob appeared at the prompt). The low-level client also could not express repeated form keys (Dictionary<string,string> only).",
|
||||
"scan_history": [
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "new"
|
||||
},
|
||||
{
|
||||
"scan_date": "2026-05-22",
|
||||
"local_id": null,
|
||||
"status": "fixed"
|
||||
}
|
||||
],
|
||||
"resolution": {
|
||||
"scan_date": "2026-05-22",
|
||||
"evidence": "Added PostAsync(string, IEnumerable<KeyValuePair<string,string>>) to IPveHttpClient/PveHttpClient (BuildFormContent now emits repeated keys). ExecuteGuestCommand builds command = [exe] + args as repeated 'command' fields and no longer touches input-data.",
|
||||
"verified_by": "dotnet build (0 warnings) + dotnet test (594 passed; new PveHttpClientFormEncodingTests for repeated keys + per-value encoding, and VmServiceTests asserting the command array and absence of input-data)"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -16,6 +16,13 @@ namespace PSProxmoxVE.Core.Client
|
||||
/// <summary>Performs a POST request against the specified API resource path.</summary>
|
||||
Task<string> PostAsync(string resource, Dictionary<string, string>? data = null);
|
||||
|
||||
/// <summary>
|
||||
/// Performs a POST request whose form body may contain repeated keys, used for
|
||||
/// PVE array parameters (e.g. guest-exec "command"). Each pair becomes one
|
||||
/// <c>key=value</c> field, so a key may appear multiple times.
|
||||
/// </summary>
|
||||
Task<string> PostAsync(string resource, IEnumerable<KeyValuePair<string, string>> data);
|
||||
|
||||
/// <summary>Performs a PUT request against the specified API resource path.</summary>
|
||||
Task<string> PutAsync(string resource, Dictionary<string, string>? data = null);
|
||||
|
||||
@@ -25,7 +32,7 @@ namespace PSProxmoxVE.Core.Client
|
||||
/// <summary>Synchronous wrapper for <see cref="GetAsync"/>.</summary>
|
||||
string Get(string resource);
|
||||
|
||||
/// <summary>Synchronous wrapper for <see cref="PostAsync"/>.</summary>
|
||||
/// <summary>Synchronous wrapper for <see cref="PostAsync(string, Dictionary{string, string})"/>.</summary>
|
||||
string Post(string resource, Dictionary<string, string>? data = null);
|
||||
|
||||
/// <summary>Synchronous wrapper for <see cref="PutAsync"/>.</summary>
|
||||
|
||||
@@ -111,6 +111,21 @@ namespace PSProxmoxVE.Core.Client
|
||||
return await SendAsync(request, resource, "POST").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// POST whose form body may contain repeated keys, for PVE array parameters
|
||||
/// (e.g. guest-exec "command"). Each pair becomes one key=value field.
|
||||
/// </summary>
|
||||
/// <param name="resource">Relative resource path</param>
|
||||
/// <param name="data">Form fields; a key may appear more than once</param>
|
||||
/// <returns>Raw JSON response body</returns>
|
||||
public async Task<string> PostAsync(string resource, IEnumerable<KeyValuePair<string, string>> data)
|
||||
{
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
var request = BuildRequest(HttpMethod.Post, resource, mutating: true);
|
||||
request.Content = BuildFormContent(data);
|
||||
return await SendAsync(request, resource, "POST").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Performs a PUT request against the specified API resource path.</summary>
|
||||
/// <param name="resource">Relative resource path</param>
|
||||
/// <param name="data">Form fields to send as application/x-www-form-urlencoded body</param>
|
||||
@@ -142,7 +157,7 @@ namespace PSProxmoxVE.Core.Client
|
||||
/// <c>:</c> and <c>!</c> which PVE's internal API consumers (e.g. cluster join)
|
||||
/// do not properly URL-decode.
|
||||
/// </summary>
|
||||
private static StringContent BuildFormContent(Dictionary<string, string> data)
|
||||
private static StringContent BuildFormContent(IEnumerable<KeyValuePair<string, string>> data)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (var kvp in data)
|
||||
@@ -169,6 +184,11 @@ namespace PSProxmoxVE.Core.Client
|
||||
{
|
||||
case '&': sb.Append("%26"); break;
|
||||
case '=': sb.Append("%3D"); break;
|
||||
// PVE's form parser treats a raw ';' as a field separator (the
|
||||
// historical alternative to '&'), so an unencoded ';' inside a value
|
||||
// (e.g. boot=order=scsi0;ide2) splits the value into bogus extra
|
||||
// fields. Encode it so the value arrives intact.
|
||||
case ';': sb.Append("%3B"); break;
|
||||
case '+': sb.Append("%2B"); break;
|
||||
case ' ': sb.Append('+'); break;
|
||||
case '%': sb.Append("%25"); break;
|
||||
@@ -186,7 +206,7 @@ namespace PSProxmoxVE.Core.Client
|
||||
public string Get(string resource) =>
|
||||
GetAsync(resource).GetAwaiter().GetResult();
|
||||
|
||||
/// <summary>Synchronous wrapper for <see cref="PostAsync"/>.</summary>
|
||||
/// <summary>Synchronous wrapper for <see cref="PostAsync(string, Dictionary{string, string})"/>.</summary>
|
||||
public string Post(string resource, Dictionary<string, string>? data = null) =>
|
||||
PostAsync(resource, data).GetAwaiter().GetResult();
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using PSProxmoxVE.Core.Utilities;
|
||||
|
||||
namespace PSProxmoxVE.Core.Models.Vms;
|
||||
|
||||
@@ -52,6 +56,24 @@ public class PveVmConfig
|
||||
[JsonProperty("machine")]
|
||||
public string? Machine { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// SCSI controller hardware model (e.g., "virtio-scsi-single", "lsi").
|
||||
/// </summary>
|
||||
[JsonProperty("scsihw")]
|
||||
public string? ScsiHardware { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// EFI vars disk spec (present on OVMF/UEFI VMs), e.g. "local-lvm:vm-100-disk-1,...".
|
||||
/// </summary>
|
||||
[JsonProperty("efidisk0")]
|
||||
public string? EfiDisk0 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// TPM state disk spec (present on VMs with a virtual TPM).
|
||||
/// </summary>
|
||||
[JsonProperty("tpmstate0")]
|
||||
public string? TpmState0 { get; set; }
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Boot / Args
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -288,6 +310,34 @@ public class PveVmConfig
|
||||
[JsonProperty("searchdomain")]
|
||||
public string? Searchdomain { get; set; }
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Catch-all for unmapped config keys
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Raw landing spot for any config key not mapped to a typed property above.
|
||||
/// Populated by Newtonsoft during deserialization; exposed natively via
|
||||
/// <see cref="AdditionalProperties"/>.
|
||||
/// </summary>
|
||||
[JsonExtensionData]
|
||||
private IDictionary<string, JToken>? ExtensionData { get; set; }
|
||||
|
||||
private Dictionary<string, object?>? _additionalProperties;
|
||||
|
||||
/// <summary>
|
||||
/// Any VM config keys not surfaced as a typed property above (e.g. hostpci0,
|
||||
/// usb0, numa0, additional disk buses). Keys map to native .NET values so the
|
||||
/// dictionary works naturally in PowerShell pipelines.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public Dictionary<string, object?> AdditionalProperties =>
|
||||
// Built once from the deserialized extension data (the model is effectively
|
||||
// immutable after deserialization), avoiding a fresh allocation per access
|
||||
// when iterating many configs in a pipeline.
|
||||
_additionalProperties ??= ExtensionData == null
|
||||
? new Dictionary<string, object?>()
|
||||
: ExtensionData.ToDictionary(kvp => kvp.Key, kvp => JsonHelper.ToNative(kvp.Value));
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString()
|
||||
{
|
||||
|
||||
@@ -599,16 +599,22 @@ namespace PSProxmoxVE.Core.Services
|
||||
IPveHttpClient client = _injectedClient ?? new PveHttpClient(session);
|
||||
try
|
||||
{
|
||||
var data = new Dictionary<string, string>
|
||||
// PVE's agent/exec "command" is an array: element 0 is the executable and
|
||||
// each subsequent element is one argv entry. It is sent as repeated form
|
||||
// keys (command=<exe>&command=<arg1>&...). Do NOT use "input-data" for
|
||||
// arguments — that is the process's STDIN, not argv.
|
||||
var data = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
["command"] = command
|
||||
new KeyValuePair<string, string>("command", command)
|
||||
};
|
||||
|
||||
if (args != null && args.Length > 0)
|
||||
if (args != null)
|
||||
{
|
||||
// PVE expects input-data for arguments passed as a JSON-encoded string array
|
||||
var argsJson = Newtonsoft.Json.JsonConvert.SerializeObject(args);
|
||||
data["input-data"] = argsJson;
|
||||
foreach (var arg in args)
|
||||
{
|
||||
if (arg == null)
|
||||
throw new ArgumentException("Args elements must not be null.", nameof(args));
|
||||
data.Add(new KeyValuePair<string, string>("command", arg));
|
||||
}
|
||||
}
|
||||
|
||||
var response = client.PostAsync($"nodes/{Uri.EscapeDataString(node)}/qemu/{vmid}/agent/exec", data)
|
||||
|
||||
@@ -96,6 +96,67 @@ namespace PSProxmoxVE.Cmdlets.Vms
|
||||
[Parameter(Mandatory = false, HelpMessage = "Disk format (e.g. raw, qcow2).")]
|
||||
public string? DiskFormat { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">
|
||||
/// Bus/controller for the primary disk: "virtio" (default), "scsi", "sata", or "ide".
|
||||
/// Determines the device key (virtio0, scsi0, sata0, ide0).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Primary disk bus: virtio (default), scsi, sata, ide.")]
|
||||
[ValidateSet("virtio", "scsi", "sata", "ide", IgnoreCase = true)]
|
||||
public string? DiskBus { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">
|
||||
/// SCSI controller hardware model (sets the VM-level "scsihw" key), e.g.
|
||||
/// "virtio-scsi-single", "virtio-scsi-pci", "lsi". Required as
|
||||
/// "virtio-scsi-single" when combining -DiskBus scsi with -DiskIoThread.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "SCSI controller model (e.g. virtio-scsi-single).")]
|
||||
public string? ScsiHardware { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">
|
||||
/// Enable a dedicated IO thread for the primary disk (iothread=1). Valid only for
|
||||
/// the virtio bus or for the scsi bus with -ScsiHardware virtio-scsi-single.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Enable a dedicated IO thread (iothread=1).")]
|
||||
public SwitchParameter DiskIoThread { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">Async IO mode for the primary disk: "native", "threads", or "io_uring".</para>
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Async IO mode: native, threads, io_uring.")]
|
||||
[ValidateSet("native", "threads", "io_uring", IgnoreCase = true)]
|
||||
public string? DiskAio { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">
|
||||
/// Mark the primary disk as SSD (ssd=1). Not supported on the virtio bus — use
|
||||
/// -DiskBus scsi, sata, or ide.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Mark the primary disk as SSD (ssd=1).")]
|
||||
public SwitchParameter DiskSsd { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">Enable discard/TRIM passthrough on the primary disk (discard=on).</para>
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Enable discard/TRIM passthrough (discard=on).")]
|
||||
public SwitchParameter DiskDiscard { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">
|
||||
/// Cache mode for the primary disk: "none", "writethrough", "writeback",
|
||||
/// "directsync", or "unsafe".
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[Parameter(Mandatory = false, HelpMessage = "Disk cache mode: none, writethrough, writeback, directsync, unsafe.")]
|
||||
[ValidateSet("none", "writethrough", "writeback", "directsync", "unsafe", IgnoreCase = true)]
|
||||
public string? DiskCache { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <para type="description">Network interface model (e.g., "virtio", "e1000").</para>
|
||||
/// </summary>
|
||||
@@ -128,13 +189,16 @@ namespace PSProxmoxVE.Cmdlets.Vms
|
||||
|
||||
protected override void ProcessRecord()
|
||||
{
|
||||
// Validate -DiskSize before ShouldProcess so typos like "512M" are rejected
|
||||
// even with -WhatIf, and so the error is raised regardless of whether
|
||||
// -DiskStorage is also supplied.
|
||||
// Validate -DiskSize and disk-option combinations before ShouldProcess so
|
||||
// typos and invalid combos are rejected even with -WhatIf, and so the error
|
||||
// is raised regardless of whether -DiskStorage is also supplied.
|
||||
string? diskSizeGib = null;
|
||||
if (!string.IsNullOrEmpty(DiskSize))
|
||||
diskSizeGib = SizeParser.NormalizeToGibibytes(DiskSize!, nameof(DiskSize));
|
||||
|
||||
var diskBus = string.IsNullOrEmpty(DiskBus) ? "virtio" : DiskBus!.ToLowerInvariant();
|
||||
ValidateDiskOptions(diskBus);
|
||||
|
||||
if (!ShouldProcess($"VM on node '{Node}'", "New-PveVm"))
|
||||
return;
|
||||
|
||||
@@ -172,14 +236,16 @@ namespace PSProxmoxVE.Cmdlets.Vms
|
||||
config["machine"] = Machine!;
|
||||
if (!string.IsNullOrEmpty(OsType))
|
||||
config["ostype"] = OsType!;
|
||||
if (!string.IsNullOrEmpty(ScsiHardware))
|
||||
config["scsihw"] = ScsiHardware!;
|
||||
|
||||
if (!string.IsNullOrEmpty(DiskStorage) && diskSizeGib != null)
|
||||
{
|
||||
var diskValue = $"{DiskStorage}:{diskSizeGib}";
|
||||
if (!string.IsNullOrEmpty(DiskFormat))
|
||||
diskValue += $",format={DiskFormat}";
|
||||
config["virtio0"] = diskValue;
|
||||
}
|
||||
config[$"{diskBus}0"] = BuildDiskSpec(DiskStorage!, diskSizeGib);
|
||||
else if (HasDiskOptions())
|
||||
WriteWarning("Disk options were specified but no disk is being created "
|
||||
+ "(-DiskStorage and -DiskSize are both required). The per-disk options "
|
||||
+ "(-DiskBus/-DiskIoThread/-DiskAio/-DiskSsd/-DiskDiscard/-DiskCache) were ignored; "
|
||||
+ "-ScsiHardware, if specified, is still applied as the VM-level scsihw setting.");
|
||||
|
||||
if (!string.IsNullOrEmpty(Bridge))
|
||||
{
|
||||
@@ -200,5 +266,62 @@ namespace PSProxmoxVE.Cmdlets.Vms
|
||||
|
||||
WriteObject(task);
|
||||
}
|
||||
|
||||
private bool HasDiskOptions() =>
|
||||
!string.IsNullOrEmpty(DiskBus)
|
||||
|| !string.IsNullOrEmpty(ScsiHardware)
|
||||
|| DiskIoThread.IsPresent
|
||||
|| !string.IsNullOrEmpty(DiskAio)
|
||||
|| DiskSsd.IsPresent
|
||||
|| DiskDiscard.IsPresent
|
||||
|| !string.IsNullOrEmpty(DiskCache);
|
||||
|
||||
/// <summary>
|
||||
/// Validates disk option combinations that PVE would otherwise reject at VM start
|
||||
/// rather than at create time, surfacing a clear error up front.
|
||||
/// </summary>
|
||||
private void ValidateDiskOptions(string diskBus)
|
||||
{
|
||||
if (DiskSsd.IsPresent && diskBus == "virtio")
|
||||
throw new PSArgumentException(
|
||||
"-DiskSsd is not supported on the virtio bus. Use -DiskBus scsi, sata, or ide.",
|
||||
nameof(DiskSsd));
|
||||
|
||||
if (DiskIoThread.IsPresent)
|
||||
{
|
||||
if (diskBus == "sata" || diskBus == "ide")
|
||||
throw new PSArgumentException(
|
||||
"-DiskIoThread requires -DiskBus virtio or scsi.",
|
||||
nameof(DiskIoThread));
|
||||
|
||||
if (diskBus == "scsi"
|
||||
&& !string.Equals(ScsiHardware, "virtio-scsi-single", System.StringComparison.OrdinalIgnoreCase))
|
||||
throw new PSArgumentException(
|
||||
"-DiskIoThread on a scsi disk requires -ScsiHardware virtio-scsi-single.",
|
||||
nameof(DiskIoThread));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the disk volume spec ("<storage>:<sizeGiB>[,opt=val...]") for the
|
||||
/// primary disk, appending format and any requested IO options in a stable order.
|
||||
/// </summary>
|
||||
private string BuildDiskSpec(string storage, string sizeGib)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder($"{storage}:{sizeGib}");
|
||||
if (!string.IsNullOrEmpty(DiskFormat))
|
||||
sb.Append($",format={DiskFormat}");
|
||||
if (!string.IsNullOrEmpty(DiskCache))
|
||||
sb.Append($",cache={DiskCache!.ToLowerInvariant()}");
|
||||
if (!string.IsNullOrEmpty(DiskAio))
|
||||
sb.Append($",aio={DiskAio!.ToLowerInvariant()}");
|
||||
if (DiskSsd.IsPresent)
|
||||
sb.Append(",ssd=1");
|
||||
if (DiskDiscard.IsPresent)
|
||||
sb.Append(",discard=on");
|
||||
if (DiskIoThread.IsPresent)
|
||||
sb.Append(",iothread=1");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
RootModule = 'PSProxmoxVE.dll'
|
||||
|
||||
# Version number of this module.
|
||||
ModuleVersion = '0.1.3'
|
||||
ModuleVersion = '0.2.0'
|
||||
|
||||
# Supported PSEditions
|
||||
CompatiblePSEditions = @('Desktop', 'Core')
|
||||
@@ -372,17 +372,20 @@
|
||||
|
||||
# Release notes for this version
|
||||
ReleaseNotes = @'
|
||||
## 0.1.3
|
||||
## 0.2.0
|
||||
|
||||
Added:
|
||||
- New-PveVm disk controller / IO options: -DiskBus (virtio/scsi/sata/ide),
|
||||
-ScsiHardware, -DiskIoThread, -DiskAio, -DiskSsd, -DiskDiscard, -DiskCache,
|
||||
with up-front validation of invalid combinations (#65).
|
||||
- Get-PveVmConfig now surfaces scsihw/efidisk0/tpmstate0 plus an
|
||||
AdditionalProperties dictionary for any other config key (#65).
|
||||
|
||||
Fixed:
|
||||
- New-PveVm -DiskSize / New-PveContainer -RootFsSize normalize unit suffixes
|
||||
(32G, 1T, etc.) to bare GiB before sending to PVE so the documented call
|
||||
shape works on LVM/LVM-thin storages (#58).
|
||||
- HttpClient timeouts are now configurable via -TimeoutSeconds on
|
||||
Connect-PveServer (session default), Send-PveFile, and
|
||||
Invoke-PveStorageDownload (per-call, 30-minute implicit default).
|
||||
Timeouts surface as PveApiException(RequestTimeout) instead of a raw
|
||||
TaskCanceledException (#59).
|
||||
- Form values containing ';' were split into bogus fields, breaking a
|
||||
multi-device boot order via Set-PveVmConfig; semicolons are now encoded (#64).
|
||||
- Invoke-PveVmGuestExec -Args reached the guest as JSON on STDIN instead of
|
||||
argv; arguments are now sent as the PVE command array (#68).
|
||||
|
||||
Full changelog: https://github.com/goodolclint/PSProxmoxVE/blob/main/CHANGELOG.md
|
||||
'@
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using PSProxmoxVE.Core.Authentication;
|
||||
using PSProxmoxVE.Core.Client;
|
||||
using Xunit;
|
||||
|
||||
namespace PSProxmoxVE.Core.Tests.Client
|
||||
{
|
||||
public class PveHttpClientFormEncodingTests
|
||||
{
|
||||
private static void SetInnerHttpClient(PveHttpClient client, HttpClient newInner)
|
||||
{
|
||||
var field = typeof(PveHttpClient).GetField("_httpClient",
|
||||
BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
((HttpClient)field.GetValue(client)!).Dispose();
|
||||
field.SetValue(client, newInner);
|
||||
}
|
||||
|
||||
private static PveSession NewSession()
|
||||
{
|
||||
return new PveSession("pve.example.com", 8006, false,
|
||||
"root@pam!token=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
|
||||
}
|
||||
|
||||
private static (PveHttpClient client, CapturingHandler handler) NewCapturingClient()
|
||||
{
|
||||
var client = new PveHttpClient(NewSession());
|
||||
var handler = new CapturingHandler();
|
||||
SetInnerHttpClient(client, new HttpClient(handler));
|
||||
return (client, handler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAsync_SemicolonInValue_IsPercentEncoded()
|
||||
{
|
||||
var (client, handler) = NewCapturingClient();
|
||||
using (client)
|
||||
{
|
||||
await client.PostAsync("nodes/pve/qemu/100/config",
|
||||
new Dictionary<string, string> { ["boot"] = "order=scsi0;ide2" });
|
||||
}
|
||||
|
||||
// PVE treats a raw ';' as a form-field separator, so it must be encoded.
|
||||
Assert.Contains("boot=order%3Dscsi0%3Bide2", handler.LastBody);
|
||||
Assert.DoesNotContain(";", handler.LastBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PutAsync_SemicolonInValue_IsPercentEncoded()
|
||||
{
|
||||
var (client, handler) = NewCapturingClient();
|
||||
using (client)
|
||||
{
|
||||
await client.PutAsync("nodes/pve/qemu/100/config",
|
||||
new Dictionary<string, string> { ["boot"] = "order=ide2;virtio0;net0" });
|
||||
}
|
||||
|
||||
Assert.Contains("boot=order%3Dide2%3Bvirtio0%3Bnet0", handler.LastBody);
|
||||
Assert.DoesNotContain(";", handler.LastBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAsync_CommaAndColonInValue_RemainLiteral()
|
||||
{
|
||||
var (client, handler) = NewCapturingClient();
|
||||
using (client)
|
||||
{
|
||||
// Drive options use literal commas; cluster-join values use literal colons.
|
||||
// Minimal-encoding policy must keep both unescaped.
|
||||
await client.PostAsync("nodes/pve/qemu/100/config",
|
||||
new Dictionary<string, string> { ["ide2"] = "nas:iso/win.iso,media=cdrom" });
|
||||
}
|
||||
|
||||
Assert.Contains("ide2=nas:iso/win.iso,media%3Dcdrom", handler.LastBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAsync_RepeatedKeys_EmitOneFieldPerValue()
|
||||
{
|
||||
var (client, handler) = NewCapturingClient();
|
||||
using (client)
|
||||
{
|
||||
// PVE array params (e.g. guest-exec command) are sent as repeated keys.
|
||||
var data = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new KeyValuePair<string, string>("command", "cmd.exe"),
|
||||
new KeyValuePair<string, string>("command", "/c"),
|
||||
new KeyValuePair<string, string>("command", "echo"),
|
||||
new KeyValuePair<string, string>("command", "WLMARK42"),
|
||||
};
|
||||
await client.PostAsync("nodes/pve/qemu/100/agent/exec", data);
|
||||
}
|
||||
|
||||
Assert.Equal("command=cmd.exe&command=/c&command=echo&command=WLMARK42", handler.LastBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAsync_RepeatedKeys_EncodeEachValueIndependently()
|
||||
{
|
||||
var (client, handler) = NewCapturingClient();
|
||||
using (client)
|
||||
{
|
||||
var data = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new KeyValuePair<string, string>("command", "powershell.exe"),
|
||||
new KeyValuePair<string, string>("command", "-Command"),
|
||||
new KeyValuePair<string, string>("command", "echo a=b;c"),
|
||||
};
|
||||
await client.PostAsync("nodes/pve/qemu/100/agent/exec", data);
|
||||
}
|
||||
|
||||
// The '=' and ';' inside an arg must be encoded so they don't split the body,
|
||||
// while spaces follow the form convention ('+').
|
||||
Assert.Equal("command=powershell.exe&command=-Command&command=echo+a%3Db%3Bc", handler.LastBody);
|
||||
}
|
||||
|
||||
private sealed class CapturingHandler : HttpMessageHandler
|
||||
{
|
||||
public string LastBody { get; private set; } = string.Empty;
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
LastBody = request.Content == null
|
||||
? string.Empty
|
||||
: await request.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("{\"data\":null}")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,5 +173,57 @@ namespace PSProxmoxVE.Core.Tests.Models
|
||||
Assert.Equal("8.8.8.8", config.Nameserver);
|
||||
Assert.Equal("example.com", config.Searchdomain);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PveVmConfig_Deserialize_SurfacesScsiHardware()
|
||||
{
|
||||
var json = TestHelper.LoadFixture("pve9_vm_config.json");
|
||||
var data = JObject.Parse(json)["data"];
|
||||
Assert.NotNull(data);
|
||||
var config = data.ToObject<PveVmConfig>();
|
||||
Assert.NotNull(config);
|
||||
Assert.Equal("virtio-scsi-single", config.ScsiHardware);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PveVmConfig_Deserialize_SurfacesEfiDiskAndTpm()
|
||||
{
|
||||
var json = @"{ ""efidisk0"": ""local-lvm:vm-100-disk-1,efitype=4m,size=528K"",
|
||||
""tpmstate0"": ""local-lvm:vm-100-disk-2,size=4M,version=v2.0"" }";
|
||||
var config = JObject.Parse(json).ToObject<PveVmConfig>();
|
||||
Assert.NotNull(config);
|
||||
Assert.Contains("efitype=4m", config!.EfiDisk0);
|
||||
Assert.Contains("version=v2.0", config.TpmState0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PveVmConfig_UnmappedKeys_LandInAdditionalProperties_AsNativeTypes()
|
||||
{
|
||||
// hostpci0 and numa0 are not typed properties; they must not be dropped.
|
||||
var json = @"{ ""cores"": 2,
|
||||
""hostpci0"": ""0000:01:00.0,pcie=1"",
|
||||
""numa0"": ""cpus=0-1,memory=2048"" }";
|
||||
var config = JObject.Parse(json).ToObject<PveVmConfig>();
|
||||
Assert.NotNull(config);
|
||||
|
||||
Assert.Equal(2, config!.Cores); // typed property still works
|
||||
Assert.True(config.AdditionalProperties.ContainsKey("hostpci0"));
|
||||
Assert.Equal("0000:01:00.0,pcie=1", config.AdditionalProperties["hostpci0"]);
|
||||
// Value must be a native type (string), never a Newtonsoft JToken (D013).
|
||||
Assert.IsType<string>(config.AdditionalProperties["hostpci0"]);
|
||||
Assert.DoesNotContain("Newtonsoft", config.AdditionalProperties["hostpci0"]!.GetType().FullName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PveVmConfig_TypedKeys_DoNotLeakIntoAdditionalProperties()
|
||||
{
|
||||
var json = TestHelper.LoadFixture("pve9_vm_config.json");
|
||||
var data = JObject.Parse(json)["data"];
|
||||
var config = data!.ToObject<PveVmConfig>();
|
||||
Assert.NotNull(config);
|
||||
// scsihw and cores are typed → they must not also appear in the catch-all.
|
||||
Assert.False(config!.AdditionalProperties.ContainsKey("scsihw"));
|
||||
Assert.False(config.AdditionalProperties.ContainsKey("cores"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Moq;
|
||||
using PSProxmoxVE.Core.Authentication;
|
||||
using PSProxmoxVE.Core.Client;
|
||||
using PSProxmoxVE.Core.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace PSProxmoxVE.Core.Tests.Services
|
||||
{
|
||||
public class VmServiceTests
|
||||
{
|
||||
private const string TestNode = "pve1";
|
||||
private const int TestVmId = 100;
|
||||
|
||||
private static PveSession CreateSession() =>
|
||||
new PveSession("pve1.example.com", 8006, true, "PVE:root@pam:TEST_TOKEN");
|
||||
|
||||
[Fact]
|
||||
public void ExecuteGuestCommand_SendsCommandAndArgsAsRepeatedCommandArray()
|
||||
{
|
||||
List<KeyValuePair<string, string>>? captured = null;
|
||||
var mockClient = new Mock<IPveHttpClient>();
|
||||
mockClient
|
||||
.Setup(c => c.PostAsync(It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
|
||||
.Callback<string, IEnumerable<KeyValuePair<string, string>>>((_, data) => captured = data.ToList())
|
||||
.ReturnsAsync("{\"data\":{\"pid\":4242}}");
|
||||
|
||||
var service = new VmService(mockClient.Object);
|
||||
var pid = service.ExecuteGuestCommand(CreateSession(), TestNode, TestVmId,
|
||||
"cmd.exe", new[] { "/c", "echo", "WLMARK42" });
|
||||
|
||||
Assert.Equal(4242, pid);
|
||||
Assert.NotNull(captured);
|
||||
|
||||
// Every element (exe + each arg) is its own "command" entry, in order.
|
||||
Assert.All(captured!, kvp => Assert.Equal("command", kvp.Key));
|
||||
Assert.Equal(
|
||||
new[] { "cmd.exe", "/c", "echo", "WLMARK42" },
|
||||
captured!.Select(kvp => kvp.Value).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteGuestCommand_DoesNotUseInputDataForArgs()
|
||||
{
|
||||
List<KeyValuePair<string, string>>? captured = null;
|
||||
var mockClient = new Mock<IPveHttpClient>();
|
||||
mockClient
|
||||
.Setup(c => c.PostAsync(It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
|
||||
.Callback<string, IEnumerable<KeyValuePair<string, string>>>((_, data) => captured = data.ToList())
|
||||
.ReturnsAsync("{\"data\":{\"pid\":1}}");
|
||||
|
||||
var service = new VmService(mockClient.Object);
|
||||
service.ExecuteGuestCommand(CreateSession(), TestNode, TestVmId,
|
||||
"powershell.exe", new[] { "-NoProfile", "-Command", "echo hi" });
|
||||
|
||||
Assert.NotNull(captured);
|
||||
// Args are argv, not STDIN — "input-data" must never be emitted.
|
||||
Assert.DoesNotContain(captured!, kvp => kvp.Key == "input-data");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteGuestCommand_NoArgs_SendsSingleCommandEntry()
|
||||
{
|
||||
List<KeyValuePair<string, string>>? captured = null;
|
||||
var mockClient = new Mock<IPveHttpClient>();
|
||||
mockClient
|
||||
.Setup(c => c.PostAsync(It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
|
||||
.Callback<string, IEnumerable<KeyValuePair<string, string>>>((_, data) => captured = data.ToList())
|
||||
.ReturnsAsync("{\"data\":{\"pid\":7}}");
|
||||
|
||||
var service = new VmService(mockClient.Object);
|
||||
service.ExecuteGuestCommand(CreateSession(), TestNode, TestVmId, "whoami", null);
|
||||
|
||||
Assert.NotNull(captured);
|
||||
var only = Assert.Single(captured!);
|
||||
Assert.Equal("command", only.Key);
|
||||
Assert.Equal("whoami", only.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteGuestCommand_EmptyArgs_SendsSingleCommandEntry()
|
||||
{
|
||||
List<KeyValuePair<string, string>>? captured = null;
|
||||
var mockClient = new Mock<IPveHttpClient>();
|
||||
mockClient
|
||||
.Setup(c => c.PostAsync(It.IsAny<string>(), It.IsAny<IEnumerable<KeyValuePair<string, string>>>()))
|
||||
.Callback<string, IEnumerable<KeyValuePair<string, string>>>((_, data) => captured = data.ToList())
|
||||
.ReturnsAsync("{\"data\":{\"pid\":9}}");
|
||||
|
||||
var service = new VmService(mockClient.Object);
|
||||
service.ExecuteGuestCommand(CreateSession(), TestNode, TestVmId, "whoami", new string[0]);
|
||||
|
||||
Assert.NotNull(captured);
|
||||
var only = Assert.Single(captured!);
|
||||
Assert.Equal("command", only.Key);
|
||||
Assert.Equal("whoami", only.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteGuestCommand_NullArgElement_ThrowsArgumentException()
|
||||
{
|
||||
var mockClient = new Mock<IPveHttpClient>();
|
||||
var service = new VmService(mockClient.Object);
|
||||
|
||||
var ex = Assert.Throws<ArgumentException>(() =>
|
||||
service.ExecuteGuestCommand(CreateSession(), TestNode, TestVmId,
|
||||
"cmd.exe", new[] { "/c", null!, "echo" }));
|
||||
Assert.Equal("args", ex.ParamName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,18 @@ Describe 'Linux VM — Integration' -Tag 'Integration' {
|
||||
$result.ExitCode | Should -Be 0
|
||||
$result.Stdout | Should -Not -BeNullOrEmpty
|
||||
}
|
||||
|
||||
It 'Should pass -Args to the guest as argv (Invoke-PveVmGuestExec)' {
|
||||
if (Skip-IfNoLinuxVm) { return }
|
||||
|
||||
# Regression guard for #68: args must reach the process as argv, not STDIN.
|
||||
# With the old bug, echo got no arguments and stdout was empty.
|
||||
$marker = 'PSPROXMOXVE_ARG_TEST'
|
||||
$result = Invoke-PveVmGuestExec -Node $script:Node -VmId $script:LinuxVmId `
|
||||
-Command 'echo' -Args @($marker)
|
||||
$result.ExitCode | Should -Be 0
|
||||
$result.Stdout.Trim() | Should -Be $marker
|
||||
}
|
||||
}
|
||||
|
||||
Context 'Guest Agent VM — Lifecycle' {
|
||||
|
||||
@@ -168,4 +168,80 @@ Describe 'New-PveVm' {
|
||||
Should -Not -Throw
|
||||
}
|
||||
}
|
||||
|
||||
Context 'Disk controller / IO parameter metadata' {
|
||||
BeforeAll { $script:Cmd = Get-Command 'New-PveVm' }
|
||||
|
||||
It 'Should have <_> parameter' -ForEach @(
|
||||
'DiskBus', 'ScsiHardware', 'DiskIoThread', 'DiskAio', 'DiskSsd', 'DiskDiscard', 'DiskCache'
|
||||
) {
|
||||
$script:Cmd.Parameters.ContainsKey($_) | Should -BeTrue
|
||||
}
|
||||
|
||||
It 'DiskBus should have a ValidateSet of virtio, scsi, sata, ide' {
|
||||
$vs = $script:Cmd.Parameters['DiskBus'].Attributes |
|
||||
Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } |
|
||||
Select-Object -First 1
|
||||
$vs.ValidValues | Should -Contain 'virtio'
|
||||
$vs.ValidValues | Should -Contain 'scsi'
|
||||
$vs.ValidValues | Should -Contain 'sata'
|
||||
$vs.ValidValues | Should -Contain 'ide'
|
||||
}
|
||||
|
||||
It 'DiskIoThread and DiskSsd should be switch parameters' {
|
||||
$script:Cmd.Parameters['DiskIoThread'].ParameterType | Should -Be ([System.Management.Automation.SwitchParameter])
|
||||
$script:Cmd.Parameters['DiskSsd'].ParameterType | Should -Be ([System.Management.Automation.SwitchParameter])
|
||||
}
|
||||
}
|
||||
|
||||
Context 'Disk option validation' {
|
||||
# Validation runs before ShouldProcess, so -WhatIf exercises it offline.
|
||||
|
||||
It 'Should reject -DiskSsd on the virtio bus' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskSsd -WhatIf -ErrorAction Stop } |
|
||||
Should -Throw '*virtio bus*'
|
||||
}
|
||||
|
||||
It 'Should reject -DiskSsd on the default (virtio) bus when bus omitted' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskSsd -WhatIf -ErrorAction Stop } |
|
||||
Should -Throw '*virtio bus*'
|
||||
}
|
||||
|
||||
It 'Should accept -DiskSsd on the scsi bus' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskBus scsi -DiskSsd -WhatIf -ErrorAction Stop } |
|
||||
Should -Not -Throw
|
||||
}
|
||||
|
||||
It 'Should reject -DiskIoThread on the sata bus' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskBus sata -DiskIoThread -WhatIf -ErrorAction Stop } |
|
||||
Should -Throw '*requires -DiskBus virtio or scsi*'
|
||||
}
|
||||
|
||||
It 'Should reject -DiskIoThread on scsi without -ScsiHardware virtio-scsi-single' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskBus scsi -DiskIoThread -WhatIf -ErrorAction Stop } |
|
||||
Should -Throw '*virtio-scsi-single*'
|
||||
}
|
||||
|
||||
It 'Should reject -DiskIoThread on scsi with a wrong -ScsiHardware (virtio-scsi-pci)' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskBus scsi -ScsiHardware 'virtio-scsi-pci' -DiskIoThread -WhatIf -ErrorAction Stop } |
|
||||
Should -Throw '*virtio-scsi-single*'
|
||||
}
|
||||
|
||||
It 'Should accept -DiskIoThread on scsi with -ScsiHardware virtio-scsi-single' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskBus scsi -ScsiHardware 'virtio-scsi-single' -DiskIoThread -WhatIf -ErrorAction Stop } |
|
||||
Should -Not -Throw
|
||||
}
|
||||
|
||||
It 'Should accept -DiskIoThread on the default virtio bus' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -DiskIoThread -WhatIf -ErrorAction Stop } |
|
||||
Should -Not -Throw
|
||||
}
|
||||
|
||||
It 'Should accept a fully tuned scsi disk spec' {
|
||||
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '60' -DiskBus scsi `
|
||||
-ScsiHardware 'virtio-scsi-single' -DiskIoThread -DiskAio native -DiskSsd -DiskDiscard `
|
||||
-DiskCache none -WhatIf -ErrorAction Stop } |
|
||||
Should -Not -Throw
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user