use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use crate::json_read::Value;
const FORMAT: i64 = 1;
pub(crate) const PENDING_FILE: &str = "cluster-pending";
const LOCK_POLL: Duration = Duration::from_millis(50);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum GateState {
Waiting,
Passed,
Failed,
}
impl GateState {
pub(super) fn as_str(self) -> &'static str {
match self {
GateState::Waiting => "waiting",
GateState::Passed => "passed",
GateState::Failed => "failed",
}
}
fn parse(s: &str) -> Option<GateState> {
match s {
"waiting" => Some(GateState::Waiting),
"passed" => Some(GateState::Passed),
"failed" => Some(GateState::Failed),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RecordPhase {
Submitting,
Pending,
Running,
Succeeded,
Failed,
Error,
Unknown,
Gone,
}
impl RecordPhase {
pub(crate) fn as_str(self) -> &'static str {
match self {
RecordPhase::Submitting => "Submitting",
RecordPhase::Pending => "Pending",
RecordPhase::Running => "Running",
RecordPhase::Succeeded => "Succeeded",
RecordPhase::Failed => "Failed",
RecordPhase::Error => "Error",
RecordPhase::Unknown => "Unknown",
RecordPhase::Gone => "Gone",
}
}
pub(crate) fn parse(s: &str) -> RecordPhase {
match s {
"Submitting" => RecordPhase::Submitting,
"Pending" => RecordPhase::Pending,
"Running" => RecordPhase::Running,
"Succeeded" => RecordPhase::Succeeded,
"Failed" => RecordPhase::Failed,
"Error" => RecordPhase::Error,
"Gone" => RecordPhase::Gone,
_ => RecordPhase::Unknown,
}
}
pub(crate) fn finished(self) -> bool {
match self {
RecordPhase::Succeeded
| RecordPhase::Failed
| RecordPhase::Error
| RecordPhase::Gone => true,
RecordPhase::Submitting
| RecordPhase::Pending
| RecordPhase::Running
| RecordPhase::Unknown => false,
}
}
pub(crate) fn plain(self) -> &'static str {
match self {
RecordPhase::Submitting => "being submitted",
RecordPhase::Pending => "queued",
RecordPhase::Running => "running",
RecordPhase::Succeeded => "finished",
RecordPhase::Failed => "failed",
RecordPhase::Error => "ended in error",
RecordPhase::Unknown => "not reported yet",
RecordPhase::Gone => "gone (TTL passed or deleted)",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PendingError {
pub(crate) op: &'static str,
pub(crate) path: PathBuf,
pub(crate) cause: String,
}
impl PendingError {
fn new(op: &'static str, path: &Path, cause: impl ToString) -> PendingError {
PendingError {
op,
path: path.to_path_buf(),
cause: cause.to_string(),
}
}
}
impl std::fmt::Display for PendingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}: {}", self.op, self.path.display(), self.cause)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Gate {
pub(super) id: String,
pub(super) task: String,
pub(super) argv: Vec<String>,
pub(super) scope: String,
pub(super) prepare: Option<String>,
pub(super) digest: String,
pub(super) contract: String,
pub(super) token: String,
pub(super) state: GateState,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Source {
pub(super) snapshot_ref: Option<String>,
pub(super) oid: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Pending {
pub(super) name: String,
pub(super) uid: Option<String>,
pub(super) label: String,
pub(super) namespace: String,
pub(super) kubeconfig: PathBuf,
pub(super) tree: String,
pub(super) source: Source,
pub(super) submitted: u64,
pub(super) phase: RecordPhase,
pub(super) gates: Vec<Gate>,
pub(super) awaiting_signer: bool,
}
impl Pending {
pub(super) fn render(&self) -> String {
use crate::json::{array, int_field, object, opt_string_field, string_array_field};
use crate::json::{bool_field, string_field};
let gates: Vec<String> = self
.gates
.iter()
.map(|g| {
object(&[
string_field("id", &g.id),
string_field("task", &g.task),
string_array_field("argv", &g.argv),
string_field("scope", &g.scope),
opt_string_field("prepare", g.prepare.as_deref()),
string_field("digest", &g.digest),
string_field("contract", &g.contract),
string_field("token", &g.token),
string_field("state", g.state.as_str()),
])
})
.collect();
let source = object(&[
opt_string_field("snapshotRef", self.source.snapshot_ref.as_deref()),
string_field("oid", &self.source.oid),
bool_field("pushed", self.source.snapshot_ref.is_some()),
]);
let mut fields = vec![
string_field("name", &self.name),
opt_string_field("uid", self.uid.as_deref()),
string_field("label", &self.label),
string_field("namespace", &self.namespace),
string_field("kubeconfig", &self.kubeconfig.to_string_lossy()),
string_field("tree", &self.tree),
format!("\"source\":{source}"),
int_field(
"submitted",
i64::try_from(self.submitted).unwrap_or(i64::MAX),
),
string_field("phase", self.phase.as_str()),
format!("\"gates\":{}", array(&gates)),
];
if self.awaiting_signer {
fields.push(string_field("signer", "awaiting"));
}
object(&fields)
}
fn parse(v: &Value) -> Option<Pending> {
let text = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
let gates = v
.get("gates")?
.items()
.iter()
.map(parse_gate)
.collect::<Option<Vec<Gate>>>()?;
let source = v.get("source")?;
let submitted = match v.get("submitted")? {
Value::Num(n) => n.parse().ok()?,
_ => return None,
};
Some(Pending {
name: text("name")?,
uid: text("uid"),
label: text("label")?,
namespace: text("namespace")?,
kubeconfig: PathBuf::from(text("kubeconfig")?),
tree: text("tree")?,
source: Source {
snapshot_ref: source
.get("snapshotRef")
.and_then(Value::as_str)
.map(str::to_string),
oid: source.get("oid")?.as_str()?.to_string(),
},
submitted,
phase: RecordPhase::parse(&text("phase")?),
gates,
awaiting_signer: text("signer").as_deref() == Some("awaiting"),
})
}
pub(super) fn waiting(&self) -> impl Iterator<Item = &Gate> {
self.gates.iter().filter(|g| g.state == GateState::Waiting)
}
}
fn parse_gate(v: &Value) -> Option<Gate> {
let text = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
Some(Gate {
id: text("id")?,
task: text("task")?,
argv: v
.get("argv")?
.items()
.iter()
.map(|a| a.as_str().map(str::to_string))
.collect::<Option<Vec<String>>>()?,
scope: text("scope")?,
prepare: text("prepare"),
digest: text("digest")?,
contract: text("contract")?,
token: text("token")?,
state: GateState::parse(v.get("state")?.as_str()?)?,
})
}
#[cfg(test)]
pub(crate) fn sample_file(submitted: u64) -> String {
let mut record = tests::sample("rh-sample");
record.submitted = submitted;
render_file(&[record])
}
pub(super) fn render_file(records: &[Pending]) -> String {
let body: Vec<String> = records.iter().map(Pending::render).collect();
format!(
"{{\"format\":{FORMAT},\"records\":{}}}\n",
crate::json::array(&body)
)
}
pub(super) fn parse_file(text: &str) -> Result<Vec<Pending>, String> {
let doc = crate::json_read::parse(text).ok_or("not JSON")?;
match doc.get("format") {
Some(Value::Num(n)) if n == &FORMAT.to_string() => {}
_ => return Err(format!("a layout this {} did not write", crate::names::BIN)),
}
doc.get("records")
.ok_or("no records")?
.items()
.iter()
.map(|r| {
Pending::parse(r)
.ok_or_else(|| format!("a record this {} cannot read", crate::names::BIN))
})
.collect()
}
pub(super) struct Guard {
_file: File,
}
#[cfg(unix)]
extern "C" {
#[link_name = "flock"]
fn libc_flock(fd: i32, op: i32) -> i32;
}
#[cfg(unix)]
const LOCK_EX: i32 = 2;
#[cfg(unix)]
const LOCK_NB: i32 = 4;
#[cfg(unix)]
fn try_lock_file(path: &Path) -> Option<File> {
use std::os::unix::io::AsRawFd;
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(path)
.ok()?;
(unsafe { libc_flock(file.as_raw_fd(), LOCK_EX | LOCK_NB) } == 0).then_some(file)
}
#[cfg(not(unix))]
fn try_lock_file(_path: &Path) -> Option<File> {
None
}
pub(super) struct Store {
dir: PathBuf,
}
impl Store {
pub(super) fn here() -> Option<Store> {
let common =
crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
Some(Store {
dir: Path::new(&common).join(crate::names::STATE_DIR),
})
}
#[cfg(test)]
pub(super) fn in_dir(dir: &Path) -> Store {
Store {
dir: dir.to_path_buf(),
}
}
fn file(&self) -> PathBuf {
self.dir.join(PENDING_FILE)
}
pub(super) fn exists(&self) -> bool {
self.file().exists()
}
pub(super) fn try_lock(&self) -> Option<Guard> {
std::fs::create_dir_all(&self.dir).ok()?;
try_lock_file(&self.dir.join("cluster-pending.lock")).map(|_file| Guard { _file })
}
pub(super) fn lock_within(&self, wait: Duration) -> Option<Guard> {
let until = Instant::now() + wait;
loop {
if let Some(held) = self.try_lock() {
return Some(held);
}
if Instant::now() >= until {
return None;
}
std::thread::sleep(LOCK_POLL);
}
}
pub(super) fn read(&self) -> Result<Vec<Pending>, PendingError> {
let path = self.file();
match std::fs::read_to_string(&path) {
Ok(text) => {
parse_file(&text).map_err(|why| PendingError::new("cannot read", &path, why))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
Err(e) => Err(PendingError::new("cannot read", &path, e)),
}
}
pub(super) fn write(&self, _held: &Guard, records: &[Pending]) -> Result<(), PendingError> {
let path = self.file();
if records.is_empty() {
return match std::fs::remove_file(&path) {
Ok(()) => sync_dir(&self.dir),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(PendingError::new("cannot remove", &path, e)),
};
}
let staging = self
.dir
.join(format!("cluster-pending.tmp-{}", std::process::id()));
let staged = File::create(&staging).and_then(|mut file| {
file.write_all(render_file(records).as_bytes())?;
file.sync_all()
});
let moved = staged.and_then(|()| std::fs::rename(&staging, &path));
if let Err(e) = moved {
let removed = std::fs::remove_file(&staging);
drop(removed);
return Err(PendingError::new("cannot write", &path, e));
}
sync_dir(&self.dir)
}
}
fn sync_dir(dir: &Path) -> Result<(), PendingError> {
#[cfg(unix)]
{
File::open(dir)
.and_then(|d| d.sync_all())
.map_err(|e| PendingError::new("cannot sync", dir, e))
}
#[cfg(not(unix))]
{
let _ = dir; Ok(())
}
}
#[cfg(test)]
pub(in crate::cluster::detached) mod tests {
use super::*;
pub(in crate::cluster::detached) fn sample(name: &str) -> Pending {
Pending {
name: name.into(),
uid: Some("uid-1".into()),
label: "7-00000000000000aa-0".into(),
namespace: "greengate-gates".into(),
kubeconfig: PathBuf::from("/k \"quoted\".yaml"),
tree: "t".repeat(40),
source: Source {
snapshot_ref: Some("refs/snapshots/7-00000000000000aa-0".into()),
oid: "c".repeat(40),
},
submitted: 1_700_000_000,
phase: RecordPhase::Running,
gates: vec![Gate {
id: "pre-push-lint".into(),
task: "g0".into(),
argv: vec!["scripts/gate.sh".into(), "--a b".into()],
scope: "Scope { .. }".into(),
prepare: Some("make \"deps\"".into()),
digest: format!("sha256:{}", "a".repeat(64)),
contract: crate::gate_identity::CLUSTER_CONTRACT.into(),
token: "pre-push-lint@abc".into(),
state: GateState::Waiting,
}],
awaiting_signer: false,
}
}
#[test]
fn a_record_survives_the_round_trip() {
let mut second = sample("wf-2");
second.uid = None;
second.source.snapshot_ref = None;
second.gates[0].prepare = None;
second.gates[0].state = GateState::Passed;
let records = vec![sample("wf-1"), second];
assert_eq!(parse_file(&render_file(&records)), Ok(records));
}
#[test]
fn a_file_without_the_signer_field_still_reads() {
let old = "{\"format\":1,\"records\":[{\"name\":\"wf-1\",\"uid\":\"uid-1\",\
\"label\":\"7-00000000000000aa-0\",\"namespace\":\"greengate-gates\",\
\"kubeconfig\":\"/k.yaml\",\"tree\":\"tttt\",\"source\":{\"snapshotRef\":null,\
\"oid\":\"cccc\",\"pushed\":false},\"submitted\":1700000000,\"phase\":\"Running\",\
\"gates\":[{\"id\":\"pre-push-lint\",\"task\":\"g0\",\"argv\":[\"scripts/gate.sh\"],\
\"scope\":\"s\",\"prepare\":null,\"digest\":\"sha256:aa\",\"contract\":\"c\",\
\"token\":\"pre-push-lint@abc\",\"state\":\"passed\"}]}]}\n";
let records = parse_file(old).expect("an old file reads");
assert_eq!(records.len(), 1);
assert!(!records[0].awaiting_signer);
assert!(
!render_file(&records).contains("\"signer\""),
"nothing awaits, nothing is written"
);
}
#[test]
fn an_awaiting_record_round_trips() {
let mut awaiting = sample("wf-1");
awaiting.gates[0].state = GateState::Passed;
awaiting.awaiting_signer = true;
let text = render_file(&[awaiting.clone(), sample("wf-2")]);
assert_eq!(text.matches("\"signer\":\"awaiting\"").count(), 1, "{text}");
assert_eq!(parse_file(&text), Ok(vec![awaiting, sample("wf-2")]));
let other = text.replace("\"signer\":\"awaiting\"", "\"signer\":\"later\"");
assert!(!parse_file(&other).expect("reads")[0].awaiting_signer);
}
#[test]
fn a_foreign_file_is_an_error_not_an_empty_list() {
assert!(parse_file("").is_err());
assert!(parse_file("{\"format\":2,\"records\":[]}").is_err());
assert!(parse_file("{\"format\":1,\"records\":[{\"name\":\"x\"}]}").is_err());
}
#[test]
fn writing_replaces_the_file_and_no_record_removes_it() {
let dir = std::env::temp_dir().join(format!("greengate-pending-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("mkdir");
let store = Store::in_dir(&dir);
assert_eq!(store.read(), Ok(Vec::new()));
let Some(held) = store.try_lock() else {
return;
};
store.write(&held, &[sample("wf-1")]).expect("write");
assert!(store.exists());
assert_eq!(store.read(), Ok(vec![sample("wf-1")]));
store.write(&held, &[]).expect("remove");
assert!(!store.exists());
drop(held);
std::fs::remove_dir_all(&dir).expect("clean");
}
#[cfg(unix)]
#[test]
fn a_second_writer_does_not_get_the_lock() {
let dir =
std::env::temp_dir().join(format!("greengate-pending-lock-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("mkdir");
let store = Store::in_dir(&dir);
let first = store.try_lock().expect("the first writer locks");
assert!(store.try_lock().is_none(), "busy at once, never waiting");
assert!(store.lock_within(Duration::from_millis(120)).is_none());
drop(first);
assert!(store.lock_within(Duration::from_secs(5)).is_some());
std::fs::remove_dir_all(&dir).expect("clean");
}
}