shell_compose/
dispatcher.rs

1use crate::{
2    CliCommand, ExecCommand, IpcClientError, IpcStream, Justfile, JustfileError, Message,
3    ProcStatus, Runner,
4};
5use chrono::{DateTime, Local, TimeZone};
6use job_scheduler_ng::{self as job_scheduler, JobScheduler};
7use log::{error, info};
8use serde::{Deserialize, Serialize};
9use std::collections::{BTreeMap, HashMap};
10use std::str::FromStr;
11use std::sync::{mpsc, Arc, Mutex};
12use std::thread;
13use std::time::Duration;
14use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System};
15use thiserror::Error;
16
17pub type JobId = u32;
18pub type Pid = u32;
19
20pub struct Dispatcher<'a> {
21    jobs: BTreeMap<JobId, JobInfo>,
22    last_job_id: JobId,
23    cronjobs: HashMap<JobId, job_scheduler::Uuid>,
24    procs: Arc<Mutex<Vec<Runner>>>,
25    scheduler: Arc<Mutex<JobScheduler<'a>>>,
26    system: System,
27    /// Sender channel for Runner threads
28    channel: mpsc::Sender<Pid>,
29}
30
31#[derive(Clone, Serialize, Deserialize, Debug)]
32pub struct JobInfo {
33    pub job_type: JobType,
34    pub args: Vec<String>,
35    pub entrypoint: Option<String>,
36    pub restart: RestartInfo,
37    // stats: #Runs, #Success, #Restarts
38}
39
40#[derive(Clone, Serialize, Deserialize, Debug)]
41pub enum JobType {
42    Shell,
43    Service(String),
44    Cron(String),
45}
46
47#[derive(Clone, Serialize, Deserialize, Debug)]
48pub struct RestartInfo {
49    pub policy: Restart,
50    /// Waiting time before restart in ms
51    pub wait_time: u64,
52}
53
54/// Restart policy
55#[derive(Clone, Serialize, Deserialize, Debug)]
56pub enum Restart {
57    Always,
58    OnFailure,
59    Never,
60}
61
62struct JobSpawnInfo<'a> {
63    job_id: JobId,
64    args: &'a [String],
65    restart_info: RestartInfo,
66}
67
68#[derive(Clone, Serialize, Deserialize, Debug)]
69pub struct Job {
70    pub id: JobId,
71    pub info: JobInfo,
72}
73
74#[derive(Error, Debug)]
75pub enum DispatcherError {
76    #[error(transparent)]
77    CliArgsError(#[from] clap::Error),
78    #[error("Failed to spawn process: {0}")]
79    ProcSpawnError(std::io::Error),
80    #[error("Failed to spawn process (timeout)")]
81    ProcSpawnTimeoutError,
82    #[error("Failed to terminate child process: {0}")]
83    KillError(std::io::Error),
84    #[error("Job {0} not found")]
85    JobNotFoundError(JobId),
86    #[error("Service `{0}` not found")]
87    ServiceNotFoundError(String),
88    #[error("Process exit code: {0}")]
89    ProcExitError(i32),
90    #[error("Empty command")]
91    EmptyProcCommandError,
92    #[error(transparent)]
93    JustfileError(#[from] JustfileError),
94    #[error("Communication protocol error")]
95    UnexpectedMessageError,
96    #[error(transparent)]
97    IpcClientError(#[from] IpcClientError),
98    #[error("Cron error: {0}")]
99    CronError(#[from] cron::error::Error),
100}
101
102impl Default for RestartInfo {
103    fn default() -> Self {
104        RestartInfo {
105            policy: Restart::OnFailure,
106            wait_time: 50,
107        }
108    }
109}
110
111impl JobInfo {
112    pub fn new_shell_job(args: Vec<String>) -> Self {
113        JobInfo {
114            job_type: JobType::Shell,
115            args,
116            entrypoint: None,
117            restart: RestartInfo {
118                policy: Restart::Never,
119                ..Default::default()
120            },
121        }
122    }
123    pub fn new_cron_job(cron: String, args: Vec<String>) -> Self {
124        JobInfo {
125            job_type: JobType::Cron(cron),
126            args,
127            entrypoint: None,
128            restart: RestartInfo {
129                policy: Restart::Never,
130                ..Default::default()
131            },
132        }
133    }
134    pub fn new_service(service: String) -> Self {
135        JobInfo {
136            job_type: JobType::Service(service.clone()),
137            args: vec!["just".to_string(), service], // TODO: exclude entrypoint
138            entrypoint: Some("just".to_string()),
139            restart: RestartInfo::default(),
140        }
141    }
142}
143
144impl Dispatcher<'_> {
145    pub fn create() -> Dispatcher<'static> {
146        let procs = Arc::new(Mutex::new(Vec::new()));
147        let scheduler = Arc::new(Mutex::new(JobScheduler::new()));
148
149        let scheduler_spawn = scheduler.clone();
150        let _handle = thread::spawn(move || cron_scheduler(scheduler_spawn));
151
152        let (send, recv) = mpsc::channel();
153        let send_spawn = send.clone();
154        let procs_spawn = procs.clone();
155        let _watcher = thread::spawn(move || child_watcher(procs_spawn, send_spawn, recv));
156
157        let system = System::new_with_specifics(
158            RefreshKind::new().with_processes(ProcessRefreshKind::new()),
159        );
160
161        Dispatcher {
162            jobs: BTreeMap::new(),
163            last_job_id: 0,
164            cronjobs: HashMap::new(),
165            procs,
166            scheduler,
167            system,
168            channel: send,
169        }
170    }
171    pub fn exec_command(&mut self, cmd: ExecCommand) -> Message {
172        info!("Executing `{cmd:?}`");
173        let res = match cmd {
174            ExecCommand::Run { args } => self.run(&args),
175            ExecCommand::Runat { at, args } => self.run_at(&at, &args),
176            ExecCommand::Start { service } => self.start(&service),
177            ExecCommand::Up { group } => self.up(&group),
178        };
179        match res {
180            Err(e) => {
181                error!("{e}");
182                Message::Err(format!("{e}"))
183            }
184            Ok(job_ids) => Message::JobsStarted(job_ids),
185        }
186    }
187    pub fn cli_command(&mut self, cmd: CliCommand, stream: &mut IpcStream) {
188        info!("Executing `{cmd:?}`");
189        let res = match cmd {
190            CliCommand::Stop { job_id } => self.stop(job_id),
191            CliCommand::Down { group } => self.down(&group),
192            CliCommand::Ps => self.ps(stream),
193            CliCommand::Jobs => self.jobs(stream),
194            CliCommand::Logs { job_or_service } => self.log(job_or_service, stream),
195            CliCommand::Exit => std::process::exit(0),
196        };
197        if let Err(e) = &res {
198            error!("{e}");
199        }
200        let _ = stream.send_message(&res.into());
201    }
202    fn add_job(&mut self, job: JobInfo) -> JobId {
203        self.last_job_id += 1;
204        self.jobs.insert(self.last_job_id, job);
205        self.last_job_id
206    }
207    fn spawn_info(&self, job_id: JobId) -> Result<JobSpawnInfo<'_>, DispatcherError> {
208        let job = self
209            .jobs
210            .get(&job_id)
211            .ok_or(DispatcherError::JobNotFoundError(job_id))?;
212        Ok(JobSpawnInfo {
213            job_id,
214            args: &job.args,
215            restart_info: job.restart.clone(),
216        })
217    }
218    /// Find service job
219    fn find_job(&self, service: &str) -> Option<JobId> {
220        self.jobs
221            .iter()
222            .find(|(_id, info)| matches!(&info.job_type, JobType::Service(name) if name == service))
223            .map(|(id, _info)| *id)
224    }
225    fn run(&mut self, args: &[String]) -> Result<Vec<JobId>, DispatcherError> {
226        let job_info = JobInfo::new_shell_job(args.to_vec());
227        let job_id = self.add_job(job_info);
228        self.spawn_job(job_id)?;
229        Ok(vec![job_id])
230    }
231    fn spawn_job(&mut self, job_id: JobId) -> Result<(), DispatcherError> {
232        let job = self.spawn_info(job_id)?;
233        let child = Runner::spawn(job.job_id, job.args, job.restart_info, self.channel.clone())?;
234        self.procs.lock().expect("lock").push(child);
235        // Wait for startup failure
236        thread::sleep(Duration::from_millis(10));
237        if let Some(child) = self.procs.lock().expect("lock").last() {
238            return match child.info.state {
239                ProcStatus::ExitErr(code) => Err(DispatcherError::ProcExitError(code)),
240                // ProcStatus::Unknown(e) => Err(DispatcherError::ProcSpawnError(e)),
241                _ => Ok(()),
242            };
243        }
244        Ok(())
245    }
246    /// Stop job
247    fn stop(&mut self, job_id: JobId) -> Result<(), DispatcherError> {
248        if let Some(uuid) = self.cronjobs.remove(&job_id) {
249            info!("Removing cron job {job_id}");
250            self.scheduler.lock().expect("lock").remove(uuid);
251        }
252        for child in self
253            .procs
254            .lock()
255            .expect("lock")
256            .iter_mut()
257            .filter(|child| child.info.job_id == job_id)
258        {
259            if child.is_running() {
260                child.user_terminated = true;
261                child.terminate().map_err(DispatcherError::KillError)?;
262            }
263        }
264        if self.jobs.remove(&job_id).is_some() {
265            Ok(())
266        } else {
267            Err(DispatcherError::JobNotFoundError(job_id))
268        }
269    }
270    /// Add cron job
271    fn run_at(&mut self, cron: &str, args: &[String]) -> Result<Vec<JobId>, DispatcherError> {
272        let job_info = JobInfo::new_cron_job(cron.to_string(), args.to_vec());
273        let restart_info = job_info.restart.clone();
274        let job_id = self.add_job(job_info);
275        let job_args = args.to_vec();
276        let procs = self.procs.clone();
277        let channel = self.channel.clone();
278        let uuid = self
279            .scheduler
280            .lock()
281            .expect("lock")
282            .add(job_scheduler::Job::new(cron.parse()?, move || {
283                let child = Runner::spawn(job_id, &job_args, restart_info.clone(), channel.clone())
284                    .unwrap();
285                procs.lock().expect("lock").push(child);
286            }));
287        self.cronjobs.insert(job_id, uuid);
288        Ok(vec![job_id])
289    }
290    /// Start service (just recipe)
291    fn start(&mut self, service: &str) -> Result<Vec<JobId>, DispatcherError> {
292        // Find existing job or add new
293        let job_id = self
294            .find_job(service)
295            .unwrap_or_else(|| self.add_job(JobInfo::new_service(service.to_string())));
296        // Check for existing process for this service
297        let running = self
298            .procs
299            .lock()
300            .expect("lock")
301            .iter_mut()
302            .any(|child| child.info.job_id == job_id && child.is_running());
303        if running {
304            Ok(vec![])
305        } else {
306            self.spawn_job(job_id)?;
307            Ok(vec![job_id])
308        }
309    }
310    /// Start service group (all just repipes in group)
311    fn up(&mut self, group: &str) -> Result<Vec<JobId>, DispatcherError> {
312        let mut job_ids = Vec::new();
313        let justfile = Justfile::parse()?;
314        let recipes = justfile.group_recipes(group);
315        for service in recipes {
316            let ids = self.start(&service)?;
317            job_ids.extend(ids);
318        }
319        Ok(job_ids)
320    }
321    /// Stop service group
322    fn down(&mut self, group: &str) -> Result<(), DispatcherError> {
323        let mut job_ids = Vec::new();
324        let justfile = Justfile::parse()?;
325        let recipes = justfile.group_recipes(group);
326        for service in recipes {
327            self.jobs
328                .iter()
329                .filter(|(_id, info)| matches!(&info.job_type, JobType::Service(name) if *name == service))
330                .for_each(|(id, _info)| job_ids.push(*id));
331        }
332        for job_id in job_ids {
333            self.stop(job_id)?;
334        }
335        Ok(())
336    }
337    /// Return info about running and finished processes
338    fn ps(&mut self, stream: &mut IpcStream) -> Result<(), DispatcherError> {
339        // Update system info
340        // For accurate CPU usage, a process needs to be refreshed twice
341        // https://docs.rs/sysinfo/latest/i686-pc-windows-msvc/sysinfo/struct.Process.html#method.cpu_usage
342        let ts = Local::now();
343        self.system.refresh_processes_specifics(
344            ProcessesToUpdate::All,
345            true,
346            ProcessRefreshKind::new().with_cpu(),
347        );
348        // Collect pids and child pids
349        let pids: Vec<sysinfo::Pid> = self
350            .procs
351            .lock()
352            .expect("lock")
353            .iter()
354            .flat_map(|proc| {
355                let parent_pid = sysinfo::Pid::from(proc.info.pid as usize);
356                self.system
357                    .processes()
358                    .iter()
359                    .filter(move |(_pid, process)| {
360                        process.parent().unwrap_or(0.into()) == parent_pid
361                    })
362                    .map(|(pid, _process)| *pid)
363                    .chain([parent_pid])
364            })
365            .collect();
366        std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL); // 200ms
367        let duration = (Local::now() - ts).num_milliseconds();
368        fn per_second(value: u64, ms: i64) -> u64 {
369            (value as f64 * 1000.0 / ms as f64) as u64
370        }
371        self.system.refresh_processes_specifics(
372            ProcessesToUpdate::Some(&pids),
373            true,
374            ProcessRefreshKind::new()
375                .with_cpu()
376                .with_disk_usage()
377                .with_memory(),
378        );
379
380        let mut proc_infos = Vec::new();
381        for child in &mut self.procs.lock().expect("lock").iter_mut().rev() {
382            let parent_pid = sysinfo::Pid::from(child.info.pid as usize);
383            // CPU usage has to be measured from just child processs
384            // For tasks spawning child processes, we should consider the whole process subtree!
385            let main_pid = if child.info.program() == "just" {
386                self.system
387                    .processes()
388                    .iter()
389                    .find(|(_pid, process)| {
390                        process.parent().unwrap_or(0.into()) == parent_pid
391                            && process.name() != "ctrl-c"
392                    })
393                    .map(|(pid, _process)| *pid)
394                    .unwrap_or(parent_pid)
395            } else {
396                parent_pid
397            };
398            if let Some(process) = self.system.process(main_pid) {
399                child.info.cpu = process.cpu_usage();
400                child.info.memory = process.memory();
401                child.info.virtual_memory = process.virtual_memory();
402                let disk = process.disk_usage();
403                child.info.total_written_bytes = disk.total_written_bytes;
404                child.info.written_bytes = per_second(disk.written_bytes, duration);
405                child.info.total_read_bytes = disk.total_read_bytes;
406                child.info.read_bytes = per_second(disk.read_bytes, duration);
407            } else {
408                child.info.cpu = 0.0;
409                child.info.memory = 0;
410                child.info.virtual_memory = 0;
411                child.info.written_bytes = 0;
412                child.info.read_bytes = 0;
413            }
414            let info = child.update_proc_state();
415            proc_infos.push(info.clone());
416        }
417        stream.send_message(&Message::PsInfo(proc_infos))?;
418        Ok(())
419    }
420    /// Return info about jobs
421    fn jobs(&mut self, stream: &mut IpcStream) -> Result<(), DispatcherError> {
422        let mut job_infos = Vec::new();
423        for (id, info) in self.jobs.iter().rev() {
424            job_infos.push(Job {
425                id: *id,
426                info: info.clone(),
427            });
428        }
429        stream.send_message(&Message::JobInfo(job_infos))?;
430        Ok(())
431    }
432    /// Return log lines
433    fn log(
434        &mut self,
435        job_or_service: Option<String>,
436        stream: &mut IpcStream,
437    ) -> Result<(), DispatcherError> {
438        let mut job_id_filter = None;
439        if let Some(job_or_service) = job_or_service {
440            if let Ok(job_id) = JobId::from_str(&job_or_service) {
441                if self.jobs.contains_key(&job_id) {
442                    job_id_filter = Some(job_id);
443                } else {
444                    return Err(DispatcherError::JobNotFoundError(job_id));
445                }
446            } else {
447                job_id_filter = Some(
448                    self.find_job(&job_or_service)
449                        .ok_or(DispatcherError::ServiceNotFoundError(job_or_service))?,
450                );
451            }
452        }
453
454        let mut last_seen_ts: HashMap<Pid, DateTime<Local>> = HashMap::new();
455        'logwait: loop {
456            // Collect log entries from child proceses
457            let mut log_lines = Vec::new();
458            for child in self.procs.lock().expect("lock").iter_mut() {
459                if let Ok(output) = child.output.lock() {
460                    let last_seen = last_seen_ts
461                        .entry(child.proc.id())
462                        .or_insert(Local.timestamp_millis_opt(0).single().expect("ts"));
463                    for entry in output.lines_since(last_seen) {
464                        if let Some(job_id) = job_id_filter {
465                            if entry.job_id != job_id {
466                                continue;
467                            }
468                        }
469                        log_lines.push(entry.clone());
470                    }
471                }
472            }
473
474            if log_lines.is_empty() {
475                // Exit when client is disconnected
476                stream.alive()?;
477            } else {
478                log_lines.sort_by_key(|entry| entry.ts);
479                for entry in log_lines {
480                    if stream.send_message(&Message::LogLine(entry)).is_err() {
481                        info!("Aborting log command (stream error)");
482                        break 'logwait;
483                    }
484                }
485            }
486            // Wait for new output
487            thread::sleep(Duration::from_millis(100));
488        }
489        Ok(())
490    }
491}
492
493fn cron_scheduler(scheduler: Arc<Mutex<JobScheduler<'static>>>) {
494    loop {
495        let wait_time = if let Ok(mut scheduler) = scheduler.lock() {
496            scheduler.tick();
497            scheduler.time_till_next_job()
498        } else {
499            Duration::from_millis(50)
500        };
501        std::thread::sleep(wait_time);
502    }
503}
504
505// sender: Sender channel for Runner threads
506// recv: Watcher receiver channel
507fn child_watcher(
508    procs: Arc<Mutex<Vec<Runner>>>,
509    sender: mpsc::Sender<Pid>,
510    recv: mpsc::Receiver<Pid>,
511) {
512    loop {
513        // PID of terminated process sent from output_listener
514        let pid = recv.recv().expect("recv");
515        let ts = Local::now();
516        let mut respawn_child = None;
517        if let Some(child) = procs
518            .lock()
519            .expect("lock")
520            .iter_mut()
521            .find(|p| p.info.pid == pid)
522        {
523            // https://doc.rust-lang.org/std/process/struct.Child.html#warning
524            let exit_code = child.proc.wait().ok().and_then(|st| st.code());
525            let _ = child.update_proc_state();
526            child.info.end = Some(ts);
527            if let Some(code) = exit_code {
528                info!(target: &format!("{pid}"), "Process terminated with exit code {code}");
529            } else {
530                info!(target: &format!("{pid}"), "Process terminated");
531            }
532            let respawn = !child.user_terminated
533                && match child.restart_info.policy {
534                    Restart::Always => true,
535                    Restart::OnFailure => {
536                        matches!(child.info.state, ProcStatus::ExitErr(code) if code > 0)
537                    }
538                    Restart::Never => false,
539                };
540            if respawn {
541                respawn_child = Some((child.info.clone(), child.restart_info.clone()));
542            }
543        } else {
544            info!(target: &format!("{pid}"), "(Unknown) process terminated");
545        }
546        if let Some((child_info, restart_info)) = respawn_child {
547            thread::sleep(Duration::from_millis(restart_info.wait_time));
548            let result = Runner::spawn(
549                child_info.job_id,
550                &child_info.cmd_args,
551                restart_info,
552                sender.clone(),
553            );
554            match result {
555                Ok(child) => procs.lock().expect("lock").push(child),
556                Err(e) => error!("Error trying to respawn failed process: {e}"),
557            }
558        }
559    }
560}