Skip to content

Commit

Permalink
daemon: Make binary writing idempotent
Browse files Browse the repository at this point in the history
Fixes OCPBUGS-16921
  • Loading branch information
cgwalters committed Jul 27, 2023
1 parent 0cd135b commit 25e033a
Showing 1 changed file with 27 additions and 22 deletions.
49 changes: 27 additions & 22 deletions pkg/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 25e033a

Please sign in to comment.