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
|
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
use crossbeam_channel::{bounded, Sender};
use crate::config::Config;
use crate::db::{self, builds, Db};
use crate::pipeline::{self, Outcome};
/// Handle on a running pool. Dropping without `shutdown` leaves the threads
/// running; call `shutdown` to join them cleanly.
pub struct Pool {
stop: Arc<AtomicBool>,
handles: Vec<JoinHandle<()>>,
}
impl Pool {
/// Start the dispatcher and `max_concurrent_builds` workers.
pub fn spawn(cfg: Arc<Config>, db: Db) -> Pool {
let stop = Arc::new(AtomicBool::new(false));
let workers = cfg.max_concurrent_builds.max(1);
// Bounded at the worker count: the dispatcher must not run ahead and
// lease builds that no worker has picked up yet, because a leased build
// whose worker never starts would sit until its lease expires.
let (tx, rx) = bounded::<String>(workers);
let mut handles = Vec::new();
for n in 0..workers {
let cfg = cfg.clone();
let db = db.clone();
let stop = stop.clone();
let rx = rx.clone();
handles.push(
std::thread::Builder::new()
.name(format!("worker-{n}"))
.spawn(move || worker(cfg, db, rx, stop))
.expect("spawn worker"),
);
}
drop(rx);
let cfg2 = cfg.clone();
let db2 = db.clone();
let stop2 = stop.clone();
handles.push(
std::thread::Builder::new()
.name("dispatcher".into())
.spawn(move || dispatcher(cfg2, db2, stop2, tx))
.expect("spawn dispatcher"),
);
Pool { stop, handles }
}
/// Ask the threads to stop and wait for them. A build that is mid-step will
/// finish that step, fail its lease, and be requeued by the next process's
/// reaper — which is the designed behaviour, not a bug to wait out.
pub fn shutdown(self) {
self.stop.store(true, Ordering::SeqCst);
for h in self.handles {
let _ = h.join();
}
}
}
fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) {
// The reaper runs first on every loop, including the first, so "recover from
// a crash" and "notice an expired lease" are the same code path.
while !stop.load(Ordering::SeqCst) {
dispatch_once(&cfg, &db, &tx);
let mut slept = 0u64;
while slept < cfg.dispatch_tick_secs && !stop.load(Ordering::SeqCst) {
std::thread::sleep(std::time::Duration::from_millis(200));
slept += 1;
}
}
}
/// One dispatcher pass. Returns the ids handed to workers. Public so a test can
/// drive one pass deterministically instead of racing a thread.
pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> {
let reaped = builds::reap_expired(db).unwrap_or(0);
if reaped > 0 {
db::audit_system(
&db.writer,
"build.reaped",
"build",
"*",
serde_json::json!({"requeued": reaped}),
)
.ok();
}
// Blocked builds become eligible again when the blocking package arrives.
let _ = builds::requeue_blocked(db);
let _ = builds::cancel_superseded(db);
let room = admissible(cfg, db);
if room == 0 {
return Vec::new();
}
let owner = format!("worker-{}", std::process::id());
let ids = builds::claim_batch(db, &owner, room, cfg.lease_secs).unwrap_or_default();
for id in &ids {
if tx.send(id.clone()).is_err() {
// No worker to take it: give the lease back rather than let it
// expire with nobody holding it.
let _ = builds::requeue_transient(db, id);
}
}
ids
}
/// How many builds may be admitted right now (§8.2 backpressure). A build that
/// cannot fit on disk stays queued rather than filling the filesystem halfway
/// through a compile.
pub fn admissible(cfg: &Config, db: &Db) -> usize {
let in_flight = builds::in_flight(db).unwrap_or(0) as usize;
let slots = cfg.max_concurrent_builds.saturating_sub(in_flight);
if slots == 0 {
return 0;
}
let free = free_disk_mb(&cfg.root);
if free < cfg.min_free_disk_mb {
return 0;
}
slots
}
/// Megabytes free on the filesystem holding `path`.
pub fn free_disk_mb(path: &std::path::Path) -> u64 {
use std::ffi::CString;
let c = match CString::new(path.as_os_str().to_string_lossy().as_bytes()) {
Ok(c) => c,
Err(_) => return u64::MAX,
};
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::statvfs(c.as_ptr(), &mut stat) };
if rc != 0 {
// If we cannot find out, do not block the queue over a measurement
// problem; the pipeline's own disk guard is the backstop.
return u64::MAX;
}
let bsize = stat.f_frsize as u64;
let avail = stat.f_bavail as u64;
avail * bsize / (1024 * 1024)
}
fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, stop: Arc<AtomicBool>) {
for id in rx.iter() {
if stop.load(Ordering::SeqCst) {
let _ = builds::requeue_transient(&db, &id);
continue;
}
let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1);
match pipeline::run(&cfg, &db, &id) {
Ok(Outcome::Failed { transient, .. }) => {
// §8.4: transient failures retry with a bounded number of
// attempts; a deterministic failure does not, because it would
// produce the same answer.
if transient && attempt < cfg.max_transient_attempts {
let _ = builds::requeue_transient(&db, &id);
db::audit_system(
&db.writer,
"build.retry",
"build",
&id,
serde_json::json!({"attempt": attempt, "max": cfg.max_transient_attempts}),
)
.ok();
}
}
Ok(Outcome::Cancelled) => {}
Ok(Outcome::Blocked { .. }) | Ok(Outcome::Succeeded { .. }) | Err(_) => {}
}
if stop.load(Ordering::SeqCst) {
break;
}
}
}
|