Skip to content

Commit

Permalink
added get openstack loadbalancer function
Browse files Browse the repository at this point in the history
  • Loading branch information
azhry committed Mar 22, 2023
1 parent 34ecd8e commit 7d5c099
Show file tree
Hide file tree
Showing 4 changed files with 135 additions and 13 deletions.
69 changes: 58 additions & 11 deletions api/openstack.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ import (

type (
OpenstackClient struct {
NetworkEndpoint string
AuthEndpoint string
AuthToken string
ProjectId string
NetworkEndpoint string
LoadBalancerEndpoint string
AuthEndpoint string
AuthToken string
ProjectId string
}

OpenstackCredential struct {
Expand Down Expand Up @@ -71,9 +72,27 @@ func (c *OpenstackClient) Authenticate(auth OpenstackAuth) (*http.Response, erro
}
}

authMap := map[string]interface{}{}
authByte, _ := json.Marshal(auth)
json.Unmarshal(authByte, &authMap)

if identity, ok := authMap["identity"]; ok {
if len(auth.Identity.Methods) > 0 {
identityMap := identity.(map[string]interface{})
switch auth.Identity.Methods[0] {
case "password":
delete(identityMap, "application_credential")

case "application_credential":
delete(identityMap, "password")
}
authMap["identity"] = identityMap
}
}

url := c.AuthEndpoint + "/v3/auth/tokens"
b, _ := json.Marshal(map[string]interface{}{
"auth": auth,
"auth": authMap,
})
requestBody := b

Expand Down Expand Up @@ -156,33 +175,61 @@ func (c *OpenstackClient) ValidateQuotas() (bool, error) {
}

floatingIpQuota := quotas.Quota.FloatingIp
if floatingIpQuota.Limit != -1 && floatingIpQuota.Used >= floatingIpQuota.Limit {
if floatingIpQuota.Limit != -1 && floatingIpQuota.Limit != 0 && floatingIpQuota.Used >= floatingIpQuota.Limit {
return false, fmt.Errorf("floating ip quota limit exceeded")
}
networkQuota := quotas.Quota.Network
if networkQuota.Limit != -1 && networkQuota.Used >= networkQuota.Limit {
if networkQuota.Limit != -1 && networkQuota.Limit != 0 && networkQuota.Used >= networkQuota.Limit {
return false, fmt.Errorf("network quota limit exceeded")
}
routerQuota := quotas.Quota.Router
if routerQuota.Limit != -1 && routerQuota.Used >= routerQuota.Limit {
if routerQuota.Limit != -1 && routerQuota.Limit != 0 && routerQuota.Used >= routerQuota.Limit {
return false, fmt.Errorf("router quota limit exceeded")
}
securityGroupQuota := quotas.Quota.SecurityGroup
if securityGroupQuota.Limit != -1 && securityGroupQuota.Used+2 >= securityGroupQuota.Limit {
if securityGroupQuota.Limit != -1 && securityGroupQuota.Limit != 0 && securityGroupQuota.Used+2 >= securityGroupQuota.Limit {
return false, fmt.Errorf("security group quota limit exceeded")
}
securityGroupRuleQuota := quotas.Quota.SecurityGroupRule
if securityGroupRuleQuota.Limit != -1 && securityGroupRuleQuota.Used+10 >= securityGroupRuleQuota.Limit {
if securityGroupRuleQuota.Limit != -1 && securityGroupRuleQuota.Limit != 0 && securityGroupRuleQuota.Used+10 >= securityGroupRuleQuota.Limit {
return false, fmt.Errorf("security group rules quota limit exceeded")
}
portQuota := quotas.Quota.Port
if portQuota.Limit != -1 && portQuota.Used+3 >= portQuota.Limit {
if portQuota.Limit != -1 && portQuota.Limit != 0 && portQuota.Used+3 >= portQuota.Limit {
return false, fmt.Errorf("port quota limit exceeded")
}

return true, nil
}

func (c *OpenstackClient) GetLoadBalancer(loadBalancerId string) (*model.LoadBalancerResponse, error) {
url := c.LoadBalancerEndpoint + "/v2/lbaas/loadbalancers/" + loadBalancerId
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Auth-Token", c.AuthToken)

client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()

body, _ := io.ReadAll(response.Body)

loadBalancer := model.LoadBalancerResponse{}
json.Unmarshal(body, &loadBalancer)

if loadBalancer.LoadBalancer.ID == "" {
return nil, nil
}

return &loadBalancer, nil
}

func (c *OpenstackClient) UpdateYamlManifest(yamlString string, opt option.ManifestOption) (string, error) {
var (
err error
Expand Down
28 changes: 28 additions & 0 deletions model/openstack.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package model

import "time"

type (
QuotasResponse struct {
Quota Quota `json:"quota"`
Expand All @@ -23,4 +25,30 @@ type (
Used int `json:"used"`
Reserved int `json:"reserved"`
}

LoadBalancerResponse struct {
LoadBalancer LoadBalancer `json:"loadbalancer"`
}

LoadBalancer struct {
ID string `json:"id"`
AdminStateUp bool `json:"admin_state_up"`
Description string `json:"description"`
ProjectID string `json:"project_id"`
ProvisioningStatus string `json:"provisioning_status"`
FlavorID string `json:"flavor_id"`
VipSubnetID string `json:"vip_subnet_id"`
VipAddress string `json:"vip_address"`
VipNetworkID string `json:"vip_network_id"`
VipPortID string `json:"vip_port_id"`
AdditionalVips []interface{} `json:"additional_vips"`
Provider string `json:"provider"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
OperatingStatus string `json:"operating_status"`
Name string `json:"name"`
VipQosPolicyID string `json:"vip_qos_policy_id"`
AvailabilityZone string `json:"availability_zone"`
Tags []interface{} `json:"tags"`
}
)
5 changes: 3 additions & 2 deletions test/cluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,15 +279,16 @@ func TestGetKubeconfigValues(t *testing.T) {

// go test ./test -v -run ^TestGetService$
func TestGetService(t *testing.T) {
capi, _ := api.NewClusterApiClient("", "./data/az-vega.kubeconfig")
s, err := capi.GetService("eventing-webhook", "knative-eventing")
capi, _ := api.NewClusterApiClient("", "./data/capi-az-local.kubeconfig")
s, err := capi.GetService("ingress-dftw8qey-ingress-nginx-controller", "lyrid-9cc8b789-e6df-434a-afbb-371e8280ec1a")
if err != nil {
t.Fatal(err)
}
t.Log(s.Spec.LoadBalancerIP)
t.Log(s.Spec.ExternalIPs)
t.Log(s.Spec.ClusterIP)
t.Log(s.Status.LoadBalancer.Ingress)
t.Log(s.Annotations["loadbalancer.openstack.org/load-balancer-id"])
}

// go test ./test -v -run ^TestGetSecret$
Expand Down
46 changes: 46 additions & 0 deletions test/openstack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,3 +365,49 @@ func TestCreatePersistentVolumeClaim(t *testing.T) {
t.Fatal("Error create storage class:", error.Error(err))
}
}

// go test ./test -v -run ^TestGetLoadBalancer$
func TestGetLoadBalancer(t *testing.T) {
cl := api.OpenstackClient{
NetworkEndpoint: os.Getenv("OS_NETWORK_ENDPOINT"),
LoadBalancerEndpoint: os.Getenv("OS_LOADBALANCER_ENDPOINT"),
AuthEndpoint: os.Getenv("OS_AUTH_ENDPOINT"),
AuthToken: os.Getenv("OS_TOKEN"),
ProjectId: os.Getenv("OS_PROJECT_ID"),
}

os.Setenv("OS_TOKEN", "")

credential := api.OpenstackAuth{
Identity: api.OpenstackIdentity{
Methods: []string{"application_credential"},
ApplicationCredential: api.OpenstackCredential{
ApplicationCredentialName: os.Getenv("OS_APPLICATION_CREDENTIAL_NAME"),
ApplicationCredentialId: os.Getenv("OS_APPLICATION_CREDENTIAL_ID"),
ApplicationCredentialSecret: os.Getenv("OS_APPLICATION_CREDENTIAL_SECRET"),
},
},
}
_, err := cl.Authenticate(credential)
if err != nil {
t.Fatal(err)
}

t.Log(credential)

t.Run("get existing load balancer", func(t *testing.T) {
res, err := cl.GetLoadBalancer("59107a73-6f12-4a8d-9812-383b3e66977a")
if err != nil {
t.Fatal(error.Error(err))
}
t.Log(res)
})

t.Run("get non-existing load balancer", func(t *testing.T) {
res, err := cl.GetLoadBalancer("xxxyyz")
if err != nil {
t.Fatal(error.Error(err))
}
t.Log(res)
})
}

0 comments on commit 7d5c099

Please sign in to comment.