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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions integration/windows/environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func (e *WindowsEnvironment) ShrinkRootPartition() {
sizeMinBuffer := 1 * GB
cmdFmtString := "Get-Partition -DriveLetter C | Resize-Partition -Size $((Get-PartitionSupportedSize -DriveLetter C).SizeMin + %d)"

shrunkSuccessfully := false
for i := 0; i < 5; i++ {
cmd := fmt.Sprintf(cmdFmtString, sizeMinBuffer)
stdout, stderr, exitCode, err := e.RunPowershellCommandWithOffsetAndResponses(cmd)
Expand Down Expand Up @@ -72,8 +73,14 @@ func (e *WindowsEnvironment) ShrinkRootPartition() {
}
}

shrunkSuccessfully = true
break
}

Expect(shrunkSuccessfully).WithOffset(1).To(
BeTrue(),
fmt.Sprintf("Failed to shrink root partition after 5 attempts; last command: %s", fmt.Sprintf(cmdFmtString, sizeMinBuffer)),
)
}

func (e *WindowsEnvironment) EnsureRootPartitionAtMaxSize() {
Expand Down
4 changes: 4 additions & 0 deletions integration/windows/ephemeral_disk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ var _ = Describe("EphemeralDisk", func() {
agent.EnsureDataDirDoesntExist()

if diskLetter != "" {
Expect(diskLetter).NotTo(Equal("C"),
"diskLetter must never be the system partition (C:) — "+
"this indicates the agent created the data-dir junction pointing to the root drive, "+
"or AssignDriveLetter returned an unexpected value")
agent.RunPowershellCommand(fmt.Sprintf("Remove-Partition -DriveLetter %s -Confirm:$false", diskLetter))
}
if diskNumber != "0" {
Expand Down
54 changes: 45 additions & 9 deletions platform/windows/disk/partitioner.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"regexp"
"strconv"
"strings"
"time"

boshsys "github.com/cloudfoundry/bosh-utils/system"
)
Expand All @@ -13,6 +14,11 @@ var diskNumberPattern = regexp.MustCompile(`^[0-9]+$`)

type Partitioner struct {
Runner boshsys.CmdRunner

// DriveLetterPollInterval controls how long AssignDriveLetter waits between
// queries when Get-Partition reports no letter yet (DriveLetter == char(0)).
// Zero (the default) uses 1 second. Override in tests to avoid delays.
DriveLetterPollInterval time.Duration
}

// ParseDiskNumberString validates a non-negative decimal disk or partition index for Windows PowerShell -Number parameters.
Expand Down Expand Up @@ -151,15 +157,45 @@ func (p *Partitioner) AssignDriveLetter(diskNumber, partitionNumber string) (str
dn, pn,
)

stdout, _, _, err := p.ps(driveScript)
if err != nil {
return "", fmt.Errorf(
"failed to find drive letter for partition %s on disk %s: %s",
partitionNumber,
diskNumber,
err,
)
// PowerShell's Partition.DriveLetter is a .NET char. When no letter has been
// assigned the property holds char(0) — the null character — which PowerShell
// prints as "\x00\r\n". If we returned that empty string the caller would call
// linker.Link with a bare ":" target; on Windows that resolves to the current
// directory on the default drive (typically C:\), silently creating a junction
// that points back to the system partition.
//
// Retry up to 10 times to tolerate transient WMI staleness after the access
// path is added.
pollInterval := p.DriveLetterPollInterval
if pollInterval == 0 {
pollInterval = time.Second
}

return strings.TrimSpace(stdout), nil
for attempt := 0; attempt < 10; attempt++ {
stdout, _, _, err := p.ps(driveScript)
if err != nil {
return "", fmt.Errorf(
"failed to find drive letter for partition %s on disk %s: %s",
partitionNumber,
diskNumber,
err,
)
}

// The DriveLetter property is a char; an unassigned partition returns the null
// character (\x00). Strip it along with whitespace before checking.
letter := strings.Trim(strings.TrimSpace(stdout), "\x00")
if letter != "" {
return letter, nil
}

time.Sleep(pollInterval)
}
Comment on lines +174 to +193
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid sleeping after the last retry attempt.

The loop sleeps even on the final failed attempt, adding an unnecessary delay before returning the error.

Proposed fix
 	for attempt := 0; attempt < 10; attempt++ {
 		stdout, _, _, err := p.ps(driveScript)
 		if err != nil {
 			return "", fmt.Errorf(
 				"failed to find drive letter for partition %s on disk %s: %s",
 				partitionNumber,
 				diskNumber,
 				err,
 			)
 		}

 		// The DriveLetter property is a char; an unassigned partition returns the null
 		// character (\x00). Strip it along with whitespace before checking.
 		letter := strings.Trim(strings.TrimSpace(stdout), "\x00")
 		if letter != "" {
 			return letter, nil
 		}

-		time.Sleep(pollInterval)
+		if attempt < 9 {
+			time.Sleep(pollInterval)
+		}
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for attempt := 0; attempt < 10; attempt++ {
stdout, _, _, err := p.ps(driveScript)
if err != nil {
return "", fmt.Errorf(
"failed to find drive letter for partition %s on disk %s: %s",
partitionNumber,
diskNumber,
err,
)
}
// The DriveLetter property is a char; an unassigned partition returns the null
// character (\x00). Strip it along with whitespace before checking.
letter := strings.Trim(strings.TrimSpace(stdout), "\x00")
if letter != "" {
return letter, nil
}
time.Sleep(pollInterval)
}
for attempt := 0; attempt < 10; attempt++ {
stdout, _, _, err := p.ps(driveScript)
if err != nil {
return "", fmt.Errorf(
"failed to find drive letter for partition %s on disk %s: %s",
partitionNumber,
diskNumber,
err,
)
}
// The DriveLetter property is a char; an unassigned partition returns the null
// character (\x00). Strip it along with whitespace before checking.
letter := strings.Trim(strings.TrimSpace(stdout), "\x00")
if letter != "" {
return letter, nil
}
if attempt < 9 {
time.Sleep(pollInterval)
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@platform/windows/disk/partitioner.go` around lines 174 - 193, The retry loop
in GetDriveLetter (the for attempt := 0; attempt < 10; attempt++ block using
p.ps with driveScript) always calls time.Sleep(pollInterval) even after the
final attempt; modify the loop so it only sleeps between attempts (e.g., compute
maxAttempts := 10 or use attempt < 9) and call time.Sleep(pollInterval) only
when attempt < maxAttempts-1, leaving the error return path (which uses
partitionNumber and diskNumber) unchanged.


return "", fmt.Errorf(
"drive letter was not assigned to partition %s on disk %s after %d attempts",
partitionNumber,
diskNumber,
10,
)
}
41 changes: 41 additions & 0 deletions platform/windows/disk/partitioner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"errors"
"fmt"
"strings"
"time"

"github.com/cloudfoundry/bosh-utils/system/fakes"
. "github.com/onsi/ginkgo/v2"
Expand Down Expand Up @@ -264,5 +265,45 @@
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring(`AssignDriveLetter: invalid partition number "2;Invoke-Expression"`))
})

It("retries when Get-Partition reports char(0) before returning the valid letter", func() {
// Simulate WMI returning the null character on the first poll, then the
// real letter on the second. Without the retry the function would return ""
// and the caller would create a junction pointing at bare ":", which Windows
// resolves to the current directory on the default drive (often C:\).
partitioner.DriveLetterPollInterval = time.Millisecond

addKey := strings.Join([]string{"-NoProfile", "-NonInteractive", "-Command",
`Add-PartitionAccessPath -DiskNumber 1 -PartitionNumber 2 -AssignDriveLetter`}, " ")
getKey := strings.Join([]string{"-NoProfile", "-NonInteractive", "-Command",
`Get-Partition -DiskNumber 1 -PartitionNumber 2 | Select-Object -ExpandProperty DriveLetter`}, " ")

cmdRunner.AddCmdResult(addKey, fakes.FakeCmdResult{})
cmdRunner.AddCmdResult(getKey, fakes.FakeCmdResult{Stdout: "\x00\n"}) // null char — unassigned
cmdRunner.AddCmdResult(getKey, fakes.FakeCmdResult{Stdout: "E\n"}) // assigned on second poll

Check failure on line 283 in platform/windows/disk/partitioner_test.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

File is not properly formatted (goimports)

Check failure on line 283 in platform/windows/disk/partitioner_test.go

View workflow job for this annotation

GitHub Actions / lint (ubuntu-latest)

File is not properly formatted (goimports)

Check failure on line 283 in platform/windows/disk/partitioner_test.go

View workflow job for this annotation

GitHub Actions / lint (ubuntu-latest)

File is not properly formatted (goimports)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix goimports formatting at this line to unblock lint.

CI is currently failing goimports on this line; please run goimports on the file and commit the formatted result.

Likely formatting-only adjustment
-			cmdRunner.AddCmdResult(getKey, fakes.FakeCmdResult{Stdout: "E\n"})   // assigned on second poll
+			cmdRunner.AddCmdResult(getKey, fakes.FakeCmdResult{Stdout: "E\n"}) // assigned on second poll
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cmdRunner.AddCmdResult(getKey, fakes.FakeCmdResult{Stdout: "E\n"}) // assigned on second poll
cmdRunner.AddCmdResult(getKey, fakes.FakeCmdResult{Stdout: "E\n"}) // assigned on second poll
🧰 Tools
🪛 GitHub Check: lint (macos-latest)

[failure] 283-283:
File is not properly formatted (goimports)

🪛 GitHub Check: lint (ubuntu-latest)

[failure] 283-283:
File is not properly formatted (goimports)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@platform/windows/disk/partitioner_test.go` at line 283, The failing line uses
goimports-incompatible formatting; run goimports on
platform/windows/disk/partitioner_test.go (or the whole repo) and commit the
formatted file so the line with cmdRunner.AddCmdResult(getKey,
fakes.FakeCmdResult{Stdout: "E\n"}) conforms to goimports rules—this will fix
import grouping/formatting and unblock CI; locate the call by searching for
AddCmdResult, getKey, or fakes.FakeCmdResult to confirm the change.


driveLetter, err := partitioner.AssignDriveLetter(diskNumber, partitionNumber)
Expect(err).NotTo(HaveOccurred())
Expect(driveLetter).To(Equal("E"))
})

It("returns an error when DriveLetter stays null across all retry attempts", func() {
partitioner.DriveLetterPollInterval = time.Millisecond

addKey := strings.Join([]string{"-NoProfile", "-NonInteractive", "-Command",
`Add-PartitionAccessPath -DiskNumber 1 -PartitionNumber 2 -AssignDriveLetter`}, " ")
getKey := strings.Join([]string{"-NoProfile", "-NonInteractive", "-Command",
`Get-Partition -DiskNumber 1 -PartitionNumber 2 | Select-Object -ExpandProperty DriveLetter`}, " ")

cmdRunner.AddCmdResult(addKey, fakes.FakeCmdResult{})
// Sticky so every Get-Partition call returns the null char.
cmdRunner.AddCmdResult(getKey, fakes.FakeCmdResult{Stdout: "\x00\n", Sticky: true})

_, err := partitioner.AssignDriveLetter(diskNumber, partitionNumber)
Expect(err).To(MatchError(ContainSubstring(
fmt.Sprintf("drive letter was not assigned to partition %s on disk %s after 10 attempts",
partitionNumber, diskNumber),
)))
})
})
})
Loading