1use std::collections::{BTreeMap, BTreeSet, HashMap};
10use std::hash::{DefaultHasher, Hash as _, Hasher as _};
11use std::path::PathBuf;
12use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
13use std::sync::{Arc, Mutex as StdMutex, PoisonError};
14use std::time::{Duration, Instant};
15
16use schedr_model::runner::{
17 AgentMessage, ErrorSummary, OutputStream, RunnerMessage, RunnerMode, TaskRequest,
18 WatchersRequest,
19};
20use schedr_model::task::{SensorMode, TaskKind};
21use schedr_proto::pb;
22use tokio::io::AsyncWriteExt as _;
23use tokio::sync::{Mutex, Notify, mpsc, oneshot, watch};
24
25use crate::attempt::{Ran, WorkerSetup};
26use crate::channel::{read_message, write_message};
27use crate::handles::{AttemptHandles, HandleError};
28use crate::launch::{
29 LaunchError, PythonTask, connection_answer, secret_answer, start_runner, unless_stopped,
30};
31use crate::mask::{Mask, MaskSet, MaskStream};
32use crate::metrics::{CodeLabels, WatcherMetrics};
33use crate::process::{OsProcess, ProcessSpec};
34use crate::secrets::AttemptSecrets;
35use crate::status::{StopReason, Termination};
36use crate::supervise::{Limits, Process, Signal, Stops, Supervised};
37
38const FAILED_EXIT_CODE: i32 = 1;
40
41const TERMINATED: i32 = 15;
43
44const KILLED: i32 = 9;
46
47#[cfg(test)]
48mod tests;
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct FoundEvent {
53 pub key: String,
55 pub data: serde_json::Value,
57 pub at: Option<jiff::Timestamp>,
59}
60
61#[derive(Clone)]
63pub struct EventSink {
64 pub batched: bool,
66 pub found: Arc<dyn Fn(FoundEvent) -> oneshot::Receiver<()> + Send + Sync>,
68 pub poked: Arc<dyn Fn(Option<String>) + Send + Sync>,
70}
71
72impl std::fmt::Debug for EventSink {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 f.write_str("EventSink")
75 }
76}
77
78impl PartialEq for EventSink {
79 fn eq(&self, other: &Self) -> bool {
80 Arc::ptr_eq(&self.found, &other.found)
81 }
82}
83
84#[derive(Debug, Clone, Default)]
86pub struct WatcherHosts {
87 hosts: Arc<Mutex<BTreeMap<Vec<String>, Arc<Host>>>>,
88 next_watcher: Arc<AtomicU64>,
89 code_sets: Arc<StdMutex<BTreeSet<Vec<String>>>>,
91 code: Arc<StdMutex<Option<watch::Sender<Copies>>>>,
93 watching: Arc<AtomicBool>,
95 metrics: WatcherMetrics,
96 lost: Arc<StdMutex<BTreeMap<Vec<String>, u64>>>,
98 reports: Arc<StdMutex<Vec<pb::WatcherHost>>>,
100}
101
102#[derive(Debug, Default, Clone, Copy)]
104struct HostStats {
105 threads: u32,
106 tied_threads: u32,
107 thread_stops: u64,
108}
109
110impl HostStats {
111 fn heard(
112 stats: &StdMutex<Self>,
113 metrics: &WatcherMetrics,
114 (threads, tied_threads, thread_stops, loop_lag_ms): (u32, u32, u64, u64),
115 ) {
116 let mut stats = stats.lock().unwrap_or_else(PoisonError::into_inner);
117 metrics
118 .thread_stops
119 .inc_by(thread_stops.saturating_sub(stats.thread_stops));
120 *stats = Self {
121 threads,
122 tied_threads: tied_threads.min(threads),
124 thread_stops: thread_stops.max(stats.thread_stops),
125 };
126 #[allow(clippy::cast_precision_loss)] metrics.loop_lag.observe(loop_lag_ms as f64 / 1000.0);
128 }
129}
130
131fn code_of(sys_path: &[String]) -> String {
133 let names: Vec<String> = sys_path
134 .iter()
135 .filter_map(|dir| {
136 let name = std::path::Path::new(dir).file_name()?;
137 Some(name.to_string_lossy().into_owned())
138 })
139 .collect();
140 names.join(",")
141}
142
143#[derive(Debug, Clone)]
145struct Blamed {
146 watcher: u64,
147 stack: Option<String>,
149}
150
151#[derive(Debug, Default)]
153struct Going {
154 blamed: Option<Blamed>,
155 why: Option<String>,
157 dead: bool,
159 retired: bool,
161 names: BTreeMap<u64, String>,
163}
164
165type Copies = BTreeMap<String, PathBuf>;
166
167type Routes = Arc<StdMutex<HashMap<u64, mpsc::Sender<RunnerMessage>>>>;
168
169pub const ROUTE_MESSAGES: usize = 16;
173
174#[derive(Debug)]
176struct Host {
177 pid: i32,
178 outbox: mpsc::UnboundedSender<AgentMessage>,
179 routes: Routes,
180 stop: Arc<Notify>,
181 ended: watch::Receiver<Option<Termination>>,
182 mask: Arc<MaskSet>,
185 going: Arc<StdMutex<Going>>,
186 stats: Arc<StdMutex<HostStats>>,
187}
188
189impl Host {
190 async fn start(
192 setup: &WorkerSetup,
193 sys_path: &[String],
194 hosts: &WatcherHosts,
195 ) -> Result<Self, LaunchError> {
196 let mask = Arc::new(MaskSet::new(0));
198 let spec = host_spec(setup, sys_path, Mask(Some(Arc::clone(&mask))));
199 let runner = start_runner(&spec, RunnerMode::Watchers, |_| {}).await?;
200 let pid = runner.process.id();
201 let (reader, mut writer) = runner.stream.into_split();
202 let (outbox, mut outgoing) = mpsc::unbounded_channel::<AgentMessage>();
203 let _ = outbox.send(AgentMessage::Watchers(WatchersRequest {
204 sys_path: sys_path.to_vec(),
205 block_limit_ms: millis(setup.timeouts.watcher_block_limit),
206 import_limit_ms: millis(setup.timeouts.watcher_import_limit),
207 poke_overruns: setup.timeouts.watcher_poke_overruns,
208 }));
209 let stop = Arc::new(Notify::new());
210 let routes = Routes::default();
211 let writing = tokio::spawn(async move {
212 while let Some(message) = outgoing.recv().await {
213 if write_message(&mut writer, &message).await.is_err() {
214 return;
215 }
216 }
217 });
218 let going = Arc::new(StdMutex::new(Going::default()));
219 let stats = Arc::new(StdMutex::new(HostStats::default()));
220 let silence = setup
222 .timeouts
223 .watcher_block_limit
224 .max(setup.timeouts.watcher_import_limit)
225 * 2;
226 let reading = tokio::spawn(read_host(
227 reader,
228 Arc::clone(&routes),
229 Arc::clone(&stop),
230 Arc::clone(&going),
231 (silence, pid, Arc::clone(&mask)),
232 (Arc::clone(&stats), hosts.metrics.clone()),
233 ));
234 let (ended_sender, ended) = watch::channel(None);
235 let watch_over = HostEnd {
236 stopping: Arc::clone(&stop),
237 routes: Arc::clone(&routes),
238 ended: ended_sender,
239 drain: spec.output_drain,
240 going: Arc::clone(&going),
241 sys_path: sys_path.to_vec(),
242 hosts: hosts.clone(),
243 };
244 tokio::spawn(watch_over.run(runner.process, reading, writing));
245 Ok(Self {
246 pid,
247 outbox,
248 routes,
249 stop,
250 ended,
251 mask,
252 going,
253 stats,
254 })
255 }
256
257 fn alive(&self) -> bool {
258 self.ended.borrow().is_none()
259 }
260
261 fn kill_for(&self, watcher: u64) {
263 let dead = self
264 .going
265 .lock()
266 .unwrap_or_else(PoisonError::into_inner)
267 .dead;
268 if !dead {
269 blame(&self.going, watcher, None);
270 }
271 self.stop.notify_one();
272 }
273
274 fn named(&self, watcher: u64, request: &TaskRequest) {
276 self.going
277 .lock()
278 .unwrap_or_else(PoisonError::into_inner)
279 .names
280 .insert(watcher, format!("{}.{}", request.dag_id, request.task.id));
281 }
282
283 fn unnamed(&self, watcher: u64) {
285 if self.alive() {
286 self.going
287 .lock()
288 .unwrap_or_else(PoisonError::into_inner)
289 .names
290 .remove(&watcher);
291 }
292 }
293
294 fn names(&self) -> String {
296 let going = self.going.lock().unwrap_or_else(PoisonError::into_inner);
297 let names: BTreeSet<&str> = going.names.values().map(String::as_str).collect();
298 names.into_iter().collect::<Vec<_>>().join(", ")
299 }
300
301 fn going(&self) -> (Option<Blamed>, Option<String>) {
302 let going = self.going.lock().unwrap_or_else(PoisonError::into_inner);
303 (going.blamed.clone(), going.why.clone())
304 }
305}
306
307async fn read_host(
310 mut reader: tokio::net::unix::OwnedReadHalf,
311 routes: Routes,
312 stop: Arc<Notify>,
313 going: Arc<StdMutex<Going>>,
314 (silence, pid, mask): (Duration, i32, Arc<MaskSet>),
315 (stats, metrics): (Arc<StdMutex<HostStats>>, WatcherMetrics),
316) {
317 loop {
318 let read = read_message::<_, RunnerMessage>(&mut reader);
319 let Ok(read) = tokio::time::timeout(silence, read).await else {
320 tracing::warn!(pid, "a watcher host stopped answering: killing it");
321 set_why(&going, format!("its host didn't answer for {silence:?}"));
322 stop.notify_one();
323 return;
324 };
325 match read {
326 Ok(RunnerMessage::WatcherMessage { watcher, message }) => {
327 if matches!(*message, RunnerMessage::WatcherStuck) {
328 if is_on_it(&routes, watcher) {
329 blame(&going, watcher, None);
330 }
331 continue;
332 }
333 let route = routes
334 .lock()
335 .unwrap_or_else(PoisonError::into_inner)
336 .get(&watcher)
337 .cloned();
338 if let Some(route) = route
341 && tokio::time::timeout(silence, route.send(*message))
342 .await
343 .is_err()
344 {
345 tracing::warn!(pid, watcher, "a wait step's log isn't being written");
346 set_why(
347 &going,
348 format!("a log on its host wasn't written for {silence:?}"),
349 );
350 stop.notify_one();
351 return;
352 }
353 }
354 Ok(RunnerMessage::HostAlive {
355 threads,
356 tied_threads,
357 thread_stops,
358 loop_lag_ms,
359 }) => HostStats::heard(
360 &stats,
361 &metrics,
362 (threads, tied_threads, thread_stops, loop_lag_ms),
363 ),
364 Ok(RunnerMessage::LoopBlocked { watcher, stack }) => {
365 tracing::warn!(pid, ?watcher, "a watcher blocked its host's loop");
366 let stack = mask.mask_text(&stack);
368 match watcher.filter(|watcher| is_on_it(&routes, *watcher)) {
370 Some(watcher) => blame(&going, watcher, Some(stack)),
371 None => set_why(
372 &going,
373 format!("its host's event loop was held by no wait step:\n{stack}"),
374 ),
375 }
376 stop.notify_one();
378 }
379 Ok(other) => {
380 tracing::warn!(?other, "a watcher host sent something unexpected");
381 }
382 Err(error) => {
383 let retired = going.lock().unwrap_or_else(PoisonError::into_inner).retired;
384 if retired {
385 tracing::debug!(%error, pid, "a watcher host with no wait step left ended");
387 } else {
388 tracing::warn!(%error, pid, "a watcher host's channel ended");
389 }
390 stop.notify_one();
391 return;
392 }
393 }
394 }
395}
396
397fn is_on_it(routes: &Routes, watcher: u64) -> bool {
398 routes
399 .lock()
400 .unwrap_or_else(PoisonError::into_inner)
401 .contains_key(&watcher)
402}
403
404fn retire(going: &StdMutex<Going>) {
408 let mut going = going.lock().unwrap_or_else(PoisonError::into_inner);
409 going.retired = going.blamed.is_none() && going.why.is_none() && !going.dead;
410}
411
412fn blame(going: &StdMutex<Going>, watcher: u64, stack: Option<String>) {
414 going
415 .lock()
416 .unwrap_or_else(PoisonError::into_inner)
417 .blamed
418 .get_or_insert(Blamed { watcher, stack });
419}
420
421fn set_why(going: &StdMutex<Going>, why: String) {
422 going
423 .lock()
424 .unwrap_or_else(PoisonError::into_inner)
425 .why
426 .get_or_insert(why);
427}
428
429fn millis(duration: Duration) -> u64 {
430 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
431}
432
433struct HostEnd {
435 stopping: Arc<Notify>,
436 routes: Routes,
437 ended: watch::Sender<Option<Termination>>,
438 drain: Duration,
439 going: Arc<StdMutex<Going>>,
440 sys_path: Vec<String>,
441 hosts: WatcherHosts,
442}
443
444impl HostEnd {
445 fn count(&self) {
448 let blamed = self
449 .going
450 .lock()
451 .unwrap_or_else(PoisonError::into_inner)
452 .blamed
453 .is_some();
454 let on_it = !self
455 .routes
456 .lock()
457 .unwrap_or_else(PoisonError::into_inner)
458 .is_empty();
459 if blamed {
460 self.hosts.metrics.blocked_kills.inc();
461 } else if on_it {
462 self.hosts.host_lost(&self.sys_path);
463 }
464 }
465
466 async fn run(
467 self,
468 mut process: OsProcess,
469 reading: tokio::task::JoinHandle<()>,
470 writing: tokio::task::JoinHandle<()>,
471 ) {
472 let termination = tokio::select! {
473 biased;
474 () = self.stopping.notified() => {
475 let _ = process.signal(Signal::Kill);
476 process.wait().await
477 }
478 termination = process.wait() => termination,
479 };
480 self.going
481 .lock()
482 .unwrap_or_else(PoisonError::into_inner)
483 .dead = true;
484 let _ = process.signal(Signal::Kill);
486 let _ = tokio::time::timeout(self.drain, process.output()).await;
487 let mut reading = reading;
489 if tokio::time::timeout(self.drain, &mut reading)
490 .await
491 .is_err()
492 {
493 reading.abort();
494 }
495 writing.abort();
496 self.count();
497 let _ = self
498 .ended
499 .send(Some(termination.unwrap_or(Termination::Unknown)));
500 self.routes
501 .lock()
502 .unwrap_or_else(PoisonError::into_inner)
503 .clear();
504 }
505}
506
507fn host_spec(setup: &WorkerSetup, sys_path: &[String], mask: Mask) -> ProcessSpec {
510 let mut hasher = DefaultHasher::new();
511 sys_path.hash(&mut hasher);
512 ProcessSpec {
513 program: setup.python.clone(),
514 args: vec![
515 "-P".to_owned(),
517 "-X".to_owned(),
520 "thread_inherit_context=1".to_owned(),
521 "-m".to_owned(),
522 "schedr.runner".to_owned(),
523 "watchers".to_owned(),
524 ],
525 env: setup
526 .agent_env
527 .iter()
528 .filter(|(name, _)| crate::env::is_allowed(name) || setup.pass_env.contains(name))
529 .map(|(k, v)| (k.clone(), v.clone()))
530 .collect(),
531 working_dir: setup.log_dir.clone(),
532 log_file: setup
533 .log_dir
534 .join(format!("watchers-{:016x}.log", hasher.finish())),
535 max_output_size: 64 * 1024,
536 mask,
537 start_timeout: setup.timeouts.runner_start,
538 output_drain: setup.timeouts.output_drain,
539 }
540}
541
542struct Entered {
544 hosts: WatcherHosts,
545 host: Arc<Host>,
546 watcher: u64,
547 messages: mpsc::Receiver<RunnerMessage>,
548 grace: Duration,
550 left: bool,
551}
552
553impl WatcherHosts {
554 #[must_use]
556 pub fn with_metrics(metrics: WatcherMetrics) -> Self {
557 Self {
558 metrics,
559 ..Self::default()
560 }
561 }
562
563 async fn enter(
565 &self,
566 setup: &WorkerSetup,
567 sys_path: &[String],
568 grace: Duration,
569 ) -> Result<Entered, LaunchError> {
570 self.watch_hosts(setup);
571 let mut hosts = self.hosts.lock().await;
572 let running = hosts.get(sys_path).filter(|host| host.alive()).cloned();
573 let host = if let Some(host) = running {
574 host
575 } else {
576 self.code_set(sys_path, true);
578 let host = match Host::start(setup, sys_path, self).await {
579 Ok(host) => Arc::new(host),
580 Err(error) => {
581 self.code_set(sys_path, false);
582 return Err(error);
583 }
584 };
585 hosts.insert(sys_path.to_vec(), Arc::clone(&host));
586 host
587 };
588 let watcher = self.next_watcher.fetch_add(1, Ordering::Relaxed);
589 let (route, messages) = mpsc::channel(setup.timeouts.watcher_log_backlog.max(1));
590 host.routes
591 .lock()
592 .unwrap_or_else(PoisonError::into_inner)
593 .insert(watcher, route);
594 Ok(Entered {
595 hosts: self.clone(),
596 host,
597 watcher,
598 messages,
599 grace,
600 left: false,
601 })
602 }
603
604 fn watch_hosts(&self, setup: &WorkerSetup) {
608 if self.watching.swap(true, Ordering::SeqCst) {
609 return;
610 }
611 let hosts = self.clone();
612 let watch = setup.memory.clone();
613 let budget = setup.timeouts.watcher_memory_budget;
614 tokio::spawn(async move {
615 let mut tick = tokio::time::interval(watch.interval);
616 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
617 loop {
618 tick.tick().await;
619 let running: Vec<(Vec<String>, Arc<Host>)> = hosts
620 .hosts
621 .lock()
622 .await
623 .iter()
624 .filter(|(_, host)| host.alive())
625 .map(|(code, host)| (code.clone(), Arc::clone(host)))
626 .collect();
627 let root = watch.proc_root.clone();
628 let pids: Vec<i32> = running.iter().map(|(_, host)| host.pid).collect();
629 let Ok(sizes) = tokio::task::spawn_blocking(move || {
630 pids.iter()
631 .map(|pid| crate::memory::group_memory(&root, *pid, true).unwrap_or(0))
632 .collect::<Vec<u64>>()
633 })
634 .await
635 else {
636 continue;
637 };
638 hosts.looked_at(&running, &sizes);
639 let used: u64 = sizes.iter().sum();
640 let largest = sizes.iter().enumerate().max_by_key(|(_, size)| **size);
641 if used > budget
642 && let Some((index, _)) = largest
643 {
644 let host = &running[index].1;
645 tracing::warn!(pid = host.pid, used, budget, "killing a watcher host");
646 set_why(
647 &host.going,
648 format!(
649 "its host was killed: wait step hosts use {}, over `[watchers] \
650 memory_budget` of {}",
651 crate::memory::show_size(used),
652 crate::memory::show_size(budget),
653 ),
654 );
655 host.stop.notify_one();
656 }
657 }
658 });
659 }
660
661 fn looked_at(&self, running: &[(Vec<String>, Arc<Host>)], sizes: &[u64]) {
664 let mut lost = self
665 .lost
666 .lock()
667 .unwrap_or_else(PoisonError::into_inner)
668 .clone();
669 let (mut tied, mut untied) = (0_u64, 0_u64);
670 let mut reports = Vec::new();
671 for ((code, host), memory) in running.iter().zip(sizes) {
672 let stats = *host.stats.lock().unwrap_or_else(PoisonError::into_inner);
673 tied += u64::from(stats.tied_threads);
674 untied += u64::from(stats.threads - stats.tied_threads);
675 let wait_steps = host
676 .routes
677 .lock()
678 .unwrap_or_else(PoisonError::into_inner)
679 .len();
680 reports.push(pb::WatcherHost {
681 code: code_of(code),
682 wait_steps: u32::try_from(wait_steps).unwrap_or(u32::MAX),
683 threads: stats.threads,
684 tied_threads: stats.tied_threads,
685 memory_bytes: *memory,
686 hosts_lost: lost.remove(code).unwrap_or(0),
687 });
688 }
689 reports.extend(lost.iter().map(|(code, count)| pb::WatcherHost {
690 code: code_of(code),
691 hosts_lost: *count,
692 ..pb::WatcherHost::default()
693 }));
694 self.metrics.set_threads(tied, untied);
695 self.metrics
696 .hosts
697 .set(i64::try_from(running.len()).unwrap_or(i64::MAX));
698 self.metrics
699 .memory
700 .set(i64::try_from(sizes.iter().sum::<u64>()).unwrap_or(i64::MAX));
701 *self.reports.lock().unwrap_or_else(PoisonError::into_inner) = reports;
702 }
703
704 #[must_use]
706 pub fn reports(&self) -> Vec<pb::WatcherHost> {
707 self.reports
708 .lock()
709 .unwrap_or_else(PoisonError::into_inner)
710 .clone()
711 }
712
713 fn host_lost(&self, sys_path: &[String]) {
714 self.metrics
715 .hosts_lost
716 .get_or_create(&CodeLabels {
717 code: code_of(sys_path),
718 })
719 .inc();
720 *self
721 .lost
722 .lock()
723 .unwrap_or_else(PoisonError::into_inner)
724 .entry(sys_path.to_vec())
725 .or_default() += 1;
726 }
727
728 async fn leave(&self, host: &Arc<Host>, watcher: u64) {
730 host.unnamed(watcher);
731 let mut hosts = self.hosts.lock().await;
732 let empty = {
733 let mut routes = host.routes.lock().unwrap_or_else(PoisonError::into_inner);
734 routes.remove(&watcher);
735 routes.is_empty()
736 };
737 if empty {
738 retire(&host.going);
739 host.stop.notify_one();
740 let mut gone = None;
741 hosts.retain(|key, known| {
742 let keep = !Arc::ptr_eq(known, host);
743 if !keep {
744 gone = Some(key.clone());
745 }
746 keep
747 });
748 if let Some(key) = gone {
749 self.code_set(&key, false);
750 }
751 }
752 }
753
754 fn code_set(&self, sys_path: &[String], running: bool) {
755 let mut sets = self
756 .code_sets
757 .lock()
758 .unwrap_or_else(PoisonError::into_inner);
759 if running {
760 sets.insert(sys_path.to_vec());
761 } else {
762 sets.remove(sys_path);
763 }
764 }
765
766 #[must_use]
769 pub fn code_in_use(&self) -> Vec<String> {
770 let sets = self
771 .code_sets
772 .lock()
773 .unwrap_or_else(PoisonError::into_inner);
774 sets.iter()
775 .flatten()
776 .filter_map(|dir| {
777 let name = std::path::Path::new(dir).file_name()?;
778 Some(name.to_string_lossy().into_owned())
779 })
780 .collect()
781 }
782
783 pub fn code_changed(&self, copies: &Copies) {
785 self.code_channel().send_if_modified(|now| {
786 let changed = now != copies;
787 if changed {
788 let old: Vec<&PathBuf> = now
790 .values()
791 .filter(|copy| !copies.values().any(|current| current == *copy))
792 .collect();
793 self.lost
794 .lock()
795 .unwrap_or_else(PoisonError::into_inner)
796 .retain(|code, _| {
797 !code
798 .iter()
799 .any(|dir| old.iter().any(|copy| copy.as_os_str() == dir.as_str()))
800 });
801 now.clone_from(copies);
802 }
803 changed
804 });
805 }
806
807 fn code_channel(&self) -> watch::Sender<Copies> {
808 self.code
809 .lock()
810 .unwrap_or_else(PoisonError::into_inner)
811 .get_or_insert_with(|| watch::channel(Copies::new()).0)
812 .clone()
813 }
814
815 pub async fn running(&self) -> usize {
817 self.hosts.lock().await.len()
818 }
819}
820
821impl Entered {
822 async fn leave(mut self) {
823 self.left = true;
824 self.hosts.leave(&self.host, self.watcher).await;
825 }
826}
827
828impl Drop for Entered {
829 fn drop(&mut self) {
830 if self.left {
831 return;
832 }
833 let _ = self.host.outbox.send(AgentMessage::CancelWatcher {
836 watcher: self.watcher,
837 });
838 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
839 return;
840 };
841 let hosts = self.hosts.clone();
842 let host = Arc::clone(&self.host);
843 let watcher = self.watcher;
844 let grace = self.grace;
845 let mut messages = std::mem::replace(&mut self.messages, mpsc::channel(1).1);
846 runtime.spawn(async move {
847 let ended = async {
848 while let Some(message) = messages.recv().await {
849 if ends_a_watcher(&message) {
850 return;
851 }
852 }
853 };
854 if tokio::time::timeout(grace, ended).await.is_err() {
855 host.kill_for(watcher);
856 }
857 hosts.leave(&host, watcher).await;
858 });
859 }
860}
861
862impl Entered {
863 fn cancel_grace_ms(&self) -> u64 {
865 millis(self.grace)
866 }
867}
868
869const fn ends_a_watcher(message: &RunnerMessage) -> bool {
871 matches!(
872 message,
873 RunnerMessage::TaskSucceeded { .. }
874 | RunnerMessage::TaskFailed { .. }
875 | RunnerMessage::WatcherCancelled
876 | RunnerMessage::WatcherMoved
877 )
878}
879
880struct AttemptLog<'a> {
882 mask: &'a Mask,
883 file: tokio::fs::File,
884 stdout: Option<MaskStream<'a>>,
885 stderr: Option<MaskStream<'a>>,
886}
887
888impl<'a> AttemptLog<'a> {
889 async fn open(spec: &'a ProcessSpec) -> std::io::Result<Self> {
890 let file = crate::process::open_log_file(&spec.log_file).await?;
891 let stream = || spec.mask.0.as_deref().map(MaskSet::stream);
892 Ok(Self {
893 mask: &spec.mask,
894 file,
895 stdout: stream(),
896 stderr: stream(),
897 })
898 }
899
900 async fn write(&mut self, stream: OutputStream, text: &str) {
901 let masking = match stream {
902 OutputStream::Stdout => &mut self.stdout,
903 OutputStream::Stderr => &mut self.stderr,
904 };
905 let masked = match masking {
906 Some(masking) => masking.push(text.as_bytes()),
907 None => text.as_bytes().to_vec(),
908 };
909 let _ = self.file.write_all(&masked).await;
910 }
911
912 async fn note(&mut self, text: &str) {
914 let masked = match &self.mask.0 {
915 Some(mask) => mask.mask(text.as_bytes()),
916 None => text.as_bytes().to_vec(),
917 };
918 let _ = self.file.write_all(&masked).await;
919 }
920
921 async fn finish(mut self) {
922 for masking in [&mut self.stdout, &mut self.stderr].into_iter().flatten() {
923 let rest = masking.finish();
924 let _ = self.file.write_all(&rest).await;
925 }
926 let _ = self.file.flush().await;
927 }
928}
929
930struct Answers {
933 secrets: Option<Arc<AttemptSecrets>>,
934 handles: Option<Arc<AttemptHandles>>,
935 events: Option<EventSink>,
936 api: Option<crate::api::ApiCaller>,
937 pending: tokio::task::JoinSet<()>,
938 told_masked_key: bool,
940}
941
942type AnswerParts = (
944 Option<Arc<AttemptSecrets>>,
945 Option<Arc<AttemptHandles>>,
946 Option<EventSink>,
947 Option<crate::api::ApiCaller>,
948);
949
950impl Answers {
951 fn new((secrets, handles, events, api): AnswerParts) -> Self {
952 Self {
953 secrets,
954 handles,
955 events,
956 api,
957 pending: tokio::task::JoinSet::new(),
958 told_masked_key: false,
959 }
960 }
961
962 fn masks_a_key(&self, key: &str, data: &serde_json::Value, batched: bool) -> bool {
965 self.secrets
966 .as_ref()
967 .is_some_and(|secrets| holds_secret(&secrets.mask, key, data, batched))
968 }
969
970 async fn serve(
972 &mut self,
973 message: RunnerMessage,
974 host: &Arc<Host>,
975 watcher: u64,
976 log: &mut AttemptLog<'_>,
977 ) -> Option<RunnerMessage> {
978 if let RunnerMessage::WatcherLog { stream, text } = &message {
979 log.write(*stream, text).await;
980 return None;
981 }
982 if let RunnerMessage::TriggerPoked { error } = message {
983 if let Some(events) = &self.events {
984 let error = match self.secrets.as_ref().map(|s| &s.mask) {
985 Some(mask) if !mask.is_empty() => error.map(|why| mask.mask_text(&why)),
986 _ => error,
987 };
988 (events.poked)(error);
989 }
990 return None;
991 }
992 if let RunnerMessage::TriggerEvent { key, data, at } = message {
993 let Some(events) = &self.events else {
994 return None;
995 };
996 if !self.told_masked_key && self.masks_a_key(&key, &data, events.batched) {
998 self.told_masked_key = true;
999 log.write(OutputStream::Stderr, MASKED_KEY).await;
1000 }
1001 let (key, data) = match self.secrets.as_ref().map(|s| &s.mask) {
1003 Some(mask) if !mask.is_empty() => (mask.mask_text(&key), mask.mask_json(&data)),
1004 _ => (key, data),
1005 };
1006 let stored = (events.found)(FoundEvent { key, data, at });
1007 let host = Arc::clone(host);
1008 self.pending.spawn(async move {
1009 if stored.await.is_ok() {
1011 let _ = host.outbox.send(AgentMessage::ToWatcher {
1012 watcher,
1013 message: Box::new(AgentMessage::EventStored),
1014 });
1015 }
1016 });
1017 return None;
1018 }
1019 if !matches!(
1020 message,
1021 RunnerMessage::SecretGet { .. }
1022 | RunnerMessage::HandleAdd { .. }
1023 | RunnerMessage::ConnectionGet { .. }
1024 | RunnerMessage::ApiCall { .. }
1025 ) {
1026 return Some(message);
1027 }
1028 let secrets = self.secrets.clone();
1029 let handles = self.handles.clone();
1030 let api = self.api.clone();
1031 let host = Arc::clone(host);
1032 self.pending.spawn(async move {
1033 let answer = answer_to(
1034 message,
1035 secrets.as_deref(),
1036 handles.as_deref(),
1037 api.as_ref(),
1038 )
1039 .await;
1040 let _ = host.outbox.send(AgentMessage::ToWatcher {
1041 watcher,
1042 message: Box::new(answer),
1043 });
1044 });
1045 None
1046 }
1047}
1048
1049async fn answer_to(
1050 message: RunnerMessage,
1051 secrets: Option<&AttemptSecrets>,
1052 handles: Option<&AttemptHandles>,
1053 api: Option<&crate::api::ApiCaller>,
1054) -> AgentMessage {
1055 match message {
1056 RunnerMessage::ApiCall {
1057 method,
1058 path,
1059 body,
1060 idempotency_key,
1061 } => {
1062 let request = crate::api::ApiRequest {
1063 method,
1064 path,
1065 body,
1066 idempotency_key,
1067 masked: false,
1068 }
1069 .masked_by(secrets);
1070 crate::api::runner_answer(api, request).await
1071 }
1072 RunnerMessage::SecretGet { secret } => secret_answer(secrets, &secret).await,
1073 RunnerMessage::ConnectionGet { name } => connection_answer(secrets, &name).await,
1074 RunnerMessage::HandleAdd { handle } => {
1075 let added = match handles {
1076 Some(handles) => handles.add(handle).await,
1077 None => Err(HandleError::NoCleanup),
1078 };
1079 added.map_or_else(
1080 |error| AgentMessage::HandleRefused {
1081 message: error.to_string(),
1082 },
1083 |()| AgentMessage::HandleAdded,
1084 )
1085 }
1086 other => AgentMessage::Refused {
1087 reason: format!("not a question: {}", crate::channel::describe(&other)),
1088 },
1089 }
1090}
1091
1092enum Stage {
1094 Entering(tokio::task::JoinHandle<Result<Entered, LaunchError>>),
1096 Entered { to: Entered, stopping: bool },
1099}
1100
1101struct Moving {
1102 stage: Stage,
1103 request: TaskRequest,
1105 code_hash: Option<String>,
1107}
1108
1109struct Poke<'a> {
1111 setup: &'a WorkerSetup,
1112 hosts: &'a WatcherHosts,
1113 mask: Mask,
1114 grace: Duration,
1115 request: TaskRequest,
1117 code: watch::Receiver<Copies>,
1118 tried: Vec<String>,
1120 max_wait: Option<Duration>,
1121 started: Instant,
1122 moving: Option<Moving>,
1123}
1124
1125impl Poke<'_> {
1126 fn begin_move(&mut self) {
1128 if self.moving.is_some() {
1129 return;
1130 }
1131 let copies = self.code.borrow_and_update().clone();
1132 let Some(root_dir) = copies.get(&self.request.dag_file.root) else {
1133 return;
1134 };
1135 let sys_path = self.setup.sys_path_at(&copies);
1136 if sys_path == self.tried {
1137 return;
1138 }
1139 self.tried.clone_from(&sys_path);
1140 let code_hash = root_dir
1142 .file_name()
1143 .map(|name| name.to_string_lossy().replacen('-', ":", 1));
1144 let mut request = self.request.clone();
1145 request.dag_file.root_dir = root_dir.to_string_lossy().into_owned();
1146 request.sys_path.clone_from(&sys_path);
1147 let (hosts, setup, grace) = (self.hosts.clone(), self.setup.clone(), self.grace);
1148 let entering = tokio::spawn(async move { hosts.enter(&setup, &sys_path, grace).await });
1149 self.moving = Some(Moving {
1150 stage: Stage::Entering(entering),
1151 request,
1152 code_hash,
1153 });
1154 }
1155
1156 async fn entered_new_host(
1158 &mut self,
1159 result: Result<Result<Entered, LaunchError>, tokio::task::JoinError>,
1160 log: &mut AttemptLog<'_>,
1161 ) {
1162 let Some(moving) = self.moving.as_mut() else {
1163 return;
1164 };
1165 match result {
1166 Ok(Ok(to)) => {
1167 if let Some(mask) = &self.mask.0 {
1169 mask.also_in(Arc::clone(&to.host.mask));
1170 }
1171 let _ = to.host.outbox.send(AgentMessage::StartWatcher {
1172 watcher: to.watcher,
1173 task: Box::new(moving.request.clone()),
1174 cancel_grace_ms: to.cancel_grace_ms(),
1175 moved_in: true,
1176 });
1177 moving.stage = Stage::Entered {
1178 to,
1179 stopping: false,
1180 };
1181 }
1182 Ok(Err(error)) => self.stays(&error.to_string(), log).await,
1183 Err(error) => self.stays(&error.to_string(), log).await,
1184 }
1185 }
1186
1187 async fn stays(&mut self, why: &str, log: &mut AttemptLog<'_>) {
1189 log.note(&format!(
1190 "new code can't start this wait step, it stays on its code: {why}\n"
1191 ))
1192 .await;
1193 if let Some(Moving {
1194 stage: Stage::Entered { to, .. },
1195 ..
1196 }) = self.moving.take()
1197 {
1198 to.leave().await;
1199 }
1200 }
1201
1202 async fn on_new_code_message(
1204 &mut self,
1205 message: Option<RunnerMessage>,
1206 old: &Entered,
1207 answers: &mut Answers,
1208 log: &mut AttemptLog<'_>,
1209 ) {
1210 let Some(Moving {
1211 stage: Stage::Entered { to, stopping },
1212 ..
1213 }) = self.moving.as_mut()
1214 else {
1215 return;
1216 };
1217 let why = match message {
1218 Some(RunnerMessage::TaskImported) if !*stopping => {
1219 *stopping = true;
1220 let _ = old.host.outbox.send(AgentMessage::MoveWatcher {
1221 watcher: old.watcher,
1222 });
1223 return;
1224 }
1225 Some(RunnerMessage::TaskFailed { error, .. }) => {
1226 format!("{}: {}", error.exception, error.message)
1227 }
1228 None => "its host ended".to_owned(),
1229 Some(other) => {
1230 let (host, watcher) = (Arc::clone(&to.host), to.watcher);
1231 let _ = answers.serve(other, &host, watcher, log).await;
1232 return;
1233 }
1234 };
1235 self.stays(&why, log).await;
1236 }
1237
1238 fn left_of_max_wait(&self) -> Option<u64> {
1239 self.max_wait.map(|wait| {
1240 u64::try_from(wait.saturating_sub(self.started.elapsed()).as_millis())
1241 .unwrap_or(u64::MAX)
1242 })
1243 }
1244}
1245
1246struct Place {
1248 host: StdMutex<Arc<Host>>,
1249 watcher: AtomicU64,
1250 cancelling: AtomicBool,
1252 moved_to: StdMutex<Option<String>>,
1254 request: StdMutex<TaskRequest>,
1256 going_when_imported: StdMutex<Option<Instant>>,
1258}
1259
1260impl Place {
1261 fn started(entered: &Entered, request: &TaskRequest, running_since: Option<Instant>) -> Self {
1264 let _ = entered.host.outbox.send(AgentMessage::StartWatcher {
1265 watcher: entered.watcher,
1266 task: Box::new(request.clone()),
1267 cancel_grace_ms: entered.cancel_grace_ms(),
1268 moved_in: running_since.is_some(),
1269 });
1270 entered.host.named(entered.watcher, request);
1271 Self {
1272 host: StdMutex::new(Arc::clone(&entered.host)),
1273 watcher: AtomicU64::new(entered.watcher),
1274 cancelling: AtomicBool::new(false),
1275 moved_to: StdMutex::new(None),
1276 request: StdMutex::new(request.clone()),
1277 going_when_imported: StdMutex::new(running_since),
1278 }
1279 }
1280
1281 fn go_when_imported(&self, entered: &Entered) {
1283 let since = self
1284 .going_when_imported
1285 .lock()
1286 .unwrap_or_else(PoisonError::into_inner)
1287 .take();
1288 let Some(since) = since else {
1289 return;
1290 };
1291 let request = self.request.lock().unwrap_or_else(PoisonError::into_inner);
1292 let max_wait_ms = match request.task.kind {
1293 TaskKind::Sensor { max_wait_ms, .. } => max_wait_ms,
1294 _ => None,
1295 };
1296 let _ = entered.host.outbox.send(AgentMessage::GoWatcher {
1297 watcher: entered.watcher,
1298 max_wait_ms: max_wait_ms.map(|max| max.saturating_sub(millis(since.elapsed()))),
1299 });
1300 }
1301
1302 fn host(&self) -> Arc<Host> {
1303 Arc::clone(&self.host.lock().unwrap_or_else(PoisonError::into_inner))
1304 }
1305
1306 fn moved_to(&self) -> Option<String> {
1307 self.moved_to
1308 .lock()
1309 .unwrap_or_else(PoisonError::into_inner)
1310 .take()
1311 }
1312
1313 fn cancel(&self) {
1314 self.cancelling.store(true, Ordering::SeqCst);
1315 let _ = self.host().outbox.send(AgentMessage::CancelWatcher {
1316 watcher: self.watcher.load(Ordering::SeqCst),
1317 });
1318 }
1319}
1320
1321async fn conversation(
1324 mut entered: Entered,
1325 mut poke: Option<Poke<'_>>,
1326 place: &Place,
1327 mut answers: Answers,
1328 log: &mut AttemptLog<'_>,
1329) -> Option<RunnerMessage> {
1330 let ended = loop {
1331 let still = !place.cancelling.load(Ordering::SeqCst);
1332 if let (Some(poke), true) = (&mut poke, still) {
1333 poke.begin_move();
1334 }
1335 let (code, moving) = match &mut poke {
1336 Some(poke) => (Some(&mut poke.code), poke.moving.as_mut()),
1337 None => (None, None),
1338 };
1339 let new_code = async {
1340 match code {
1341 Some(code) if still => {
1342 if code.changed().await.is_err() {
1343 std::future::pending::<()>().await;
1344 }
1345 }
1346 _ => std::future::pending().await,
1347 }
1348 };
1349 let from_new = async {
1350 match moving.map(|moving| &mut moving.stage) {
1351 Some(Stage::Entering(entering)) => Happened::Entered(entering.await),
1352 Some(Stage::Entered { to, .. }) => Happened::New(to.messages.recv().await),
1353 None => std::future::pending().await,
1354 }
1355 };
1356 let happened = tokio::select! {
1357 biased;
1358 message = entered.messages.recv() => Happened::Old(message),
1359 happened = from_new => happened,
1360 () = new_code => Happened::NewCode,
1361 Some(_) = answers.pending.join_next() => Happened::NewCode,
1363 };
1364 match happened {
1365 Happened::NewCode => {}
1366 Happened::Old(Some(RunnerMessage::TaskImported)) => place.go_when_imported(&entered),
1367 Happened::Old(None) => break None,
1368 Happened::Old(Some(RunnerMessage::WatcherMoved)) => {
1369 if place.cancelling.load(Ordering::SeqCst) {
1370 break Some(RunnerMessage::WatcherCancelled);
1371 }
1372 let Some(poke) = poke.as_mut() else {
1373 break None;
1374 };
1375 match moved(poke, log).await {
1376 Ok(to) => {
1377 place
1378 .request
1379 .lock()
1380 .unwrap_or_else(PoisonError::into_inner)
1381 .clone_from(&poke.request);
1382 *place.host.lock().unwrap_or_else(PoisonError::into_inner) =
1383 Arc::clone(&to.0.host);
1384 place.watcher.store(to.0.watcher, Ordering::SeqCst);
1385 if to.1.is_some() {
1386 *place
1387 .moved_to
1388 .lock()
1389 .unwrap_or_else(PoisonError::into_inner) = to.1;
1390 }
1391 let old = std::mem::replace(&mut entered, to.0);
1392 old.leave().await;
1393 }
1394 Err(why) => {
1395 log.note(&format!("this wait step can't go on: {why}\n"))
1396 .await;
1397 break None;
1398 }
1399 }
1400 }
1401 Happened::Old(Some(message)) => {
1402 let host = Arc::clone(&entered.host);
1403 if let Some(message) = answers.serve(message, &host, entered.watcher, log).await {
1404 break Some(message);
1405 }
1406 }
1407 Happened::Entered(result) => {
1408 if let Some(poke) = poke.as_mut() {
1409 poke.entered_new_host(result, log).await;
1410 }
1411 }
1412 Happened::New(message) => {
1413 if let Some(poke) = poke.as_mut() {
1414 poke.on_new_code_message(message, &entered, &mut answers, log)
1415 .await;
1416 }
1417 }
1418 }
1419 };
1420 drop(poke);
1421 entered.leave().await;
1422 ended
1423}
1424
1425async fn moved(
1429 poke: &mut Poke<'_>,
1430 log: &mut AttemptLog<'_>,
1431) -> Result<(Entered, Option<String>), String> {
1432 let left = poke.left_of_max_wait();
1433 if let Some(Moving {
1434 stage: Stage::Entered { to, .. },
1435 request,
1436 code_hash,
1437 }) = poke.moving.take()
1438 {
1439 to.host.named(to.watcher, &request);
1440 let _ = to.host.outbox.send(AgentMessage::GoWatcher {
1441 watcher: to.watcher,
1442 max_wait_ms: left,
1443 });
1444 log.note("moved to new code\n").await;
1445 poke.request = request;
1446 return Ok((to, code_hash));
1447 }
1448 let to = poke
1449 .hosts
1450 .enter(poke.setup, &poke.request.sys_path, poke.grace)
1451 .await
1452 .map_err(|error| error.to_string())?;
1453 let _ = to.host.outbox.send(AgentMessage::StartWatcher {
1454 watcher: to.watcher,
1455 task: Box::new(poke.request.clone()),
1456 cancel_grace_ms: to.cancel_grace_ms(),
1457 moved_in: true,
1458 });
1459 to.host.named(to.watcher, &poke.request);
1460 let _ = to.host.outbox.send(AgentMessage::GoWatcher {
1461 watcher: to.watcher,
1462 max_wait_ms: left,
1463 });
1464 Ok((to, None))
1465}
1466
1467enum Happened {
1468 Old(Option<RunnerMessage>),
1469 New(Option<RunnerMessage>),
1470 Entered(Result<Result<Entered, LaunchError>, tokio::task::JoinError>),
1471 NewCode,
1472}
1473
1474pub async fn run_watcher(
1482 hosts: &WatcherHosts,
1483 setup: &WorkerSetup,
1484 process: &ProcessSpec,
1485 task: PythonTask,
1486 limits: Limits,
1487 mut stop: Stops,
1488 spawned: impl FnOnce(i32),
1489) -> Result<Ran, LaunchError> {
1490 let PythonTask {
1491 mut request,
1492 secrets,
1493 handles,
1494 events,
1495 api,
1496 } = task;
1497 let parts = (secrets, handles, events, api);
1498 let started = Instant::now();
1499 let deadline = limits
1500 .timeout
1501 .map(|timeout| tokio::time::Instant::from_std(started) + timeout);
1502 let ran = |supervised, runner_result| {
1503 Ran::with_no_process(supervised, runner_result, started.elapsed())
1504 };
1505 let mut log = AttemptLog::open(process)
1506 .await
1507 .map_err(|source| LaunchError::Start {
1508 what: process.log_file.display().to_string(),
1509 source,
1510 })?;
1511 let mut spawned = Some(spawned);
1512 let mut moved_to = None;
1513 let mut again = false;
1514 loop {
1515 let sys_path = request.sys_path.clone();
1516 let entering = hosts.enter(setup, &sys_path, limits.grace);
1517 let entered = match unless_stopped(entering, Some((&mut stop, deadline))).await {
1518 Ok(entered) => entered?,
1519 Err(reason) => {
1520 let supervised = Supervised {
1521 termination: Termination::Unknown,
1522 stopped: Some(reason),
1523 killed: false,
1524 };
1525 return Ok(ran(supervised, None));
1526 }
1527 };
1528 if let Some(spawned) = spawned.take() {
1529 spawned(entered.host.pid);
1530 }
1531 if let Some(mask) = &process.mask.0 {
1532 mask.also_in(Arc::clone(&entered.host.mask));
1533 }
1534 let poke = poke_of(
1535 hosts,
1536 setup,
1537 &request,
1538 started,
1539 (&process.mask, limits.grace),
1540 );
1541 let starts = again.then_some(started);
1543 let place = Place::started(&entered, &request, starts);
1544 let (message, reason, killed) = {
1545 let answers = Answers::new(parts.clone());
1546 let talking = conversation(entered, poke, &place, answers, &mut log);
1547 let talking = Box::pin(talking);
1548 until_ended(talking, &mut stop, deadline, &place, limits).await
1549 };
1550 moved_to = place.moved_to().or(moved_to);
1551 let (message, host_lost) = if message.is_none() && reason.is_none() {
1552 let trigger = place_is_trigger(&place);
1553 match after_host_ended(&place, setup, trigger).await {
1554 AfterHost::Fails(message) => (Some(message), None),
1555 AfterHost::Lost(why) => (None, Some(why)),
1556 AfterHost::StartsAgain => {
1557 log.note(STARTS_AGAIN).await;
1559 hosts.metrics.restarts.inc();
1560 request = place
1561 .request
1562 .into_inner()
1563 .unwrap_or_else(PoisonError::into_inner);
1564 again = true;
1565 continue;
1566 }
1567 }
1568 } else {
1569 (message, None)
1570 };
1571 log.finish().await;
1572 let struck = place
1573 .host()
1574 .going()
1575 .0
1576 .is_some_and(|blamed| blamed.watcher == place.watcher.load(Ordering::SeqCst));
1577 let supervised = Supervised {
1578 termination: termination_of(message.as_ref(), killed, &place).await,
1579 stopped: reason,
1580 killed,
1581 };
1582 let result = message.filter(|message| !matches!(message, RunnerMessage::WatcherCancelled));
1583 return Ok(Ran {
1584 moved_to,
1585 host_lost,
1586 struck,
1587 ..ran(supervised, result)
1588 });
1589 }
1590}
1591
1592const STARTS_AGAIN: &str =
1593 "another wait step had its host killed: this one starts again on a new host\n";
1594
1595enum AfterHost {
1597 Fails(RunnerMessage),
1599 StartsAgain,
1601 Lost(String),
1603}
1604
1605async fn after_host_ended(place: &Place, setup: &WorkerSetup, trigger: bool) -> AfterHost {
1606 let host = place.host();
1607 let termination = ended_host(&host).await;
1608 match host.going() {
1609 (Some(blamed), _) if blamed.watcher == place.watcher.load(Ordering::SeqCst) => {
1610 AfterHost::Fails(blocked(setup, blamed.stack))
1611 }
1612 (Some(_), _) if trigger => {
1614 AfterHost::Lost("its host was killed for another watcher on it".to_owned())
1615 }
1616 (Some(_), _) => AfterHost::StartsAgain,
1617 (None, why) => {
1618 let why = why.unwrap_or_else(|| format!("its host ended: {termination:?}"));
1619 let names = host.names();
1620 AfterHost::Lost(format!(
1621 "{why}\nNo wait step can be blamed. On its host: {names}"
1622 ))
1623 }
1624 }
1625}
1626
1627fn place_is_trigger(place: &Place) -> bool {
1628 place
1629 .request
1630 .lock()
1631 .unwrap_or_else(PoisonError::into_inner)
1632 .trigger
1633 .is_some()
1634}
1635
1636fn blocked(setup: &WorkerSetup, stack: Option<String>) -> RunnerMessage {
1638 let limit = setup.timeouts.watcher_block_limit;
1639 RunnerMessage::TaskFailed {
1640 error: ErrorSummary {
1641 exception: "BlockedEventLoop".to_owned(),
1642 message: stack.as_ref().map_or_else(
1643 || "it wouldn't end in its grace time, so its host was killed".to_owned(),
1644 |_| {
1645 format!(
1646 "it didn't reach an `await` within `[watchers] block_limit` ({} s), \
1647 holding up every wait step on its host. Use an async client or \
1648 `asyncio.to_thread`",
1649 limit.as_secs_f64()
1650 )
1651 },
1652 ),
1653 traceback: stack.unwrap_or_default(),
1654 },
1655 kind: Some(schedr_model::runner::BLOCKED_EVENT_LOOP.to_owned()),
1656 }
1657}
1658
1659async fn until_ended(
1662 mut talking: impl Future<Output = Option<RunnerMessage>> + Unpin,
1663 stop: &mut Stops,
1664 deadline: Option<tokio::time::Instant>,
1665 place: &Place,
1666 limits: Limits,
1667) -> (Option<RunnerMessage>, Option<StopReason>, bool) {
1668 let until = async {
1669 match deadline {
1670 Some(deadline) => tokio::time::sleep_until(deadline).await,
1671 None => std::future::pending().await,
1672 }
1673 };
1674 let reason = tokio::select! {
1675 biased;
1676 reason = stop.next_reason() => reason,
1677 () = until => StopReason::TimedOut,
1678 message = &mut talking => return (message, None, false),
1679 };
1680 place.cancel();
1681 let (message, killed) = cancelled(place, &mut talking, stop, limits, reason).await;
1682 (message, Some(reason), killed)
1683}
1684
1685async fn termination_of(
1687 message: Option<&RunnerMessage>,
1688 killed: bool,
1689 place: &Place,
1690) -> Termination {
1691 match message {
1692 Some(RunnerMessage::TaskSucceeded { .. }) => Termination::Exited(0),
1693 Some(RunnerMessage::TaskFailed { .. }) => Termination::Exited(FAILED_EXIT_CODE),
1694 Some(RunnerMessage::WatcherCancelled) => Termination::Signaled(TERMINATED),
1695 Some(_) => Termination::Unknown,
1696 None if killed => Termination::Signaled(KILLED),
1697 None => ended_host(&place.host()).await,
1698 }
1699}
1700
1701fn poke_of<'a>(
1703 hosts: &'a WatcherHosts,
1704 setup: &'a WorkerSetup,
1705 request: &TaskRequest,
1706 started: Instant,
1707 (mask, grace): (&Mask, Duration),
1708) -> Option<Poke<'a>> {
1709 if request.trigger.is_some() {
1711 return None;
1712 }
1713 let TaskKind::Sensor {
1714 mode: SensorMode::Poke,
1715 max_wait_ms,
1716 ..
1717 } = request.task.kind
1718 else {
1719 return None;
1720 };
1721 Some(Poke {
1722 setup,
1723 hosts,
1724 mask: mask.clone(),
1725 grace,
1726 request: request.clone(),
1727 code: hosts.code_channel().subscribe(),
1728 tried: request.sys_path.clone(),
1729 max_wait: max_wait_ms.map(Duration::from_millis),
1730 started,
1731 moving: None,
1732 })
1733}
1734
1735async fn ended_host(host: &Host) -> Termination {
1737 let mut ended = host.ended.clone();
1738 match ended.wait_for(Option::is_some).await {
1739 Ok(termination) => (*termination).unwrap_or(Termination::Unknown),
1740 Err(_) => Termination::Unknown,
1741 }
1742}
1743
1744async fn cancelled(
1747 place: &Place,
1748 talking: &mut (impl Future<Output = Option<RunnerMessage>> + Unpin),
1749 stop: &mut Stops,
1750 limits: Limits,
1751 reason: StopReason,
1752) -> (Option<RunnerMessage>, bool) {
1753 let grace = if reason == StopReason::Interrupted {
1754 limits.interrupt_grace
1755 } else {
1756 limits.grace
1757 };
1758 let mut kill_at = tokio::time::Instant::now() + grace;
1759 loop {
1760 tokio::select! {
1761 biased;
1762 later = stop.next_reason() => {
1763 if later == StopReason::Interrupted {
1764 kill_at = kill_at.min(tokio::time::Instant::now() + limits.interrupt_grace);
1765 }
1766 }
1767 message = &mut *talking => return (message, false),
1768 () = tokio::time::sleep_until(kill_at) => {
1769 place.host().kill_for(place.watcher.load(Ordering::SeqCst));
1770 return (None, true);
1771 }
1772 }
1773 }
1774}
1775
1776const MASKED_KEY: &str = "schedr: an event's key held a secret this trigger read: it is stored \
1778 and shown masked, so keys differing only in secrets count as one key (a key seen before \
1779 starts no run); keep secrets out of keys\n";
1780
1781fn holds_secret(mask: &MaskSet, key: &str, data: &serde_json::Value, batched: bool) -> bool {
1784 if mask.is_empty() {
1785 return false;
1786 }
1787 let items = data.as_array().filter(|_| batched).into_iter().flatten();
1788 let mut keys = std::iter::once(key).chain(items.filter_map(|item| item["key"].as_str()));
1789 keys.any(|key| mask.mask_text(key) != key)
1790}