From 83e6b65566b67700938501d6e07fbbbe0b8cf87e Mon Sep 17 00:00:00 2001 From: Lantao Liu Date: Tue, 5 Jun 2018 18:25:03 +0000 Subject: [PATCH] Select ipv4 first if there is one. Signed-off-by: Lantao Liu --- pkg/server/sandbox_run.go | 12 +++++++++++- pkg/server/sandbox_run_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/pkg/server/sandbox_run.go b/pkg/server/sandbox_run.go index 5fa198e4a..fe216682e 100644 --- a/pkg/server/sandbox_run.go +++ b/pkg/server/sandbox_run.go @@ -524,7 +524,7 @@ func (c *criService) setupPod(id string, path string, config *runtime.PodSandbox } // Check if the default interface has IP config if configs, ok := result.Interfaces[defaultIfName]; ok && len(configs.IPConfigs) > 0 { - return configs.IPConfigs[0].IP.String(), nil + return selectPodIP(configs.IPConfigs), nil } // If it comes here then the result was invalid so destroy the pod network and return error if err := c.teardownPod(id, path, config); err != nil { @@ -550,6 +550,16 @@ func toCNIPortMappings(criPortMappings []*runtime.PortMapping) []cni.PortMapping return portMappings } +// selectPodIP select an ip from the ip list. It prefers ipv4 more than ipv6. +func selectPodIP(ipConfigs []*cni.IPConfig) string { + for _, c := range ipConfigs { + if c.IP.To4() != nil { + return c.IP.String() + } + } + return ipConfigs[0].IP.String() +} + // untrustedWorkload returns true if the sandbox contains untrusted workload. func untrustedWorkload(config *runtime.PodSandboxConfig) bool { return config.GetAnnotations()[annotations.UntrustedWorkload] == "true" diff --git a/pkg/server/sandbox_run_test.go b/pkg/server/sandbox_run_test.go index 4808c20af..e72dfbec7 100644 --- a/pkg/server/sandbox_run_test.go +++ b/pkg/server/sandbox_run_test.go @@ -17,6 +17,7 @@ limitations under the License. package server import ( + "net" "os" "path/filepath" "testing" @@ -407,6 +408,31 @@ func TestToCNIPortMappings(t *testing.T) { } } +func TestSelectPodIP(t *testing.T) { + for desc, test := range map[string]struct { + ips []string + expected string + }{ + "ipv4 should be picked even if ipv6 comes first": { + ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43"}, + expected: "192.168.17.43", + }, + "ipv6 should be picked when there is no ipv4": { + ips: []string{"2001:db8:85a3::8a2e:370:7334"}, + expected: "2001:db8:85a3::8a2e:370:7334", + }, + } { + t.Logf("TestCase %q", desc) + var ipConfigs []*cni.IPConfig + for _, ip := range test.ips { + ipConfigs = append(ipConfigs, &cni.IPConfig{ + IP: net.ParseIP(ip), + }) + } + assert.Equal(t, test.expected, selectPodIP(ipConfigs)) + } +} + func TestTypeurlMarshalUnmarshalSandboxMeta(t *testing.T) { for desc, test := range map[string]struct { configChange func(*runtime.PodSandboxConfig)