Fix hostport duplicate chain names

closes #55771
This commit is contained in:
Chun Chen 2017-11-06 18:27:35 +08:00
parent 86480fc0af
commit 932cf077ee
4 changed files with 30 additions and 2 deletions

View File

@ -21,6 +21,7 @@ import (
"crypto/sha256"
"encoding/base32"
"fmt"
"strconv"
"strings"
"sync"
@ -247,7 +248,7 @@ func (hm *hostportManager) closeHostports(hostportMappings []*PortMapping) error
// WARNING: Please do not change this function. Otherwise, HostportManager may not be able to
// identify existing iptables chains.
func getHostportChain(id string, pm *PortMapping) utiliptables.Chain {
hash := sha256.Sum256([]byte(id + string(pm.HostPort) + string(pm.Protocol)))
hash := sha256.Sum256([]byte(id + strconv.Itoa(int(pm.HostPort)) + string(pm.Protocol)))
encoded := base32.StdEncoding.EncodeToString(hash[:])
return utiliptables.Chain(kubeHostportChainPrefix + encoded[:16])
}

View File

@ -198,3 +198,16 @@ func TestHostportManager(t *testing.T) {
assert.EqualValues(t, true, port.closed)
}
}
func TestGetHostportChain(t *testing.T) {
m := make(map[string]int)
chain := getHostportChain("testrdma-2", &PortMapping{HostPort: 57119, Protocol: "TCP", ContainerPort: 57119})
m[string(chain)] = 1
chain = getHostportChain("testrdma-2", &PortMapping{HostPort: 55429, Protocol: "TCP", ContainerPort: 55429})
m[string(chain)] = 1
chain = getHostportChain("testrdma-2", &PortMapping{HostPort: 56833, Protocol: "TCP", ContainerPort: 56833})
m[string(chain)] = 1
if len(m) != 3 {
t.Fatal(m)
}
}

View File

@ -21,6 +21,7 @@ import (
"crypto/sha256"
"encoding/base32"
"fmt"
"strconv"
"strings"
"time"
@ -142,7 +143,7 @@ func writeLine(buf *bytes.Buffer, words ...string) {
// this because IPTables Chain Names must be <= 28 chars long, and the longer
// they are the harder they are to read.
func hostportChainName(pm *PortMapping, podFullName string) utiliptables.Chain {
hash := sha256.Sum256([]byte(string(pm.HostPort) + string(pm.Protocol) + podFullName))
hash := sha256.Sum256([]byte(strconv.Itoa(int(pm.HostPort)) + string(pm.Protocol) + podFullName))
encoded := base32.StdEncoding.EncodeToString(hash[:])
return utiliptables.Chain(kubeHostportChainPrefix + encoded[:16])
}

View File

@ -223,3 +223,16 @@ func matchRule(chain *fakeChain, match string) bool {
}
return false
}
func TestHostportChainName(t *testing.T) {
m := make(map[string]int)
chain := hostportChainName(&PortMapping{HostPort: 57119, Protocol: "TCP", ContainerPort: 57119}, "testrdma-2")
m[string(chain)] = 1
chain = hostportChainName(&PortMapping{HostPort: 55429, Protocol: "TCP", ContainerPort: 55429}, "testrdma-2")
m[string(chain)] = 1
chain = hostportChainName(&PortMapping{HostPort: 56833, Protocol: "TCP", ContainerPort: 56833}, "testrdma-2")
m[string(chain)] = 1
if len(m) != 3 {
t.Fatal(m)
}
}