greengate-runtime 5.0.0

The amont hook logic: registry, dispatchers, checks and the trust model
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! `land --detach`, its hidden worker, and `land --wait`.
//!
//! The launcher judges `HEAD`, writes the receipt once as `running`, starts
//! a worker that holds the receipt's `flock`, and returns. The worker pushes
//! only the judged sha, never retries, and always finalizes the receipt.
//! `--wait` reads the receipt: a `running` receipt whose lock is free belongs
//! to a dead worker (a pid is reused; a lock is not).

use crate::json_read::{self, Value};
use crate::land::{
    finish, lock_held, now_nanos, receipt_body, receipt_dir, short, shown_ref, verdict_word,
    write_atomic, Meta, Options, Report, Status,
};
use crate::names::BIN;
use crate::posix_signal::{libc_pipe, libc_read, libc_signal, libc_write, SIGHUP, SIGINT, SIGTERM};
use std::fs::File;
use std::os::unix::io::FromRawFd;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// How often `--wait` reads the receipt.
const WAIT_POLL: Duration = Duration::from_secs(2);

/// How long a launch waits for another launch's check to end.
const LAUNCH_LOCK_BUDGET: Duration = Duration::from_secs(10);

/// Exit code of `--wait` when the worker died without finalizing: a
/// refusal, as the plan says; the died lines tell it apart.
const WORKER_DIED: i32 = 1;

/// `word` single-quoted, so it pastes into any shell.
fn quoted(word: &str) -> String {
    format!("'{}'", word.replace('\'', "'\\''"))
}

/// `word` as one shell word, single-quoted when it needs it.
fn shell_word(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_./=:".contains(c));
    if plain {
        word.to_string()
    } else {
        quoted(word)
    }
}

fn wait_command(receipt: &Path) -> String {
    format!("{BIN} land --wait {}", quoted(&receipt.to_string_lossy()))
}

fn lock_path(receipt: &Path) -> PathBuf {
    let mut lock = receipt.as_os_str().to_owned();
    lock.push(".lock");
    PathBuf::from(lock)
}

/// What `--wait` and the worker read back from a receipt.
struct View {
    status: String,
    exit: Option<i32>,
    branch: String,
    dst: String,
    remote_before: String,
    remote_after: String,
    started: i64,
    judged: String,
    log: String,
    worker_pid: Option<u32>,
    flags: Vec<String>,
}

fn text(doc: &Value, key: &str) -> String {
    doc.get(key)
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string()
}

fn number(doc: &Value, key: &str) -> Option<i64> {
    match doc.get(key) {
        Some(Value::Num(n)) => n.parse().ok(),
        _ => None,
    }
}

fn read_view(path: &Path) -> Option<View> {
    let doc = json_read::parse(std::fs::read_to_string(path).ok()?.trim())?;
    Some(View {
        status: doc.get("status")?.as_str()?.to_string(),
        exit: number(&doc, "exit").and_then(|n| i32::try_from(n).ok()),
        branch: text(&doc, "branch"),
        dst: text(&doc, "dst"),
        remote_before: text(&doc, "remote_before"),
        remote_after: text(&doc, "remote_after"),
        started: number(&doc, "started").unwrap_or(0),
        judged: text(&doc, "judged"),
        log: text(&doc, "log"),
        worker_pid: number(&doc, "worker_pid")
            .and_then(|n| u32::try_from(n).ok())
            .filter(|pid| *pid != 0),
        flags: doc
            .get("flags")
            .map(|f| {
                f.items()
                    .iter()
                    .filter_map(|v| v.as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default(),
    })
}

/// The status word a final receipt carries, as the exit code it stands for.
fn code_of_word(word: &str) -> i32 {
    match word {
        "landed" => 0,
        "usage" => 2,
        "unreachable" | "unverified" => 3,
        "not-observed" => 4,
        "interrupted" => 130,
        _ => 1,
    }
}

/// The object the land will push, as `land` resolves it: HEAD, or the tag
/// itself (an annotated tag is its tag object, not the commit it points
/// at, so it matches what `resolve_tag` pushes). `None` when git cannot
/// name it.
fn judged_head(tag: Option<&str>) -> Option<String> {
    match tag {
        Some(name) => {
            let dst = format!("refs/tags/{name}");
            crate::git::stdout(&["rev-parse", "--verify", "-q", &dst])
        }
        None => crate::git::stdout(&["rev-parse", "HEAD"]),
    }
    .filter(|sha| !sha.is_empty())
}

/// The receipt a land has until its worker takes it over: what the launcher
/// knows without resolving anything.
fn skeleton(options: &Options) -> Report {
    let mut report = Report::new(Status::Refused);
    match &options.tag {
        Some(name) => {
            report.dst = format!("refs/tags/{name}");
            report.branch = report.dst.clone();
        }
        None => {
            if let Some(branch) =
                crate::git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"])
            {
                report.dst = format!("refs/heads/{branch}");
                report.branch = branch;
            }
        }
    }
    report
}

/// A launch that does not start a worker: the reason on stderr, and under
/// `--json` the refused document on stdout, as every other land prints one.
fn refused_launch(options: &Options, why: &str) -> i32 {
    eprintln!("{BIN}: land: {why}");
    finish(&Report::new(Status::Refused), options.json)
}

/// `land --detach`: judge, record, start the worker, print where to wait.
pub(crate) fn launch(options: &Options) -> i32 {
    let Some(dir) = receipt_dir() else {
        return refused_launch(options, "could not find the git directory");
    };
    if let Err(e) = std::fs::create_dir_all(&dir) {
        return refused_launch(options, &format!("could not create {}: {e}", dir.display()));
    }
    // The check for a live worker, the receipt and the spawn are one step:
    // two launches that pass the check together would both start.
    let launch_lock = match std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(dir.join("land.lock"))
    {
        Ok(file) => file,
        Err(e) => return refused_launch(options, &format!("could not open the launch lock: {e}")),
    };
    if !crate::fdlock::exclusive_within(&launch_lock, LAUNCH_LOCK_BUDGET) {
        return refused_launch(options, "another launch is in progress; try again");
    }
    if let Some(live) = live_receipt(&dir) {
        let why = format!(
            "a detached land is already running: {}\n    {}",
            live.display(),
            wait_command(&live)
        );
        return refused_launch(options, &why);
    }
    crate::land::prune_receipts(&dir);

    let Some(judged) = judged_head(options.tag.as_deref()) else {
        let what = options
            .tag
            .as_deref()
            .map_or_else(|| "HEAD".to_string(), |name| format!("the tag {name}"));
        return refused_launch(
            options,
            &format!("no commit to judge: git cannot resolve {what}"),
        );
    };
    let started = now_nanos();
    let receipt = dir.join(format!("{started}-{}.json", std::process::id()));
    let log = receipt.with_extension("log");
    let lock = match std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(lock_path(&receipt))
    {
        Ok(file) => file,
        Err(e) => return refused_launch(options, &format!("could not open the receipt lock: {e}")),
    };
    if !crate::fdlock::try_exclusive(&lock) {
        return refused_launch(options, "the receipt lock is already held");
    }
    let report = skeleton(options);
    let meta = Meta {
        judged: judged.clone(),
        log: log.to_string_lossy().into_owned(),
        worker_pid: None,
        flags: options.rerun_flags(),
    };
    let body = receipt_body(&report, "running", None, (started, None), Some(&meta));
    if let Err(e) = write_atomic(&receipt, &body) {
        return refused_launch(
            options,
            &format!("could not write the receipt {}: {e}", receipt.display()),
        );
    }

    let fd = std::os::unix::io::AsRawFd::as_raw_fd(&lock);
    let mut worker_args: Vec<String> = vec![
        "land".into(),
        "--worker".into(),
        "--receipt".into(),
        receipt.to_string_lossy().into_owned(),
        "--lock-fd".into(),
        fd.to_string(),
    ];
    worker_args.extend(options.rerun_flags());
    let worker_args: Vec<&str> = worker_args.iter().map(String::as_str).collect();
    if let Err(e) = crate::rehearsal::spawn_amont(&worker_args, &log, Some(fd)) {
        let mut failed = report;
        failed.status = Status::Refused;
        let body = receipt_body(
            &failed,
            failed.status.as_str(),
            Some(failed.status.code()),
            (started, Some(now_nanos())),
            Some(&meta),
        );
        if let Err(write_error) = write_atomic(&receipt, &body) {
            eprintln!("{BIN}: land: could not finalize the receipt: {write_error}");
        }
        return refused_launch(options, &format!("could not start the worker: {e}"));
    }
    drop(launch_lock);

    let wait = wait_command(&receipt);
    if options.json {
        println!(
            "{}",
            crate::json::object(&[
                crate::json::string_field("status", "detached"),
                crate::json::string_field("receipt", &receipt.to_string_lossy()),
                crate::json::string_field("log", &meta.log),
                crate::json::string_field("wait", &wait),
            ])
        );
    } else {
        println!("{wait}");
    }
    eprintln!("detached {} {}", short(&judged), shown_ref(&report));
    eprintln!("not landed yet: wait on the receipt");
    0
}

/// A `running` receipt of this worktree whose worker is alive.
fn live_receipt(dir: &Path) -> Option<PathBuf> {
    let entries = std::fs::read_dir(dir).ok()?;
    entries.flatten().map(|e| e.path()).find(|path| {
        path.extension().is_some_and(|e| e == "json")
            && read_view(path).is_some_and(|view| view.status == "running")
            && lock_held(path)
    })
}

/// The receipt's last writer: the worker, once, or the signal watcher.
struct Finalizer {
    path: PathBuf,
    started: i64,
    meta: Meta,
    skeleton: Report,
    /// Held for the whole final write: a signal that arrives during it waits
    /// for the rename, so the process never exits with the receipt half done.
    done: Mutex<bool>,
}

impl Finalizer {
    /// Writes the final receipt once. Returns whether this call wrote it:
    /// `false` when an earlier call already finalized the receipt.
    fn write(&self, report: &Report) -> bool {
        let mut done = self.done.lock().unwrap_or_else(|e| e.into_inner());
        if *done {
            return false;
        }
        *done = true;
        let mut report = report.clone();
        if report.branch.is_empty() && report.dst.is_empty() {
            report.branch = self.skeleton.branch.clone();
            report.dst = self.skeleton.dst.clone();
        }
        let body = receipt_body(
            &report,
            report.status.as_str(),
            Some(report.status.code()),
            (self.started, Some(now_nanos())),
            Some(&self.meta),
        );
        if let Err(e) = write_atomic(&self.path, &body) {
            eprintln!(
                "{BIN}: land: could not write the receipt {}: {e}",
                self.path.display()
            );
        }
        true
    }
}

static SIGNAL_PIPE_WRITE: AtomicI32 = AtomicI32::new(-1);
static PENDING_SIGNAL: AtomicI32 = AtomicI32::new(0);

extern "C" fn on_signal(sig: i32) {
    // Stores and one write: the watcher thread does the rest.
    PENDING_SIGNAL.store(sig, Ordering::SeqCst);
    let fd = SIGNAL_PIPE_WRITE.load(Ordering::SeqCst);
    if fd >= 0 {
        let byte = 1u8;
        // SAFETY: write(2) of one byte is async-signal-safe.
        unsafe {
            libc_write(fd, &byte as *const u8, 1);
        }
    }
}

/// On SIGTERM, SIGINT or SIGHUP: finalize `interrupted`, stop the worker's
/// children, exit 128+n.
fn finalize_on_signals(fin: Arc<Finalizer>) {
    let mut fds = [0i32; 2];
    // SAFETY: pipe(2) fills two descriptors.
    if unsafe { libc_pipe(fds.as_mut_ptr()) } != 0 {
        eprintln!("{BIN}: land: no signal pipe; a signal will not finalize the receipt");
        return;
    }
    // Nothing the worker starts inherits the pipe.
    for fd in fds {
        if !crate::fdlock::set_cloexec(fd) {
            eprintln!("{BIN}: land: could not set close-on-exec on the signal pipe");
        }
    }
    SIGNAL_PIPE_WRITE.store(fds[1], Ordering::SeqCst);
    let read_fd = fds[0];
    std::thread::spawn(move || {
        let mut byte = 0u8;
        loop {
            // SAFETY: read(2) into one owned byte.
            let n = unsafe { libc_read(read_fd, &mut byte as *mut u8, 1) };
            if n > 0 {
                break;
            }
            if n == 0 {
                return;
            }
            // -1: interrupted by a signal; read again.
        }
        let sig = PENDING_SIGNAL.load(Ordering::SeqCst);
        let mut report = fin.skeleton.clone();
        report.status = Status::Interrupted(sig);
        if !fin.write(&report) {
            // The land had already finalized its receipt: the signal came
            // after the result, so it changes neither the receipt nor the
            // exit code. The main thread finishes as usual.
            return;
        }
        // A push may already have left: the remote state is unknown.
        if fin.skeleton.dst.is_empty() {
            eprintln!("{BIN}: land: interrupted by signal {sig}; the remote state is unknown");
        } else {
            eprintln!(
                "{BIN}: land: interrupted by signal {sig}; the remote state is unknown: check git ls-remote <remote> {}",
                fin.skeleton.dst
            );
        }
        crate::fdlock::kill_group(std::process::id() as i32, SIGTERM);
        std::process::exit(128 + sig);
    });
    // SAFETY: `on_signal` only stores and writes.
    unsafe {
        for sig in [SIGHUP, SIGINT, SIGTERM] {
            libc_signal(sig, on_signal as *const () as usize);
        }
    }
}

/// The hidden `land --worker`: take the receipt, land the judged sha, finalize.
pub(crate) fn worker(options: &Options) -> i32 {
    // The parser refuses `--worker` without both (usage, exit 2); no
    // receipt path is known here to finalize.
    let (Some(receipt), Some(lock_fd)) = (&options.receipt, options.lock_fd) else {
        return 2;
    };
    let path = PathBuf::from(receipt);
    // First: nothing this worker starts may hold the lock after it dies. A
    // descriptor at 0-2 is stdio, never the lock; refuse rather than take it.
    if lock_fd <= 2 || !crate::fdlock::set_cloexec(lock_fd) {
        eprintln!("{BIN}: land: the lock descriptor {lock_fd} is not usable");
        return finalize_refused(&path, read_view(&path).as_ref());
    }
    // SAFETY: the launcher passed this descriptor (checked above to be no
    // stdio descriptor), an open lock file nothing else in this process owns.
    let _lock = unsafe { File::from_raw_fd(lock_fd) };
    let Some(view) = read_view(&path) else {
        eprintln!("{BIN}: land: cannot read the receipt {receipt}");
        return finalize_refused(&path, None);
    };
    let mut skeleton = Report::new(Status::Refused);
    skeleton.branch = view.branch.clone();
    skeleton.dst = view.dst.clone();
    let meta = Meta {
        judged: view.judged.clone(),
        log: view.log.clone(),
        worker_pid: Some(std::process::id()),
        flags: view.flags.clone(),
    };
    let body = receipt_body(
        &skeleton,
        "running",
        None,
        (view.started, None),
        Some(&meta),
    );
    if let Err(e) = write_atomic(&path, &body) {
        // Nothing may be pushed that the receipt cannot record.
        eprintln!(
            "{BIN}: land: could not take over the receipt {receipt}: {e}; nothing was pushed"
        );
        return finalize_refused(&path, Some(&view));
    }
    let fin = Arc::new(Finalizer {
        path,
        started: view.started,
        meta,
        skeleton,
        done: Mutex::new(false),
    });
    finalize_on_signals(Arc::clone(&fin));

    let report = match &options.tag {
        Some(name) => crate::land::land_tag(name, Some(&view.judged)),
        None => crate::land::land(options.mode(), Some(&view.judged)),
    };
    let _ = fin.write(&report); // the signal watcher may have finalized it first; either way it is final
    finish(&report, options.json)
}

/// A worker that cannot take its receipt over still finalizes it, so no
/// `--wait` reads a dead `running` receipt. What the launcher recorded (the
/// ref, the judged sha, the log, the flags) is kept when it can be read.
fn finalize_refused(path: &Path, view: Option<&View>) -> i32 {
    let mut report = Report::new(Status::Refused);
    let now = now_nanos();
    let meta = view.map(|v| {
        report.branch = v.branch.clone();
        report.dst = v.dst.clone();
        Meta {
            judged: v.judged.clone(),
            log: v.log.clone(),
            worker_pid: Some(std::process::id()),
            flags: v.flags.clone(),
        }
    });
    let started = view.map_or(now, |v| v.started);
    let body = receipt_body(
        &report,
        report.status.as_str(),
        Some(report.status.code()),
        (started, Some(now)),
        meta.as_ref(),
    );
    if let Err(e) = write_atomic(path, &body) {
        eprintln!(
            "{BIN}: land: could not finalize the receipt {}: {e}",
            path.display()
        );
    }
    report.status.code()
}

/// `land --wait <receipt>`.
pub(crate) fn wait(receipt: &str) -> i32 {
    let path = Path::new(receipt);
    let Some(first) = read_view(path) else {
        eprintln!("{BIN}: land: no readable receipt at {receipt}");
        return 2;
    };
    eprintln!("waiting on {receipt} (log: {})", first.log);
    loop {
        let Some(view) = read_view(path) else {
            eprintln!("{BIN}: land: the receipt {receipt} is gone or unreadable");
            return 2;
        };
        if view.status != "running" {
            let shown = if view.branch.is_empty() {
                view.dst.strip_prefix("refs/tags/").unwrap_or(&view.dst)
            } else {
                &view.branch
            };
            println!(
                "{}",
                verdict_word(&view.status, &view.remote_before, &view.remote_after, shown)
            );
            return view.exit.unwrap_or_else(|| code_of_word(&view.status));
        }
        if !lock_held(path) {
            // The worker may have finalized between the read and the lock.
            match read_view(path) {
                Some(again) if again.status == "running" => return died(&again),
                _ => continue,
            }
        }
        std::thread::sleep(crate::clock::scaled(WAIT_POLL));
    }
}

fn died(view: &View) -> i32 {
    let pid = view
        .worker_pid
        .map_or_else(|| "unknown".to_string(), |p| p.to_string());
    println!("worker {pid} died");
    println!("  log: {}", quoted(&view.log));
    let flags: Vec<String> = view.flags.iter().map(|f| shell_word(f)).collect();
    println!("  rerun: {BIN} land --detach {}", flags.join(" "));
    WORKER_DIED
}