1/* 2Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package vm 18 19import ( 20 "context" 21 "flag" 22 23 "github.com/vmware/govmomi/govc/cli" 24 "github.com/vmware/govmomi/govc/flags" 25) 26 27type destroy struct { 28 *flags.ClientFlag 29 *flags.SearchFlag 30} 31 32func init() { 33 cli.Register("vm.destroy", &destroy{}) 34} 35 36func (cmd *destroy) Register(ctx context.Context, f *flag.FlagSet) { 37 cmd.ClientFlag, ctx = flags.NewClientFlag(ctx) 38 cmd.ClientFlag.Register(ctx, f) 39 40 cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualMachines) 41 cmd.SearchFlag.Register(ctx, f) 42} 43 44func (cmd *destroy) Process(ctx context.Context) error { 45 if err := cmd.ClientFlag.Process(ctx); err != nil { 46 return err 47 } 48 if err := cmd.SearchFlag.Process(ctx); err != nil { 49 return err 50 } 51 return nil 52} 53 54func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error { 55 vms, err := cmd.VirtualMachines(f.Args()) 56 if err != nil { 57 return err 58 } 59 60 for _, vm := range vms { 61 task, err := vm.PowerOff(ctx) 62 if err != nil { 63 return err 64 } 65 66 // Ignore error since the VM may already been in powered off state. 67 // vm.Destroy will fail if the VM is still powered on. 68 _ = task.Wait(ctx) 69 70 task, err = vm.Destroy(ctx) 71 if err != nil { 72 return err 73 } 74 75 err = task.Wait(ctx) 76 if err != nil { 77 return err 78 } 79 } 80 81 return nil 82} 83