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

feat(lb): add support for frontend ACL #382

Merged
merged 9 commits into from
Jan 27, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
19 changes: 19 additions & 0 deletions scaleway/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,17 @@ func expandStrings(data interface{}) []string {
return stringSlice
}

func expandSliceStringPtr(data interface{}) []*string {
if data == nil {
return nil
}
stringSlice := []*string(nil)
for _, s := range data.([]interface{}) {
stringSlice = append(stringSlice, expandStringPtr(s))
}
return stringSlice
}

func flattenIPPtr(ip *net.IP) interface{} {
if ip == nil {
return ""
Expand All @@ -569,6 +580,14 @@ func flattenStringPtr(s *string) interface{} {
return *s
}

func flattenSliceStringPtr(s []*string) interface{} {
res := make([]interface{}, 0, len(s))
for _, strPtr := range s {
res = append(res, flattenStringPtr(strPtr))
}
return res
}

func expandStringPtr(data interface{}) *string {
if data == nil || data == "" {
return nil
Expand Down
68 changes: 68 additions & 0 deletions scaleway/helpers_lb.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,74 @@ func flattenLbBackendMarkdownAction(action lb.OnMarkedDownAction) interface{} {
return action.String()
}

func flattenLbAcl(acl *lb.ACL) interface{} {
res := map[string]interface{}{
"name": acl.Name,
"match": flattenLbAclMatch(acl.Match),
"action": flattenLbAclAction(acl.Action),
}
return res
}

// expandLbAcl transforms a state acl to an api one.
func expandLbAcl(i interface{}) *lb.ACL {
rawRule := i.(map[string]interface{})
acl := &lb.ACL{
Name: rawRule["name"].(string),
Match: expandLbAclMatch(rawRule["match"]),
Action: expandLbAclAction(rawRule["action"]),
}

//remove http filter values if we do not pass any http filter
if acl.Match.HTTPFilter == "" || acl.Match.HTTPFilter == lb.ACLHTTPFilterACLHTTPFilterNone {
acl.Match.HTTPFilter = lb.ACLHTTPFilterACLHTTPFilterNone
acl.Match.HTTPFilterValue = []*string{}
}
alekc marked this conversation as resolved.
Show resolved Hide resolved

return acl
}
func flattenLbAclAction(action *lb.ACLAction) interface{} {
return map[string]interface{}{
"type": action.Type,
}
}
func expandLbAclAction(raw interface{}) *lb.ACLAction {
if raw == nil || len(raw.([]interface{})) != 1 {
return nil
}
rawMap := raw.([]interface{})[0].(map[string]interface{})
return &lb.ACLAction{
Type: lb.ACLActionType(rawMap["type"].(string)),
}
}
func flattenLbAclMatch(match *lb.ACLMatch) interface{} {
return map[string]interface{}{
"ip_subnet": flattenSliceStringPtr(match.IPSubnet),
"http_filter": match.HTTPFilter.String(),
"http_filter_value": flattenSliceStringPtr(match.HTTPFilterValue),
"invert": match.Invert,
}
}
func expandLbAclMatch(raw interface{}) *lb.ACLMatch {
if raw == nil || len(raw.([]interface{})) != 1 {
return nil
}
rawMap := raw.([]interface{})[0].(map[string]interface{})

//scaleway api require ip subnet, so if we did not specify one, just put 0.0.0.0/0 instead
ipSubnet := expandSliceStringPtr(rawMap["ip_subnet"].([]interface{}))
if len(ipSubnet) == 0 {
ipSubnet = []*string{scw.StringPtr("0.0.0.0/0")}
}

return &lb.ACLMatch{
IPSubnet: ipSubnet,
HTTPFilter: lb.ACLHTTPFilter(rawMap["http_filter"].(string)),
HTTPFilterValue: expandSliceStringPtr(rawMap["http_filter_value"].([]interface{})),
Invert: rawMap["invert"].(bool),
}
}

func expandLbBackendMarkdownAction(raw interface{}) lb.OnMarkedDownAction {
if raw == "none" {
return lb.OnMarkedDownActionOnMarkedDownActionNone
Expand Down
219 changes: 209 additions & 10 deletions scaleway/resource_lb_frontend_beta.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package scaleway

import (
"math"
"sort"
alekc marked this conversation as resolved.
Show resolved Hide resolved

"github.com/google/go-cmp/cmp"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/scaleway/scaleway-sdk-go/api/lb/v1"
"github.com/scaleway/scaleway-sdk-go/scw"
)

func resourceScalewayLbFrontendBeta() *schema.Resource {
Expand Down Expand Up @@ -58,6 +61,88 @@ func resourceScalewayLbFrontendBeta() *schema.Resource {
ValidateFunc: validationUUIDorUUIDWithLocality(),
Description: "Certificate ID",
},
"acl": {
Type: schema.TypeList,
Optional: true,
Description: "ACL rules",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "The name of ACL",
},
"action": {
Type: schema.TypeList,
Required: true,
Description: "Action to undertake",
MaxItems: 1,
MinItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
lb.ACLActionTypeAllow.String(),
lb.ACLActionTypeDeny.String(),
}, false),
Description: "<allow> or <deny> request",
},
},
},
},
"match": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
MinItems: 1,
Description: "AclMatch Rule",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip_subnet": {
Type: schema.TypeList,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Optional: true,
Description: "This is the source IP v4/v6 address of the client of the session to match or not. " +
"Addresses values can be specified either as plain addresses or with a netmask appended.",
},
"http_filter": {
Type: schema.TypeString,
Optional: true,
Default: lb.ACLHTTPFilterACLHTTPFilterNone.String(),
ValidateFunc: validation.StringInSlice([]string{
lb.ACLHTTPFilterACLHTTPFilterNone.String(),
lb.ACLHTTPFilterPathBegin.String(),
lb.ACLHTTPFilterPathEnd.String(),
lb.ACLHTTPFilterRegex.String(),
}, false),
Description: "Http filter (if backend have a HTTP forward protocol)",
},
"http_filter_value": {
Type: schema.TypeList,
Optional: true,
Description: "Http filter value",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"invert": {
Type: schema.TypeBool,
Optional: true,
Description: "If true, then condition is unless type",
},
},
},
},
"region": regionSchema(),
"organization_id": organizationIDSchema(),
},
},
},
},
}
}
Expand All @@ -70,22 +155,26 @@ func resourceScalewayLbFrontendBetaCreate(d *schema.ResourceData, m interface{})
return err
}

var createReq = &lb.CreateFrontendRequest{
res, err := lbAPI.CreateFrontend(&lb.CreateFrontendRequest{
Region: region,
LbID: LbID,
Name: expandOrGenerateString(d.Get("name"), "lb-frt"),
InboundPort: int32(d.Get("inbound_port").(int)),
BackendID: expandID(d.Get("backend_id")),
TimeoutClient: expandDuration(d.Get("timeout_client")),
CertificateID: expandStringPtr(expandID(d.Get("certificate_id"))),
}
res, err := lbAPI.CreateFrontend(createReq)
})
if err != nil {
return err
}

d.SetId(newRegionalId(region, res.ID))

err = resourceScalewayLbFrontendBetaUpdateAcl(d, lbAPI, region, res.ID)
if err != nil {
return err
}

return resourceScalewayLbFrontendBetaRead(d, m)
}

Expand All @@ -108,18 +197,109 @@ func resourceScalewayLbFrontendBetaRead(d *schema.ResourceData, m interface{}) e
return err
}

d.Set("lb_id", newRegionalId(region, res.Lb.ID))
d.Set("backend_id", newRegionalId(region, res.Backend.ID))
d.Set("name", res.Name)
d.Set("inbound_port", int(res.InboundPort))
d.Set("timeout_client", flattenDuration(res.TimeoutClient))
_ = d.Set("lb_id", newRegionalId(region, res.Lb.ID))
_ = d.Set("backend_id", newRegionalId(region, res.Backend.ID))
_ = d.Set("name", res.Name)
_ = d.Set("inbound_port", int(res.InboundPort))
_ = d.Set("timeout_client", flattenDuration(res.TimeoutClient))

if res.Certificate != nil {
d.Set("certificate_id", newRegionalId(region, res.Certificate.ID))
_ = d.Set("certificate_id", newRegionalId(region, res.Certificate.ID))
} else {
d.Set("certificate_id", "")
_ = d.Set("certificate_id", "")
}

//read related acls.
resAcl, err := lbAPI.ListACLs(&lb.ListACLsRequest{
Region: region,
FrontendID: ID,
}, scw.WithAllPages())
if err != nil {
return err
}
sort.Slice(resAcl.ACLs, func(i, j int) bool {
return resAcl.ACLs[i].Index < resAcl.ACLs[j].Index
})
stateAcls := make([]interface{}, 0, len(resAcl.ACLs))
for _, apiAcl := range resAcl.ACLs {
stateAcls = append(stateAcls, flattenLbAcl(apiAcl))
}
_ = d.Set("acl", stateAcls)

return nil
}

func resourceScalewayLbFrontendBetaUpdateAcl(d *schema.ResourceData, lbAPI *lb.API, region scw.Region, frontendID string) error {
//Fetch existing acl from the api. and convert it to a hashmap with index as key
resAcl, err := lbAPI.ListACLs(&lb.ListACLsRequest{
Region: region,
FrontendID: frontendID,
}, scw.WithAllPages())
if err != nil {
return err
}
apiAcls := make(map[int32]*lb.ACL)
for _, acl := range resAcl.ACLs {
apiAcls[acl.Index] = acl
}

//convert state acl and sanitize them a bit
newAcl := make([]*lb.ACL, 0)
for _, rawAcl := range d.Get("acl").([]interface{}) {
newAcl = append(newAcl, expandLbAcl(rawAcl))
}

//loop
for index, stateAcl := range newAcl {
key := int32(index) + 1
if apiAcl, found := apiAcls[key]; found {
//there is an old acl with the same key. Remove it from array to mark that we've dealt with it
delete(apiAcls, key)

//if the state acl doesn't specify a name, set it to the same as the existing rule
if stateAcl.Name == "" {
stateAcl.Name = apiAcl.Name
}
//Verify if their values are the same and ignore if that's the case, update otherwise
if aclEquals(stateAcl, apiAcl) {
continue
}
_, err = lbAPI.UpdateACL(&lb.UpdateACLRequest{
Region: region,
ACLID: apiAcl.ID,
Name: stateAcl.Name,
Action: stateAcl.Action,
Match: stateAcl.Match,
Index: key,
})
if err != nil {
return err
}
continue
}
//old acl doesn't exist, create a new one
_, err = lbAPI.CreateACL(&lb.CreateACLRequest{
Region: region,
FrontendID: frontendID,
Name: expandOrGenerateString(stateAcl.Name, "lb-acl"),
Action: stateAcl.Action,
Match: stateAcl.Match,
Index: key,
})
if err != nil {
return err
}
}
//we've finished with all new acl, delete any remaining old one which were not dealt with yet
for _, acl := range apiAcls {
err = lbAPI.DeleteACL(&lb.DeleteACLRequest{
Region: region,
ACLID: acl.ID,
})
if err != nil {
return err
}
}
return nil
}

Expand All @@ -144,6 +324,12 @@ func resourceScalewayLbFrontendBetaUpdate(d *schema.ResourceData, m interface{})
return err
}

//update acl
err = resourceScalewayLbFrontendBetaUpdateAcl(d, lbAPI, region, ID)
if err != nil {
return err
}

return resourceScalewayLbFrontendBetaRead(d, m)
}

Expand All @@ -164,3 +350,16 @@ func resourceScalewayLbFrontendBetaDelete(d *schema.ResourceData, m interface{})

return nil
}

func aclEquals(aclA, aclB *lb.ACL) bool {
if aclA.Name != aclB.Name {
return false
}
if !cmp.Equal(aclA.Match, aclB.Match) {
return false
}
if !cmp.Equal(aclA.Action, aclB.Action) {
return false
}
return true
}
Loading