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

fix(modules.kafka): Use broker container IP instead of host IP for advertised broker listener #1989

Merged
merged 10 commits into from May 8, 2024
9 changes: 8 additions & 1 deletion modules/kafka/kafka.go
Expand Up @@ -72,12 +72,19 @@ func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomize
return err
}

inspect, err := c.Inspect(ctx)
if err != nil {
return err
}

hostname := inspect.Config.Hostname

port, err := c.MappedPort(ctx, publicPort)
if err != nil {
return err
}

scriptContent := fmt.Sprintf(starterScriptContent, host, port.Int(), host)
scriptContent := fmt.Sprintf(starterScriptContent, host, port.Int(), hostname)

return c.CopyToContainer(ctx, []byte(scriptContent), starterScript, 0o755)
},
Expand Down
32 changes: 32 additions & 0 deletions modules/kafka/kafka_test.go
Expand Up @@ -2,6 +2,7 @@ package kafka_test

import (
"context"
"io"
"strings"
"testing"

Expand All @@ -28,6 +29,8 @@ func TestKafka(t *testing.T) {
}
})

assertAdvertisedListeners(t, kafkaContainer)

if !strings.EqualFold(kafkaContainer.ClusterID, "kraftCluster") {
t.Fatalf("expected clusterID to be %s, got %s", "kraftCluster", kafkaContainer.ClusterID)
}
Expand Down Expand Up @@ -93,3 +96,32 @@ func TestKafka_invalidVersion(t *testing.T) {
t.Fatal(err)
}
}

// assertAdvertisedListeners checks that the advertised listeners are set correctly:
// - The BROKER:// protocol is using the hostname of the Kafka container
func assertAdvertisedListeners(t *testing.T, container testcontainers.Container) {
inspect, err := container.Inspect(context.Background())
if err != nil {
t.Fatal(err)
}

hostname := inspect.Config.Hostname

code, r, err := container.Exec(context.Background(), []string{"cat", "/usr/sbin/testcontainers_start.sh"})
if err != nil {
t.Fatal(err)
}

if code != 0 {
t.Fatalf("expected exit code to be 0, got %d", code)
}

bs, err := io.ReadAll(r)
if err != nil {
t.Fatal(err)
}

if !strings.Contains(string(bs), "BROKER://"+hostname+":9092") {
t.Fatalf("expected advertised listeners to contain %s, got %s", "BROKER://"+hostname+":9092", string(bs))
}
}