github.com/vmware/govmomi@v0.43.0/govc/vm/upgrade.go (about) 1 /* 2 Copyright (c) 2014-2022 VMware, Inc. All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package vm 18 19 import ( 20 "context" 21 "flag" 22 "fmt" 23 24 "github.com/vmware/govmomi/govc/cli" 25 "github.com/vmware/govmomi/govc/flags" 26 "github.com/vmware/govmomi/task" 27 "github.com/vmware/govmomi/vim25/types" 28 ) 29 30 type upgrade struct { 31 *flags.VirtualMachineFlag 32 version int 33 } 34 35 func init() { 36 cli.Register("vm.upgrade", &upgrade{}) 37 } 38 39 func isAlreadyUpgraded(err error) bool { 40 if fault, ok := err.(task.Error); ok { 41 _, ok = fault.Fault().(*types.AlreadyUpgraded) 42 return ok 43 } 44 45 return false 46 } 47 48 func (cmd *upgrade) Register(ctx context.Context, f *flag.FlagSet) { 49 cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx) 50 cmd.VirtualMachineFlag.Register(ctx, f) 51 52 f.IntVar(&cmd.version, "version", 0, "Target vm hardware version, by default -- latest available") 53 } 54 55 func (cmd *upgrade) Process(ctx context.Context) error { 56 if err := cmd.VirtualMachineFlag.Process(ctx); err != nil { 57 return err 58 } 59 return nil 60 } 61 62 func (cmd *upgrade) Description() string { 63 return `Upgrade VMs to latest hardware version 64 65 Examples: 66 govc vm.upgrade -vm $vm_name 67 govc vm.upgrade -version=$version -vm $vm_name 68 govc vm.upgrade -version=$version -vm.uuid $vm_uuid` 69 } 70 71 func (cmd *upgrade) Run(ctx context.Context, f *flag.FlagSet) error { 72 vm, err := cmd.VirtualMachine() 73 if err != nil { 74 return err 75 } 76 77 var version = "" 78 if cmd.version != 0 { 79 version = fmt.Sprintf("vmx-%02d", cmd.version) 80 } 81 82 task, err := vm.UpgradeVM(ctx, version) 83 if err != nil { 84 return err 85 } 86 err = task.Wait(ctx) 87 if err != nil { 88 if isAlreadyUpgraded(err) { 89 fmt.Println(err.Error()) 90 } else { 91 return err 92 } 93 } 94 95 return nil 96 }