github.com/vmware/govmomi@v0.43.0/govc/vapp/destroy.go (about) 1 /* 2 Copyright (c) 2015 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 vapp 18 19 import ( 20 "context" 21 "flag" 22 23 "github.com/vmware/govmomi/find" 24 "github.com/vmware/govmomi/govc/cli" 25 "github.com/vmware/govmomi/govc/flags" 26 "github.com/vmware/govmomi/vim25/types" 27 ) 28 29 type destroy struct { 30 *flags.DatacenterFlag 31 } 32 33 func init() { 34 cli.Register("vapp.destroy", &destroy{}) 35 } 36 37 func (cmd *destroy) Register(ctx context.Context, f *flag.FlagSet) { 38 cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx) 39 cmd.DatacenterFlag.Register(ctx, f) 40 } 41 42 func (cmd *destroy) Process(ctx context.Context) error { 43 if err := cmd.DatacenterFlag.Process(ctx); err != nil { 44 return err 45 } 46 return nil 47 } 48 49 func (cmd *destroy) Usage() string { 50 return "VAPP..." 51 } 52 53 func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error { 54 if f.NArg() == 0 { 55 return flag.ErrHelp 56 } 57 58 finder, err := cmd.Finder() 59 if err != nil { 60 return err 61 } 62 63 for _, arg := range f.Args() { 64 vapps, err := finder.VirtualAppList(ctx, arg) 65 if err != nil { 66 if _, ok := err.(*find.NotFoundError); ok { 67 // Ignore if vapp cannot be found 68 continue 69 } 70 71 return err 72 } 73 74 for _, vapp := range vapps { 75 powerOff := func() error { 76 task, err := vapp.PowerOff(ctx, false) 77 if err != nil { 78 return err 79 } 80 err = task.Wait(ctx) 81 if err != nil { 82 // it's safe to ignore if the vapp is already powered off 83 if f, ok := err.(types.HasFault); ok { 84 switch f.Fault().(type) { 85 case *types.InvalidPowerState: 86 return nil 87 } 88 } 89 return err 90 } 91 return nil 92 } 93 if err := powerOff(); err != nil { 94 return err 95 } 96 97 destroy := func() error { 98 task, err := vapp.Destroy(ctx) 99 if err != nil { 100 return err 101 } 102 err = task.Wait(ctx) 103 if err != nil { 104 return err 105 } 106 return nil 107 } 108 if err := destroy(); err != nil { 109 return err 110 } 111 } 112 } 113 114 return nil 115 }