Skip to content

Commit a8c89a4

Browse files
committed
feat(sync): gracefully handle SIGTERMs
1 parent e2df5f9 commit a8c89a4

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

aw-sync/src/main.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ extern crate serde_json;
1515

1616
use std::error::Error;
1717
use std::path::PathBuf;
18+
use signal_hook::consts::signal::{SIGINT, SIGTERM};
19+
use signal_hook::iterator::Signals;
20+
use std::sync::mpsc;
21+
use std::thread;
22+
use std::time::Duration;
1823

1924
use chrono::{DateTime, Utc};
2025
use clap::{Parser, Subcommand};
@@ -207,16 +212,36 @@ fn main() -> Result<(), Box<dyn Error>> {
207212
}
208213

209214
fn daemon(client: &AwClient) -> Result<(), Box<dyn Error>> {
210-
loop {
215+
let (tx, rx) = mpsc::channel();
216+
217+
// Spawn a thread to handle signals
218+
let mut signals = Signals::new(&[SIGTERM, SIGINT])?;
219+
thread::spawn(move || {
220+
for _ in signals.forever() {
221+
let _ = tx.send(());
222+
}
223+
});
224+
225+
loop{
211226
if let Err(e) = daemon_sync_cycle(client) {
212227
error!("Error during sync cycle: {}", e);
213228
// Re-throw the error
214229
return Err(e);
215230
}
216231

217232
info!("Sync pass done, sleeping for 5 minutes");
218-
std::thread::sleep(std::time::Duration::from_secs(300));
233+
234+
// Wait for either the sleep duration or a signal
235+
match rx.recv_timeout(Duration::from_secs(300)) {
236+
Ok(_) | Err(mpsc::RecvTimeoutError::Disconnected) => {
237+
info!("Received termination signal, shutting down");
238+
break;
239+
}
240+
Err(mpsc::RecvTimeoutError::Timeout) => {}
241+
}
219242
}
243+
244+
Ok(())
220245
}
221246

222247
fn daemon_sync_cycle(client: &AwClient) -> Result<(), Box<dyn Error>> {

0 commit comments

Comments
 (0)