From 0b542721e9396358630c28f6d9b329ba2595ec73 Mon Sep 17 00:00:00 2001 From: crStiv Date: Fri, 27 Dec 2024 02:44:39 +0100 Subject: [PATCH 1/2] Update nat.go --- p2p/nat/nat.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/p2p/nat/nat.go b/p2p/nat/nat.go index c65604426833..8d922c97f31d 100644 --- a/p2p/nat/nat.go +++ b/p2p/nat/nat.go @@ -21,6 +21,7 @@ import ( "errors" "fmt" "net" + "os" "strings" "sync" "time" @@ -133,7 +134,13 @@ func Map(m Interface, c <-chan struct{}, protocol string, extport, intport int, // Mapping operations will not return an error but won't actually do anything. type ExtIP net.IP -func (n ExtIP) ExternalIP() (net.IP, error) { return net.IP(n), nil } +func (n ExtIP) ExternalIP() (net.IP, error) { + if IsKubernetesEnvironment() { + return net.IP(n), nil + } + return net.IP(n), nil +} + func (n ExtIP) String() string { return fmt.Sprintf("ExtIP(%v)", net.IP(n)) } // These do nothing. @@ -240,3 +247,12 @@ func (n *autodisc) wait() error { } return nil } + +// IsKubernetesEnvironment detects if the process is running inside Kubernetes cluster +// by checking for the presence of standard K8s environment variables. +func IsKubernetesEnvironment() bool { + if _, exists := os.LookupEnv("KUBERNETES_SERVICE_HOST"); exists { + return true + } + return false +} From 39101e314f357cf269247a320aeab47aef17d322 Mon Sep 17 00:00:00 2001 From: crStiv Date: Fri, 27 Dec 2024 02:46:38 +0100 Subject: [PATCH 2/2] Update nat_test.go --- p2p/nat/nat_test.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/p2p/nat/nat_test.go b/p2p/nat/nat_test.go index 814e6d9e14c8..1bacc1af302d 100644 --- a/p2p/nat/nat_test.go +++ b/p2p/nat/nat_test.go @@ -18,11 +18,12 @@ package nat import ( "net" + "os" "testing" "time" ) -// This test checks that autodisc doesn't hang and returns +// This test ensures that autodisc doesn't hang and returns // consistent results when multiple goroutines call its methods // concurrently. func TestAutoDiscRace(t *testing.T) { @@ -61,3 +62,21 @@ func TestAutoDiscRace(t *testing.T) { } } } + +func TestExtIPInKubernetes(t *testing.T) { + // Setting up the test environment + os.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + defer os.Unsetenv("KUBERNETES_SERVICE_HOST") + + testIP := net.ParseIP("192.0.2.1") + extIP := ExtIP(testIP) + + // Verify that the IP is returned unchanged in Kubernetes + ip, err := extIP.ExternalIP() + if err != nil { + t.Fatalf("ExternalIP failed: %v", err) + } + if !ip.Equal(testIP) { + t.Errorf("wrong IP: got %v, want %v", ip, testIP) + } +}