Watch
0
0
Fork
You've already forked hyperhive
0

Compare commits

..
19 changed files with 576 additions and 83 deletions

3
Cargo.lock generated
View file

@ -5278,6 +5278,7 @@ dependencies = [
"serde_json",
"serde_norway",
"swarm-authelia-bridge-sock",
"swarm-secret-client",
"tokio",
"tracing",
"tracing-subscriber",
@ -5438,6 +5439,7 @@ dependencies = [
"anyhow",
"axum",
"clap",
"futures-util",
"sha2 0.11.1",
"swarm-agent-verify",
"swarm-secret-client",
@ -5599,6 +5601,7 @@ version = "0.1.0"
dependencies = [
"backon",
"futures-util",
"libc",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry_sdk",

View file

@ -385,17 +385,7 @@ async fn cmd_serve(
let coord_sig = coord.clone();
tokio::select! {
res = server::serve(socket, coord) => { res? }
_ = tokio::signal::ctrl_c() => {
tracing::info!("SIGINT received — requesting shutdown");
coord_sig.request_shutdown();
}
() = async {
let mut sig = tokio::signal::unix::signal(
tokio::signal::unix::SignalKind::terminate()
).expect("failed to install SIGTERM handler");
sig.recv().await;
} => {
tracing::info!("SIGTERM received — requesting shutdown");
() = swarm_secret_client::shutdown_signal() => {
coord_sig.request_shutdown();
}
}

View file

@ -19,6 +19,8 @@ serde.workspace = true
serde_json.workspace = true
serde_norway = "0.9.42"
swarm-authelia-bridge-sock.workspace = true
# `shutdown_signal`: the bridge drains its in-flight requests on SIGTERM.
swarm-secret-client.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true

View file

@ -106,6 +106,7 @@ struct AppState {
#[tokio::main]
async fn main() -> Result<()> {
let stop = swarm_secret_client::shutdown_signal();
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
@ -130,9 +131,22 @@ async fn main() -> Result<()> {
let listener = bind_socket(&socket)?;
tracing::info!(socket = %socket.display(), "swarm-authelia-bridge listening");
axum::serve(listener, app)
serve(listener, app, stop).await
}
/// Answers on `listener` until `stop` resolves, then lets the requests in hand
/// finish, for at most the drain, and returns.
async fn serve(
listener: tokio::net::UnixListener,
app: Router,
stop: impl Future<Output = ()> + Clone + Send + 'static,
) -> Result<()> {
let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone());
swarm_secret_client::serve_bounded(stop, serving.into_future())
.await
.context("serving swarm-authelia-bridge")
.transpose()
.context("serving swarm-authelia-bridge")?;
Ok(())
}
/// Bind the listening socket at `path`, replacing a stale one a crash left

View file

@ -88,6 +88,7 @@ fn push_budget(reply_by: tokio::time::Instant) -> Duration {
#[tokio::main]
async fn main() -> Result<()> {
let stop = swarm_secret_client::shutdown_signal();
hive_log::init();
swarm_secret_client::install_crypto_provider();
let var = |name: &str| {
@ -174,8 +175,19 @@ async fn main() -> Result<()> {
let slot = Arc::new(tokio::sync::Semaphore::new(1));
serve_meta_builds(&queue, &publisher, Store, &builder, &slot, &metrics).await?;
answer_builds(requests, publisher, Store, builder, slot, metrics).await;
bail!("the subscription to {SUBJECT} ended")
answer_builds(
requests.take_until(stop.clone()),
publisher,
Store,
builder,
slot,
metrics,
)
.await;
if stop.peek().is_none() {
bail!("the subscription to {SUBJECT} ended");
}
Ok(())
}
/// Where a reply goes. [`Queue`] in production; tests record.
@ -260,6 +272,8 @@ async fn send_reply(
}
/// Answer every PR check, each in its own task, with the build's result.
/// Returns once `requests` ends; a build still running is not waited for, and
/// its requester gets no reply, as when the process is killed.
async fn answer_builds(
mut requests: impl Stream<Item = Message> + Unpin,
publisher: impl Publisher,

View file

@ -100,6 +100,7 @@ impl login::CredentialSink for AgentLeaf {
#[tokio::main]
async fn main() -> Result<()> {
let stop = swarm_secret_client::shutdown_signal();
hive_log::init();
swarm_secret_client::install_crypto_provider();
let var = |name: &str| {
@ -138,9 +139,11 @@ async fn main() -> Result<()> {
let mut requests = queue
.subscribe(SUBJECT)
.await
.with_context(|| format!("subscribing to {SUBJECT}"))?;
.with_context(|| format!("subscribing to {SUBJECT}"))?
.take_until(stop.clone());
tracing::info!(subject = SUBJECT, "claude login minter: awaiting logins");
let mut in_flight = swarm_secret_client::InFlight::new();
while let Some(msg) = requests.next().await {
let Some(reply_to) = msg.reply.clone() else {
tracing::warn!("a login step arrived with no reply subject; dropping it");
@ -149,7 +152,7 @@ async fn main() -> Result<()> {
let queue = queue.clone();
let logins = Arc::clone(&logins);
let metrics = Arc::clone(&metrics);
tokio::spawn(async move {
in_flight.spawn(async move {
let reply = handle(&msg.payload, &logins, &metrics).await;
match serde_json::to_vec(&reply) {
Ok(body) => {
@ -161,7 +164,11 @@ async fn main() -> Result<()> {
}
});
}
bail!("the subscription to {SUBJECT} ended")
in_flight.drain().await;
if stop.peek().is_none() {
bail!("the subscription to {SUBJECT} ended");
}
Ok(())
}
/// Answer one step and count it.

View file

@ -269,7 +269,7 @@ async fn main() -> Result<()> {
reviews: Arc::default(),
alerts: alerts::from_env(),
};
serve(listener, state).await
serve(listener, state, swarm_secret_client::shutdown_signal()).await
}
/// Registers the `bao.client_cert.*` gauges for the controller's own store
@ -286,11 +286,20 @@ fn register_cert_gauges(provider: Option<&opentelemetry_sdk::metrics::SdkMeterPr
}
/// Start taking the queued review requests and answering the notification
/// router's, then serve `state` on `listener`.
async fn serve(listener: tokio::net::UnixListener, state: AppState) -> Result<()> {
review_classifier::review::spawn_queue(&state);
/// router's, then serve `state` on `listener` until `stop` resolves. The
/// requests in hand finish for at most the drain; the review queue takes no
/// request after `stop`.
async fn serve(
listener: tokio::net::UnixListener,
state: AppState,
stop: impl Future<Output = ()> + Clone + Send + 'static,
) -> Result<()> {
review_classifier::review::spawn_queue(&state, stop.clone());
request_reviewer::spawn(&state);
axum::serve(listener, build_app(state))
let serving = axum::serve(listener, build_app(state)).with_graceful_shutdown(stop.clone());
swarm_secret_client::serve_bounded(stop, serving.into_future())
.await
.context("serving swarm-controller")
.transpose()
.context("serving swarm-controller")?;
Ok(())
}

View file

@ -443,7 +443,10 @@ async fn open_consumer(
/// Take the queued review requests and review each, for as long as the
/// controller runs, once this host has forge access.
pub(crate) fn spawn_queue(state: &AppState) {
pub(crate) fn spawn_queue(
state: &AppState,
stop: impl Future<Output = ()> + Clone + Send + 'static,
) {
let Some(client) = state.status.as_ref().map(|s| s.queue_client()) else {
tracing::warn!("no swarm queue is configured on this host; requested reviews don't run");
return;
@ -466,7 +469,7 @@ pub(crate) fn spawn_queue(state: &AppState) {
runs,
metrics: Metrics::global(),
};
consume(&client, TIMING, &reviews, handles).await;
consume(&client, TIMING, &reviews, handles, stop).await;
});
}
@ -494,8 +497,9 @@ impl<S, Q: Clone, P> Clone for Handles<S, Q, P> {
}
/// Take requests from [`REQUEST_STREAM`] one at a time, each once a run
/// place is free, and review each in a task of its own. Never returns;
/// dropping it stops every review it started, and the queue delivers their
/// place is free, and review each in a task of its own. Returns once `stop`
/// resolves, taking no request after it; dropping it, as the return does, stops
/// every review it started without acking, and the queue delivers their
/// requests again.
///
/// The limit is read from the settings before each wait for a place. A
@ -506,6 +510,7 @@ async fn consume<S, Q, P>(
timing: Timing,
reviews: &Arc<Reviews>,
handles: Handles<S, Q, P>,
stop: impl Future<Output = ()> + Clone,
) where
S: FileSource + PullSource + Send + Sync + 'static,
Q: RunSink + SettingsSource,
@ -519,7 +524,11 @@ async fn consume<S, Q, P>(
"opening the review request queue failed; trying again"
),
}
tokio::time::sleep(timing.pull_wait).await;
tokio::select! {
biased;
() = stop.clone() => return,
() = tokio::time::sleep(timing.pull_wait) => {}
}
};
let mut tasks = JoinSet::new();
loop {
@ -536,8 +545,17 @@ async fn consume<S, Q, P>(
the last limit read"
),
}
let slot = reviews.slot().await;
let message = match next(&consumer, timing.pull_wait).await {
let slot = tokio::select! {
biased;
() = stop.clone() => return,
slot = reviews.slot() => slot,
};
let taken = tokio::select! {
biased;
() = stop.clone() => return,
taken = next(&consumer, timing.pull_wait) => taken,
};
let message = match taken {
Ok(Some(message)) => message,
Ok(None) => continue,
Err(e) => {
@ -546,7 +564,11 @@ async fn consume<S, Q, P>(
"taking a review request from the queue failed; trying again"
);
drop(slot);
tokio::time::sleep(timing.pull_wait).await;
tokio::select! {
biased;
() = stop.clone() => return,
() = tokio::time::sleep(timing.pull_wait) => {}
}
continue;
}
};
@ -2032,6 +2054,15 @@ mod tests {
/// A controller taking requests, its run places in `reviews`.
fn consume(&self, reviews: &Arc<Reviews>) -> JoinHandle<()> {
self.consume_until(reviews, std::future::pending())
}
/// A controller that takes no request once `stop` resolves.
fn consume_until(
&self,
reviews: &Arc<Reviews>,
stop: impl Future<Output = ()> + Clone + Send + 'static,
) -> JoinHandle<()> {
let client = self.client.clone();
let reviews = Arc::clone(reviews);
let forge = Arc::clone(&self.rig.forge);
@ -2047,7 +2078,7 @@ mod tests {
runs: store,
metrics,
};
consume(&client, TEST_TIMING, &reviews, handles).await;
consume(&client, TEST_TIMING, &reviews, handles, stop).await;
})
}
@ -2113,6 +2144,36 @@ mod tests {
assert_eq!(q.rig.gate.reached(), 2, "no run after the ack");
}
/// After the stop the controller returns and takes no request, and the
/// review it was running stays un-acked, so the queue still holds it.
#[tokio::test]
async fn after_the_stop_no_request_is_taken_and_the_running_one_stays_unacked() {
let q = Queued::new().await;
q.request(7, "abc123").await;
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
let stop = futures_util::FutureExt::shared(async move {
let _ = stop_rx.await;
});
let consumer = q.consume_until(&q.rig.reviews, stop);
until("the first run started", || q.rig.gate.reached() == 1).await;
stop_tx.send(()).expect("stop");
tokio::time::timeout(Duration::from_secs(5), consumer)
.await
.expect("consume returns after the stop")
.expect("consume did not panic");
// A request that arrives now, and the one running, which the queue
// would redeliver after its ack wait: neither runs.
q.request(8, "abc123").await;
tokio::time::sleep(TEST_TIMING.ack_wait * 3).await;
assert_eq!(q.rig.gate.reached(), 1, "no request taken after the stop");
assert!(
q.rig.posted().is_empty(),
"the unfinished review is not posted"
);
assert_eq!(q.waiting().await, 2, "neither request is acked");
}
#[tokio::test]
async fn a_newer_request_for_a_pr_replaces_the_waiting_one() {
let q = Queued::new().await;

View file

@ -21,3 +21,7 @@ tracing-subscriber.workspace = true
[lints]
workspace = true
[dev-dependencies]
# `Shared`, so the injected stop future can be cloned like `shutdown_signal`'s.
futures-util.workspace = true

View file

@ -195,6 +195,7 @@ async fn handle(
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let stop = swarm_secret_client::shutdown_signal();
swarm_secret_client::install_crypto_provider();
tracing_subscriber::fmt()
.with_env_filter(
@ -235,14 +236,31 @@ async fn main() -> anyhow::Result<()> {
tracing::info!(socket = %args.socket.display(), "swarm-logs-auth listening");
let app = axum::Router::new().fallback(handle).with_state(responder);
axum::serve(listener, app).await.context("serving")
serve(listener, app, stop).await
}
/// Answers on `listener` until `stop` resolves, then lets the requests in hand
/// finish, for at most the drain, and returns.
async fn serve(
listener: tokio::net::UnixListener,
app: axum::Router,
stop: impl Future<Output = ()> + Clone + Send + 'static,
) -> anyhow::Result<()> {
let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone());
swarm_secret_client::serve_bounded(stop, serving.into_future())
.await
.transpose()
.context("serving")?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use futures_util::FutureExt as _;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use swarm_secret_client::queue::AgentCredential;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
/// What the mirrored grant leaf answers.
#[derive(Clone, Copy)]
@ -474,4 +492,59 @@ mod tests {
}
assert_eq!(store.lookups(), 3);
}
/// A request that is being answered when the stop arrives is still
/// answered, and `serve` returns only afterwards.
#[tokio::test]
async fn a_request_in_flight_at_the_stop_is_answered_before_serve_returns() {
let started = Arc::new(tokio::sync::Notify::new());
let release = Arc::new(tokio::sync::Notify::new());
let app = {
let (started, release) = (Arc::clone(&started), Arc::clone(&release));
axum::Router::new().fallback(move || {
let (started, release) = (Arc::clone(&started), Arc::clone(&release));
async move {
started.notify_one();
release.notified().await;
"answered"
}
})
};
let socket =
std::env::temp_dir().join(format!("swarm-logs-auth-stop-{}.sock", std::process::id()));
let _ = std::fs::remove_file(&socket);
let listener = tokio::net::UnixListener::bind(&socket).expect("bind");
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
let stop = async move {
let _ = stop_rx.await;
}
.shared();
let mut serving = tokio::spawn(serve(listener, app, stop));
let mut conn = tokio::net::UnixStream::connect(&socket)
.await
.expect("connect");
conn.write_all(b"GET / HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n")
.await
.expect("send");
started.notified().await;
stop_tx.send(()).expect("stop");
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(
!serving.is_finished(),
"serve returned with a request in flight"
);
release.notify_one();
let mut reply = String::new();
conn.read_to_string(&mut reply).await.expect("reply");
assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
assert!(reply.ends_with("answered"), "{reply}");
let finished = tokio::time::timeout(Duration::from_secs(5), &mut serving)
.await
.expect("serve returns once the request is answered");
finished.expect("task").expect("serve is Ok");
let _ = std::fs::remove_file(&socket);
}
}

View file

@ -282,6 +282,7 @@ async fn handle(State(responder): State<Arc<Responder<Store>>>, headers: HeaderM
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let stop = swarm_secret_client::shutdown_signal();
swarm_secret_client::install_crypto_provider();
tracing_subscriber::fmt()
.with_env_filter(
@ -322,7 +323,22 @@ async fn main() -> anyhow::Result<()> {
tracing::info!(socket = %args.socket.display(), "swarm-metrics-auth listening");
let app = axum::Router::new().fallback(handle).with_state(responder);
axum::serve(listener, app).await.context("serving")
serve(listener, app, stop).await
}
/// Answers on `listener` until `stop` resolves, then lets the requests in hand
/// finish, for at most the drain, and returns.
async fn serve(
listener: tokio::net::UnixListener,
app: axum::Router,
stop: impl Future<Output = ()> + Clone + Send + 'static,
) -> anyhow::Result<()> {
let serving = axum::serve(listener, app).with_graceful_shutdown(stop.clone());
swarm_secret_client::serve_bounded(stop, serving.into_future())
.await
.transpose()
.context("serving")?;
Ok(())
}
#[cfg(test)]

View file

@ -182,6 +182,7 @@ struct Args {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let stop = swarm_secret_client::shutdown_signal();
swarm_secret_client::install_crypto_provider();
tracing_subscriber::fmt()
.with_env_filter(
@ -210,14 +211,14 @@ async fn main() -> anyhow::Result<()> {
)
.await
}
(None, Some(args)) => serve(args).await,
(None, Some(args)) => serve(args, stop).await,
(None, None) => unreachable!("clap requires the responder's flags when no verb is given"),
}
}
/// The responder: answers every authorization request until its
/// subscription ends.
async fn serve(args: Args) -> anyhow::Result<()> {
async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Result<()> {
// The bucket is NOT a flag. `swarm_queue_client::status`'s own docs say
// why: reader and writer must name the same bucket, and an option is a
// way for two deployments to disagree about which one that is. This
@ -279,25 +280,33 @@ async fn serve(args: Args) -> anyhow::Result<()> {
callout_xkey,
issuer,
});
answer_each(requests, CONCURRENT_REQUESTS, move |msg| {
let responder = Arc::clone(&responder);
let client = client.clone();
async move {
let Some((reply_to, reply)) = responder.answer(&msg).await else {
return;
};
if let Err(e) = client.publish(reply_to, reply.into()).await {
tracing::warn!(error = ?e, "failed to publish auth response");
answer_each(
requests.take_until(stop.clone()),
CONCURRENT_REQUESTS,
move |msg| {
let responder = Arc::clone(&responder);
let client = client.clone();
async move {
let Some((reply_to, reply)) = responder.answer(&msg).await else {
return;
};
if let Err(e) = client.publish(reply_to, reply.into()).await {
tracing::warn!(error = ?e, "failed to publish auth response");
}
}
}
})
},
)
.await;
anyhow::bail!("subscription to {AUTH_SUBJECT} ended")
if stop.peek().is_none() {
anyhow::bail!("subscription to {AUTH_SUBJECT} ended");
}
Ok(())
}
/// Runs `answer` on each of `requests`, at most `permits` at once. A request
/// waits in `requests` until a permit is free; the reply carries `server_id`
/// and `user_nkey`, so the order answers go out in does not matter.
/// and `user_nkey`, so the order answers go out in does not matter. Once
/// `requests` ends, the answers in hand get the drain to finish.
async fn answer_each<R, F, Fut>(
mut requests: impl futures_util::Stream<Item = R> + Unpin,
permits: usize,
@ -307,16 +316,18 @@ async fn answer_each<R, F, Fut>(
Fut: std::future::Future<Output = ()> + Send + 'static,
{
let permits = Arc::new(tokio::sync::Semaphore::new(permits));
let mut in_flight = swarm_secret_client::InFlight::new();
while let Some(request) = requests.next().await {
let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
unreachable!("the semaphore is never closed");
};
let answering = answer(request);
tokio::spawn(async move {
in_flight.spawn(async move {
answering.await;
drop(permit);
});
}
in_flight.drain().await;
}
/// Whether the server has stopped waiting for the answer to a request whose

View file

@ -35,7 +35,7 @@ use std::time::{Duration, Instant};
use anyhow::{Context as _, Result, bail};
use async_nats::jetstream::{self, consumer::pull, kv, message::PublishMessage};
use futures_util::StreamExt as _;
use futures_util::{FutureExt as _, StreamExt as _};
use metrics::Handled;
use swarm_queue_client::{ClientSecret, QueueConfig};
use swarm_secret_client::stored_secret::StoredSecret;
@ -79,6 +79,7 @@ const ROSTER_TTL: Duration = Duration::from_mins(1);
#[tokio::main]
async fn main() -> Result<()> {
let stop = swarm_secret_client::shutdown_signal();
hive_log::init();
swarm_secret_client::install_crypto_provider();
let var = |name: &str| {
@ -113,16 +114,26 @@ async fn main() -> Result<()> {
stream = forge_events::STREAM,
"notify router: routing forge events"
);
loop {
if let Err(e) = router.pull_once().await {
router.metrics.pull_failed();
tracing::warn!(
error = format!("{e:#}"),
"notify router: pulling events failed; retrying"
);
tokio::time::sleep(RETRY_DELAY).await;
while stop.clone().now_or_never().is_none() {
let pulled =
swarm_secret_client::serve_bounded(stop.clone(), router.pull_once(stop.clone())).await;
match pulled {
Some(Ok(())) => {}
Some(Err(e)) => {
router.metrics.pull_failed();
tracing::warn!(
error = format!("{e:#}"),
"notify router: pulling events failed; retrying"
);
tokio::select! {
() = stop.clone() => {}
() = tokio::time::sleep(RETRY_DELAY) => {}
}
}
None => break,
}
}
Ok(())
}
struct Router {
@ -184,8 +195,11 @@ impl Router {
})
}
/// Pull one batch and handle each event in stream order.
async fn pull_once(&mut self) -> Result<()> {
/// Pull one batch and handle each event in stream order, taking no event
/// after `stop` resolves. The one being handled finishes and is settled;
/// the rest of the batch is left un-acked and comes back after the ack
/// wait.
async fn pull_once(&mut self, stop: swarm_secret_client::Shutdown) -> Result<()> {
if let Ok(info) = self.events.info().await {
self.metrics
.consumer(info.num_pending, info.num_ack_pending, info.num_redelivered);
@ -199,7 +213,10 @@ impl Router {
.await
.context("requesting a batch")?;
let batch = batch.map(|m| m.map_err(|e| anyhow::anyhow!("{e}")));
settle::batch(batch, async |m: &jetstream::Message| self.handle(m).await).await
settle::batch(batch, stop, async |m: &jetstream::Message| {
self.handle(m).await
})
.await
}
/// Handle one event and count how it went.

View file

@ -33,11 +33,15 @@ impl Pulled for async_nats::jetstream::Message {
/// Handle each event of `batch` with `handle` and settle it. Returns the
/// error of the first event that has to be retried, once the rest of the
/// batch is nakked behind it.
///
/// Once `stop` resolves no further event is taken: the one being handled is
/// settled, and the rest stay un-acked and come back after the ack wait.
pub(crate) async fn batch<P: Pulled>(
batch: impl Stream<Item = Result<P>>,
stop: impl Future<Output = ()>,
mut handle: impl AsyncFnMut(&P) -> Result<(), Skip>,
) -> Result<()> {
let mut batch = std::pin::pin!(batch);
let mut batch = std::pin::pin!(batch.take_until(stop));
let mut failed: Option<anyhow::Error> = None;
while let Some(event) = batch.next().await {
let event = event?;
@ -102,14 +106,18 @@ mod tests {
})
});
let mut handled = Vec::new();
let result = batch(futures_util::stream::iter(events), async |e: &Fake<'_>| {
handled.push(e.name);
if e.name == "assigned" {
Err(Skip::Retry(anyhow::anyhow!("the queue is down")))
} else {
Ok(())
}
})
let result = batch(
futures_util::stream::iter(events),
std::future::pending(),
async |e: &Fake<'_>| {
handled.push(e.name);
if e.name == "assigned" {
Err(Skip::Retry(anyhow::anyhow!("the queue is down")))
} else {
Ok(())
}
},
)
.await;
assert!(result.is_err());
assert_eq!(handled, ["opened", "assigned"]);
@ -135,13 +143,17 @@ mod tests {
settled: &settled,
})
});
let result = batch(futures_util::stream::iter(events), async |e: &Fake<'_>| {
if e.name == "bad" {
Err(Skip::Unusable("no".to_owned()))
} else {
Ok(())
}
})
let result = batch(
futures_util::stream::iter(events),
std::future::pending(),
async |e: &Fake<'_>| {
if e.name == "bad" {
Err(Skip::Unusable("no".to_owned()))
} else {
Ok(())
}
},
)
.await;
assert!(result.is_ok());
assert_eq!(
@ -152,4 +164,44 @@ mod tests {
]
);
}
/// The stop arrives while `assigned` is being handled: it is still
/// settled, and `unassigned` and `closed` are neither handled nor settled,
/// so the queue redelivers them.
#[tokio::test]
async fn after_the_stop_the_event_in_hand_is_settled_and_the_rest_is_left_unacked() {
let settled = RefCell::new(Vec::new());
let events = ["opened", "assigned", "unassigned", "closed"].map(|name| {
Ok(Fake {
name,
settled: &settled,
})
});
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
let mut stop_tx = Some(stop_tx);
let mut handled = Vec::new();
let result = batch(
futures_util::stream::iter(events),
async {
let _ = stop_rx.await;
},
async |e: &Fake<'_>| {
handled.push(e.name);
if e.name == "assigned" {
stop_tx.take().expect("sent once").send(()).expect("stop");
}
Ok(())
},
)
.await;
assert!(result.is_ok());
assert_eq!(handled, ["opened", "assigned"]);
assert_eq!(
settled.into_inner(),
[
("opened", format!("{:?}", AckKind::Ack)),
("assigned", format!("{:?}", AckKind::Ack)),
]
);
}
}

View file

@ -47,6 +47,7 @@ fn main() -> Result<()> {
}
async fn serve() -> Result<()> {
let stop = swarm_secret_client::shutdown_signal();
hive_log::init();
swarm_secret_client::install_crypto_provider();
let var = |name: &str| {
@ -92,7 +93,8 @@ async fn serve() -> Result<()> {
let mut requests = queue
.queue_subscribe(SUBJECT, QUEUE_GROUP.to_owned())
.await
.with_context(|| format!("subscribing to {SUBJECT}"))?;
.with_context(|| format!("subscribing to {SUBJECT}"))?
.take_until(stop.clone());
tracing::info!(subject = SUBJECT, "review classifier: awaiting try-outs");
let models = std::sync::Arc::new(models);
@ -115,7 +117,10 @@ async fn serve() -> Result<()> {
}
});
}
bail!("the subscription to {SUBJECT} ended")
if stop.peek().is_none() {
bail!("the subscription to {SUBJECT} ended");
}
Ok(())
}
/// Decode one request, answer it and log the run.

View file

@ -47,6 +47,8 @@ workspace = true
# provider compiled in rustls picks it without an install, so the provider
# test would pass with `install_crypto_provider` doing nothing.
[dev-dependencies]
# `raise`, to send the test process a real SIGTERM.
libc.workspace = true
# `InMemoryMetricExporter`, to read back what `cert_metrics` exports.
opentelemetry_sdk = { workspace = true, features = ["testing"] }
rustls = { workspace = true, features = ["ring"] }

View file

@ -55,10 +55,12 @@ pub mod policy;
pub mod proxy;
pub mod queue;
pub mod review_classifier;
pub mod shutdown;
pub mod startup_read;
pub mod stored_secret;
pub use client::SecretStore;
pub use shutdown::{DRAIN, InFlight, Shutdown, serve_bounded, shutdown_signal};
pub use startup_read::read_with_startup_retry;
/// What can go wrong between "we have a client certificate" and "we have the

View file

@ -0,0 +1,206 @@
//! Stopping a daemon when its unit is stopped.
//!
//! `systemctl stop` and a container runtime both send SIGTERM. A process with
//! no handler dies on the default action, mid-request; one that waits on
//! [`shutdown_signal`] finishes what it has in hand and exits 0. Every swarm
//! daemon's `main` shares this one definition of "told to stop" and of how
//! long it then gets ([`DRAIN`]).
use std::future::Future;
use std::time::Duration;
use futures_util::FutureExt as _;
use futures_util::future::{BoxFuture, Shared};
use tokio::signal::unix::{SignalKind, signal};
use tokio::task::JoinSet;
/// How long work in hand may take once the signal has arrived. Well under
/// systemd's default `TimeoutStopSec` (90 s) and a pod's 30 s grace period, so
/// the process exits 0 before either escalates to SIGKILL.
pub const DRAIN: Duration = Duration::from_secs(10);
/// What [`shutdown_signal`] returns: a future that is `Clone`, and whose clones
/// all resolve on the one signal.
pub type Shutdown = Shared<BoxFuture<'static, ()>>;
/// Resolves when the process receives SIGTERM or SIGINT.
///
/// The handlers are installed when this is called, not when the future is
/// first polled, so call it early in `main`: a signal arriving between the
/// call and the first poll is still seen, and one before the call kills the
/// process as before. Clones of the [`Shutdown`] it returns all resolve on the
/// one signal, so a server, a message loop and a bound can all wait on it.
///
/// # Panics
///
/// When the runtime is not running, or the kernel refuses a handler.
pub fn shutdown_signal() -> Shutdown {
let mut term = signal(SignalKind::terminate()).expect("installing the SIGTERM handler");
let mut int = signal(SignalKind::interrupt()).expect("installing the SIGINT handler");
async move {
tokio::select! {
_ = term.recv() => tracing::info!("SIGTERM received; shutting down"),
_ = int.recv() => tracing::info!("SIGINT received; shutting down"),
}
}
.boxed()
.shared()
}
/// Runs `serving`, a server built with `with_graceful_shutdown` on a clone of
/// `stop`, and stops waiting for it [`DRAIN`] after `stop` resolves. `None`
/// means connections were still open then.
///
/// A graceful shutdown waits for every connection to close, and a streaming
/// response never does on its own; without this bound such a daemon sits out
/// the unit's stop timeout and is killed.
pub async fn serve_bounded<T>(
stop: impl Future<Output = ()>,
serving: impl Future<Output = T>,
) -> Option<T> {
tokio::pin!(serving);
tokio::select! {
out = &mut serving => Some(out),
() = async {
stop.await;
tokio::time::sleep(DRAIN).await;
} => {
tracing::warn!(drain = ?DRAIN, "still running after the drain; exiting anyway");
None
}
}
}
/// The handlers a daemon has spawned for messages it already took.
///
/// After the signal the daemon takes no more, calls [`InFlight::drain`], and
/// whatever is still running then is abandoned. Nothing is acknowledged on
/// its behalf, so an unfinished message is redelivered or times out at its
/// sender exactly as it would after a kill.
#[derive(Default)]
pub struct InFlight(JoinSet<()>);
impl InFlight {
/// An empty set.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Runs `handler` on its own task. Handlers that already finished are
/// dropped first, so the set stays as small as the work in hand.
pub fn spawn(&mut self, handler: impl Future<Output = ()> + Send + 'static) {
while self.0.try_join_next().is_some() {}
self.0.spawn(handler);
}
/// Waits up to [`DRAIN`] for the handlers still running.
pub async fn drain(mut self) {
let finished =
tokio::time::timeout(DRAIN, async { while self.0.join_next().await.is_some() {} })
.await;
if finished.is_err() {
tracing::warn!(
abandoned = self.0.len(),
drain = ?DRAIN,
"handlers still running after the drain; abandoning them"
);
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::Notify;
use super::*;
/// A real SIGTERM, then a real SIGINT, raised at this process: the handlers
/// are installed by the call, so the signals are consumed rather than
/// killing the test binary. One test, so the two raises never overlap.
#[tokio::test]
async fn resolves_on_a_sigterm_and_on_a_sigint_raised_at_the_process() {
let stop = shutdown_signal();
let mut stop = std::pin::pin!(stop);
assert!(
stop.as_mut().now_or_never().is_none(),
"resolved with no signal"
);
// SAFETY: `raise` takes a signal number and touches no memory.
assert_eq!(unsafe { libc::raise(libc::SIGTERM) }, 0);
tokio::time::timeout(Duration::from_secs(5), stop)
.await
.expect("SIGTERM resolves the future");
let stop = shutdown_signal();
// SAFETY: as above.
assert_eq!(unsafe { libc::raise(libc::SIGINT) }, 0);
tokio::time::timeout(Duration::from_secs(5), stop)
.await
.expect("SIGINT resolves the future");
}
/// A server that finishes by itself is returned from at once, and its
/// output is the caller's.
#[tokio::test]
async fn serve_bounded_returns_what_the_server_returns() {
let out = serve_bounded(std::future::pending(), async { 7 }).await;
assert_eq!(out, Some(7));
}
/// After `stop`, a server that never ends is given up on once [`DRAIN`]
/// has passed, and not before.
#[tokio::test(start_paused = true)]
async fn serve_bounded_gives_up_only_after_the_drain() {
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
let bounded = tokio::spawn(serve_bounded(
async { stop_rx.await.unwrap() },
std::future::pending::<()>(),
));
tokio::time::sleep(DRAIN * 3).await;
assert!(!bounded.is_finished(), "gave up with no stop");
stop_tx.send(()).unwrap();
tokio::time::sleep(DRAIN / 2).await;
assert!(!bounded.is_finished(), "gave up inside the drain");
tokio::time::sleep(DRAIN / 2 + Duration::from_secs(1)).await;
assert!(bounded.is_finished(), "still waiting past the drain");
assert_eq!(bounded.await.unwrap(), None);
}
/// A handler that finishes inside the drain is waited for.
#[tokio::test(start_paused = true)]
async fn drain_waits_for_a_handler_that_finishes_in_time() {
let done = Arc::new(AtomicBool::new(false));
let mut in_flight = InFlight::new();
let flag = Arc::clone(&done);
in_flight.spawn(async move {
tokio::time::sleep(DRAIN / 2).await;
flag.store(true, Ordering::SeqCst);
});
in_flight.drain().await;
assert!(done.load(Ordering::SeqCst));
}
/// A handler that outlives the drain is abandoned: the drain returns at
/// the bound with the handler unfinished.
#[tokio::test(start_paused = true)]
async fn drain_abandons_a_handler_that_outlives_it() {
let done = Arc::new(AtomicBool::new(false));
let started = Arc::new(Notify::new());
let mut in_flight = InFlight::new();
let (flag, up) = (Arc::clone(&done), Arc::clone(&started));
in_flight.spawn(async move {
up.notify_one();
tokio::time::sleep(DRAIN * 5).await;
flag.store(true, Ordering::SeqCst);
});
started.notified().await;
let before = tokio::time::Instant::now();
in_flight.drain().await;
assert_eq!(before.elapsed(), DRAIN);
assert!(!done.load(Ordering::SeqCst));
}
}

View file

@ -115,6 +115,7 @@ async fn connect_queue(var: Var<'_>) -> Result<async_nats::Client> {
#[tokio::main]
async fn main() -> Result<()> {
let stop = swarm_secret_client::shutdown_signal();
hive_log::init();
swarm_secret_client::install_crypto_provider();
let var = |name: &str| {
@ -151,7 +152,8 @@ async fn main() -> Result<()> {
let mut requests = queue
.queue_subscribe(subject_wildcard(), QUEUE_GROUP.to_owned())
.await
.context("subscribing to the request subject")?;
.context("subscribing to the request subject")?
.take_until(stop.clone());
tracing::info!(
subject = subject_wildcard(),
"swarm-stt: answering requests"
@ -207,7 +209,10 @@ async fn main() -> Result<()> {
}
});
}
bail!("the request subscription ended")
if stop.peek().is_none() {
bail!("the request subscription ended");
}
Ok(())
}
/// One agent's place among the requests in flight; dropping it frees the place.