232 lines
7.8 KiB
Rust
232 lines
7.8 KiB
Rust
//! The supervisor loop: load and unload the engine, restart it with a backoff, answer what arrives meanwhile.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
/// What the supervisor does after one engine session ended.
|
|
enum AfterSession {
|
|
Finish,
|
|
Unloaded,
|
|
Restart,
|
|
}
|
|
|
|
/// The supervisor's state across sessions.
|
|
struct SessionSupervisor {
|
|
config: WorkerConfig,
|
|
status: Arc<RwLock<WorkerStatus>>,
|
|
shutdown: watch::Receiver<bool>,
|
|
requests: mpsc::Receiver<GenerationCommand>,
|
|
control: mpsc::Receiver<Control>,
|
|
waiting: Vec<LoadReply>,
|
|
inbox: Option<GenerationCommand>,
|
|
unloaded: bool,
|
|
started_before: bool,
|
|
attempt: u32,
|
|
}
|
|
|
|
/// A lazy engine has not reported its context yet: `--max-context N` says what it will be.
|
|
async fn record_configured_context(config: &WorkerConfig, status: &RwLock<WorkerStatus>) {
|
|
if let Some(configured) = config
|
|
.args
|
|
.windows(2)
|
|
.find(|pair| pair[0] == "--max-context")
|
|
.and_then(|pair| pair[1].parse::<usize>().ok())
|
|
.filter(|context| *context > 0)
|
|
{
|
|
status.write().await.known_max_context = Some(configured);
|
|
}
|
|
}
|
|
|
|
pub async fn run_supervised(
|
|
config: WorkerConfig,
|
|
status: Arc<RwLock<WorkerStatus>>,
|
|
shutdown: watch::Receiver<bool>,
|
|
requests: mpsc::Receiver<GenerationCommand>,
|
|
control: mpsc::Receiver<Control>,
|
|
) {
|
|
if config.max_restarts > 3 {
|
|
crate::elog!("worker max_restarts must be between 0 and 3");
|
|
update(&status, WorkerState::Failed, None).await;
|
|
return;
|
|
}
|
|
record_configured_context(&config, &status).await;
|
|
let unloaded = config.lazy;
|
|
let mut supervisor = SessionSupervisor {
|
|
config,
|
|
status,
|
|
shutdown,
|
|
requests,
|
|
control,
|
|
waiting: Vec::new(),
|
|
inbox: None,
|
|
unloaded,
|
|
started_before: false,
|
|
attempt: 0,
|
|
};
|
|
supervisor.run().await;
|
|
}
|
|
|
|
impl SessionSupervisor {
|
|
async fn run(&mut self) {
|
|
loop {
|
|
if self.unloaded && self.wait_until_wanted().await {
|
|
return;
|
|
}
|
|
if self.load_refused().await {
|
|
continue;
|
|
}
|
|
self.started_before = true;
|
|
match self.run_one_session().await {
|
|
AfterSession::Finish => return,
|
|
AfterSession::Unloaded => {
|
|
self.unloaded = true;
|
|
continue;
|
|
}
|
|
AfterSession::Restart => {}
|
|
}
|
|
let delay = self.announce_restart().await;
|
|
if self.back_off(delay).await {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Sit unloaded until a load or a request needs the engine; `true` when the supervisor is shutting down.
|
|
async fn wait_until_wanted(&mut self) -> bool {
|
|
update(&self.status, WorkerState::Unloaded, None).await;
|
|
let wake = wait_unloaded(
|
|
&mut self.shutdown,
|
|
&mut self.requests,
|
|
&mut self.control,
|
|
&mut self.waiting,
|
|
)
|
|
.await;
|
|
match wake {
|
|
Wake::Shutdown => {
|
|
update(&self.status, WorkerState::Stopping, None).await;
|
|
return true;
|
|
}
|
|
Wake::Load => {}
|
|
Wake::Command(command) => self.inbox = Some(*command),
|
|
}
|
|
self.unloaded = false;
|
|
self.attempt = 0;
|
|
false
|
|
}
|
|
|
|
/// Answer the waiting loads and the request in the inbox with the failure, and go back to unloaded.
|
|
async fn fail_pending(&mut self, error: LoadError, message: String) {
|
|
fail_loads(&mut self.waiting, &error).await;
|
|
if let Some(command) = self.inbox.take() {
|
|
send_failure(command.result, message).await;
|
|
}
|
|
self.unloaded = true;
|
|
}
|
|
|
|
/// The gates before a start (not the first one of an eager engine); `true` when a load is refused.
|
|
async fn load_refused(&mut self) -> bool {
|
|
self.reload_refused().await || self.vision_refused().await
|
|
}
|
|
|
|
async fn reload_refused(&mut self) -> bool {
|
|
if !(self.started_before || self.config.lazy) {
|
|
return false;
|
|
}
|
|
let Err(error) = reload_gate(&self.config).await else {
|
|
return false;
|
|
};
|
|
let message = match &error {
|
|
LoadError::GpuBusy(m) | LoadError::Failed(m) => m.clone(),
|
|
};
|
|
crate::elog!("{message}");
|
|
self.fail_pending(error, message).await;
|
|
true
|
|
}
|
|
|
|
/// The image encoder first, as at a start: a GPU encoder takes its VRAM before the engine sizes its cache.
|
|
async fn vision_refused(&mut self) -> bool {
|
|
let Some(vision) = &self.config.vision else {
|
|
return false;
|
|
};
|
|
let Err(error) = vision.ensure_running().await else {
|
|
return false;
|
|
};
|
|
let message = error.to_string();
|
|
crate::elog!("{message}");
|
|
let error = LoadError::Failed(message.clone());
|
|
self.fail_pending(error, message).await;
|
|
true
|
|
}
|
|
|
|
async fn run_one_session(&mut self) -> AfterSession {
|
|
let inputs = SessionInputs {
|
|
shutdown: &mut self.shutdown,
|
|
requests: &mut self.requests,
|
|
control: &mut self.control,
|
|
inbox: &mut self.inbox,
|
|
waiting: &mut self.waiting,
|
|
};
|
|
let exit = run_session(&self.config, &self.status, inputs).await;
|
|
match exit {
|
|
SessionExit::Stopped => AfterSession::Finish,
|
|
SessionExit::StartupFailed => {
|
|
let error = LoadError::Failed("the engine failed to start".into());
|
|
fail_loads(&mut self.waiting, &error).await;
|
|
AfterSession::Finish
|
|
}
|
|
SessionExit::Unloaded => AfterSession::Unloaded,
|
|
SessionExit::RuntimeFailed if self.attempt == self.config.max_restarts => {
|
|
let error = LoadError::Failed("the engine failed".into());
|
|
fail_loads(&mut self.waiting, &error).await;
|
|
AfterSession::Finish
|
|
}
|
|
SessionExit::RuntimeFailed => AfterSession::Restart,
|
|
}
|
|
}
|
|
|
|
/// Mark the worker restarting, refuse what queued up, and return the backoff delay.
|
|
async fn announce_restart(&mut self) -> Duration {
|
|
update(&self.status, WorkerState::Restarting, None).await;
|
|
let delay = Duration::from_secs(2 << self.attempt);
|
|
crate::elog!(
|
|
"Strata engine restart {}/{} in {} seconds",
|
|
self.attempt + 1,
|
|
self.config.max_restarts,
|
|
delay.as_secs()
|
|
);
|
|
self.attempt += 1;
|
|
while let Ok(command) = self.requests.try_recv() {
|
|
send_failure(
|
|
command.result,
|
|
"worker failed; request was not replayed".to_owned(),
|
|
)
|
|
.await;
|
|
}
|
|
delay
|
|
}
|
|
|
|
/// Wait out the restart delay, refusing requests that arrive; `true` when the supervisor is shutting down.
|
|
async fn back_off(&mut self, delay: Duration) -> bool {
|
|
let backoff = tokio::time::sleep(delay);
|
|
tokio::pin!(backoff);
|
|
let mut requests_closed = self.requests.is_closed() && self.requests.is_empty();
|
|
loop {
|
|
tokio::select! {
|
|
biased;
|
|
_ = self.shutdown.changed() => {
|
|
update(&self.status, WorkerState::Stopping, None).await;
|
|
return true;
|
|
}
|
|
_ = &mut backoff => return false,
|
|
command = self.requests.recv(), if !requests_closed => {
|
|
match command {
|
|
Some(command) => send_failure(command.result,
|
|
"worker is restarting; request was not replayed".to_owned()).await,
|
|
None => requests_closed = true,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|