From b87cf1ba9c0e51552300c8149e41f89e9d563dc0 Mon Sep 17 00:00:00 2001 From: Abhishek Chanda Date: Tue, 22 Mar 2016 17:16:59 -0700 Subject: [PATCH] pkg: add a function to generate chain names Adds a function to generate chain names for use in iptables and ports all drivers to use that function. Also adds tests for the said function. --- utils/utils.go | 20 ++++++++++++++++++++ utils/utils_suite_test.go | 13 +++++++++++++ utils/utils_test.go | 18 ++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 utils/utils.go create mode 100644 utils/utils_suite_test.go create mode 100644 utils/utils_test.go diff --git a/utils/utils.go b/utils/utils.go new file mode 100644 index 00000000..eaf48d0b --- /dev/null +++ b/utils/utils.go @@ -0,0 +1,20 @@ +package utils + +import ( + "crypto/sha512" + "fmt" +) + +// 29 - len('CNI') - 2*len('-') +const maxNameLen = 16 + +// Generates a chain name to be used with iptables. +// Ensures that the generated name is less than +// 29 chars in length +func FormatChainName(name string, id string) string { + h := sha512.Sum512([]byte(id)) + if len(name) > maxNameLen { + return fmt.Sprintf("CNI-%s-%x", name[:len(name)-maxNameLen], h[:8]) + } + return fmt.Sprintf("CNI-%s-%x", name, h[:8]) +} diff --git a/utils/utils_suite_test.go b/utils/utils_suite_test.go new file mode 100644 index 00000000..f160db60 --- /dev/null +++ b/utils/utils_suite_test.go @@ -0,0 +1,13 @@ +package utils_test + +import ( + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + + "testing" +) + +func TestUtils(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Utils Suite") +} diff --git a/utils/utils_test.go b/utils/utils_test.go new file mode 100644 index 00000000..e9b9f9bf --- /dev/null +++ b/utils/utils_test.go @@ -0,0 +1,18 @@ +package utils + +import ( + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe("Utils", func() { + It("should format a short name", func() { + chain := FormatChainName("test", "1234") + Expect(chain).To(Equal("CNI-test-d404559f602eab6f")) + }) + + It("should truncate a long name", func() { + chain := FormatChainName("testalongnamethatdoesnotmakesense", "1234") + Expect(chain).To(Equal("CNI-testalongnamethat-d404559f602eab6f")) + }) +})