use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
#[cfg(target_os = "linux")]
mod linux_image;
#[cfg(all(target_os = "linux", feature = "test-hooks"))]
pub use linux_image::prepare_fixture_pin;
#[rustfmt::skip]
test_support_visibility! {
struct PinnedExecutable {
#[cfg(any(test, feature = "test-support"))]
pub executable: PathBuf,
#[cfg(not(any(test, feature = "test-support")))]
executable: PathBuf,
#[cfg(any(test, feature = "test-support"))]
pub directory: PathBuf,
#[cfg(not(any(test, feature = "test-support")))]
directory: PathBuf,
state: Mutex<PinState>,
}
}
struct PinState {
owner: Option<std::fs::File>,
#[cfg(any(target_os = "linux", target_os = "macos"))]
source: std::fs::File,
#[cfg(target_os = "linux")]
image_key: linux_image::ImageKey,
#[cfg(target_os = "linux")]
pin_identity: linux_image::PinIdentity,
}
#[rustfmt::skip]
test_support_visibility! {
static PINNED: OnceLock<PinnedExecutable> = OnceLock::new();
}
thread_local! {
static TASK_IMAGE: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
}
const OWNER_LOCK: &str = "owner.lock";
pub const TASK_IMAGE_DIR: &str = "startup-image";
#[cfg(target_os = "macos")]
struct StartupSource {
path: PathBuf,
file: std::fs::File,
}
#[cfg(target_os = "macos")]
static SOURCE: OnceLock<Result<StartupSource, String>> = OnceLock::new();
pub fn capture_at_startup() {
#[cfg(target_os = "macos")]
SOURCE.get_or_init(|| {
let path = std::env::current_exe()
.and_then(|path| path.canonicalize())
.map_err(|error| error.to_string())?;
let file = std::fs::File::open(&path).map_err(|error| error.to_string())?;
Ok(StartupSource { path, file })
});
}
pub fn initialize() -> io::Result<()> {
if PINNED.get().is_some() {
return Ok(());
}
let storage = crate::storage_path::storage_dir(None);
let pin = prepare(&storage)?;
PINNED
.set(pin)
.map_err(|_| io::Error::other("executable pin was initialized concurrently"))
}
#[rustfmt::skip]
test_support_visibility! {
fn prepare(storage: &Path) -> io::Result<PinnedExecutable> {
#[cfg(target_os = "macos")]
capture_at_startup();
#[cfg(target_os = "macos")]
let source = SOURCE
.get()
.expect("startup source captured")
.as_ref()
.map_err(|error| io::Error::other(error.clone()))?;
#[cfg(target_os = "macos")]
let mut source_file = source.file.try_clone()?;
#[cfg(target_os = "macos")]
let source_path = source.path.clone();
#[cfg(target_os = "linux")]
let source_file = std::fs::File::open(linux_image_path())?;
#[cfg(target_os = "linux")]
let image_key = linux_image::ImageKey::new(&source_file)?;
crate::private_storage::open_root(storage)?;
let storage = storage.canonicalize()?;
let run = storage.join("run");
match crate::private_storage::create_dir(&run) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error),
}
if !std::fs::symlink_metadata(&run)?.file_type().is_dir() {
return Err(io::Error::other(
"AFT storage run domain is not a directory",
));
}
crate::private_storage::tighten_open_dir(&storage, &run);
cleanup(&run)?;
let pid = std::process::id();
let start = crate::process_identity::process_start_time_ms(pid)
.ok_or_else(|| io::Error::other("cannot determine executable pin owner start time"))?;
let directory = run.join(format!("aft-pinned-{pid}-{start}"));
crate::private_storage::create_dir(&directory)?;
let result = (|| {
let owner = owner_lock(&directory)?;
#[cfg(target_os = "linux")]
let (executable, pin_identity) = image_key.pin(&run, &source_file)?;
#[cfg(target_os = "macos")]
let executable = {
let destination = directory.join("aft");
materialize(&source_path, &mut source_file, &destination, link_image)?;
warm_new_image(&destination);
destination
};
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let executable = std::env::current_exe()?;
std::fs::metadata(&executable)?;
Ok(PinnedExecutable {
executable,
directory: directory.clone(),
state: Mutex::new(PinState {
owner: Some(owner),
#[cfg(any(target_os = "linux", target_os = "macos"))]
source: source_file,
#[cfg(target_os = "linux")]
image_key,
#[cfg(target_os = "linux")]
pin_identity,
}),
})
})();
if result.is_err() {
let _ = std::fs::remove_dir_all(directory);
}
result
}
}
fn cleanup(run: &Path) -> io::Result<()> {
for entry in std::fs::read_dir(run)? {
let entry = entry?;
let name = entry.file_name();
let Some((pid, start)) = owner(&name.to_string_lossy()) else {
continue;
};
if !entry.file_type()?.is_dir() {
continue;
}
let alive = match crate::process_identity::process_start_time_ms(pid) {
Some(actual) => actual == start,
None => crate::fs_lock::process_alive(pid),
};
if !alive {
let lease_path = entry.path().join(OWNER_LOCK);
let lease = if lease_path.try_exists()? {
let mut options = crate::private_storage::options();
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW);
}
let Ok(file) = options.read(true).write(true).open(&lease_path) else {
continue;
};
if file.try_lock().is_err() {
continue;
}
Some(file)
} else {
None
};
drop(lease);
match std::fs::remove_dir_all(entry.path()) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
}
Ok(())
}
fn owner_lock(directory: &Path) -> io::Result<std::fs::File> {
let file = crate::private_storage::options()
.read(true)
.write(true)
.create_new(true)
.open(directory.join(OWNER_LOCK))?;
file.lock_shared()?;
Ok(file)
}
impl PinnedExecutable {
fn path(&self) -> io::Result<PathBuf> {
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
#[cfg(target_os = "linux")]
let has_image = self
.executable
.symlink_metadata()
.is_ok_and(|metadata| state.pin_identity.matches(&metadata));
#[cfg(not(target_os = "linux"))]
let has_image = self.executable.is_file();
if has_image && self.directory.is_dir() {
return Ok(self.executable.clone());
}
crate::slog_warn!(
"startup executable pin missing; restoring {}",
self.executable.display()
);
crate::private_storage::create_dir_all(&self.directory)?;
if !self.directory.join(OWNER_LOCK).try_exists()? {
state.owner = Some(owner_lock(&self.directory)?);
}
#[cfg(target_os = "linux")]
{
(_, state.pin_identity) = state.image_key.pin(
self.directory.parent().expect("pin owner directory in run"),
&state.source,
)?;
}
#[cfg(target_os = "macos")]
{
let temporary = self.directory.join("aft.repin");
let _ = std::fs::remove_file(&temporary);
materialize(&self.executable, &mut state.source, &temporary, |_, _| {
Err(io::Error::other("repair from held startup image"))
})?;
std::fs::rename(temporary, &self.executable)?;
}
std::fs::metadata(&self.executable)?;
Ok(self.executable.clone())
}
#[rustfmt::skip]
test_support_visibility! {
fn cleanup_at_exit(&self) {
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
state.owner.take();
let _ = std::fs::remove_dir_all(&self.directory);
}
}
fn task_image(&self, task_io: &Path) -> io::Result<PathBuf> {
let executable = self.path()?;
let directory = task_io.join(TASK_IMAGE_DIR);
crate::private_storage::create_dir(&directory)?;
let destination = task_executable(task_io);
#[cfg(unix)]
{
#[cfg(target_os = "linux")]
std::os::unix::fs::symlink(&executable, &destination)?;
#[cfg(not(target_os = "linux"))]
{
let mut source = std::fs::File::open(&executable)?;
materialize(&executable, &mut source, &destination, |from, to| {
std::fs::hard_link(from, to)
})?;
}
let entry = self.directory.join("shims/gh");
let retained = directory.join("shims/gh");
match std::fs::symlink_metadata(&entry) {
Ok(metadata) if metadata.is_symlink() => {
let target = std::fs::read_link(&entry)?;
let target = if target == self.executable {
destination
} else {
target
};
crate::private_storage::create_dir(&directory.join("shims"))?;
std::os::unix::fs::symlink(target, &retained)?;
}
Ok(metadata) if metadata.is_file() => {
crate::private_storage::create_dir(&directory.join("shims"))?;
std::fs::copy(&entry, &retained)?;
}
Ok(_) => return Err(io::Error::other("unexpected gh shim file type")),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
#[cfg(windows)]
{
if std::fs::hard_link(&executable, &destination).is_err() {
std::fs::copy(&executable, &destination)?;
}
let shim = self.directory.join("shims/gh.cmd");
if shim.is_file() {
let contents = std::fs::read(&shim)?;
let contents = if contents == crate::gh_shim_paths::windows_gh_cmd(&executable) {
crate::gh_shim_paths::windows_gh_cmd(&destination)
} else {
contents
};
crate::private_storage::create_dir(&directory.join("shims"))?;
std::fs::write(directory.join("shims/gh.cmd"), contents)?;
}
}
Ok(directory)
}
}
pub fn with_task_image<R>(task_io: &Path, run: impl FnOnce() -> R) -> io::Result<R> {
let Some(pin) = PINNED.get() else {
return Ok(run());
};
let directory = pin.task_image(task_io)?;
struct Scope(Option<PathBuf>);
impl Drop for Scope {
fn drop(&mut self) {
TASK_IMAGE.with(|slot| {
slot.replace(self.0.take());
});
}
}
let _scope = Scope(TASK_IMAGE.with(|slot| slot.replace(Some(directory))));
Ok(run())
}
pub fn task_executable(task_io: &Path) -> PathBuf {
task_io
.join(TASK_IMAGE_DIR)
.join(if cfg!(windows) { "aft.exe" } else { "aft" })
}
pub fn retain_task_environment(
task_io: &Path,
environment: &mut std::collections::HashMap<String, String>,
) -> io::Result<()> {
with_task_image(task_io, || {
let mut values = environment
.iter()
.map(|(key, value)| (key.into(), value.into()))
.collect();
task_environment(&task_executable(task_io), &mut values);
*environment = values
.into_iter()
.map(|(key, value)| {
(
key.to_string_lossy().into_owned(),
value.to_string_lossy().into_owned(),
)
})
.collect();
})
}
pub fn is_dead_pin_path(path: &Path) -> bool {
path.is_absolute()
&& path.ancestors().any(|ancestor| {
ancestor
.file_name()
.and_then(|name| name.to_str())
.and_then(owner)
.is_some()
&& ancestor.parent().and_then(Path::file_name) == Some(std::ffi::OsStr::new("run"))
})
&& matches!(path.try_exists(), Ok(false))
}
pub fn task_environment(
launcher: &Path,
environment: &mut std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>,
) {
let Some(pin) = PINNED.get() else {
return;
};
let Some(directory) = launcher
.parent()
.filter(|path| path.file_name() == Some(std::ffi::OsStr::new(TASK_IMAGE_DIR)))
else {
return;
};
let redirect = |path: &Path| {
if path == pin.executable {
return launcher.to_path_buf();
}
path.strip_prefix(&pin.directory)
.map(|suffix| directory.join(suffix))
.unwrap_or_else(|_| path.to_path_buf())
};
for key in [
crate::gh_shim_paths::GH_SHIMS_DIR_ENV,
crate::gh_shim_paths::GH_SHIM_BINARY_ENV,
] {
if let Some(value) = environment.get_mut(std::ffi::OsStr::new(key)) {
*value = redirect(Path::new(value)).into_os_string();
}
}
if let Some(value) = environment.get_mut(std::ffi::OsStr::new("PATH")) {
let entries = std::env::split_paths(value)
.map(|path| redirect(&path))
.filter(|path| !is_dead_pin_path(path))
.collect::<Vec<_>>();
if let Ok(path) = std::env::join_paths(entries) {
*value = path;
}
}
}
fn owner(name: &str) -> Option<(u32, u64)> {
let (pid, start) = name.strip_prefix("aft-pinned-")?.split_once('-')?;
Some((pid.parse().ok()?, start.parse().ok()?))
}
#[cfg(target_os = "macos")]
fn link_image(source: &Path, destination: &Path) -> io::Result<()> {
let _ = (source, destination);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"the daemon's executable is never hard-linked",
))
}
#[cfg(all(unix, not(target_os = "linux")))]
fn materialize(
source_path: &Path,
source: &mut std::fs::File,
destination: &Path,
link: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
match link(source_path, destination) {
Ok(()) => {
let held = source.metadata()?;
let linked = std::fs::metadata(destination)?;
if (held.dev(), held.ino()) != (linked.dev(), linked.ino()) {
let _ = std::fs::remove_file(destination);
return Err(io::Error::other("deployment image changed while pinning"));
}
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => return Err(error),
Err(_) => {
#[cfg(target_os = "macos")]
if clone_held_image(source, destination).is_ok() {
return Ok(());
}
let mut output = crate::private_storage::executable_options()
.write(true)
.create_new(true)
.open(destination)?;
use std::io::Write;
use std::os::unix::fs::FileExt;
let mut offset = 0;
let mut buffer = [0; 64 * 1024];
loop {
let count = match source.read_at(&mut buffer, offset) {
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
result => result?,
};
if count == 0 {
break;
}
output.write_all(&buffer[..count])?;
offset += count as u64;
}
aft_store::sync::sync_all(&output, destination)?;
output.set_permissions(std::fs::Permissions::from_mode(0o500))?;
}
}
Ok(())
}
#[cfg(target_os = "macos")]
fn warm_new_image(image: &Path) {
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
const WARM_BUDGET: std::time::Duration = std::time::Duration::from_secs(30);
let started = std::time::Instant::now();
let mut child = match Command::new(image)
.env_clear()
.args(["gh-shim", "--shim-version"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0)
.spawn()
{
Ok(child) => child,
Err(error) => {
log::warn!("pinned image first launch failed to start: {error}");
return;
}
};
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if started.elapsed() < WARM_BUDGET => {
std::thread::sleep(std::time::Duration::from_millis(10))
}
_ => {
unsafe {
libc::kill(-(child.id() as i32), libc::SIGKILL);
}
let _ = child.wait();
log::warn!(
"pinned image first launch did not finish within {}s",
WARM_BUDGET.as_secs()
);
return;
}
}
}
let elapsed = started.elapsed();
if elapsed > std::time::Duration::from_secs(1) {
log::info!("pinned image first launch took {}ms", elapsed.as_millis());
}
}
#[cfg(target_os = "macos")]
fn clone_held_image(source: &std::fs::File, destination: &Path) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::AsRawFd;
let target =
std::ffi::CString::new(destination.as_os_str().as_bytes()).map_err(io::Error::other)?;
if unsafe { libc::fclonefileat(source.as_raw_fd(), libc::AT_FDCWD, target.as_ptr(), 0) } != 0 {
return Err(io::Error::last_os_error());
}
if let Err(error) =
std::fs::set_permissions(destination, std::fs::Permissions::from_mode(0o500))
{
let _ = std::fs::remove_file(destination);
return Err(error);
}
Ok(())
}
pub fn cleanup_at_exit() {
if let Some(pin) = PINNED.get() {
pin.cleanup_at_exit();
}
}
pub fn startup_image_metadata() -> Option<std::fs::Metadata> {
#[cfg(target_os = "linux")]
{
std::fs::metadata(linux_image_path()).ok()
}
#[cfg(target_os = "macos")]
{
capture_at_startup();
SOURCE.get()?.as_ref().ok()?.file.metadata().ok()
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
std::env::current_exe().and_then(std::fs::metadata).ok()
}
}
pub fn path() -> io::Result<PathBuf> {
#[cfg(not(target_os = "linux"))]
if let Some(directory) = TASK_IMAGE.with(|slot| slot.borrow().clone()) {
return Ok(directory.join(if cfg!(windows) { "aft.exe" } else { "aft" }));
}
if let Some(pin) = PINNED.get() {
return pin.path();
}
std::env::current_exe()
}
#[cfg(target_os = "linux")]
pub fn linux_task_pin() -> io::Result<Option<PathBuf>> {
if TASK_IMAGE.with(|slot| slot.borrow().is_some()) {
PINNED.get().map(PinnedExecutable::path).transpose()
} else {
Ok(None)
}
}
pub fn shims_dir(storage: &Path) -> PathBuf {
if let Some(directory) = TASK_IMAGE.with(|slot| slot.borrow().clone()) {
return directory.join("shims");
}
match PINNED.get() {
Some(pin) => pin.directory.join("shims"),
None => storage.join(crate::gh_shim_paths::SHIMS_DIR_NAME),
}
}
#[cfg(target_os = "linux")]
fn linux_image_path() -> PathBuf {
PathBuf::from(format!("/proc/{}/exe", std::process::id()))
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code, unused_imports))]
pub mod tests {
use super::*;
#[test]
fn pinned_executable_unpinned_path_is_current_exe() {
assert!(PINNED.get().is_none());
assert_eq!(path().unwrap(), std::env::current_exe().unwrap());
}
#[test]
fn pinned_executable_unpinned_shims_use_storage() {
assert!(PINNED.get().is_none());
let storage = tempfile::tempdir().unwrap();
assert_eq!(
shims_dir(storage.path()),
storage.path().join(crate::gh_shim_paths::SHIMS_DIR_NAME)
);
}
#[rustfmt::skip]
test_support_visibility! {
#[cfg_attr(test, test)]
fn pinned_executable_cleanup_preserves_live_owner_and_unrelated_entries() {
let storage = tempfile::tempdir().unwrap();
let run = storage.path();
let pid = std::process::id();
let start = crate::process_identity::process_start_time_ms(pid).unwrap();
let live = run.join(format!("aft-pinned-{pid}-{start}"));
let reused = run.join(format!("aft-pinned-{pid}-{}", start - 1));
let unrelated = run.join("operator-state");
for directory in [&live, &reused, &unrelated] {
std::fs::create_dir(directory).unwrap();
std::fs::write(directory.join("aft"), b"image").unwrap();
}
cleanup(run).unwrap();
assert!(live.join("aft").exists());
assert!(!reused.exists(), "a reused PID must not retain an old pin");
assert!(unrelated.join("aft").exists());
}
}
#[cfg(unix)]
#[test]
fn pinned_executable_cleanup_preserves_another_live_process() {
let mut child = std::process::Command::new("/bin/sleep")
.arg("60")
.spawn()
.unwrap();
let storage = tempfile::tempdir().unwrap();
let pid = child.id();
let start = crate::process_identity::process_start_time_ms(pid).unwrap();
let directory = storage.path().join(format!("aft-pinned-{pid}-{start}"));
std::fs::create_dir(&directory).unwrap();
std::fs::write(directory.join("aft"), b"live image").unwrap();
let result = cleanup(storage.path());
let retained = directory.join("aft").exists();
let alive = child.try_wait().unwrap().is_none();
child.kill().unwrap();
child.wait().unwrap();
result.unwrap();
assert!(
alive && retained,
"cleanup removed a live process's executable"
);
cleanup(storage.path()).unwrap();
assert!(!directory.exists());
}
#[test]
fn pinned_executable_cleanup_lease_overrides_mismatched_process_clock() {
let storage = tempfile::tempdir().unwrap();
let pid = std::process::id();
let start = crate::process_identity::process_start_time_ms(pid).unwrap();
let directory = storage
.path()
.join(format!("aft-pinned-{pid}-{}", start - 1));
std::fs::create_dir(&directory).unwrap();
let lease = owner_lock(&directory).unwrap();
cleanup(storage.path()).unwrap();
assert!(
directory.exists(),
"a held lease must override an apparent PID reuse"
);
drop(lease);
cleanup(storage.path()).unwrap();
assert!(!directory.exists());
}
#[cfg(unix)]
#[test]
fn pinned_executable_task_image_and_shim_outlive_daemon_pin() {
let storage = tempfile::tempdir().unwrap();
let task = tempfile::tempdir().unwrap();
let pin = prepare(storage.path()).unwrap();
std::fs::create_dir(pin.directory.join("shims")).unwrap();
std::os::unix::fs::symlink(&pin.executable, pin.directory.join("shims/gh")).unwrap();
let image = pin.task_image(task.path()).unwrap();
pin.cleanup_at_exit();
assert!(!pin.directory.exists());
assert_eq!(
std::fs::read_link(image.join("shims/gh")).unwrap(),
image.join("aft")
);
let output = std::process::Command::new(image.join("shims/gh"))
.args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("1 test"));
}
#[cfg(windows)]
#[test]
fn pinned_executable_windows_task_wrapper_outlives_daemon_pin() {
let storage = tempfile::tempdir().unwrap();
let task = tempfile::tempdir().unwrap();
let pin = prepare(storage.path()).unwrap();
std::fs::create_dir(pin.directory.join("shims")).unwrap();
std::fs::write(
pin.directory.join("shims/gh.cmd"),
crate::gh_shim_paths::windows_gh_cmd(&pin.executable),
)
.unwrap();
let image = pin.task_image(task.path()).unwrap();
pin.cleanup_at_exit();
assert!(!pin.directory.exists());
assert_eq!(
std::fs::read(image.join("shims/gh.cmd")).unwrap(),
crate::gh_shim_paths::windows_gh_cmd(&image.join("aft.exe"))
);
assert!(image.join("aft.exe").is_file());
}
#[cfg(unix)]
#[test]
fn pinned_executable_missing_pin_is_repaired_from_complete_held_image() {
use sha2::{Digest, Sha256};
use std::io::Seek;
let storage = tempfile::tempdir().unwrap();
let pin = prepare(storage.path()).unwrap();
let digest = |path: &Path| {
let mut hash = Sha256::new();
io::copy(&mut std::fs::File::open(path).unwrap(), &mut hash).unwrap();
hash.finalize()
};
let original = digest(&pin.executable);
pin.state
.lock()
.unwrap()
.source
.seek(io::SeekFrom::End(0))
.unwrap();
std::fs::remove_dir_all(&pin.directory).unwrap();
#[cfg(target_os = "linux")]
std::fs::remove_file(&pin.executable).unwrap();
assert_eq!(pin.path().unwrap(), pin.executable);
assert_eq!(original, digest(&pin.executable));
assert!(pin.directory.join(OWNER_LOCK).exists());
pin.cleanup_at_exit();
}
#[cfg(unix)]
#[test]
fn pinned_executable_cleanup_does_not_follow_symlinks() {
let storage = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let name = format!("aft-pinned-{}-1", std::process::id());
let link = storage.path().join(name);
std::fs::write(outside.path().join("aft"), b"keep").unwrap();
std::os::unix::fs::symlink(outside.path(), &link).unwrap();
cleanup(storage.path()).unwrap();
assert!(link.is_symlink());
assert_eq!(std::fs::read(outside.path().join("aft")).unwrap(), b"keep");
}
#[cfg(unix)]
#[test]
fn pinned_executable_refuses_redirected_run_directory() {
let storage = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(outside.path(), storage.path().join("run")).unwrap();
assert!(prepare(storage.path()).is_err());
assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0);
}
#[cfg(all(unix, not(target_os = "linux")))]
#[test]
fn pinned_executable_cross_volume_fallback_preserves_signed_bytes_and_executes() {
use sha2::{Digest, Sha256};
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let storage = tempfile::tempdir().unwrap();
let executable = std::env::current_exe().unwrap();
let mut source = std::fs::File::open(&executable).unwrap();
let destination = storage.path().join("aft");
materialize(&executable, &mut source, &destination, |_, _| {
Err(io::Error::from_raw_os_error(libc::EXDEV))
})
.unwrap();
let digest = |path: &Path| {
let mut file = std::fs::File::open(path).unwrap();
let mut hash = Sha256::new();
io::copy(&mut file, &mut hash).unwrap();
hash.finalize()
};
assert_eq!(digest(&executable), digest(&destination));
let copied = std::fs::metadata(&destination).unwrap();
assert_ne!(source.metadata().unwrap().ino(), copied.ino());
assert_eq!(copied.permissions().mode() & 0o777, 0o500);
let output = std::process::Command::new(&destination)
.args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("1 test"));
}
#[cfg(target_os = "macos")]
#[test]
fn pinned_executable_pin_is_a_separate_file_from_the_running_image() {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let storage = tempfile::tempdir().unwrap();
let executable = storage.path().join("deploy");
std::fs::copy(std::env::current_exe().unwrap(), &executable).unwrap();
let mut source = std::fs::File::open(&executable).unwrap();
let destination = storage.path().join("aft");
materialize(&executable, &mut source, &destination, link_image).unwrap();
let held = source.metadata().unwrap();
let pinned = std::fs::metadata(&destination).unwrap();
assert_ne!(held.ino(), pinned.ino(), "the pin is a hard link");
assert_eq!(held.nlink(), 1, "the running image gained a second name");
assert_eq!(pinned.permissions().mode() & 0o777, 0o500);
assert_eq!(
std::fs::read(&executable).unwrap(),
std::fs::read(&destination).unwrap()
);
let output = std::process::Command::new(&destination)
.args(["--list", "pinned_executable_cleanup_preserves_live_owner"])
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
}
#[cfg(target_os = "linux")]
#[test]
fn pinned_executable_prepare_and_task_image_leave_the_running_image_unchanged() {
use std::os::unix::fs::MetadataExt;
let image = linux_image_path();
let beside = std::env::current_exe().unwrap();
let beside = beside.parent().unwrap();
let storage = tempfile::tempdir_in(beside).unwrap();
let task = tempfile::tempdir_in(beside).unwrap();
let before = std::fs::metadata(&image).unwrap();
let pin = prepare(storage.path()).unwrap();
pin.task_image(task.path()).unwrap();
let pinned = std::fs::metadata(&pin.executable).unwrap();
let after = std::fs::metadata(&image).unwrap();
assert_ne!(
(before.dev(), before.ino()),
(pinned.dev(), pinned.ino()),
"the pin is a hard link to the running image"
);
assert_eq!(
before.nlink(),
after.nlink(),
"the running image gained a name"
);
assert_eq!(
(before.ctime(), before.ctime_nsec()),
(after.ctime(), after.ctime_nsec()),
"the running image's inode change time moved"
);
pin.cleanup_at_exit();
}
#[cfg(all(unix, not(target_os = "linux")))]
#[test]
fn pinned_executable_hard_link_holds_original_inode_after_replacement() {
use std::os::unix::fs::MetadataExt;
let storage = tempfile::tempdir().unwrap();
let source_path = storage.path().join("deploy");
let destination = storage.path().join("aft");
std::fs::write(&source_path, b"original image").unwrap();
let mut source = std::fs::File::open(&source_path).unwrap();
materialize(&source_path, &mut source, &destination, |from, to| {
std::fs::hard_link(from, to)
})
.unwrap();
assert_eq!(
source.metadata().unwrap().ino(),
destination.metadata().unwrap().ino()
);
let replacement = storage.path().join("new-build");
std::fs::write(&replacement, b"replacement image").unwrap();
std::fs::rename(replacement, &source_path).unwrap();
assert_eq!(std::fs::read(&destination).unwrap(), b"original image");
assert_eq!(std::fs::read(&source_path).unwrap(), b"replacement image");
}
}