From a608b7e7255a3bb84bd10dbe7127d36aa060280e Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sun, 14 Mar 2021 19:49:23 +0100 Subject: [PATCH] libcontainer/apparmor: use sync.Once for AppArmor detection Signed-off-by: Sebastiaan van Stijn --- libcontainer/apparmor/apparmor_linux.go | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/libcontainer/apparmor/apparmor_linux.go b/libcontainer/apparmor/apparmor_linux.go index 65e7c1d5545..5da14fb3b16 100644 --- a/libcontainer/apparmor/apparmor_linux.go +++ b/libcontainer/apparmor/apparmor_linux.go @@ -1,22 +1,29 @@ package apparmor import ( - "bytes" "errors" "fmt" "io/ioutil" "os" + "sync" "github.com/opencontainers/runc/libcontainer/utils" ) +var ( + appArmorEnabled bool + checkAppArmor sync.Once +) + // IsEnabled returns true if apparmor is enabled for the host. func IsEnabled() bool { - if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil { - buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled") - return err == nil && bytes.HasPrefix(buf, []byte("Y")) - } - return false + checkAppArmor.Do(func() { + if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil { + buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled") + appArmorEnabled = err == nil && len(buf) > 1 && buf[0] == 'Y' + } + }) + return appArmorEnabled } func setProcAttr(attr, value string) error {