1use super::*;
2
3pub fn quota_refresh_profiles(controller: &Controller) -> Vec<QuotaRefreshRequest> {
4 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
5 controller
6 .config
7 .enabled_profiles()
8 .map(|(id, profile)| QuotaRefreshRequest::for_profile(id, profile, cwd.clone()))
9 .collect()
10}
11
12pub fn spawn_quota_refresher() -> (
13 tokio::sync::watch::Sender<QuotaRefreshBatch>,
14 tokio::sync::mpsc::Receiver<QuotaUpdate>,
15) {
16 let (profiles_tx, mut profiles_rx) = tokio::sync::watch::channel(QuotaRefreshBatch::default());
17 let (updates_tx, updates_rx) = tokio::sync::mpsc::channel(32);
18 tokio::spawn(async move {
19 let mut quotas = QuotaManager::default();
20 let mut batch = QuotaRefreshBatch::default();
21 let mut interval = tokio::time::interval(QUOTA_REFRESH_INTERVAL);
22 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
23 interval.tick().await;
24 loop {
25 tokio::select! {
26 _ = interval.tick(), if !batch.profiles.is_empty() => {
27 if !refresh_profile_quotas(
28 &mut quotas,
29 batch.generation,
30 &batch.profiles,
31 &updates_tx,
32 ).await {
33 break;
34 }
35 }
36 changed = profiles_rx.changed() => {
37 if changed.is_err() {
38 tracing::debug!("quota profile target feed closed; stopping quota refresher");
39 break;
40 }
41 batch = profiles_rx.borrow_and_update().clone();
42 if !refresh_profile_quotas(
43 &mut quotas,
44 batch.generation,
45 &batch.profiles,
46 &updates_tx,
47 ).await {
48 break;
49 }
50 }
51 }
52 }
53 quotas.shutdown().await;
54 });
55 (profiles_tx, updates_rx)
56}
57
58pub(super) async fn refresh_profile_quotas(
59 quotas: &mut QuotaManager,
60 generation: u64,
61 profiles: &[QuotaRefreshRequest],
62 updates: &tokio::sync::mpsc::Sender<QuotaUpdate>,
63) -> bool {
64 let ids = profiles
65 .iter()
66 .map(|profile| profile.profile_id.clone())
67 .collect::<Vec<_>>();
68 if updates
69 .send(QuotaUpdate::Refreshing { profile_ids: ids })
70 .await
71 .is_err()
72 {
73 tracing::debug!("quota update consumer closed before refresh started");
74 return false;
75 }
76 let delivered = AtomicBool::new(true);
79 quotas
80 .refresh_profiles(profiles.to_vec(), |quota| {
81 let delivered = &delivered;
82 async move {
83 if delivered.load(Ordering::Acquire)
84 && updates.send(QuotaUpdate::Report(quota)).await.is_err()
85 {
86 tracing::debug!("quota update consumer closed while reporting a profile");
87 delivered.store(false, Ordering::Release);
88 }
89 }
90 })
91 .await;
92 if !delivered.into_inner() {
93 return false;
94 }
95 if updates
96 .send(QuotaUpdate::Finished { generation })
97 .await
98 .is_err()
99 {
100 tracing::debug!(
101 generation,
102 "quota update consumer closed before refresh completed"
103 );
104 false
105 } else {
106 true
107 }
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum ImageRefreshReport {
116 Started { host: String, image: String },
118 Pulled { host: String, image: String },
120 Failed {
122 host: String,
123 image: String,
124 error: String,
125 },
126}
127
128pub fn spawn_image_refresher(
140 plan: impl Fn() -> Vec<ImageRefresh> + Send + 'static,
141 report: impl Fn(ImageRefreshReport) + Send + Sync + 'static,
142 cancellation: tokio_util::sync::CancellationToken,
143) -> tokio::task::JoinHandle<()> {
144 let report: Arc<dyn Fn(ImageRefreshReport) + Send + Sync> = Arc::new(report);
145 tokio::spawn(async move {
146 let mut interval = tokio::time::interval_at(
147 tokio::time::Instant::now() + IMAGE_REFRESH_DELAY,
148 IMAGE_REFRESH_INTERVAL,
149 );
150 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
153 let mut last_failures: BTreeMap<String, String> = BTreeMap::new();
156 loop {
157 tokio::select! {
158 biased;
161 _ = cancellation.cancelled() => return,
162 _ = interval.tick() => {
163 refresh_images(plan(), &report, &mut last_failures, &cancellation).await;
164 }
165 }
166 }
167 })
168}
169
170fn refresh_key(host: &str, image: &str) -> String {
173 format!("{host}|{image}")
174}
175
176pub(super) fn record_refresh_result(
183 last_failures: &mut BTreeMap<String, String>,
184 host: &str,
185 image: &str,
186 error: Option<String>,
187 report: &dyn Fn(ImageRefreshReport),
188) {
189 let key = refresh_key(host, image);
190 let Some(error) = error else {
191 last_failures.remove(&key);
192 return;
193 };
194 if last_failures.get(&key) == Some(&error) {
195 return;
196 }
197 last_failures.insert(key, error.clone());
198 report(ImageRefreshReport::Failed {
199 host: host.to_owned(),
200 image: image.to_owned(),
201 error,
202 });
203}
204
205pub(super) fn local_engine_installed(host: &ImageHost, path: Option<&std::ffi::OsStr>) -> bool {
210 match host {
211 ImageHost::LocalPodman | ImageHost::LocalDocker | ImageHost::AppleContainer => {
212 let Some(path) = path else { return false };
213 let engine = host.engine();
214 std::env::split_paths(path).any(|directory| directory.join(engine).is_file())
215 }
216 ImageHost::SshPodman(_) | ImageHost::SshDocker(_) => true,
217 }
218}
219
220pub(super) async fn refresh_images(
221 plan: Vec<ImageRefresh>,
222 report: &Arc<dyn Fn(ImageRefreshReport) + Send + Sync>,
223 last_failures: &mut BTreeMap<String, String>,
224 cancellation: &tokio_util::sync::CancellationToken,
225) {
226 if plan.is_empty() {
227 return;
228 }
229 let cancelled = Arc::new(AtomicBool::new(false));
232 let mut hosts = tokio::task::JoinSet::new();
233 for refresh in plan {
234 if !local_engine_installed(&refresh.host, std::env::var_os("PATH").as_deref()) {
239 tracing::debug!(
240 host = refresh.host.label(),
241 image = refresh.image,
242 "container engine is not installed; skipping the image refresh"
243 );
244 continue;
245 }
246 let executor = CancellableProcessExecutor::new(cancelled.clone());
249 let report = report.clone();
250 hosts.spawn_blocking(move || {
251 let host = refresh.host.label();
252 let lock = crate::image_pull_gate::image_pull_mutex(&refresh.host, &refresh.image);
255 let held =
256 crate::image_pull_gate::hold_image_pull(&lock, || executor.is_cancelled(), || {});
257 let outcome = held.and_then(|guard| {
258 let outcome = refresh_host_image(&refresh, &executor, &*report);
259 drop(guard);
260 outcome
261 });
262 let error = match outcome {
263 Ok(_) => None,
264 Err(error) if executor.is_cancelled() => {
265 tracing::debug!(
268 host,
269 image = refresh.image,
270 error = format!("{error:#}"),
271 "container image refresh cancelled"
272 );
273 return None;
274 }
275 Err(error) => {
276 tracing::warn!(
277 host,
278 image = refresh.image,
279 error = format!("{error:#}"),
280 "could not refresh a container image"
281 );
282 Some(format!("{error:#}"))
283 }
284 };
285 Some((host, refresh.image, error))
286 });
287 }
288 let mut cancelling = false;
289 loop {
290 tokio::select! {
291 biased;
292 _ = cancellation.cancelled(), if !cancelling => {
293 cancelling = true;
294 cancelled.store(true, Ordering::Release);
295 }
296 joined = hosts.join_next() => match joined {
297 None => return,
298 Some(Ok(None)) => {}
299 Some(Ok(Some((host, image, error)))) => {
300 record_refresh_result(last_failures, &host, &image, error, &**report);
301 }
302 Some(Err(error)) => {
303 tracing::warn!(%error, "container image refresh task failed");
304 }
305 },
306 }
307 }
308}
309
310#[derive(Debug, Clone, PartialEq, Eq)]
312pub(super) enum ImageRefreshOutcome {
313 Present,
316 Unchanged,
318 Pulled { id: String },
320}
321
322pub(super) fn refresh_host_image(
333 refresh: &ImageRefresh,
334 executor: &impl CommandExecutor,
335 report: &dyn Fn(ImageRefreshReport),
336) -> Result<ImageRefreshOutcome> {
337 let host = refresh.host.label();
338 let cached = image_id(&refresh.image_id, executor);
339 if refresh.when == RefreshWhen::WhenAbsent && cached.is_some() {
340 tracing::debug!(
341 host,
342 image = refresh.image,
343 "the host already has this container image"
344 );
345 return Ok(ImageRefreshOutcome::Present);
346 }
347 if cached.is_none() {
351 report(ImageRefreshReport::Started {
352 host: host.clone(),
353 image: refresh.image.clone(),
354 });
355 }
356 run_refresh_command(&refresh.pull, executor)?;
357 let pulled = image_id(&refresh.image_id, executor);
358 let outcome = if pulled.is_some() && (cached.is_none() || pulled != cached) {
359 let id = pulled.unwrap_or_default();
360 tracing::info!(
361 host,
362 image = refresh.image,
363 id,
364 "pulled a newer container image"
365 );
366 report(ImageRefreshReport::Pulled {
367 host,
368 image: refresh.image.clone(),
369 });
370 ImageRefreshOutcome::Pulled { id }
371 } else {
372 tracing::debug!(
373 host,
374 image = refresh.image,
375 "container image is already current"
376 );
377 ImageRefreshOutcome::Unchanged
378 };
379 if let Some(prune) = &refresh.prune {
380 run_refresh_command(prune, executor)?;
381 }
382 Ok(outcome)
383}
384
385pub(super) fn image_id(command: &CommandSpec, executor: &impl CommandExecutor) -> Option<String> {
388 let output = executor.execute(command).ok()?;
389 if output.status != 0 {
390 return None;
391 }
392 let id = String::from_utf8_lossy(&output.stdout).trim().to_owned();
393 (!id.is_empty()).then_some(id)
394}
395
396pub(super) fn run_refresh_command(
397 command: &CommandSpec,
398 executor: &impl CommandExecutor,
399) -> Result<()> {
400 let output = executor.execute(command)?;
401 if output.status != 0 {
402 bail!(
403 "{} failed with status {}: {}",
404 command.purpose,
405 output.status,
406 String::from_utf8_lossy(&output.stderr).trim()
407 );
408 }
409 Ok(())
410}
411
412pub fn complete_manual_quota_refresh(
413 pending_generation: &mut Option<u64>,
414 completed_generation: u64,
415) -> bool {
416 if *pending_generation != Some(completed_generation) {
417 return false;
418 }
419 *pending_generation = None;
420 true
421}