hyperv: lookup machine on local filesystem first

when looking for a machine, look it up locally first to prevent
accidental collision with non-podman machine vms.  in the cast of
`podman machine ls`, only list podman machines found by json files

Enabled remove with force.

[NO NEW TESTS NEEDED]

Signed-off-by: Brent Baude <bbaude@redhat.com>
This commit is contained in:
Brent Baude
2023-03-22 15:29:24 -05:00
parent 67c98ec5de
commit 518eafaa34
15 changed files with 232 additions and 54 deletions

View File

@@ -68,7 +68,6 @@ const (
ErrShutdownInProgress = 32782
)
type shutdownCompError struct {
errorCode int
message string
@@ -114,4 +113,45 @@ func translateShutdownError(code int) error {
}
return &shutdownCompError{code, message}
}
}
// Modify resource errors
const (
ErrModifyResourceNotSupported = 1
ErrModifyResourceFailed = 2
ErrModifyResourceTimeout = 3
ErrModifyResourceInvalidParameter = 4
ErrModifyResourceInvalidState = 5
ErrModifyResourceIncompatParam = 6
)
type modifyResourceError struct {
errorCode int
message string
}
func (m *modifyResourceError) Error() string {
return fmt.Sprintf("%s (%d)", m.message, m.errorCode)
}
func translateModifyError(code int) error {
var message string
switch code {
case ErrModifyResourceNotSupported:
message = "virtual machine does not support modification operations"
case ErrModifyResourceFailed:
message = "resource modification failed"
case ErrModifyResourceTimeout:
message = "timeout modifying resource"
case ErrModifyResourceInvalidParameter:
message = "a modify resource operation was passed an invalid parameter"
case ErrModifyResourceInvalidState:
message = "the requested modification could not be applied due to an invalid state"
case ErrModifyResourceIncompatParam:
message = "an incompatible parameter was passed to a modify resource operation"
default:
message = "unknown error"
}
return &modifyResourceError{code, message}
}

View File

@@ -3,6 +3,8 @@
package hypervctl
import "fmt"
const MemoryResourceType = "Microsoft:Hyper-V:Memory"
type MemorySettings struct {
@@ -41,7 +43,11 @@ type MemorySettings struct {
}
func createMemorySettings(settings *MemorySettings) (string, error) {
return createResourceSettingGeneric(settings, MemoryResourceType)
str, err := createResourceSettingGeneric(settings, MemoryResourceType)
if err != nil {
err = fmt.Errorf("could not create memory settings: %w", err)
}
return str, err
}
func fetchDefaultMemorySettings() (*MemorySettings, error) {

View File

@@ -3,6 +3,8 @@
package hypervctl
import "fmt"
const ProcessorResourceType = "Microsoft:Hyper-V:Processor"
/*
@@ -88,5 +90,9 @@ func fetchDefaultProcessorSettings() (*ProcessorSettings, error) {
}
func createProcessorSettings(settings *ProcessorSettings) (string, error) {
return createResourceSettingGeneric(settings, ProcessorResourceType)
str, err := createResourceSettingGeneric(settings, ProcessorResourceType)
if err != nil {
err = fmt.Errorf("could not create processor settings: %w", err)
}
return str, err
}

View File

@@ -46,12 +46,11 @@ const (
SummaryRequestOtherEnabledState = 132
)
type SummaryRequestSet []uint
var (
// SummaryRequestCommon includes a smaller subset of commonly used fields
// SummaryRequestCommon includes a smaller subset of commonly used fields
SummaryRequestCommon = SummaryRequestSet{
SummaryRequestName,
SummaryRequestElementName,
@@ -72,7 +71,7 @@ var (
SummaryRequestSwapFilesInUse,
}
// SummaryRequestNearAll includes everything but load history and thumbnails
// SummaryRequestNearAll includes everything but load history and thumbnails
SummaryRequestNearAll = SummaryRequestSet{
SummaryRequestName,
SummaryRequestElementName,

View File

@@ -174,7 +174,7 @@ func addResource(service *wmiext.Service, systemSettingPath string, resourceSett
return "", fmt.Errorf("AddResourceSettings failed: %w", err)
}
err = waitVMResult(res, service, job)
err = waitVMResult(res, service, job, "failed to add resource", nil)
if len(resultingSettings) > 0 {
return resultingSettings[0], err

View File

@@ -139,9 +139,9 @@ func (builder *SystemSettingsBuilder) Build() (*SystemSettings, error) {
return nil, fmt.Errorf("failed to define system: %w", err)
}
err = waitVMResult(res, service, job)
err = waitVMResult(res, service, job, "failed to define system", nil)
if err != nil {
return nil, fmt.Errorf("failed to define system: %w", err)
return nil, err
}
newSettings, err := service.FindFirstRelatedInstance(resultingSystem, "Msvm_VirtualSystemSettingData")

View File

@@ -183,18 +183,27 @@ func (vm *VirtualMachine) kvpOperation(op string, key string, value string, ille
return err
}
func waitVMResult(res int32, service *wmiext.Service, job *wmiext.Instance) error {
func waitVMResult(res int32, service *wmiext.Service, job *wmiext.Instance, errorMsg string, translate func(int) error) error {
var err error
if res == 4096 {
switch res {
case 0:
return nil
case 4096:
err = wmiext.WaitJob(service, job)
defer job.Close()
default:
if translate != nil {
return translate(int(res))
}
return fmt.Errorf("%s (result code %d)", errorMsg, res)
}
if err != nil {
desc, _ := job.GetAsString("ErrorDescription")
desc = strings.Replace(desc, "\n", " ", -1)
return fmt.Errorf("failed to define system: %w (%s)", err, desc)
return fmt.Errorf("%s: %w (%s)", errorMsg, err, desc)
}
return err
@@ -270,7 +279,7 @@ func (vm *VirtualMachine) Start() error {
Out("ReturnValue", &res).End(); err != nil {
return err
}
return waitVMResult(res, srv, job)
return waitVMResult(res, srv, job, "failed to start vm", nil)
}
func getService(_ *wmiext.Service) (*wmiext.Service, error) {
@@ -328,7 +337,7 @@ func (vm *VirtualMachine) GetSummaryInformation(requestedFields SummaryRequestSe
}
defer service.Close()
instance, err := service.FindFirstRelatedInstance(vm.Path(), "Msvm_VirtualSystemSettingData")
instance, err := vm.fetchSystemSettingsInstance(service)
if err != nil {
return nil, err
}
@@ -418,6 +427,98 @@ func (vmm *VirtualMachineManager) NewVirtualMachine(name string, config *Hardwar
return nil
}
func (vm *VirtualMachine) fetchSystemSettingsInstance(service *wmiext.Service) (*wmiext.Instance, error) {
// When a settings snapshot is taken there are multiple associations, use only the realized/active version
return service.FindFirstRelatedInstanceThrough(vm.Path(), "Msvm_VirtualSystemSettingData", "Msvm_SettingsDefineState")
}
func (vm *VirtualMachine) fetchExistingResourceSettings(service *wmiext.Service, resourceType string, resourceSettings interface{}) error {
const errFmt = "could not fetch resource settings (%s): %w"
// When a settings snapshot is taken there are multiple associations, use only the realized/active version
instance, err := vm.fetchSystemSettingsInstance(service)
if err != nil {
return fmt.Errorf(errFmt, resourceType, err)
}
defer instance.Close()
path, err := instance.Path()
if err != nil {
return fmt.Errorf(errFmt, resourceType, err)
}
return service.FindFirstRelatedObject(path, resourceType, resourceSettings)
}
// Update processor and/or mem
func (vm *VirtualMachine) UpdateProcessorMemSettings(updateProcessor func(*ProcessorSettings), updateMemory func(*MemorySettings)) error {
service, err := wmiext.NewLocalService(HyperVNamespace)
if err != nil {
return err
}
defer service.Close()
proc := &ProcessorSettings{}
mem := &MemorySettings{}
var settings []string
if updateProcessor != nil {
err = vm.fetchExistingResourceSettings(service, "Msvm_ProcessorSettingData", proc)
if err != nil {
return err
}
updateProcessor(proc)
processorStr, err := createProcessorSettings(proc)
if err != nil {
return err
}
settings = append(settings, processorStr)
}
if updateMemory != nil {
err = vm.fetchExistingResourceSettings(service, "Msvm_MemorySettingData", mem)
if err != nil {
return err
}
updateMemory(mem)
memStr, err := createMemorySettings(mem)
if err != nil {
return err
}
settings = append(settings, memStr)
}
if len(settings) < 1 {
return nil
}
vsms, err := service.GetSingletonInstance("Msvm_VirtualSystemManagementService")
if err != nil {
return err
}
defer vsms.Close()
var job *wmiext.Instance
var res int32
err = vsms.BeginInvoke("ModifyResourceSettings").
In("ResourceSettings", settings).
Execute().
Out("Job", &job).
Out("ReturnValue", &res).
End()
if err != nil {
return fmt.Errorf("failed to modify resource settings: %w", err)
}
return waitVMResult(res, service, job, "failed to modify resource settings", translateModifyError)
}
func (vm *VirtualMachine) remove() (int32, error) {
var (
err error
@@ -433,7 +534,7 @@ func (vm *VirtualMachine) remove() (int32, error) {
return -1, err
}
wmiInst, err := srv.FindFirstRelatedInstance(vm.Path(), "Msvm_VirtualSystemSettingData")
wmiInst, err := vm.fetchSystemSettingsInstance(srv)
if err != nil {
return -1, err
}
@@ -448,7 +549,7 @@ func (vm *VirtualMachine) remove() (int32, error) {
if err != nil {
return -1, err
}
defer wmiInst.Close()
defer vsms.Close()
var (
job *wmiext.Instance
@@ -465,7 +566,7 @@ func (vm *VirtualMachine) remove() (int32, error) {
}
// do i have this correct? you can get an error without a result?
if err := waitVMResult(res, srv, job); err != nil {
if err := waitVMResult(res, srv, job, "failed to remove vm", nil); err != nil {
return -1, err
}
return res, nil

View File

@@ -138,7 +138,7 @@ func (*VirtualMachineManager) CreateVhdxFile(path string, maxSize uint64) error
return fmt.Errorf("failed to create vhdx: %w", err)
}
return waitVMResult(ret, service, job)
return waitVMResult(ret, service, job, "failed to create vhdx", nil)
}
// GetSummaryInformation returns the live VM summary information for all virtual machines.

View File

@@ -17,8 +17,8 @@ import (
)
var (
unixEpoch = time.Unix(0,0)
zeroTime = time.Time{}
unixEpoch = time.Unix(0, 0)
zeroTime = time.Time{}
)
// Automation variants do not follow the OLE rules, instead they use the following mapping:
@@ -346,7 +346,7 @@ func convertTimeToDataTime(time *time.Time) ole.VARIANT {
return ole.NewVariant(ole.VT_BSTR, int64(uintptr(unsafe.Pointer(ole.SysAllocStringLen(s)))))
}
func convertDurationToDateTime(duration time.Duration) ole.VARIANT {
func convertDurationToDateTime(duration time.Duration) ole.VARIANT {
const daySeconds = time.Second * 86400
if duration == 0 {
@@ -367,7 +367,7 @@ func convertDurationToDateTime(duration time.Duration) ole.VARIANT {
micros := duration / time.Microsecond
s:=fmt.Sprintf("%08d%02d%02d%02d.%06d:000", days, hours, mins, seconds, micros)
s := fmt.Sprintf("%08d%02d%02d%02d.%06d:000", days, hours, mins, seconds, micros)
return ole.NewVariant(ole.VT_BSTR, int64(uintptr(unsafe.Pointer(ole.SysAllocStringLen(s)))))
}
@@ -426,7 +426,7 @@ func parseIntervalTime(interval string) (time.Time, error) {
}
days, err := parseUintChain(interval[0:8], nil)
hours, err := parseUintChain(interval[8:10], err)
hours, err := parseUintChain(interval[8:10], err)
mins, err := parseUintChain(interval[10:12], err)
secs, err := parseUintChain(interval[12:14], err)
micros, err := parseUintChain(interval[15:21], err)
@@ -440,7 +440,7 @@ func parseIntervalTime(interval string) (time.Time, error) {
stamp += hours * 3600
stamp += mins * 60
return time.Unix(int64(stamp), int64(micros * 1000)), nil
return time.Unix(int64(stamp), int64(micros*1000)), nil
}
func convertIntervalToDuration(variant *ole.VARIANT) (time.Duration, error) {
@@ -465,7 +465,6 @@ func parseUintChain(str string, err error) (uint64, error) {
return strconv.ParseUint(str, 10, 0)
}
func abs(num int) int {
if num < 0 {
return -num

View File

@@ -306,6 +306,20 @@ func (s *Service) FindFirstRelatedInstance(objPath string, className string) (*I
return s.FindFirstInstance(wql)
}
// FindFirstRelatedInstanceThrough finds and returns a related associator of the specified WMI object path of the
// expected className type, and only through the expected association type.
func (s *Service) FindFirstRelatedInstanceThrough(objPath string, resultClass string, assocClass string) (*Instance, error) {
wql := fmt.Sprintf("ASSOCIATORS OF {%s} WHERE AssocClass = %s ResultClass = %s ", objPath, assocClass, resultClass)
return s.FindFirstInstance(wql)
}
// FindFirstRelatedObject finds and returns a related associator of the specified WMI object path of the
// expected className type, and populates the passed in struct with its fields
func (s *Service) FindFirstRelatedObject(objPath string, className string, target interface{}) error {
wql := fmt.Sprintf("ASSOCIATORS OF {%s} WHERE ResultClass = %s", objPath, className)
return s.FindFirstObject(wql, target)
}
// FindFirstObject finds and returns the first WMI Instance in the result set for a WSL query, and
// populates the specified struct pointer passed in through the target parameter.
func (s *Service) FindFirstObject(wql string, target interface{}) error {