use std::io::Read;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use ostrya_core::{Checksum, KeyFile};
use sha2::{Digest, Sha256};
use super::BucketRepo;
use crate::error::{Error, Result};
use crate::remote::s3::{DeleteIfMatch, PutIfAbsent};
pub(super) const LOCK_KEY: &str = "extensions/ostrya/lock";
pub(super) const PROBE_KEY: &str = "extensions/ostrya/lock-probe";
const PROBE_BODY: &[u8] = b"ostrya lock probe\n";
const GROUP: &str = "lock";
const MAX_LOCK: u64 = 64 * 1024;
const MAX_HOST: u64 = 256;
const HOSTNAME_FILE: &str = "/proc/sys/kernel/hostname";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LockOperation {
Init,
Push,
Prune,
Summary,
Fsck,
}
impl LockOperation {
pub fn as_str(self) -> &'static str {
match self {
LockOperation::Init => "init",
LockOperation::Push => "push",
LockOperation::Prune => "prune",
LockOperation::Summary => "summary",
LockOperation::Fsck => "fsck",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct LockHolder {
pub id: Option<String>,
pub host: Option<String>,
pub pid: Option<u32>,
pub operation: Option<String>,
pub started: Option<u64>,
}
impl std::fmt::Display for LockHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut parts = Vec::new();
if let Some(operation) = &self.operation {
parts.push(format!("operation {}", operation.escape_debug()));
}
if let Some(host) = self.host.as_deref().filter(|host| !host.is_empty()) {
parts.push(format!("host {}", host.escape_debug()));
}
if let Some(pid) = self.pid {
parts.push(format!("pid {pid}"));
}
if let Some(started) = self.started {
parts.push(format!("started at {started} seconds since the epoch, UTC"));
}
if let Some(id) = &self.id {
parts.push(format!("id {id}"));
}
if parts.is_empty() {
f.write_str("a writer that the lock body does not name")
} else {
f.write_str(&parts.join(", "))
}
}
}
#[derive(Debug)]
#[must_use = "a dropped lock stays in the bucket; release it"]
pub struct WriterLock<'a> {
repo: &'a BucketRepo,
id: String,
broken: Option<LockHolder>,
}
struct Held {
holder: LockHolder,
etag: Option<String>,
}
impl BucketRepo {
pub(super) async fn take_lock(
&self,
operation: LockOperation,
break_lock: bool,
) -> Result<WriterLock<'_>> {
self.probe_exclusion().await?;
let broken = if break_lock {
self.break_lock().await?
} else {
None
};
let host = host_name();
let id = new_id(&host);
let started = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
let body = lock_body(&id, &host, std::process::id(), operation, started)?.into_bytes();
match self.bucket.put_if_absent(LOCK_KEY, body).await? {
PutIfAbsent::Created { .. }
| PutIfAbsent::Matches { .. }
| PutIfAbsent::Refused { .. } => Ok(WriterLock {
repo: self,
id,
broken,
}),
_ => Err(self.locked(self.read_lock(false).await?)),
}
}
async fn probe_exclusion(&self) -> Result<()> {
match self
.bucket
.put_if_absent(PROBE_KEY, PROBE_BODY.to_vec())
.await?
{
PutIfAbsent::Present | PutIfAbsent::Refused { .. } => return Ok(()),
PutIfAbsent::Created { .. } | PutIfAbsent::Matches { .. } => {}
_ => return Err(self.unknown_probe()),
}
match self
.bucket
.put_if_absent(PROBE_KEY, PROBE_BODY.to_vec())
.await?
{
PutIfAbsent::Present | PutIfAbsent::Refused { .. } => Ok(()),
PutIfAbsent::Created { .. } => Err(Error::BucketNoExclusion {
address: self.address().to_string(),
}),
_ => Err(self.unknown_probe()),
}
}
fn unknown_probe(&self) -> Error {
Error::Remote(crate::remote::Error::Transport(format!(
"the probe of the writer lock of {} had an unknown outcome, so it is not known if \
the server honors If-None-Match; the run wrote no lock; run the operation again",
self.address()
)))
}
pub(super) async fn read_holder(&self) -> Result<Option<LockHolder>> {
Ok(self.read_lock(false).await?.map(|held| held.holder))
}
async fn break_lock(&self) -> Result<Option<LockHolder>> {
let Some(held) = self.read_lock(true).await? else {
return Ok(None);
};
let Some(etag) = held.etag.as_deref() else {
return Err(Error::Remote(crate::remote::Error::Transport(format!(
"the read of the writer lock of {} gave no ETag, so the break of the lock \
cannot delete it with If-Match; the call deleted no lock",
self.address()
))));
};
match self.bucket.delete_if_match(LOCK_KEY, etag).await? {
DeleteIfMatch::Deleted => Ok(Some(held.holder)),
_ => match self.read_lock(false).await? {
None => Ok(None),
other => Err(self.locked(other)),
},
}
}
async fn read_lock(&self, etag: bool) -> Result<Option<Held>> {
match self.bucket.get(LOCK_KEY, MAX_LOCK).await {
Ok(Some(object)) => Ok(Some(Held {
holder: parse_holder(&object.bytes),
etag: object.etag,
})),
Ok(None) => Ok(None),
Err(crate::remote::Error::LimitExceeded(_)) if etag => {
Ok(self.bucket.get_stream(LOCK_KEY).await?.map(|stream| Held {
holder: LockHolder::default(),
etag: stream.etag().map(str::to_owned),
}))
}
Err(crate::remote::Error::LimitExceeded(_)) => Ok(Some(Held {
holder: LockHolder::default(),
etag: None,
})),
Err(e) => Err(e.into()),
}
}
fn locked(&self, held: Option<Held>) -> Error {
Error::BucketLocked {
address: self.address().to_string(),
holder: held.map(|held| Box::new(held.holder)),
}
}
}
impl WriterLock<'_> {
pub fn id(&self) -> &str {
&self.id
}
pub fn broken(&self) -> Option<&LockHolder> {
self.broken.as_ref()
}
pub async fn check(&self) -> Result<()> {
match self.repo.read_lock(false).await? {
Some(held) if self.is_own(&held.holder) => Ok(()),
other => Err(self.lost(other)),
}
}
pub async fn release(self) -> Result<()> {
let bucket = &self.repo.bucket;
let held = match self.repo.read_lock(false).await? {
Some(held) if self.is_own(&held.holder) => held,
other => return Err(self.lost(other)),
};
match held.etag.as_deref() {
Some(etag) => match bucket.delete_if_match(LOCK_KEY, etag).await? {
DeleteIfMatch::Deleted => Ok(()),
_ => Err(self.lost(self.repo.read_lock(false).await?)),
},
None => Ok(bucket.delete(LOCK_KEY).await?),
}
}
fn is_own(&self, holder: &LockHolder) -> bool {
names_id(holder, &self.id)
}
fn lost(&self, held: Option<Held>) -> Error {
Error::BucketLockLost {
address: self.repo.address().to_string(),
holder: held.map(|held| Box::new(held.holder)),
}
}
}
pub(crate) fn describe_locked(holder: Option<&LockHolder>) -> String {
match holder {
Some(holder) => format!("another writer holds the writer lock: {holder}"),
None => "a request of this run found a lock, and the lock was gone at the read after \
it, so a new run can take the lock"
.to_owned(),
}
}
pub(crate) fn describe_lost(holder: Option<&LockHolder>) -> String {
match holder {
Some(holder) => format!("another lock is in its place: {holder}"),
None => "the bucket holds no lock".to_owned(),
}
}
fn lock_body(
id: &str,
host: &str,
pid: u32,
operation: LockOperation,
started: u64,
) -> Result<String> {
let mut body = KeyFile::default();
body.set_value(GROUP, "id", id)?;
body.set_string(GROUP, "host", host)?;
body.set_value(GROUP, "pid", &pid.to_string())?;
body.set_value(GROUP, "operation", operation.as_str())?;
body.set_value(GROUP, "started", &started.to_string())?;
Ok(body.to_string())
}
fn parse_holder(bytes: &[u8]) -> LockHolder {
let Some(body) = std::str::from_utf8(bytes)
.ok()
.and_then(|text| KeyFile::parse(text).ok())
.filter(|body| body.has_group(GROUP))
else {
return LockHolder::default();
};
let text = |key: &str| body.get_string(GROUP, key).ok().flatten();
let value = |key: &str| body.get_value(GROUP, key);
LockHolder {
id: value("id").filter(|id| is_lock_id(id)).map(str::to_owned),
host: text("host"),
pid: value("pid").and_then(|pid| pid.parse().ok()),
operation: text("operation"),
started: value("started").and_then(|started| started.parse().ok()),
}
}
fn names_id(holder: &LockHolder, id: &str) -> bool {
holder.id.as_deref() == Some(id)
}
fn is_lock_id(id: &str) -> bool {
id.len() == 64 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
fn new_id(host: &str) -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_nanos());
let text = format!("{host}\n{}\n{nanos}\n{counter}", std::process::id());
Checksum::from_bytes(Sha256::digest(text.as_bytes()).into()).to_hex()
}
fn host_name() -> String {
let mut bytes = Vec::new();
let read = std::fs::File::open(HOSTNAME_FILE)
.and_then(|file| file.take(MAX_HOST).read_to_end(&mut bytes));
if read.is_err() {
return String::new();
}
String::from_utf8(bytes)
.ok()
.and_then(|text| text.lines().next().map(str::to_owned))
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn holder(text: &[u8]) -> LockHolder {
parse_holder(text)
}
#[test]
fn the_lock_body_has_one_group_and_five_keys_in_order() {
let id = "ab".repeat(32);
let body = lock_body(&id, "build1", 4242, LockOperation::Prune, 1_761_062_400).unwrap();
assert_eq!(
body,
format!(
"[lock]\nid={id}\nhost=build1\npid=4242\noperation=prune\nstarted=1761062400\n"
)
);
assert_eq!(
holder(body.as_bytes()),
LockHolder {
id: Some(id),
host: Some("build1".into()),
pid: Some(4242),
operation: Some("prune".into()),
started: Some(1_761_062_400),
}
);
}
#[test]
fn a_host_name_with_a_leading_space_and_a_backslash_reads_back() {
let id = "0f".repeat(32);
let body = lock_body(&id, " a\\b", 1, LockOperation::Push, 0).unwrap();
assert!(body.contains("host=\\sa\\\\b\n"), "{body}");
assert_eq!(holder(body.as_bytes()).host.as_deref(), Some(" a\\b"));
let body = lock_body(&id, "", 1, LockOperation::Fsck, 0).unwrap();
assert!(body.contains("\nhost=\n"), "{body}");
}
#[test]
fn a_body_that_this_version_cannot_read_names_no_id() {
let good = "a".repeat(64);
for body in [
format!("[lock]\nid={}\n", "A".repeat(64)),
format!("[lock]\nid={}\n", "a".repeat(63)),
format!("[other]\nid={good}\n"),
format!("id={good}\n"),
"[lock\n".to_owned(),
] {
assert_eq!(holder(body.as_bytes()).id, None, "{body}");
}
assert_eq!(holder(b"[lock]\nid=\xff\n"), LockHolder::default());
let read = holder(format!("[lock]\nid={good}\npid=x\nstarted=-1\n").as_bytes());
assert_eq!(read.id.as_deref(), Some(good.as_str()));
assert_eq!((read.pid, read.started), (None, None));
}
#[test]
fn a_holder_names_each_field_that_it_has() {
let full = LockHolder {
id: Some("c".repeat(64)),
host: Some("build\n1".into()),
pid: Some(7),
operation: Some("push".into()),
started: Some(12),
};
assert_eq!(
full.to_string(),
format!(
"operation push, host build\\n1, pid 7, started at 12 seconds since the epoch, \
UTC, id {}",
"c".repeat(64)
)
);
assert_eq!(
LockHolder::default().to_string(),
"a writer that the lock body does not name"
);
}
#[test]
fn only_the_own_id_is_the_own_lock() {
let own = "d".repeat(64);
let named = |id: Option<String>| LockHolder {
id,
..LockHolder::default()
};
assert!(names_id(&named(Some(own.clone())), &own));
assert!(!names_id(&named(Some("e".repeat(64))), &own));
assert!(!names_id(&named(None), &own));
}
#[test]
fn each_new_id_is_64_lowercase_hex_digits_and_unique() {
let first = new_id("build1");
let second = new_id("build1");
assert!(is_lock_id(&first), "{first}");
assert!(is_lock_id(&second), "{second}");
assert_ne!(first, second);
}
#[test]
fn the_operations_have_their_key_values() {
let values: Vec<&str> = [
LockOperation::Init,
LockOperation::Push,
LockOperation::Prune,
LockOperation::Summary,
LockOperation::Fsck,
]
.into_iter()
.map(LockOperation::as_str)
.collect();
assert_eq!(values, ["init", "push", "prune", "summary", "fsck"]);
}
#[test]
fn the_lock_errors_name_the_address_and_the_holder() {
let id = "a".repeat(64);
let holder = || {
Some(Box::new(LockHolder {
id: Some(id.clone()),
..LockHolder::default()
}))
};
let address = || "s3://bkt/repo".to_owned();
let locked = Error::BucketLocked {
address: address(),
holder: holder(),
};
assert_eq!(
locked.to_string(),
format!(
"the bucket repository s3://bkt/repo is locked: another writer holds the writer \
lock: id {id}"
)
);
let gone = Error::BucketLocked {
address: address(),
holder: None,
};
assert!(
gone.to_string().contains("a new run can take the lock"),
"{gone}"
);
let lost = Error::BucketLockLost {
address: address(),
holder: holder(),
};
assert_eq!(
lost.to_string(),
format!(
"the writer lock of s3://bkt/repo was broken: another lock is in its place: id {id}"
)
);
let absent = Error::BucketLockLost {
address: address(),
holder: None,
};
assert!(
absent.to_string().ends_with("the bucket holds no lock"),
"{absent}"
);
let open = Error::BucketNoExclusion { address: address() };
assert_eq!(
open.to_string(),
"the S3 server of s3://bkt/repo does not honor If-None-Match, so the writer lock \
gives no exclusion and no writer can run on it; the run wrote no lock"
);
}
#[test]
fn the_probe_body_is_fixed_ascii() {
assert_eq!(PROBE_KEY, "extensions/ostrya/lock-probe");
assert_eq!(PROBE_BODY, b"ostrya lock probe\n");
assert_eq!(PROBE_BODY.len(), 18);
}
#[test]
fn the_host_name_is_one_line() {
let host = host_name();
assert!(!host.contains('\n'), "{host:?}");
assert!(host.len() <= MAX_HOST as usize);
}
}