pkg/utils: use name+id for hash and extend tests

This commit is contained in:
Stefan Junker
2016-03-30 19:17:37 +02:00
parent c33daf6706
commit 09248dfad9
2 changed files with 30 additions and 10 deletions

View File

@ -5,16 +5,15 @@ import (
"fmt" "fmt"
) )
// 29 - len('CNI') - 2*len('-') const MaxChainLength = 29 - len("CNI-")
const maxNameLen = 16
// Generates a chain name to be used with iptables. // Generates a chain name to be used with iptables.
// Ensures that the generated name is less than // Ensures that the generated name is less than
// 29 chars in length // 29 chars in length
func FormatChainName(name string, id string) string { func FormatChainName(name string, id string) string {
h := sha512.Sum512([]byte(id)) chain := fmt.Sprintf("%x", sha512.Sum512([]byte(name+id)))
if len(name) > maxNameLen { if len(chain) > MaxChainLength {
return fmt.Sprintf("CNI-%s-%x", name[:len(name)-maxNameLen], h[:8]) chain = chain[:MaxChainLength]
} }
return fmt.Sprintf("CNI-%s-%x", name, h[:8]) return fmt.Sprintf("CNI-%s", chain)
} }

View File

@ -6,13 +6,34 @@ import (
) )
var _ = Describe("Utils", func() { var _ = Describe("Utils", func() {
It("should format a short name", func() { It("must format a short name", func() {
chain := FormatChainName("test", "1234") chain := FormatChainName("test", "1234")
Expect(chain).To(Equal("CNI-test-d404559f602eab6f")) Expect(len(chain) == 29).To(Equal(true))
Expect(chain).To(Equal("CNI-2bbe0c48b91a7d1b8a6753a8b"))
}) })
It("should truncate a long name", func() { It("must truncate a long name", func() {
chain := FormatChainName("testalongnamethatdoesnotmakesense", "1234") chain := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
Expect(chain).To(Equal("CNI-testalongnamethat-d404559f602eab6f")) Expect(len(chain) == 29).To(Equal(true))
Expect(chain).To(Equal("CNI-374f33fe84ab0ed84dcdebe38"))
}) })
It("must be predictable", func() {
chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
Expect(len(chain1) == 29).To(Equal(true))
Expect(len(chain2) == 29).To(Equal(true))
Expect(chain1).To(Equal(chain2))
})
It("must change when a character changes", func() {
chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234")
chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1235")
Expect(len(chain1) == 29).To(Equal(true))
Expect(len(chain2) == 29).To(Equal(true))
Expect(chain1).To(Equal("CNI-374f33fe84ab0ed84dcdebe38"))
Expect(chain2).NotTo(Equal("CNI-374f33fe84ab0ed84dcdebe38"))
Expect(chain1).NotTo(Equal(chain2))
})
}) })