Skip to content

feat: Use WMI to implement Volume API to reduce PowerShell overhead (library version) #372

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 3 additions & 3 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ jobs:
integration_tests:
strategy:
matrix:
go: ['1.16']
go: ['1.22']
platform: [windows-latest]
runs-on: ${{ matrix.platform }}
steps:
Expand All @@ -22,11 +22,11 @@ jobs:
Install-WindowsFeature -name Hyper-V-PowerShell

$env:CSI_PROXY_GH_ACTIONS="TRUE"
go test --timeout 20m -v -race ./integrationtests/...
go test --timeout 20m -v ./integrationtests/...
unit_tests:
strategy:
matrix:
go: ['1.16']
go: ['1.22']
platform: [windows-latest]
runs-on: ${{ matrix.platform }}
steps:
Expand Down
230 changes: 230 additions & 0 deletions docs/IMPLEMENTATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
# CSI Proxy API Implementation with WMI
<a name="top"></a>

## Table of Contents

- [Windows Management Instrumentation](#wmi)
- [microsoft/wmi library](#microsoft-wmi-library)
- [How to make WMI queries and debug with PowerShell](#debug-powershell)


<a name="wmi"></a>
## Windows Management Instrumentation

Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems.
Refer to [WMI start page](https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmi-start-page) for more details.

The purpose of WMI is to define a proprietary set of environment-independent specifications that enable sharing management information between management apps.

CSI-proxy makes WMI queries using `microsoft/wmi` library. Refer to for the call graph below.

<a name="microsoft-wmi-library"></a>
## microsoft/wmi library

![WMI based implementation](./WMI.png)

`microsoft/wmi` library leverages the traditional COM interfaces (`IDispatch`) to call the WMI.

COM interfaces wrap the parameters and return value in a `VARIANT` struct.
`microsoft/wmi` library converts the `VARIANT` to native Go types and struct.

A typical WMI query may need to obtain a WMI session of the target machine first, which
can be done by the helper methods `NewWMISession` and `QueryFromWMI` in `pkg/cim`.

A query like `SELECT * FROM MSFT_Volume` may return all the volumes on the current node.

### Queries

The query may return a list of WMI objects of the generic type `cim.WmiInstance`. You may further cast
the object down to a specific WMI class (e.g. `MSFT_Disk`). You may find the WMI class definition
from the API doc.

For example, the property `PartitionStyle` on [MSFT_Disk](https://learn.microsoft.com/en-us/windows-hardware/drivers/storage/msft-disk#properties) is defined as

| API constraints | Settings |
|-----------------|---------------------------------------|
| Property | PartitionStyle |
| Data type | UInt16 |
| Access type | Read-only |
| Qualifiers | Required |
| Description | The partition style used by the disk. |

You may use `GetProperty` to get the value of `PartitionStyle` to get the value from the `VARIANT` and
converts it back to Go types.

```go
retValue, err := disk.GetProperty("PartitionStyle")
if err != nil {
return false, fmt.Errorf("failed to query partition style of disk %d: %w", diskNumber, err)
}

partitionStyle = retValue.(int32)
```

Note that some auto-generated wrapper methods in `microsoft/wmi` may have wrong data types mapping to Go native types.
It's always recommended to use `GetProperty` instead of these pre-defined wrapper methods.

### Class Method

A WMI class may have some Class Method to call for a specific operation (e.g., creating a new partition).

You may use the method `InvokeMethodWithReturn`.

```go
result, err := disk.InvokeMethodWithReturn(
"CreatePartition",
nil, // Size
true, // UseMaximumSize
nil, // Offset
nil, // Alignment
nil, // DriveLetter
false, // AssignDriveLetter
nil, // MbrType,
cim.GPTPartitionTypeBasicData, // GPT Type
false, // IsHidden
false, // IsActive,
)
// 42002 is returned by driver letter failed to assign after partition
if (result != 0 && result != 42002) || err != nil {
return fmt.Errorf("error creating partition on disk %d. result: %d, err: %v", diskNumber, result, err)
}
```

Both input and output parameters can be found in the [CreatePartition API doc](https://learn.microsoft.com/en-us/windows-hardware/drivers/storage/createpartition-msft-disk).

```c
UInt32 CreatePartition(
[in] UInt64 Size,
[in] Boolean UseMaximumSize,
[in] UInt64 Offset,
[in] UInt32 Alignment,
[in] Char16 DriveLetter,
[in] Boolean AssignDriveLetter,
[in] UInt16 MbrType,
[in] String GptType,
[in] Boolean IsHidden,
[in] Boolean IsActive,
[out] String CreatedPartition,
[out] String ExtendedStatus
);
```

There parameters will be wrapped in `VARIANT` with the corresponding types.

Eventually the method `CreatePartition` on the WMI object will be called via `IDispatch` interface in native COM/OLE calls.

Refer to [CallMethod](https://github.com/go-ole/go-ole/blob/master/oleutil/oleutil.go#L49-L52) if you need to know the details of a COM/OLE call.

```go
func CallMethod(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_METHOD, params)
}
```

### Association

Association can be used to retrieve all instances that are associated with
a particular source instance.

There are a few Association classes in WMI.

For example, association class [MSFT_PartitionToVolume](https://learn.microsoft.com/en-us/windows-hardware/drivers/storage/msft-partitiontovolume)
can be used to retrieve a volume (`MSFT_Volume`) from a partition (`MSFT_Partition`), and vice versa.

```go
collection, err := part.GetAssociated("MSFT_PartitionToVolume", "MSFT_Volume", "Volume", "Partition")
```

<a name="debug-powershell"></a>
## Debug with PowerShell

### How to make WMI call with PowerShell

You will find the `Query` for each method in `pkg/cim` package.
For example, this is the comment of `ListVolume`

```go
// ListVolumes retrieves all available volumes on the system.
//
// The equivalent WMI query is:
//
// SELECT [selectors] FROM MSFT_Volume
//
// Refer to https://learn.microsoft.com/en-us/windows-hardware/drivers/storage/msft-volume
// for the WMI class definition.
```

You may use the same query with PowerShell cmdlet `Get-CimInstance` targeting
the corresponding namespace `Root\Microsoft\Windows\Storage`.

The return result will be an object of `MSFT_Volume` WMI class.

e.g. if we're going to list the details of the first volume on Windows system:

```powershell
PS C:\Users\Administrator> $vol = (Get-CimInstance -Namespace "Root\Microsoft\Windows\Storage" -Query "SELECT * FROM MSFT_Volume")[0]
PS C:\Users\Administrator> $vol

ObjectId : {1}\\WIN-8E2EVAQ9QSB\root/Microsoft/Windows/Storage/Providers_v2\WSP_Volume.ObjectId=
"{b65bb3cd-da86-11ee-854b-806e6f6e6963}:VO:\\?\Volume{1781d1eb-2c0a-47ed-987f-c229b9c
02527}\"
PassThroughClass :
PassThroughIds :
PassThroughNamespace :
PassThroughServer :
UniqueId : \\?\Volume{1781d1eb-2c0a-47ed-987f-c229b9c02527}\
AllocationUnitSize : 4096
DedupMode : 4
DriveLetter : C
DriveType : 3
FileSystem : NTFS
FileSystemLabel :
FileSystemType : 14
HealthStatus : 1
OperationalStatus : {53261}
Path : \\?\Volume{1781d1eb-2c0a-47ed-987f-c229b9c02527}\
Size : 536198770688
SizeRemaining : 407553982464
PSComputerName :
```

Then you may use `obj.FileSystem` to get the file system of the volume.

```powershell
PS C:\Users\Administrator> $vol.FileSystem
NTFS
```

### Association

```powershell
PS C:\Users\Administrator> $partition = (Get-CimInstance -Namespace root\Microsoft\Windows\Storage -ClassName MSFT_Partition -Filter "DiskNumber = 0")[0]
PS C:\Users\Administrator> Get-CimAssociatedInstance -InputObject $partition -Association MSFT_PartitionToVolume
```

### Call Class Method

You may get Class Methods for a single CIM class using `$class.CimClassMethods`.

```powershell

PS C:\Users\Administrator> $class = Get-CimClass -ClassName MSFT_StorageSetting -Namespace "Root\Microsoft\Windows\Storage"
PS C:\Users\Administrator> $class.CimClassMethods

Name ReturnType Parameters Qualifiers
---- ---------- ---------- ----------
Get UInt32 {StorageSetting} {implemented, static}
Set UInt32 {NewDiskPolicy, ScrubPolicy} {implemented, static}
UpdateHostStorageCache UInt32 {} {implemented, static}
```

You may use `Invoke-CimMethod` to invoke those static methods on the `CimClass` object.

```powershell
PS C:\Users\Administrator> Invoke-CimMethod -CimClass $class -MethodName UpdateHostStorageCache @{}

ReturnValue PSComputerName
----------- --------------
0

```
Binary file added docs/WMI.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 13 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
module github.com/kubernetes-csi/csi-proxy/v2

go 1.16
go 1.22

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/stretchr/testify v1.5.1
github.com/go-ole/go-ole v1.3.0
github.com/microsoft/wmi v0.25.1
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.7.0
golang.org/x/sys v0.25.0
k8s.io/klog/v2 v2.9.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logr/logr v0.4.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.0 // indirect
)
18 changes: 14 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,24 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v0.4.0 h1:K7/B1jt6fIBQVd4Owv2MqGQClcgf0R266+7C/QjRcLc=
github.com/go-logr/logr v0.4.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/microsoft/wmi v0.25.1 h1:sQv9hCEHtW5K6yEVL78T6XGRMGxk4aTpcJwCiB5rLN0=
github.com/microsoft/wmi v0.25.1/go.mod h1:1zbdSF0A+5OwTUII5p3hN7/K6KF2m3o27pSG6Y51VU8=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA=
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
k8s.io/klog/v2 v2.9.0 h1:D7HV+n1V57XeZ0m6tdRkfknthUaM06VFbWldOFh8kzM=
k8s.io/klog/v2 v2.9.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec=
63 changes: 63 additions & 0 deletions pkg/cim/disk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//go:build windows
// +build windows

package cim

import (
"fmt"
"strconv"

"github.com/microsoft/wmi/pkg/base/query"
"github.com/microsoft/wmi/server2019/root/microsoft/windows/storage"
)

const (
// PartitionStyleUnknown indicates an unknown partition table format
PartitionStyleUnknown = 0
// PartitionStyleGPT indicates the disk uses GUID Partition Table (GPT) format
PartitionStyleGPT = 2

// GPTPartitionTypeBasicData is the GUID for basic data partitions in GPT
// Used for general purpose storage partitions
GPTPartitionTypeBasicData = "{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}"
// GPTPartitionTypeMicrosoftReserved is the GUID for Microsoft Reserved Partition (MSR)
// Reserved by Windows for system use
GPTPartitionTypeMicrosoftReserved = "{e3c9e316-0b5c-4db8-817d-f92df00215ae}"

// ErrorCodeCreatePartitionAccessPathAlreadyInUse is the error code (42002) returned when the driver letter failed to assign after partition created
ErrorCodeCreatePartitionAccessPathAlreadyInUse = 42002
)

// QueryDiskByNumber retrieves disk information for a specific disk identified by its number.
//
// The equivalent WMI query is:
//
// SELECT [selectors] FROM MSFT_Disk
// WHERE DiskNumber = '<diskNumber>'
//
// Refer to https://learn.microsoft.com/en-us/windows-hardware/drivers/storage/msft-disk
// for the WMI class definition.
func QueryDiskByNumber(diskNumber uint32, selectorList []string) (*storage.MSFT_Disk, error) {
diskQuery := query.NewWmiQueryWithSelectList("MSFT_Disk", selectorList, "Number", strconv.Itoa(int(diskNumber)))
instances, err := QueryInstances(WMINamespaceStorage, diskQuery)
if err != nil {
return nil, err
}

disk, err := storage.NewMSFT_DiskEx1(instances[0])
if err != nil {
return nil, fmt.Errorf("failed to query disk %d. error: %v", diskNumber, err)
}

return disk, nil
}

// RefreshDisk Refreshes the cached disk layout information.
//
// Refer to https://learn.microsoft.com/en-us/windows-hardware/drivers/storage/msft-disk-refresh
// for the WMI method definition.
func RefreshDisk(disk *storage.MSFT_Disk) (int, string, error) {
var status string
result, err := disk.InvokeMethodWithReturn("Refresh", &status)
return int(result), status, err
}
Loading