Toxiproxy¶
Since v0.37.0
Introduction¶
The Testcontainers module for Toxiproxy.
Adding this module to your project dependencies¶
Please run the following command to add the Toxiproxy module to your Go dependencies:
go get github.com/testcontainers/testcontainers-go/modules/toxiproxy
Usage example¶
ctx := context.Background()
toxiproxyContainer, err := tctoxiproxy.Run(
ctx,
"ghcr.io/shopify/toxiproxy:2.12.0",
)
defer func() {
if err := testcontainers.TerminateContainer(toxiproxyContainer); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
Module Reference¶
Run function¶
- Since v0.37.0
The Toxiproxy module exposes one entrypoint function to create the Toxiproxy container, and this function receives three parameters:
func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*Container, error)
context.Context
, the Go context.string
, the Docker image to use.testcontainers.ContainerCustomizer
, a variadic argument for passing options.
Container Ports¶
The Toxiproxy container exposes the following ports:
8474/tcp
, the Toxiproxy control port, exported astoxiproxy.ControlPort
.
Image¶
Use the second argument in the Run
function to set a valid Docker image.
In example: Run(context.Background(), "shopify/toxiproxy:2.12.0")
.
Container Options¶
When starting the Toxiproxy container, you can pass options in a variadic way to configure it.
WithProxy¶
- Since v0.37.0
The WithProxy
option allows you to specify a proxy to be created on the Toxiproxy container.
This option allocates a random port on the host and exposes it to the Toxiproxy container, allowing
you to create a unique proxy for a given service, starting from the 8666/tcp
port.
func WithProxy(name string, upstream string) Option
If this option is used in combination with the WithConfigFile
option, the proxy defined in this option
is added to the proxies defined in the config file.
Info
If you add proxies in a programmatic manner using the Toxiproxy client, then you need to manually add exposed ports in the Toxiproxy container.
WithConfigFile¶
- Since v0.37.0
The WithConfigFile
option allows you to specify a config file for the Toxiproxy container, in the form of an io.Reader
representing
the JSON file with the Toxiproxy configuration, in the valid format of the Toxiproxy configuration file.
[
{
"name": "redis",
"listen": "0.0.0.0:8666",
"upstream": "redis:6379",
"enabled": true
}
]
func WithConfigFile(r io.Reader) testcontainers.CustomizeRequestOption
If this option is used in combination with the WithProxy
option, the proxies defined in this option
are added to the proxies defined with the WithProxy
option.
The following options are exposed by the testcontainers
package.
Basic Options¶
WithExposedPorts
Since v0.37.0WithEnv
Since v0.29.0WithWaitStrategy
Since v0.20.0WithAdditionalWaitStrategy
Not available until the next release mainWithWaitStrategyAndDeadline
Since v0.20.0WithAdditionalWaitStrategyAndDeadline
Not available until the next release mainWithEntrypoint
Since v0.37.0WithEntrypointArgs
Since v0.37.0WithCmd
Since v0.37.0WithCmdArgs
Since v0.37.0WithLabels
Since v0.37.0
Lifecycle Options¶
WithLifecycleHooks
Not available until the next release mainWithAdditionalLifecycleHooks
Not available until the next release mainWithStartupCommand
Since v0.25.0WithAfterReadyCommand
Since v0.28.0
Files & Mounts Options¶
WithFiles
Since v0.37.0WithMounts
Since v0.37.0WithTmpfs
Since v0.37.0WithImageMount
Since v0.37.0
Build Options¶
WithDockerfile
Since v0.37.0
Logging Options¶
WithLogConsumers
Since v0.28.0WithLogConsumerConfig
Not available until the next release mainWithLogger
Since v0.29.0
Image Options¶
WithAlwaysPull
Not available until the next release mainWithImageSubstitutors
Since v0.26.0WithImagePlatform
Not available until the next release main
Networking Options¶
WithNetwork
Since v0.27.0WithNetworkByName
Not available until the next release mainWithBridgeNetwork
Not available until the next release mainWithNewNetwork
Since v0.27.0
Advanced Options¶
WithHostPortAccess
Since v0.31.0WithConfigModifier
Since v0.20.0WithHostConfigModifier
Since v0.20.0WithEndpointSettingsModifier
Since v0.20.0CustomizeRequest
Since v0.20.0WithName
Not available until the next release mainWithNoStart
Not available until the next release main
Experimental Options¶
WithReuseByName
Since v0.37.0
Container Methods¶
The Toxiproxy container exposes the following methods:
ProxiedEndpoint¶
- Since v0.37.0
The ProxiedEndpoint
method returns the host and port of the proxy for a given port. It's used to create new connections to the proxied service, and it returns an error in case the port has no proxy.
func (c *Container) ProxiedEndpoint(port int) (string, string, error)
proxiedRedisHost, proxiedRedisPort, err := toxiproxyContainer.ProxiedEndpoint(8666)
if err != nil {
log.Printf("failed to get toxiproxy container port: %s", err)
return
}
// Create a redis client that connects to the toxiproxy container.
// We are defining a read timeout of 2 seconds, because we are adding
// a latency toxic of 1.1 seconds to the request.
redisURI := fmt.Sprintf("redis://%s:%s?read_timeout=2s", proxiedRedisHost, proxiedRedisPort)
The above examples show how to get the proxied endpoint and use it to create a new connection to the proxied service, in this case a Redis client.
URI¶
- Since v0.37.0
The URI
method returns the URI of the Toxiproxy container, used to create a new Toxiproxy client.
func (c *Container) URI() string
toxiURI, err := toxiproxyContainer.URI(ctx)
if err != nil {
log.Printf("failed to get toxiproxy container uri: %s", err)
return
}
toxiproxyClient := toxiproxy.NewClient(toxiURI)
- the
toxiproxy
package comes from thegithub.com/Shopify/toxiproxy/v2/client
package. - the
toxiproxyContainer
variable has been created by theRun
function.
Examples¶
Programmatically create a proxy¶
const proxyPort = "8666"
// No need to create a proxy, as we are programmatically adding it below.
toxiproxyContainer, err := tctoxiproxy.Run(
ctx,
"ghcr.io/shopify/toxiproxy:2.12.0",
network.WithNetwork([]string{"toxiproxy"}, nw),
// explicitly expose the ports that will be proxied using the programmatic API
// of the toxiproxy client. Otherwise, the ports will not be exposed and the
// toxiproxy client will not be able to connect to the proxy.
testcontainers.WithExposedPorts(proxyPort+"/tcp"),
)
defer func() {
if err := testcontainers.TerminateContainer(toxiproxyContainer); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}
// Create the proxy using the network alias of the redis container,
// as they run on the same network.
proxy, err := toxiproxyClient.CreateProxy("redis", "0.0.0.0:"+proxyPort, "redis:6379")
if err != nil {
log.Printf("failed to create proxy: %s", err)
return
}
// Create a redis client that connects to the toxiproxy container.
// We are defining a read timeout of 2 seconds, because we are adding
// a latency toxic of 1 second to the request, +/- 100ms jitter.
redisURI := fmt.Sprintf("redis://%s:%s?read_timeout=2s", toxiproxyProxyHostIP, toxiproxyProxyPort.Port())
options, err := redis.ParseURL(redisURI)
if err != nil {
log.Printf("failed to parse url: %s", err)
return
}
redisCli := redis.NewClient(options)
defer func() {
if err := redisCli.FlushAll(ctx).Err(); err != nil {
log.Printf("failed to flush redis: %s", err)
}
}()
const (
latency = 1_000
jitter = 200
)
// Add a latency toxic to the proxy
_, err = proxy.AddToxic("latency_down", "latency", "downstream", 1.0, toxiproxy.Attributes{
"latency": latency,
"jitter": jitter,
})
if err != nil {
log.Printf("failed to add toxic: %s", err)
return
}