mount-utils: only detect systemd when needed

The detectSystemd() function adds quite some logging when systemd is not
detected. This is not critical when the k8s.io/mount-utils package is
used by external applications or CSI-drivers. In that case, it may not
be required to detect systemd at all. To reduce logging in cases where
systemd does not need to be detected, add a hasSystemd() helper function
that calls detectSystemd() only once.
This commit is contained in:
Niels de Vos 2022-07-12 09:53:11 +02:00
parent 19a22f7637
commit a800b15d04
2 changed files with 21 additions and 3 deletions

View File

@ -58,7 +58,7 @@ const (
// kubelet is running in the host's root mount namespace.
type Mounter struct {
mounterPath string
withSystemd bool
withSystemd *bool
withSafeNotMountedBehavior bool
}
@ -70,11 +70,21 @@ var _ MounterForceUnmounter = &Mounter{}
func New(mounterPath string) Interface {
return &Mounter{
mounterPath: mounterPath,
withSystemd: detectSystemd(),
withSafeNotMountedBehavior: detectSafeNotMountedBehavior(),
}
}
// hasSystemd validates that the withSystemd bool is set, if it is not,
// detectSystemd will be called once for this Mounter instance.
func (mounter *Mounter) hasSystemd() bool {
if mounter.withSystemd == nil {
withSystemd := detectSystemd()
mounter.withSystemd = &withSystemd
}
return *mounter.withSystemd
}
// Mount mounts source to target as fstype with given options. 'source' and 'fstype' must
// be an empty string in case it's not required, e.g. for remount, or for auto filesystem
// type, where kernel handles fstype for you. The mount 'options' is a list of options,
@ -154,7 +164,7 @@ func (mounter *Mounter) doMount(mounterPath string, mountCmd string, source stri
mountCmd = mounterPath
}
if mounter.withSystemd && systemdMountRequired {
if mounter.hasSystemd() && systemdMountRequired {
// Try to run mount via systemd-run --scope. This will escape the
// service where kubelet runs and any fuse daemons will be started in a
// specific scope. kubelet service than can be restarted without killing

View File

@ -525,6 +525,14 @@ func TestSensitiveMountOptions(t *testing.T) {
}
}
func TestHasSystemd(t *testing.T) {
mounter := &Mounter{}
_ = mounter.hasSystemd()
if mounter.withSystemd == nil {
t.Error("Failed to run detectSystemd()")
}
}
func mountArgsContainString(t *testing.T, mountArgs []string, wanted string) bool {
for _, mountArg := range mountArgs {
if mountArg == wanted {