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

Added Consul module #2194

Merged
merged 12 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
7 changes: 7 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ updates:
day: sunday
open-pull-requests-limit: 3
rebase-strategy: disabled
- package-ecosystem: gomod
directory: /modules/consul
schedule:
interval: monthly
day: sunday
open-pull-requests-limit: 3
rebase-strategy: disabled
- package-ecosystem: gomod
directory: /modules/couchbase
schedule:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ jobs:
matrix:
go-version: [1.20.x, 1.x]
platform: [ubuntu-latest]
module: [artemis, cassandra, clickhouse, cockroachdb, compose, couchbase, elasticsearch, gcloud, inbucket, k3s, k6, kafka, localstack, mariadb, minio, mockserver, mongodb, mssql, mysql, nats, neo4j, openldap, postgres, pulsar, rabbitmq, redis, redpanda, vault]
module: [artemis, cassandra, clickhouse, cockroachdb, compose, consul, couchbase, elasticsearch, gcloud, inbucket, k3s, k6, kafka, localstack, mariadb, minio, mockserver, mongodb, mssql, mysql, nats, neo4j, openldap, postgres, pulsar, rabbitmq, redis, redpanda, vault]
exclude:
- go-version: 1.20.x
module: compose
Expand Down
6 changes: 5 additions & 1 deletion .vscode/.testcontainers-go.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
"name": "module / compose",
"path": "../modules/compose"
},
{
"name": "module / consul",
"path": "../modules/consul"
},
{
"name": "module / couchbase",
"path": "../modules/couchbase"
Expand Down Expand Up @@ -134,4 +138,4 @@
"path": "../modulegen"
}
]
}
}
53 changes: 53 additions & 0 deletions docs/modules/consul.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Consul

Not available until the next release of testcontainers-go <a href="https://github.com/testcontainers/testcontainers-go"><span class="tc-version">:material-tag: main</span></a>

## Introduction

The Testcontainers module for Consul.

## Adding this module to your project dependencies

Please run the following command to add the Consul module to your Go dependencies:

```
go get github.com/testcontainers/testcontainers-go/modules/consul
```

## Usage example

<!--codeinclude-->
[Creating a Consul container](../../modules/consul/examples_test.go) inside_block:runConsulContainer
<!--/codeinclude-->

## Module reference

The Consul module exposes one entrypoint function to create the Consul container, and this function receives two parameters:

```golang
func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*ConsulContainer, error)
```

- `context.Context`, the Go context.
- `testcontainers.ContainerCustomizer`, a variadic argument for passing options.

### Container Options

When starting the Consul container, you can pass options in a variadic way to configure it.

#### Image

If you need to set a different Consul Docker image, you can use `testcontainers.WithImage` with a valid Docker image
for Consul. E.g. `testcontainers.WithImage("docker.io/hashicorp/consul:latest")`.

{% include "../features/common_functional_options.md" %}

#### Configuration File
If you would like to customize the behavior for the deployed node you can use the `WithLocalConfig(config string)` function. It takes in a JSON string of keys and values.

### Container Methods

The Consul container exposes the following method:

#### ApiEndpoint
This method returns the connection string to connect to the Consul container API, using the default `8500` port.
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ nav:
- modules/cassandra.md
- modules/clickhouse.md
- modules/cockroachdb.md
- modules/consul.md
- modules/couchbase.md
- modules/elasticsearch.md
- modules/gcloud.md
Expand Down
6 changes: 6 additions & 0 deletions modules/consul/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
include ../../commons-test.mk

.PHONY: test
test:
$(MAKE) test-consul

76 changes: 76 additions & 0 deletions modules/consul/consul.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package consul

import (
"context"
"fmt"

"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)

const (
defaultHttpApiPort = "8500"
defaultBrokerPort = "8600"
)

const (
DefaultBaseImage = "docker.io/hashicorp/consul:1.15"
)

// ConsulContainer represents the Consul container type used in the module.
type ConsulContainer struct {
testcontainers.Container
}

// ApiEndpoint returns host:port for the HTTP API endpoint.
func (c *ConsulContainer) ApiEndpoint(ctx context.Context) (string, error) {
mappedPort, err := c.MappedPort(ctx, defaultHttpApiPort)
if err != nil {
return "", err
}

hostIP, err := c.Host(ctx)
if err != nil {
return "", err
}

uri := fmt.Sprintf("%s:%s", hostIP, mappedPort.Port())
return uri, nil
}

// WithLocalConfig passes a JSON string of keys and values to define a configuration to be used by the instance.
func WithLocalConfig(config string) testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) {
req.Env["CONSUL_LOCAL_CONFIG"] = config
}
}

// RunContainer creates an instance of the Consul container type
func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*ConsulContainer, error) {
containerReq := testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: DefaultBaseImage,
ExposedPorts: []string{
defaultHttpApiPort + "/tcp",
defaultBrokerPort + "/tcp",
defaultBrokerPort + "/udp",
},
Env: map[string]string{},
WaitingFor: wait.ForAll(
wait.ForLog("Consul agent running!"),
),
},
Started: true,
}

for _, opt := range opts {
opt.Customize(&containerReq)
}

container, err := testcontainers.GenericContainer(ctx, containerReq)
if err != nil {
return nil, err
}

return &ConsulContainer{Container: container}, nil
}
67 changes: 67 additions & 0 deletions modules/consul/consul_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package consul_test

import (
"context"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

capi "github.com/hashicorp/consul/api"

"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/consul"
)

func TestConsul(t *testing.T) {
ctx := context.Background()
tests := []struct {
name string
opts []testcontainers.ContainerCustomizer
}{
{
name: "Default",
opts: []testcontainers.ContainerCustomizer{},
},
{
name: "WithCustomConfigs",
opts: []testcontainers.ContainerCustomizer{
consul.WithLocalConfig(`{ "server":true }`),
},
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
container, err := consul.RunContainer(ctx, test.opts...)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, container.Terminate(ctx), "failed to terminate container") })

// Check if API is up
host, err := container.ApiEndpoint(ctx)
require.NoError(t, err)
assert.NotEmpty(t, len(host))

res, err := http.Get("http://" + host)
require.NoError(t, err)
assert.Equal(t, res.StatusCode, http.StatusOK)

cfg := capi.DefaultConfig()
cfg.Address = host

reg := &capi.AgentServiceRegistration{ID: "abcd", Name: test.name}

client, err := capi.NewClient(cfg)
require.NoError(t, err)

// Register / Unregister service
s := client.Agent()
err = s.ServiceRegister(reg)
require.NoError(t, err)

err = s.ServiceDeregister("abcd")
require.NoError(t, err)
})
}
}
39 changes: 39 additions & 0 deletions modules/consul/examples_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package consul_test

import (
"context"
"fmt"

"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/consul"
)

func ExampleRunContainer() {
// runconsulContainer {
ctx := context.Background()

consulContainer, err := consul.RunContainer(ctx,
testcontainers.WithImage("docker.io/hashicorp/consul:1.15"),
)
if err != nil {
panic(err)
}

// Clean up the container
defer func() {
if err := consulContainer.Terminate(ctx); err != nil {
panic(err)
}
}()
// }

state, err := consulContainer.State(ctx)
if err != nil {
panic(err)
}

fmt.Println(state.Running)

// Output:
// true
}
79 changes: 79 additions & 0 deletions modules/consul/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
module github.com/testcontainers/testcontainers-go/modules/consul

go 1.20

require (
github.com/hashicorp/consul/api v1.27.0
github.com/stretchr/testify v1.8.4
github.com/testcontainers/testcontainers-go v0.27.0
)

require (
dario.cat/mergo v1.0.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
github.com/Microsoft/hcsshim v0.11.4 // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/containerd/containerd v1.7.12 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/cpuguy83/dockercfg v0.3.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/distribution/reference v0.5.0 // indirect
github.com/docker/docker v25.0.1+incompatible // indirect
github.com/docker/go-connections v0.5.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/fatih/color v1.14.1 // indirect
github.com/felixge/httpsnoop v1.0.3 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-hclog v1.5.0 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/hashicorp/serf v0.10.1 // indirect
github.com/klauspost/compress v1.16.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/patternmatcher v0.6.0 // indirect
github.com/moby/sys/sequential v0.5.0 // indirect
github.com/moby/sys/user v0.1.0 // indirect
github.com/moby/term v0.5.0 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.0-rc5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/shirou/gopsutil/v3 v3.23.12 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
github.com/yusufpapurcu/wmi v1.2.3 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.45.0 // indirect
go.opentelemetry.io/otel v1.19.0 // indirect
go.opentelemetry.io/otel/metric v1.19.0 // indirect
go.opentelemetry.io/otel/trace v1.19.0 // indirect
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63 // indirect
golang.org/x/mod v0.12.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/tools v0.12.1-0.20230815132531-74c255bcf846 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect
google.golang.org/grpc v1.58.3 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

replace github.com/testcontainers/testcontainers-go => ../..
Loading