From 3292ea586276c08e80e2aa8b940f3e8cedd40f5a Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Wed, 24 Mar 2021 13:56:06 -0700 Subject: [PATCH] pkg/seccomp: use sync.Once to speed up IsEnabled It does not make sense to check if seccomp is supported by the kernel more than once per runtime, so let's use sync.Once to speed it up. A quick benchmark (old implementation, before this commit, after): BenchmarkIsEnabledOld-4 37183 27971 ns/op BenchmarkIsEnabled-4 1252161 947 ns/op BenchmarkIsEnabledOnce-4 666274008 2.14 ns/op Signed-off-by: Kir Kolyshkin --- pkg/seccomp/seccomp_linux.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pkg/seccomp/seccomp_linux.go b/pkg/seccomp/seccomp_linux.go index f324bde72..a23b492c6 100644 --- a/pkg/seccomp/seccomp_linux.go +++ b/pkg/seccomp/seccomp_linux.go @@ -33,9 +33,16 @@ package seccomp import ( + "sync" + "golang.org/x/sys/unix" ) +var ( + enabled bool + enabledOnce sync.Once +) + // isEnabled returns whether the kernel has been configured to support seccomp // (including the check for CONFIG_SECCOMP_FILTER kernel option). func isEnabled() bool { @@ -65,5 +72,9 @@ func isEnabled() bool { // EFAULT). IOW, EINVAL means "seccomp not supported", any other error // means it is supported. - return unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0) != unix.EINVAL + enabledOnce.Do(func() { + enabled = unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0) != unix.EINVAL + }) + + return enabled }