From 7c22973f9fec1525f8db7d0b29a152dbfc1aa7f7 Mon Sep 17 00:00:00 2001 From: Tomofumi Hayashi Date: Thu, 13 Apr 2023 22:40:16 +0900 Subject: [PATCH] Add mutex lock for load confs in GetDefaultNetworks (#1073) Thick server's chroot mutex is missing in GetDefaultNetworks, that touch the pod filesystem. This change adds mutex lock there and prevent race condition. Fix #1072 --- pkg/k8sclient/k8sclient.go | 13 +++++++++++++ pkg/server/server.go | 4 +++- pkg/types/conf.go | 4 ++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/pkg/k8sclient/k8sclient.go b/pkg/k8sclient/k8sclient.go index 7e797a25e..212c281d1 100644 --- a/pkg/k8sclient/k8sclient.go +++ b/pkg/k8sclient/k8sclient.go @@ -542,6 +542,13 @@ func getNetDelegate(client *ClientInfo, pod *v1.Pod, netname, confdir, namespace } // option2) search CNI json config file, which has as CNI name, from confDir + + // acquire lock to access file + if types.ChrootMutex != nil { + types.ChrootMutex.Lock() + defer types.ChrootMutex.Unlock() + } + configBytes, err = netutils.GetCNIConfigFromFile(netname, confdir) if err == nil { delegate, err := types.LoadDelegateNetConf(configBytes, nil, "", "") @@ -551,6 +558,12 @@ func getNetDelegate(client *ClientInfo, pod *v1.Pod, netname, confdir, namespace return delegate, resourceMap, nil } } else { + // acquire lock to access file + if types.ChrootMutex != nil { + types.ChrootMutex.Lock() + defer types.ChrootMutex.Unlock() + } + fInfo, err := os.Stat(netname) if err != nil { return nil, resourceMap, err diff --git a/pkg/server/server.go b/pkg/server/server.go index 40917faee..0a4f46c04 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -136,10 +136,12 @@ func NewCNIServer(daemonConfig *ControllerNetConf, serverConfig []byte) (*Server exec := invoke.Exec(nil) if daemonConfig.ChrootDir != "" { - exec = &ChrootExec{ + chrootExec := &ChrootExec{ Stderr: os.Stderr, chrootDir: daemonConfig.ChrootDir, } + types.ChrootMutex = &chrootExec.mu + exec = chrootExec logging.Verbosef("server configured with chroot: %s", daemonConfig.ChrootDir) } diff --git a/pkg/types/conf.go b/pkg/types/conf.go index ae95ab121..9ed5ccef7 100644 --- a/pkg/types/conf.go +++ b/pkg/types/conf.go @@ -21,6 +21,7 @@ import ( "net" "os" "strings" + "sync" "github.com/containernetworking/cni/libcni" "github.com/containernetworking/cni/pkg/skel" @@ -39,6 +40,9 @@ const ( defaultNonIsolatedNamespace = "default" ) +// ChrootMutex provides lock to access host filesystem +var ChrootMutex *sync.Mutex + // LoadDelegateNetConfList reads DelegateNetConf from bytes func LoadDelegateNetConfList(bytes []byte, delegateConf *DelegateNetConf) error { logging.Debugf("LoadDelegateNetConfList: %s, %v", string(bytes), delegateConf)