github.com/vmware/govmomi@v0.43.0/govc/vapp/power.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 "fmt" 23 24 "github.com/vmware/govmomi/govc/cli" 25 "github.com/vmware/govmomi/govc/flags" 26 "github.com/vmware/govmomi/object" 27 ) 28 29 type power struct { 30 *flags.SearchFlag 31 32 On bool 33 Off bool 34 Suspend bool 35 Force bool 36 } 37 38 func init() { 39 cli.Register("vapp.power", &power{}) 40 } 41 42 func (cmd *power) Register(ctx context.Context, f *flag.FlagSet) { 43 cmd.SearchFlag, ctx = flags.NewSearchFlag(ctx, flags.SearchVirtualApps) 44 cmd.SearchFlag.Register(ctx, f) 45 46 f.BoolVar(&cmd.On, "on", false, "Power on") 47 f.BoolVar(&cmd.Off, "off", false, "Power off") 48 f.BoolVar(&cmd.Suspend, "suspend", false, "Power suspend") 49 f.BoolVar(&cmd.Force, "force", false, "Force (If force is false, the shutdown order in the vApp is executed. If force is true, all virtual machines are powered-off (regardless of shutdown order))") 50 } 51 52 func (cmd *power) Process(ctx context.Context) error { 53 if err := cmd.SearchFlag.Process(ctx); err != nil { 54 return err 55 } 56 opts := []bool{cmd.On, cmd.Off, cmd.Suspend} 57 selected := false 58 59 for _, opt := range opts { 60 if opt { 61 if selected { 62 return flag.ErrHelp 63 } 64 selected = opt 65 } 66 } 67 68 if !selected { 69 return flag.ErrHelp 70 } 71 72 return nil 73 } 74 75 func (cmd *power) Run(ctx context.Context, f *flag.FlagSet) error { 76 vapps, err := cmd.VirtualApps(f.Args()) 77 if err != nil { 78 return err 79 } 80 81 for _, vapp := range vapps { 82 var task *object.Task 83 84 switch { 85 case cmd.On: 86 fmt.Fprintf(cmd, "Powering on %s... ", vapp.Reference()) 87 task, err = vapp.PowerOn(ctx) 88 case cmd.Off: 89 fmt.Fprintf(cmd, "Powering off %s... ", vapp.Reference()) 90 task, err = vapp.PowerOff(ctx, cmd.Force) 91 case cmd.Suspend: 92 fmt.Fprintf(cmd, "Suspend %s... ", vapp.Reference()) 93 task, err = vapp.Suspend(ctx) 94 } 95 96 if err != nil { 97 return err 98 } 99 100 if task != nil { 101 err = task.Wait(ctx) 102 } 103 if err == nil { 104 fmt.Fprintf(cmd, "OK\n") 105 continue 106 } 107 108 return err 109 } 110 111 return nil 112 }