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 crate::targets::program_on_path(host.engine(), path)
213 }
214 ImageHost::SshPodman(_) | ImageHost::SshDocker(_) => true,
215 }
216}
217
218pub(super) async fn refresh_images(
219 plan: Vec<ImageRefresh>,
220 report: &Arc<dyn Fn(ImageRefreshReport) + Send + Sync>,
221 last_failures: &mut BTreeMap<String, String>,
222 cancellation: &tokio_util::sync::CancellationToken,
223) {
224 if plan.is_empty() {
225 return;
226 }
227 let Ok(_upgrade_work) = crate::upgrade::activity("image download") else {
228 return;
229 };
230 let cancelled = Arc::new(AtomicBool::new(false));
233 let mut hosts = tokio::task::JoinSet::new();
234 for refresh in plan {
235 if !local_engine_installed(&refresh.host, std::env::var_os("PATH").as_deref()) {
240 tracing::debug!(
241 host = refresh.host.label(),
242 image = refresh.image,
243 "container engine is not installed; skipping the image refresh"
244 );
245 continue;
246 }
247 let executor = CancellableProcessExecutor::new(cancelled.clone());
250 let report = report.clone();
251 hosts.spawn_blocking(move || {
252 let host = refresh.host.label();
253 let lock = crate::image_pull_gate::image_pull_mutex(&refresh.host, &refresh.image);
256 let held =
257 crate::image_pull_gate::hold_image_pull(&lock, || executor.is_cancelled(), || {});
258 let outcome = held.and_then(|guard| {
259 let outcome = refresh_host_image(&refresh, &executor, &*report);
260 drop(guard);
261 outcome
262 });
263 let error = match outcome {
264 Ok(_) => None,
265 Err(error) if executor.is_cancelled() => {
266 tracing::debug!(
269 host,
270 image = refresh.image,
271 error = format!("{error:#}"),
272 "container image refresh cancelled"
273 );
274 return None;
275 }
276 Err(error) => {
277 tracing::warn!(
278 host,
279 image = refresh.image,
280 error = format!("{error:#}"),
281 "could not refresh a container image"
282 );
283 Some(format!("{error:#}"))
284 }
285 };
286 Some((host, refresh.image, error))
287 });
288 }
289 let mut cancelling = false;
290 loop {
291 tokio::select! {
292 biased;
293 _ = cancellation.cancelled(), if !cancelling => {
294 cancelling = true;
295 cancelled.store(true, Ordering::Release);
296 }
297 joined = hosts.join_next() => match joined {
298 None => return,
299 Some(Ok(None)) => {}
300 Some(Ok(Some((host, image, error)))) => {
301 record_refresh_result(last_failures, &host, &image, error, &**report);
302 }
303 Some(Err(error)) => {
304 tracing::warn!(%error, "container image refresh task failed");
305 }
306 },
307 }
308 }
309}
310
311#[derive(Debug, Clone, PartialEq, Eq)]
313pub(super) enum ImageRefreshOutcome {
314 Present,
317 Unchanged,
319 Pulled { id: String },
321}
322
323pub(super) fn refresh_host_image(
334 refresh: &ImageRefresh,
335 executor: &impl CommandExecutor,
336 report: &dyn Fn(ImageRefreshReport),
337) -> Result<ImageRefreshOutcome> {
338 let host = refresh.host.label();
339 let cached = image_id(&refresh.image_id, executor);
340 if refresh.when == RefreshWhen::WhenAbsent && cached.is_some() {
341 tracing::debug!(
342 host,
343 image = refresh.image,
344 "the host already has this container image"
345 );
346 return Ok(ImageRefreshOutcome::Present);
347 }
348 if cached.is_none() {
352 report(ImageRefreshReport::Started {
353 host: host.clone(),
354 image: refresh.image.clone(),
355 });
356 }
357 run_refresh_command(&refresh.pull, executor)?;
358 let pulled = image_id(&refresh.image_id, executor);
359 let outcome = if pulled.is_some() && (cached.is_none() || pulled != cached) {
360 let id = pulled.unwrap_or_default();
361 tracing::info!(
362 host,
363 image = refresh.image,
364 id,
365 "pulled a newer container image"
366 );
367 report(ImageRefreshReport::Pulled {
368 host,
369 image: refresh.image.clone(),
370 });
371 ImageRefreshOutcome::Pulled { id }
372 } else {
373 tracing::debug!(
374 host,
375 image = refresh.image,
376 "container image is already current"
377 );
378 ImageRefreshOutcome::Unchanged
379 };
380 if let Some(prune) = &refresh.prune {
381 run_refresh_command(prune, executor)?;
382 }
383 Ok(outcome)
384}
385
386pub(super) fn image_id(command: &CommandSpec, executor: &impl CommandExecutor) -> Option<String> {
389 let output = executor.execute(command).ok()?;
390 if output.status != 0 {
391 return None;
392 }
393 let id = String::from_utf8_lossy(&output.stdout).trim().to_owned();
394 (!id.is_empty()).then_some(id)
395}
396
397pub(super) fn run_refresh_command(
398 command: &CommandSpec,
399 executor: &impl CommandExecutor,
400) -> Result<()> {
401 let output = executor.execute(command)?;
402 if output.status != 0 {
403 bail!(
404 "{} failed with status {}: {}",
405 command.purpose,
406 output.status,
407 String::from_utf8_lossy(&output.stderr).trim()
408 );
409 }
410 Ok(())
411}
412
413pub fn complete_manual_quota_refresh(
414 pending_generation: &mut Option<u64>,
415 completed_generation: u64,
416) -> bool {
417 if *pending_generation != Some(completed_generation) {
418 return false;
419 }
420 *pending_generation = None;
421 true
422}