mirror of
https://github.com/prometheus-community/windows_exporter.git
synced 2026-10-17 10:09:05 +02:00
hyperv: add virtual_hard_disk sub-collector (#2693)
Signed-off-by: EisenbergD <dominik.eisenberg@beiersdorf.com> Co-authored-by: EisenbergD <dominik.eisenberg@beiersdorf.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
EisenbergD
Claude Opus 5.5
parent
89c5df9d8b
commit
ec7dcdc259
@@ -0,0 +1,260 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// Copyright The Prometheus Authors
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build windows
|
||||
|
||||
// Package virtdisk reads the size and type of virtual hard disks (VHD, VHDX,
|
||||
// VHD Set) through virtdisk.dll, the API behind Get-VHD.
|
||||
// https://learn.microsoft.com/en-us/windows/win32/api/virtdisk/
|
||||
package virtdisk
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var (
|
||||
modVirtdisk = windows.NewLazySystemDLL("virtdisk.dll")
|
||||
procOpenVirtualDisk = modVirtdisk.NewProc("OpenVirtualDisk")
|
||||
procGetVirtualDiskInformation = modVirtdisk.NewProc("GetVirtualDiskInformation")
|
||||
)
|
||||
|
||||
// Provider subtypes of GET_VIRTUAL_DISK_INFO_PROVIDER_SUBTYPE.
|
||||
const (
|
||||
ProviderSubtypeFixed uint32 = 2
|
||||
ProviderSubtypeDynamic uint32 = 3
|
||||
ProviderSubtypeDifferencing uint32 = 4
|
||||
)
|
||||
|
||||
const (
|
||||
virtualDiskAccessNone = 0x00000000 // VIRTUAL_DISK_ACCESS_NONE, required with version 2 parameters
|
||||
openVirtualDiskFlagNoParents = 0x00000001 // OPEN_VIRTUAL_DISK_FLAG_NO_PARENTS
|
||||
openVirtualDiskVersion2 = 2 // OPEN_VIRTUAL_DISK_VERSION_2
|
||||
|
||||
getVirtualDiskInfoSize = 1 // GET_VIRTUAL_DISK_INFO_SIZE
|
||||
getVirtualDiskInfoParentLocation = 3 // GET_VIRTUAL_DISK_INFO_PARENT_LOCATION
|
||||
getVirtualDiskInfoProviderSubtype = 7 // GET_VIRTUAL_DISK_INFO_PROVIDER_SUBTYPE
|
||||
)
|
||||
|
||||
// virtualStorageType is VIRTUAL_STORAGE_TYPE. The zero value is
|
||||
// VIRTUAL_STORAGE_TYPE_DEVICE_UNKNOWN with VIRTUAL_STORAGE_TYPE_VENDOR_UNKNOWN,
|
||||
// which lets OpenVirtualDisk detect VHD, VHDX and VHD Set files.
|
||||
type virtualStorageType struct {
|
||||
DeviceID uint32
|
||||
VendorID windows.GUID
|
||||
}
|
||||
|
||||
// openVirtualDiskParametersV2 is OPEN_VIRTUAL_DISK_PARAMETERS with
|
||||
// OPEN_VIRTUAL_DISK_VERSION_2. The union is 4-byte aligned.
|
||||
type openVirtualDiskParametersV2 struct {
|
||||
Version uint32
|
||||
GetInfoOnly int32 // BOOL
|
||||
ReadOnly int32 // BOOL
|
||||
ResiliencyGUID windows.GUID
|
||||
}
|
||||
|
||||
// getVirtualDiskInfo is GET_VIRTUAL_DISK_INFO. The union is 8-byte aligned
|
||||
// and its largest member is the 24-byte Size struct.
|
||||
type getVirtualDiskInfo struct {
|
||||
Version uint32
|
||||
_ uint32
|
||||
Union [24]byte
|
||||
}
|
||||
|
||||
// Info is the size and type of a virtual hard disk.
|
||||
type Info struct {
|
||||
// VirtualSize is the maximum size the virtual machine sees, in bytes.
|
||||
VirtualSize uint64
|
||||
// PhysicalSize is the size of the file on storage, in bytes.
|
||||
PhysicalSize uint64
|
||||
// ProviderSubtype is ProviderSubtypeFixed, ProviderSubtypeDynamic or ProviderSubtypeDifferencing.
|
||||
ProviderSubtype uint32
|
||||
}
|
||||
|
||||
// Available reports whether virtdisk.dll and the functions used by GetInfo
|
||||
// can be loaded. LazyProc.Call panics if they can't, so check this first.
|
||||
func Available() error {
|
||||
if err := procOpenVirtualDisk.Find(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return procGetVirtualDiskInformation.Find()
|
||||
}
|
||||
|
||||
// GetInfo opens the virtual hard disk at path read-only, without its parents,
|
||||
// and returns its size and provider subtype. It works on disks attached to
|
||||
// running virtual machines.
|
||||
func GetInfo(path string) (Info, error) {
|
||||
handle, err := open(path)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
defer func() { _ = windows.CloseHandle(handle) }()
|
||||
|
||||
size, err := getInformation(handle, getVirtualDiskInfoSize)
|
||||
if err != nil {
|
||||
return Info{}, fmt.Errorf("GetVirtualDiskInformation size %s: %w", path, err)
|
||||
}
|
||||
|
||||
subtype, err := getInformation(handle, getVirtualDiskInfoProviderSubtype)
|
||||
if err != nil {
|
||||
return Info{}, fmt.Errorf("GetVirtualDiskInformation provider subtype %s: %w", path, err)
|
||||
}
|
||||
|
||||
return Info{
|
||||
VirtualSize: binary.LittleEndian.Uint64(size.Union[0:8]),
|
||||
PhysicalSize: binary.LittleEndian.Uint64(size.Union[8:16]),
|
||||
ProviderSubtype: binary.LittleEndian.Uint32(subtype.Union[0:4]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ParentLocations returns the paths at which the parent of the differencing
|
||||
// disk at path is stored, as recorded in the disk. Disks without a parent
|
||||
// return none.
|
||||
func ParentLocations(path string) ([]string, error) {
|
||||
handle, err := open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() { _ = windows.CloseHandle(handle) }()
|
||||
|
||||
subtype, err := getInformation(handle, getVirtualDiskInfoProviderSubtype)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GetVirtualDiskInformation provider subtype %s: %w", path, err)
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(subtype.Union[0:4]) != ProviderSubtypeDifferencing {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GET_VIRTUAL_DISK_INFO with ParentLocation: the 8-byte aligned union starts
|
||||
// at offset 8 with the BOOL ParentResolved, followed by the MULTI_SZ
|
||||
// ParentLocationBuffer. A uint64 buffer keeps the alignment.
|
||||
buffer := make([]uint64, 512)
|
||||
|
||||
for range 4 {
|
||||
bytes := unsafe.Slice((*byte)(unsafe.Pointer(&buffer[0])), len(buffer)*8)
|
||||
binary.LittleEndian.PutUint32(bytes, getVirtualDiskInfoParentLocation)
|
||||
|
||||
infoSize := uint32(len(bytes))
|
||||
|
||||
ret, _, _ := procGetVirtualDiskInformation.Call(
|
||||
uintptr(handle),
|
||||
uintptr(unsafe.Pointer(&infoSize)),
|
||||
uintptr(unsafe.Pointer(&buffer[0])),
|
||||
0, // SizeUsed is optional
|
||||
)
|
||||
|
||||
switch windows.Errno(ret) {
|
||||
case 0:
|
||||
if infoSize < 12 || int(infoSize) > len(bytes) {
|
||||
return nil, fmt.Errorf("GetVirtualDiskInformation parent location %s: invalid size %d", path, infoSize)
|
||||
}
|
||||
|
||||
chars := unsafe.Slice((*uint16)(unsafe.Pointer(&bytes[12])), (int(infoSize)-12)/2)
|
||||
|
||||
return decodeMultiString(chars), nil
|
||||
case windows.ERROR_INSUFFICIENT_BUFFER, windows.ERROR_MORE_DATA:
|
||||
if int(infoSize) <= len(bytes) {
|
||||
return nil, fmt.Errorf("GetVirtualDiskInformation parent location %s: %w", path, windows.Errno(ret))
|
||||
}
|
||||
|
||||
buffer = make([]uint64, (int(infoSize)+7)/8)
|
||||
default:
|
||||
return nil, fmt.Errorf("GetVirtualDiskInformation parent location %s: %w", path, windows.Errno(ret))
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("GetVirtualDiskInformation parent location %s: buffer did not stabilize", path)
|
||||
}
|
||||
|
||||
// decodeMultiString splits a MULTI_SZ into its strings.
|
||||
func decodeMultiString(chars []uint16) []string {
|
||||
var out []string
|
||||
|
||||
for len(chars) > 0 {
|
||||
end := 0
|
||||
for end < len(chars) && chars[end] != 0 {
|
||||
end++
|
||||
}
|
||||
|
||||
if end == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
out = append(out, windows.UTF16ToString(chars[:end]))
|
||||
|
||||
if end == len(chars) {
|
||||
break
|
||||
}
|
||||
|
||||
chars = chars[end+1:]
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// open opens the virtual hard disk at path for reading its information only.
|
||||
// GetInfoOnly also opens a disk that is in use by a running virtual machine.
|
||||
func open(path string) (windows.Handle, error) {
|
||||
pathPtr, err := windows.UTF16PtrFromString(path)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("virtual disk %s: %w", path, err)
|
||||
}
|
||||
|
||||
var (
|
||||
storageType virtualStorageType
|
||||
handle windows.Handle
|
||||
)
|
||||
|
||||
params := openVirtualDiskParametersV2{Version: openVirtualDiskVersion2, GetInfoOnly: 1}
|
||||
|
||||
ret, _, _ := procOpenVirtualDisk.Call(
|
||||
uintptr(unsafe.Pointer(&storageType)),
|
||||
uintptr(unsafe.Pointer(pathPtr)),
|
||||
virtualDiskAccessNone,
|
||||
openVirtualDiskFlagNoParents,
|
||||
uintptr(unsafe.Pointer(¶ms)),
|
||||
uintptr(unsafe.Pointer(&handle)),
|
||||
)
|
||||
if ret != 0 {
|
||||
return 0, fmt.Errorf("OpenVirtualDisk %s: %w", path, windows.Errno(ret))
|
||||
}
|
||||
|
||||
return handle, nil
|
||||
}
|
||||
|
||||
func getInformation(handle windows.Handle, version uint32) (getVirtualDiskInfo, error) {
|
||||
info := getVirtualDiskInfo{Version: version}
|
||||
infoSize := uint32(unsafe.Sizeof(info))
|
||||
|
||||
ret, _, _ := procGetVirtualDiskInformation.Call(
|
||||
uintptr(handle),
|
||||
uintptr(unsafe.Pointer(&infoSize)),
|
||||
uintptr(unsafe.Pointer(&info)),
|
||||
0, // SizeUsed is optional
|
||||
)
|
||||
if ret != 0 {
|
||||
return getVirtualDiskInfo{}, windows.Errno(ret)
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// Copyright The Prometheus Authors
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build windows
|
||||
|
||||
package virtdisk
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var (
|
||||
procCreateVirtualDisk = modVirtdisk.NewProc("CreateVirtualDisk")
|
||||
|
||||
virtualStorageTypeVendorMicrosoft = windows.GUID{
|
||||
Data1: 0xEC984AEC, Data2: 0xA0F9, Data3: 0x47E9,
|
||||
Data4: [8]byte{0x90, 0x1F, 0x71, 0x41, 0x5A, 0x66, 0x34, 0x5B},
|
||||
}
|
||||
)
|
||||
|
||||
// createVirtualDiskParametersV2 is CREATE_VIRTUAL_DISK_PARAMETERS with
|
||||
// CREATE_VIRTUAL_DISK_VERSION_2, which VHDX requires. The union starts at offset 8.
|
||||
type createVirtualDiskParametersV2 struct {
|
||||
Version uint32
|
||||
_ uint32
|
||||
UniqueID windows.GUID
|
||||
MaximumSize uint64
|
||||
BlockSizeInBytes uint32
|
||||
SectorSizeInBytes uint32
|
||||
PhysicalSectorSizeInBytes uint32
|
||||
_ uint32
|
||||
ParentPath *uint16
|
||||
SourcePath *uint16
|
||||
OpenFlags uint32
|
||||
ParentVirtualStorageType virtualStorageType
|
||||
SourceVirtualStorageType virtualStorageType
|
||||
ResiliencyGUID windows.GUID
|
||||
}
|
||||
|
||||
const (
|
||||
createVirtualDiskVersion2 = 2
|
||||
createVirtualDiskFlagFullPhysicalAlloc = 0x1
|
||||
virtualStorageTypeDeviceVHDX = 3
|
||||
)
|
||||
|
||||
// createVHDX creates a VHDX for the test and closes it. Creating a virtual
|
||||
// disk needs administrator rights; the test is skipped without them.
|
||||
func createVHDX(t *testing.T, path string, size uint64, fixed bool) {
|
||||
t.Helper()
|
||||
|
||||
createVirtualDisk(t, path, createVirtualDiskParametersV2{Version: createVirtualDiskVersion2, MaximumSize: size}, fixed)
|
||||
}
|
||||
|
||||
// createDifferencingVHDX creates a differencing VHDX with parent as its parent.
|
||||
func createDifferencingVHDX(t *testing.T, path, parent string) {
|
||||
t.Helper()
|
||||
|
||||
parentPtr, err := windows.UTF16PtrFromString(parent)
|
||||
require.NoError(t, err)
|
||||
|
||||
createVirtualDisk(t, path, createVirtualDiskParametersV2{Version: createVirtualDiskVersion2, ParentPath: parentPtr}, false)
|
||||
}
|
||||
|
||||
func createVirtualDisk(t *testing.T, path string, params createVirtualDiskParametersV2, fixed bool) {
|
||||
t.Helper()
|
||||
|
||||
pathPtr, err := windows.UTF16PtrFromString(path)
|
||||
require.NoError(t, err)
|
||||
|
||||
storageType := virtualStorageType{DeviceID: virtualStorageTypeDeviceVHDX, VendorID: virtualStorageTypeVendorMicrosoft}
|
||||
|
||||
var flags uintptr
|
||||
if fixed {
|
||||
flags = createVirtualDiskFlagFullPhysicalAlloc
|
||||
}
|
||||
|
||||
var handle windows.Handle
|
||||
|
||||
ret, _, _ := procCreateVirtualDisk.Call(
|
||||
uintptr(unsafe.Pointer(&storageType)),
|
||||
uintptr(unsafe.Pointer(pathPtr)),
|
||||
virtualDiskAccessNone,
|
||||
0, // security descriptor
|
||||
flags,
|
||||
0, // provider specific flags
|
||||
uintptr(unsafe.Pointer(¶ms)),
|
||||
0, // overlapped
|
||||
uintptr(unsafe.Pointer(&handle)),
|
||||
)
|
||||
if errors.Is(windows.Errno(ret), windows.ERROR_ACCESS_DENIED) || errors.Is(windows.Errno(ret), windows.ERROR_PRIVILEGE_NOT_HELD) {
|
||||
t.Skipf("creating a virtual disk needs administrator rights: %v", windows.Errno(ret))
|
||||
}
|
||||
|
||||
require.Zero(t, ret, "CreateVirtualDisk: %v", windows.Errno(ret))
|
||||
require.NoError(t, windows.CloseHandle(handle))
|
||||
}
|
||||
|
||||
func TestAvailable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.NoError(t, Available())
|
||||
}
|
||||
|
||||
func TestGetInfo(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const size = 64 << 20 // 64 MiB
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
fixed bool
|
||||
subtype uint32
|
||||
}{
|
||||
"fixed": {true, ProviderSubtypeFixed},
|
||||
"dynamic": {false, ProviderSubtypeDynamic},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
path := filepath.Join(t.TempDir(), name+".vhdx")
|
||||
createVHDX(t, path, size, tc.fixed)
|
||||
|
||||
info, err := GetInfo(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(size), info.VirtualSize)
|
||||
require.Equal(t, tc.subtype, info.ProviderSubtype)
|
||||
|
||||
if tc.fixed {
|
||||
require.GreaterOrEqual(t, info.PhysicalSize, uint64(size))
|
||||
} else {
|
||||
require.Less(t, info.PhysicalSize, uint64(size))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetInfoMissingFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
path := filepath.Join(t.TempDir(), "missing.vhdx")
|
||||
|
||||
_, err := GetInfo(path)
|
||||
require.ErrorContains(t, err, path)
|
||||
}
|
||||
|
||||
func TestParentLocations(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := t.TempDir()
|
||||
parent := filepath.Join(dir, "parent.vhdx")
|
||||
child := filepath.Join(dir, "child.avhdx")
|
||||
|
||||
createVHDX(t, parent, 64<<20, false)
|
||||
createDifferencingVHDX(t, child, parent)
|
||||
|
||||
info, err := GetInfo(child)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ProviderSubtypeDifferencing, info.ProviderSubtype)
|
||||
|
||||
locations, err := ParentLocations(child)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Compare files, not strings: the temp dir can be a short 8.3 path
|
||||
// (RUNNER~1) while the disk records the long one.
|
||||
parentInfo, err := os.Stat(parent)
|
||||
require.NoError(t, err)
|
||||
require.Condition(t, func() bool {
|
||||
for _, location := range locations {
|
||||
if info, err := os.Stat(location); err == nil && os.SameFile(info, parentInfo) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}, "parent %s not in %v", parent, locations)
|
||||
|
||||
// A disk without a parent has no parent locations.
|
||||
locations, err = ParentLocations(parent)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, locations)
|
||||
}
|
||||
|
||||
func TestDecodeMultiString(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
in []uint16
|
||||
want []string
|
||||
}{
|
||||
"two": {append(append(windows.StringToUTF16(`..\parent.vhdx`), windows.StringToUTF16(`C:\vm\parent.vhdx`)...), 0), []string{`..\parent.vhdx`, `C:\vm\parent.vhdx`}},
|
||||
"one": {windows.StringToUTF16(`C:\vm\parent.vhd`), []string{`C:\vm\parent.vhd`}},
|
||||
"empty": {[]uint16{0, 0}, nil},
|
||||
"unterminated": {[]uint16{'a', 'b'}, []string{"ab"}},
|
||||
"nil": {nil, nil},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.Equal(t, tc.want, decodeMultiString(tc.in))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user