From 59f997601733c4355b240137a686b3ed4c0e44ba Mon Sep 17 00:00:00 2001 From: Shengjing Zhu Date: Thu, 11 Jan 2018 22:47:39 +0800 Subject: [PATCH] pkg/ip: don't write to /proc/sys if ipforward enabled This enables setup in a container env like systemd nspawn where /proc/sys is mouted as read only. Signed-off-by: Shengjing Zhu --- pkg/ip/ipforward_linux.go | 6 ++++++ pkg/ip/ipforward_linux_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 pkg/ip/ipforward_linux_test.go diff --git a/pkg/ip/ipforward_linux.go b/pkg/ip/ipforward_linux.go index abab3ecf..8216a2c3 100644 --- a/pkg/ip/ipforward_linux.go +++ b/pkg/ip/ipforward_linux.go @@ -15,6 +15,7 @@ package ip import ( + "bytes" "io/ioutil" "github.com/containernetworking/cni/pkg/types/current" @@ -51,5 +52,10 @@ func EnableForward(ips []*current.IPConfig) error { } func echo1(f string) error { + if content, err := ioutil.ReadFile(f); err == nil { + if bytes.Equal(bytes.TrimSpace(content), []byte("1")) { + return nil + } + } return ioutil.WriteFile(f, []byte("1"), 0644) } diff --git a/pkg/ip/ipforward_linux_test.go b/pkg/ip/ipforward_linux_test.go new file mode 100644 index 00000000..eeedcc2e --- /dev/null +++ b/pkg/ip/ipforward_linux_test.go @@ -0,0 +1,31 @@ +package ip + +import ( + "io/ioutil" + "os" + "time" + + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe("IpforwardLinux", func() { + It("echo1 must not write the file if content is 1", func() { + file, err := ioutil.TempFile(os.TempDir(), "containernetworking") + defer os.Remove(file.Name()) + err = echo1(file.Name()) + Expect(err).NotTo(HaveOccurred()) + statBefore, err := file.Stat() + Expect(err).NotTo(HaveOccurred()) + + // take a duration here, otherwise next file modification operation time + // will be same as previous one. + time.Sleep(100 * time.Millisecond) + + err = echo1(file.Name()) + Expect(err).NotTo(HaveOccurred()) + statAfter, err := file.Stat() + Expect(err).NotTo(HaveOccurred()) + Expect(statBefore.ModTime()).To(Equal(statAfter.ModTime())) + }) +})