github.com/vmware/govmomi@v0.51.0/cli/gpu/vm/remove.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package vm 6 7 import ( 8 "context" 9 "flag" 10 "fmt" 11 12 "github.com/vmware/govmomi/cli" 13 "github.com/vmware/govmomi/cli/flags" 14 "github.com/vmware/govmomi/property" 15 "github.com/vmware/govmomi/vim25/mo" 16 "github.com/vmware/govmomi/vim25/types" 17 ) 18 19 type remove struct { 20 *flags.ClientFlag 21 *flags.VirtualMachineFlag 22 } 23 24 func init() { 25 cli.Register("gpu.vm.remove", &remove{}) 26 } 27 28 func (cmd *remove) Register(ctx context.Context, f *flag.FlagSet) { 29 cmd.ClientFlag, ctx = flags.NewClientFlag(ctx) 30 cmd.ClientFlag.Register(ctx, f) 31 32 cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx) 33 cmd.VirtualMachineFlag.Register(ctx, f) 34 } 35 36 func (cmd *remove) Description() string { 37 return `Remove all vGPUs from VM. 38 39 Examples: 40 govc gpu.vm.remove -vm $vm` 41 } 42 43 func (cmd *remove) Process(ctx context.Context) error { 44 if err := cmd.ClientFlag.Process(ctx); err != nil { 45 return err 46 } 47 if err := cmd.VirtualMachineFlag.Process(ctx); err != nil { 48 return err 49 } 50 return nil 51 } 52 53 func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error { 54 vm, err := cmd.VirtualMachineFlag.VirtualMachine() 55 if err != nil { 56 return err 57 } 58 59 if vm == nil { 60 return flag.ErrHelp 61 } 62 63 // Check power state and get device list 64 var o mo.VirtualMachine 65 pc := property.DefaultCollector(vm.Client()) 66 err = pc.RetrieveOne(ctx, vm.Reference(), []string{"runtime.powerState", "config.hardware"}, &o) 67 if err != nil { 68 return err 69 } 70 71 if o.Runtime.PowerState == types.VirtualMachinePowerStatePoweredOn { 72 return fmt.Errorf("VM must be powered off to remove vGPU") 73 } 74 75 if o.Config == nil { 76 return fmt.Errorf("failed to get VM configuration") 77 } 78 79 // Find vGPU devices 80 var deviceChanges []types.BaseVirtualDeviceConfigSpec 81 for _, device := range o.Config.Hardware.Device { 82 if pci, ok := device.(*types.VirtualPCIPassthrough); ok { 83 if _, ok := pci.Backing.(*types.VirtualPCIPassthroughVmiopBackingInfo); ok { 84 spec := &types.VirtualDeviceConfigSpec{ 85 Operation: types.VirtualDeviceConfigSpecOperationRemove, 86 Device: pci, 87 } 88 deviceChanges = append(deviceChanges, spec) 89 } 90 } 91 } 92 93 if len(deviceChanges) == 0 { 94 return fmt.Errorf("no vGPU devices found") 95 } 96 97 vmConfigSpec := types.VirtualMachineConfigSpec{ 98 DeviceChange: deviceChanges, 99 } 100 101 task, err := vm.Reconfigure(ctx, vmConfigSpec) 102 if err != nil { 103 return err 104 } 105 106 return task.Wait(ctx) 107 }