1use std::collections::{BTreeMap, BTreeSet};
28use std::path::{Path, PathBuf};
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Arc, PoisonError};
31use std::time::{Duration, Instant};
32
33use jiff::Timestamp;
34use schedr_model::TaskKind;
35use schedr_model::beat::Beat;
36use schedr_model::connection::Registry;
37use schedr_model::runner::{
38 CleanupHandle, DAG_FILE_MISSING, ErrorSummary, ParseRequest, ParsedFile,
39};
40use schedr_model::task::{CleanupRun, TaskCleanup, default_outcomes};
41use schedr_proto::PROTOCOL_VERSION;
42use schedr_proto::convert::attempt_status_from_proto;
43use schedr_proto::convert::{parse_upload_parts, parsed_file_to_proto};
44use schedr_proto::pb::master_client::MasterClient;
45use schedr_proto::pb::{self, master_message, worker_message};
46use tokio::sync::{mpsc, oneshot, watch};
47
48use crate::api::ApiCaller;
49use tokio_stream::wrappers::UnboundedReceiverStream;
50use tonic::transport::Channel;
51
52use crate::attempt::{
53 AttemptSpec, CleanupGate, Gate, NotRun, Pass, Plan, Ran, WorkerSetup, failed_before_start,
54 finished, plan, plan_at, use_cleanup_script, with_resource_value,
55};
56use crate::connection_jobs::ConnectionJob;
57use crate::ctx::CtxInfo;
58use crate::drain::{Drain, DrainPeriods, DrainStep};
59use crate::fork::ForkServers;
60use crate::handles::{AttemptHandles, HandleSink};
61use crate::journal::{
62 Journal, JournalRecord, KeptAttempt, Orphan, ProcessIdentity, process_identity, stop_orphan,
63};
64use crate::launch::{AGENT_VERSION, ProcessParseRunner, PythonTask, run_command, run_python};
65use crate::mask::Mask;
66use crate::master_time::{Local, MasterTime, SharedOutbox};
67use crate::memory::{MemorySeen, SharedSeen, over_budget_message, watch_group};
68use crate::metrics::AgentMetrics;
69use crate::process::ProcessSpec;
70use crate::resource::AttemptResource;
71use crate::secrets::{AttemptSecrets, SecretStores};
72use crate::status::StopReason;
73use crate::supervise::{Limits, StopSender, Stops};
74use crate::watch::{Poll, RootWatcher};
75
76#[cfg(test)]
77mod tests;
78
79pub const START_FAILED: &str = "start_failed";
81
82pub const MAX_BACKOFF: Duration = Duration::from_secs(30);
84
85pub const ORPHAN_GRACE: Duration = Duration::from_secs(10);
87
88pub const FIRST_BACKOFF: Duration = Duration::from_millis(200);
91
92#[must_use]
98pub fn reconnect_cap(max: Duration, lease: Option<Duration>) -> Duration {
99 lease.map_or(max, |lease| max.min(lease / 2))
100}
101
102#[must_use]
105pub fn jittered(backoff: Duration, seed: u32) -> Duration {
106 let fraction = 0.5 + 0.5 * f64::from(seed) / f64::from(u32::MAX);
107 backoff.mul_f64(fraction)
108}
109
110#[derive(Debug, Clone)]
112pub struct AgentSettings {
113 pub worker_id: String,
115 pub queues: Vec<String>,
117 pub slots: u32,
119 pub watcher_slots: u32,
121 pub setup: WorkerSetup,
123 pub poll_interval: Duration,
125 pub settle_time: Duration,
127 pub journal_dir: PathBuf,
129 pub code_dir: PathBuf,
132 pub drain: DrainPeriods,
135 pub log_endpoint: String,
138 pub node: NodeIdentity,
140 pub secrets: Arc<SecretStores>,
142}
143
144#[derive(Debug, Clone, Default, PartialEq, Eq)]
146pub struct NodeIdentity {
147 pub process_id: String,
149 pub config_json: String,
152}
153
154pub type Spawned = Arc<dyn Fn(ProcessIdentity, bool) + Send + Sync>;
157
158pub type TaskEnded = Box<dyn FnOnce(pb::Finished) + Send>;
160
161#[derive(Clone, Copy)]
163struct Shared<'a> {
164 secrets: &'a Arc<AttemptSecrets>,
165 handles: &'a Arc<AttemptHandles>,
166 started: &'a AtomicBool,
168 spawned: &'a Spawned,
170}
171
172#[derive(Debug, Clone, Default, PartialEq, Eq)]
174pub struct ParseCode {
175 pub scripts: BTreeMap<String, crate::jobs::ScriptRoot>,
177 pub roots: BTreeMap<String, PathBuf>,
179}
180
181pub trait Executor: Clone + Send + Sync + 'static {
183 fn run(
188 &self,
189 spec: AttemptSpec,
190 plan: Plan,
191 stop: Stops,
192 spawned: Spawned,
193 ended: TaskEnded,
194 ) -> impl Future<Output = pb::Finished> + Send;
195
196 fn cleanup(
199 &self,
200 spec: AttemptSpec,
201 ended: pb::Finished,
202 handles: Vec<CleanupHandle>,
203 spawned: Spawned,
204 ) -> impl Future<Output = pb::Finished> + Send;
205
206 fn warnings(&self) -> watch::Receiver<Vec<pb::WorkerWarning>> {
208 watch::channel(Vec::new()).1
209 }
210
211 fn code_changed(&self, _copies: BTreeMap<String, PathBuf>) {}
213
214 fn code_in_use(&self) -> Vec<String> {
216 Vec::new()
217 }
218
219 fn watcher_hosts(&self) -> Vec<pb::WatcherHost> {
221 Vec::new()
222 }
223
224 fn memory_parts(&self) -> (u64, Vec<schedr_model::usage::TaskMemory>) {
227 (0, Vec::new())
228 }
229
230 fn parse(
232 &self,
233 root: String,
234 dir: PathBuf,
235 files: Vec<String>,
236 code: ParseCode,
237 ) -> impl Future<Output = Result<Vec<ParsedFile>, String>> + Send;
238
239 fn connection_job(
244 &self,
245 job: ConnectionJob,
246 spawned: Spawned,
247 ) -> impl Future<Output = Vec<schedr_model::commands::ConnectionReport>> + Send {
248 drop(spawned);
249 async move {
250 job.registry
251 .connections
252 .keys()
253 .chain(job.registry.refused.keys())
254 .map(|name| {
255 crate::connection_jobs::failed(
256 name,
257 "this worker can't check connections".to_owned(),
258 )
259 })
260 .collect()
261 }
262 }
263}
264
265pub(crate) const NO_PROC_WARNING: &str = "no /proc: orphaned tasks aren't stopped after a crash";
267
268static NO_PROC_SAID: AtomicBool = AtomicBool::new(false);
270
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub(crate) enum IdentityWarning {
274 NoProc,
276 ThisTask,
278}
279
280#[must_use]
288pub(crate) fn identity_warning(proc_present: bool, said: &AtomicBool) -> Option<IdentityWarning> {
289 if proc_present {
290 Some(IdentityWarning::ThisTask)
291 } else if said.swap(true, Ordering::Relaxed) {
292 None
293 } else {
294 Some(IdentityWarning::NoProc)
295 }
296}
297
298fn warn_unidentified(pid: i32, error: &std::io::Error) {
300 match identity_warning(Path::new("/proc").is_dir(), &NO_PROC_SAID) {
301 Some(IdentityWarning::NoProc) => tracing::warn!("{}", NO_PROC_WARNING),
302 Some(IdentityWarning::ThisTask) => {
303 tracing::warn!(pid, %error, "can't identify the task's process");
304 }
305 None => {}
306 }
307}
308
309#[derive(Debug, Clone)]
311pub struct ProcessExecutor {
312 pub setup: WorkerSetup,
314 pub parse: crate::parse::ParseLimits,
316 pub metrics: AgentMetrics,
318 pub drain_terminate_period: Duration,
320 pub forks: Option<ForkServers>,
322 pub watchers: crate::watchers::WatcherHosts,
324 pub secrets: Arc<SecretStores>,
326 pub running_memory: crate::memory::RunningMemory,
328}
329
330impl Executor for ProcessExecutor {
331 fn code_changed(&self, copies: BTreeMap<String, PathBuf>) {
332 self.watchers.code_changed(&copies);
333 }
334
335 fn code_in_use(&self) -> Vec<String> {
336 self.watchers.code_in_use()
337 }
338
339 fn watcher_hosts(&self) -> Vec<pb::WatcherHost> {
340 self.watchers.reports()
341 }
342
343 fn memory_parts(&self) -> (u64, Vec<schedr_model::usage::TaskMemory>) {
344 (
345 self.forks.as_ref().map_or(0, ForkServers::memory),
346 self.running_memory.now(),
347 )
348 }
349
350 fn warnings(&self) -> watch::Receiver<Vec<pb::WorkerWarning>> {
351 self.forks
352 .as_ref()
353 .map_or_else(|| watch::channel(Vec::new()).1, ForkServers::warnings)
354 }
355
356 async fn run(
357 &self,
358 spec: AttemptSpec,
359 plan: Plan,
360 stop: Stops,
361 spawned: Spawned,
362 ended: TaskEnded,
363 ) -> pb::Finished {
364 let connection_dir = self.setup.connection_dir.join(&spec.attempt_id);
365 let has_cleanup = spec.task.cleanup.is_some();
366 let mut finished = Box::pin(self.run_attempt(spec, plan, stop, spawned, ended)).await;
368 if has_cleanup && finished.cleanup.is_none() {
370 finished.cleanup = Some(pb::CleanupResult {
371 status: pb::CleanupStatus::NotNeeded.into(),
372 ..pb::CleanupResult::default()
373 });
374 }
375 remove_connection_files(&connection_dir).await;
377 finished
378 }
379
380 async fn cleanup(
381 &self,
382 mut spec: AttemptSpec,
383 mut ended: pb::Finished,
384 handles: Vec<CleanupHandle>,
385 spawned: Spawned,
386 ) -> pb::Finished {
387 let connection_dir = self.setup.connection_dir.join(&spec.attempt_id);
388 let result = Box::pin(self.kept_cleanup(&mut spec, handles, &spawned)).await;
389 ended.cleanup = Some(result);
390 remove_connection_files(&connection_dir).await;
391 ended
392 }
393
394 async fn connection_job(
395 &self,
396 job: ConnectionJob,
397 spawned: Spawned,
398 ) -> Vec<schedr_model::commands::ConnectionReport> {
399 use crate::connection_jobs::{failed, out_of_time};
400 let secrets = Arc::new(self.secrets.uncached());
402 let Some((name, _)) = job.test.clone() else {
403 let check = crate::connection_jobs::check(&secrets, &job.registry);
404 return match tokio::time::timeout_at(job.deadline, check).await {
405 Ok(reports) => reports,
406 Err(_) => job
407 .registry
408 .names()
409 .map(|name| failed(name, out_of_time("check")))
410 .collect(),
411 };
412 };
413 let left = job
415 .deadline
416 .saturating_duration_since(tokio::time::Instant::now());
417 let mut spec =
418 match crate::connection_jobs::test_spec(&job, &name, left, job.attempt_id.clone()) {
419 Ok(spec) => spec,
420 Err(why) => return vec![failed(&name, why)],
421 };
422 spec.stand_in_secrets();
423 let planned = match &spec.code_dir {
425 Some(dir) => plan_at(&spec, &self.setup, dir),
426 None => crate::attempt::plan(&spec, &self.setup),
427 };
428 let plan = match planned {
429 Ok(plan) => plan,
430 Err(NotRun::Rejected { detail, .. }) => return vec![failed(&name, detail)],
431 Err(NotRun::Failed { message, .. }) => return vec![failed(&name, message)],
432 };
433 let started = Instant::now();
434 let log = self.setup.log_file(&spec.attempt_id);
435 let (stop, stops) = Stops::new();
436 let fresh = Self {
437 secrets,
438 ..self.clone()
439 };
440 let run = fresh.run(spec, plan, stops, spawned, Box::new(|_| {}));
441 tokio::pin!(run);
442 let finished = tokio::select! {
445 finished = &mut run => finished,
446 () = tokio::time::sleep_until(job.deadline) => {
447 let _ = stop.send(StopReason::TimedOut);
448 run.await
449 }
450 };
451 let _ = tokio::fs::remove_file(&log).await;
453 vec![crate::connection_jobs::test_report(
454 &name,
455 &finished,
456 started.elapsed(),
457 )]
458 }
459
460 async fn parse(
461 &self,
462 root: String,
463 dir: PathBuf,
464 files: Vec<String>,
465 code: ParseCode,
466 ) -> Result<Vec<ParsedFile>, String> {
467 self.parse_files(root, dir, files, code).await
468 }
469}
470
471impl ProcessExecutor {
472 async fn run_attempt(
473 &self,
474 mut spec: AttemptSpec,
475 mut plan: Plan,
476 stop: Stops,
477 spawned: Spawned,
478 ended: TaskEnded,
479 ) -> pb::Finished {
480 let fetching = Instant::now();
481 let _ = tokio::fs::create_dir_all(&self.setup.log_dir).await;
482 let timeout = spec.timeout();
483 let mut stop = stop;
484 let fetched = tokio::select! {
487 fetched = self.fetch_secrets(&mut spec, &mut plan) => Ok(fetched),
488 reason = stop.next_reason() => Err(reason),
489 () = sleep_for(timeout) => Err(StopReason::TimedOut),
490 };
491 let secrets = match fetched {
492 Ok(Ok(secrets)) => secrets,
493 Ok(Err(finished)) => return *finished,
494 Err(reason) => return stopped_before_start(&spec, reason, fetching.elapsed()),
495 };
496 let elapsed = fetching.elapsed();
497 let timeout = timeout.map(|timeout| timeout.saturating_sub(elapsed));
498 if timeout.is_some_and(|left| left.is_zero()) {
501 return stopped_before_start(&spec, StopReason::TimedOut, elapsed);
502 }
503 let python = matches!(plan, Plan::Python { .. });
504 let mut handles =
505 AttemptHandles::new(spec.task.cleanup.as_ref(), Arc::clone(&secrets.mask));
506 if let Some(journal) = &spec.journal {
507 handles = handles.journaled(journal.clone(), spec.attempt_id.clone());
508 }
509 if let Some(sink) = &spec.handle_sink {
510 handles = handles.forwarded(sink.clone());
511 }
512 let handles = Arc::new(handles);
513 let started = AtomicBool::new(false);
514 let shared = Shared {
515 secrets: &secrets,
516 handles: &handles,
517 started: &started,
518 spawned: &spawned,
519 };
520 let mut finished = self.run_planned(&spec, plan, timeout, stop, shared).await;
521 ended_with_secrets(&mut finished, &secrets, python);
522 if let Some(cleanup) = &spec.task.cleanup
523 && started.load(Ordering::SeqCst)
524 {
525 ended(finished.clone());
526 let pass = match spec.cleanup_gate.clone() {
528 Some(gate) => gate.passes().await,
529 None => Some(Pass::All),
530 };
531 if let Some(pass) = pass {
532 if let Pass::From(from) = pass {
533 handles.skip(from);
534 }
535 let mut result = self.run_cleanup(&spec, cleanup, shared).await;
536 result.rest = matches!(pass, Pass::From(_));
537 finished.cleanup = Some(result);
538 }
539 }
540 let log = self.setup.log_file(&spec.attempt_id);
541 let short = too_short_lines(&secrets, self.secrets.min_mask_length);
543 append_log(&log, &(short + &masked_lines(&secrets))).await;
544 finished
545 }
546
547 async fn fetch_secrets(
550 &self,
551 spec: &mut AttemptSpec,
552 plan: &mut Plan,
553 ) -> Result<Arc<AttemptSecrets>, Box<pb::Finished>> {
554 let needed = spec.needed_secrets();
555 let fail = |kind: &str, message: &str| {
556 Box::new(failed_before_start(&spec.attempt_id, kind, message))
557 };
558 let secrets = AttemptSecrets::fetch(
559 Arc::clone(&self.secrets),
560 &needed,
561 spec.task.secrets.clone(),
562 )
563 .await
564 .map_err(|e| fail(e.kind(), &e.to_string()))?
565 .with_connections(Arc::clone(&spec.connections), spec.task.connections.clone())
566 .with_connection_dir(self.setup.connection_dir.join(&spec.attempt_id));
567 secrets
568 .open_declared()
569 .await
570 .map_err(|e| fail(e.kind(), &e.to_string()))?;
571 if needed.is_empty() && spec.task.secrets.is_empty() && !secrets.has_connections() {
572 return Ok(Arc::new(secrets));
575 }
576 if let TaskKind::Command { connection_env, .. } = &spec.task.kind {
577 spec.connection_env = command_connections(&secrets, connection_env)
578 .await
579 .map_err(|(kind, message)| fail(kind, &message))?;
580 }
581 spec.secrets = secrets.fetched();
582 spec.mask = Mask(Some(Arc::clone(&secrets.mask)));
583 let planned = match &spec.code_dir {
584 Some(dir) => plan_at(spec, &self.setup, dir),
585 None => crate::attempt::plan(spec, &self.setup),
586 };
587 *plan = planned.map_err(|not_run| match not_run {
588 NotRun::Failed { kind, message } => fail(&kind, &message),
589 NotRun::Rejected { detail, .. } => fail(DAG_FILE_MISSING, &detail),
591 })?;
592 let short = too_short_lines(&secrets, self.secrets.min_mask_length);
593 append_log(&self.setup.log_file(&spec.attempt_id), &short).await;
594 Ok(Arc::new(secrets))
595 }
596
597 async fn kept_cleanup(
600 &self,
601 spec: &mut AttemptSpec,
602 handles: Vec<CleanupHandle>,
603 spawned: &Spawned,
604 ) -> pb::CleanupResult {
605 let failed = |kind: &str, summary: Vec<u8>| pb::CleanupResult {
606 status: pb::CleanupStatus::Failed.into(),
607 error_kind: kind.to_owned(),
608 error_summary_json: summary,
609 ..pb::CleanupResult::default()
610 };
611 let Some(cleanup) = spec.task.cleanup.clone() else {
612 return pb::CleanupResult {
613 status: pb::CleanupStatus::NotNeeded.into(),
614 ..pb::CleanupResult::default()
615 };
616 };
617 use_cleanup_script(&mut spec.task);
619 if let Some(dir) = [&spec.code_dir, &spec.script_dir]
620 .into_iter()
621 .flatten()
622 .find(|dir| !dir.exists())
623 {
624 let message = format!("the attempt's code is gone from `{}`", dir.display());
625 let summary = ErrorSummary::json("CodeGone", &message).into_bytes();
626 return failed(DAG_FILE_MISSING, summary);
627 }
628 let _ = tokio::fs::create_dir_all(&self.setup.log_dir).await;
629 spec.stand_in_secrets();
630 let planned = match &spec.code_dir {
631 Some(dir) => plan_at(spec, &self.setup, dir),
632 None => crate::attempt::plan(spec, &self.setup),
633 };
634 let mut plan = match planned {
635 Ok(plan) => plan,
636 Err(NotRun::Failed { kind, message }) => {
637 return failed(
638 &kind,
639 ErrorSummary::json("CleanupNotRun", &message).into_bytes(),
640 );
641 }
642 Err(NotRun::Rejected { detail, .. }) => {
643 let summary = ErrorSummary::json("CleanupNotRun", &detail).into_bytes();
644 return failed(DAG_FILE_MISSING, summary);
645 }
646 };
647 let timeout = cleanup
649 .timeout_ms
650 .map_or(self.setup.timeouts.cleanup, Duration::from_millis);
651 let secrets = match tokio::time::timeout(timeout, self.fetch_secrets(spec, &mut plan)).await
652 {
653 Ok(Ok(secrets)) => secrets,
654 Ok(Err(finished)) => return failed(&finished.error_kind, finished.error_summary_json),
655 Err(_) => {
656 let message = "the cleanup's secrets weren't read within its timeout";
657 let summary = ErrorSummary::json("CleanupNotRun", message).into_bytes();
658 return failed("timed_out", summary);
659 }
660 };
661 let handles = Arc::new(AttemptHandles::restored(handles, Arc::clone(&secrets.mask)));
662 let started = AtomicBool::new(true);
663 let shared = Shared {
664 secrets: &secrets,
665 handles: &handles,
666 started: &started,
667 spawned,
668 };
669 self.run_cleanup(spec, &cleanup, shared).await
670 }
671
672 async fn run_cleanup(
676 &self,
677 spec: &AttemptSpec,
678 cleanup: &TaskCleanup,
679 shared: Shared<'_>,
680 ) -> pb::CleanupResult {
681 shared.handles.close();
682 let mut spec = spec.clone();
683 spec.task.outcomes = default_outcomes();
684 match (&mut spec.task.kind, &cleanup.run) {
685 (
686 TaskKind::Command {
687 command, resource, ..
688 },
689 CleanupRun::Command(line),
690 ) => {
691 command.clone_from(line);
692 *resource = None;
694 }
695 (TaskKind::Script { .. }, CleanupRun::Script { .. }) => {
696 use_cleanup_script(&mut spec.task);
697 }
698 (TaskKind::Python { .. }, CleanupRun::Python) => {
699 spec.cleanup_handles = Some(shared.handles.list());
700 }
701 _ => {
703 let message = "the task's cleanup doesn't match its kind";
704 return pb::CleanupResult {
705 status: pb::CleanupStatus::Failed.into(),
706 error_kind: "invalid_cleanup".to_owned(),
707 error_summary_json: ErrorSummary::json("InvalidCleanup", message).into_bytes(),
708 ..pb::CleanupResult::default()
709 };
710 }
711 }
712 let log = self.setup.log_file(&spec.attempt_id);
713 let timeout = cleanup
714 .timeout_ms
715 .map_or(self.setup.timeouts.cleanup, Duration::from_millis);
716 let mut result = pb::CleanupResult::default();
717 for try_number in 1..=cleanup.retries.saturating_add(1) {
718 if try_number > 1 {
719 tokio::time::sleep(Duration::from_millis(cleanup.retry_delay_ms)).await;
720 }
721 append_log(&log, &format!("cleanup: try {try_number}\n")).await;
722 let planned = match &spec.code_dir {
723 Some(dir) => plan_at(&spec, &self.setup, dir),
724 None => crate::attempt::plan(&spec, &self.setup),
725 };
726 let (_sender, stops) = Stops::new();
727 let mut ended = match planned {
728 Ok(plan) => {
729 let python = matches!(plan, Plan::Python { .. });
730 let mut ended = self
731 .run_planned(&spec, plan, Some(timeout), stops, shared)
732 .await;
733 ended_with_secrets(&mut ended, shared.secrets, python);
734 ended
735 }
736 Err(NotRun::Failed { kind, message }) => {
737 failed_before_start(&spec.attempt_id, &kind, &message)
738 }
739 Err(NotRun::Rejected { detail, .. }) => {
740 failed_before_start(&spec.attempt_id, DAG_FILE_MISSING, &detail)
741 }
742 };
743 result.tries = try_number;
744 result.duration_ms += ended.duration_ms.unwrap_or(0);
745 if ended.status == i32::from(pb::AttemptStatus::Success) {
746 result.status = pb::CleanupStatus::Ok.into();
747 result.error_kind.clear();
748 result.error_summary_json.clear();
749 return result;
750 }
751 result.status = pb::CleanupStatus::Failed.into();
752 result.error_kind = std::mem::take(&mut ended.error_kind);
753 result.error_summary_json = std::mem::take(&mut ended.error_summary_json);
754 }
755 result
756 }
757
758 fn watched(&self, spec: &AttemptSpec) -> (SharedSeen, crate::memory::Watched) {
761 let seen = SharedSeen::default();
762 let watched = self.running_memory.watch(
763 schedr_model::usage::TaskMemory {
764 attempt_id: spec.attempt_id.clone(),
765 dag_id: spec.run.dag_id.clone(),
766 run_id: spec.run.run_id.clone(),
767 task_id: spec.task.id.to_string(),
768 map_index: spec.run.map_index,
769 bytes: 0,
770 },
771 seen.clone(),
772 );
773 (seen, watched)
774 }
775
776 fn command_ctx(
778 &self,
779 spec: &AttemptSpec,
780 (secrets, handles): (&Arc<AttemptSecrets>, &Arc<AttemptHandles>),
781 resource: Option<&Arc<AttemptResource>>,
782 ) -> CtxInfo {
783 let mut ctx = CtxInfo::of(&spec.run, AGENT_VERSION);
784 ctx.max_connections = self.setup.timeouts.task_connections_open;
785 (ctx.secrets, ctx.handles) = (Some(Arc::clone(secrets)), Some(Arc::clone(handles)));
786 ctx.resource = resource.cloned();
787 ctx.api.clone_from(&spec.api);
788 ctx
789 }
790
791 async fn run_planned(
792 &self,
793 spec: &AttemptSpec,
794 plan: Plan,
795 timeout: Option<Duration>,
796 stop: Stops,
797 shared: Shared<'_>,
798 ) -> pb::Finished {
799 let Shared {
800 secrets,
801 handles,
802 started,
803 spawned: shared_spawned,
804 } = shared;
805 let limits = Limits {
806 timeout,
807 grace: spec.cancel_grace,
808 interrupt_grace: self.drain_terminate_period,
809 poll: self.setup.timeouts.stop_poll,
810 };
811 let (seen, _reported) = self.watched(spec);
812 let memory = self.setup.memory.for_task(spec.task.settings.memory_bytes);
813 let oom = stop.sender();
815 let mut hold = None;
818 let mut watching = None;
819 let spawned = |pid, forked| {
820 started.store(true, Ordering::SeqCst);
821 watching = Some(watch_group(
823 memory.clone(),
824 pid,
825 seen.clone(),
826 oom,
827 self.metrics.watchdog_kills.clone(),
828 forked,
829 ));
830 match process_identity(pid) {
831 Ok(identity) => shared_spawned(identity, forked),
832 Err(error) => warn_unidentified(pid, &error),
833 }
834 };
835 let resource =
836 AttemptResource::of(&spec.task, &spec.inputs, Arc::clone(&secrets.mask)).map(Arc::new);
837 let python_task = |request| PythonTask {
838 request,
839 secrets: Some(Arc::clone(secrets)),
840 handles: Some(Arc::clone(handles)),
841 events: None,
842 api: spec.api.clone(),
843 };
844 let ran = match plan {
845 Plan::Python { process, request }
847 if matches!(request.task.kind, schedr_model::TaskKind::Sensor { .. }) =>
848 {
849 let mut task = python_task(*request);
850 task.events = spec.trigger.as_ref().map(|(_, sink)| sink.clone());
851 crate::watchers::run_watcher(
852 &self.watchers,
853 &self.setup,
854 &process,
855 task,
856 limits,
857 stop,
858 |pid| {
859 started.store(true, Ordering::SeqCst);
860 match process_identity(pid) {
861 Ok(identity) => shared_spawned(identity, false),
862 Err(error) => warn_unidentified(pid, &error),
863 }
864 },
865 )
866 .await
867 }
868 Plan::Python { process, request } => {
869 let forks = self.forks.as_ref();
870 let task = python_task(*request);
871 run_python(&process, task, limits, stop, forks, &mut hold, spawned).await
872 }
873 Plan::Command(process) => {
874 let ctx = self.command_ctx(spec, (secrets, handles), resource.as_ref());
875 run_command(&process, Some(ctx), limits, stop, |pid| spawned(pid, false)).await
876 }
877 };
878 drop(watching);
881 drop(hold);
882 if let Ok(Ran {
883 start: Some(start),
884 forked,
885 ..
886 }) = &ran
887 {
888 self.metrics
889 .task_started(if *forked { "fork" } else { "spawn" }, start);
890 }
891 let mut finished = match ran {
892 Ok(ran) => finished(&spec.attempt_id, &spec.task, &ran),
893 Err(error) => failed_before_start(&spec.attempt_id, START_FAILED, &error.to_string()),
894 };
895 if let Some(outcome) = resource.as_ref().and_then(|r| r.outcome()) {
896 with_resource_value(&mut finished, outcome);
897 }
898 let seen = *seen.lock().unwrap_or_else(PoisonError::into_inner);
899 with_memory(&mut finished, seen, memory.budget);
900 finished
901 }
902
903 async fn parse_files(
904 &self,
905 root: String,
906 dir: PathBuf,
907 files: Vec<String>,
908 code: ParseCode,
909 ) -> Result<Vec<ParsedFile>, String> {
910 let searched = dir.clone();
912 let files =
913 tokio::task::spawn_blocking(move || crate::scan::split_dag_files(&searched, files).0)
914 .await
915 .map_err(|e| e.to_string())?;
916 if files.is_empty() {
917 return Ok(Vec::new());
918 }
919 let _ = tokio::fs::create_dir_all(&self.setup.log_dir).await;
920 let runner = ProcessParseRunner {
921 process: ProcessSpec {
922 program: self.setup.python.clone(),
923 args: vec![
924 "-P".to_owned(),
926 "-m".to_owned(),
927 "schedr.runner".to_owned(),
928 "parse".to_owned(),
929 ],
930 env: self
931 .setup
932 .agent_env
933 .iter()
934 .filter(|(name, _)| {
936 crate::env::is_allowed(name) || self.setup.pass_env.contains(name)
937 })
938 .map(|(k, v)| (k.clone(), v.clone()))
939 .collect(),
940 working_dir: dir.clone(),
941 log_file: self.setup.log_dir.join(format!("parse-{root}.log")),
942 max_output_size: 64 * 1024,
943 mask: crate::mask::Mask::default(),
944 start_timeout: self.setup.timeouts.runner_start,
945 output_drain: self.setup.timeouts.output_drain,
946 },
947 memory: self.setup.memory.clone(),
948 kills: self.metrics.watchdog_kills.clone(),
949 forks: self.forks.clone(),
950 };
951 let mut copies = code.roots;
952 copies.insert(root.clone(), dir.clone());
953 let request = ParseRequest {
954 sys_path: self.setup.sys_path_at(&copies),
955 root,
956 root_dir: dir.to_string_lossy().into_owned(),
957 files,
958 };
959 crate::parse::parse_files_with(&runner, request, self.parse, &code.scripts)
960 .await
961 .map_err(|e| e.to_string())
962 }
963}
964
965fn with_code_hash(finished: &mut pb::Finished, started_on: String) {
968 if finished.code_hash.is_empty() {
969 finished.code_hash = started_on;
970 }
971}
972
973pub fn with_memory(finished: &mut pb::Finished, seen: MemorySeen, budget: Option<u64>) {
976 finished.peak_memory_bytes = seen.peak;
977 if let (Some(used), Some(budget)) = (seen.over, budget)
978 && finished.status == i32::from(pb::AttemptStatus::OomKilled)
979 {
980 finished.error_summary_json =
981 ErrorSummary::json(MEMORY_EXCEPTION, &over_budget_message(budget, used)).into_bytes();
982 }
983}
984
985pub const ALIVE_INTERVAL: Duration = Duration::from_secs(5);
987
988pub const MAX_RESEND_GAP: u32 = 32;
992
993pub const LARGEST_TASKS: usize = 5;
996
997pub const MAX_RESENDS: u32 = 8;
1001
1002pub const MEMORY_EXCEPTION: &str = "MemoryBudgetExceeded";
1004
1005#[derive(Debug, Clone, PartialEq, Eq)]
1007pub enum SessionEnd {
1008 Stopped,
1010 Lost(String),
1012}
1013
1014pub const RESULTS_PER_GROUP: usize = 32;
1018
1019async fn next_inbound(
1021 held: &mut Option<Result<Option<pb::MasterMessage>, tonic::Status>>,
1022 inbound: &mut tonic::Streaming<pb::MasterMessage>,
1023) -> Result<Option<pb::MasterMessage>, tonic::Status> {
1024 if let Some(message) = held.take() {
1025 return message;
1026 }
1027 inbound.message().await
1028}
1029
1030pub const STARTS_PER_GROUP: usize = 32;
1033
1034struct Prepared {
1036 assign: pb::AssignTask,
1037 spec: AttemptSpec,
1038 planned: Result<Plan, NotRun>,
1039 external: Option<Vec<u8>>,
1040 received: std::time::Instant,
1041}
1042
1043#[derive(Default)]
1046struct Held {
1047 tasks: u32,
1048 wait_steps: u32,
1049 ids: std::collections::HashSet<String>,
1050}
1051
1052impl Held {
1053 fn add(&mut self, prepared: &Prepared) {
1054 self.ids.insert(prepared.assign.attempt_id.clone());
1055 if matches!(prepared.planned, Err(NotRun::Rejected { .. })) {
1056 return;
1057 }
1058 if assigned_a_wait_step(&prepared.assign) {
1059 self.wait_steps += 1;
1060 } else {
1061 self.tasks += 1;
1062 }
1063 }
1064}
1065
1066enum Done {
1067 Spawned {
1068 attempt_id: String,
1069 identity: ProcessIdentity,
1070 forked: bool,
1071 },
1072 TaskEnded(pb::Finished),
1074 Handle {
1076 attempt_id: String,
1077 position: u32,
1078 handle: CleanupHandle,
1079 },
1080 Attempt(pb::Finished),
1081 Trigger(TriggerDone),
1082 ApiCall {
1084 call: pb::ApiCall,
1085 answer: oneshot::Sender<pb::ApiAnswer>,
1086 },
1087 Parse {
1088 job_id: String,
1089 root: pb::RootHash,
1090 copies: Vec<String>,
1092 files: Result<Vec<ParsedFile>, String>,
1093 },
1094 Connections {
1095 job_id: String,
1096 hash: Option<String>,
1098 attempt_id: Option<String>,
1100 reports: Vec<schedr_model::commands::ConnectionReport>,
1101 },
1102}
1103
1104#[derive(Debug)]
1106struct WaitingCleanup {
1107 spec: AttemptSpec,
1108 handles: Vec<CleanupHandle>,
1109 ended: Option<pb::Finished>,
1111 rest: bool,
1113}
1114
1115pub const UNSENT_ANSWERS: usize = 16;
1117
1118#[derive(Debug)]
1120pub struct Agent<E> {
1121 settings: AgentSettings,
1122 executor: E,
1123 incarnation: String,
1124 journal: Journal,
1125 master_time: MasterTime,
1127 leader_epoch: (i64, Option<tokio::time::Instant>),
1132 clock_skew: Option<pb::WorkerWarning>,
1135 carried_cutoff: Option<tokio::time::Instant>,
1139 sample_sent: Option<Duration>,
1142 #[cfg(test)]
1145 journal_stall: (Duration, Arc<std::sync::atomic::AtomicUsize>),
1146 watchers: BTreeMap<String, RootWatcher>,
1147 triggers: BTreeMap<String, RunningTrigger>,
1150 triggers_ended: BTreeMap<String, pb::TriggerStopped>,
1153 running: BTreeMap<String, StopSender>,
1155 forked: BTreeSet<String>,
1159 wait_steps: BTreeMap<String, bool>,
1161 cleaning: BTreeMap<String, pb::Finished>,
1163 waiting: BTreeMap<String, WaitingCleanup>,
1166 cleanup_room: BTreeMap<String, Duration>,
1168 stopped: std::collections::BTreeSet<String>,
1170 gates: BTreeMap<String, watch::Sender<Gate>>,
1172 rest_cleaning: BTreeSet<String>,
1174 heard: tokio::time::Instant,
1176 deadline: watch::Sender<Option<tokio::time::Instant>>,
1178 lease: Option<Duration>,
1180 cut_off: bool,
1182 warned_room: std::collections::BTreeSet<(String, String)>,
1184 unacked: BTreeMap<String, pb::Finished>,
1185 unsent_answers: std::collections::VecDeque<pb::ConnectionJobDone>,
1188 api_calls: BTreeMap<u64, (pb::ApiCall, oneshot::Sender<pb::ApiAnswer>)>,
1190 api_call_id: u64,
1192 code_hashes: BTreeMap<String, String>,
1194 other_copies: BTreeMap<String, Vec<String>>,
1197 uses: BTreeMap<String, std::collections::BTreeSet<String>>,
1199 reported: BTreeMap<String, String>,
1202 parsing: BTreeMap<String, usize>,
1204 parses_running: BTreeSet<(String, String)>,
1208 connection_jobs: Arc<tokio::sync::Mutex<()>>,
1210 done_tx: mpsc::UnboundedSender<Done>,
1211 done_rx: mpsc::UnboundedReceiver<Done>,
1212 warnings: watch::Receiver<Vec<pb::WorkerWarning>>,
1214 heartbeat: Duration,
1215 registered: bool,
1217 master_limit: usize,
1219 shutdown: Option<watch::Receiver<u32>>,
1221 drain: Option<Drain>,
1223 beat: Beat,
1225 metrics: AgentMetrics,
1226}
1227
1228async fn command_connections(
1231 secrets: &AttemptSecrets,
1232 given: &BTreeMap<String, String>,
1233) -> Result<BTreeMap<String, String>, (&'static str, String)> {
1234 let mut variables: BTreeMap<String, String> = BTreeMap::new();
1235 let mut from: BTreeMap<String, &str> = BTreeMap::new();
1236 for (prefix, name) in given {
1237 let more = secrets
1238 .connection_env(name, prefix)
1239 .await
1240 .map_err(|e| (e.kind(), e.to_string()))?;
1241 for (variable, value) in more {
1242 if let Some(other) = from.insert(variable.clone(), prefix) {
1243 return Err((
1244 crate::attempt::RENDER_FAILED,
1245 format!(
1246 "`{variable}` is a variable of the connections given as {other} and as \
1247 {prefix}: use prefixes that don't start one another"
1248 ),
1249 ));
1250 }
1251 variables.insert(variable, value);
1252 }
1253 }
1254 Ok(variables)
1255}
1256
1257async fn remove_connection_files(dir: &Path) {
1259 match tokio::fs::remove_dir_all(dir).await {
1260 Ok(()) => {}
1261 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1262 Err(error) => {
1263 tracing::warn!(dir = %dir.display(), %error, "can't remove an attempt's connection files");
1264 }
1265 }
1266}
1267
1268async fn sweep_connection_files(dir: &Path, alive: &std::collections::BTreeSet<String>) {
1271 let mut entries = match tokio::fs::read_dir(dir).await {
1272 Ok(entries) => entries,
1273 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
1274 Err(error) => {
1275 tracing::warn!(dir = %dir.display(), %error, "can't read the connection files' folder");
1276 return;
1277 }
1278 };
1279 while let Ok(Some(entry)) = entries.next_entry().await {
1280 let name = entry.file_name().to_string_lossy().into_owned();
1281 if !alive.contains(&name) {
1282 remove_connection_files(&entry.path()).await;
1283 }
1284 }
1285}
1286
1287impl<E: Executor> Agent<E> {
1288 #[must_use]
1290 pub fn new(settings: AgentSettings, executor: E, incarnation: String) -> Self {
1291 let unacked_kept = settings.setup.timeouts.unacked_messages_kept;
1292 let sample_window = settings.setup.timeouts.master_sample_window;
1293 let watchers = settings
1294 .setup
1295 .roots
1296 .iter()
1297 .chain(&settings.setup.script_roots)
1298 .map(|(name, dir)| {
1299 let store = settings.code_dir.join(code_folder(name));
1300 (
1301 name.clone(),
1302 RootWatcher::new(dir, store, settings.settle_time),
1303 )
1304 })
1305 .collect();
1306 let (done_tx, done_rx) = mpsc::unbounded_channel();
1307 let journal = Journal::new(settings.journal_dir.clone());
1308 let warnings = executor.warnings();
1309 Self {
1310 settings,
1311 executor,
1312 master_time: MasterTime::with_window(sample_window).keeping(unacked_kept),
1313 leader_epoch: (0, None),
1314 clock_skew: None,
1315 carried_cutoff: None,
1316 sample_sent: None,
1317 #[cfg(test)]
1318 journal_stall: (Duration::ZERO, Arc::default()),
1319 warnings,
1320 incarnation,
1321 journal,
1322 watchers,
1323 running: BTreeMap::new(),
1324 forked: BTreeSet::new(),
1325 triggers: BTreeMap::new(),
1326 triggers_ended: BTreeMap::new(),
1327 wait_steps: BTreeMap::new(),
1328 cleaning: BTreeMap::new(),
1329 waiting: BTreeMap::new(),
1330 cleanup_room: BTreeMap::new(),
1331 stopped: std::collections::BTreeSet::new(),
1332 gates: BTreeMap::new(),
1333 rest_cleaning: BTreeSet::new(),
1334 heard: tokio::time::Instant::now(),
1335 deadline: watch::channel(None).0,
1336 lease: None,
1337 cut_off: false,
1338 warned_room: std::collections::BTreeSet::new(),
1339 unacked: BTreeMap::new(),
1340 unsent_answers: std::collections::VecDeque::new(),
1341 api_calls: BTreeMap::new(),
1342 api_call_id: first_api_call_id(),
1343 code_hashes: BTreeMap::new(),
1344 other_copies: BTreeMap::new(),
1345 uses: BTreeMap::new(),
1346 reported: BTreeMap::new(),
1347 parsing: BTreeMap::new(),
1348 parses_running: BTreeSet::new(),
1349 connection_jobs: Arc::new(tokio::sync::Mutex::new(())),
1350 done_tx,
1351 done_rx,
1352 heartbeat: Duration::from_secs(10),
1353 registered: false,
1354 master_limit: GRPC_DEFAULT_LIMIT,
1355 shutdown: None,
1356 drain: None,
1357 beat: Beat::default(),
1358 metrics: AgentMetrics::default(),
1359 }
1360 .with_metrics(AgentMetrics::default())
1361 }
1362
1363 #[must_use]
1365 pub fn with_metrics(mut self, metrics: AgentMetrics) -> Self {
1366 metrics.slots.set(i64::from(self.settings.slots));
1367 metrics
1368 .watchers
1369 .slots
1370 .set(i64::from(self.settings.watcher_slots));
1371 self.metrics = metrics;
1372 self
1373 }
1374
1375 #[must_use]
1378 pub fn beat(&self) -> Beat {
1379 self.beat.clone()
1380 }
1381
1382 fn alive(&self) {
1384 self.beat.beat();
1385 self.set_slot_gauges();
1386 }
1387
1388 fn set_slot_gauges(&self) {
1390 let running = i64::try_from(self.running.len()).unwrap_or(i64::MAX);
1391 let unacked = i64::try_from(self.unacked.len()).unwrap_or(i64::MAX);
1392 self.metrics
1393 .slots_used
1394 .set(i64::try_from(self.tasks_running()).unwrap_or(i64::MAX));
1395 self.metrics
1396 .watchers
1397 .slots_used
1398 .set(i64::try_from(self.wait_steps.len()).unwrap_or(i64::MAX));
1399 self.metrics.journal_records.set(running + unacked);
1400 }
1401
1402 #[must_use]
1404 pub fn running(&self) -> Vec<String> {
1405 self.running.keys().cloned().collect()
1406 }
1407
1408 pub async fn run<C, F>(&mut self, connect: C, mut shutdown: watch::Receiver<u32>)
1413 where
1414 C: Fn() -> F,
1415 F: Future<Output = Result<MasterClient<Channel>, String>>,
1416 {
1417 let requested = *shutdown.borrow_and_update();
1418 self.shutdown = Some(shutdown);
1419 self.recover().await;
1420 self.on_shutdown(requested);
1421 let timeouts = self.settings.setup.timeouts;
1422 let mut backoff = timeouts.reconnect_first;
1423 loop {
1424 self.registered = false;
1425 let Some(connected) = self.offline(connect()).await else {
1426 return;
1427 };
1428 let end = match connected {
1429 Ok(client) => self.session(client).await,
1430 Err(error) => SessionEnd::Lost(error),
1431 };
1432 match end {
1433 SessionEnd::Stopped => return,
1434 SessionEnd::Lost(reason) => {
1435 tracing::warn!(reason, "master connection lost; connecting again");
1436 self.hold_cleanups();
1437 }
1438 }
1439 if self.registered {
1440 backoff = timeouts.reconnect_first;
1441 }
1442 let seed = std::time::SystemTime::now()
1445 .duration_since(std::time::UNIX_EPOCH)
1446 .map_or(0, |d| d.subsec_nanos())
1447 .wrapping_mul(2_654_435_761);
1448 if self
1449 .offline(tokio::time::sleep(jittered(
1450 backoff.min(reconnect_cap(timeouts.reconnect_max, self.lease)),
1451 seed,
1452 )))
1453 .await
1454 .is_none()
1455 {
1456 return;
1457 }
1458 backoff = (backoff * 2).min(reconnect_cap(timeouts.reconnect_max, self.lease));
1459 }
1460 }
1461
1462 async fn offline<T>(&mut self, work: impl Future<Output = T>) -> Option<T> {
1465 self.waiting_for(work, false).await
1466 }
1467
1468 async fn waiting_for<T>(
1472 &mut self,
1473 work: impl Future<Output = T>,
1474 connecting: bool,
1475 ) -> Option<T> {
1476 tokio::pin!(work);
1477 let timeouts = self.settings.setup.timeouts;
1478 let mut tick = tokio::time::interval(timeouts.drain_tick);
1479 let mut alive = tokio::time::interval(timeouts.alive);
1480 loop {
1481 let cut_off_at = self.cut_off_at();
1482 tokio::select! {
1483 _ = alive.tick() => self.on_alive(),
1484 () = at(cut_off_at) => self.stop_cut_off(),
1485 out = &mut work => return Some(out),
1486 Some(done) = self.done_rx.recv() => self.on_done_group(done, None, None).await,
1487 count = next_request(&mut self.shutdown) => {
1488 self.on_shutdown(count);
1489 }
1490 _ = tick.tick(), if self.drain.is_some() => {
1491 if self.drain_step(connecting) == DrainStep::Finish {
1492 return None;
1493 }
1494 }
1495 }
1496 }
1497 }
1498
1499 async fn fetch_with_timers(
1504 &mut self,
1505 client: &mut MasterClient<Channel>,
1506 attempt_id: &str,
1507 to_master: &ToMaster,
1508 (heartbeat, opened): (&mut tokio::time::Interval, tokio::time::Instant),
1509 ) -> Option<Result<Vec<u8>, String>> {
1510 let (heard, seen) = watch::channel(self.heard.max(opened));
1511 let fetching = fetch_inputs(client, attempt_id, &heard, self.lease);
1512 tokio::pin!(fetching);
1513 loop {
1514 self.heard = self.heard.max(*seen.borrow());
1515 self.publish_deadline();
1516 let give_up_at = earliest(self.cut_off_at(), self.silent_at(opened));
1517 tokio::select! {
1518 fetched = &mut fetching => {
1519 return match fetched {
1520 Fetched::Bytes(bytes) => Some(Ok(bytes)),
1521 Fetched::Failed(error) => Some(Err(error)),
1522 Fetched::Silent => {
1523 self.cut_off_if_late();
1524 None
1525 }
1526 };
1527 }
1528 _ = heartbeat.tick() => {
1529 self.send_beat(to_master);
1530 self.send_poke_reports(to_master);
1531 }
1532 () = at(give_up_at) => {
1533 self.heard = self.heard.max(*seen.borrow());
1534 if self.silent_too_long(opened) {
1535 return None;
1536 }
1537 }
1538 }
1539 }
1540 }
1541
1542 fn answer_too_late(message: &master_message::Message, age: Duration) -> bool {
1547 let master_message::Message::Registered(registered) = message else {
1548 return false;
1549 };
1550 registered.timing.as_ref().is_some_and(|t| {
1551 t.lease_timeout_ms > 0 && age.as_millis() >= u128::from(t.lease_timeout_ms)
1552 })
1553 }
1554
1555 fn drain_running(&self) -> usize {
1558 let held = self
1559 .gates
1560 .iter()
1561 .filter(|(id, gate)| *gate.borrow() == Gate::Held && self.cleaning.contains_key(*id))
1562 .count();
1563 self.running
1564 .len()
1565 .saturating_add(self.triggers.len())
1566 .saturating_sub(self.waiting.len().saturating_add(held))
1567 }
1568
1569 fn send_state(&mut self, to_master: &ToMaster) {
1571 if self.drain.is_some() {
1572 let _ = to_master.send(wrap(worker_message::Message::Draining(pb::Draining {})));
1573 }
1574 self.report_warnings(to_master);
1576 }
1577
1578 fn report_warnings(&mut self, to_master: &ToMaster) {
1580 let mut warnings = self.warnings.borrow_and_update().clone();
1581 warnings.extend(self.clock_skew.clone());
1582 let _ = to_master.send(wrap(worker_message::Message::Warnings(pb::Warnings {
1583 warnings,
1584 })));
1585 }
1586
1587 fn register_message(&self, roots: Vec<pb::RootHash>) -> pb::Register {
1589 pb::Register {
1590 worker_id: self.settings.worker_id.clone(),
1591 incarnation_id: self.incarnation.clone(),
1592 protocol: Some(PROTOCOL_VERSION),
1593 schedr_version: AGENT_VERSION.to_owned(),
1594 queues: self.settings.queues.clone(),
1595 slots: self.settings.slots,
1596 watcher_slots: self.settings.watcher_slots,
1597 running_triggers: self
1598 .triggers
1599 .keys()
1600 .chain(self.triggers_ended.keys())
1601 .cloned()
1602 .collect(),
1603 log_endpoint: self.settings.log_endpoint.clone(),
1604 roots,
1605 secret_storages: self.settings.secrets.names(),
1606 journal: self.journal_entries(),
1607 process_id: self.settings.node.process_id.clone(),
1608 config_json: self.settings.node.config_json.clone(),
1609 }
1610 }
1611
1612 fn set_gate(&mut self, spec: &mut AttemptSpec) {
1614 if spec.task.cleanup.as_ref().is_some_and(|c| c.anywhere) {
1615 let (gate, passes) = watch::channel(Gate::Open);
1616 self.gates.insert(spec.attempt_id.clone(), gate);
1617 spec.cleanup_gate = Some(CleanupGate {
1618 gate: passes,
1619 deadline: self.deadline.subscribe(),
1620 });
1621 }
1622 }
1623
1624 fn publish_deadline(&self) {
1626 let deadline = self.lease_deadline();
1627 self.deadline.send_if_modified(|now| {
1628 let changed = *now != deadline;
1629 *now = deadline;
1630 changed
1631 });
1632 }
1633
1634 fn cut_off_at(&self) -> Option<tokio::time::Instant> {
1637 if self.cut_off || self.gates.is_empty() {
1638 return None;
1639 }
1640 self.lease_deadline()
1641 }
1642
1643 fn lease_deadline(&self) -> Option<tokio::time::Instant> {
1648 let lease = self.lease?;
1649 let received = self.heard + lease;
1650 Some(
1651 self.master_cutoff(lease)
1652 .map_or(received, |at| at.min(received)),
1653 )
1654 }
1655
1656 fn master_cutoff(&self, lease: Duration) -> Option<tokio::time::Instant> {
1658 let now = tokio::time::Instant::now();
1659 let by_master = self
1660 .master_time
1661 .cutoff_in(lease, Local::now())
1662 .map(|wait| now + wait);
1663 match (by_master, self.carried_cutoff) {
1664 (Some(at), Some(carried)) => Some(at.min(carried)),
1665 (at, carried) => at.or(carried),
1666 }
1667 }
1668
1669 fn open_session(&mut self) -> tokio::time::Instant {
1672 self.carried_cutoff = self.lease.and_then(|lease| self.master_cutoff(lease));
1673 self.clock_skew = None;
1674 self.master_time.open()
1675 }
1676
1677 fn on_alive(&mut self) {
1680 self.alive();
1681 self.publish_master_reading();
1682 self.publish_deadline();
1683 self.cut_off_if_late();
1684 }
1685
1686 fn silent_at(&self, opened: tokio::time::Instant) -> Option<tokio::time::Instant> {
1691 self.lease.map(|lease| self.heard.max(opened) + lease)
1692 }
1693
1694 fn silent_too_long(&mut self, opened: tokio::time::Instant) -> bool {
1697 let silent = self.gone_silent(opened);
1698 self.cut_off_if_late() || silent
1699 }
1700
1701 fn gone_silent(&self, opened: tokio::time::Instant) -> bool {
1703 self.silent_at(opened)
1704 .is_some_and(|at| at <= tokio::time::Instant::now())
1705 }
1706
1707 fn cut_off_if_late(&mut self) -> bool {
1710 let late = self
1711 .cut_off_at()
1712 .is_some_and(|at| at <= tokio::time::Instant::now());
1713 if late {
1714 self.stop_cut_off();
1715 }
1716 late
1717 }
1718
1719 fn stop_cut_off(&mut self) {
1722 self.cut_off = true;
1723 self.hold_cleanups();
1724 for trigger in self.triggers.values() {
1726 let _ = trigger.stop.send(StopReason::CutOff);
1727 }
1728 for id in self.gates.keys() {
1729 if !self.cleaning.contains_key(id)
1730 && let Some(stop) = self.running.get(id)
1731 {
1732 tracing::warn!(
1733 attempt_id = id,
1734 "no word from the master: stopping the task"
1735 );
1736 let _ = stop.send(StopReason::CutOff);
1737 }
1738 }
1739 }
1740
1741 fn hold_cleanups(&self) {
1744 for gate in self.gates.values() {
1745 gate.send_if_modified(|gate| {
1746 let open = *gate == Gate::Open;
1747 if open {
1748 *gate = Gate::Held;
1749 }
1750 open
1751 });
1752 }
1753 }
1754
1755 fn on_shutdown(&mut self, count: u32) -> bool {
1758 let now = Instant::now();
1759 if let Some(drain) = &mut self.drain {
1760 drain.force(now);
1761 tracing::warn!("asked to stop again: interrupting the running tasks");
1762 return false;
1763 }
1764 if count == 0 {
1765 return false;
1766 }
1767 let mut drain = Drain::new(now, self.settings.drain);
1768 if count > 1 {
1769 drain.force(now);
1770 }
1771 self.drain = Some(drain);
1772 tracing::info!(
1773 running = self.running.len(),
1774 grace = ?self.settings.drain.grace,
1775 "draining: no new tasks; the running ones get until the grace period ends"
1776 );
1777 true
1778 }
1779
1780 fn drain_step(&mut self, connected: bool) -> DrainStep {
1782 let running = self.drain_running();
1783 let Some(drain) = &mut self.drain else {
1784 return DrainStep::Wait;
1785 };
1786 let now = Instant::now();
1787 let step = drain.step(now, running, self.unacked.len(), connected);
1788 for trigger in self.triggers.values() {
1790 let _ = trigger.stop.send(StopReason::Interrupted);
1791 }
1792 for (id, stop) in &self.running {
1796 let room = self.cleanup_room.get(id).copied().unwrap_or_default();
1797 let poke = self.wait_steps.get(id).copied().unwrap_or(false);
1799 if !self.cleaning.contains_key(id)
1800 && (poke || drain.stop_due(now, room))
1801 && self.stopped.insert(id.clone())
1802 {
1803 let _ = stop.send(StopReason::Interrupted);
1804 }
1805 }
1806 if step == DrainStep::Interrupt {
1807 tracing::warn!(
1808 running = self.running.len(),
1809 "the grace period is ending: interrupting the running tasks"
1810 );
1811 }
1812 step
1813 }
1814
1815 pub async fn recover(&mut self) {
1820 let journal = self.journal.clone();
1821 let records = match tokio::task::spawn_blocking(move || journal.recover()).await {
1822 Ok(Ok(records)) => records,
1823 Ok(Err(error)) => {
1824 tracing::error!(dir = %self.journal.dir().display(), %error, "can't read the journal");
1825 return;
1826 }
1827 Err(error) => {
1828 tracing::error!(%error, "reading the journal failed");
1829 return;
1830 }
1831 };
1832 let mut orphans = tokio::task::JoinSet::new();
1833 let mut ended = BTreeMap::new();
1834 for (attempt_id, record) in records {
1835 let process = match record {
1836 JournalRecord::Finished(finished) => {
1837 self.unacked.insert(attempt_id, finished);
1838 continue;
1839 }
1840 JournalRecord::Running(process) => process,
1841 JournalRecord::Cleaning(finished, process) => {
1842 ended.insert(attempt_id.clone(), finished);
1843 process
1844 }
1845 };
1846 let timeouts = self.settings.setup.timeouts;
1847 orphans.spawn(async move {
1848 let Some(identity) = process else {
1849 return Ok(attempt_id);
1850 };
1851 match stop_orphan(identity, timeouts.orphan_grace, timeouts.orphan).await {
1852 Ok(Orphan::Gone) => {}
1853 Ok(how) => tracing::warn!(
1854 attempt_id,
1855 pgid = identity.pgid,
1856 ?how,
1857 "stopped a task process left by the previous agent"
1858 ),
1859 Err(error) => {
1860 tracing::error!(
1862 attempt_id,
1863 pgid = identity.pgid,
1864 %error,
1865 "can't stop a task process left by the previous agent"
1866 );
1867 return Err(attempt_id);
1868 }
1869 }
1870 Ok(attempt_id)
1871 });
1872 }
1873 let mut alive = std::collections::BTreeSet::new();
1874 while let Some(stopped) = orphans.join_next().await {
1875 match stopped {
1876 Ok(Ok(attempt_id)) => {
1877 let ended = ended.remove(&attempt_id);
1878 if !self.wait_for_cleanup(&attempt_id, ended).await {
1879 self.forget(&attempt_id).await;
1880 }
1881 }
1882 Ok(Err(attempt_id)) => {
1883 alive.insert(attempt_id);
1884 }
1885 Err(_) => {}
1886 }
1887 }
1888 sweep_connection_files(&self.settings.setup.connection_dir, &alive).await;
1889 }
1890
1891 async fn wait_for_cleanup(&mut self, attempt_id: &str, ended: Option<pb::Finished>) -> bool {
1894 let journal = self.journal.clone();
1895 let id = attempt_id.to_owned();
1896 let read = tokio::task::spawn_blocking(move || {
1897 Ok::<_, std::io::Error>((journal.kept(&id)?, journal.handles(&id)?))
1898 })
1899 .await;
1900 let (kept, journaled) = match read {
1901 Ok(Ok((Some(kept), handles))) => (kept, handles),
1902 Ok(Ok((None, _))) => return false,
1903 Ok(Err(error)) => {
1906 tracing::error!(attempt_id, %error, "can't read a kept attempt; no cleanup here");
1907 return false;
1908 }
1909 Err(error) => {
1910 tracing::error!(attempt_id, %error, "reading a kept attempt failed");
1911 return false;
1912 }
1913 };
1914 let handles = match kept.assign.cleanup_only.as_ref().map(moved_handles) {
1916 None => journaled,
1917 Some(Ok(handles)) => handles,
1918 Some(Err(error)) => {
1919 tracing::error!(attempt_id, %error, "a moved cleanup's handles don't read");
1920 return false;
1921 }
1922 };
1923 let mut spec = match AttemptSpec::from_assign(&kept.assign, None) {
1924 Ok(spec) if spec.task.cleanup.is_some() => spec,
1925 Ok(_) => return false,
1926 Err(error) => {
1927 tracing::warn!(attempt_id, %error, "can't read a kept attempt; its cleanup is lost");
1928 return false;
1929 }
1930 };
1931 spec.code_dir = kept.code_dir;
1932 spec.root_copies = kept.root_copies;
1933 spec.script_dir = kept.script_dir;
1934 if let Some(hash) = kept.code_hash {
1935 self.code_hashes.insert(attempt_id.to_owned(), hash);
1936 }
1937 self.remember_other_copies(&spec);
1938 let (stop, _) = Stops::new();
1939 self.running.insert(attempt_id.to_owned(), stop);
1940 let waiting = WaitingCleanup {
1941 spec,
1942 handles,
1943 ended,
1944 rest: false,
1945 };
1946 self.waiting.insert(attempt_id.to_owned(), waiting);
1947 true
1948 }
1949
1950 async fn start_waiting(
1953 &mut self,
1954 attempt_id: &str,
1955 waiting: WaitingCleanup,
1956 to_master: &ToMaster,
1957 ) {
1958 let ended = waiting.ended.unwrap_or_else(|| restarted(attempt_id));
1959 let done = self.done_tx.clone();
1960 let on_spawn = self.done_tx.clone();
1961 let id = attempt_id.to_owned();
1962 let spawned: Spawned = Arc::new(move |identity, forked| {
1963 let _ = on_spawn.send(Done::Spawned {
1964 attempt_id: id.clone(),
1965 identity,
1966 forked,
1967 });
1968 });
1969 self.task_ended(ended.clone(), Some(to_master)).await;
1970 let executor = self.executor.clone();
1971 let (spec, handles, rest) = (waiting.spec, waiting.handles, waiting.rest);
1972 tokio::spawn(async move {
1973 let mut finished = executor.cleanup(spec, ended, handles, spawned).await;
1974 if let Some(cleanup) = finished.cleanup.as_mut() {
1975 cleanup.rest = rest;
1976 }
1977 let _ = done.send(Done::Attempt(finished));
1978 });
1979 }
1980
1981 async fn task_ended(&mut self, mut finished: pb::Finished, to_master: Option<&ToMaster>) {
1983 fit_result(&mut finished, self.master_limit);
1984 if let (true, Some(hash)) = (
1986 finished.code_hash.is_empty(),
1987 self.code_hashes.get(&finished.attempt_id),
1988 ) {
1989 finished.code_hash.clone_from(hash);
1990 }
1991 let id = finished.attempt_id.clone();
1992 self.cleanup_room.remove(&id);
1993 let record = JournalRecord::Cleaning(finished.clone(), None);
1994 if let Err(error) = self.record(&id, record).await {
1995 tracing::warn!(attempt_id = id, %error, "can't record the task's end");
1996 }
1997 self.cleaning.insert(id, finished.clone());
1998 if let Some(to_master) = to_master {
1999 let _ = to_master.send(task_ended_message(finished));
2000 }
2001 }
2002
2003 async fn record(&self, attempt_id: &str, record: JournalRecord) -> std::io::Result<()> {
2005 let journal = self.journal.clone();
2006 let attempt_id = attempt_id.to_owned();
2007 tokio::task::spawn_blocking(move || journal.write(&attempt_id, &record))
2008 .await
2009 .map_err(std::io::Error::other)?
2010 }
2011
2012 async fn acknowledged(&mut self, attempt_id: &str) {
2014 if self.unacked.remove(attempt_id).is_some() {
2015 self.forget(attempt_id).await;
2016 self.set_slot_gauges();
2017 }
2018 }
2019
2020 async fn forget(&self, attempt_id: &str) {
2023 let journal = self.journal.clone();
2024 let id = attempt_id.to_owned();
2025 let removed = tokio::task::spawn_blocking(move || journal.remove(&id))
2026 .await
2027 .map_err(std::io::Error::other)
2028 .and_then(|removed| removed);
2029 if let Err(error) = removed {
2030 tracing::warn!(attempt_id, %error, "can't remove the attempt from the journal");
2031 }
2032 }
2033
2034 async fn open_stream(
2041 &mut self,
2042 client: &mut MasterClient<Channel>,
2043 outbound: mpsc::UnboundedReceiver<pb::WorkerMessage>,
2044 opened: tokio::time::Instant,
2045 ) -> Result<tonic::Streaming<pb::MasterMessage>, SessionEnd> {
2046 let give_up_at = earliest(self.cut_off_at(), self.silent_at(opened));
2047 let opening = async {
2048 tokio::select! {
2049 control = client.control(UnboundedReceiverStream::new(outbound)) => Some(control),
2050 () = at(give_up_at) => None,
2051 }
2052 };
2053 match self.waiting_for(opening, true).await {
2054 None => Err(SessionEnd::Stopped),
2055 Some(Some(Ok(response))) => Ok(response.into_inner()),
2056 Some(Some(Err(status))) => Err(SessionEnd::Lost(status.to_string())),
2057 Some(None) => {
2058 self.cut_off_if_late();
2059 Err(SessionEnd::Lost(NO_WORD.to_owned()))
2060 }
2061 }
2062 }
2063
2064 async fn hashes(&mut self) -> Option<Vec<pb::RootHash>> {
2068 let names: Vec<String> = self.watchers.keys().cloned().collect();
2069 for name in names {
2070 while let Some(watcher) = self.watchers.get_mut(&name) {
2071 if watcher.hash().is_some() {
2072 break;
2073 }
2074 let wait = match watcher.poll(Instant::now()) {
2075 Ok(Poll::Settling(wait)) => Some(wait),
2076 Ok(_) => None,
2077 Err(error) => {
2078 tracing::warn!(root = name.as_str(), %error, "can't scan the root");
2079 Some(self.settings.poll_interval)
2080 }
2081 };
2082 if let Some(wait) = wait
2083 && self
2084 .waiting_for(tokio::time::sleep(wait), true)
2085 .await
2086 .is_none()
2087 {
2088 return None;
2089 }
2090 }
2091 }
2092 self.reported = self
2093 .watchers
2094 .keys()
2095 .filter_map(|name| Some((name.clone(), self.reported_hash(name)?)))
2096 .collect();
2097 Some(
2098 self.reported
2099 .iter()
2100 .map(|(name, hash)| root_hash(&self.settings.setup, name, hash))
2101 .collect(),
2102 )
2103 }
2104
2105 fn reported_hash(&self, name: &str) -> Option<String> {
2112 let content = self.watchers.get(name)?.hash()?;
2113 let scripts = &self.settings.setup.script_roots;
2114 if scripts.contains_key(name) {
2115 return Some(fold_hash("script", content, &[]));
2116 }
2117 let mut folded = Vec::new();
2118 for other in self
2120 .settings
2121 .setup
2122 .roots
2123 .keys()
2124 .filter(|other| *other != name)
2125 {
2126 let hash = self.watchers.get(other)?.hash()?;
2127 folded.push((format!("dag:{other}"), hash.to_owned()));
2128 }
2129 for script in self.uses.get(name).into_iter().flatten() {
2130 if !scripts.contains_key(script) {
2131 return None;
2132 }
2133 folded.push((script.clone(), self.reported_hash(script)?));
2134 }
2135 if folded.is_empty() {
2136 return Some(content.to_owned());
2137 }
2138 Some(fold_hash("dag", content, &folded))
2139 }
2140
2141 fn report_changes(&mut self, to_master: &ToMaster) {
2144 self.executor.code_changed(
2145 self.watchers
2146 .iter()
2147 .filter(|(name, _)| !self.settings.setup.script_roots.contains_key(*name))
2148 .filter_map(|(name, watcher)| {
2149 Some((name.clone(), watcher.code_dir()?.to_path_buf()))
2150 })
2151 .collect(),
2152 );
2153 let names: Vec<String> = self.watchers.keys().cloned().collect();
2154 for name in names {
2155 let now = self.reported_hash(&name);
2156 if now.as_ref() == self.reported.get(&name) {
2157 continue;
2158 }
2159 if now.is_none() {
2160 let missing: Vec<&str> = self
2161 .uses
2162 .get(&name)
2163 .into_iter()
2164 .flatten()
2165 .filter(|script| !self.settings.setup.script_roots.contains_key(*script))
2166 .map(String::as_str)
2167 .collect();
2168 tracing::warn!(
2169 root = name.as_str(),
2170 missing = missing.join(", "),
2171 "DAG root withdrawn: its DAGs use script roots this worker doesn't have"
2172 );
2173 }
2174 let hash = now.clone().unwrap_or_default();
2175 match now {
2176 Some(hash) => self.reported.insert(name.clone(), hash),
2177 None => self.reported.remove(&name),
2178 };
2179 let changed = worker_message::Message::CodeVersionChanged(pb::CodeVersionChanged {
2180 root: Some(root_hash(&self.settings.setup, &name, &hash)),
2181 });
2182 let _ = to_master.send(wrap(changed));
2183 }
2184 }
2185
2186 fn set_uses(&mut self, roots: Vec<pb::RootUses>, to_master: &ToMaster) {
2188 self.uses = roots
2189 .into_iter()
2190 .map(|uses| (uses.root, uses.script_roots.into_iter().collect()))
2191 .collect();
2192 self.report_changes(to_master);
2193 }
2194
2195 pub async fn session(&mut self, mut client: MasterClient<Channel>) -> SessionEnd {
2197 let Some(roots) = self.hashes().await else {
2198 return SessionEnd::Stopped;
2199 };
2200 let (sender, outbound) = mpsc::unbounded_channel::<pb::WorkerMessage>();
2203 let opened = self.open_session();
2205 let to_master = ToMaster::new(sender, self.master_time.outbox());
2206 let register = self.register_message(roots);
2207 if to_master
2208 .send(wrap(worker_message::Message::Register(register)))
2209 .is_err()
2210 {
2211 return SessionEnd::Lost("the outbound stream closed".to_owned());
2212 }
2213 let mut inbound = match self.open_stream(&mut client, outbound, opened).await {
2214 Ok(inbound) => inbound,
2215 Err(end) => return end,
2216 };
2217 self.send_state(&to_master);
2218 let mut warnings_open = true;
2219 let mut heartbeat = heartbeat_timer(self.heartbeat);
2220 let mut watch = tokio::time::interval(self.settings.poll_interval);
2221 let timeouts = self.settings.setup.timeouts;
2222 let mut tick = tokio::time::interval(timeouts.drain_tick);
2223 let mut alive = tokio::time::interval(timeouts.alive);
2224 let mut resends = Resends::limited(timeouts.result_resends, timeouts.result_resend_gap_max);
2227 let mut held_message = None;
2230 loop {
2231 let give_up_at = earliest(self.cut_off_at(), self.silent_at(opened));
2232 tokio::select! {
2233 () = at(give_up_at) => {
2234 self.cut_off_if_late();
2235 return SessionEnd::Lost(NO_WORD.to_owned());
2236 }
2237 count = next_request(&mut self.shutdown) => {
2238 if self.on_shutdown(count) {
2239 let draining = worker_message::Message::Draining(pb::Draining {});
2240 let _ = to_master.send(wrap(draining));
2241 }
2242 }
2243 _ = tick.tick(), if self.drain.is_some() => {
2244 if self.drain_step(true) == DrainStep::Finish {
2245 let bye = worker_message::Message::Deregister(pb::Deregister {});
2246 let _ = to_master.send(wrap(bye));
2247 drop(to_master);
2250 let left = self.drain.map_or(timeouts.deregister, |drain| {
2251 drain.deregister_by().saturating_duration_since(Instant::now())
2252 });
2253 let _ = tokio::time::timeout(timeouts.deregister.min(left), async {
2254 while let Ok(Some(_)) = inbound.message().await {}
2255 })
2256 .await;
2257 return SessionEnd::Stopped;
2258 }
2259 }
2260 message = next_inbound(&mut held_message, &mut inbound) => match message {
2261 Ok(Some(pb::MasterMessage { message: Some(message), clock })) => {
2262 if let Err(end) = self.take_in(&message, clock.as_ref(), opened, &to_master) {
2263 return end;
2264 }
2265 let link = (&to_master, &mut client, (&mut heartbeat, opened));
2266 let handled =
2267 Box::pin(self.handle_inbound(message, clock.as_ref(), &mut inbound, &mut held_message, link));
2268 if let Err(end) = handled.await {
2269 return end;
2270 }
2271 if self.cut_off || self.gone_silent(opened) {
2273 return SessionEnd::Lost(NO_WORD.to_owned());
2274 }
2275 }
2276 Ok(Some(_)) => {}
2277 Ok(None) => return SessionEnd::Lost("the master ended the stream".to_owned()),
2278 Err(status) => return SessionEnd::Lost(status.to_string()),
2279 },
2280 Some(done) = self.done_rx.recv() => {
2281 self.on_done_group(done, Some(&to_master), Some(&mut client)).await;
2282 }
2283 _ = heartbeat.tick() => {
2284 if let Some(end) = self.send_heartbeat(&mut resends, &to_master) {
2285 return end;
2286 }
2287 }
2288 _ = watch.tick() => self.watch(&to_master),
2289 _ = alive.tick() => self.on_alive(),
2290 changed = self.warnings.changed(), if warnings_open => {
2291 if changed.is_ok() {
2292 self.report_warnings(&to_master);
2293 } else {
2294 warnings_open = false;
2296 }
2297 }
2298 }
2299 }
2300 }
2301
2302 fn refused(
2305 &mut self,
2306 message: &master_message::Message,
2307 clock: Option<&pb::MasterClock>,
2308 opened: tokio::time::Instant,
2309 ) -> Option<String> {
2310 if Self::answer_too_late(message, opened.elapsed()) {
2311 return Some(TOO_LATE.to_owned());
2312 }
2313 self.older_leader(clock)
2314 }
2315
2316 fn older_leader(&mut self, clock: Option<&pb::MasterClock>) -> Option<String> {
2320 let epoch = clock?.lease_epoch;
2321 let (highest, heard) = self.leader_epoch;
2322 let now = tokio::time::Instant::now();
2323 if epoch < highest {
2324 let fenced = match (heard, self.lease) {
2325 (Some(heard), Some(lease)) => now.duration_since(heard) < lease,
2326 _ => true,
2327 };
2328 if fenced {
2329 self.metrics.older_epoch.inc();
2330 return Some(format!(
2331 "a master leading with lease epoch {epoch}, after epoch {highest}: deposed, \
2332 connecting again"
2333 ));
2334 }
2335 tracing::warn!(
2336 epoch,
2337 highest,
2338 "a master with a lower lease epoch, and none of epoch {highest} for a lease: \
2339 its database was restored or replaced; following it"
2340 );
2341 }
2342 self.leader_epoch = (epoch, Some(now));
2343 None
2344 }
2345
2346 fn heard_master(&mut self, clock: Option<&pb::MasterClock>, to_master: &ToMaster) {
2349 self.heard = tokio::time::Instant::now();
2350 let skew = clock.and_then(|clock| self.master_time.heard(clock, Local::now()));
2351 if self
2352 .lease
2353 .is_some_and(|lease| self.master_time.cutoff_in(lease, Local::now()).is_some())
2354 {
2355 self.carried_cutoff = None;
2356 }
2357 self.publish_deadline();
2358 self.publish_master_reading();
2359 let threshold = self.settings.setup.timeouts.clock_skew_warning;
2360 if let Some(skew) = skew
2361 && skew > threshold
2362 && self.clock_skew.is_none()
2363 {
2364 tracing::warn!(
2366 skew_ms = skew.as_millis(),
2367 "this worker's wall clock differs from the master's beyond the round trip"
2368 );
2369 self.clock_skew = Some(pb::WorkerWarning {
2370 kind: "clock_skew".to_owned(),
2371 interpreter: String::new(),
2372 message: format!(
2373 "this worker's wall clock differs from the master's by {:.1} s beyond the \
2374 round trip: times it shows and logs are off by that much (sync its clock)",
2375 skew.as_secs_f64()
2376 ),
2377 });
2378 self.report_warnings(to_master);
2379 }
2380 }
2381
2382 fn publish_master_reading(&mut self) {
2384 let now = Local::now();
2385 if let Some(reading) = self.master_time.reading(now) {
2386 self.sample_sent = Some(now.boot.saturating_sub(reading.age));
2387 self.metrics
2388 .master_round_trip
2389 .set(reading.round_trip.as_secs_f64());
2390 }
2391 if let Some(sent) = self.sample_sent {
2393 self.metrics
2394 .master_sample_age
2395 .set(now.boot.saturating_sub(sent).as_secs_f64());
2396 }
2397 }
2398
2399 fn send_beat(&mut self, to_master: &ToMaster) {
2401 self.publish_master_reading();
2402 let _ = to_master.send(self.heartbeat_message());
2403 }
2404
2405 fn heartbeat_message(&self) -> pb::WorkerMessage {
2408 let watcher_hosts = self.executor.watcher_hosts();
2409 let usage = self.usage(&watcher_hosts);
2410 wrap(worker_message::Message::Heartbeat(pb::Heartbeat {
2411 free_slots: self.free_slots(),
2412 free_watcher_slots: self.free_watcher_slots(),
2413 running_attempt_ids: self.running(),
2414 running_triggers: self.triggers.keys().cloned().collect(),
2415 watcher_hosts,
2416 usage,
2417 }))
2418 }
2419
2420 fn usage(&self, watcher_hosts: &[pb::WatcherHost]) -> Option<pb::WorkerUsage> {
2422 let node = crate::memory::this_node()?;
2423 let (fork_servers_bytes, tasks) = self.executor.memory_parts();
2424 Some(pb::WorkerUsage {
2425 process: Some(pb::NodeUsage {
2426 resident_bytes: node.resident_bytes,
2427 cpu_seconds: node.cpu_seconds,
2428 container_bytes: node.container_bytes,
2429 container_limit_bytes: node.container_limit_bytes,
2430 }),
2431 fork_servers_bytes,
2432 watcher_hosts_bytes: watcher_hosts.iter().map(|h| h.memory_bytes).sum(),
2433 tasks_bytes: tasks.iter().map(|t| t.bytes).sum(),
2434 largest_tasks: tasks
2435 .into_iter()
2436 .take(LARGEST_TASKS)
2437 .map(|t| pb::TaskMemory {
2438 attempt_id: t.attempt_id,
2439 dag_id: t.dag_id,
2440 run_id: t.run_id,
2441 task_id: t.task_id,
2442 map_index: t.map_index,
2443 bytes: t.bytes,
2444 })
2445 .collect(),
2446 })
2447 }
2448
2449 fn send_heartbeat(
2450 &mut self,
2451 resends: &mut Resends,
2452 to_master: &ToMaster,
2453 ) -> Option<SessionEnd> {
2454 self.send_beat(to_master);
2455 self.send_poke_reports(to_master);
2456 let Some(due) = resends.due(self.unacked.keys()) else {
2457 return Some(SessionEnd::Lost(format!(
2458 "a result is still unacknowledged after {} sends; reconnecting, so the \
2459 master's reconciliation settles it",
2460 resends.most
2461 )));
2462 };
2463 for id in due {
2464 self.send_again(&id, to_master);
2465 }
2466 None
2467 }
2468
2469 async fn handle_inbound(
2474 &mut self,
2475 message: master_message::Message,
2476 clock: Option<&pb::MasterClock>,
2477 inbound: &mut tonic::Streaming<pb::MasterMessage>,
2478 held: &mut Option<Result<Option<pb::MasterMessage>, tonic::Status>>,
2479 (to_master, client, timers): (
2480 &ToMaster,
2481 &mut MasterClient<Channel>,
2482 (&mut tokio::time::Interval, tokio::time::Instant),
2483 ),
2484 ) -> Result<(), SessionEnd> {
2485 let (heartbeat, opened) = timers;
2486 let sequence = clock.map_or(0, |c| c.sequence);
2487 let master_message::Message::AssignTask(first) = message else {
2488 Box::pin(self.on_master(message, to_master, client, (heartbeat, opened))).await;
2489 to_master.handled(sequence);
2491 return Ok(());
2492 };
2493 let mut burst = vec![first];
2494 let mut sequences = vec![sequence];
2495 while burst.len() < self.settings.setup.timeouts.starts_per_journal_group {
2496 match futures_util::FutureExt::now_or_never(inbound.message()) {
2497 Some(Ok(Some(pb::MasterMessage {
2498 message: Some(master_message::Message::AssignTask(next)),
2499 clock,
2500 }))) => {
2501 let next = master_message::Message::AssignTask(next);
2502 if let Err(end) = self.take_in(&next, clock.as_ref(), opened, to_master) {
2503 Box::pin(self.assign_group(burst, to_master, client, (heartbeat, opened)))
2506 .await;
2507 for sequence in sequences {
2508 to_master.handled(sequence);
2509 }
2510 return Err(end);
2511 }
2512 let master_message::Message::AssignTask(next) = next else {
2513 unreachable!("built as an assignment above")
2514 };
2515 burst.push(next);
2516 sequences.push(clock.as_ref().map_or(0, |c| c.sequence));
2517 }
2518 Some(other) => {
2519 *held = Some(other);
2520 break;
2521 }
2522 None => break,
2523 }
2524 }
2525 Box::pin(self.assign_group(burst, to_master, client, (heartbeat, opened))).await;
2526 for sequence in sequences {
2528 to_master.handled(sequence);
2529 }
2530 Ok(())
2531 }
2532
2533 fn take_in(
2536 &mut self,
2537 message: &master_message::Message,
2538 clock: Option<&pb::MasterClock>,
2539 opened: tokio::time::Instant,
2540 to_master: &ToMaster,
2541 ) -> Result<(), SessionEnd> {
2542 if let Some(why) = self.refused(message, clock, opened) {
2543 return Err(SessionEnd::Lost(why));
2544 }
2545 if self.silent_too_long(opened) {
2548 return Err(SessionEnd::Lost(NO_WORD.to_owned()));
2549 }
2550 self.heard_master(clock, to_master);
2551 Ok(())
2552 }
2553
2554 async fn on_master(
2555 &mut self,
2556 message: master_message::Message,
2557 to_master: &ToMaster,
2558 client: &mut MasterClient<Channel>,
2559 (heartbeat, opened): (&mut tokio::time::Interval, tokio::time::Instant),
2560 ) {
2561 match message {
2562 master_message::Message::Registered(registered) => {
2563 self.registered = true;
2564 if registered.max_message_size > 0 {
2565 self.master_limit =
2566 usize::try_from(registered.max_message_size).unwrap_or(usize::MAX);
2567 }
2568 if let Some(timing) = registered.timing.filter(|t| t.heartbeat_interval_ms > 0) {
2569 self.heartbeat = Duration::from_millis(timing.heartbeat_interval_ms);
2570 *heartbeat = heartbeat_timer(self.heartbeat);
2571 self.lease = (timing.lease_timeout_ms > 0)
2572 .then(|| Duration::from_millis(timing.lease_timeout_ms));
2573 self.publish_deadline();
2574 }
2575 self.cut_off = false;
2576 for decision in registered.decisions {
2577 self.decide(&decision, to_master).await;
2578 }
2579 for event in self.unstored_events() {
2580 let _ = to_master.send(event);
2581 }
2582 for stopped in std::mem::take(&mut self.triggers_ended).into_values() {
2583 let _ = to_master.send(wrap(worker_message::Message::TriggerStopped(stopped)));
2584 }
2585 for trigger in self.triggers.values_mut() {
2587 trigger.poke.unsent = trigger.poke.at.is_some();
2588 }
2589 self.api_calls.retain(|_, (_, answer)| !answer.is_closed());
2591 for (call, _) in self.api_calls.values() {
2592 let _ = to_master.send(wrap(worker_message::Message::ApiCall(call.clone())));
2593 }
2594 for done in self.unsent_answers.drain(..) {
2595 let _ = to_master.send(wrap(worker_message::Message::ConnectionJobDone(done)));
2596 }
2597 self.set_uses(registered.script_uses, to_master);
2598 }
2599 master_message::Message::ScriptUses(uses) => self.set_uses(uses.roots, to_master),
2600 master_message::Message::AssignTask(assign) => {
2601 self.assign(assign, to_master, client, (heartbeat, opened))
2602 .await;
2603 }
2604 master_message::Message::AssignParse(job) => self.parse(job),
2605 master_message::Message::HeartbeatAck(_) => {}
2607 master_message::Message::ConnectionJob(job) => self.connection_job(job),
2608 master_message::Message::AssignTrigger(assign) => {
2609 self.start_trigger(&assign, to_master);
2610 }
2611 master_message::Message::CancelTrigger(cancel) => {
2612 if let Some(trigger) = self.triggers.get(&cancel.instance_id) {
2613 let _ = trigger.stop.send(StopReason::Cancelled);
2614 }
2615 }
2616 master_message::Message::ApiAnswer(answer) => {
2617 if let Some((_, to)) = self.api_calls.remove(&answer.request_id) {
2618 let _ = to.send(answer);
2619 }
2620 }
2621 master_message::Message::TriggerEventAck(ack) => {
2622 if let Some(trigger) = self.triggers.get_mut(&ack.instance_id)
2623 && let Some((_, stored)) = trigger.unstored.remove(&ack.seq)
2624 {
2625 let _ = stored.send(());
2626 }
2627 }
2628 master_message::Message::CancelAttempt(cancel) => {
2629 if let Some(stop) = self.running.get(&cancel.attempt_id) {
2632 let _ = stop.send(if cancel.interrupted {
2633 StopReason::Interrupted
2634 } else {
2635 StopReason::Cancelled
2636 });
2637 }
2638 }
2639 master_message::Message::FinishedAck(ack) => {
2640 self.forked.remove(&ack.attempt_id);
2641 self.acknowledged(&ack.attempt_id).await;
2642 }
2643 }
2644 }
2645
2646 async fn decide(&mut self, decision: &pb::JournalDecision, to_master: &ToMaster) {
2647 let id = &decision.attempt_id;
2648 match pb::AttemptDecision::try_from(decision.decision) {
2649 Ok(pb::AttemptDecision::Ack) => {
2650 self.forked.remove(id);
2651 self.acknowledged(id).await;
2652 }
2653 Ok(pb::AttemptDecision::CleanRest) => {
2654 let from = decision.cleanup_from;
2657 self.rest_cleaning.insert(id.clone());
2658 if let Some(gate) = self.gates.get(id) {
2659 gate.send_replace(Gate::Rest(from));
2660 }
2661 if let Some(mut waiting) = self.waiting.remove(id) {
2662 let from = (from as usize).min(waiting.handles.len());
2663 waiting.handles.drain(..from);
2664 waiting.rest = true;
2665 self.start_waiting(id, waiting, to_master).await;
2666 }
2667 if let Some(stop) = self.running.get(id) {
2669 let _ = stop.send(StopReason::Cancelled);
2670 }
2671 }
2672 Ok(pb::AttemptDecision::Kill) => {
2673 self.forked.remove(id);
2674 self.acknowledged(id).await;
2675 if let Some(gate) = self.gates.get(id) {
2676 gate.send_replace(Gate::Dropped);
2677 }
2678 if self.waiting.remove(id).is_some() {
2679 self.running.remove(id);
2681 self.set_slot_gauges();
2682 self.release_code(id);
2683 self.forget(id).await;
2684 self.collect_code();
2685 }
2686 if let Some(stop) = self.running.get(id) {
2687 let _ = stop.send(StopReason::Cancelled);
2688 }
2689 }
2690 _ => {
2691 if let Some(gate) = self.gates.get(id) {
2692 gate.send_replace(Gate::Open);
2693 }
2694 if self.running.contains_key(id) {
2695 if self.forked.contains(id) {
2696 let _ = to_master.send(forked_started(id));
2697 }
2698 self.send_handles(id, to_master).await;
2699 }
2700 if let Some(waiting) = self.waiting.remove(id) {
2701 self.start_waiting(id, waiting, to_master).await;
2702 } else if let Some(ended) = self.cleaning.get(id) {
2703 let mut ended = ended.clone();
2706 fit_result(&mut ended, self.master_limit);
2707 let _ = to_master.send(task_ended_message(ended));
2708 } else {
2709 if self.unacked.contains_key(id) && self.forked.contains(id) {
2710 let _ = to_master.send(forked_started(id));
2711 }
2712 self.send_again(id, to_master);
2713 }
2714 }
2715 }
2716 }
2717
2718 async fn send_handles(&self, attempt_id: &str, to_master: &ToMaster) {
2721 let journal = self.journal.clone();
2722 let id = attempt_id.to_owned();
2723 let read = tokio::task::spawn_blocking(move || journal.handles(&id)).await;
2724 match read {
2725 Ok(Ok(handles)) if !handles.is_empty() => {
2726 let _ = to_master.send(handles_message(attempt_id.to_owned(), 0, &handles));
2727 }
2728 Ok(Ok(_)) => {}
2729 Ok(Err(error)) => {
2730 tracing::warn!(attempt_id, %error, "can't read the handles to send them again");
2731 }
2732 Err(error) => tracing::warn!(attempt_id, %error, "reading the handles failed"),
2733 }
2734 }
2735
2736 fn send_again(&self, id: &str, to_master: &ToMaster) {
2740 if let Some(finished) = self.unacked.get(id) {
2741 let mut finished = finished.clone();
2742 fit_result(&mut finished, self.master_limit);
2743 let _ = to_master.send(wrap(worker_message::Message::Finished(finished)));
2744 }
2745 }
2746
2747 async fn external_inputs(
2751 &mut self,
2752 assign: &pb::AssignTask,
2753 to_master: &ToMaster,
2754 client: &mut MasterClient<Channel>,
2755 timers: (&mut tokio::time::Interval, tokio::time::Instant),
2756 ) -> Option<Option<Vec<u8>>> {
2757 if !assign.inputs_external {
2758 return Some(None);
2759 }
2760 match self
2761 .fetch_with_timers(client, &assign.attempt_id, to_master, timers)
2762 .await?
2763 {
2764 Ok(bytes) => Some(Some(bytes)),
2765 Err(detail) => {
2766 let rejected = pb::Rejected {
2767 attempt_id: assign.attempt_id.clone(),
2768 reason: pb::RejectReason::InvalidSpecification.into(),
2769 detail,
2770 };
2771 let _ = to_master.send(wrap(worker_message::Message::Rejected(rejected)));
2772 None
2773 }
2774 }
2775 }
2776
2777 async fn assign(
2778 &mut self,
2779 assign: pb::AssignTask,
2780 to_master: &ToMaster,
2781 client: &mut MasterClient<Channel>,
2782 timers: (&mut tokio::time::Interval, tokio::time::Instant),
2783 ) {
2784 Box::pin(self.assign_group(vec![assign], to_master, client, timers)).await;
2785 }
2786
2787 async fn assign_group(
2791 &mut self,
2792 assigns: Vec<pb::AssignTask>,
2793 to_master: &ToMaster,
2794 client: &mut MasterClient<Channel>,
2795 timers: (&mut tokio::time::Interval, tokio::time::Instant),
2796 ) {
2797 let (heartbeat, opened) = timers;
2798 let mut ready = Vec::new();
2799 let mut held = Held::default();
2800 for assign in assigns {
2801 if assign.inputs_external && !ready.is_empty() {
2804 Box::pin(self.start_group(std::mem::take(&mut ready), to_master, opened)).await;
2805 held = Held::default();
2806 }
2807 if self.cut_off || self.gone_silent(opened) {
2810 break;
2811 }
2812 let prepared = self
2813 .prepare(assign, to_master, client, (&mut *heartbeat, opened), &held)
2814 .await;
2815 if let Some(prepared) = prepared {
2816 held.add(&prepared);
2817 ready.push(prepared);
2818 }
2819 }
2820 Box::pin(self.start_group(ready, to_master, opened)).await;
2821 }
2822
2823 async fn start_group(
2825 &mut self,
2826 ready: Vec<Prepared>,
2827 to_master: &ToMaster,
2828 opened: tokio::time::Instant,
2829 ) {
2830 let journaled = self.journal_starts(&ready, opened).await;
2831 for (prepared, journaled) in ready.into_iter().zip(journaled) {
2832 self.after_journal(prepared, journaled, to_master).await;
2833 }
2834 }
2835
2836 async fn prepare(
2840 &mut self,
2841 assign: pb::AssignTask,
2842 to_master: &ToMaster,
2843 client: &mut MasterClient<Channel>,
2844 timers: (&mut tokio::time::Interval, tokio::time::Instant),
2845 held: &Held,
2846 ) -> Option<Prepared> {
2847 let received = std::time::Instant::now();
2848 let reject = |reason: pb::RejectReason, detail: String| {
2849 wrap(worker_message::Message::Rejected(pb::Rejected {
2850 attempt_id: assign.attempt_id.clone(),
2851 reason: reason.into(),
2852 detail,
2853 }))
2854 };
2855 if assign.cleanup_only.is_some() && self.cleaning_rest(&assign.attempt_id) {
2856 let detail = "cleaning the rest of this attempt's handles".to_owned();
2859 let _ = to_master.send(reject(pb::RejectReason::NoFreeSlot, detail));
2860 return None;
2861 }
2862 if self.running.contains_key(&assign.attempt_id)
2863 || self.unacked.contains_key(&assign.attempt_id)
2864 || held.ids.contains(&assign.attempt_id)
2865 {
2866 tracing::warn!(
2868 attempt_id = assign.attempt_id.as_str(),
2869 "assignment of an attempt this worker already has; ignored"
2870 );
2871 return None;
2872 }
2873 if let Some((reason, detail)) = self.cannot_take_held(assigned_a_wait_step(&assign), held) {
2874 let _ = to_master.send(reject(reason, detail.to_owned()));
2875 return None;
2876 }
2877 let external = self
2878 .external_inputs(&assign, to_master, client, timers)
2879 .await?;
2880 let mut spec = match AttemptSpec::from_assign(&assign, external.as_deref()) {
2881 Ok(spec) => spec,
2882 Err(error) => {
2883 let _ = to_master.send(reject(
2884 pb::RejectReason::InvalidSpecification,
2885 error.to_string(),
2886 ));
2887 return None;
2888 }
2889 };
2890 if let Some(detail) = self.code_mismatch(&assign) {
2891 let _ = to_master.send(reject(pb::RejectReason::CodeMismatch, detail));
2892 return None;
2893 }
2894 spec.stand_in_secrets();
2897 let planned = self.plan(&mut spec, &assign);
2898 Some(Prepared {
2899 assign,
2900 spec,
2901 planned,
2902 external,
2903 received,
2904 })
2905 }
2906
2907 async fn after_journal(
2910 &mut self,
2911 prepared: Prepared,
2912 journaled: Result<(), Option<(pb::RejectReason, String)>>,
2913 to_master: &ToMaster,
2914 ) {
2915 let Prepared {
2916 assign,
2917 mut spec,
2918 planned,
2919 received,
2920 ..
2921 } = prepared;
2922 let reject = |reason: pb::RejectReason, detail: String| {
2923 wrap(worker_message::Message::Rejected(pb::Rejected {
2924 attempt_id: assign.attempt_id.clone(),
2925 reason: reason.into(),
2926 detail,
2927 }))
2928 };
2929 if let Err(why) = journaled {
2930 if let Some((reason, detail)) = why {
2931 let _ = to_master.send(reject(reason, detail));
2932 }
2933 return;
2934 }
2935 self.remember_code(&assign, &spec);
2936 self.note_cleanup(&mut spec, &assign);
2937 spec.api = Some(ApiCaller::of_attempt(&spec.attempt_id, self.api_send()));
2938 if let Some(only) = &assign.cleanup_only
2939 && !matches!(planned, Err(NotRun::Rejected { .. }))
2940 {
2941 match moved_handles(only) {
2942 Ok(handles) => {
2943 self.moved_cleanup(spec, handles, to_master, received).await;
2944 }
2945 Err(error) => {
2947 self.release_code(&spec.attempt_id);
2948 self.forget(&spec.attempt_id).await;
2949 let detail = format!("a handle that doesn't read: {error}");
2950 let _ = to_master.send(reject(pb::RejectReason::InvalidSpecification, detail));
2951 }
2952 }
2953 return;
2954 }
2955 self.start_planned(spec, planned, to_master, received);
2956 }
2957
2958 fn started(&self, attempt_id: &str, method: pb::StartMethod) -> pb::Started {
2961 let estimate = self.master_time.estimate(Local::now());
2962 pb::Started {
2963 attempt_id: attempt_id.to_owned(),
2964 start_method: method.into(),
2965 started_master_ms: estimate.map(|(_, ms)| ms),
2966 started_timeline: estimate.map_or(0, |(timeline, _)| timeline),
2967 }
2968 }
2969
2970 fn start_planned(
2973 &mut self,
2974 mut spec: AttemptSpec,
2975 planned: Result<Plan, NotRun>,
2976 to_master: &ToMaster,
2977 received: std::time::Instant,
2978 ) {
2979 let started = wrap(worker_message::Message::Started(
2980 self.started(&spec.attempt_id, pb::StartMethod::Spawn),
2981 ));
2982 match planned {
2983 Err(NotRun::Rejected { reason, detail }) => {
2984 self.release_code(&spec.attempt_id);
2985 let _ = to_master.send(wrap(worker_message::Message::Rejected(pb::Rejected {
2986 attempt_id: spec.attempt_id.clone(),
2987 reason: reason.into(),
2988 detail,
2989 })));
2990 }
2991 Err(NotRun::Failed { kind, message }) => {
2992 let _ = to_master.send(started);
2993 self.metrics
2994 .assign_to_started
2995 .observe(received.elapsed().as_secs_f64());
2996 let failed = failed_before_start(&spec.attempt_id, &kind, &message);
2997 let _ = self.done_tx.send(Done::Attempt(failed));
2998 }
2999 Ok(plan) => {
3000 let (stop, stopped) = Stops::new();
3001 self.running.insert(spec.attempt_id.clone(), stop);
3002 self.note_wait_step(&spec);
3003 self.set_gate(&mut spec);
3004 let _ = to_master.send(started);
3005 self.metrics
3006 .assign_to_started
3007 .observe(received.elapsed().as_secs_f64());
3008 self.set_slot_gauges();
3010 self.launch(spec, plan, stopped);
3011 }
3012 }
3013 }
3014
3015 fn start_trigger(&mut self, assign: &pb::AssignTrigger, to_master: &ToMaster) {
3018 let stopped = |kind: &str, message: String| {
3019 wrap(worker_message::Message::TriggerStopped(
3020 pb::TriggerStopped {
3021 dag_id: assign.dag_id.clone(),
3022 instance_id: assign.instance_id.clone(),
3023 error_kind: kind.to_owned(),
3024 message,
3025 ..pb::TriggerStopped::default()
3026 },
3027 ))
3028 };
3029 if let Some((_, detail)) = self.cannot_take(true) {
3030 let _ = to_master.send(stopped("not_placed", detail.to_owned()));
3031 return;
3032 }
3033 if self.triggers.contains_key(&assign.instance_id) {
3034 return;
3035 }
3036 let now = proto_time(Timestamp::now());
3037 let task_assign = pb::AssignTask {
3038 attempt_id: assign.instance_id.clone(),
3039 map_index: -1,
3040 try_number: 1,
3041 run: Some(pb::RunInfo {
3042 run_id: assign.instance_id.clone(),
3043 kind: "event".to_owned(),
3044 planned_for: Some(now),
3045 since: Some(now),
3046 dag_id: assign.dag_id.clone(),
3047 ..pb::RunInfo::default()
3048 }),
3049 task_json: assign.task_json.clone(),
3050 dag_file: assign.dag_file.clone(),
3051 expected_code_hash: assign.expected_code_hash.clone(),
3052 cancel_grace_ms: assign.cancel_grace_ms,
3053 connections_json: assign.connections_json.clone(),
3054 ..pb::AssignTask::default()
3055 };
3056 let mut spec = match AttemptSpec::from_assign(&task_assign, None) {
3057 Ok(spec) => spec,
3058 Err(error) => {
3059 let _ = to_master.send(stopped("not_placed", error.to_string()));
3060 return;
3061 }
3062 };
3063 if let Some(detail) = self.code_mismatch(&task_assign) {
3064 let _ = to_master.send(stopped("not_placed", detail));
3065 return;
3066 }
3067 let instance_id = assign.instance_id.clone();
3068 let sink = self.trigger_sink(&instance_id, batches(&spec.task));
3069 let start = schedr_model::runner::TriggerStart {
3070 after: assign.after.clone(),
3071 };
3072 spec.trigger = Some((start, sink));
3073 let send = self.api_send();
3074 spec.api = Some(ApiCaller::of_trigger(
3075 &assign.instance_id,
3076 &assign.dag_id,
3077 send,
3078 ));
3079 spec.stand_in_secrets();
3080 let plan = match self.plan(&mut spec, &task_assign) {
3081 Ok(plan) => plan,
3082 Err(NotRun::Rejected { detail, .. }) => {
3083 let _ = to_master.send(stopped("not_placed", detail));
3084 return;
3085 }
3086 Err(NotRun::Failed { kind, message }) => {
3087 let _ = to_master.send(stopped(&kind, message));
3088 return;
3089 }
3090 };
3091 self.remember_code(&task_assign, &spec);
3092 let (stop, stops) = Stops::new();
3093 self.triggers.insert(
3094 instance_id.clone(),
3095 RunningTrigger {
3096 dag_id: assign.dag_id.clone(),
3097 stop,
3098 next_seq: 0,
3099 unstored: BTreeMap::new(),
3100 poke: PokeReport {
3101 failures: assign.failures,
3102 ..PokeReport::default()
3103 },
3104 },
3105 );
3106 let executor = self.executor.clone();
3107 let ended = self.done_tx.clone();
3108 tokio::spawn(async move {
3109 let spawned: Spawned = Arc::new(|_, _| {});
3110 let finished = executor
3111 .run(spec, plan, stops, spawned, Box::new(|_| {}))
3112 .await;
3113 let _ = ended.send(Done::Trigger(TriggerDone::Ended {
3114 instance_id,
3115 finished: Box::new(finished),
3116 }));
3117 });
3118 }
3119
3120 fn result_ready(&mut self, mut finished: pb::Finished) -> pb::Finished {
3123 fit_result(&mut finished, self.master_limit);
3124 let status = attempt_status_from_proto(finished.status)
3125 .map_or_else(|_| "unknown".to_owned(), |s| s.to_string());
3126 self.metrics.attempt_ended(&status);
3127 if let Some(hash) = self.release_code(&finished.attempt_id) {
3128 with_code_hash(&mut finished, hash);
3129 self.collect_code();
3130 }
3131 finished
3132 }
3133
3134 fn result_recorded(&mut self, finished: pb::Finished, to_master: Option<&ToMaster>) {
3136 self.ended_running(&finished.attempt_id);
3137 self.cleaning.remove(&finished.attempt_id);
3138 self.cleanup_room.remove(&finished.attempt_id);
3139 self.stopped.remove(&finished.attempt_id);
3140 self.gates.remove(&finished.attempt_id);
3141 self.unacked
3142 .insert(finished.attempt_id.clone(), finished.clone());
3143 self.set_slot_gauges();
3145 if let Some(to_master) = to_master {
3146 let _ = to_master.send(wrap(worker_message::Message::Finished(finished)));
3147 }
3148 }
3149
3150 async fn on_done_group(
3155 &mut self,
3156 done: Done,
3157 to_master: Option<&ToMaster>,
3158 client: Option<&mut MasterClient<Channel>>,
3159 ) {
3160 let link = to_master.zip(client);
3161 let first = match done {
3162 Done::Attempt(first) => first,
3163 Done::Spawned {
3164 attempt_id,
3165 identity,
3166 forked,
3167 } => {
3168 let (record, repeat) = self.spawned_record(&attempt_id, identity, forked);
3169 return Box::pin(self.spawned_group((attempt_id, record, repeat), link)).await;
3170 }
3171 other => return self.on_done(other, link).await,
3172 };
3173 let mut results = vec![self.result_ready(first)];
3174 let mut next = None;
3175 while results.len() < self.settings.setup.timeouts.results_per_journal_group {
3176 match self.done_rx.try_recv() {
3177 Ok(Done::Attempt(finished)) => results.push(self.result_ready(finished)),
3178 Ok(other) => {
3179 next = Some(other);
3180 break;
3181 }
3182 Err(_) => break,
3183 }
3184 }
3185 self.record_results(&results).await;
3186 let to_master = link.as_ref().map(|(to_master, _)| *to_master);
3187 for finished in results {
3188 self.result_recorded(finished, to_master);
3189 }
3190 if let Some(next) = next {
3191 Box::pin(self.on_done(next, link)).await;
3192 }
3193 }
3194
3195 fn spawned_record(
3199 &mut self,
3200 attempt_id: &str,
3201 identity: ProcessIdentity,
3202 forked: bool,
3203 ) -> (JournalRecord, bool) {
3204 let ended = self.cleaning.get(attempt_id).cloned();
3207 let repeat = forked && ended.is_none();
3208 if repeat {
3209 self.forked.insert(attempt_id.to_owned());
3210 }
3211 let record = match ended {
3212 Some(ended) => JournalRecord::Cleaning(ended, Some(identity)),
3213 None => JournalRecord::Running(Some(identity)),
3214 };
3215 (record, repeat)
3216 }
3217
3218 async fn spawned_group(
3221 &mut self,
3222 first: (String, JournalRecord, bool),
3223 link: Option<(&ToMaster, &mut MasterClient<Channel>)>,
3224 ) {
3225 let to_master = link.as_ref().map(|(to_master, _)| *to_master);
3226 let mut records = vec![first];
3227 let mut next = None;
3228 while records.len() < self.settings.setup.timeouts.starts_per_journal_group {
3229 match self.done_rx.try_recv() {
3230 Ok(Done::Spawned {
3231 attempt_id,
3232 identity,
3233 forked,
3234 }) => {
3235 let (record, repeat) = self.spawned_record(&attempt_id, identity, forked);
3236 records.push((attempt_id, record, repeat));
3237 }
3238 Ok(other) => {
3239 next = Some(other);
3240 break;
3241 }
3242 Err(_) => break,
3243 }
3244 }
3245 self.keep_processes(records, to_master).await;
3246 if let Some(next) = next {
3247 Box::pin(self.on_done(next, link)).await;
3248 }
3249 }
3250
3251 async fn keep_processes(
3254 &mut self,
3255 records: Vec<(String, JournalRecord, bool)>,
3256 to_master: Option<&ToMaster>,
3257 ) {
3258 let began = std::time::Instant::now();
3259 let written = if let [(id, record, _)] = records.as_slice() {
3260 self.record(id, record.clone()).await
3261 } else {
3262 let journal = self.journal.clone();
3263 let group: Vec<(String, JournalRecord)> = records
3264 .iter()
3265 .map(|(id, record, _)| (id.clone(), record.clone()))
3266 .collect();
3267 tokio::task::spawn_blocking(move || {
3268 let refs: Vec<(&str, &JournalRecord)> = group
3269 .iter()
3270 .map(|(id, record)| (id.as_str(), record))
3271 .collect();
3272 journal.write_many(&refs)
3273 })
3274 .await
3275 .map_err(std::io::Error::other)
3276 .and_then(|written| written)
3277 };
3278 match written {
3279 Ok(()) => self.metrics.journal_written("process", began.elapsed()),
3280 Err(_) if records.len() > 1 => {
3281 for (attempt_id, record, _) in &records {
3283 if let Err(error) = self.record(attempt_id, record.clone()).await {
3284 tracing::warn!(attempt_id, %error, "can't record the task's process");
3285 }
3286 }
3287 }
3288 Err(error) => {
3289 let attempt_id = records[0].0.as_str();
3290 tracing::warn!(attempt_id, %error, "can't record the task's process");
3291 }
3292 }
3293 if let Some(to_master) = to_master {
3294 for (attempt_id, _, repeat) in &records {
3295 if *repeat {
3296 let _ = to_master.send(forked_started(attempt_id));
3297 }
3298 }
3299 }
3300 }
3301
3302 async fn record_results(&self, results: &[pb::Finished]) {
3304 if let [one] = results {
3305 return self.record_finished(one).await;
3306 }
3307 let journal = self.journal.clone();
3308 let records: Vec<(String, JournalRecord)> = results
3309 .iter()
3310 .map(|f| (f.attempt_id.clone(), JournalRecord::Finished(f.clone())))
3311 .collect();
3312 let began = std::time::Instant::now();
3313 let written = tokio::task::spawn_blocking(move || {
3314 let refs: Vec<(&str, &JournalRecord)> =
3315 records.iter().map(|(id, r)| (id.as_str(), r)).collect();
3316 journal.write_many(&refs)
3317 })
3318 .await
3319 .map_err(std::io::Error::other)
3320 .and_then(|written| written);
3321 if written.is_ok() {
3322 self.metrics.journal_written("results", began.elapsed());
3323 }
3324 if let Err(error) = written {
3325 tracing::warn!(
3326 results = results.len(),
3327 %error,
3328 "can't record the results; they are lost if the agent restarts before the \
3329 master acknowledges them"
3330 );
3331 }
3332 }
3333
3334 async fn record_finished(&self, finished: &pb::Finished) {
3336 let began = std::time::Instant::now();
3337 let recorded = self
3338 .record(
3339 &finished.attempt_id,
3340 JournalRecord::Finished(finished.clone()),
3341 )
3342 .await;
3343 if recorded.is_ok() {
3344 self.metrics.journal_written("results", began.elapsed());
3345 }
3346 if let Err(error) = recorded {
3347 tracing::warn!(
3348 attempt_id = finished.attempt_id.as_str(),
3349 %error,
3350 "can't record the result; it is lost if the agent restarts before the \
3351 master acknowledges it"
3352 );
3353 }
3354 }
3355
3356 fn trigger_sink(&self, instance_id: &str, batched: bool) -> crate::watchers::EventSink {
3358 let done = self.done_tx.clone();
3359 let found = instance_id.to_owned();
3360 let poke_done = self.done_tx.clone();
3361 let poked = instance_id.to_owned();
3362 crate::watchers::EventSink {
3363 batched,
3364 found: Arc::new(move |event| {
3365 let (stored, answer) = tokio::sync::oneshot::channel();
3366 let _ = done.send(Done::Trigger(TriggerDone::Found {
3367 instance_id: found.clone(),
3368 event,
3369 stored,
3370 }));
3371 answer
3372 }),
3373 poked: Arc::new(move |error| {
3374 let _ = poke_done.send(Done::Trigger(TriggerDone::Poked {
3375 instance_id: poked.clone(),
3376 error,
3377 }));
3378 }),
3379 }
3380 }
3381
3382 fn trigger_done(&mut self, done: TriggerDone, to_master: Option<&ToMaster>) {
3384 match done {
3385 TriggerDone::Found {
3386 instance_id,
3387 event,
3388 stored,
3389 } => self.trigger_found(instance_id, event, stored, to_master),
3390 TriggerDone::Poked { instance_id, error } => {
3391 self.trigger_poked(&instance_id, error, to_master);
3392 }
3393 TriggerDone::Ended {
3394 instance_id,
3395 finished,
3396 } => self.trigger_ended(&instance_id, &finished, to_master),
3397 }
3398 }
3399
3400 fn trigger_found(
3403 &mut self,
3404 instance_id: String,
3405 event: crate::watchers::FoundEvent,
3406 stored: tokio::sync::oneshot::Sender<()>,
3407 to_master: Option<&ToMaster>,
3408 ) {
3409 let Some(trigger) = self.triggers.get_mut(&instance_id) else {
3410 return;
3411 };
3412 trigger.next_seq += 1;
3413 let message = pb::TriggerEvent {
3414 dag_id: trigger.dag_id.clone(),
3415 instance_id,
3416 seq: trigger.next_seq,
3417 key: event.key,
3418 data_json: serde_json::to_vec(&event.data).unwrap_or_default(),
3419 at: event.at.map(proto_time),
3420 };
3421 trigger
3422 .unstored
3423 .insert(trigger.next_seq, (message.clone(), stored));
3424 if let Some(to_master) = to_master {
3425 let _ = to_master.send(wrap(worker_message::Message::TriggerEvent(message)));
3426 }
3427 }
3428
3429 fn trigger_poked(
3431 &mut self,
3432 instance_id: &str,
3433 error: Option<String>,
3434 to_master: Option<&ToMaster>,
3435 ) {
3436 let Some(trigger) = self.triggers.get_mut(instance_id) else {
3437 return;
3438 };
3439 let changed = trigger.poke.error != error;
3440 trigger.poke.failures = if error.is_some() {
3441 trigger.poke.failures.saturating_add(1)
3442 } else {
3443 0
3444 };
3445 trigger.poke.error = error;
3446 trigger.poke.at = Some(Timestamp::now());
3447 trigger.poke.unsent = true;
3448 if changed && let Some(to_master) = to_master {
3449 let _ = to_master.send(poke_report(instance_id, trigger));
3450 trigger.poke.unsent = false;
3451 }
3452 }
3453
3454 fn send_poke_reports(&mut self, to_master: &ToMaster) {
3456 for (instance_id, trigger) in &mut self.triggers {
3457 if trigger.poke.unsent {
3458 let _ = to_master.send(poke_report(instance_id, trigger));
3459 trigger.poke.unsent = false;
3460 }
3461 }
3462 }
3463
3464 fn trigger_ended(
3467 &mut self,
3468 instance_id: &str,
3469 finished: &pb::Finished,
3470 to_master: Option<&ToMaster>,
3471 ) {
3472 let code = self.release_code(instance_id);
3473 self.collect_code();
3474 let Some(trigger) = self.triggers.remove(instance_id) else {
3475 return;
3476 };
3477 let mut stopped = trigger_stopped(trigger.dag_id, instance_id.to_owned(), finished);
3478 stopped.returned_event = trigger.next_seq > 0;
3479 if let Some(code) = code {
3480 stopped.code_hash = code;
3481 }
3482 match to_master {
3483 Some(to_master) => {
3484 let _ = to_master.send(wrap(worker_message::Message::TriggerStopped(stopped)));
3485 }
3486 None => {
3487 self.triggers_ended.insert(instance_id.to_owned(), stopped);
3488 }
3489 }
3490 }
3491
3492 fn unstored_events(&self) -> impl Iterator<Item = pb::WorkerMessage> {
3494 self.triggers
3495 .values()
3496 .flat_map(|trigger| trigger.unstored.values())
3497 .map(|(event, _)| wrap(worker_message::Message::TriggerEvent(event.clone())))
3498 }
3499
3500 async fn moved_cleanup(
3503 &mut self,
3504 spec: AttemptSpec,
3505 handles: Vec<CleanupHandle>,
3506 to_master: &ToMaster,
3507 received: std::time::Instant,
3508 ) {
3509 let id = spec.attempt_id.clone();
3510 let _ = to_master.send(wrap(worker_message::Message::Started(
3511 self.started(&id, pb::StartMethod::Spawn),
3512 )));
3513 self.metrics
3514 .assign_to_started
3515 .observe(received.elapsed().as_secs_f64());
3516 let (stop, _) = Stops::new();
3517 self.running.insert(id.clone(), stop);
3518 self.set_slot_gauges();
3519 let waiting = WaitingCleanup {
3520 spec,
3521 handles,
3522 ended: None,
3523 rest: false,
3524 };
3525 self.start_waiting(&id, waiting, to_master).await;
3526 }
3527
3528 async fn journal_starts(
3533 &self,
3534 ready: &[Prepared],
3535 opened: tokio::time::Instant,
3536 ) -> Vec<Result<(), Option<(pb::RejectReason, String)>>> {
3537 let disk = |error: &std::io::Error| {
3538 let detail = format!(
3539 "can't write the journal in `{}`: {error}; check the worker's data directory",
3540 self.journal.dir().display()
3541 );
3542 Some((pb::RejectReason::DiskNotWritable, detail))
3543 };
3544 let mut outcomes: Vec<Result<(), Option<(pb::RejectReason, String)>>> =
3545 ready.iter().map(|_| Ok(())).collect();
3546 let began = std::time::Instant::now();
3547 let mut writing = Vec::new();
3548 for (at, prepared) in ready.iter().enumerate() {
3549 if matches!(prepared.planned, Err(NotRun::Rejected { .. })) {
3550 continue;
3551 }
3552 #[cfg(test)]
3553 if !self.journal_stall.0.is_zero() {
3554 tokio::time::sleep(self.journal_stall.0).await;
3555 self.journal_stall
3556 .1
3557 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3558 }
3559 match self.keep_for_cleanup(prepared).await {
3560 Ok(()) => writing.push(at),
3561 Err(error) => outcomes[at] = Err(disk(&error)),
3562 }
3563 }
3564 if writing.is_empty() {
3565 return outcomes;
3566 }
3567 let ids: Vec<String> = writing
3568 .iter()
3569 .map(|&at| ready[at].spec.attempt_id.clone())
3570 .collect();
3571 let written = if let [id] = ids.as_slice() {
3572 self.record(id, JournalRecord::Running(None)).await
3573 } else {
3574 let journal = self.journal.clone();
3575 let records = ids.clone();
3576 tokio::task::spawn_blocking(move || {
3577 let running = JournalRecord::Running(None);
3578 let refs: Vec<(&str, &JournalRecord)> =
3579 records.iter().map(|id| (id.as_str(), &running)).collect();
3580 journal.write_many(&refs)
3581 })
3582 .await
3583 .map_err(std::io::Error::other)
3584 .and_then(|written| written)
3585 };
3586 match written {
3587 Ok(()) => self.metrics.journal_written("start", began.elapsed()),
3588 Err(_) if ids.len() > 1 => {
3589 for (&at, id) in writing.iter().zip(&ids) {
3591 if let Err(error) = self.record(id, JournalRecord::Running(None)).await {
3592 outcomes[at] = Err(disk(&error));
3593 }
3594 }
3595 }
3596 Err(error) => outcomes[writing[0]] = Err(disk(&error)),
3597 }
3598 if self.cut_off || self.gone_silent(opened) {
3601 for &at in &writing {
3602 if outcomes[at].is_ok() {
3603 let id = &ready[at].spec.attempt_id;
3604 tracing::warn!(
3605 attempt_id = id.as_str(),
3606 "the lease ran out while the attempt was journaled; not started"
3607 );
3608 self.forget(id).await;
3609 outcomes[at] = Err(None);
3610 }
3611 }
3612 }
3613 outcomes
3617 }
3618
3619 async fn keep_for_cleanup(&self, prepared: &Prepared) -> std::io::Result<()> {
3622 let Prepared {
3623 assign,
3624 spec,
3625 external,
3626 ..
3627 } = prepared;
3628 if spec.task.cleanup.is_none() {
3629 return Ok(());
3630 }
3631 let mut assign = assign.clone();
3632 if let Some(inputs) = external {
3633 assign.inputs_json.clone_from(inputs);
3634 assign.inputs_external = false;
3635 }
3636 let kept = KeptAttempt {
3637 assign,
3638 code_dir: spec.code_dir.clone(),
3639 code_hash: self.code_hash_of(spec),
3640 root_copies: spec.root_copies.clone(),
3641 script_dir: spec.script_dir.clone(),
3642 };
3643 let journal = self.journal.clone();
3644 let id = spec.attempt_id.clone();
3645 tokio::task::spawn_blocking(move || journal.keep(&id, &kept))
3646 .await
3647 .map_err(std::io::Error::other)
3648 .and_then(|kept| kept)
3649 }
3650
3651 fn code_hash_of(&self, spec: &AttemptSpec) -> Option<String> {
3653 self.watchers
3654 .get(&spec.dag_root)
3655 .and_then(RootWatcher::hash)
3656 .map(str::to_owned)
3657 }
3658
3659 fn api_call(
3662 &mut self,
3663 mut call: pb::ApiCall,
3664 answer: oneshot::Sender<pb::ApiAnswer>,
3665 to_master: Option<&ToMaster>,
3666 ) {
3667 if answer.is_closed() {
3669 return;
3670 }
3671 self.api_call_id = self.api_call_id.wrapping_add(1);
3672 call.request_id = self.api_call_id;
3673 let size = prost::Message::encoded_len(&call);
3675 if size > self.master_limit.saturating_sub(1024) {
3676 let error = format!(
3677 "the request is {size} bytes, over the {} the master takes ([grpc] \
3678 max_message_size)",
3679 self.master_limit
3680 );
3681 let _ = answer.send(pb::ApiAnswer {
3682 request_id: call.request_id,
3683 status: 413,
3684 body_json: serde_json::to_vec(&serde_json::json!({ "error": error }))
3685 .unwrap_or_default(),
3686 });
3687 return;
3688 }
3689 if let Some(to_master) = to_master {
3690 let _ = to_master.send(wrap(worker_message::Message::ApiCall(call.clone())));
3691 }
3692 self.api_calls.retain(|_, (_, answer)| !answer.is_closed());
3694 self.api_calls.insert(call.request_id, (call, answer));
3695 }
3696
3697 fn api_send(&self) -> crate::api::ApiSend {
3700 let done = self.done_tx.clone();
3701 Arc::new(move |call| {
3702 let (answer, answered) = oneshot::channel();
3703 let _ = done.send(Done::ApiCall { call, answer });
3704 answered
3705 })
3706 }
3707
3708 fn note_cleanup(&mut self, spec: &mut AttemptSpec, assign: &pb::AssignTask) {
3711 let Some(cleanup) = &spec.task.cleanup else {
3712 return;
3713 };
3714 spec.journal = Some(self.journal.clone());
3715 let done = self.done_tx.clone();
3716 let attempt_id = spec.attempt_id.clone();
3717 spec.handle_sink = Some(HandleSink(Arc::new(move |position, handle| {
3718 let _ = done.send(Done::Handle {
3719 attempt_id: attempt_id.clone(),
3720 position,
3721 handle: handle.clone(),
3722 });
3723 })));
3724 let room = cleanup
3725 .timeout_ms
3726 .map_or(self.settings.setup.timeouts.cleanup, Duration::from_millis);
3727 self.cleanup_room.insert(spec.attempt_id.clone(), room);
3728 let drain = self.settings.drain;
3729 let dag = assign.run.as_ref().map_or("", |run| run.dag_id.as_str());
3730 if cleanup.timeout_ms.is_some()
3732 && !drain.cleanup_fits(room)
3733 && self
3734 .warned_room
3735 .insert((dag.to_owned(), assign.task_id.clone()))
3736 {
3737 tracing::warn!(
3738 dag,
3739 task = assign.task_id.as_str(),
3740 cleanup_timeout = ?room,
3741 grace = ?drain.grace,
3742 "the task's `cleanup_timeout` doesn't fit in `termination_grace_period`: whatever \
3743 ends the worker at the end of a drain (a pod's kill, a service manager) would \
3744 lose its cleanup"
3745 );
3746 }
3747 }
3748
3749 fn launch(&self, spec: AttemptSpec, plan: Plan, stopped: Stops) {
3751 let executor = self.executor.clone();
3752 let done = self.done_tx.clone();
3753 let on_spawn = self.done_tx.clone();
3754 let attempt_id = spec.attempt_id.clone();
3755 let spawned: Spawned = Arc::new(move |identity, forked| {
3756 let _ = on_spawn.send(Done::Spawned {
3757 attempt_id: attempt_id.clone(),
3758 identity,
3759 forked,
3760 });
3761 });
3762 let on_end = self.done_tx.clone();
3763 let ended: TaskEnded = Box::new(move |finished| {
3764 let _ = on_end.send(Done::TaskEnded(finished));
3765 });
3766 tokio::spawn(async move {
3767 let finished = executor.run(spec, plan, stopped, spawned, ended).await;
3768 let _ = done.send(Done::Attempt(finished));
3769 });
3770 }
3771
3772 fn remember_other_copies(&mut self, spec: &AttemptSpec) {
3776 let held: Vec<String> = spec
3777 .root_copies
3778 .values()
3779 .chain(&spec.script_dir)
3780 .filter_map(|dir| Some(dir.file_name()?.to_string_lossy().into_owned()))
3781 .collect();
3782 if !held.is_empty() {
3783 self.other_copies.insert(spec.attempt_id.clone(), held);
3784 }
3785 }
3786
3787 fn release_code(&mut self, attempt_id: &str) -> Option<String> {
3788 self.other_copies.remove(attempt_id);
3789 self.rest_cleaning.remove(attempt_id);
3790 self.code_hashes.remove(attempt_id)
3791 }
3792
3793 fn remember_code(&mut self, assign: &pb::AssignTask, spec: &AttemptSpec) {
3795 let attempt_id = spec.attempt_id.as_str();
3796 self.remember_other_copies(spec);
3797 if let Some(hash) = assign
3798 .dag_file
3799 .as_ref()
3800 .and_then(|f| self.watchers.get(&f.root))
3801 .and_then(RootWatcher::hash)
3802 {
3803 self.code_hashes
3804 .insert(attempt_id.to_owned(), hash.to_owned());
3805 }
3806 }
3807
3808 fn cannot_take(&self, wait_step: bool) -> Option<(pb::RejectReason, &'static str)> {
3810 self.cannot_take_held(wait_step, &Held::default())
3811 }
3812
3813 fn cannot_take_held(
3816 &self,
3817 wait_step: bool,
3818 held: &Held,
3819 ) -> Option<(pb::RejectReason, &'static str)> {
3820 if self.drain.is_some() {
3821 Some((pb::RejectReason::Draining, "the worker is draining"))
3822 } else if wait_step && self.free_watcher_slots() <= held.wait_steps {
3823 Some((pb::RejectReason::NoFreeSlot, "no free watcher slot"))
3824 } else if !wait_step && self.free_slots() <= held.tasks {
3825 Some((pb::RejectReason::NoFreeSlot, "no free slot"))
3826 } else {
3827 None
3828 }
3829 }
3830
3831 fn plan(&self, spec: &mut AttemptSpec, assign: &pb::AssignTask) -> Result<Plan, NotRun> {
3834 spec.default_timeout(assign, &self.settings.setup.timeouts);
3835 let code = self
3838 .watchers
3839 .get(&spec.dag_root)
3840 .and_then(RootWatcher::code_dir);
3841 spec.code_dir = code.map(Path::to_path_buf);
3842 spec.root_copies = self
3843 .watchers
3844 .iter()
3845 .filter(|(name, _)| {
3846 **name != spec.dag_root && !self.settings.setup.script_roots.contains_key(*name)
3847 })
3848 .filter_map(|(name, watcher)| Some((name.clone(), watcher.code_dir()?.to_path_buf())))
3849 .collect();
3850 if let TaskKind::Script { job, .. } = &spec.task.kind {
3852 let root = job.split_once(':').map_or(job.as_str(), |(root, _)| root);
3853 spec.script_dir = self
3854 .watchers
3855 .get(root)
3856 .filter(|_| self.settings.setup.script_roots.contains_key(root))
3857 .and_then(RootWatcher::code_dir)
3858 .map(Path::to_path_buf);
3859 }
3860 let mut moved = None;
3862 if assign.cleanup_only.is_some() {
3863 let mut cleanup = spec.clone();
3864 use_cleanup_script(&mut cleanup.task);
3865 moved = Some(cleanup);
3866 }
3867 let planning = moved.as_ref().unwrap_or(spec);
3868 let planned = match code {
3869 Some(dir) => plan_at(planning, &self.settings.setup, dir),
3870 None => plan(planning, &self.settings.setup),
3871 };
3872 match planned {
3873 Err(NotRun::Rejected {
3874 reason: pb::RejectReason::DagFileMissing | pb::RejectReason::ScriptReferenceNotFound,
3875 detail,
3876 }) if self.has_expected_code(assign) => Err(NotRun::Failed {
3877 kind: DAG_FILE_MISSING.to_owned(),
3878 message: format!("{detail}, in the newest code of its root: the file is gone"),
3879 }),
3880 planned => planned,
3881 }
3882 }
3883
3884 fn has_expected_code(&self, assign: &pb::AssignTask) -> bool {
3886 let expected = assign.expected_code_hash.as_str();
3887 !expected.is_empty()
3888 && assign
3889 .dag_file
3890 .as_ref()
3891 .and_then(|f| self.reported_hash(&f.root))
3892 .as_deref()
3893 == Some(expected)
3894 }
3895
3896 fn code_mismatch(&self, assign: &pb::AssignTask) -> Option<String> {
3899 let root = assign.dag_file.as_ref()?.root.as_str();
3900 let scanned = self
3901 .watchers
3902 .get(root)
3903 .and_then(RootWatcher::hash)
3904 .is_some();
3905 let Some(here) = self.reported_hash(root) else {
3906 return scanned.then(|| {
3908 format!(
3909 "root `{root}` is withdrawn here: a script root it uses isn't on this worker"
3910 )
3911 });
3912 };
3913 let expected = assign.expected_code_hash.as_str();
3914 (!expected.is_empty() && here != expected)
3915 .then(|| format!("root `{root}` here is at {here}, the task expects {expected}"))
3916 }
3917
3918 fn collect_code(&self) {
3921 let mut in_use: std::collections::BTreeSet<String> = self
3922 .code_hashes
3923 .values()
3924 .chain(self.other_copies.values().flatten())
3925 .chain(self.parsing.keys())
3926 .map(|hash| hash.replace(':', "-"))
3927 .collect();
3928 in_use.extend(self.executor.code_in_use());
3929 for watcher in self.watchers.values() {
3930 let Ok(entries) = std::fs::read_dir(watcher.store()) else {
3931 continue;
3932 };
3933 let current = watcher.code_dir();
3934 for entry in entries.flatten() {
3935 let path = entry.path();
3936 let name = entry.file_name().to_string_lossy().into_owned();
3937 if Some(path.as_path()) == current || in_use.contains(&name) {
3938 continue;
3939 }
3940 if let Err(error) = crate::scan::remove_capture(&path) {
3941 tracing::warn!(path = %path.display(), %error, "can't remove old DAG code");
3942 }
3943 }
3944 }
3945 }
3946
3947 fn parse(&mut self, job: pb::AssignParse) {
3948 let Some(root) = job.root else {
3949 return;
3950 };
3951 if self.drain.is_some() {
3952 tracing::info!(
3954 root = root.root.as_str(),
3955 "parse job while draining; left to others"
3956 );
3957 return;
3958 }
3959 let Some(watcher) = self.watchers.get(&root.root) else {
3960 tracing::warn!(
3961 root = root.root.as_str(),
3962 "parse job for a root this worker doesn't have"
3963 );
3964 return;
3965 };
3966 if self.reported_hash(&root.root).as_deref() != Some(root.content_hash.as_str()) {
3967 return;
3969 }
3970 let Some(copy) = watcher.hash().map(str::to_owned) else {
3971 return;
3972 };
3973 let (Some(snapshot), Some(code)) = (watcher.snapshot(), watcher.code_dir()) else {
3974 return;
3975 };
3976 if !self
3977 .parses_running
3978 .insert((root.root.clone(), root.content_hash.clone()))
3979 {
3980 tracing::debug!(root = root.root.as_str(), "parse job already running");
3981 return;
3982 }
3983 let mut files = snapshot.python_files();
3986 if let Some(only) = self.settings.setup.parse_only.get(&root.root) {
3988 files.retain(|file| only.contains(file));
3989 }
3990 let dir = code.to_path_buf();
3991 let done = self.done_tx.clone();
3992 if self.settings.setup.script_roots.contains_key(&root.root) {
3993 let files: Vec<String> = snapshot.files().keys().cloned().collect();
3995 let wanted: Vec<String> = files
3996 .iter()
3997 .filter(|file| crate::jobs::is_config(file))
3998 .cloned()
3999 .collect();
4000 *self.parsing.entry(copy.clone()).or_default() += 1;
4001 tokio::task::spawn_blocking(move || {
4002 let parsed = crate::jobs::read_root(&root.root, &dir, (&files, &wanted), None);
4003 let _ = done.send(Done::Parse {
4004 job_id: job.parse_job_id,
4005 root,
4006 copies: vec![copy],
4007 files: Ok(parsed),
4008 });
4009 });
4010 return;
4011 }
4012 let (code, mut copies) = self.parse_code(&root.root);
4013 copies.push(copy);
4014 for copy in &copies {
4015 *self.parsing.entry(copy.clone()).or_default() += 1;
4016 }
4017 let executor = self.executor.clone();
4018 tokio::spawn(async move {
4019 let parsed = executor.parse(root.root.clone(), dir, files, code).await;
4020 let _ = done.send(Done::Parse {
4021 job_id: job.parse_job_id,
4022 root,
4023 copies,
4024 files: parsed,
4025 });
4026 });
4027 }
4028
4029 fn parse_code(&self, root: &str) -> (ParseCode, Vec<String>) {
4032 let mut code = ParseCode::default();
4033 let mut held = Vec::new();
4034 for (name, watcher) in &self.watchers {
4035 let (Some(hash), Some(dir)) = (watcher.hash(), watcher.code_dir()) else {
4036 continue;
4037 };
4038 if name == root {
4039 continue;
4040 }
4041 if let Some(configured) = self.settings.setup.script_roots.get(name) {
4042 code.scripts.insert(
4043 name.clone(),
4044 crate::jobs::ScriptRoot {
4045 configured: configured.clone(),
4046 copy: dir.to_path_buf(),
4047 },
4048 );
4049 } else {
4050 code.roots.insert(name.clone(), dir.to_path_buf());
4051 }
4052 held.push(hash.to_owned());
4053 }
4054 (code, held)
4055 }
4056
4057 fn connection_job(&mut self, job: pb::ConnectionJob) {
4060 let job_id = job.job_id.clone();
4061 let root = job.root.unwrap_or_default();
4062 let registry: Registry = match serde_json::from_slice(&job.connections_json) {
4063 Ok(registry) => registry,
4064 Err(e) => {
4065 tracing::warn!(job_id, error = %e, "a connections job that doesn't read");
4066 return;
4067 }
4068 };
4069 let watcher = self.watchers.get(&root.root);
4071 let current = self.reported_hash(&root.root).as_deref() == Some(root.content_hash.as_str());
4072 let code_dir = watcher
4073 .filter(|_| current)
4074 .and_then(|w| w.code_dir().map(Path::to_path_buf));
4075 let hash = code_dir
4077 .as_ref()
4078 .and_then(|_| watcher.and_then(RootWatcher::hash).map(str::to_owned));
4079 if let Some(hash) = &hash {
4080 *self.parsing.entry(hash.clone()).or_default() += 1;
4081 }
4082 let test = job
4083 .test
4084 .map(|t| (t.name, Duration::from_millis(t.timeout_ms)));
4085 if test.is_some() && code_dir.is_none() {
4086 let name = test.map(|(name, _)| name).unwrap_or_default();
4087 let why = format!(
4088 "this worker no longer has root `{}` at the code it was sent for: try again",
4089 root.root
4090 );
4091 let _ = self.done_tx.send(Done::Connections {
4092 job_id,
4093 hash,
4094 attempt_id: None,
4095 reports: vec![crate::connection_jobs::failed(&name, why)],
4096 });
4097 return;
4098 }
4099 let allowed = test.as_ref().map_or(
4102 Duration::from_millis(schedr_model::commands::CONNECTION_CHECK_TIMEOUT_MS),
4103 |(_, timeout)| *timeout,
4104 );
4105 let deadline = tokio::time::Instant::now() + allowed;
4106 let attempt_id = format!("connection-test-{}", jiff::Timestamp::now().as_nanosecond());
4108 let tested = test.is_some().then(|| attempt_id.clone());
4109 let job = ConnectionJob {
4110 root: root.root,
4111 code_dir,
4112 registry: Arc::new(registry),
4113 test,
4114 cancel_grace: self.settings.setup.timeouts.connection_cancel_grace,
4115 attempt_id: attempt_id.clone(),
4116 deadline,
4117 };
4118 let executor = self.executor.clone();
4119 let done = self.done_tx.clone();
4120 let on_spawn = self.done_tx.clone();
4121 let spawned: Spawned = Arc::new(move |identity, _| {
4123 let _ = on_spawn.send(Done::Spawned {
4124 attempt_id: attempt_id.clone(),
4125 identity,
4126 forked: false,
4127 });
4128 });
4129 let one_at_a_time = Arc::clone(&self.connection_jobs);
4130 tokio::spawn(async move {
4131 let reports = match tokio::time::timeout_at(deadline, one_at_a_time.lock()).await {
4132 Ok(_turn) => executor.connection_job(job, spawned).await,
4133 Err(_) => job
4134 .registry
4135 .names()
4136 .map(|name| {
4137 crate::connection_jobs::failed(
4138 name,
4139 crate::connection_jobs::out_of_time(
4140 "wait for its turn (one connections job at a time per worker)",
4141 ),
4142 )
4143 })
4144 .collect(),
4145 };
4146 let _ = done.send(Done::Connections {
4147 job_id,
4148 hash,
4149 attempt_id: tested,
4150 reports,
4151 });
4152 });
4153 }
4154
4155 async fn on_done(&mut self, done: Done, link: Option<(&ToMaster, &mut MasterClient<Channel>)>) {
4158 match done {
4159 Done::Spawned {
4160 attempt_id,
4161 identity,
4162 forked,
4163 } => {
4164 let to_master = link.as_ref().map(|(to_master, _)| *to_master);
4165 let (record, repeat) = self.spawned_record(&attempt_id, identity, forked);
4166 self.keep_processes(vec![(attempt_id, record, repeat)], to_master)
4167 .await;
4168 }
4169 Done::TaskEnded(finished) => {
4170 self.task_ended(finished, link.map(|(to_master, _)| to_master))
4171 .await;
4172 }
4173 Done::Handle {
4174 attempt_id,
4175 position,
4176 handle,
4177 } => {
4178 if let Some((to_master, _)) = link {
4179 let _ = to_master.send(handles_message(attempt_id, position, &[handle]));
4180 }
4181 }
4182 Done::Attempt(finished) => {
4183 let finished = self.result_ready(finished);
4184 self.record_finished(&finished).await;
4185 self.result_recorded(finished, link.map(|(to_master, _)| to_master));
4186 }
4187 Done::Trigger(done) => self.trigger_done(done, link.map(|(to, _)| to)),
4188 Done::ApiCall { call, answer } => {
4189 self.api_call(call, answer, link.map(|(to, _)| to));
4190 }
4191 Done::Parse {
4192 job_id,
4193 root,
4194 copies,
4195 files,
4196 } => {
4197 self.parses_running
4198 .remove(&(root.root.clone(), root.content_hash.clone()));
4199 for copy in copies {
4200 if let Some(count) = self.parsing.get_mut(©) {
4201 *count -= 1;
4202 if *count == 0 {
4203 self.parsing.remove(©);
4204 }
4205 }
4206 }
4207 self.collect_code();
4208 self.report_parse(job_id, root, files, link);
4209 }
4210 Done::Connections {
4211 job_id,
4212 hash,
4213 attempt_id,
4214 reports,
4215 } => {
4216 self.connections_done(job_id, hash, attempt_id, &reports, link.map(|(to, _)| to))
4217 .await;
4218 }
4219 }
4220 }
4221
4222 async fn connections_done(
4225 &mut self,
4226 job_id: String,
4227 hash: Option<String>,
4228 attempt_id: Option<String>,
4229 reports: &[schedr_model::commands::ConnectionReport],
4230 to_master: Option<&ToMaster>,
4231 ) {
4232 if let Some(attempt_id) = attempt_id {
4233 self.forget(&attempt_id).await;
4234 }
4235 if let Some(hash) = hash
4236 && let Some(count) = self.parsing.get_mut(&hash)
4237 {
4238 *count -= 1;
4239 if *count == 0 {
4240 self.parsing.remove(&hash);
4241 }
4242 self.collect_code();
4243 }
4244 let report_json = reports
4245 .iter()
4246 .filter_map(|report| serde_json::to_vec(report).ok())
4247 .collect();
4248 let done = pb::ConnectionJobDone {
4249 job_id,
4250 report_json,
4251 };
4252 if let Some(to_master) = to_master {
4253 let _ = to_master.send(wrap(worker_message::Message::ConnectionJobDone(done)));
4254 } else {
4255 if self.unsent_answers.len() >= self.settings.setup.timeouts.unsent_connection_answers {
4257 self.unsent_answers.pop_front();
4258 }
4259 self.unsent_answers.push_back(done);
4260 }
4261 }
4262
4263 fn report_parse(
4265 &self,
4266 job_id: String,
4267 root: pb::RootHash,
4268 files: Result<Vec<ParsedFile>, String>,
4269 link: Option<(&ToMaster, &mut MasterClient<Channel>)>,
4270 ) {
4271 match (files, link) {
4272 (Ok(_), None) => tracing::warn!(
4273 root = root.root.as_str(),
4274 "parse result dropped: no master connection (the job is given out again)"
4275 ),
4276 (Ok(files), Some((_, client))) => {
4277 let limit = self.master_limit;
4278 let result = pb::ParseResult {
4279 parse_job_id: job_id,
4280 worker_id: self.settings.worker_id.clone(),
4281 root: Some(root),
4282 schedr_version: AGENT_VERSION.to_owned(),
4283 files: files
4284 .iter()
4285 .map(|file| fitted_file(parsed_file_to_proto(file), limit))
4286 .collect(),
4287 };
4288 let parts = tokio_stream::iter(parse_upload_parts(result));
4292 let mut client = client.clone();
4293 tokio::spawn(async move {
4294 if let Err(status) = client.upload_parse_result(parts).await {
4295 tracing::error!(%status, "parse result not uploaded");
4296 }
4297 });
4298 }
4299 (Err(error), _) => {
4300 tracing::error!(root = root.root.as_str(), error, "parse job failed");
4301 }
4302 }
4303 }
4304
4305 fn watch(&mut self, to_master: &ToMaster) {
4306 let mut changed_any = false;
4307 for (name, watcher) in &mut self.watchers {
4308 match watcher.poll(Instant::now()) {
4309 Ok(Poll::Changed { .. }) => changed_any = true,
4310 Ok(_) => {}
4311 Err(error) => tracing::warn!(root = name.as_str(), %error, "can't scan the root"),
4312 }
4313 }
4314 if changed_any {
4315 self.report_changes(to_master);
4317 self.collect_code();
4319 }
4320 }
4321
4322 fn cleaning_rest(&self, id: &str) -> bool {
4324 self.rest_cleaning.contains(id)
4325 }
4326
4327 fn handle_count(&self, id: &str) -> u32 {
4331 let waiting = self.waiting.get(id).map_or(0, |w| w.handles.len());
4332 let journaled = self.journal.handles(id).map_or_else(
4333 |error| {
4334 tracing::warn!(attempt_id = id, %error, "can't read the journaled handles");
4335 0
4336 },
4337 |handles| handles.len(),
4338 );
4339 u32::try_from(journaled.max(waiting)).unwrap_or(u32::MAX)
4340 }
4341
4342 fn journal_entries(&self) -> Vec<pb::JournalEntry> {
4343 let running = self.running.keys().map(|id| pb::JournalEntry {
4344 attempt_id: id.clone(),
4345 state: pb::JournalState::Running.into(),
4346 handles: self.handle_count(id),
4347 });
4348 let finished = self.unacked.keys().map(|id| pb::JournalEntry {
4349 attempt_id: id.clone(),
4350 state: pb::JournalState::Finished.into(),
4351 handles: self.handle_count(id),
4352 });
4353 running.chain(finished).collect()
4354 }
4355
4356 fn free_slots(&self) -> u32 {
4357 if self.drain.is_some() {
4358 return 0;
4359 }
4360 self.settings
4361 .slots
4362 .saturating_sub(u32::try_from(self.tasks_running()).unwrap_or(u32::MAX))
4363 }
4364
4365 fn free_watcher_slots(&self) -> u32 {
4366 if self.drain.is_some() {
4367 return 0;
4368 }
4369 self.settings
4370 .watcher_slots
4371 .saturating_sub(u32::try_from(self.wait_steps.len()).unwrap_or(u32::MAX))
4372 .saturating_sub(u32::try_from(self.triggers.len()).unwrap_or(u32::MAX))
4373 }
4374
4375 fn note_wait_step(&mut self, spec: &AttemptSpec) {
4376 if let schedr_model::TaskKind::Sensor { mode, .. } = spec.task.kind {
4377 self.wait_steps.insert(
4378 spec.attempt_id.clone(),
4379 mode == schedr_model::SensorMode::Poke,
4380 );
4381 }
4382 }
4383
4384 fn ended_running(&mut self, attempt_id: &str) {
4385 self.running.remove(attempt_id);
4386 self.wait_steps.remove(attempt_id);
4387 self.set_slot_gauges();
4388 }
4389
4390 fn tasks_running(&self) -> usize {
4392 self.running.len().saturating_sub(self.wait_steps.len())
4393 }
4394}
4395
4396fn forked_started(attempt_id: &str) -> pb::WorkerMessage {
4399 wrap(worker_message::Message::Started(pb::Started {
4400 attempt_id: attempt_id.to_owned(),
4401 start_method: pb::StartMethod::Fork.into(),
4402 ..pb::Started::default()
4404 }))
4405}
4406
4407enum TriggerDone {
4409 Found {
4411 instance_id: String,
4412 event: crate::watchers::FoundEvent,
4413 stored: tokio::sync::oneshot::Sender<()>,
4414 },
4415 Poked {
4417 instance_id: String,
4418 error: Option<String>,
4419 },
4420 Ended {
4422 instance_id: String,
4423 finished: Box<pb::Finished>,
4424 },
4425}
4426
4427#[derive(Debug, Default)]
4429struct PokeReport {
4430 at: Option<Timestamp>,
4431 error: Option<String>,
4432 failures: u32,
4433 unsent: bool,
4434}
4435
4436#[derive(Debug)]
4438struct RunningTrigger {
4439 dag_id: String,
4440 stop: StopSender,
4441 next_seq: u64,
4442 unstored: BTreeMap<u64, (pb::TriggerEvent, tokio::sync::oneshot::Sender<()>)>,
4444 poke: PokeReport,
4445}
4446
4447fn poke_report(instance_id: &str, trigger: &RunningTrigger) -> pb::WorkerMessage {
4448 wrap(worker_message::Message::TriggerPoked(pb::TriggerPoked {
4449 dag_id: trigger.dag_id.clone(),
4450 instance_id: instance_id.to_owned(),
4451 at: trigger.poke.at.map(proto_time),
4452 error: trigger.poke.error.clone().unwrap_or_default(),
4453 failures: trigger.poke.failures,
4454 }))
4455}
4456
4457fn proto_time(time: Timestamp) -> prost_types::Timestamp {
4458 prost_types::Timestamp {
4459 seconds: time.as_second(),
4460 nanos: time.subsec_nanosecond(),
4461 }
4462}
4463
4464fn trigger_stopped(
4467 dag_id: String,
4468 instance_id: String,
4469 finished: &pb::Finished,
4470) -> pb::TriggerStopped {
4471 let asked = finished.status == pb::AttemptStatus::Cancelled as i32
4472 || finished.status == pb::AttemptStatus::Interrupted as i32
4473 || finished.status == pb::AttemptStatus::Success as i32;
4474 let (error_kind, message) = if asked {
4475 (String::new(), String::new())
4476 } else {
4477 let summary: Option<schedr_model::runner::ErrorSummary> =
4478 serde_json::from_slice(&finished.error_summary_json).ok();
4479 let kind = if finished.error_kind.is_empty() {
4480 "trigger_failed".to_owned()
4481 } else {
4482 finished.error_kind.clone()
4483 };
4484 (
4485 kind,
4486 summary.map_or_else(String::new, |s| format!("{}: {}", s.exception, s.message)),
4487 )
4488 };
4489 pb::TriggerStopped {
4490 dag_id,
4491 instance_id,
4492 error_kind,
4493 message,
4494 struck: finished.struck,
4495 code_hash: finished.code_hash.clone(),
4496 done: finished.status == pb::AttemptStatus::Success as i32,
4497 returned_event: false,
4498 }
4499}
4500
4501fn assigned_a_wait_step(assign: &pb::AssignTask) -> bool {
4503 serde_json::from_slice::<schedr_model::Task>(&assign.task_json)
4504 .is_ok_and(|task| matches!(task.kind, schedr_model::TaskKind::Sensor { .. }))
4505}
4506
4507fn heartbeat_timer(period: Duration) -> tokio::time::Interval {
4510 let mut interval = tokio::time::interval(period);
4511 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
4512 interval
4513}
4514
4515#[derive(Debug)]
4520struct Resends {
4521 beat: u64,
4523 due: BTreeMap<String, Resend>,
4525 most: u32,
4527 gap_max: u32,
4529}
4530
4531impl Default for Resends {
4532 fn default() -> Self {
4533 Self::limited(MAX_RESENDS, MAX_RESEND_GAP)
4534 }
4535}
4536
4537#[derive(Debug, Clone, Copy)]
4538struct Resend {
4539 at: u64,
4540 gap: u32,
4541 sent: u32,
4542}
4543
4544impl Resends {
4545 fn limited(most: u32, gap_max: u32) -> Self {
4547 Self {
4548 beat: 0,
4549 due: BTreeMap::new(),
4550 most: most.max(1),
4551 gap_max: gap_max.max(1),
4552 }
4553 }
4554
4555 fn due<'a>(&mut self, unacked: impl Iterator<Item = &'a String>) -> Option<Vec<String>> {
4559 self.beat += 1;
4560 let beat = self.beat;
4561 let mut due = BTreeMap::new();
4562 let mut send = Vec::new();
4563 for id in unacked {
4564 let mut resend = self.due.get(id).copied().unwrap_or(Resend {
4565 at: beat + 1,
4566 gap: 1,
4567 sent: 0,
4568 });
4569 if resend.at <= beat {
4570 if resend.sent >= self.most {
4571 return None;
4572 }
4573 send.push(id.clone());
4574 resend.gap = resend.gap.saturating_mul(2).min(self.gap_max);
4575 resend.at = beat + u64::from(resend.gap);
4576 resend.sent += 1;
4577 }
4578 due.insert(id.clone(), resend);
4579 }
4580 self.due = due;
4581 Some(send)
4582 }
4583}
4584
4585fn code_folder(name: &str) -> String {
4589 use sha2::Digest as _;
4590 let readable: String = name
4591 .chars()
4592 .map(|c| {
4593 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
4594 c
4595 } else {
4596 '_'
4597 }
4598 })
4599 .collect();
4600 let digest = sha2::Sha256::digest(name.as_bytes());
4601 format!(
4602 "{readable}-{:02x}{:02x}{:02x}{:02x}",
4603 digest[0], digest[1], digest[2], digest[3]
4604 )
4605}
4606
4607enum Fetched {
4609 Bytes(Vec<u8>),
4610 Failed(String),
4611 Silent,
4613}
4614
4615async fn fetch_inputs(
4618 client: &mut MasterClient<Channel>,
4619 attempt_id: &str,
4620 heard: &watch::Sender<tokio::time::Instant>,
4621 lease: Option<Duration>,
4622) -> Fetched {
4623 let stream = client
4624 .fetch_inputs(pb::FetchInputsRequest {
4625 attempt_id: attempt_id.to_owned(),
4626 })
4627 .await;
4628 let mut stream = match stream {
4629 Ok(response) => response.into_inner(),
4630 Err(status) => return Fetched::Failed(status.to_string()),
4631 };
4632 let mut bytes = Vec::new();
4633 loop {
4634 match stream.message().await {
4635 Ok(Some(chunk)) => {
4636 let now = tokio::time::Instant::now();
4637 if lease.is_some_and(|lease| now >= *heard.borrow() + lease) {
4638 return Fetched::Silent;
4639 }
4640 heard.send_replace(now);
4641 bytes.extend(chunk.data);
4642 }
4643 Ok(None) => return Fetched::Bytes(bytes),
4644 Err(status) => return Fetched::Failed(status.to_string()),
4645 }
4646 }
4647}
4648
4649#[must_use]
4653pub fn fold_hash(kind: &str, content: &str, used: &[(String, String)]) -> String {
4654 use sha2::{Digest, Sha256};
4655 let mut hasher = Sha256::new();
4656 hasher.update(kind.as_bytes());
4657 hasher.update(b"\n");
4658 hasher.update(content.as_bytes());
4659 for (name, hash) in used {
4660 hasher.update(b"\n");
4661 hasher.update(name.as_bytes());
4662 hasher.update(b"=");
4663 hasher.update(hash.as_bytes());
4664 }
4665 let digest = hasher.finalize();
4666 let mut text = String::with_capacity(crate::scan::HASH_PREFIX.len() + 64);
4667 text.push_str(crate::scan::HASH_PREFIX);
4668 for byte in digest {
4669 use std::fmt::Write as _;
4670 let _ = write!(text, "{byte:02x}");
4671 }
4672 text
4673}
4674
4675fn root_hash(setup: &WorkerSetup, name: &str, hash: &str) -> pb::RootHash {
4676 let kind = if setup.script_roots.contains_key(name) {
4677 pb::RootKind::Script
4678 } else {
4679 pb::RootKind::Dag
4680 };
4681 pb::RootHash {
4682 kind: kind.into(),
4683 root: name.to_owned(),
4684 content_hash: hash.to_owned(),
4685 }
4686}
4687
4688const GRPC_DEFAULT_LIMIT: usize = 4 << 20;
4690
4691const MESSAGE_OVERHEAD: usize = 64 << 10;
4693
4694fn fit_result(finished: &mut pb::Finished, limit: usize) {
4699 let fits = |finished: &pb::Finished| {
4700 prost::Message::encoded_len(finished).saturating_add(MESSAGE_OVERHEAD) <= limit
4701 };
4702 if fits(finished) {
4703 return;
4704 }
4705 if let Some(cleanup) = finished.cleanup.as_mut()
4706 && !cleanup.error_summary_json.is_empty()
4707 {
4708 let message = format!(
4709 "the cleanup's error took {} bytes, too many to report",
4710 cleanup.error_summary_json.len()
4711 );
4712 cleanup.error_summary_json = ErrorSummary::json("ResultTooLarge", &message).into_bytes();
4713 if fits(finished) {
4714 return;
4715 }
4716 }
4717 let size = prost::Message::encoded_len(finished);
4718 let message = format!(
4719 "the result is {size} bytes, more than the master accepts ({limit} bytes, [grpc] \
4720 max_message_size): lower the task's max_output_size, or raise the setting"
4721 );
4722 tracing::error!(attempt_id = finished.attempt_id.as_str(), %message, "result too large");
4723 finished.status = pb::AttemptStatus::Failed.into();
4724 finished.output_json = Vec::new();
4725 finished.outcome = String::new();
4726 "output_too_large".clone_into(&mut finished.error_kind);
4727 finished.error_summary_json = ErrorSummary::json("ResultTooLarge", &message).into_bytes();
4728}
4729
4730fn fitted_file(file: pb::ParsedFile, limit: usize) -> pb::ParsedFile {
4733 let size = prost::Message::encoded_len(&file);
4734 if size.saturating_add(MESSAGE_OVERHEAD) <= limit {
4735 return file;
4736 }
4737 let message = format!(
4738 "the file's parse result is {size} bytes, more than the master accepts ({limit} \
4739 bytes, [grpc] max_message_size): raise the setting, or split the file"
4740 );
4741 tracing::error!(path = file.path.as_str(), %message, "parsed file not uploaded");
4742 pb::ParsedFile {
4743 path: file.path,
4744 dag_json: Vec::new(),
4745 import_error: Some(pb::ImportError {
4746 exception: schedr_model::runner::PARSE_RESULT_TOO_LARGE_EXCEPTION.to_owned(),
4747 message,
4748 traceback: String::new(),
4749 }),
4750 connection_json: Vec::new(),
4751 script_roots: file.script_roots,
4753 }
4754}
4755
4756pub const DEREGISTER_WAIT: Duration = Duration::from_hours(1);
4762
4763pub const DRAIN_TICK: Duration = Duration::from_millis(100);
4765
4766async fn next_request(shutdown: &mut Option<watch::Receiver<u32>>) -> u32 {
4768 if let Some(requests) = shutdown
4769 && requests.changed().await.is_ok()
4770 {
4771 return *requests.borrow();
4772 }
4773 std::future::pending().await
4774}
4775
4776fn handles_message(attempt_id: String, first: u32, handles: &[CleanupHandle]) -> pb::WorkerMessage {
4778 wrap(worker_message::Message::HandlesAdded(pb::HandlesAdded {
4779 attempt_id,
4780 first,
4781 handle_json: handles
4782 .iter()
4783 .filter_map(|handle| serde_json::to_vec(handle).ok())
4784 .collect(),
4785 }))
4786}
4787
4788fn task_ended_message(result: pb::Finished) -> pb::WorkerMessage {
4790 wrap(worker_message::Message::TaskEnded(pb::TaskEnded {
4791 result: Some(result),
4792 }))
4793}
4794
4795const NO_WORD: &str = "no word from the master for the worker lease";
4797
4798fn earliest(
4800 a: Option<tokio::time::Instant>,
4801 b: Option<tokio::time::Instant>,
4802) -> Option<tokio::time::Instant> {
4803 a.into_iter().chain(b).min()
4804}
4805
4806const TOO_LATE: &str = "the master's answer came after the worker lease; asking again";
4808
4809async fn at(when: Option<tokio::time::Instant>) {
4811 match when {
4812 Some(when) => tokio::time::sleep_until(when).await,
4813 None => std::future::pending().await,
4814 }
4815}
4816
4817fn moved_handles(only: &pb::CleanupOnly) -> Result<Vec<CleanupHandle>, serde_json::Error> {
4819 only.handle_json
4820 .iter()
4821 .map(|json| serde_json::from_slice(json))
4822 .collect()
4823}
4824
4825fn restarted(attempt_id: &str) -> pb::Finished {
4828 let message = "the worker's agent restarted while the attempt ran (possibly out of memory)";
4829 pb::Finished {
4830 attempt_id: attempt_id.to_owned(),
4831 status: pb::AttemptStatus::Lost.into(),
4832 error_summary_json: ErrorSummary::json("WorkerRestarted", message).into_bytes(),
4833 ..pb::Finished::default()
4834 }
4835}
4836
4837const fn wrap(message: worker_message::Message) -> pb::WorkerMessage {
4838 pb::WorkerMessage {
4839 message: Some(message),
4840 clock: None,
4841 }
4842}
4843
4844struct ToMaster {
4850 sender: mpsc::UnboundedSender<pb::WorkerMessage>,
4851 outbox: SharedOutbox,
4852}
4853
4854impl ToMaster {
4855 const fn new(sender: mpsc::UnboundedSender<pb::WorkerMessage>, outbox: SharedOutbox) -> Self {
4856 Self { sender, outbox }
4857 }
4858
4859 fn send(&self, mut message: pb::WorkerMessage) -> Result<(), mpsc::error::SendError<()>> {
4861 let mut outbox = crate::master_time::lock(&self.outbox);
4863 message.clock = Some(outbox.stamp(Local::now()));
4864 self.sender
4865 .send(message)
4866 .map_err(|_| mpsc::error::SendError(()))
4867 }
4868
4869 fn handled(&self, sequence: u64) {
4871 crate::master_time::lock(&self.outbox).handled(sequence);
4872 }
4873}
4874
4875fn ended_with_secrets(finished: &mut pb::Finished, secrets: &AttemptSecrets, python: bool) {
4879 if python && !secrets.mask.is_empty() {
4880 for field in [&mut finished.output_json, &mut finished.error_summary_json] {
4881 if field.is_empty() {
4882 continue;
4883 }
4884 if let Ok(value) = serde_json::from_slice::<serde_json::Value>(field) {
4885 *field = serde_json::to_vec(&secrets.mask.mask_json(&value)).unwrap_or_default();
4886 } else {
4887 *field = secrets.mask.mask(field);
4888 }
4889 }
4890 }
4891 let failed = finished.status == i32::from(pb::AttemptStatus::Failed);
4892 if failed
4893 && finished.error_kind.is_empty()
4894 && let Some(kind) = secrets.failed_kind()
4895 {
4896 kind.clone_into(&mut finished.error_kind);
4897 }
4898}
4899
4900fn too_short_lines(secrets: &AttemptSecrets, min: usize) -> String {
4903 use std::fmt::Write as _;
4904 let short = std::mem::take(
4905 &mut *secrets
4906 .too_short
4907 .lock()
4908 .unwrap_or_else(PoisonError::into_inner),
4909 );
4910 let mut lines = String::new();
4911 for name in &short {
4912 let _ = writeln!(
4913 lines,
4914 "schedr: `{name}` is too short to be masked (under {min} characters, \
4915 [secret_storage] min_mask_length): it shows in this log as it is"
4916 );
4917 }
4918 lines
4919}
4920
4921fn masked_lines(secrets: &AttemptSecrets) -> String {
4923 use std::fmt::Write as _;
4924 let mut lines = String::new();
4925 for (label, count) in secrets.mask.counts() {
4926 let times = if count == 1 {
4927 "once".to_owned()
4928 } else {
4929 format!("{count} times")
4930 };
4931 let _ = writeln!(
4932 lines,
4933 "schedr: `{label}` was masked {times} in this task's log and output (`****`): \
4934 every text equal to its value is masked, also where it isn't the secret"
4935 );
4936 }
4937 secrets.mask.mask_text(&lines)
4939}
4940
4941async fn append_log(path: &Path, text: &str) {
4944 if text.is_empty() {
4945 return;
4946 }
4947 match crate::process::open_log_file(path).await {
4948 Ok(mut file) => {
4949 use tokio::io::AsyncWriteExt as _;
4950 let _ = file.write_all(text.as_bytes()).await;
4951 let _ = file.flush().await;
4952 }
4953 Err(error) => tracing::warn!(%error, path = %path.display(), "can't write to a task log"),
4954 }
4955}
4956
4957async fn sleep_for(timeout: Option<Duration>) {
4959 match timeout {
4960 Some(timeout) => tokio::time::sleep(timeout).await,
4961 None => std::future::pending().await,
4962 }
4963}
4964
4965fn stopped_before_start(
4968 spec: &AttemptSpec,
4969 reason: StopReason,
4970 duration: Duration,
4971) -> pb::Finished {
4972 let ran = Ran {
4973 supervised: crate::supervise::Supervised {
4974 termination: crate::status::Termination::Unknown,
4975 stopped: Some(reason),
4976 killed: false,
4977 },
4978 runner_result: None,
4979 output: None,
4980 duration,
4981 start: None,
4982 forked: false,
4983 ended: crate::usage::Ended::default(),
4984 moved_to: None,
4985 host_lost: None,
4986 struck: false,
4987 };
4988 finished(&spec.attempt_id, &spec.task, &ran)
4989}
4990
4991fn batches(task: &schedr_model::Task) -> bool {
4993 matches!(
4994 task.kind,
4995 schedr_model::TaskKind::Sensor {
4996 batch_ms: Some(_),
4997 ..
4998 }
4999 )
5000}
5001
5002fn first_api_call_id() -> u64 {
5005 std::time::SystemTime::now()
5006 .duration_since(std::time::UNIX_EPOCH)
5007 .map_or(0, |since| {
5008 u64::try_from(since.as_nanos()).unwrap_or(u64::MAX)
5009 })
5010}