From 9f42ae70e1cb41cee40cbab331877354ac54d45e Mon Sep 17 00:00:00 2001 From: Arnob kumar saha Date: Tue, 5 Dec 2023 12:20:28 +0600 Subject: [PATCH] Check if seccomp profile is set before assign; Check only once Signed-off-by: Arnob kumar saha --- policy/secomp/lib.go | 58 +++++++++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/policy/secomp/lib.go b/policy/secomp/lib.go index 8801c1844..a874a4f90 100644 --- a/policy/secomp/lib.go +++ b/policy/secomp/lib.go @@ -18,6 +18,7 @@ package secomp import ( "fmt" + "sync" "kmodules.xyz/client-go/discovery" meta_util "kmodules.xyz/client-go/meta" @@ -28,35 +29,42 @@ import ( "k8s.io/client-go/rest" ) -var profile string +var ( + profile string + seccomp *core.SeccompProfile + once sync.Once +) func init() { - if meta_util.PossiblyInCluster() { - cfg, err := rest.InClusterConfig() - if err != nil { - panic(err) - } - kc := kubernetes.NewForConfigOrDie(cfg) - yes, err := discovery.CheckAPIVersion(kc.Discovery(), ">= 1.27") - if err != nil { - panic(err) - } - if yes { - profile = string(core.SeccompProfileTypeRuntimeDefault) - } - } pflag.StringVar(&profile, "default-seccomp-profile-type", profile, "Default seccomp profile") } func DefaultSeccompProfile() *core.SeccompProfile { - if profile == "" { - return nil - } else if profile != string(core.SeccompProfileTypeUnconfined) && - profile != string(core.SeccompProfileTypeRuntimeDefault) && - profile != string(core.SeccompProfileTypeLocalhost) { - panic(fmt.Errorf("unknown seccomp profile type %s", profile)) - } - return &core.SeccompProfile{ - Type: core.SeccompProfileType(profile), - } + once.Do(func() { + if meta_util.PossiblyInCluster() { + cfg, err := rest.InClusterConfig() + if err != nil { + panic(err) + } + kc := kubernetes.NewForConfigOrDie(cfg) + yes, err := discovery.CheckAPIVersion(kc.Discovery(), ">= 1.27") + if err != nil { + panic(err) + } + if yes && profile == "" { + profile = string(core.SeccompProfileTypeRuntimeDefault) + } + } + if profile == "" { + seccomp = nil + } else if profile != string(core.SeccompProfileTypeUnconfined) && + profile != string(core.SeccompProfileTypeRuntimeDefault) && + profile != string(core.SeccompProfileTypeLocalhost) { + panic(fmt.Errorf("unknown seccomp profile type %s", profile)) + } + seccomp = &core.SeccompProfile{ + Type: core.SeccompProfileType(profile), + } + }) + return seccomp }