github.com/vmware/govmomi@v0.43.0/govc/cluster/group/info_flag.go (about) 1 /* 2 Copyright (c) 2017 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 group 18 19 import ( 20 "context" 21 "flag" 22 "fmt" 23 24 "github.com/vmware/govmomi/govc/flags" 25 "github.com/vmware/govmomi/vim25/types" 26 ) 27 28 type InfoFlag struct { 29 *flags.ClusterFlag 30 31 groups []types.BaseClusterGroupInfo 32 33 name string 34 } 35 36 func NewInfoFlag(ctx context.Context) (*InfoFlag, context.Context) { 37 f := &InfoFlag{} 38 f.ClusterFlag, ctx = flags.NewClusterFlag(ctx) 39 return f, ctx 40 } 41 42 func (f *InfoFlag) Register(ctx context.Context, fs *flag.FlagSet) { 43 f.ClusterFlag.Register(ctx, fs) 44 45 fs.StringVar(&f.name, "name", "", "Cluster group name") 46 } 47 48 func (f *InfoFlag) Process(ctx context.Context) error { 49 return f.ClusterFlag.Process(ctx) 50 } 51 52 func (f *InfoFlag) Groups(ctx context.Context) ([]types.BaseClusterGroupInfo, error) { 53 if f.groups != nil { 54 return f.groups, nil 55 } 56 57 cluster, err := f.Cluster() 58 if err != nil { 59 return nil, err 60 } 61 62 config, err := cluster.Configuration(ctx) 63 if err != nil { 64 return nil, err 65 } 66 67 f.groups = config.Group 68 69 return f.groups, nil 70 } 71 72 type ClusterGroupInfo struct { 73 info types.BaseClusterGroupInfo 74 75 refs *[]types.ManagedObjectReference 76 77 kind string 78 } 79 80 func newGroupInfo(info types.BaseClusterGroupInfo) *ClusterGroupInfo { 81 group := &ClusterGroupInfo{info: info} 82 83 switch info := info.(type) { 84 case *types.ClusterHostGroup: 85 group.refs = &info.Host 86 group.kind = "HostSystem" 87 case *types.ClusterVmGroup: 88 group.refs = &info.Vm 89 group.kind = "VirtualMachine" 90 } 91 92 return group 93 } 94 95 func (f *InfoFlag) Group(ctx context.Context) (*ClusterGroupInfo, error) { 96 groups, err := f.Groups(ctx) 97 if err != nil { 98 return nil, err 99 } 100 101 for _, group := range groups { 102 if group.GetClusterGroupInfo().Name == f.name { 103 return newGroupInfo(group), nil 104 } 105 } 106 107 return nil, fmt.Errorf("group %q not found", f.name) 108 } 109 110 func (f *InfoFlag) Apply(ctx context.Context, update types.ArrayUpdateSpec, info types.BaseClusterGroupInfo) error { 111 spec := &types.ClusterConfigSpecEx{ 112 GroupSpec: []types.ClusterGroupSpec{ 113 { 114 ArrayUpdateSpec: update, 115 Info: info, 116 }, 117 }, 118 } 119 120 return f.Reconfigure(ctx, spec) 121 }