github.com/vmware/govmomi@v0.51.0/cli/dvs/portgroup/spec.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package portgroup 6 7 import ( 8 "context" 9 "flag" 10 "fmt" 11 "strconv" 12 "strings" 13 14 "github.com/vmware/govmomi/cli/flags" 15 "github.com/vmware/govmomi/vim25/types" 16 ) 17 18 type VLANMode string 19 20 const ( 21 VLAN = VLANMode("vlan") 22 TrunkVLAN = VLANMode("trunking") 23 ) 24 25 type DVPortgroupConfigSpec struct { 26 types.DVPortgroupConfigSpec 27 } 28 29 var ( 30 vlanMode string 31 vlanId int32 32 vlanRange string 33 vlanSpec types.BaseVmwareDistributedVirtualSwitchVlanSpec 34 ) 35 36 func (spec *DVPortgroupConfigSpec) Register(ctx context.Context, f *flag.FlagSet) { 37 ptypes := types.DistributedVirtualPortgroupPortgroupType("").Strings() 38 39 vlanModes := []string{ 40 string(VLAN), 41 string(TrunkVLAN), 42 } 43 44 f.StringVar(&spec.Type, "type", ptypes[0], 45 fmt.Sprintf("Portgroup type (%s)", strings.Join(ptypes, "|"))) 46 f.Var(flags.NewInt32(&spec.NumPorts), "nports", "Number of ports") 47 f.Var(flags.NewInt32(&vlanId), "vlan", "VLAN ID") 48 f.StringVar(&vlanRange, "vlan-range", "0-4094", "VLAN Ranges with comma delimited") 49 f.StringVar(&vlanMode, "vlan-mode", "vlan", fmt.Sprintf("vlan mode (%s)", strings.Join(vlanModes, "|"))) 50 f.Var(flags.NewOptionalBool(&spec.AutoExpand), "auto-expand", "Ignore the limit on the number of ports") 51 } 52 53 func getRange(vlanRange string) []types.NumericRange { 54 nRanges := make([]types.NumericRange, 0) 55 strRanges := strings.Split(vlanRange, ",") 56 for _, v := range strRanges { 57 vlans := strings.Split(v, "-") 58 if len(vlans) != 2 { 59 panic(fmt.Sprintf("range %s does not follow format with vlanId-vlanId", v)) 60 } 61 start, err := strconv.Atoi(vlans[0]) 62 if err != nil { 63 panic(fmt.Sprintf("range %s does not follow format with vlanId-vlanId error: %v", v, err)) 64 } 65 end, err := strconv.Atoi(vlans[1]) 66 if err != nil { 67 panic(fmt.Sprintf("range %s does not follow format with vlanId-vlanId error: %v", v, err)) 68 } 69 nRanges = append(nRanges, types.NumericRange{ 70 Start: int32(start), 71 End: int32(end), 72 }) 73 } 74 return nRanges 75 } 76 77 func (spec *DVPortgroupConfigSpec) Spec() types.DVPortgroupConfigSpec { 78 config := new(types.VMwareDVSPortSetting) 79 switch VLANMode(vlanMode) { 80 case VLAN: 81 spec := new(types.VmwareDistributedVirtualSwitchVlanIdSpec) 82 spec.VlanId = vlanId 83 vlanSpec = spec 84 case TrunkVLAN: 85 spec := new(types.VmwareDistributedVirtualSwitchTrunkVlanSpec) 86 spec.VlanId = getRange(vlanRange) 87 vlanSpec = spec 88 } 89 config.Vlan = vlanSpec 90 spec.DefaultPortConfig = config 91 return spec.DVPortgroupConfigSpec 92 }