Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add load balancer server pool CRUD #205

Merged
merged 9 commits into from
Jul 1, 2019
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

* Added edge gateway create/delete functions [#130](https://github.com/vmware/go-vcloud-director/issues/130).
* Added load balancer service monitor [#196](https://github.com/vmware/go-vcloud-director/pull/196)
* Added load balancer server pool [#205](https://github.com/vmware/go-vcloud-director/pull/205)

## 2.2.0 (May 15, 2019)

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module github.com/vmware/go-vcloud-director/v2

require (
github.com/hashicorp/go-version v1.1.0
github.com/kr/pretty v0.1.0
github.com/kr/pretty v0.1.0 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127
gopkg.in/yaml.v2 v2.2.2
)
3 changes: 1 addition & 2 deletions govcd/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ At least one of the following tags should be defined:
* ALL : Runs all the tests (== functional + unit == all feature tests)

* functional: Runs all the tests that use check.v1
* unit: Runs unit tests that do not use check.v1
and don't need a live vCD (currently unused, but we plan to)
* unit: Runs unit tests that do not use check.v1 and don't need a live vCD

* catalog: Runs catalog related tests (also catalog_item, media)
* disk: Runs disk related tests
Expand Down
103 changes: 87 additions & 16 deletions govcd/api_vcd_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// +build api functional catalog vapp gateway network org query extnetwork task vm vdc system disk ALL
// +build api functional catalog vapp gateway network org query extnetwork task vm vdc system disk lbServerPool lbServiceMonitor ALL

/*
* Copyright 2019 VMware, Inc. All rights reserved. Licensed under the Apache v2 License.
Expand Down Expand Up @@ -57,7 +57,8 @@ const (
TestVMDetachDisk = "TestVMDetachDisk"
TestCreateExternalNetwork = "TestCreateExternalNetwork"
TestDeleteExternalNetwork = "TestDeleteExternalNetwork"
Test_LBServiceMonitor = "Test_LBServiceMonitor"
Test_LBServiceMonitor = "TestLBServiceMonitor"
Test_LBServerPool = "TestLBServerPool"
)

const (
Expand Down Expand Up @@ -328,10 +329,13 @@ func (vcd *TestVCD) infoCleanup(format string, args ...interface{}) {
}
}

// Gets the two components of a "parent" string, as passed to AddToCleanupList
// Gets the two or three components of a "parent" string, as passed to AddToCleanupList
// If the number of split strings is not 2 or 3 it return 3 empty strings
// Example input parent: my-org|my-vdc|my-edge-gw, separator: |
// Output output: first: my-org, second: my-vdc, third: my-edge-gw
func splitParent(parent string, separator string) (first, second, third string) {
strList := strings.Split(parent, separator)
if len(strList) < 2 && len(strList) > 3 {
if len(strList) < 2 || len(strList) > 3 {
return "", "", ""
}
first = strList[0]
Expand All @@ -344,6 +348,27 @@ func splitParent(parent string, separator string) (first, second, third string)
return
}

func getOrgVdcEdgeByNames(vcd *TestVCD, orgName, vdcName, edgeName string) (Org, Vdc, EdgeGateway, error) {
if orgName == "" || vdcName == "" || edgeName == "" {
return Org{}, Vdc{}, EdgeGateway{}, fmt.Errorf("orgName, vdcName, edgeName cant be empty")
}

org, err := GetOrgByName(vcd.client, orgName)
if err != nil {
vcd.infoCleanup("could not find org '%s'", orgName)
}
vdc, err := org.GetVdcByName(vdcName)
if err != nil {
vcd.infoCleanup("could not find vdc '%s'", vdcName)
}

edge, err := vdc.FindEdgeGateway(edgeName)
if err != nil {
vcd.infoCleanup("could not find edge '%s'", vdcName)
}
return org, vdc, edge, nil
}

var splitParentNotFound string = "removeLeftoverEntries: [ERROR] missing parent info (%s). The parent fields must be defined with a separator '|'\n"
var notFoundMsg string = "removeLeftoverEntries: [INFO] No action for %s '%s'\n"

Expand Down Expand Up @@ -631,21 +656,34 @@ func (vcd *TestVCD) removeLeftoverEntities(entity CleanupEntity) {

orgName, vdcName, edgeName := splitParent(entity.Parent, "|")

org, err := GetOrgByName(vcd.client, orgName)
_, _, edge, err := getOrgVdcEdgeByNames(vcd, orgName, vdcName, edgeName)
if err != nil {
vcd.infoCleanup("removeLeftoverEntries: [ERROR] Could not find org '%s'\n", orgName)
vcd.infoCleanup("removeLeftoverEntries: [ERROR] %s \n", err)
}
vdc, err := org.GetVdcByName(vdcName)

err = edge.DeleteLBServiceMonitor(&types.LBMonitor{Name: entity.Name})
if err != nil {
vcd.infoCleanup("removeLeftoverEntries: [ERROR] Could not find vdc '%s'\n", vdcName)
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
}

vcd.infoCleanup(removedMsg, entity.EntityType, entity.Name, entity.CreatedBy)
return

case "lbServerPool":
if entity.Parent == "" {
vcd.infoCleanup("removeLeftoverEntries: [ERROR] No parent specified '%s'\n", entity.Name)
return
}

edge, err := vdc.FindEdgeGateway(edgeName)
orgName, vdcName, edgeName := splitParent(entity.Parent, "|")

_, _, edge, err := getOrgVdcEdgeByNames(vcd, orgName, vdcName, edgeName)
if err != nil {
vcd.infoCleanup("removeLeftoverEntries: [ERROR] Could not find edge '%s'\n", vdcName)
vcd.infoCleanup("removeLeftoverEntries: [ERROR] %s \n", err)
}

err = edge.DeleteLBServiceMonitor(&types.LBMonitor{Name: entity.Name})
err = edge.DeleteLBServerPool(&types.LBPool{Name: entity.Name})
if err != nil {
vcd.infoCleanup(notFoundMsg, entity.EntityType, entity.Name)
return
Expand Down Expand Up @@ -763,10 +801,6 @@ func (vcd *TestVCD) createTestVapp(name string) (VApp, error) {
return vapp, err
}

func init() {
testingTags["api"] = "api_vcd_test.go"
}

func Test_splitParent(t *testing.T) {
type args struct {
parent string
Expand All @@ -779,7 +813,40 @@ func Test_splitParent(t *testing.T) {
wantSecond string
wantThird string
}{
// TODO: Add test cases.
{
name: "Empty",
args: args{parent: "", separator: "|"},
wantFirst: "",
wantSecond: "",
wantThird: "",
},
{
name: "One",
wantFirst: "",
wantSecond: "",
wantThird: "",
},
{
name: "Two",
args: args{parent: "first|second", separator: "|"},
wantFirst: "first",
wantSecond: "second",
wantThird: "",
},
{
name: "Three",
args: args{parent: "first|second|third", separator: "|"},
wantFirst: "first",
wantSecond: "second",
wantThird: "third",
},
{
name: "Four",
args: args{parent: "first|second|third|fourth", separator: "|"},
wantFirst: "",
wantSecond: "",
wantThird: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand All @@ -796,3 +863,7 @@ func Test_splitParent(t *testing.T) {
})
}
}

func init() {
testingTags["api"] = "api_vcd_test.go"
}
193 changes: 193 additions & 0 deletions govcd/lbserverpool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package govcd

/*
* Copyright 2019 VMware, Inc. All rights reserved. Licensed under the Apache v2 License.
*/

import (
"fmt"
"net/http"
"strings"

"github.com/vmware/go-vcloud-director/v2/types/v56"
)

// CreateLBServerPool creates a load balancer server pool based on mandatory fields. It is a synchronous
// operation. It returns created object with all fields (including ID) populated or an error.
// Name and Algorithm fields must be populated.
func (eGW *EdgeGateway) CreateLBServerPool(lbPoolConfig *types.LBPool) (*types.LBPool, error) {
if err := validateCreateLBServerPool(lbPoolConfig); err != nil {
return nil, err
}

httpPath, err := eGW.buildProxiedEdgeEndpointURL(types.LBServerPoolPath)
if err != nil {
return nil, fmt.Errorf("could not get Edge Gateway API endpoint: %s", err)
}
// We expect to get http.StatusCreated or if not an error of type types.NSXError
resp, err := eGW.client.ExecuteRequestWithCustomError(httpPath, http.MethodPost, types.AnyXMLMime,
"error creating load balancer server pool: %s", lbPoolConfig, &types.NSXError{})
if err != nil {
return nil, err
}
location := resp.Header.Get("Location")

// Last element in location header is the server pool ID
// i.e. Location: [/network/edges/edge-3/loadbalancer/config/pools/pool-7]
if location == "" {
return nil, fmt.Errorf("unable to retrieve ID for new load balancer server pool with name %s", lbPoolConfig.Name)
}
splitLocation := strings.Split(location, "/")
lbPoolID := splitLocation[len(splitLocation)-1]
readPool, err := eGW.ReadLBServerPool(&types.LBPool{ID: lbPoolID})
if err != nil {
return nil, fmt.Errorf("unable to retrieve lb server pool with ID (%s) after creation: %s", readPool.ID, err)
}
return readPool, nil
}

// ReadLBServerPool is able to find the types.LBPool type by Name and/or ID.
// If both - Name and ID are specified it performs a lookup by ID and returns an error if the specified name and found
// name do not match.
func (eGW *EdgeGateway) ReadLBServerPool(lbPoolConfig *types.LBPool) (*types.LBPool, error) {
if err := validateReadLBServerPool(lbPoolConfig); err != nil {
return nil, err
}

httpPath, err := eGW.buildProxiedEdgeEndpointURL(types.LBServerPoolPath)
if err != nil {
return nil, fmt.Errorf("could not get Edge Gateway API endpoint: %s", err)
}

// Anonymous struct to unwrap "server pool response"
lbPoolResponse := &struct {
LBPools []*types.LBPool `xml:"pool"`
}{}

// This query returns all server pools as the API does not have filtering options
_, err = eGW.client.ExecuteRequest(httpPath, http.MethodGet, types.AnyXMLMime,
"unable to read load lalancer server pool: %s", nil, lbPoolResponse)
if err != nil {
return nil, err
}

// Search for pool by ID or by Name
for _, pool := range lbPoolResponse.LBPools {
// If ID was specified for lookup - look for the same ID
if lbPoolConfig.ID != "" && pool.ID == lbPoolConfig.ID {
return pool, nil
}

// If Name was specified for lookup - look for the same Name
if lbPoolConfig.Name != "" && pool.Name == lbPoolConfig.Name {
// We found it by name. Let's verify if search ID was specified and it matches the lookup object
if lbPoolConfig.ID != "" && pool.ID != lbPoolConfig.ID {
return nil, fmt.Errorf("load balancer server pool was found by name (%s), but it's ID (%s) does not match specified ID (%s)",
pool.Name, pool.ID, lbPoolConfig.ID)
}
return pool, nil
}
}

return nil, fmt.Errorf("could not find load balancer server pool (name: %s, ID: %s)",
lbPoolConfig.Name, lbPoolConfig.ID)
}

// UpdateLBServerPool updates types.LBPool with all fields. At least name or ID must be specified.
// If both - Name and ID are specified it performs a lookup by ID and returns an error if the specified name and found
// name do not match.
// Name and Algorithm fields must be populated.
func (eGW *EdgeGateway) UpdateLBServerPool(lbPoolConfig *types.LBPool) (*types.LBPool, error) {
if err := validateUpdateLBServerPool(lbPoolConfig); err != nil {
return nil, err
}

// if only name was specified for update, ID must be found, because ID is mandatory for update
if lbPoolConfig.ID == "" {
readLBPool, err := eGW.ReadLBServerPool(&types.LBPool{Name: lbPoolConfig.Name})
if err != nil {
return nil, fmt.Errorf("unable to find load balancer pool by name for update: %s", err)
}
lbPoolConfig.ID = readLBPool.ID
}

httpPath, err := eGW.buildProxiedEdgeEndpointURL(types.LBServerPoolPath + lbPoolConfig.ID)
if err != nil {
return nil, fmt.Errorf("could not get Edge Gateway API endpoint: %s", err)
}

// Result should be 204, if not we expect an error of type types.NSXError
_, err = eGW.client.ExecuteRequestWithCustomError(httpPath, http.MethodPut, types.AnyXMLMime,
"error while updating load balancer server pool : %s", lbPoolConfig, &types.NSXError{})
if err != nil {
return nil, err
}

readPool, err := eGW.ReadLBServerPool(&types.LBPool{ID: lbPoolConfig.ID})
if err != nil {
return nil, fmt.Errorf("unable to retrieve server pool with ID (%s) after update: %s", readPool.ID, err)
}
return readPool, nil
}

// DeleteLBServerPool is able to delete the types.LBPool type by Name and/or ID.
// If both - Name and ID are specified it performs a lookup by ID and returns an error if the specified name and found
// name do not match.
func (eGW *EdgeGateway) DeleteLBServerPool(lbPoolConfig *types.LBPool) error {
if err := validateDeleteLBServerPool(lbPoolConfig); err != nil {
return err
}

lbPoolID := lbPoolConfig.ID
// if only name was specified for deletion, ID must be found, because only ID can be used for deletion
if lbPoolConfig.ID == "" {
readLBPool, err := eGW.ReadLBServerPool(&types.LBPool{Name: lbPoolConfig.Name})
if err != nil {
return fmt.Errorf("unable to find load balancer pool by name for deletion: %s", err)
}
lbPoolID = readLBPool.ID
}

httpPath, err := eGW.buildProxiedEdgeEndpointURL(types.LBServerPoolPath + lbPoolID)
if err != nil {
return fmt.Errorf("could not get Edge Gateway API endpoint: %s", err)
}
return eGW.client.ExecuteRequestWithoutResponse(httpPath, http.MethodDelete, types.AnyXMLMime,
"unable to delete Server Pool: %s", nil)
}

func validateCreateLBServerPool(lbPoolConfig *types.LBPool) error {
if lbPoolConfig.Name == "" {
return fmt.Errorf("load balancer server pool Name cannot be empty")
}

if lbPoolConfig.Algorithm == "" {
return fmt.Errorf("load balancer server pool Algorithm cannot be empty")
}

for _, member := range lbPoolConfig.Members {
if member.Condition == "" {
return fmt.Errorf("load balancer server pool Member must have Condition set")
}
}

return nil
}

func validateReadLBServerPool(lbPoolConfig *types.LBPool) error {
if lbPoolConfig.ID == "" && lbPoolConfig.Name == "" {
return fmt.Errorf("to read load balancer server pool at least one of `ID`, `Name` fields must be specified")
}

return nil
}

func validateUpdateLBServerPool(lbPoolConfig *types.LBPool) error {
// Update and create have the same requirements for now
return validateCreateLBServerPool(lbPoolConfig)
}

func validateDeleteLBServerPool(lbPoolConfig *types.LBPool) error {
// Read and delete have the same requirements for now
return validateReadLBServerPool(lbPoolConfig)
}
Loading