1use std::collections::{BTreeMap, BTreeSet};
9use std::sync::{Arc, Mutex};
10use std::time::Duration;
11
12use tokio::sync::{Notify, mpsc, oneshot, watch};
13use tracing::{info, warn};
14
15use super::records::RecordSelection;
16use super::stop::Stop;
17use super::{Engine, Occupant, Slot};
18use crate::actions::policy::{Policies, Policy};
19use crate::api;
20use crate::cache;
21use crate::config::{ByteSize, Config};
22use crate::docker::{DockerApi, Tty, TtySize};
23use crate::github::GithubApi;
24use crate::isolation;
25use crate::scheduler::{SlotRef, StopReason};
26use crate::sizing::auto;
27use crate::store::Store;
28use crate::sync::lock;
29use crate::time;
30
31pub(super) const CANCEL_GRACE: Duration = Duration::from_secs(90);
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
38pub enum Shutdown {
39 No,
41 Graceful,
43 Detach,
46 Force,
48}
49
50impl Shutdown {
51 pub fn stopping(self) -> Option<api::Stopping> {
53 match self {
54 Shutdown::No => None,
55 Shutdown::Graceful => Some(api::Stopping::WaitsForJobs),
56 Shutdown::Detach => Some(api::Stopping::LeavesJobs),
57 Shutdown::Force => Some(api::Stopping::KillsJobs),
58 }
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum RunningJobs {
65 Keep,
67 Kill,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum RunningSlots {
74 Drain,
76 Keep,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum Author {
83 Owner,
86 AutoSizing,
88}
89
90pub fn same_slice(running: &Config, new: &Config) -> Result<(), ControlError> {
93 if new.host.slice == running.host.slice {
94 return Ok(());
95 }
96 Err(ControlError::Invalid(format!(
97 "restart runnerd to change the slice: it runs in {}, and host.slice is {} in the new config",
98 running.host.slice, new.host.slice
99 )))
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum Target {
105 Repository(String),
107 All,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
113pub enum ControlError {
114 #[error("{0}")]
116 NotFound(String),
117 #[error("{message}")]
119 Busy {
120 message: String,
122 jobs: Vec<api::RunningJob>,
124 },
125 #[error("{0}")]
127 Conflict(String),
128 #[error("{0}")]
130 Invalid(String),
131 #[error("{0}")]
133 Failed(String),
134 #[error("{0}")]
136 NotRecorded(String),
137 #[error("runnerd is stopping")]
139 Stopped,
140}
141
142#[derive(Debug)]
144pub enum Command {
145 Pause {
147 target: Target,
149 jobs: RunningJobs,
151 reply: oneshot::Sender<Result<api::Paused, ControlError>>,
153 },
154 Resume {
156 target: Target,
158 reply: oneshot::Sender<Result<(), ControlError>>,
160 },
161 Reseed {
163 profile: String,
165 reply: oneshot::Sender<Result<(), ControlError>>,
167 },
168 CleanCache {
170 name: String,
172 reply: oneshot::Sender<Result<(), ControlError>>,
174 },
175 ReplaceConfig {
177 config: Box<Config>,
179 memory_max: Option<u64>,
181 cpus: Option<u64>,
183 commit: Commit,
185 running: RunningSlots,
187 author: Author,
189 reply: oneshot::Sender<Result<Vec<String>, ControlError>>,
192 },
193 RemoveRecords {
195 selection: RecordSelection,
197 reply: oneshot::Sender<Result<api::RemovedRecords, ControlError>>,
199 },
200 OpenShell {
202 job: u64,
204 size: TtySize,
206 reply: oneshot::Sender<Result<Tty, ControlError>>,
208 },
209 CloseShell {
211 container: String,
213 },
214}
215
216pub struct Commit(Box<dyn FnOnce() -> Result<Option<String>, String> + Send>);
219
220impl Commit {
221 pub fn new(write: impl FnOnce() -> Result<Option<String>, String> + Send + 'static) -> Commit {
223 Commit(Box::new(write))
224 }
225
226 pub async fn run(self) -> Result<Option<String>, String> {
228 tokio::task::spawn_blocking(self.0)
229 .await
230 .unwrap_or_else(|join_error| Err(join_error.to_string()))
231 }
232}
233
234impl std::fmt::Debug for Commit {
235 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236 f.write_str("Commit")
237 }
238}
239
240#[derive(Debug)]
242pub struct Commands(mpsc::UnboundedReceiver<Command>);
243
244impl Commands {
245 pub async fn recv(&mut self) -> Option<Command> {
247 self.0.recv().await
248 }
249}
250
251#[derive(Debug)]
253pub struct Control {
254 repositories: Mutex<BTreeSet<String>>,
257 paused: Mutex<BTreeSet<String>>,
258 actions: Policies,
261 store: Store,
263 shutdown: watch::Sender<Stop>,
264 pub(super) wake: Notify,
265 commands: mpsc::UnboundedSender<Command>,
266}
267
268impl Control {
269 pub fn new(
273 repositories: impl IntoIterator<Item = String>,
274 paused: impl IntoIterator<Item = String>,
275 store: Store,
276 ) -> (Control, Commands) {
277 let repositories: BTreeSet<String> = repositories.into_iter().collect();
278 let paused: BTreeSet<String> = paused
279 .into_iter()
280 .filter(|repository| repositories.contains(repository))
281 .collect();
282 drop(store.paused(paused.iter().cloned().collect()));
284 let (commands, receiver) = mpsc::unbounded_channel();
285 let control = Control {
286 actions: Policies::new(api::JobActions::On, repositories.clone()),
287 repositories: Mutex::new(repositories),
288 paused: Mutex::new(paused),
289 store,
290 shutdown: watch::Sender::new(Stop::none()),
291 wake: Notify::new(),
292 commands,
293 };
294 (control, Commands(receiver))
295 }
296
297 pub fn mode(&self) -> Shutdown {
299 self.shutdown.borrow().mode()
300 }
301
302 pub(super) fn docker_gone(&self) -> bool {
304 self.shutdown.borrow().docker_gone()
305 }
306
307 pub(super) fn note_docker_gone(&self) -> bool {
310 let news = self.shutdown.send_if_modified(Stop::note_docker_gone);
311 if news {
312 self.wake.notify_one();
313 }
314 news
315 }
316
317 pub(super) async fn hurried(&self) {
319 let mut mode = self.shutdown.subscribe();
320 let _ = mode.wait_for(|stop| stop.hurried()).await;
322 }
323
324 pub async fn set_paused(&self, target: &Target, paused: bool) -> Result<(), ControlError> {
330 let recorded = {
331 let repositories = lock(&self.repositories);
332 let names: Vec<&String> = match target {
333 Target::Repository(repository) => {
334 let Some(name) = repositories.get(repository) else {
335 return Err(not_configured(repository, repositories.iter()));
336 };
337 vec![name]
338 }
339 Target::All => repositories.iter().collect(),
340 };
341 let mut set = lock(&self.paused);
342 for name in names {
343 if paused {
344 set.insert(name.clone());
345 } else {
346 set.remove(name);
347 }
348 }
349 self.store.paused(set.iter().cloned().collect())
351 };
352 self.wake.notify_one();
353 if recorded.await {
354 return Ok(());
355 }
356 let name = match target {
357 Target::Repository(repository) => repository.as_str(),
358 Target::All => "every repository",
359 };
360 let (done, undone) = if paused {
361 ("paused", "resumes it")
362 } else {
363 ("resumed", "pauses it again")
364 };
365 let message = format!(
366 "{name} is {done} until runnerd restarts, but the job history cannot record it, so a restart {undone}"
367 );
368 warn!("{message}");
369 Err(ControlError::NotRecorded(message))
370 }
371
372 pub(crate) fn set_repositories(&self, repositories: BTreeSet<String>) {
374 let mut configured = lock(&self.repositories);
375 let mut paused = lock(&self.paused);
376 let before = paused.len();
377 paused.retain(|repository| repositories.contains(repository));
378 if paused.len() != before {
379 drop(self.store.paused(paused.iter().cloned().collect()));
381 }
382 *configured = repositories;
383 }
384
385 pub fn shutdown(&self, mode: Shutdown) -> Shutdown {
388 self.shutdown.send_if_modified(|stop| stop.ask(mode));
389 self.wake.notify_one();
390 self.mode()
391 }
392
393 pub fn is_paused(&self, repository: &str) -> bool {
395 lock(&self.paused).contains(repository)
396 }
397
398 pub fn action_policy(&self) -> Arc<Policy> {
400 self.actions.now()
401 }
402
403 pub fn set_action_policy(&self, setting: api::JobActions, repositories: BTreeSet<String>) {
406 self.actions.replace(setting, repositories);
407 }
408
409 pub async fn stop_asked(&self) {
411 let mut mode = self.shutdown.subscribe();
412 let _ = mode.wait_for(|stop| stop.mode() != Shutdown::No).await;
414 }
415
416 async fn send<T>(
417 &self,
418 command: impl FnOnce(oneshot::Sender<T>) -> Command,
419 ) -> Result<T, ControlError> {
420 let (reply, answer) = oneshot::channel();
421 self.commands
422 .send(command(reply))
423 .map_err(|_| ControlError::Stopped)?;
424 answer.await.map_err(|_| ControlError::Stopped)
425 }
426
427 pub async fn pause(
431 &self,
432 target: Target,
433 jobs: RunningJobs,
434 ) -> Result<api::Paused, ControlError> {
435 self.send(|reply| Command::Pause {
436 target,
437 jobs,
438 reply,
439 })
440 .await?
441 }
442
443 pub async fn resume(&self, target: Target) -> Result<(), ControlError> {
446 self.send(|reply| Command::Resume { target, reply }).await?
447 }
448
449 pub async fn reseed(&self, profile: &str) -> Result<(), ControlError> {
451 self.send(|reply| Command::Reseed {
452 profile: profile.to_owned(),
453 reply,
454 })
455 .await?
456 }
457
458 pub async fn clean_cache(&self, name: &str) -> Result<(), ControlError> {
460 self.send(|reply| Command::CleanCache {
461 name: name.to_owned(),
462 reply,
463 })
464 .await?
465 }
466
467 pub async fn remove_records(
469 &self,
470 selection: RecordSelection,
471 ) -> Result<api::RemovedRecords, ControlError> {
472 self.send(|reply| Command::RemoveRecords { selection, reply })
473 .await?
474 }
475
476 pub async fn open_shell(&self, job: u64, size: TtySize) -> Result<Tty, ControlError> {
479 self.send(|reply| Command::OpenShell { job, size, reply })
480 .await?
481 }
482
483 pub fn close_shell(&self, container: String) {
485 let _ = self.commands.send(Command::CloseShell { container });
486 }
487
488 pub async fn replace_config(
496 &self,
497 config: Config,
498 memory_max: Option<u64>,
499 cpus: Option<u64>,
500 commit: Commit,
501 running: RunningSlots,
502 author: Author,
503 ) -> Result<Vec<String>, ControlError> {
504 self.send(|reply| Command::ReplaceConfig {
505 config: Box::new(config),
506 memory_max,
507 cpus,
508 commit,
509 running,
510 author,
511 reply,
512 })
513 .await?
514 }
515}
516
517fn not_configured<'name>(
519 repository: &str,
520 configured: impl Iterator<Item = &'name String>,
521) -> ControlError {
522 let configured: Vec<&str> = configured.map(String::as_str).collect();
523 let configured = if configured.is_empty() {
524 "none is configured".to_owned()
525 } else {
526 format!("configured: {}", configured.join(", "))
527 };
528 ControlError::NotFound(format!(
529 "{repository} is not a configured repository; {configured}"
530 ))
531}
532
533fn list(jobs: &[api::RunningJob]) -> String {
535 jobs.iter()
536 .map(ToString::to_string)
537 .collect::<Vec<_>>()
538 .join(", ")
539}
540
541impl<G: GithubApi + 'static, D: DockerApi + 'static> Engine<G, D> {
542 pub(super) async fn command(&mut self, command: Command) {
544 match command {
545 Command::Pause {
546 target,
547 jobs,
548 reply,
549 } => {
550 let _ = reply.send(self.pause(&target, jobs).await);
551 }
552 Command::Resume { target, reply } => {
553 let _ = reply.send(self.control.set_paused(&target, false).await);
554 }
555 Command::Reseed { profile, reply } => {
556 let _ = reply.send(self.request_reseed(&profile));
557 }
558 Command::CleanCache { name, reply } => {
559 let _ = reply.send(self.clean_cache(&name).await);
560 }
561 Command::ReplaceConfig {
562 config,
563 memory_max,
564 cpus,
565 commit,
566 running,
567 author,
568 reply,
569 } => {
570 if let Err(refused) = same_slice(&self.config, &config) {
571 let _ = reply.send(Err(refused));
572 return;
573 }
574 if running == RunningSlots::Keep
575 && let Some(occupied) = self.occupied_past(&config)
576 {
577 let _ = reply.send(Err(ControlError::Conflict(occupied)));
578 return;
579 }
580 let undone = match author {
581 Author::Owner => self.undone_raises(&config).await,
582 Author::AutoSizing => Vec::new(),
583 };
584 let answer = match commit.run().await {
585 Ok(warning) => {
586 for line in &undone {
587 warn!("config replaced: {line}");
588 }
589 self.reload(*config, memory_max, cpus);
590 Ok(warning.into_iter().chain(undone).collect())
591 }
592 Err(message) => Err(ControlError::Failed(message)),
593 };
594 let _ = reply.send(answer);
595 }
596 Command::RemoveRecords { selection, reply } => {
597 let _ = reply.send(self.remove_records(&selection).await);
598 }
599 Command::OpenShell { job, size, reply } => {
600 let opened = self.open_shell(job, size).await;
601 if let Err(Ok(tty)) = reply.send(opened) {
603 self.close_shell(&tty.container).await;
604 }
605 }
606 Command::CloseShell { container } => self.close_shell(&container).await,
607 }
608 }
609
610 pub(super) async fn pause(
614 &mut self,
615 target: &Target,
616 running: RunningJobs,
617 ) -> Result<api::Paused, ControlError> {
618 let repositories: BTreeSet<String> = match target {
619 Target::Repository(repository) if self.repositories.listed(repository).is_none() => {
620 return Err(not_configured(repository, self.repositories.listed_names()));
621 }
622 Target::Repository(repository) => BTreeSet::from([repository.clone()]),
623 Target::All => self.repositories.listed_names().cloned().collect(),
624 };
625 self.take_found();
626 let runners: Vec<(SlotRef, Occupant)> = self
627 .occupied()
628 .filter(|(_, occupant)| repositories.contains(&occupant.repository))
629 .map(|(slot, occupant)| (slot, occupant.clone()))
630 .collect();
631 let jobs: Vec<api::RunningJob> = runners
632 .iter()
633 .filter(|(_, occupant)| occupant.engaged())
634 .map(|(_, occupant)| occupant.running_job())
635 .collect();
636 if running == RunningJobs::Keep && !jobs.is_empty() {
637 let mut by_repository: BTreeMap<&str, Vec<api::RunningJob>> = BTreeMap::new();
638 for job in &jobs {
639 by_repository
640 .entry(&job.repository)
641 .or_default()
642 .push(job.clone());
643 }
644 let runs: Vec<String> = by_repository
645 .iter()
646 .map(|(repository, jobs)| format!("{repository} runs {}", list(jobs)))
647 .collect();
648 return Err(ControlError::Busy {
650 message: runs.join("; "),
651 jobs,
652 });
653 }
654 let recorded = self.control.set_paused(target, true).await;
656 match target {
657 Target::Repository(repository) => info!("{repository}: paused"),
658 Target::All => info!("paused every repository"),
659 }
660 let mut stopped = Vec::new();
661 if running == RunningJobs::Keep {
662 return recorded.map(|()| api::Paused { stopped });
663 }
664 for (slot, occupant) in runners {
665 let repository = &occupant.repository;
666 let cancelled = if let Some(job) = occupant.named_job() {
667 self.cancel(repository, job).await
668 } else {
669 if occupant.listed_busy() {
670 warn!(
671 "{repository}: {} runs a job its log has not named yet; GitHub fails it once the runner is gone",
672 occupant.runner_name
673 );
674 }
675 false
676 };
677 if cancelled {
678 if let Some(cancelled) = self
680 .slots
681 .values_mut()
682 .flatten()
683 .filter_map(Slot::occupant_mut)
684 .find(|candidate| candidate.runner_name == occupant.runner_name)
685 {
686 cancelled
687 .engagement
688 .cancelled(tokio::time::Instant::now() + CANCEL_GRACE);
689 }
690 self.store.runner_cancel_by(
692 &occupant.runner_name,
693 time::now_ms() + u64::try_from(CANCEL_GRACE.as_millis()).unwrap_or(u64::MAX),
694 );
695 } else {
696 self.kill(&slot).await;
697 if self
698 .occupied()
699 .any(|(_, candidate)| candidate.runner_name == occupant.runner_name)
700 {
701 continue;
702 }
703 }
704 stopped.push(occupant.running_job());
705 }
706 match recorded {
707 Ok(()) => Ok(api::Paused { stopped }),
708 Err(ControlError::NotRecorded(message)) if !stopped.is_empty() => Err(
709 ControlError::NotRecorded(format!("{message}; stopped {}", list(&stopped))),
710 ),
711 Err(error) => Err(error),
712 }
713 }
714
715 pub(super) async fn kill_cancelled(&mut self) {
717 let now = tokio::time::Instant::now();
718 let overdue: Vec<(SlotRef, String)> = self
719 .occupied()
720 .filter(|(_, occupant)| occupant.engagement.cancel_overdue(now))
721 .map(|(slot, occupant)| (slot, occupant.runner_name.clone()))
722 .collect();
723 for (slot, name) in overdue {
724 warn!(
725 "{name} did not exit {}s after its run was cancelled",
726 CANCEL_GRACE.as_secs()
727 );
728 self.kill(&slot).await;
730 }
731 }
732
733 async fn cancel(&self, repository: &str, job: u64) -> bool {
735 let run = match self.github.job(repository, job).await {
736 Ok(details) => details.run_id,
737 Err(error) => {
738 warn!("{repository}: cannot read job {job} to cancel its run: {error}");
739 return false;
740 }
741 };
742 match self.github.cancel_run(repository, run).await {
743 Ok(()) => {
744 info!("{repository}: cancelled run {run} of job {job}");
745 true
746 }
747 Err(error) => {
748 warn!("{repository}: cannot cancel run {run}: {error}");
749 false
750 }
751 }
752 }
753
754 pub(super) fn request_reseed(&mut self, profile: &str) -> Result<(), ControlError> {
756 if !self.config.profiles.contains_key(profile) {
757 return Err(ControlError::NotFound(format!(
758 "{profile} is not a configured profile"
759 )));
760 }
761 if self.is_reseeding(profile) {
762 return Err(ControlError::Conflict(format!(
763 "{profile} is reseeding already"
764 )));
765 }
766 if self.shell_profiles().contains(profile) {
768 return Err(ControlError::Conflict(format!(
769 "a shell is open in a record of {profile}, which mounts its snapshot; reseed it once the shell exits"
770 )));
771 }
772 info!("{profile}: reseeding once its slots are free");
773 self.upkeep.request(profile);
774 Ok(())
775 }
776
777 pub(super) async fn clean_cache(&mut self, name: &str) -> Result<(), ControlError> {
780 let Some(volume) = cache::volumes(&self.names, &self.config)
781 .into_iter()
782 .find(|volume| volume.name == name)
783 else {
784 return Err(ControlError::NotFound(format!(
785 "{name} is not a cache volume of this config; `runnerctl caches` lists them"
786 )));
787 };
788 let using: Vec<SlotRef> = match &volume.kind {
789 api::CacheKind::Snapshot { profile } => {
790 return Err(ControlError::Invalid(format!(
791 "{name} is {profile}'s snapshot, which every slot's layers sit on; reseed {profile} to rebuild it"
792 )));
793 }
794 api::CacheKind::Slot { profile, slot } => {
795 if self.upkeep.reseed_runs(profile) {
796 return Err(ControlError::Conflict(format!(
797 "{profile} is reseeding, which writes {name}"
798 )));
799 }
800 self.occupied()
801 .filter(|(at, _)| at.profile == *profile && at.index + 1 == *slot)
802 .map(|(at, _)| at)
803 .collect()
804 }
805 api::CacheKind::Pnpm
806 | api::CacheKind::Maven
807 | api::CacheKind::Mirror
808 | api::CacheKind::Build => self.occupied().map(|(at, _)| at).collect(),
809 };
810 let shared = matches!(volume.kind, api::CacheKind::Pnpm | api::CacheKind::Maven);
811 if shared && self.records.has_shells() {
812 return Err(ControlError::Conflict(format!(
813 "a shell open in a record mounts {name}; clean it once the shell exits"
814 )));
815 }
816 let idle = using
819 .iter()
820 .filter(|slot| self.occupant(slot).is_some_and(Occupant::idle))
821 .map(|slot| (slot.clone(), StopReason::Clean))
822 .collect();
823 self.remove_idle(idle).await;
824 let users: Vec<api::RunningJob> = using
825 .iter()
826 .filter_map(|slot| self.occupant(slot))
827 .map(Occupant::running_job)
828 .collect();
829 if !users.is_empty() {
830 return Err(ControlError::Busy {
831 message: format!(
832 "{name} is in use by {}; clean it once they finish",
833 list(&users)
834 ),
835 jobs: users,
836 });
837 }
838 if volume.kind == api::CacheKind::Build {
839 let Some(cache) = self.build_cache.clone() else {
840 return Err(ControlError::Failed(
841 "the build cache did not open when runnerd started; its log says why"
842 .to_owned(),
843 ));
844 };
845 let trimmed = tokio::task::spawn_blocking(move || cache.clear())
846 .await
847 .map_err(|error| ControlError::Failed(format!("cannot empty {name}: {error}")))?;
848 info!(
849 "emptied {name}: {} entries, {}",
850 trimmed.before.entries,
851 ByteSize(trimmed.before.bytes)
852 );
853 self.trim_due = true;
854 return Ok(());
855 }
856 if volume.kind == api::CacheKind::Mirror && self.mirror.may_run() {
857 cache::mirror_down(&*self.docker, &self.names)
858 .await
859 .map_err(|error| {
860 ControlError::Failed(format!("cannot stop the mirror: {error}"))
861 })?;
862 self.mirror.stopped();
863 }
864 self.docker
865 .remove_volume(name)
866 .await
867 .map_err(|error| ControlError::Failed(format!("cannot remove {name}: {error}")))?;
868 info!("removed {name}");
869 if let api::CacheKind::Slot { profile, slot } = &volume.kind {
871 self.ran.remove(&SlotRef {
872 profile: profile.clone(),
873 index: slot.saturating_sub(1),
874 });
875 }
876 self.trim_due = true;
878 Ok(())
879 }
880
881 async fn undone_raises(&self, config: &Config) -> Vec<String> {
884 let now = time::now_ms() / 1000;
885 let since = now.saturating_sub(auto::UNDONE_RAISES).saturating_mul(1000);
886 match self.store.sizing_changes(since).await {
887 Ok(changes) => auto::undone_raises(&self.config, config, &changes, now),
888 Err(store_error) => {
889 warn!(
890 "cannot read auto sizing's changes to compare a new config with: {store_error}"
891 );
892 Vec::new()
893 }
894 }
895 }
896
897 fn occupied_past(&self, config: &Config) -> Option<String> {
899 self.slots.iter().find_map(|(name, slots)| {
900 let kept = config
901 .profiles
902 .get(name)
903 .map_or(0, |profile| profile.slots as usize);
904 slots
905 .iter()
906 .enumerate()
907 .skip(kept)
908 .find(|(_, slot)| !slot.is_free())
909 .map(|(index, _)| {
910 format!(
911 "{name}'s slot {} has a runner, and the new config keeps {kept} slots",
912 index + 1
913 )
914 })
915 })
916 }
917
918 pub(super) fn reload(&mut self, config: Config, memory_max: Option<u64>, cpus: Option<u64>) {
923 let mut old = std::mem::replace(&mut self.config, config);
924 for (name, state) in self.repositories.iter_listed_mut() {
927 let new = &self.config;
928 state.forget_health(|profile| same_runners(&old, new, name, profile));
929 }
930 if let Some(cache) = &self.build_cache {
931 cache.set_max_size(self.config.caches.build.max_size.0);
932 }
933 for (name, profile) in &self.config.profiles {
934 let slots = self.slots.entry(name.clone()).or_default();
935 if slots.len() < profile.slots as usize {
936 slots.resize_with(profile.slots as usize, Slot::default);
937 }
938 self.retired.remove(name);
939 }
940 for (name, profile) in std::mem::take(&mut old.profiles) {
941 if !self.config.profiles.contains_key(&name) {
942 self.retired.insert(name, profile);
943 }
944 }
945 self.drop_closed_slots();
946 self.images.stale_due = true;
947 let names: BTreeSet<String> = self
948 .config
949 .repositories
950 .iter()
951 .map(|repository| repository.name.clone())
952 .collect();
953 self.repositories.reload(&names);
954 let config = &self.config;
956 for (name, state) in self.repositories.iter_listed_mut() {
957 state.forget_waits(|profile| config.pool_in(name, profile).is_some());
958 }
959 self.control.set_action_policy(
960 api::JobActions::configured(self.config.github.job_actions),
961 names.clone(),
962 );
963 self.control.set_repositories(names);
964 let profiles = &self.config.profiles;
965 self.upkeep
966 .forget_removed(|name| profiles.contains_key(name));
967 self.prepare_failures.retain(|slot, _| {
968 profiles
969 .get(&slot.profile)
970 .is_some_and(|profile| slot.index < profile.slots as usize)
971 });
972 self.isolation = isolation::backend(self.config.host.isolation);
973 let pooled = |config: &Config| {
976 config.host.admission == crate::config::Admission::Measured && config.host.pooled_count
977 };
978 if pooled(&self.config)
979 && (!pooled(&old)
980 || memory_max != self.memory_max
981 || old.host.memory_ceiling != self.config.host.memory_ceiling)
982 {
983 self.measured.restart_growth(self.now());
984 }
985 self.memory_max = memory_max;
986 self.cpus = cpus;
987 self.caches
988 .send_replace(cache::volumes(&self.names, &self.config));
989 self.reread_warm();
991 info!("reloaded the config");
992 }
993}
994
995fn same_runners(old: &Config, new: &Config, repository: &str, profile: &str) -> bool {
998 let labels = |pool: &crate::config::Repository| -> BTreeSet<String> {
999 pool.labels
1000 .iter()
1001 .map(|label| label.to_ascii_lowercase())
1002 .collect()
1003 };
1004 let (Some(was), Some(is)) = (
1005 old.pool_in(repository, profile),
1006 new.pool_in(repository, profile),
1007 ) else {
1008 return false;
1009 };
1010 let (Some(was_made), Some(is_made)) = (old.profiles.get(profile), new.profiles.get(profile))
1011 else {
1012 return false;
1013 };
1014 labels(was) == labels(is)
1015 && was_made.image == is_made.image
1016 && was_made.memory.0 == is_made.memory.0
1017 && was_made.cpus == is_made.cpus
1018 && old.host.isolation == new.host.isolation
1019}