Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supervisor #3

Merged
merged 2 commits into from
Nov 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = { version = "4.4.6", features = ["derive"] }
futures = "0.3.28"
libc = "0.2.149"
tokio = { version = "1.33.0", features = ["full"] }
tokio-util = { version = "0.7.9", features = ["full"] }
66 changes: 66 additions & 0 deletions src/bin/supervisor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use clap::Parser;
use std::io::{self, Write};
use tokio::process::Command;
use tokio::signal::ctrl_c;
use tokio::time;
use tokio_util::sync::CancellationToken;

#[derive(Parser)]
struct Arguments {
#[arg(short, long)]
command: String,
#[arg(short, long, default_value = "60")]
interval: u64,
#[clap(last = true)]
arguments: Vec<String>,
}

#[tokio::main]
async fn main() {
let pid = std::process::id();
println!("{pid}");
let arguments = Arguments::parse();

let mut command = Command::new(arguments.command);
command.args(arguments.arguments);

let interval = time::interval(time::Duration::from_secs(arguments.interval));

let token = CancellationToken::new();
let k = tokio::spawn(run(command, interval, token.clone()));
let _ = ctrl_c().await;
token.cancel();
let _ = k.await;
}

fn kill_gracefully(child_id: i32) {
unsafe {
libc::kill(child_id, libc::SIGTERM);
}
}

async fn run(mut command: Command, mut interval: time::Interval, token: CancellationToken) {
loop {
tokio::select! {
_ = interval.tick() => {}
_ = token.cancelled() => { return }
}
println!("Starting");
let child = command.spawn().expect("Failed to execute command");
if let Some(child_id) = child.id() {
tokio::select! {
output = child.wait_with_output() => {
let outcome = output.expect("Failed to execute command");
io::stdout().write_all(&outcome.stdout).unwrap();
io::stderr().write_all(&outcome.stderr).unwrap();
println!("{:?}", outcome.status.code());
}
_ = token.cancelled() => {
println!("KILLING");
kill_gracefully(child_id as i32);
return
}
}
}
}
}