Replace use of Sprintf with net.JoinHostPort

On IPv6 clusters, one of the most frequent problems I encounter is
assumptions that one can build a URL with a host and port simply by
using Sprintf, like this:

```go
fmt.Sprintf("http://%s:%d/foo", host, port)
```

When `host` is an IPv6 address, this produces an invalid URL as it must
be bracketed, like this:

```
http://[2001:4860:4860::8888]:9443
```

This change fixes the occurences of joining a host and port with the
purpose built `net.JoinHostPort` function.

I encounter this problem often enough that I started to [write a linter
for it](https://github.com/stbenjam/go-sprintf-host-port).  I don't
think the linter is quite ready for wide use yet, but I did run it
against the Kube codebase and found these.  While the host portion in
some of these changes may always be an FQDN or IPv4 IP today, it's an
easy thing that can break later on.
This commit is contained in:
Stephen Benjamin
2022-04-06 18:16:02 -04:00
parent 3bef1692ef
commit b351745c1c
8 changed files with 28 additions and 11 deletions

View File

@@ -18,9 +18,12 @@ package windows
import (
"fmt"
"net"
"strconv"
v1 "k8s.io/api/core/v1"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/kubernetes/test/e2e/framework"
e2enode "k8s.io/kubernetes/test/e2e/framework/node"
e2eservice "k8s.io/kubernetes/test/e2e/framework/service"
@@ -77,7 +80,7 @@ var _ = SIGDescribe("Services", func() {
framework.ExpectEqual(testPod.Spec.NodeSelector["kubernetes.io/os"], "windows")
ginkgo.By(fmt.Sprintf("checking connectivity Pod to curl http://%s:%d", nodeIP, nodePort))
assertConsistentConnectivity(f, testPod.ObjectMeta.Name, windowsOS, windowsCheck(fmt.Sprintf("http://%s:%d", nodeIP, nodePort)))
assertConsistentConnectivity(f, testPod.ObjectMeta.Name, windowsOS, windowsCheck(fmt.Sprintf("http://%s", net.JoinHostPort(nodeIP, strconv.Itoa(nodePort)))))
})