agentmux_srv/bootstrap/
shutdown.rs1use super::*;
7
8pub fn emit_estart(ws_port: u16, web_port: u16, version: &str, build_time: &str, instance_id: &str) {
13 let supervised =
17 std::env::var(agentmux_common::srv_stderr::SUPERVISOR_PREPARES_ENV).as_deref() == Ok("1");
18 let pending_migrations = if supervised {
19 0
20 } else {
21 crate::boot_timing::time("estart_pending_count", || migrations::count_pending_migrations(&base::get_mux_data_dir()))
22 };
23 eprintln!(
24 "{}",
25 agentmux_common::srv_stderr::estart_line(&agentmux_common::srv_stderr::Estart {
26 ws_endpoint: format!("127.0.0.1:{ws_port}"),
27 web_endpoint: format!("127.0.0.1:{web_port}"),
28 version: version.to_string(),
29 build_time: build_time.to_string(),
30 instance_id: instance_id.to_string(),
31 pending_migrations,
32 })
33 );
34}
35
36pub fn install_shutdown_handlers(watch_stdin: bool) -> tokio_util::sync::CancellationToken {
41 let stdin_token = tokio_util::sync::CancellationToken::new();
45 let stdin_shutdown = stdin_token.clone();
46 if watch_stdin {
47 std::thread::spawn(move || {
48 use std::io::Read;
49 let mut stdin = std::io::stdin().lock();
50 let mut buf = [0u8; 1024];
51 loop {
52 match stdin.read(&mut buf) {
53 Ok(0) => {
54 eprintln_lossy!("stdin closed, shutting down");
55 stdin_shutdown.cancel();
56 break;
57 }
58 Ok(_) => {}
59 Err(e) => {
60 eprintln_lossy!("stdin read error: {}, shutting down", e);
61 stdin_shutdown.cancel();
62 break;
63 }
64 }
65 }
66 });
67 }
68
69 let signal_token = stdin_token.clone();
71 tokio::spawn(async move {
72 let ctrl_c = tokio::signal::ctrl_c();
73 #[cfg(unix)]
74 {
75 let mut sigterm =
76 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).unwrap();
77 tokio::select! {
78 _ = ctrl_c => {
79 tracing::info!("received SIGINT, shutting down");
80 }
81 _ = sigterm.recv() => {
82 tracing::info!("received SIGTERM, shutting down");
83 }
84 }
85 }
86 #[cfg(not(unix))]
87 {
88 ctrl_c.await.ok();
89 tracing::info!("received Ctrl+C, shutting down");
90 }
91 signal_token.cancel();
92 });
93
94 stdin_token
95}
96
97pub fn spawn_wal_checkpoint_loop(
103 token: tokio_util::sync::CancellationToken,
104 wal_mstore: Arc<Store>,
105 wal_filestore: Arc<FileStore>,
106) {
107 tokio::spawn(async move {
108 const INTERVAL: std::time::Duration = std::time::Duration::from_secs(30 * 60);
109 loop {
110 tokio::select! {
111 _ = tokio::time::sleep(INTERVAL) => {}
112 _ = token.cancelled() => break,
113 }
114 if let Err(e) = wal_mstore.checkpoint() {
115 tracing::warn!(error = %e, "wal_checkpoint(TRUNCATE) on objects.db failed");
116 } else {
117 tracing::debug!("wal_checkpoint(TRUNCATE): objects.db ok");
118 }
119 if let Err(e) = wal_filestore.checkpoint() {
120 tracing::warn!(error = %e, "wal_checkpoint(TRUNCATE) on filestore.db failed");
121 } else {
122 tracing::debug!("wal_checkpoint(TRUNCATE): filestore.db ok");
123 }
124 }
125 });
126}
127
128pub fn spawn_global_transcripts_truncate_loop(token: tokio_util::sync::CancellationToken, store: Option<Arc<FileStore>>) {
144 use crate::backend::transcript::{framer, kinds};
145 let Some(store) = store else { return };
146 let Some(mut owner) = crate::backend::storage::filestore::TruncateOwner::for_store(&store) else { return };
147 let Some(dir) = store.path().and_then(|p| p.parent()).map(|p| p.to_path_buf()) else { return };
148 tokio::spawn(async move {
149 const TRUNCATE_EVERY: std::time::Duration = std::time::Duration::from_secs(30 * 60);
150 let mut wait = std::time::Duration::from_secs(2 * 60);
151 let mut last_truncate: Option<std::time::Instant> = None;
152 let skip = Arc::new(std::sync::Mutex::new(std::collections::HashSet::new()));
153 let mut last_waiting: Option<String> = None;
154 loop {
155 tokio::select! {
156 _ = tokio::time::sleep(wait) => {}
157 _ = framer::woken() => {
160 tokio::select! {
161 _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {}
162 _ = token.cancelled() => break,
163 }
164 }
165 _ = token.cancelled() => break,
166 }
167 wait = std::time::Duration::from_secs(60);
168 if owner.is_owner() && last_truncate.is_none_or(|t| t.elapsed() >= TRUNCATE_EVERY) {
169 last_truncate = Some(std::time::Instant::now());
170 let store = Arc::clone(&store);
171 match tokio::task::spawn_blocking(move || store.checkpoint_truncate_apart()).await {
172 Ok(Ok(true)) => tracing::debug!("wal_checkpoint(TRUNCATE): global transcripts ok"),
173 Ok(Ok(false)) => tracing::debug!("wal_checkpoint(TRUNCATE): global transcripts busy; the next pass finishes"),
174 Ok(Err(e)) => tracing::warn!(error = %e, "wal_checkpoint(TRUNCATE) on the global transcript store failed"),
175 Err(e) => tracing::warn!(error = %e, "global transcript store truncate task failed"),
176 }
177 }
178 if owner.is_owner() {
183 let store = Arc::clone(&store);
184 match tokio::task::spawn_blocking(move || store.reclaim_free_pages()).await {
185 Ok(Ok(pages)) if pages > 0 => tracing::info!(pages, "history store: gave freed pages back"),
186 Ok(Err(e)) => tracing::warn!(error = %e, "history store: giving freed pages back failed"),
187 _ => {}
188 }
189 }
190 let mut kinds_left = false;
194 if owner.is_owner() {
195 let store = Arc::clone(&store);
196 match tokio::task::spawn_blocking(move || kinds::step(&store, kinds::STEP_BYTES)).await {
197 Ok(report) => kinds_left = !report.done,
198 Err(e) => tracing::warn!(error = %e, "history kinds: the counting task failed"),
199 }
200 }
201 if !framer::enabled() {
202 if kinds_left {
203 wait = std::time::Duration::from_secs(5);
204 }
205 continue;
206 }
207 let (store, dir, skip) = (Arc::clone(&store), dir.clone(), Arc::clone(&skip));
208 let pass = tokio::task::spawn_blocking(move || {
209 let mut skip = skip.lock().unwrap_or_else(|e| e.into_inner());
210 framer::pass(&store, &dir, framer::PASS_FRAMES, &mut skip, agentmux_common::time::now_ms())
211 })
212 .await;
213 match pass {
214 Ok(Ok(report)) => {
215 framer::note_pass(report.frames, report.done);
216 if report.waiting != last_waiting {
217 if let Some(who) = &report.waiting {
218 tracing::info!(who = %who, "framer: waiting");
219 }
220 last_waiting = report.waiting.clone();
221 }
222 if report.frames > 0 {
223 tracing::info!(
224 frames = report.frames,
225 codec2 = report.codec2,
226 raw_bytes = report.raw_bytes,
227 stored_bytes = report.stored_bytes,
228 skipped = report.skipped,
229 "framer: compressed"
230 );
231 }
232 if (!report.done && report.waiting.is_none()) || kinds_left {
233 wait = std::time::Duration::from_secs(5);
234 }
235 }
236 Ok(Err(e)) => framer::note_pass_failed(&e),
237 Err(e) => tracing::warn!(error = %e, "framer: pass task failed"),
238 }
239 }
240 });
241}