From 25e033aefb28c9ca227fe7e17588871c93049d53 Mon Sep 17 00:00:00 2001 From: Colin Walters Date: Thu, 27 Jul 2023 13:05:57 -0400 Subject: [PATCH] daemon: Make binary writing idempotent Fixes OCPBUGS-16921 --- pkg/daemon/daemon.go | 49 ++++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/pkg/daemon/daemon.go b/pkg/daemon/daemon.go index 6a9f2079ca..d5d6a67791 100644 --- a/pkg/daemon/daemon.go +++ b/pkg/daemon/daemon.go @@ -471,35 +471,40 @@ func ReexecuteForTargetRoot(target string) error { } else { klog.Info("assuming we can use container binary chroot() to host") } - sourceBinary := "/usr/bin/machine-config-daemon" + sourceBinarySuffix - src, err := os.Open(sourceBinary) - if err != nil { - return fmt.Errorf("opening %s: %w", sourceBinary, err) - } - defer src.Close() targetBinBase := "run/bin/machine-config-daemon" targetBin := filepath.Join(target, targetBinBase) - targetBinDir := filepath.Dir(targetBin) - if _, err := os.Stat(targetBinDir); err != nil { - if err := os.Mkdir(targetBinDir, 0o755); err != nil { - return fmt.Errorf("mkdir %s: %w", targetBinDir, err) + + // Be idempotent + if _, err := os.Stat(targetBin); err != nil { + sourceBinary := "/usr/bin/machine-config-daemon" + sourceBinarySuffix + src, err := os.Open(sourceBinary) + if err != nil { + return fmt.Errorf("opening %s: %w", sourceBinary, err) } - } + defer src.Close() - f, err := os.Create(targetBin) - if err != nil { - return fmt.Errorf("writing %s: %w", targetBin, err) - } - if _, err := io.Copy(f, src); err != nil { + targetBinDir := filepath.Dir(targetBin) + if _, err := os.Stat(targetBinDir); err != nil { + if err := os.Mkdir(targetBinDir, 0o755); err != nil { + return fmt.Errorf("mkdir %s: %w", targetBinDir, err) + } + } + + f, err := os.Create(targetBin) + if err != nil { + return fmt.Errorf("writing %s: %w", targetBin, err) + } + if _, err := io.Copy(f, src); err != nil { + f.Close() + return fmt.Errorf("writing %s: %w", targetBin, err) + } + if err := f.Chmod(0o755); err != nil { + return err + } + // Must close our writable fd f.Close() - return fmt.Errorf("writing %s: %w", targetBin, err) - } - if err := f.Chmod(0o755); err != nil { - return err } - // Must close our writable fd - f.Close() if err := syscall.Chroot(target); err != nil { return fmt.Errorf("failed to chroot to %s: %w", target, err)