Skip to content

Commit

Permalink
SiteShield provider added to address akamai#235
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrei Petriv committed Jul 24, 2021
1 parent d5a4fed commit e321b66
Show file tree
Hide file tree
Showing 10 changed files with 455 additions and 0 deletions.
1 change: 1 addition & 0 deletions pkg/providers/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ import (
_ "github.com/akamai/terraform-provider-akamai/v2/pkg/providers/iam"
_ "github.com/akamai/terraform-provider-akamai/v2/pkg/providers/networklists"
_ "github.com/akamai/terraform-provider-akamai/v2/pkg/providers/property"
_ "github.com/akamai/terraform-provider-akamai/v2/pkg/providers/siteshield"
)
87 changes: 87 additions & 0 deletions pkg/providers/siteshield/data_akamai_siteshield_map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package siteshield

import (
"context"
"errors"
"fmt"
"strconv"

"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/siteshield"
"github.com/akamai/terraform-provider-akamai/v2/pkg/akamai"
"github.com/akamai/terraform-provider-akamai/v2/pkg/tools"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func dataSourceSiteShieldMap() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceSiteShieldMapRead,
Schema: map[string]*schema.Schema{
"map_id": {
Type: schema.TypeInt,
Optional: true,
},
"current_cidrs": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"proposed_cidrs": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
},
"rule_name": {
Type: schema.TypeString,
Computed: true,
},
"acknowledged": {
Type: schema.TypeBool,
Computed: true,
},
},
}
}

func dataSourceSiteShieldMapRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := akamai.Meta(m)
client := inst.Client(meta)
logger := meta.Log("SSMAP", "dataSiteShieldMap")

mapID, err := tools.GetIntValue("map_id", d)
d.SetId(strconv.Itoa(mapID))

if err != nil && !errors.Is(err, tools.ErrNotFound) {
return diag.FromErr(err)
}

ssMapID := siteshield.SiteShieldMapRequest{UniqueID: mapID}

ssMap, err := client.GetSiteShieldMap(ctx, ssMapID)
if err != nil {
logger.Errorf("calling 'getSiteShieldMap': %s", err.Error())
return diag.FromErr(err)
}

if err := d.Set("current_cidrs", ssMap.SiteShieldMap.CurrentCidrs); err != nil {
logger.Errorf("error setting 'current_cidrs': %s", err.Error())
return diag.FromErr(fmt.Errorf("%w: %s", tools.ErrValueSet, err.Error()))
}

if err := d.Set("proposed_cidrs", ssMap.SiteShieldMap.ProposedCidrs); err != nil {
logger.Errorf("error setting 'proposed_cidrs': %s", err.Error())
return diag.FromErr(fmt.Errorf("%w: %s", tools.ErrValueSet, err.Error()))
}

if err := d.Set("rule_name", ssMap.SiteShieldMap.RuleName); err != nil {
logger.Errorf("error setting 'rule_name': %s", err.Error())
return diag.FromErr(fmt.Errorf("%w: %s", tools.ErrValueSet, err.Error()))
}

if err := d.Set("acknowledged", ssMap.SiteShieldMap.Acknowledged); err != nil {
logger.Errorf("error setting 'acknowledged': %s", err.Error())
return diag.FromErr(fmt.Errorf("%w: %s", tools.ErrValueSet, err.Error()))
}

return nil
}
45 changes: 45 additions & 0 deletions pkg/providers/siteshield/data_akamai_siteshield_map_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package siteshield

import (
"encoding/json"
"testing"

"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/siteshield"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/stretchr/testify/mock"
)

func TestAccAkamaiSiteShield_data_basic(t *testing.T) {
t.Run("get SiteShield map", func(t *testing.T) {
client := &mocksiteshield{}

cv := siteshield.SiteShieldMapResponse{}
expectJS := compactJSON(loadFixtureBytes("testdata/TestDSSiteShield/SiteShield.json"))
json.Unmarshal([]byte(expectJS), &cv)

client.On("GetSiteShieldMap",
mock.Anything,
siteshield.SiteShieldMapRequest{UniqueID: 1234},
).Return(&cv, nil)

useClient(client, func() {
resource.Test(t, resource.TestCase{
IsUnitTest: true,
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: loadFixtureString("testdata/TestDSSiteShield/get_map.tf"),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr("data.akamai_siteshield_map.test", "map_id", "1234"),
resource.TestCheckResourceAttr("data.akamai_siteshield_map.test", "rule_name", "a;s36.akamai.net"),
resource.TestCheckResourceAttr("data.akamai_siteshield_map.test", "acknowledged", "false"),
),
},
},
})
})

client.AssertExpectations(t)
})

}
120 changes: 120 additions & 0 deletions pkg/providers/siteshield/provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package siteshield

import (
"sync"

"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/siteshield"
"github.com/akamai/terraform-provider-akamai/v2/pkg/akamai"
"github.com/akamai/terraform-provider-akamai/v2/pkg/config"
"github.com/apex/log"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

type (
provider struct {
*schema.Provider

client siteshield.SSMAPS
}
// Option is a siteshield provider option
Option func(p *provider)
)

var (
once sync.Once

inst *provider
)

// Subprovider returns a core sub provider
func Subprovider(opts ...Option) akamai.Subprovider {
once.Do(func() {
inst = &provider{Provider: Provider()}

for _, opt := range opts {
opt(inst)
}
})

return inst
}

// Provider returns the Akamai terraform.Resource provider.
func Provider() *schema.Provider {
provider := &schema.Provider{
Schema: map[string]*schema.Schema{
"siteshield": {
Optional: true,
Type: schema.TypeSet,
Elem: config.Options("siteshield"),
},
},
DataSourcesMap: map[string]*schema.Resource{
"akamai_siteshield_map": dataSourceSiteShieldMap(),
},
}
return provider
}

// WithClient sets the client interface function, used for mocking and testing
func WithClient(c siteshield.SSMAPS) Option {
return func(p *provider) {
p.client = c
}
}

// Client returns the PAPI interface
func (p *provider) Client(meta akamai.OperationMeta) siteshield.SSMAPS {
if p.client != nil {
return p.client
}
return siteshield.Client(meta.Session())
}

func getSiteShieldV1Service(d *schema.ResourceData) error {
var section string

if section != "" {
if err := d.Set("config_section", section); err != nil {
return err
}
}

return nil
}

func (p *provider) Name() string {
return "siteshield"
}

// SiteShieldProviderVersion update version string anytime provider adds new features
const SiteShieldProviderVersion string = "v0.0.1"

func (p *provider) Version() string {
return SiteShieldProviderVersion
}

func (p *provider) Schema() map[string]*schema.Schema {
return p.Provider.Schema
}

func (p *provider) Resources() map[string]*schema.Resource {
return p.Provider.ResourcesMap
}

func (p *provider) DataSources() map[string]*schema.Resource {
return p.Provider.DataSourcesMap
}

func (p *provider) Configure(log log.Interface, d *schema.ResourceData) diag.Diagnostics {
log.Debug("START Configure")

err := getSiteShieldV1Service(d)
if err != nil {
return diag.FromErr(err)
}

return nil
}
112 changes: 112 additions & 0 deletions pkg/providers/siteshield/provider_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package siteshield

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"sync"
"testing"

"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/siteshield"
"github.com/akamai/terraform-provider-akamai/v2/pkg/akamai"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

var testAccProviders map[string]*schema.Provider
var testProvider *schema.Provider

func init() {
testProvider = akamai.Provider(Subprovider())()
testAccProviders = map[string]*schema.Provider{
"akamai": testProvider,
}
}

func TestProvider(t *testing.T) {
if err := Provider().InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}

func testAccPreCheck(t *testing.T) {

}

func getTestProvider() *schema.Provider {
return testProvider
}

// Only allow one test at a time to patch the client via useClient()
var clientLock sync.Mutex

// useClient swaps out the client on the global instance for the duration of the given func
func useClient(client siteshield.SSMAPS, f func()) {
clientLock.Lock()
orig := inst.client
inst.client = client

defer func() {
inst.client = orig
clientLock.Unlock()
}()

f()
}

// TODO marks a test as being in a "pending" state and logs a message telling the user why. Such tests are expected to
// fail for the time being and may exist for the sake of unfinished/future features or to document known buggy cases
// that won't be fixed right away. The failure of a pending test is not considered an error and the test will therefore
// be skipped unless the TEST_TODO environment variable is set to a non-empty value.
func TODO(t *testing.T, message string) {
t.Helper()
t.Log(fmt.Sprintf("TODO: %s", message))

if os.Getenv("TEST_TODO") == "" {
t.Skip("TODO: Set TEST_TODO=1 in env to run this test")
}
}

func setEnv(home string, env map[string]string) {
os.Clearenv()
os.Setenv("HOME", home)
if len(env) > 0 {
for key, val := range env {
os.Setenv(key, val)
}
}
}

func restoreEnv(env []string) {
os.Clearenv()
for _, value := range env {
envVar := strings.Split(value, "=")
os.Setenv(envVar[0], envVar[1])
}
}

// loadFixtureBytes returns the entire contents of the given file as a byte slice
func loadFixtureBytes(path string) []byte {
contents, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
return contents
}

// loadFixtureString returns the entire contents of the given file as a string
func loadFixtureString(path string) string {
return string(loadFixtureBytes(path))
}

// compactJSON converts a JSON-encoded byte slice to a compact form (so our JSON fixtures can be readable)
func compactJSON(encoded []byte) string {
buf := bytes.Buffer{}
if err := json.Compact(&buf, encoded); err != nil {
panic(fmt.Sprintf("%s: %s", err, string(encoded)))
}

return buf.String()
}
9 changes: 9 additions & 0 deletions pkg/providers/siteshield/siteshield.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// +build all siteshield

package siteshield

import "github.com/akamai/terraform-provider-akamai/v2/pkg/providers/registry"

func init() {
registry.RegisterProvider(Subprovider())
}
Loading

0 comments on commit e321b66

Please sign in to comment.