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¶
WithExposedPortsSince v0.37.0WithEnvSince v0.29.0WithWaitStrategySince v0.20.0WithAdditionalWaitStrategySince v0.38.0WithWaitStrategyAndDeadlineSince v0.20.0WithAdditionalWaitStrategyAndDeadlineSince v0.38.0WithEntrypointSince v0.37.0WithEntrypointArgsSince v0.37.0WithCmdSince v0.37.0WithCmdArgsSince v0.37.0WithLabelsSince v0.37.0
Lifecycle Options¶
WithLifecycleHooksSince v0.38.0WithAdditionalLifecycleHooksSince v0.38.0WithStartupCommandSince v0.25.0WithAfterReadyCommandSince v0.28.0
Files & Mounts Options¶
WithFilesSince v0.37.0WithMountsSince v0.37.0WithTmpfsSince v0.37.0WithImageMountSince v0.37.0
Build Options¶
WithDockerfileSince v0.37.0
Logging Options¶
WithLogConsumersSince v0.28.0WithLogConsumerConfigSince v0.38.0WithLoggerSince v0.29.0
Image Options¶
WithAlwaysPullSince v0.38.0WithImageSubstitutorsSince v0.26.0WithImagePlatformSince v0.38.0
Networking Options¶
WithNetworkSince v0.27.0WithNetworkByNameSince v0.38.0WithBridgeNetworkSince v0.38.0WithNewNetworkSince v0.27.0
Advanced Options¶
WithHostPortAccessSince v0.31.0WithConfigModifierSince v0.20.0WithHostConfigModifierSince v0.20.0WithEndpointSettingsModifierSince v0.20.0CustomizeRequestSince v0.20.0WithNameSince v0.38.0WithNoStartSince v0.38.0WithProviderNot available until the next release main
Experimental Options¶
WithReuseByNameSince 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
toxiproxypackage comes from thegithub.com/Shopify/toxiproxy/v2/clientpackage. - the
toxiproxyContainervariable has been created by theRunfunction.
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
}