ostrya 0.2.2

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Per-transaction staging directories under `<repo>/tmp`.
//!
//! A transaction stages objects in `tmp/staging-<boot-id>-XXXXXX`, created fresh
//! per transaction and removed when the transaction ends. A sibling file
//! `staging-<boot-id>-XXXXXX-lock` is held with an exclusive record lock for the
//! transaction's lifetime, marking the directory as owned by a live
//! transaction. Encoding the boot id in the name separates directories from the
//! current boot, whose owner may still be alive, from earlier boots, whose owner
//! is certainly gone.
//!
//! On transaction start the reaper removes leftover staging directories whose
//! owner has died. It takes each sibling lock non-blockingly; a directory whose
//! lock it can take, with no live holder, is removed. A directory with no lock
//! file is removed only once it is older than `tmp-expiry-secs`, since it may be
//! mid-creation in another process. A process-global map of the staging
//! directories this process currently owns keeps the reaper from touching them:
//! the record locks are process-associated, so a second descriptor to a live
//! sibling lock would neither conflict nor survive being closed. A directory
//! enters that map before it is created and leaves it after it is removed, so
//! every directory a same-process reaper can list is already in the map.
//!
//! Each entry of that map holds a descriptor for the `tmp/` directory the
//! staging directory lives in, so [`reap_owned`] removes every one of them with
//! no live [`StagingDir`] in hand. A process that ends without running
//! destructors reaches it through
//! [`reap_process_staging`](crate::reap_process_staging).

use std::collections::HashMap;
use std::ffi::CString;
use std::io;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::sync::{Mutex, OnceLock};

use rustix::fs::{AtFlags, Dir, FileType, FlockOperation, Mode, OFlags};
use rustix::io::Errno;

/// The mode staging directories are created with, matching the tool.
const STAGING_DIR_MODE: u32 = 0o775;

/// The mode a staging lock file is created with, matching the tool.
const STAGING_LOCK_MODE: u32 = 0o600;

/// The character set of the random staging-name suffix (mkdtemp's alphabet).
const SUFFIX_ALPHABET: &[u8; 62] =
    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

/// The length of the random staging-name suffix.
const SUFFIX_LEN: usize = 6;

/// The number of unique-name attempts before giving up.
const MKDTEMP_ATTEMPTS: u32 = 128;

/// The staging directories this process currently owns, each name mapped to a
/// descriptor for the `tmp/` directory it lives in.
fn active() -> &'static Mutex<HashMap<String, OwnedFd>> {
    static ACTIVE: OnceLock<Mutex<HashMap<String, OwnedFd>>> = OnceLock::new();
    ACTIVE.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Remove the staging directories this process owns, together with their
/// sibling lock files.
///
/// A [`StagingDir`] removes its own directory when it drops, so this is for a
/// process that ends without running destructors: it leaves `tmp/` as an
/// unwound return would. Every owned directory is removed, so a transaction
/// that continues afterward finds its staged objects gone.
pub(crate) fn reap_owned() {
    let owned = std::mem::take(&mut *active().lock().unwrap());
    for (name, tmp_fd) in owned {
        remove_staging(tmp_fd.as_fd(), &name);
    }
}

/// Remove the staging directory `name` under `tmp_fd` and its sibling lock
/// file. Absent entries are already in the wanted state, and a removal that
/// fails leaves the entry for the next reaper.
fn remove_staging(tmp_fd: BorrowedFd<'_>, name: &str) {
    let _ = remove_tree_at(tmp_fd, name);
    let lock_name = format!("{name}-lock");
    let _ = rustix::fs::unlinkat(tmp_fd, lock_name.as_str(), AtFlags::empty());
}

/// A transaction's staging area: the directory, its held sibling lock, and the
/// `tmp/` descriptor they live under.
#[derive(Debug)]
pub(crate) struct StagingDir {
    tmp_fd: OwnedFd,
    /// The staging directory descriptor. Objects are ingested into this
    /// directory by the write path and renamed out of it into `objects/` at
    /// commit.
    dir_fd: OwnedFd,
    /// The sibling lock descriptor, held for the transaction's lifetime to mark
    /// the directory as owned. Kept only for its lock; never read.
    #[allow(dead_code)]
    lock_fd: OwnedFd,
    name: String,
}

impl StagingDir {
    /// Create a fresh staging directory under the repository rooted at
    /// `repo_fd`, reaping stale leftovers first. Runs synchronous filesystem
    /// calls and is meant to be offloaded to the blocking pool.
    pub(crate) fn create(repo_fd: BorrowedFd<'_>, expiry_secs: i64) -> io::Result<StagingDir> {
        match rustix::fs::mkdirat(repo_fd, "tmp", Mode::from_raw_mode(STAGING_DIR_MODE)) {
            Ok(()) | Err(Errno::EXIST) => {}
            Err(e) => return Err(e.into()),
        }
        let tmp_fd = rustix::fs::openat(
            repo_fd,
            "tmp",
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
        )?;

        reap_stale(tmp_fd.as_fd(), expiry_secs);

        let prefix = format!("staging-{}-", boot_id()?);
        // `mkdtemp` claims the name in `active` before the directory exists, so
        // a concurrent same-process reaper never sees it unclaimed.
        let (name, dir_fd) = mkdtemp(tmp_fd.as_fd(), &prefix)?;

        let lock_name = format!("{name}-lock");
        let lock_fd = match acquire_staging_lock(tmp_fd.as_fd(), &lock_name) {
            Ok(fd) => fd,
            Err(e) => {
                active().lock().unwrap().remove(&name);
                let _ = remove_tree_at(tmp_fd.as_fd(), &name);
                return Err(e);
            }
        };

        Ok(StagingDir {
            tmp_fd,
            dir_fd,
            lock_fd,
            name,
        })
    }

    /// The staging directory descriptor. Objects are ingested here and renamed
    /// into `objects/` at commit.
    pub(crate) fn dir_fd(&self) -> BorrowedFd<'_> {
        self.dir_fd.as_fd()
    }
}

impl Drop for StagingDir {
    fn drop(&mut self) {
        remove_staging(self.tmp_fd.as_fd(), &self.name);
        // Release the in-process claim only after the directory and its lock
        // sibling are gone, so a concurrent same-process reaper never sees the
        // directory unprotected while its lock still exists.
        active().lock().unwrap().remove(&self.name);
        // The descriptor fields close after this body, releasing the sibling
        // lock and the directory handle.
    }
}

/// Create the sibling lock file and hold it exclusively. A fresh lock file is
/// uncontended, so the attempt does not block.
fn acquire_staging_lock(tmp_fd: BorrowedFd<'_>, lock_name: &str) -> io::Result<OwnedFd> {
    let lock_fd = rustix::fs::openat(
        tmp_fd,
        lock_name,
        OFlags::RDWR | OFlags::CREATE | OFlags::CLOEXEC | OFlags::NOFOLLOW,
        Mode::from_raw_mode(STAGING_LOCK_MODE),
    )?;
    if let Err(e) = rustix::fs::fcntl_lock(&lock_fd, FlockOperation::NonBlockingLockExclusive) {
        // The open created the lock file; remove it so a failed acquire leaves
        // no orphaned sibling behind.
        let _ = rustix::fs::unlinkat(tmp_fd, lock_name, AtFlags::empty());
        return Err(e.into());
    }
    Ok(lock_fd)
}

/// The current boot id, read once and cached for the process.
fn boot_id() -> io::Result<&'static str> {
    static BOOT_ID: OnceLock<String> = OnceLock::new();
    if let Some(id) = BOOT_ID.get() {
        return Ok(id);
    }
    let raw = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?;
    let id = raw.trim().to_owned();
    if id.is_empty() {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "empty boot id"));
    }
    Ok(BOOT_ID.get_or_init(|| id))
}

/// Create a uniquely named directory `prefix + suffix` under `tmp_fd`, retrying
/// on a name collision. The returned name is claimed in `active`, which the
/// caller releases when the staging directory ends.
///
/// The claim precedes the `mkdirat` that publishes the name, so every directory
/// a same-process reaper can list is already claimed. The claim is the only
/// barrier that holds within one process: the record locks are
/// process-associated, so a reaper reaching the sibling lock of a live directory
/// takes it without conflict and removes the directory. The claim carries its
/// own duplicate of `tmp_fd`, which is what [`reap_owned`] removes the
/// directory through.
fn mkdtemp(tmp_fd: BorrowedFd<'_>, prefix: &str) -> io::Result<(String, OwnedFd)> {
    for _ in 0..MKDTEMP_ATTEMPTS {
        let name = format!("{prefix}{}", random_suffix());
        let claim = tmp_fd.try_clone_to_owned()?;
        // A name another live transaction in this process owns is left to its
        // owner: releasing that claim here would strip its protection.
        {
            let mut active = active().lock().unwrap();
            if active.contains_key(&name) {
                continue;
            }
            active.insert(name.clone(), claim);
        }
        match rustix::fs::mkdirat(tmp_fd, name.as_str(), Mode::from_raw_mode(STAGING_DIR_MODE)) {
            Ok(()) => {
                match rustix::fs::openat(
                    tmp_fd,
                    name.as_str(),
                    OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
                    Mode::empty(),
                ) {
                    Ok(dir_fd) => return Ok((name, dir_fd)),
                    Err(e) => {
                        active().lock().unwrap().remove(&name);
                        return Err(e.into());
                    }
                }
            }
            Err(Errno::EXIST) => {
                active().lock().unwrap().remove(&name);
                continue;
            }
            Err(e) => {
                active().lock().unwrap().remove(&name);
                return Err(e.into());
            }
        }
    }
    Err(io::Error::new(
        io::ErrorKind::AlreadyExists,
        "could not allocate a unique staging directory",
    ))
}

/// A six-character `[A-Za-z0-9]` suffix, seeded from the time, pid, and a
/// per-process counter. The name only needs to be unique on the host, so a
/// collision simply retries.
fn random_suffix() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    let mut state =
        nanos ^ (u64::from(std::process::id()) << 32) ^ counter.wrapping_mul(0x9E37_79B9_7F4A_7C15);

    let mut suffix = String::with_capacity(SUFFIX_LEN);
    for _ in 0..SUFFIX_LEN {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;
        suffix.push(SUFFIX_ALPHABET[(state % 62) as usize] as char);
    }
    suffix
}

/// Remove leftover staging directories whose owning transaction has died.
fn reap_stale(tmp_fd: BorrowedFd<'_>, expiry_secs: i64) {
    let Ok(entries) = Dir::read_from(tmp_fd) else {
        return;
    };
    // Collect names first so removals do not disturb the directory read.
    let mut names: Vec<String> = Vec::new();
    for entry in entries {
        let Ok(entry) = entry else { continue };
        let Ok(name) = entry.file_name().to_str() else {
            continue;
        };
        if !name.starts_with("staging-") || name.ends_with("-lock") {
            continue;
        }
        names.push(name.to_owned());
    }
    for name in names {
        reap_one(tmp_fd, &name, expiry_secs);
    }
}

/// Reap one candidate staging directory if its owner is gone.
fn reap_one(tmp_fd: BorrowedFd<'_>, name: &str, expiry_secs: i64) {
    // Never touch a directory this process owns: its sibling lock is held on
    // another descriptor, and even opening and closing that lock file would drop
    // the hold under the process-associated record-lock semantics.
    if active().lock().unwrap().contains_key(name) {
        return;
    }
    let lock_name = format!("{name}-lock");
    match rustix::fs::openat(
        tmp_fd,
        lock_name.as_str(),
        OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOFOLLOW,
        Mode::empty(),
    ) {
        Ok(lock_fd) => {
            // Taking the lock means no live owner in any process.
            if rustix::fs::fcntl_lock(&lock_fd, FlockOperation::NonBlockingLockExclusive).is_ok() {
                let _ = remove_tree_at(tmp_fd, name);
                let _ = rustix::fs::unlinkat(tmp_fd, lock_name.as_str(), AtFlags::empty());
            }
        }
        Err(Errno::NOENT) => {
            // No lock file: mid-creation elsewhere or an orphan. Reap only once
            // it is past the expiry window.
            if older_than(tmp_fd, name, expiry_secs) {
                let _ = remove_tree_at(tmp_fd, name);
            }
        }
        Err(_) => {}
    }
}

/// Whether the entry `name` under `tmp_fd` is older than `expiry_secs`.
///
/// The age test matches the tool: an entry is expired once its age in whole
/// seconds exceeds `expiry_secs`. At `expiry_secs = 0` an entry created in the
/// current second (age 0) is kept and only entries at least a second old are
/// reaped, so a directory still being created is not removed by age.
fn older_than(tmp_fd: BorrowedFd<'_>, name: &str, expiry_secs: i64) -> bool {
    let Ok(stat) = rustix::fs::statat(tmp_fd, name, AtFlags::SYMLINK_NOFOLLOW) else {
        return false;
    };
    let Ok(now) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) else {
        return false;
    };
    (now.as_secs() as i64 - stat.st_mtime) > expiry_secs
}

/// Remove the directory `name` under `parent` and everything below it.
fn remove_tree_at(parent: BorrowedFd<'_>, name: &str) -> io::Result<()> {
    match rustix::fs::openat(
        parent,
        name,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
        Mode::empty(),
    ) {
        Ok(dir_fd) => clear_dir(dir_fd.as_fd())?,
        Err(Errno::NOENT) => return Ok(()),
        Err(e) => return Err(e.into()),
    }
    match rustix::fs::unlinkat(parent, name, AtFlags::REMOVEDIR) {
        Ok(()) | Err(Errno::NOENT) => Ok(()),
        Err(e) => Err(e.into()),
    }
}

/// Remove every entry within the directory `dir`, recursing into
/// subdirectories.
fn clear_dir(dir: BorrowedFd<'_>) -> io::Result<()> {
    let mut children: Vec<(CString, bool)> = Vec::new();
    let entries = Dir::read_from(dir)?;
    for entry in entries {
        let entry = entry?;
        let name = entry.file_name();
        if name == c"." || name == c".." {
            continue;
        }
        let is_dir = match entry.file_type() {
            FileType::Directory => true,
            FileType::Unknown => {
                let stat = rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)?;
                FileType::from_raw_mode(stat.st_mode) == FileType::Directory
            }
            _ => false,
        };
        children.push((name.to_owned(), is_dir));
    }

    for (name, is_dir) in children {
        let name = name.as_c_str();
        if is_dir {
            match rustix::fs::openat(
                dir,
                name,
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
                Mode::empty(),
            ) {
                Ok(child) => clear_dir(child.as_fd())?,
                Err(Errno::NOENT) => continue,
                Err(e) => return Err(e.into()),
            }
            match rustix::fs::unlinkat(dir, name, AtFlags::REMOVEDIR) {
                Ok(()) | Err(Errno::NOENT) => {}
                Err(e) => return Err(e.into()),
            }
        } else {
            match rustix::fs::unlinkat(dir, name, AtFlags::empty()) {
                Ok(()) | Err(Errno::NOENT) => {}
                Err(e) => return Err(e.into()),
            }
        }
    }
    Ok(())
}