42 Commits

Author SHA1 Message Date
GoodOlClint 3a50dd2fb7 Merge pull request #70 from GoodOlClint/chore/release-0.2.0
chore: release 0.2.0
2026-05-22 15:50:49 -05:00
Clint Branham ee69c699b1 chore: release 0.2.0
Minor bump: this release adds features (New-PveVm disk controller/IO
options and Get-PveVmConfig key surfacing, #65) alongside two bug fixes
(#64 semicolon form-encoding, #68 guest-exec argv).

Updates the three release artifacts in lockstep: psd1 ModuleVersion,
psd1 ReleaseNotes, and CHANGELOG ([0.2.0] cut from [Unreleased]).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 15:47:36 -05:00
GoodOlClint 5cb5c90db8 Merge pull request #69 from GoodOlClint/fix/guest-exec-args
fix: deliver Invoke-PveVmGuestExec -Args as argv (#68)
2026-05-22 14:41:45 -05:00
Clint Branham 56dcf22cea fix: address PR #69 review feedback
- VmService.ExecuteGuestCommand: guard against null elements in -Args.
  The old JSON-serialization tolerated nulls (as "null"); the repeated-key
  path would NRE in EncodeFormValue. Throw a clear ArgumentException instead.
- findings.json: refresh the stale counters block (untouched since F085) to
  the actual ledger state — next_id 92, resolved 83 — and bump last_updated
  to 2026-05-22. last_scan_date stays 2026-03-26 (F086–F091 came from issue
  triage, not a formal review scan).
- VmServiceTests: add empty-array (single command entry) and null-element
  (throws) cases.

Note: F091 is the correct next ID — F086–F090 already exist from prior
merged PRs (#60/#61/#66/#67); only the counters were lagging.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:38:54 -05:00
Clint Branham bc71ed4a12 fix: deliver Invoke-PveVmGuestExec -Args to the guest as argv
ExecuteGuestCommand JSON-serialized the args array into the agent/exec
'input-data' field — which is the process's STDIN, not its arguments. So
guest commands ran with no argv: cmd.exe started interactively and the
JSON blob ['/c','echo',...] arrived at its prompt.

PVE's agent/exec 'command' parameter is itself an array (element 0 = the
executable, the rest = argv) sent as repeated form keys. The low-level
client couldn't express repeated keys (Dictionary<string,string> only),
so:

- Add PostAsync(string, IEnumerable<KeyValuePair<string,string>>) to
  IPveHttpClient/PveHttpClient; BuildFormContent now emits one key=value
  field per pair, so a key may repeat.
- ExecuteGuestCommand builds command = [exe] + args as repeated 'command'
  fields and no longer touches input-data.

Tests: form-encoder repeated-key + per-value encoding cases; VmService
tests asserting the command array, order, and absence of input-data; an
integration regression guard that echoes an arg and checks it round-trips
as stdout.

Tracked as F091. Closes #68.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:32:04 -05:00
GoodOlClint 5266accfae Merge pull request #67 from GoodOlClint/feat/new-pvevm-disk-options
feat: New-PveVm disk controller/IO options + surface all Get-PveVmConfig keys (#65)
2026-05-22 14:27:30 -05:00
Clint Branham e959fbb9b8 fix: correct New-PveVm disk-options warning text
Now that -ScsiHardware is part of HasDiskOptions(), the old "options were
ignored" wording was misleading: scsihw is written unconditionally as a
VM-level key and is never ignored. Reword to state that the per-disk
options are the ones dropped, and that -ScsiHardware (if specified) is
still applied. Accurate whether or not -ScsiHardware was passed.

Addresses PR #67 follow-up review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:25:21 -05:00
Clint Branham 80b70cdaf6 fix: address PR #67 review feedback
- HasDiskOptions(): include -ScsiHardware so the "disk options ignored"
  warning fires when -ScsiHardware is passed without -DiskStorage/-DiskSize.
- PveVmConfig.AdditionalProperties: lazy-init a backing field so the native
  dictionary is built once rather than reallocated on every property access
  (matters when iterating many configs in a pipeline). Safe because the model
  is effectively immutable after deserialization.
- New-PveVm.Tests.ps1: add a case asserting -DiskIoThread on scsi with a
  wrong -ScsiHardware (virtio-scsi-pci) is rejected, covering the validator's
  "!= virtio-scsi-single" branch (not just the null case).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:18:32 -05:00
Clint Branham 63ee16a9e7 Merge remote-tracking branch 'origin/main' into feat/new-pvevm-disk-options
# Conflicts:
#	docs/review/findings.json
2026-05-22 14:15:20 -05:00
GoodOlClint dd5739046e Merge pull request #66 from GoodOlClint/fix/form-encode-semicolon
fix: percent-encode ';' in form values (#64)
2026-05-22 14:13:03 -05:00
Clint Branham c1714048b4 feat: disk controller/IO options on New-PveVm + surface all Get-PveVmConfig keys
New-PveVm (F089):
- Add -DiskBus (virtio/scsi/sata/ide, default virtio), -ScsiHardware (scsihw),
  -DiskIoThread, -DiskAio, -DiskSsd, -DiskDiscard, -DiskCache so a tuned disk
  (e.g. virtio-scsi-single + scsi0,iothread=1,aio=native,ssd=1,discard=on) can
  be created in one call instead of diskless + a hand-built Set-PveVmConfig string.
- Disk spec built via BuildDiskSpec; ValidateDiskOptions runs before ShouldProcess
  and rejects ssd on virtio and iothread on sata/ide or scsi-without-virtio-scsi-single
  with clear errors, instead of letting PVE fail at VM start.

Get-PveVmConfig (F090):
- PveVmConfig was a fixed allow-list, silently dropping keys like scsihw, efidisk0,
  tpmstate0, hostpci0. Add typed scsihw/efidisk0/tpmstate0 plus a [JsonExtensionData]
  catch-all exposed as AdditionalProperties (native types via JsonHelper.ToNative,
  per D013 — no JToken leakage). Makes the disk tuning above verifiable by reading
  the config back.

Closes #65.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:10:14 -05:00
Clint Branham 3fd770d84c fix: percent-encode ';' in form values
PveHttpClient.EncodeFormValue encoded &, =, +, space, and % but left ';'
literal. PVE's application/x-www-form-urlencoded parser treats a raw ';'
as a field separator (the historical alternative to '&'), so a value like

    boot=order=scsi0;ide2

was split into 'boot=order=scsi0' plus an empty 'ide2' field, and PVE
rejected the PUT with "ide2: unable to parse drive options". This broke
any multi-device boot order set via Set-PveVmConfig -AdditionalConfig,
and any other value containing ';'.

Encode ';' as %3B. Safe under the existing minimal-encoding policy that
keeps ':' and '!' literal for cluster-join: cluster-join payloads never
contain ';', and PVE url-decodes config form values.

Tracked as F088. Closes #64.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 14:04:31 -05:00
GoodOlClint 5e5a8fcda4 Merge pull request #63 from GoodOlClint/docs/changelog-and-releasenotes-catchup
docs: cut CHANGELOG into versioned entries, refresh ReleaseNotes
2026-05-20 19:27:05 -05:00
Clint Branham 79c97ec211 docs: cut CHANGELOG into versioned entries, refresh ReleaseNotes
Doc hygiene catch-up surfaced by the PR #62 review:

- CHANGELOG.md: the [Unreleased] section had accumulated all post-preview
  work without ever being cut into release entries. Promote it into:
    - [0.1.3] - new fixes from #58 (DiskSize normalization) and #59
      (HttpClient -TimeoutSeconds + RequestTimeout surfacing)
    - [0.1.2] - #43/#44/#45 fixes from PR #46
    - [0.1.1] - the cmdlet expansion + OpenAPI validation that
      actually shipped to PSGallery as 0.1.1
  Reset [Unreleased] to empty.

- src/PSProxmoxVE/PSProxmoxVE.psd1: replace the stale "Initial preview
  release" ReleaseNotes (carried over since 0.1.0-preview) with actual
  0.1.3 notes. PSGallery shows this on the version page.

- CLAUDE.md: document the release process so future bumps update the
  psd1 version, psd1 ReleaseNotes, and CHANGELOG together before the
  tag is cut. Prevents this hygiene gap from recurring.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 19:23:29 -05:00
GoodOlClint 098ea7e8d4 Merge pull request #62 from GoodOlClint/chore/bump-version-0.1.3
chore: bump version to 0.1.3
2026-05-20 19:19:01 -05:00
Clint Branham ff728fc6d6 chore: bump version to 0.1.3
Releases #58 (LVM disk-size unit normalization) and #59 (HttpClient
timeout / -TimeoutSeconds) fixes to PSGallery.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 19:14:54 -05:00
GoodOlClint 02254ed13b Merge pull request #61 from GoodOlClint/fix/http-client-timeout
fix: add -TimeoutSeconds for long-running HTTP calls (#59)
2026-05-20 18:26:08 -05:00
Clint Branham cb97a86c9f fix: drop net48-incompatible TimeoutException filter in timeout catch
The when filter (ex.InnerException is TimeoutException) only matches on
.NET 5+. On .NET Framework 4.8 — which CI exercises via the test project's
net48 target — HttpClient.Timeout throws a bare TaskCanceledException
with no inner exception, so CI failed:

  Expected: typeof(PSProxmoxVE.Core.Exceptions.PveApiException)
  Actual:   typeof(System.Threading.Tasks.TaskCanceledException)
  ---- System.Threading.Tasks.TaskCanceledException : A task was canceled.

PveHttpClient.SendAsync never passes a CancellationToken to the inner
HttpClient.SendAsync, so the only way a TaskCanceledException can reach
this catch is HttpClient.Timeout firing — true on net48, .NET Core, and
.NET 5+. Drop the filter and wrap unconditionally.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:22:47 -05:00
Clint Branham a1d9550d83 fix: surface HttpClient timeouts as PveApiException(RequestTimeout)
When HttpClient.Timeout elapses, .NET throws TaskCanceledException — not
HttpRequestException — so the existing catch in PveHttpClient.SendAsync
missed it and callers got a raw stack trace. With -TimeoutSeconds now
configurable and documented, this gap became user-visible.

In .NET 5+ HttpClient surfaces transport timeouts as TaskCanceledException
with a TimeoutException inner; user-driven token cancellation does not.
Catch by that inner-type signature and rethrow as PveApiException with
HttpStatusCode.RequestTimeout, the resource path, and a message that
reports the configured timeout.

Adds SendAsync_TimeoutFires_ThrowsPveApiExceptionWithRequestTimeout which
swaps in a delaying HttpMessageHandler with a 50ms timeout to exercise
the path deterministically. Drops the redundant
DefaultSessionTimeoutIs100Seconds test (covered by
PveSessionTests.Timeout_DefaultIs100Seconds and the existing flow-through
test).

Addresses PR #61 review feedback.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:17:31 -05:00
Clint Branham ea2bcdc336 Merge main into fix/http-client-timeout
Resolves findings.json conflict — F086 (from #60, merged into main) and
F087 (this branch) both append to the trailing findings array. Kept both
entries, in numeric order.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:17:20 -05:00
GoodOlClint 239a6b8fe9 Merge pull request #60 from GoodOlClint/fix/disk-size-unit-normalization
fix: normalize -DiskSize/-RootFsSize before sending to PVE (#58)
2026-05-20 18:10:36 -05:00
Clint Branham f3b06171b2 fix: add -TimeoutSeconds for long-running HTTP calls
PveHttpClient was constructed without setting HttpClient.Timeout, so
.NET's 100s default applied to every request. Multi-GB ISO uploads via
Send-PveFile on a real LAN reliably tripped this with TaskCanceledException
after 100 seconds, and there was no way to override it.

- PveSession gains a Timeout (TimeSpan) property, defaulting to 100s.
- PveHttpClient accepts an optional per-instance timeout override that
  takes precedence over the session timeout.
- 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 default. -TimeoutSeconds 0 means Timeout.InfiniteTimeSpan.

Tracked as F087. Closes #59.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:08:26 -05:00
Clint Branham fa361a3691 fix: address PR #60 review feedback
- SizeParser: wrap TB-suffix overflow in try/catch so callers get
  ArgumentException with the parameter name rather than OverflowException.
- New-PveVm/New-PveContainer: validate -DiskSize/-RootFsSize before
  ShouldProcess so typos like "512M" are rejected even with -WhatIf and
  even when the matching -DiskStorage/-RootFsStorage is omitted.
- Add Pester tests for the new DiskSize and RootFsSize validation paths,
  including a new New-PveContainer.Tests.ps1.
- Add SizeParserTests coverage for the TB overflow path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 18:06:13 -05:00
Clint Branham 6181c8ce77 fix: normalize -DiskSize and -RootFsSize before sending to PVE
Disk and rootfs size strings were interpolated directly into the disk
spec as "<storage>:<size>", so "60G" produced "local-lvm:60G". On
LVM/LVM-thin storages PVE parses the value after the colon as a volume
name unless it is a bare integer, returning "unable to parse lvm volume
name '60G'". File-backed storages mask this by accepting either form.

SizeParser.NormalizeToGibibytes() now strips G/GB/T/TB suffixes and
returns a bare GiB integer string, so the documented "32G" call shape
works on every storage type. Sub-GB units are rejected with a clear
error rather than being silently truncated.

Tracked as F086. Closes #58.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:59:21 -05:00
GoodOlClint f2925ba49f Merge pull request #57 from GoodOlClint/dependabot/nuget/src/PSProxmoxVE.Core/main/SharpCompress-0.48.1
Bump SharpCompress from 0.47.4 to 0.48.1
2026-05-19 14:20:37 -05:00
dependabot[bot] 9a9830f2e1 Bump SharpCompress from 0.47.4 to 0.48.1
---
updated-dependencies:
- dependency-name: SharpCompress
  dependency-version: 0.48.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-19 15:08:29 +00:00
GoodOlClint 4b0ddf566a Merge pull request #56 from GoodOlClint/dependabot/nuget/tests/PSProxmoxVE.Core.Tests/main/coverlet.collector-10.0.1
Bump coverlet.collector from 8.0.1 to 10.0.1
2026-05-19 10:02:10 -05:00
dependabot[bot] e1bb0d0268 Bump coverlet.collector from 8.0.1 to 10.0.1
---
updated-dependencies:
- dependency-name: coverlet.collector
  dependency-version: 10.0.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-19 14:52:38 +00:00
GoodOlClint 46c4ee3713 Merge pull request #54 from GoodOlClint/dependabot/nuget/tests/PSProxmoxVE.Core.Tests/main/Microsoft.NET.Test.Sdk-18.5.1
Bump Microsoft.NET.Test.Sdk from 18.4.0 to 18.5.1
2026-05-19 09:49:47 -05:00
dependabot[bot] 7219133050 Bump Microsoft.NET.Test.Sdk from 18.4.0 to 18.5.1
---
updated-dependencies:
- dependency-name: Microsoft.NET.Test.Sdk
  dependency-version: 18.5.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-04 16:02:50 +00:00
GoodOlClint af4ef8402d Merge pull request #50 from GoodOlClint/dependabot/nuget/tests/PSProxmoxVE.Core.Tests/main/Microsoft.NET.Test.Sdk-18.4.0
Bump Microsoft.NET.Test.Sdk from 18.3.0 to 18.4.0
2026-04-13 09:21:58 -05:00
GoodOlClint 9bf7b2d922 Merge branch 'main' into dependabot/nuget/tests/PSProxmoxVE.Core.Tests/main/Microsoft.NET.Test.Sdk-18.4.0 2026-04-13 09:20:01 -05:00
GoodOlClint a77d2b2062 Merge pull request #48 from GoodOlClint/dependabot/nuget/src/PSProxmoxVE.Core/main/SharpCompress-0.47.4
Bump SharpCompress from 0.47.3 to 0.47.4
2026-04-13 09:19:27 -05:00
GoodOlClint 7dc39646ae Merge branch 'main' into dependabot/nuget/src/PSProxmoxVE.Core/main/SharpCompress-0.47.4 2026-04-13 09:17:59 -05:00
GoodOlClint 6664861ca9 Merge pull request #49 from GoodOlClint/dependabot/github_actions/main/softprops/action-gh-release-3
chore(deps): Bump softprops/action-gh-release from 2 to 3
2026-04-13 09:15:00 -05:00
dependabot[bot] 97ff7701da Bump SharpCompress from 0.47.3 to 0.47.4
---
updated-dependencies:
- dependency-name: SharpCompress
  dependency-version: 0.47.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-13 14:14:39 +00:00
dependabot[bot] 23ffc3531f chore(deps): Bump softprops/action-gh-release from 2 to 3
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 2 to 3.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v2...v3)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-version: '3'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-13 14:12:00 +00:00
GoodOlClint 2a809b0374 Merge pull request #52 from GoodOlClint/fix/claude-review-post-comments
fix: post Claude Code Review findings as PR comments
2026-04-13 09:10:59 -05:00
Clint Branham 6e2f25a083 fix: rewrite Claude Code Review workflow to match official examples
Previous approach (/code-review:code-review --comment) was based on
incorrect documentation research. Reviewing the actual official
examples at anthropics/claude-code-action/examples/pr-review-*.yml
reveals the correct pattern:

1. Use a custom prompt with explicit review instructions (not a
   plugin slash command)
2. Use claude_args with --allowedTools to enable the MCP inline
   comment tool and gh pr CLI commands — this is what lets Claude
   actually post to the PR
3. Enable track_progress: true for visual progress tracking

Without --allowedTools, Claude has no way to post anything because
the tools for PR commenting aren't allowed by default.

Also removed the plugins and plugin_marketplaces inputs since
they're not needed — the review runs via prompt instructions and
the allowed tools alone.

The custom prompt is tailored to PSProxmoxVE with focus areas
specific to the module: DECISIONS.md compliance, cmdlet
conventions, API correctness against the PVE OpenAPI spec,
test coverage, and security.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 09:09:54 -05:00
dependabot[bot] aca5ff238b Bump Microsoft.NET.Test.Sdk from 18.3.0 to 18.4.0
---
updated-dependencies:
- dependency-name: Microsoft.NET.Test.Sdk
  dependency-version: 18.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-13 13:56:51 +00:00
GoodOlClint ac901dbc1b Merge pull request #51 from GoodOlClint/fix/claude-review-allow-dependabot
fix: allow dependabot PRs in Claude Code Review
2026-04-13 08:53:38 -05:00
Clint Branham 2aa2d5994e fix: allow dependabot PRs in Claude Code Review action
Dependabot PRs were being rejected with:
  Workflow initiated by non-human actor: dependabot (type: Bot)

Add allowed_bots: 'dependabot[bot]' to permit dependency update reviews.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 08:52:36 -05:00
32 changed files with 1502 additions and 63 deletions
+29 -3
View File
@@ -25,6 +25,32 @@ jobs:
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
plugin_marketplaces: 'https://github.com/anthropics/claude-code.git'
plugins: 'code-review@claude-code-plugins'
prompt: '/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}'
allowed_bots: 'dependabot[bot]'
track_progress: true
prompt: |
REPO: ${{ github.repository }}
PR NUMBER: ${{ github.event.pull_request.number }}
Review this pull request for the PSProxmoxVE PowerShell module.
Focus areas:
1. **DECISIONS.md compliance** — Check against the 13 architectural
decisions (D001-D013). Any violation is a regression.
2. **Code quality** — Cmdlet conventions (sealed, OutputType,
ConfirmImpact.High for destructive, VmId ValidateRange),
SecureString for passwords, Uri.EscapeDataString on path params,
no bare catch blocks, Newtonsoft-only JSON.
3. **API correctness** — Parameter names and enum values must match
the PVE OpenAPI spec (see tests/PSProxmoxVE.Core.Tests/Fixtures/
pve-api-enums.pve*.json for valid values per PVE version).
4. **Tests** — New cmdlets should have xUnit service tests and
Pester parameter-validation tests.
5. **Security** — No hardcoded credentials, no secrets in logs,
TLS verification on by default.
Provide inline comments for specific issues and a summary comment
for general observations. Skip nitpicks unless they indicate a
real problem.
claude_args: |
--allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*)"
+1 -1
View File
@@ -108,6 +108,6 @@ jobs:
Publish-Module -Path ./publish/PSProxmoxVE -NuGetApiKey $env:NUGET_API_KEY -Verbose
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
generate_release_notes: true
+57 -18
View File
@@ -7,28 +7,64 @@ 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
- `Connect-PveServer -TimeoutSeconds` to set the session-default `HttpClient` timeout (default 100s; `0` = infinite). (#59)
- `Send-PveFile -TimeoutSeconds` and `Invoke-PveStorageDownload -TimeoutSeconds` for per-call override with a 30-minute implicit default so large uploads/downloads no longer trip the 100s default. (#59)
### Fixed
- `New-PveVm -DiskSize` and `New-PveContainer -RootFsSize` now normalize unit suffixes (`32G`, `1T`, `32GB`, etc.) to bare GiB before constructing the disk spec. Previously the suffix was passed verbatim, which LVM/LVM-thin storages rejected with `unable to parse lvm volume name '32G'`. Sub-GB units (`M`, `MB`, `K`, `KB`) are now rejected client-side with a clear error. (#58)
- `PveHttpClient.SendAsync` surfaces `HttpClient.Timeout` firings as `PveApiException(RequestTimeout)` with the resource path and configured timeout, instead of leaking a raw `TaskCanceledException`. Works across `net48`, `net10.0`, and `netstandard2.0`. (#59)
- Disk-size validation runs before `ShouldProcess` so typos like `512M` are caught with `-WhatIf`, regardless of whether `-DiskStorage`/`-RootFsStorage` is also supplied. (#58)
## [0.1.2] - 2026-03-27
### Fixed
- `Get-PveApiToken`: `FullTokenId` is now computed from `UserId!TokenId` (was always empty). (#44)
- `Set-PvePermission`: added `token` ACL type with auto-detection from `!` in `-UgId`, enabling permission assignment for API tokens. (#43)
- `Connect-PveServer`: always emits the session to the pipeline. Use `-Quiet` to suppress; `-PassThru` is kept hidden for backwards compatibility. (#45)
## [0.1.1] - 2026-03-26
### Added
- Firewall management cmdlets (21): rules, security groups, aliases, IP sets, options at cluster/node/VM/container levels
- Backup/vzdump cmdlets (5): ad-hoc backup creation and scheduled backup job CRUD
- SDN IPAM cmdlets (3): Get/New/Remove-PveSdnIpam for IPAM plugin management
- SDN DNS cmdlets (3): Get/New/Remove-PveSdnDns for DNS plugin management
- SDN Controller cmdlets (3): Get/New/Remove-PveSdnController for controller management
- PSGallery version badge in README
- Integration tests for firewall rules, aliases, IP sets, backup jobs, and OVA import
- SDN Update cmdlets (7): Set-PveSdnZone/Vnet/Subnet/Controller/Ipam/Dns + Invoke-PveSdnApply
- Set-PveRole, Set-PveStorage, Set-PveApiToken for missing update operations
- Get-PveClusterResource: single-call cluster-wide inventory of all VMs, containers, nodes, storage
- Task management: Get-PveTaskList (list tasks on node), Stop-PveTask (cancel running tasks)
- Pool management cmdlets (4): Get/New/Set/Remove-PvePool
- Get-PveBackupInfo: find VMs/containers not covered by backup jobs
- VM disk operations: Move-PveVmDisk (storage migration), Remove-PveVmDisk (detach/delete)
- Guest agent extensions (6): Get-PveVmGuestOsInfo, Get-PveVmGuestFsInfo, Read/Write-PveVmGuestFile, Set-PveVmGuestPassword, Invoke-PveVmGuestFsTrim
- Container gaps (6): Suspend/Resume-PveContainer, Resize-PveContainerDisk, New-PveContainerTemplate, Move-PveContainerVolume, Get-PveContainerInterface
- Storage content management (4): Get-PveStorageStatus, Remove/Set-PveStorageContent, New-PveStorageDisk
- Node operations (6): Get/Set-PveNodeConfig, Get/Set-PveNodeDns, Start/Stop-PveNodeVms
- Access management (9): Get/New/Set/Remove-PveGroup, Get/New/Set/Remove-PveDomain, Set-PvePassword
- SDN IPAM cmdlets (3): `Get`/`New`/`Remove-PveSdnIpam` for IPAM plugin management
- SDN DNS cmdlets (3): `Get`/`New`/`Remove-PveSdnDns` for DNS plugin management
- SDN Controller cmdlets (3): `Get`/`New`/`Remove-PveSdnController` for controller management
- SDN Update cmdlets (7): `Set-PveSdnZone`/`Vnet`/`Subnet`/`Controller`/`Ipam`/`Dns` + `Invoke-PveSdnApply`
- `Set-PveRole`, `Set-PveStorage`, `Set-PveApiToken` for missing update operations
- `Get-PveClusterResource`: single-call cluster-wide inventory of all VMs, containers, nodes, storage
- Task management: `Get-PveTaskList` (list tasks on node), `Stop-PveTask` (cancel running tasks)
- Pool management cmdlets (4): `Get`/`New`/`Set`/`Remove-PvePool`
- `Get-PveBackupInfo`: find VMs/containers not covered by backup jobs
- VM disk operations: `Move-PveVmDisk` (storage migration), `Remove-PveVmDisk` (detach/delete)
- Guest agent extensions (6): `Get-PveVmGuestOsInfo`, `Get-PveVmGuestFsInfo`, `Read`/`Write-PveVmGuestFile`, `Set-PveVmGuestPassword`, `Invoke-PveVmGuestFsTrim`
- Container gaps (6): `Suspend`/`Resume-PveContainer`, `Resize-PveContainerDisk`, `New-PveContainerTemplate`, `Move-PveContainerVolume`, `Get-PveContainerInterface`
- Storage content management (4): `Get-PveStorageStatus`, `Remove`/`Set-PveStorageContent`, `New-PveStorageDisk`
- Node operations (6): `Get`/`Set-PveNodeConfig`, `Get`/`Set-PveNodeDns`, `Start`/`Stop-PveNodeVms`
- Access management (9): `Get`/`New`/`Set`/`Remove-PveGroup`, `Get`/`New`/`Set`/`Remove-PveDomain`, `Set-PvePassword`
- Two-tier version gating: introduced vs default version with clear user messaging
- 70 xUnit tests validating every `ValidateSet` against the PVE OpenAPI spec, with `pve-api-enums.json` fixture extracted from the full spec
- Integration tests for firewall rules, aliases, IP sets, backup jobs, and OVA import
- PSGallery version badge in README
### Changed
@@ -41,7 +77,7 @@ and this project adheres to [Conventional Commits](https://www.conventionalcommi
- `ValidateRange(100, 999999999)` added to all `VmId` parameters
- `Uri.EscapeDataString()` applied to all dynamic URL path segments
- Hardcoded verb strings replaced with verb class constants (`VerbsCommon.Get`, etc.)
- Auth header magic strings extracted to named constants in PveHttpClient
- Auth header magic strings extracted to named constants in `PveHttpClient`
- Bare `catch` blocks replaced with specific or filtered exception handling
- MAML help (dll-Help.xml) and 170 markdown cmdlet docs generated
- PSGallery publish workflow with PS 5.1 smoke testing
@@ -49,6 +85,9 @@ and this project adheres to [Conventional Commits](https://www.conventionalcommi
### Fixed
- `ConfirmImpact.High` added to all destructive cmdlets (Stop, Reset, Restart, Suspend, Remove, Restore, New-PveTemplate)
- Storage `ValidateSet`: removed `glusterfs` (dropped in PVE 9), added `btrfs` and `esxi`
- Backup compression: `none``0` (PVE expects the string `"0"`, not `"none"`)
- Cluster resource filter: removed `lxc` (PVE uses `vm` for both QEMU and LXC)
- Hardcoded test password moved from CI workflow to GitHub Actions secret
- Terraform variable default password removed (requires env var)
+18
View File
@@ -93,3 +93,21 @@ This repo uses a structured review system to track findings and prevent regressi
Finding IDs (F001, F002...) are permanent. A resolved finding is never deleted from
findings.json — it is marked `resolved` with evidence of the fix. If a finding reappears,
it is marked `regressed` and retains its original ID.
## Releasing to PSGallery
Tag-driven: pushing a `v*` tag to `main` triggers `.github/workflows/publish.yml` (build →
PS 5.1 smoke test → publish to PSGallery → create GitHub Release with auto-generated notes).
Each release PR must update **three** things in lockstep before the tag is cut:
1. `ModuleVersion` in `src/PSProxmoxVE/PSProxmoxVE.psd1` (semver patch for bug-fix-only;
minor for new features; major for breaking changes).
2. `ReleaseNotes` in the same psd1 — this is what PSGallery surfaces on the version page.
Replace the previous version's notes; do not append.
3. `CHANGELOG.md` — cut the `[Unreleased]` section into a new `[X.Y.Z] - YYYY-MM-DD`
block and reset `[Unreleased]` to empty.
After merge, tag `main` with `vX.Y.Z` and push the tag. The publish workflow rewrites
the psd1 `ModuleVersion` in the build artifact from the tag, so the tag and the source
version must match.
+192 -4
View File
@@ -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
},
@@ -2815,6 +2815,194 @@
"evidence": "Replaced JArray? Nodelist with List<Dictionary<string, object?>>? + NativeListConverter, and JObject? Totem with Dictionary<string, object?>? + NativeDictionaryConverter. Removed Newtonsoft.Json.Linq dependency.",
"verified_by": "dotnet build + dotnet test (382 passed)"
}
},
{
"id": "F086",
"title": "New-PveVm -DiskSize and New-PveContainer -RootFsSize pass unit suffix verbatim, LVM rejects 'NG'",
"category": "api_contract",
"severity": "high",
"status": "resolved",
"first_detected": "2026-05-20",
"github_issue": 58,
"files": [
"src/PSProxmoxVE/Cmdlets/Vms/NewPveVmCmdlet.cs",
"src/PSProxmoxVE/Cmdlets/Containers/NewPveContainerCmdlet.cs"
],
"description": "Disk and rootfs sizes are interpolated directly into the disk spec as '<storage>:<size>'. The parameter docstring advertises 'e.g. 32G' but on LVM/LVM-thin storages PVE parses the value after the colon as a volume name unless it is a bare integer, failing with 'unable to parse lvm volume name \"32G\"'. File-backed storages (NFS, directory) accept either form, masking the bug in mixed environments.",
"scan_history": [
{
"scan_date": "2026-05-20",
"local_id": null,
"status": "new"
},
{
"scan_date": "2026-05-20",
"local_id": null,
"status": "fixed"
}
],
"resolution": {
"scan_date": "2026-05-20",
"evidence": "Added SizeParser.NormalizeToGibibytes() which strips G/GB/T/TB suffixes, rejects sub-GB units with a clear error, and converts TB overflows to ArgumentException. New-PveVm and New-PveContainer normalize -DiskSize and -RootFsSize before ShouldProcess so typos are caught with -WhatIf, regardless of whether the matching -DiskStorage/-RootFsStorage was supplied.",
"verified_by": "dotnet build + dotnet test (577 passed, 32 SizeParserTests) + Pester (39 passed, new DiskSize/RootFsSize validation contexts)"
}
},
{
"id": "F087",
"title": "HttpClient uses 100s default timeout; Send-PveFile and other long-running calls fail on large payloads",
"category": "reliability",
"severity": "high",
"status": "resolved",
"first_detected": "2026-05-20",
"github_issue": 59,
"files": [
"src/PSProxmoxVE.Core/Client/PveHttpClient.cs",
"src/PSProxmoxVE.Core/Authentication/PveSession.cs",
"src/PSProxmoxVE.Core/Authentication/PveAuthenticator.cs",
"src/PSProxmoxVE/Cmdlets/Storage/SendPveFileCmdlet.cs",
"src/PSProxmoxVE/Cmdlets/Storage/InvokePveStorageDownloadCmdlet.cs",
"src/PSProxmoxVE/Cmdlets/Connection/ConnectPveServerCmdlet.cs"
],
"description": "PveHttpClient constructs HttpClient without setting Timeout, so .NET's 100s default applies to every request. Send-PveFile, Invoke-PveStorageDownload, and Connect-PveServer expose no way to override it, so multi-GB ISO uploads on a real LAN reliably trip the 100s timeout with TaskCanceledException. PveHttpClient.SendAsync also failed to surface the timeout as a PveApiException, leaking the raw TaskCanceledException to callers.",
"scan_history": [
{
"scan_date": "2026-05-20",
"local_id": null,
"status": "new"
},
{
"scan_date": "2026-05-20",
"local_id": null,
"status": "fixed"
}
],
"resolution": {
"scan_date": "2026-05-20",
"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)"
}
}
]
}
@@ -18,12 +18,22 @@ namespace PSProxmoxVE.Core.Authentication
/// Authenticates using username and password, obtaining a ticket and CSRF token.
/// The username must be in the form user@realm (e.g. root@pam).
/// </summary>
/// <param name="hostname">Hostname or IP address of the Proxmox VE server.</param>
/// <param name="port">TCP port of the Proxmox VE API.</param>
/// <param name="skipCertificateCheck">When true, skips TLS certificate validation.</param>
/// <param name="username">Username including realm (e.g. root@pam).</param>
/// <param name="password">Plain-text password for the user.</param>
/// <param name="timeout">
/// Optional HTTP timeout to apply both to the authentication call and to subsequent
/// requests made with this session. When null, the default 100s applies.
/// </param>
public static PveSession AuthenticateWithCredentials(
string hostname,
int port,
bool skipCertificateCheck,
string username,
string password)
string password,
TimeSpan? timeout = null)
{
if (string.IsNullOrWhiteSpace(hostname))
throw new ArgumentException("Hostname cannot be null or empty.", nameof(hostname));
@@ -41,7 +51,7 @@ namespace PSProxmoxVE.Core.Authentication
};
string responseBody;
using (var httpClient = new PveHttpClient(hostname, port, skipCertificateCheck))
using (var httpClient = new PveHttpClient(hostname, port, skipCertificateCheck, timeout))
{
responseBody = httpClient.Post("/api2/json/access/ticket", formData);
}
@@ -57,6 +67,8 @@ namespace PSProxmoxVE.Core.Authentication
var ticketExpiry = DateTime.UtcNow.AddHours(2);
var session = new PveSession(hostname, port, skipCertificateCheck, ticket, csrfToken, ticketExpiry);
if (timeout.HasValue)
session.Timeout = timeout.Value;
session.ServerVersion = GetVersion(session);
@@ -67,11 +79,20 @@ namespace PSProxmoxVE.Core.Authentication
/// Authenticates using a Proxmox VE API token.
/// The token must be in the format USER@REALM!TOKENID=UUID (e.g. root@pam!mytoken=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
/// </summary>
/// <param name="hostname">Hostname or IP address of the Proxmox VE server.</param>
/// <param name="port">TCP port of the Proxmox VE API.</param>
/// <param name="skipCertificateCheck">When true, skips TLS certificate validation.</param>
/// <param name="apiToken">API token in USER@REALM!TOKENID=UUID format.</param>
/// <param name="timeout">
/// Optional HTTP timeout to apply to requests made with this session.
/// When null, the default 100s applies.
/// </param>
public static PveSession AuthenticateWithApiToken(
string hostname,
int port,
bool skipCertificateCheck,
string apiToken)
string apiToken,
TimeSpan? timeout = null)
{
if (string.IsNullOrWhiteSpace(hostname))
throw new ArgumentException("Hostname cannot be null or empty.", nameof(hostname));
@@ -83,6 +104,8 @@ namespace PSProxmoxVE.Core.Authentication
nameof(apiToken));
var session = new PveSession(hostname, port, skipCertificateCheck, apiToken);
if (timeout.HasValue)
session.Timeout = timeout.Value;
session.ServerVersion = GetVersion(session);
@@ -33,6 +33,13 @@ namespace PSProxmoxVE.Core.Authentication
/// <summary>The Proxmox VE version detected on the server at connection time.</summary>
public PveVersion? ServerVersion { get; internal set; }
/// <summary>
/// The default HTTP request timeout applied to clients created with this session.
/// Defaults to 100 seconds (HttpClient's built-in default). Cmdlets that perform
/// long-running operations (e.g. Send-PveFile) may override this per-call.
/// </summary>
public TimeSpan Timeout { get; internal set; } = TimeSpan.FromSeconds(100);
/// <summary>Returns true if the ticket has expired (only relevant for Ticket auth mode)</summary>
public bool IsExpired
{
@@ -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>
+44 -4
View File
@@ -37,7 +37,12 @@ namespace PSProxmoxVE.Core.Client
/// Creates an HTTP client authenticated with the specified PVE session.
/// </summary>
/// <param name="session">The authenticated PVE session providing credentials and base URL.</param>
public PveHttpClient(PveSession session)
/// <param name="timeoutOverride">
/// Optional per-instance timeout override. When supplied, takes precedence over
/// <see cref="PveSession.Timeout"/>. Pass <see cref="System.Threading.Timeout.InfiniteTimeSpan"/>
/// to disable the timeout entirely (useful for multi-GB uploads/downloads).
/// </param>
public PveHttpClient(PveSession session, TimeSpan? timeoutOverride = null)
{
_session = session ?? throw new ArgumentNullException(nameof(session));
_baseUrl = session.BaseUrl;
@@ -49,6 +54,7 @@ namespace PSProxmoxVE.Core.Client
(HttpRequestMessage _, X509Certificate2 _, X509Chain _, SslPolicyErrors _) => true;
}
_httpClient = new HttpClient(handler);
_httpClient.Timeout = timeoutOverride ?? session.Timeout;
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
@@ -58,7 +64,7 @@ namespace PSProxmoxVE.Core.Client
/// Creates a bare HTTP client for pre-session use (e.g. initial authentication).
/// No auth headers are added to requests made with this constructor.
/// </summary>
internal PveHttpClient(string hostname, int port, bool skipCertificateCheck)
internal PveHttpClient(string hostname, int port, bool skipCertificateCheck, TimeSpan? timeout = null)
{
if (string.IsNullOrWhiteSpace(hostname))
throw new ArgumentException("Hostname cannot be null or empty.", nameof(hostname));
@@ -73,6 +79,8 @@ namespace PSProxmoxVE.Core.Client
(HttpRequestMessage _, X509Certificate2 _, X509Chain _, SslPolicyErrors _) => true;
}
_httpClient = new HttpClient(handler);
if (timeout.HasValue)
_httpClient.Timeout = timeout.Value;
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
@@ -103,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>
@@ -134,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)
@@ -161,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;
@@ -178,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();
@@ -345,6 +373,18 @@ namespace PSProxmoxVE.Core.Client
{
response = await _httpClient.SendAsync(request).ConfigureAwait(false);
}
catch (TaskCanceledException ex)
{
// PveHttpClient.SendAsync passes no CancellationToken to HttpClient.SendAsync,
// so a TaskCanceledException reaching here can only be HttpClient.Timeout
// firing — on .NET Framework, on .NET Core, and on .NET 5+ (where it also
// carries a TimeoutException inner). Wrap it uniformly across frameworks.
var seconds = _httpClient.Timeout == System.Threading.Timeout.InfiniteTimeSpan
? "infinite"
: _httpClient.Timeout.TotalSeconds.ToString("0", System.Globalization.CultureInfo.InvariantCulture) + "s";
throw new PveApiException(HttpStatusCode.RequestTimeout,
$"Request timed out after {seconds}.", resource, httpMethod, ex);
}
catch (HttpRequestException ex)
{
throw new PveApiException(HttpStatusCode.ServiceUnavailable,
@@ -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()
{
+1 -1
View File
@@ -18,7 +18,7 @@
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="SharpCompress" Version="0.47.3" />
<PackageReference Include="SharpCompress" Version="0.48.1" />
</ItemGroup>
</Project>
+13 -7
View File
@@ -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)
@@ -0,0 +1,79 @@
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace PSProxmoxVE.Core.Utilities
{
/// <summary>
/// Parses storage size strings (e.g. "32G", "1T", "60") and normalizes them
/// to a bare integer count of gibibytes for use in PVE disk specs.
/// </summary>
/// <remarks>
/// PVE accepts a size suffix on file-backed storages (NFS, directory) but parses
/// the value after the colon as a volume name on LVM-backed storages — so
/// <c>local-lvm:32G</c> fails with "unable to parse lvm volume name '32G'" while
/// <c>local-lvm:32</c> works on every storage type. Cmdlets that build disk specs
/// must normalize size inputs through this helper before joining with the storage.
/// </remarks>
public static class SizeParser
{
private static readonly Regex Pattern = new Regex(
@"^\s*(?<num>\d+)\s*(?<unit>[A-Za-z]*)\s*$",
RegexOptions.Compiled);
/// <summary>
/// Parses a size string and returns the value as a bare integer count of GiB.
/// Accepts values like "60", "60G", "60GB" (= 60), "1T", "1TB" (= 1024).
/// Sub-GB units are rejected because PVE disk allocation is GB-granular.
/// </summary>
/// <param name="value">The size string supplied by the user.</param>
/// <param name="parameterName">Parameter name used in the error message.</param>
/// <returns>The size in whole GiB as a string, suitable for direct use in disk specs.</returns>
/// <exception cref="ArgumentException">The input cannot be parsed or uses an unsupported unit.</exception>
public static string NormalizeToGibibytes(string value, string parameterName = "size")
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"{parameterName} must not be null or empty.", parameterName);
var match = Pattern.Match(value);
if (!match.Success)
throw new ArgumentException(
$"{parameterName} '{value}' is not a valid size. Expected a positive integer optionally suffixed with G, GB, T, or TB (e.g. '32G', '1T', '60').",
parameterName);
if (!long.TryParse(match.Groups["num"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num) || num <= 0)
throw new ArgumentException(
$"{parameterName} '{value}' must be a positive integer.",
parameterName);
var unit = match.Groups["unit"].Value.ToUpperInvariant();
long gib;
switch (unit)
{
case "":
case "G":
case "GB":
case "GIB":
gib = num;
break;
case "T":
case "TB":
case "TIB":
try { gib = checked(num * 1024L); }
catch (OverflowException)
{
throw new ArgumentException(
$"{parameterName} '{value}' is too large to represent in GiB.",
parameterName);
}
break;
default:
throw new ArgumentException(
$"{parameterName} '{value}' uses unsupported unit '{unit}'. Use G, GB, T, or TB. Sub-GB units (M, MB, K, KB) are not supported by PVE disk allocation.",
parameterName);
}
return gib.ToString(CultureInfo.InvariantCulture);
}
}
}
@@ -48,6 +48,17 @@ namespace PSProxmoxVE.Cmdlets.Connection
[Parameter(Mandatory = false, HelpMessage = "Skip TLS certificate validation.")]
public SwitchParameter SkipCertificateCheck { get; set; }
/// <summary>
/// HTTP request timeout in seconds for all calls made with this session.
/// Defaults to 100 seconds (HttpClient's built-in default). Pass 0 to disable
/// the timeout entirely. Cmdlets that perform long-running operations
/// (Send-PveFile, Invoke-PveStorageDownload) accept their own -TimeoutSeconds
/// that overrides this value per-call.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "HTTP timeout in seconds (0 = infinite). Default 100s.")]
[ValidateRange(0, int.MaxValue)]
public int? TimeoutSeconds { get; set; }
/// <summary>Deprecated — session is now always output. Kept for backwards compatibility.</summary>
[Parameter(Mandatory = false, DontShow = true)]
public SwitchParameter PassThru { get; set; }
@@ -59,6 +70,13 @@ namespace PSProxmoxVE.Cmdlets.Connection
protected override void ProcessRecord()
{
PveSession session;
TimeSpan? timeout = null;
if (TimeoutSeconds.HasValue)
{
timeout = TimeoutSeconds.Value == 0
? System.Threading.Timeout.InfiniteTimeSpan
: TimeSpan.FromSeconds(TimeoutSeconds.Value);
}
switch (ParameterSetName)
{
@@ -77,7 +95,7 @@ namespace PSProxmoxVE.Cmdlets.Connection
try
{
session = PveAuthenticator.AuthenticateWithCredentials(
Server, Port, SkipCertificateCheck.IsPresent, username, password);
Server, Port, SkipCertificateCheck.IsPresent, username, password, timeout);
}
catch (Exception ex)
{
@@ -96,7 +114,7 @@ namespace PSProxmoxVE.Cmdlets.Connection
try
{
session = PveAuthenticator.AuthenticateWithApiToken(
Server, Port, SkipCertificateCheck.IsPresent, ApiToken!);
Server, Port, SkipCertificateCheck.IsPresent, ApiToken!, timeout);
}
catch (Exception ex)
{
@@ -6,6 +6,7 @@ using Newtonsoft.Json.Linq;
using PSProxmoxVE.Core.Client;
using PSProxmoxVE.Core.Models.Vms;
using PSProxmoxVE.Core.Services;
using PSProxmoxVE.Core.Utilities;
namespace PSProxmoxVE.Cmdlets.Containers
{
@@ -59,9 +60,13 @@ namespace PSProxmoxVE.Cmdlets.Containers
public int? Cores { get; set; }
/// <summary>
/// <para type="description">Size of the root filesystem (e.g., "8G").</para>
/// <para type="description">
/// Size of the root filesystem. Accepts a bare integer in GiB ("8") or a value
/// suffixed with G/GB/T/TB (case-insensitive); the value is normalized to a
/// bare GiB count before being sent to the API.
/// </para>
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Size of the root filesystem (e.g. 8G).")]
[Parameter(Mandatory = false, HelpMessage = "Size of the root filesystem in GiB (e.g. 8 or 8G).")]
public string? RootFsSize { get; set; }
/// <summary>
@@ -125,6 +130,13 @@ namespace PSProxmoxVE.Cmdlets.Containers
protected override void ProcessRecord()
{
// Validate -RootFsSize before ShouldProcess so typos like "512M" are rejected
// even with -WhatIf, and so the error is raised regardless of whether
// -RootFsStorage is also supplied.
string? rootFsSizeGib = null;
if (!string.IsNullOrEmpty(RootFsSize))
rootFsSizeGib = SizeParser.NormalizeToGibibytes(RootFsSize!, nameof(RootFsSize));
if (!ShouldProcess($"Container on node '{Node}'", "New-PveContainer"))
return;
@@ -160,8 +172,8 @@ namespace PSProxmoxVE.Cmdlets.Containers
if (!string.IsNullOrEmpty(RootFsStorage))
{
var rootFsValue = RootFsStorage!;
if (!string.IsNullOrEmpty(RootFsSize))
rootFsValue += $":{RootFsSize}";
if (rootFsSizeGib != null)
rootFsValue += $":{rootFsSizeGib}";
config["rootfs"] = rootFsValue;
}
@@ -44,6 +44,16 @@ namespace PSProxmoxVE.Cmdlets.Storage
[Parameter(Mandatory = false, HelpMessage = "Wait for the task to complete before returning.")]
public SwitchParameter Wait { get; set; }
/// <summary>
/// HTTP timeout for issuing the download request, in seconds. Pass 0 for infinite.
/// When omitted, defaults to 30 minutes. Note: this only bounds the API call that
/// schedules the download; the actual file transfer runs server-side and is tracked
/// by the returned task.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "HTTP timeout in seconds (0 = infinite). Defaults to 1800 (30 min).")]
[ValidateRange(0, int.MaxValue)]
public int? TimeoutSeconds { get; set; }
protected override void ProcessRecord()
{
if (!ShouldProcess($"{Node}/{Storage}/{Filename}", $"Download from {Url}"))
@@ -51,7 +61,19 @@ namespace PSProxmoxVE.Cmdlets.Storage
var session = GetSession();
RequireVersion(session, "Storage URL download", 7, 0);
using var client = new PveHttpClient(session);
TimeSpan timeout;
if (TimeoutSeconds.HasValue)
{
timeout = TimeoutSeconds.Value == 0
? System.Threading.Timeout.InfiniteTimeSpan
: TimeSpan.FromSeconds(TimeoutSeconds.Value);
}
else
{
timeout = TimeSpan.FromMinutes(30);
}
using var client = new PveHttpClient(session, timeout);
WriteVerbose($"Downloading '{Url}' to {Node}/{Storage}...");
var resource = $"nodes/{Uri.EscapeDataString(Node)}/storage/{Uri.EscapeDataString(Storage)}/download-url";
@@ -60,6 +60,15 @@ namespace PSProxmoxVE.Cmdlets.Storage
[Parameter(Mandatory = false, HelpMessage = "Wait for the task to complete before returning.")]
public SwitchParameter Wait { get; set; }
/// <summary>
/// HTTP timeout for this upload, in seconds. Pass 0 for infinite (no timeout).
/// When omitted, defaults to 30 minutes — overriding the session timeout so that
/// large file uploads do not trip the default 100-second HttpClient timeout.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "HTTP timeout in seconds (0 = infinite). Defaults to 1800 (30 min).")]
[ValidateRange(0, int.MaxValue)]
public int? TimeoutSeconds { get; set; }
protected override void ProcessRecord()
{
var fileName = System.IO.Path.GetFileName(Path);
@@ -75,7 +84,18 @@ namespace PSProxmoxVE.Cmdlets.Storage
+ $"Connected server is PVE {session.ServerVersion}. The upload will proceed without checksum verification.");
}
using var client = new PveHttpClient(session);
TimeSpan timeout;
if (TimeoutSeconds.HasValue)
{
timeout = TimeoutSeconds.Value == 0
? System.Threading.Timeout.InfiniteTimeSpan
: TimeSpan.FromSeconds(TimeoutSeconds.Value);
}
else
{
timeout = TimeSpan.FromMinutes(30);
}
using var client = new PveHttpClient(session, timeout);
WriteVerbose($"Uploading {fileName} to {Node}/{Storage} (content={ContentType})...");
var resource = $"nodes/{Uri.EscapeDataString(Node)}/storage/{Uri.EscapeDataString(Storage)}/upload";
+144 -9
View File
@@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq;
using PSProxmoxVE.Core.Client;
using PSProxmoxVE.Core.Models.Vms;
using PSProxmoxVE.Core.Services;
using PSProxmoxVE.Core.Utilities;
namespace PSProxmoxVE.Cmdlets.Vms
{
@@ -74,9 +75,13 @@ namespace PSProxmoxVE.Cmdlets.Vms
public string? Machine { get; set; }
/// <summary>
/// <para type="description">Size of the primary disk (e.g., "32G").</para>
/// <para type="description">
/// Size of the primary disk. Accepts a bare integer in GiB ("32") or a value
/// suffixed with G/GB/T/TB (case-insensitive); the value is normalized to a
/// bare GiB count before being sent to the API.
/// </para>
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Size of the primary disk (e.g. 32G).")]
[Parameter(Mandatory = false, HelpMessage = "Size of the primary disk in GiB (e.g. 32 or 32G).")]
public string? DiskSize { get; set; }
/// <summary>
@@ -91,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>
@@ -123,6 +189,16 @@ namespace PSProxmoxVE.Cmdlets.Vms
protected override void ProcessRecord()
{
// 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;
@@ -160,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) && !string.IsNullOrEmpty(DiskSize))
{
var diskValue = $"{DiskStorage}:{DiskSize}";
if (!string.IsNullOrEmpty(DiskFormat))
diskValue += $",format={DiskFormat}";
config["virtio0"] = diskValue;
}
if (!string.IsNullOrEmpty(DiskStorage) && diskSizeGib != null)
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))
{
@@ -188,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 ("&lt;storage&gt;:&lt;sizeGiB&gt;[,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();
}
}
}
+19 -2
View File
@@ -10,7 +10,7 @@
RootModule = 'PSProxmoxVE.dll'
# Version number of this module.
ModuleVersion = '0.1.2'
ModuleVersion = '0.2.0'
# Supported PSEditions
CompatiblePSEditions = @('Desktop', 'Core')
@@ -371,7 +371,24 @@
ProjectUri = 'https://github.com/goodolclint/PSProxmoxVE'
# Release notes for this version
ReleaseNotes = 'Initial preview release. Supports PVE 8.x and 9.x with VM, container, storage, network, SDN, user/role/permission, template, cloud-init, snapshot, and task management.'
ReleaseNotes = @'
## 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:
- 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
'@
}
@@ -100,5 +100,14 @@ namespace PSProxmoxVE.Core.Tests.Authentication
Assert.True(session.SkipCertificateCheck);
}
[Fact]
public void Timeout_DefaultIs100Seconds()
{
var session = new PveSession(TestHostname, TestPort, false,
"root@pam!mytoken=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
Assert.Equal(TimeSpan.FromSeconds(100), session.Timeout);
}
}
}
@@ -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}")
};
}
}
}
}
@@ -0,0 +1,101 @@
using System;
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 PSProxmoxVE.Core.Exceptions;
using Xunit;
namespace PSProxmoxVE.Core.Tests.Client
{
public class PveHttpClientTimeoutTests
{
private static HttpClient GetInnerHttpClient(PveHttpClient client)
{
var field = typeof(PveHttpClient).GetField("_httpClient",
BindingFlags.Instance | BindingFlags.NonPublic)!;
return (HttpClient)field.GetValue(client)!;
}
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");
}
[Fact]
public void Constructor_UsesSessionTimeoutByDefault()
{
var session = NewSession();
session.Timeout = TimeSpan.FromSeconds(42);
using var client = new PveHttpClient(session);
Assert.Equal(TimeSpan.FromSeconds(42), GetInnerHttpClient(client).Timeout);
}
[Fact]
public void Constructor_OverrideTakesPrecedenceOverSessionTimeout()
{
var session = NewSession();
session.Timeout = TimeSpan.FromSeconds(42);
using var client = new PveHttpClient(session, TimeSpan.FromMinutes(30));
Assert.Equal(TimeSpan.FromMinutes(30), GetInnerHttpClient(client).Timeout);
}
[Fact]
public void Constructor_InfiniteTimeSpanIsAccepted()
{
var session = NewSession();
using var client = new PveHttpClient(session, Timeout.InfiniteTimeSpan);
Assert.Equal(Timeout.InfiniteTimeSpan, GetInnerHttpClient(client).Timeout);
}
[Fact]
public async Task SendAsync_TimeoutFires_ThrowsPveApiExceptionWithRequestTimeout()
{
var session = NewSession();
using var client = new PveHttpClient(session);
// Swap in an HttpClient with a delaying handler and a 50ms timeout so
// HttpClient.Timeout fires reliably without any real network.
var delayingClient = new HttpClient(new DelayingHandler(TimeSpan.FromSeconds(30)))
{
Timeout = TimeSpan.FromMilliseconds(50)
};
SetInnerHttpClient(client, delayingClient);
var ex = await Assert.ThrowsAsync<PveApiException>(() => client.GetAsync("version"));
Assert.Equal(HttpStatusCode.RequestTimeout, ex.StatusCode);
Assert.Contains("timed out", ex.Message, StringComparison.OrdinalIgnoreCase);
}
private sealed class DelayingHandler : HttpMessageHandler
{
private readonly TimeSpan _delay;
public DelayingHandler(TimeSpan delay) { _delay = delay; }
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
await Task.Delay(_delay, cancellationToken).ConfigureAwait(false);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
}
}
@@ -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"));
}
}
}
@@ -9,14 +9,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.5.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="coverlet.collector" Version="8.0.1">
<PackageReference Include="coverlet.collector" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
@@ -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);
}
}
}
@@ -0,0 +1,90 @@
using System;
using PSProxmoxVE.Core.Utilities;
using Xunit;
namespace PSProxmoxVE.Core.Tests.Utilities
{
public class SizeParserTests
{
[Theory]
[InlineData("32", "32")]
[InlineData("32G", "32")]
[InlineData("32g", "32")]
[InlineData("32GB", "32")]
[InlineData("32gb", "32")]
[InlineData("32GiB", "32")]
[InlineData("1T", "1024")]
[InlineData("1t", "1024")]
[InlineData("1TB", "1024")]
[InlineData("1TiB", "1024")]
[InlineData("2T", "2048")]
[InlineData(" 60G ", "60")]
[InlineData("60 G", "60")]
public void NormalizeToGibibytes_AcceptedInputs_ReturnsBareGibibyteString(string input, string expected)
{
var result = SizeParser.NormalizeToGibibytes(input);
Assert.Equal(expected, result);
}
[Theory]
[InlineData("512M")]
[InlineData("512MB")]
[InlineData("1024K")]
[InlineData("1024KB")]
[InlineData("100B")]
[InlineData("1P")]
[InlineData("1PB")]
public void NormalizeToGibibytes_UnsupportedUnit_Throws(string input)
{
var ex = Assert.Throws<ArgumentException>(() => SizeParser.NormalizeToGibibytes(input));
Assert.Contains("unsupported unit", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData(null)]
public void NormalizeToGibibytes_EmptyOrWhitespace_Throws(string? input)
{
Assert.Throws<ArgumentException>(() => SizeParser.NormalizeToGibibytes(input!));
}
[Theory]
[InlineData("abc")]
[InlineData("G")]
[InlineData("-32")]
[InlineData("32.5G")]
[InlineData("32 G B")]
public void NormalizeToGibibytes_Malformed_Throws(string input)
{
Assert.Throws<ArgumentException>(() => SizeParser.NormalizeToGibibytes(input));
}
[Theory]
[InlineData("0")]
[InlineData("0G")]
public void NormalizeToGibibytes_Zero_Throws(string input)
{
var ex = Assert.Throws<ArgumentException>(() => SizeParser.NormalizeToGibibytes(input));
Assert.Contains("positive", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void NormalizeToGibibytes_UsesProvidedParameterNameInError()
{
var ex = Assert.Throws<ArgumentException>(() => SizeParser.NormalizeToGibibytes("512M", "DiskSize"));
Assert.Equal("DiskSize", ex.ParamName);
Assert.Contains("DiskSize", ex.Message);
}
[Fact]
public void NormalizeToGibibytes_TerabyteOverflow_ThrowsArgumentException()
{
// long.MaxValue with a T suffix overflows when multiplied by 1024.
var input = long.MaxValue.ToString(System.Globalization.CultureInfo.InvariantCulture) + "T";
var ex = Assert.Throws<ArgumentException>(() => SizeParser.NormalizeToGibibytes(input, "DiskSize"));
Assert.Equal("DiskSize", ex.ParamName);
Assert.Contains("too large", ex.Message, StringComparison.OrdinalIgnoreCase);
}
}
}
@@ -112,5 +112,17 @@ Describe 'Connect-PveServer' {
$overlap = $credSets | Where-Object { $tokenSets -contains $_ }
$overlap | Should -BeNullOrEmpty
}
It 'Should have a TimeoutSeconds parameter' {
$script:Cmd.Parameters.ContainsKey('TimeoutSeconds') | Should -BeTrue
}
It 'TimeoutSeconds should reject negative values' {
$securePass = ConvertTo-SecureString 'hunter2' -AsPlainText -Force
$cred = [System.Management.Automation.PSCredential]::new('root@pam', $securePass)
{
Connect-PveServer -Server 'pve.example.com' -Credential $cred -TimeoutSeconds -1 -ErrorAction Stop
} | Should -Throw
}
}
}
@@ -0,0 +1,68 @@
#Requires -Module Pester
<#
.SYNOPSIS
Pester 5 tests for New-PveContainer.
All tests are fully offline — no live Proxmox VE target is required.
#>
BeforeAll {
. $PSScriptRoot/../_TestHelper.ps1
}
Describe 'New-PveContainer' {
Context 'Command existence' {
It 'Should be available after module import' {
Get-Command 'New-PveContainer' -ErrorAction SilentlyContinue |
Should -Not -BeNullOrEmpty
}
It 'Should be a CmdletInfo (binary cmdlet)' {
(Get-Command 'New-PveContainer').CommandType | Should -Be 'Cmdlet'
}
}
Context 'ShouldProcess support' {
BeforeAll {
$script:Cmd = Get-Command 'New-PveContainer'
}
It 'Should support ShouldProcess (WhatIf parameter present)' {
$script:Cmd.Parameters.ContainsKey('WhatIf') | Should -BeTrue
}
It 'Should support ShouldProcess (Confirm parameter present)' {
$script:Cmd.Parameters.ContainsKey('Confirm') | Should -BeTrue
}
}
Context 'RootFsSize validation' {
# Validation runs before ShouldProcess so -WhatIf is enough to exercise it
# without an active session.
It 'Should reject sub-GB units (e.g. 512M)' {
{ New-PveContainer -Node 'pve-node1' -RootFsStorage 'local-lvm' -RootFsSize '512M' -WhatIf -ErrorAction Stop } |
Should -Throw '*unsupported unit*'
}
It 'Should reject sub-GB units even when -RootFsStorage is omitted' {
{ New-PveContainer -Node 'pve-node1' -RootFsSize '512M' -WhatIf -ErrorAction Stop } |
Should -Throw '*unsupported unit*'
}
It 'Should reject malformed input (e.g. 8.5G)' {
{ New-PveContainer -Node 'pve-node1' -RootFsStorage 'local-lvm' -RootFsSize '8.5G' -WhatIf -ErrorAction Stop } |
Should -Throw '*not a valid size*'
}
It 'Should accept a bare integer with -WhatIf' {
{ New-PveContainer -Node 'pve-node1' -RootFsStorage 'local-lvm' -RootFsSize '8' -WhatIf -ErrorAction Stop } |
Should -Not -Throw
}
It 'Should accept "8G" with -WhatIf' {
{ New-PveContainer -Node 'pve-node1' -RootFsStorage 'local-lvm' -RootFsSize '8G' -WhatIf -ErrorAction Stop } |
Should -Not -Throw
}
}
}
@@ -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' {
@@ -154,6 +154,20 @@ Describe 'Send-PveFile' {
if (-not $script:CmdExists) { Set-ItResult -Skipped -Because 'Not yet compiled'; return }
$script:Cmd.Parameters.ContainsKey('Session') | Should -BeTrue
}
It 'Should have TimeoutSeconds parameter' {
if (-not $script:CmdExists) { Set-ItResult -Skipped -Because 'Not yet compiled'; return }
$script:Cmd.Parameters.ContainsKey('TimeoutSeconds') | Should -BeTrue
}
It 'TimeoutSeconds should reject negative values' {
if (-not $script:CmdExists) { Set-ItResult -Skipped -Because 'Not yet compiled'; return }
$tmpIso = [System.IO.Path]::GetTempFileName()
try {
{ Send-PveFile -Node 'n' -Storage 's' -Path $tmpIso -TimeoutSeconds -1 -Confirm:$false -ErrorAction Stop } |
Should -Throw
} finally { Remove-Item $tmpIso -ErrorAction SilentlyContinue }
}
}
Context 'Without active session' {
@@ -150,6 +150,17 @@ Describe 'Invoke-PveStorageDownload' {
$script:Cmd.Parameters.ContainsKey('Wait') | Should -BeTrue
$script:Cmd.Parameters['Wait'].SwitchParameter | Should -BeTrue
}
It 'Should have TimeoutSeconds parameter' {
Skip-IfMissing 'Invoke-PveStorageDownload'
$script:Cmd.Parameters.ContainsKey('TimeoutSeconds') | Should -BeTrue
}
It 'TimeoutSeconds should reject negative values' {
Skip-IfMissing 'Invoke-PveStorageDownload'
{ Invoke-PveStorageDownload -Node 'pve1' -Storage 'local' -Url 'https://example.com/test.iso' -Filename 'test.iso' -TimeoutSeconds -1 -Confirm:$false -ErrorAction Stop } |
Should -Throw
}
}
Context 'Session parameter' {
@@ -133,4 +133,115 @@ Describe 'New-PveVm' {
Should -Throw '*No active Proxmox VE session*'
}
}
Context 'DiskSize validation' {
# Validation runs before ShouldProcess so -WhatIf is enough to exercise it
# without an active session.
It 'Should reject sub-GB units (e.g. 512M)' {
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '512M' -WhatIf -ErrorAction Stop } |
Should -Throw '*unsupported unit*'
}
It 'Should reject sub-GB units even when -DiskStorage is omitted' {
{ New-PveVm -Node 'pve-node1' -DiskSize '512M' -WhatIf -ErrorAction Stop } |
Should -Throw '*unsupported unit*'
}
It 'Should reject malformed input (e.g. 32.5G)' {
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32.5G' -WhatIf -ErrorAction Stop } |
Should -Throw '*not a valid size*'
}
It 'Should accept a bare integer with -WhatIf' {
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32' -WhatIf -ErrorAction Stop } |
Should -Not -Throw
}
It 'Should accept "32G" with -WhatIf' {
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '32G' -WhatIf -ErrorAction Stop } |
Should -Not -Throw
}
It 'Should accept "1T" with -WhatIf' {
{ New-PveVm -Node 'pve-node1' -DiskStorage 'local-lvm' -DiskSize '1T' -WhatIf -ErrorAction Stop } |
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
}
}
}