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 support for LocalStack v2 #994

Merged
merged 7 commits into from
Apr 12, 2023
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
44 changes: 36 additions & 8 deletions modules/localstack/localstack.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const defaultPort = 4566
const defaultRegion = "us-east-1"
const defaultVersion = "1.4.0"
mdelapenya marked this conversation as resolved.
Show resolved Hide resolved
const hostnameExternalEnvVar = "HOSTNAME_EXTERNAL"
const localstackHostEnvVar = "LOCALSTACK_HOST"

const defaultAccessKeyID = "accesskey"
const defaultSecretAccessKey = "secretkey"
Expand All @@ -40,6 +41,25 @@ func isLegacyMode(image string) bool {
return true
}

func isVersion2(image string) bool {
parts := strings.Split(image, ":")
version := parts[len(parts)-1]

if version == "latest" {
return true
}

if !strings.HasPrefix(version, "v") {
version = fmt.Sprintf("v%s", version)
}

if semver.IsValid(version) {
return semver.Compare(version, "v2.0") > 0 // version >= v2.0
}

return true
}

// StartContainer creates an instance of the LocalStack container type, being possible to pass a custom request and options:
// - overrideReq: a function that can be used to override the default container request, usually used to set the image version, environment variables for localstack, etc.
func StartContainer(ctx context.Context, overrideReq OverrideContainerRequestOption) (*LocalStackContainer, error) {
Expand Down Expand Up @@ -67,11 +87,19 @@ func StartContainer(ctx context.Context, overrideReq OverrideContainerRequestOpt
return nil, fmt.Errorf("version=%s. Testcontainers for Go does not support running LocalStack in legacy mode. Please use a version >= 0.11.0", localStackReq.Image)
}

hostnameExternalReason, err := configureDockerHost(&localStackReq)
if err != nil {
return nil, err
if isVersion2(localStackReq.Image) {
hostnameExternalReason, err := configureDockerHost(&localStackReq, localstackHostEnvVar)
if err != nil {
return nil, err
}
fmt.Printf("Setting %s to %s (%s)\n", localstackHostEnvVar, req.Env[localstackHostEnvVar], hostnameExternalReason)
} else {
hostnameExternalReason, err := configureDockerHost(&localStackReq, hostnameExternalEnvVar)
if err != nil {
return nil, err
}
fmt.Printf("Setting %s to %s (%s)\n", hostnameExternalEnvVar, req.Env[hostnameExternalEnvVar], hostnameExternalReason)
}
fmt.Printf("Setting %s to %s (%s)\n", hostnameExternalEnvVar, req.Env[hostnameExternalEnvVar], hostnameExternalReason)

container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: localStackReq.ContainerRequest,
Expand All @@ -87,11 +115,11 @@ func StartContainer(ctx context.Context, overrideReq OverrideContainerRequestOpt
return c, nil
}

func configureDockerHost(req *LocalStackContainerRequest) (reason string, err error) {
func configureDockerHost(req *LocalStackContainerRequest, envVar string) (reason string, err error) {
err = nil
reason = ""

if _, ok := req.Env[hostnameExternalEnvVar]; ok {
if _, ok := req.Env[envVar]; ok {
reason = "explicitly as environment variable"
return
}
Expand All @@ -101,7 +129,7 @@ func configureDockerHost(req *LocalStackContainerRequest) (reason string, err er
if len(req.Networks) > 0 && len(req.NetworkAliases) > 0 && len(req.NetworkAliases[req.Networks[0]]) > 0 {
alias := req.NetworkAliases[req.Networks[0]][len(req.NetworkAliases[req.Networks[0]])-1]

req.Env[hostnameExternalEnvVar] = alias
req.Env[envVar] = alias
reason = "to match last network alias on container with non-default network"
return
}
Expand All @@ -119,7 +147,7 @@ func configureDockerHost(req *LocalStackContainerRequest) (reason string, err er
return
}

req.Env[hostnameExternalEnvVar] = daemonHost
req.Env[envVar] = daemonHost
reason = "to match host-routable address for container"

return
Expand Down
133 changes: 98 additions & 35 deletions modules/localstack/localstack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ package localstack
import (
"context"
"fmt"
"github.com/testcontainers/testcontainers-go/wait"
"io"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -20,52 +24,60 @@ func generateContainerRequest() *LocalStackContainerRequest {
}

func TestConfigureDockerHost(t *testing.T) {
tests := []struct {
envVar string
}{
{hostnameExternalEnvVar},
{localstackHostEnvVar},
}

t.Run("HOSTNAME_EXTERNAL variable is passed as part of the request", func(t *testing.T) {
req := generateContainerRequest()
for _, tt := range tests {
t.Run("HOSTNAME_EXTERNAL variable is passed as part of the request", func(t *testing.T) {
req := generateContainerRequest()

req.Env[hostnameExternalEnvVar] = "foo"
req.Env[tt.envVar] = "foo"

reason, err := configureDockerHost(req)
assert.Nil(t, err)
assert.Equal(t, "explicitly as environment variable", reason)
})
reason, err := configureDockerHost(req, tt.envVar)
assert.Nil(t, err)
assert.Equal(t, "explicitly as environment variable", reason)
})

t.Run("HOSTNAME_EXTERNAL matches the last network alias on a container with non-default network", func(t *testing.T) {
req := generateContainerRequest()
t.Run("HOSTNAME_EXTERNAL matches the last network alias on a container with non-default network", func(t *testing.T) {
req := generateContainerRequest()

req.Networks = []string{"foo", "bar", "baaz"}
req.NetworkAliases = map[string][]string{
"foo": {"foo0", "foo1", "foo2", "foo3"},
"bar": {"bar0", "bar1", "bar2", "bar3"},
"baaz": {"baaz0", "baaz1", "baaz2", "baaz3"},
}
req.Networks = []string{"foo", "bar", "baaz"}
req.NetworkAliases = map[string][]string{
"foo": {"foo0", "foo1", "foo2", "foo3"},
"bar": {"bar0", "bar1", "bar2", "bar3"},
"baaz": {"baaz0", "baaz1", "baaz2", "baaz3"},
}

reason, err := configureDockerHost(req)
assert.Nil(t, err)
assert.Equal(t, "to match last network alias on container with non-default network", reason)
assert.Equal(t, "foo3", req.Env[hostnameExternalEnvVar])
})
reason, err := configureDockerHost(req, tt.envVar)
assert.Nil(t, err)
assert.Equal(t, "to match last network alias on container with non-default network", reason)
assert.Equal(t, "foo3", req.Env[tt.envVar])
})

t.Run("HOSTNAME_EXTERNAL matches the daemon host because there are no aliases", func(t *testing.T) {
dockerProvider, err := testcontainers.NewDockerProvider()
assert.Nil(t, err)
defer dockerProvider.Close()
t.Run("HOSTNAME_EXTERNAL matches the daemon host because there are no aliases", func(t *testing.T) {
dockerProvider, err := testcontainers.NewDockerProvider()
assert.Nil(t, err)
defer dockerProvider.Close()

// because the daemon host could be a remote one, we need to get it from the provider
expectedDaemonHost, err := dockerProvider.DaemonHost(context.Background())
assert.Nil(t, err)
// because the daemon host could be a remote one, we need to get it from the provider
expectedDaemonHost, err := dockerProvider.DaemonHost(context.Background())
assert.Nil(t, err)

req := generateContainerRequest()
req := generateContainerRequest()

req.Networks = []string{"foo", "bar", "baaz"}
req.NetworkAliases = map[string][]string{}
req.Networks = []string{"foo", "bar", "baaz"}
req.NetworkAliases = map[string][]string{}

reason, err := configureDockerHost(req)
assert.Nil(t, err)
assert.Equal(t, "to match host-routable address for container", reason)
assert.Equal(t, expectedDaemonHost, req.Env[hostnameExternalEnvVar])
})
reason, err := configureDockerHost(req, tt.envVar)
assert.Nil(t, err)
assert.Equal(t, "to match host-routable address for container", reason)
assert.Equal(t, expectedDaemonHost, req.Env[tt.envVar])
})
}
}

func TestIsLegacyMode(t *testing.T) {
Expand Down Expand Up @@ -165,3 +177,54 @@ func TestStartWithNetwork(t *testing.T) {
require.Equal(t, 1, len(networks))
require.Equal(t, "localstack-network", networks[0])
}

func TestStartV2WithNetwork(t *testing.T) {
ctx := context.Background()

nw, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{
NetworkRequest: testcontainers.NetworkRequest{
Name: "localstack-network-v2",
},
})
require.Nil(t, err)
assert.NotNil(t, nw)

localstack, err := StartContainer(
ctx,
OverrideContainerRequest(testcontainers.ContainerRequest{
Image: "localstack/localstack:2.0.0",
Networks: []string{"localstack-network-v2"},
NetworkAliases: map[string][]string{"localstack-network-v2": {"localstack"}},
}),
)
require.Nil(t, err)
assert.NotNil(t, localstack)

cli, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: "amazon/aws-cli:2.7.27",
Networks: []string{"localstack-network-v2"},
Entrypoint: []string{"tail"},
Cmd: []string{"-f", "/dev/null"},
Env: map[string]string{
"AWS_ACCESS_KEY_ID": "accesskey",
"AWS_SECRET_ACCESS_KEY": "secretkey",
"AWS_REGION": "eu-west-1",
},
WaitingFor: wait.ForExec([]string{"/usr/local/bin/aws", "sqs", "create-queue", "--queue-name", "baz", "--region", "eu-west-1",
"--endpoint-url", "http://localstack:4566", "--no-verify-ssl"}).
WithStartupTimeout(time.Second * 10).
WithExitCodeMatcher(func(exitCode int) bool {
return exitCode == 0
}).
WithResponseMatcher(func(r io.Reader) bool {
respBytes, _ := io.ReadAll(r)
resp := string(respBytes)
return strings.Contains(resp, "http://localstack:4566")
}),
},
Started: true,
})
require.Nil(t, err)
assert.NotNil(t, cli)
}