diff --git a/.github/workflows/linux-desktop-reliability.yml b/.github/workflows/linux-desktop-reliability.yml index c3691806c37..26f8c2dd4e3 100644 --- a/.github/workflows/linux-desktop-reliability.yml +++ b/.github/workflows/linux-desktop-reliability.yml @@ -632,6 +632,17 @@ jobs: curl --fail --location --retry 3 -o "$RUNNER_TEMP/Cap.AppImage" "$CAP_APPIMAGE_URL" echo "$CAP_APPIMAGE_SHA256 $RUNNER_TEMP/Cap.AppImage" | sha256sum --check + - name: apt-install.sh falls back when the Ubuntu archive is unreachable + run: | + log="$RUNNER_TEMP/apt-install-self-test.log" + status=0 + docker run --rm --add-host archive.ubuntu.com:127.0.0.1 --add-host security.ubuntu.com:127.0.0.1 \ + -v "$PWD/scripts/linux-desktop-harness/apt-install.sh":/apt-install.sh:ro ubuntu:24.04 \ + sh -c 'sh /apt-install.sh -qq hello >/dev/null && hello' 2>"$log" || status=$? + cat "$log" + [ "$status" = 0 ] + grep -q "falling back to http://azure.archive.ubuntu.com/ubuntu" "$log" + - name: Connect a capture stream in NixOS appimage-run timeout-minutes: 30 env: diff --git a/.github/workflows/windows-recording-encoder.yml b/.github/workflows/windows-recording-encoder.yml index 3a0f2b26fc8..689091f0496 100644 --- a/.github/workflows/windows-recording-encoder.yml +++ b/.github/workflows/windows-recording-encoder.yml @@ -15,6 +15,7 @@ on: - "crates/recording/src/output_pipeline/win_fragmented_m4s.rs" - "crates/recording/src/output_pipeline/core.rs" - "crates/recording/src/studio_recording.rs" + - "crates/recording/src/stop_progress.rs" - "crates/recording/src/recovery.rs" - "Cargo.lock" - ".github/workflows/windows-recording-encoder.yml" @@ -28,6 +29,7 @@ on: - "crates/recording/src/output_pipeline/win_fragmented_m4s.rs" - "crates/recording/src/output_pipeline/core.rs" - "crates/recording/src/studio_recording.rs" + - "crates/recording/src/stop_progress.rs" - "crates/recording/src/recovery.rs" - "Cargo.lock" - ".github/workflows/windows-recording-encoder.yml" diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rs index 6536287d942..4f783fe9f5f 100644 --- a/apps/cli/src/record.rs +++ b/apps/cli/src/record.rs @@ -1141,27 +1141,38 @@ async fn wait_for_studio_finish( "Recording is still finishing; waiting up to {}s for it to save: {path}", STUDIO_FINISH_WAIT.as_secs() ); - match tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()).await { - Ok(outcome) => { + let waiting = std::time::Instant::now(); + let finished = tokio::select! { + biased; + finished = tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()) => finished.ok(), + () = finishing.stalled() => None, + }; + match finished { + Some(outcome) => { if outcome.result.is_ok() { eprintln!("Recording finished saving: {path}"); } outcome } - Err(_) => { + None => { STUDIO_STILL_FINISHING.store(true, std::sync::atomic::Ordering::SeqCst); studio_recording::StudioStopOutcome { capture_stopped: false, - result: Err(format!( - "Recording is still finishing after {}s. Nothing was discarded; it will be recovered when it is next exported (cap export \"{path}\") or opened in Cap", - STUDIO_FINISH_WAIT.as_secs() - )), + result: Err(still_finishing_message(waiting.elapsed(), &path)), finishing: None, } } } } +#[cfg(windows)] +fn still_finishing_message(waited: Duration, path: &str) -> String { + format!( + "Recording is still finishing after {}s. Nothing was discarded; it will be recovered when it is next exported (cap export \"{path}\") or opened in Cap", + waited.as_secs() + ) +} + /// Ends the process after `report` once `cap record` has given up waiting /// for Studio tracks still finishing. A writer still blocked in the OS keeps /// both the runtime and the normal process exit waiting on it, so the process diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 8bfbdf4f24d..b612c244b15 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -1579,6 +1579,8 @@ title = "Aufnahmemodus wählen" [dialog.saving] in_background = "Ihre Aufnahme wird noch gespeichert und erscheint in Ihrer Bibliothek, sobald sie fertig ist. Sie können jetzt eine neue Aufnahme starten." +stalled = "Beim Speichern Ihrer Aufnahme ging es nicht mehr voran. Es wurde nichts gelöscht. Falls sie nicht in Ihrer Bibliothek erscheint, bietet Cap beim nächsten Start an, sie wiederherzustellen. Sie können jetzt eine neue Aufnahme starten." +stalled_title = "Noch nicht gespeichert" title = "Wird noch gespeichert" [dialog.storage] diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 128c6b9769a..93d67b87268 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -1581,6 +1581,8 @@ title = "Choose Recording Mode" [dialog.saving] in_background = "Your recording is still saving and will appear in your library when it is done. You can start a new recording now." +stalled = "Your recording stopped making progress while it was saving. Nothing was deleted. If it does not appear in your library, Cap will offer to recover it the next time it starts. You can start a new recording now." +stalled_title = "Not saved yet" title = "Still saving" [dialog.storage] diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index de75cd8ec07..2fff96f095b 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -1579,6 +1579,8 @@ title = "Elegir modo de grabación" [dialog.saving] in_background = "Tu grabación todavía se está guardando y aparecerá en tu biblioteca cuando termine. Ya puedes iniciar una nueva grabación." +stalled = "Tu grabación dejó de avanzar mientras se guardaba. No se ha borrado nada. Si no aparece en tu biblioteca, Cap te ofrecerá recuperarla la próxima vez que se inicie. Ya puedes iniciar una nueva grabación." +stalled_title = "Aún no se ha guardado" title = "Todavía se está guardando" [dialog.storage] diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 9519ea32592..5a90427bce2 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -1579,6 +1579,8 @@ title = "Choisir le mode d'enregistrement" [dialog.saving] in_background = "Votre enregistrement est encore en cours de sauvegarde et apparaîtra dans votre bibliothèque une fois terminé. Vous pouvez lancer un nouvel enregistrement dès maintenant." +stalled = "La sauvegarde de votre enregistrement a cessé de progresser. Rien n'a été supprimé. S'il n'apparaît pas dans votre bibliothèque, Cap vous proposera de le récupérer à son prochain démarrage. Vous pouvez lancer un nouvel enregistrement dès maintenant." +stalled_title = "Pas encore sauvegardé" title = "Sauvegarde en cours" [dialog.storage] diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 00030a324de..1d3160f91ca 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -1579,6 +1579,8 @@ title = "रिकॉर्डिंग मोड चुनें" [dialog.saving] in_background = "आपकी रिकॉर्डिंग अभी सहेजी जा रही है और पूरी होने पर आपकी लाइब्रेरी में दिखेगी। आप अभी नई रिकॉर्डिंग शुरू कर सकते हैं।" +stalled = "सहेजते समय आपकी रिकॉर्डिंग का आगे बढ़ना रुक गया। कुछ भी हटाया नहीं गया है। अगर यह आपकी लाइब्रेरी में नहीं दिखती, तो Cap अगली बार शुरू होने पर इसे रिकवर करने का विकल्प देगा। आप अभी नई रिकॉर्डिंग शुरू कर सकते हैं।" +stalled_title = "अभी तक सहेजा नहीं गया" title = "अभी सहेजा जा रहा है" [dialog.storage] diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 88135b351a4..5b95b63870a 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -1579,6 +1579,8 @@ title = "録画モードを選択" [dialog.saving] in_background = "録画はまだ保存中です。完了するとライブラリに表示されます。新しい録画をすぐに開始できます。" +stalled = "録画の保存が途中で進まなくなりました。削除されたものはありません。ライブラリに表示されない場合は、次回 Cap を起動したときに復元できます。新しい録画をすぐに開始できます。" +stalled_title = "まだ保存されていません" title = "保存中です" [dialog.storage] diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index bdedaa3993c..ab78c64a6ec 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -1579,6 +1579,8 @@ title = "选择录制模式" [dialog.saving] in_background = "你的录制仍在保存,完成后会显示在你的资料库中。你现在可以开始新的录制。" +stalled = "你的录制在保存时停止了进展。没有删除任何内容。如果它没有出现在你的资料库中,下次启动 Cap 时会提示你恢复它。你现在可以开始新的录制。" +stalled_title = "尚未保存" title = "仍在保存" [dialog.storage] diff --git a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs index e1f2193b609..1b35c70b5d0 100644 --- a/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/dialogs_surface_tests.rs @@ -301,6 +301,11 @@ fn dialog_surfaces_match_the_literals_they_replaced() { tr::dialog::saving::in_background(), "Your recording is still saving and will appear in your library when it is done. You can start a new recording now.", ), + ( + tr::dialog::saving::stalled(), + "Your recording stopped making progress while it was saving. Nothing was deleted. If it does not appear in your library, Cap will offer to recover it the next time it starts. You can start a new recording now.", + ), + (tr::dialog::saving::stalled_title(), "Not saved yet"), (tr::dialog::saving::title(), "Still saving"), ( tr::dialog::storage::stopped_kept(), diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index 078f0118760..b5af17b4bcb 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -1242,6 +1242,17 @@ impl MainWindow { debug_assert!(!still_saving); #[cfg(windows)] if still_saving { + let (title, message) = if session.read(cx).recording_save_stalled { + ( + tr::dialog::saving::stalled_title(), + tr::dialog::saving::stalled(), + ) + } else { + ( + tr::dialog::saving::title(), + tr::dialog::saving::in_background(), + ) + }; // Shown in the window: a native dialog can stall the // window while the earlier recording is still being written. let main = cx.global::().main; @@ -1250,12 +1261,7 @@ impl MainWindow { app_windows::show_main_window(cx); cx.activate(true); main.update(cx, |_, window, cx| { - crate::editor_modal::informational_alert( - &tr::dialog::saving::title(), - &tr::dialog::saving::in_background(), - window, - cx, - ) + crate::editor_modal::informational_alert(title, message, window, cx) }) }); if let Ok(response) = response { diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs index 0aba5b7e10a..17c0180a47b 100644 --- a/apps/desktop-gpui/src/recording.rs +++ b/apps/desktop-gpui/src/recording.rs @@ -669,6 +669,22 @@ impl std::fmt::Display for StudioStillSaving { #[cfg(windows)] impl std::error::Error for StudioStillSaving {} +/// Stop handed the app back because the recording stopped making progress +/// while saving, so it is not expected to finish. +#[cfg(windows)] +#[derive(Debug)] +pub(crate) struct StudioSaveStalled; + +#[cfg(windows)] +impl std::fmt::Display for StudioSaveStalled { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("The recording stopped making progress while saving") + } +} + +#[cfg(windows)] +impl std::error::Error for StudioSaveStalled {} + #[cfg(windows)] async fn wait_for_studio_finish( outcome: studio_recording::StudioStopOutcome, @@ -676,10 +692,12 @@ async fn wait_for_studio_finish( let Some(finishing) = outcome.finishing.clone() else { return Ok(outcome); }; - match tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()).await { - Ok(outcome) => Ok(outcome), - Err(_) => Err(finishing), - } + let finished = tokio::select! { + biased; + finished = tokio::time::timeout(STUDIO_FINISH_WAIT, finishing.wait()) => finished.ok(), + () = finishing.stalled() => None, + }; + finished.ok_or(finishing) } /// Keeps waiting for a failed Studio stop the app stopped waiting for and @@ -718,6 +736,7 @@ async fn finish_late_studio_stop( in_progress: Arc, ) -> (bool, anyhow::Result) { let path = finishing.project_path().to_path_buf(); + let tracks = finishing.clone(); let mut save = tokio::spawn(async move { let _in_progress = in_progress; let _finishing = finishing.clone(); @@ -733,7 +752,14 @@ async fn finish_late_studio_stop( ) .await }); - match tokio::time::timeout(STUDIO_FINISH_WAIT, &mut save).await { + let saved = tokio::select! { + biased; + saved = tokio::time::timeout(STUDIO_FINISH_WAIT, &mut save) => { + saved.map_err(|_| anyhow::Error::new(StudioStillSaving)) + } + () = tracks.stalled() => Err(anyhow::Error::new(StudioSaveStalled)), + }; + match saved { Ok(joined) => joined.unwrap_or_else(|error| { ( true, @@ -742,7 +768,7 @@ async fn finish_late_studio_stop( )), ) }), - Err(_) => { + Err(handed_back) => { tracing::warn!(path = %path.display(), "Studio recording is still saving; finishing it in the background"); drop(tokio::spawn(async move { match save.await { @@ -759,7 +785,7 @@ async fn finish_late_studio_stop( } refresh_library_after_background_save().await; })); - (true, Err(anyhow::Error::new(StudioStillSaving))) + (true, Err(handed_back)) } } } diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs index be81a420350..9500c89383e 100644 --- a/apps/desktop-gpui/src/session.rs +++ b/apps/desktop-gpui/src/session.rs @@ -440,6 +440,10 @@ pub struct RecordingSession { pub capture_source_lost: bool, /// Stop handed the app back while the last recording was still saving. pub recording_still_saving: bool, + /// That recording stopped making progress, so it is not expected to + /// finish saving in this session. + #[cfg(windows)] + pub recording_save_stalled: bool, stopped_for_low_storage: bool, stopped_elapsed: Option, /// The config of the live (or last) recording, kept for restart. @@ -534,6 +538,8 @@ impl RecordingSession { storage_notice: None, capture_source_lost: false, recording_still_saving: false, + #[cfg(windows)] + recording_save_stalled: false, stopped_for_low_storage: false, stopped_elapsed: None, last_config: None, @@ -845,6 +851,10 @@ impl RecordingSession { self.storage_notice = None; self.capture_source_lost = false; self.recording_still_saving = false; + #[cfg(windows)] + { + self.recording_save_stalled = false; + } self.stopped_for_low_storage = false; self.stopped_elapsed = None; self.last_config = Some(config.clone()); @@ -1715,6 +1725,18 @@ impl RecordingSession { tracing::warn!("Studio recording is still saving; the app is free for a new recording"); this.capture_source_lost = false; this.recording_still_saving = true; + this.recording_save_stalled = false; + } + #[cfg(windows)] + Ok(Err(error)) + if error + .chain() + .any(|cause| cause.is::()) => + { + tracing::warn!("Studio recording stopped making progress while saving; the app is free for a new recording"); + this.capture_source_lost = false; + this.recording_still_saving = true; + this.recording_save_stalled = true; } Ok(Err(error)) => { tracing::error!("recording failed to stop cleanly: {error:#}"); diff --git a/crates/enc-ffmpeg/src/mux/mod.rs b/crates/enc-ffmpeg/src/mux/mod.rs index 70acda46660..cf910afa69f 100644 --- a/crates/enc-ffmpeg/src/mux/mod.rs +++ b/crates/enc-ffmpeg/src/mux/mod.rs @@ -12,4 +12,6 @@ pub mod segmented_audio; pub mod segmented_stream; pub(crate) mod write_behind; +#[cfg(windows)] +pub use write_behind::StorageCall; pub use write_behind::StorageStalled; diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs index 500ecd2dfa5..ed8a4aa8003 100644 --- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs +++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs @@ -314,6 +314,8 @@ struct SegmentMux { bookkeeping: Bookkeeping, initial_manifest_pending: bool, encoder_tail_lost: bool, + #[cfg(windows)] + storage_call: Option, } struct SegmentLedger { @@ -345,7 +347,27 @@ impl MuxTarget for SegmentMux { if scan { self.frames_since_segment_scan = 0; } + // Bookkeeping left on this thread reads the segments back, which is + // a storage call like the write itself. + #[cfg(windows)] + let storage_call = self + .storage_call + .as_ref() + .filter(|_| matches!(self.bookkeeping, Bookkeeping::Inline(_))); + #[cfg(windows)] + if let Some(call) = storage_call { + call.set(true); + } self.bookkeeping.packet_written(scan); + #[cfg(windows)] + if let Some(call) = storage_call { + call.set(false); + } + } + + #[cfg(windows)] + fn storage_call(&self) -> Option<&super::write_behind::StorageCall> { + self.storage_call.as_ref() } } @@ -859,6 +881,8 @@ impl SegmentedVideoEncoder { }), initial_manifest_pending: true, encoder_tail_lost: false, + #[cfg(windows)] + storage_call: None, }; let mut instance = Self { @@ -934,6 +958,17 @@ impl SegmentedVideoEncoder { .with_target(|mux| mux.bookkeeping.move_to_background()) } + /// Hands out a marker that is raised while a write to the segment files + /// has not returned, so whoever waits on this encoder can tell slow + /// storage from an encoder that is stuck. + #[cfg(windows)] + pub fn watch_storage_calls(&mut self) -> super::write_behind::StorageCall { + let call = super::write_behind::StorageCall::default(); + self.mux + .with_target(|mux| mux.storage_call = Some(call.clone())); + call + } + /// Whether frames should be queued as CVPixelBuffers via /// [`Self::queue_hw_pixel_buffer`] instead of software frames. #[cfg(target_os = "macos")] @@ -2285,6 +2320,41 @@ mod tests { (names, mpd, manifest) } + #[cfg(windows)] + #[test] + fn storage_call_marker_is_lowered_once_every_write_returned() { + ffmpeg::init().unwrap(); + let temp = tempfile::tempdir().unwrap(); + for offloaded in [false, true] { + let base_path = temp.path().join(format!("offloaded-{offloaded}")); + let mut encoder = SegmentedVideoEncoder::init_libx264( + base_path, + test_video_info(), + SegmentedVideoEncoderConfig::default(), + ) + .unwrap(); + if offloaded { + encoder.offload_segment_bookkeeping().unwrap(); + } + let call = encoder.watch_storage_calls(); + assert!(!call.in_progress()); + for i in 0..120u64 { + encoder + .queue_frame( + create_test_frame(320, 240), + Duration::from_micros(i * 33_333), + ) + .unwrap(); + assert!(!call.in_progress()); + } + assert!(encoder.packets_written() > 0); + encoder + .finish_with_timestamp(Duration::from_secs(4)) + .unwrap(); + assert!(!call.in_progress()); + } + } + #[test] fn write_behind_counts_the_packets_the_writer_put_in_the_file() { ffmpeg::init().unwrap(); diff --git a/crates/enc-ffmpeg/src/mux/write_behind.rs b/crates/enc-ffmpeg/src/mux/write_behind.rs index 139e62cddf8..1d219ed23a0 100644 --- a/crates/enc-ffmpeg/src/mux/write_behind.rs +++ b/crates/enc-ffmpeg/src/mux/write_behind.rs @@ -78,6 +78,31 @@ pub(crate) trait MuxTarget: Send + 'static { fn writer_started(&mut self) {} fn packet_written(&mut self) {} + + /// The marker to raise around this target's writes, when someone waits + /// on its writer. + #[cfg(windows)] + fn storage_call(&self) -> Option<&StorageCall> { + None + } +} + +/// Raised while a write to an output has not returned. A writer blocked on +/// slow storage and one stuck anywhere else both stop producing packets; +/// this tells whoever waits on the writer which of the two it is. +#[cfg(windows)] +#[derive(Clone, Debug, Default)] +pub struct StorageCall(Arc); + +#[cfg(windows)] +impl StorageCall { + pub fn in_progress(&self) -> bool { + self.0.load(Ordering::Relaxed) + } + + pub fn set(&self, in_progress: bool) { + self.0.store(in_progress, Ordering::Relaxed); + } } /// The writer thread did not finish the output in time and may still write @@ -237,7 +262,19 @@ impl PacketSink for MuxSink { fn write_packet(&mut self, packet: Packet) -> Result<(), ffmpeg::Error> { match self { + #[cfg(not(windows))] Self::Direct(target) => packet.write_interleaved(target.output_mut()), + #[cfg(windows)] + Self::Direct(target) => { + if let Some(call) = target.storage_call() { + call.set(true); + } + let written = packet.write_interleaved(target.output_mut()); + if let Some(call) = target.storage_call() { + call.set(false); + } + written + } Self::Behind(writer) => writer.write_packet(packet), Self::Detached => unreachable!("mux sink detached"), } diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rs index 56ab1cfdb1a..fd3d3821f82 100644 --- a/crates/recording/src/lib.rs +++ b/crates/recording/src/lib.rs @@ -16,6 +16,8 @@ pub mod recovery; mod resolution_limits; pub mod screenshot; pub mod sources; +#[cfg(windows)] +mod stop_progress; pub mod studio_recording; pub mod sync_calibration; pub mod track_heal; diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs index cacf985a640..0391b7ae089 100644 --- a/crates/recording/src/output_pipeline/core.rs +++ b/crates/recording/src/output_pipeline/core.rs @@ -566,6 +566,8 @@ pub struct DiskSpaceMonitor { last_poll: Option, last_status: cap_utils::disk_space::DiskSpaceStatus, stopped: bool, + #[cfg(windows)] + query: Option, } impl DiskSpaceMonitor { @@ -574,9 +576,18 @@ impl DiskSpaceMonitor { last_poll: None, last_status: cap_utils::disk_space::DiskSpaceStatus::Ok, stopped: false, + #[cfg(windows)] + query: None, } } + /// Raises `call` while a free-space query has not returned: a volume slow + /// to answer holds the thread that polls as a slow write would. + #[cfg(windows)] + pub fn report_query_to(&mut self, call: cap_enc_ffmpeg::StorageCall) { + self.query = Some(call); + } + pub fn is_stopped(&self) -> bool { self.stopped } @@ -594,7 +605,16 @@ impl DiskSpaceMonitor { } self.last_poll = Some(now); - let bytes = match cap_utils::disk_space::free_bytes_for_path(path) { + #[cfg(windows)] + if let Some(query) = &self.query { + query.set(true); + } + let bytes = cap_utils::disk_space::free_bytes_for_path(path); + #[cfg(windows)] + if let Some(query) = &self.query { + query.set(false); + } + let bytes = match bytes { Ok(bytes) => bytes, Err(err) => { trace!(error = %err, path = %path.display(), "DiskSpaceMonitor: free_bytes_for_path failed"); diff --git a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs index ef20ab6ec97..15cbc1939d1 100644 --- a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs +++ b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs @@ -9,8 +9,10 @@ use crate::{ AudioFrame, AudioMuxer, Muxer, SharedPauseState, TaskPool, VideoMuxer, output_pipeline::{NativeCameraFrame, camera_frame_to_ffmpeg}, screen_capture, + stop_progress::StopProgress, }; use anyhow::{Context, anyhow}; +use cap_enc_ffmpeg::StorageCall; use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset}; use cap_enc_ffmpeg::segmented_stream::{ DiskSpaceCallback, QueueFrameError, SegmentedVideoEncoder, SegmentedVideoEncoderConfig, @@ -150,19 +152,36 @@ const ENCODER_FINISH_LIMIT: Duration = Duration::from_secs(5); /// waits for the encoder thread however long it takes, so a slow encoder is /// finalized instead of abandoned while still writing. #[derive(Clone, Debug, Default)] -pub struct EncoderFinishWait(Arc); +pub struct EncoderFinishWait { + without_limit: Arc, + progress: StopProgress, +} impl EncoderFinishWait { pub fn wait_without_limit(&self) { - self.0.store(true, Ordering::Release); + self.without_limit.store(true, Ordering::Release); + } + + /// What the encoders of this recording report while they stop. + pub(crate) fn progress(&self) -> &StopProgress { + &self.progress } fn limit(wait: Option<&Self>) -> Duration { match wait { - Some(wait) if wait.0.load(Ordering::Acquire) => Duration::MAX, + Some(wait) if wait.without_limit.load(Ordering::Acquire) => Duration::MAX, _ => ENCODER_FINISH_LIMIT, } } + + fn watch(wait: Option<&Self>, encoder: &mut SegmentedVideoEncoder) -> Option { + let wait = wait?; + wait.progress + .watch_packets(encoder.packets_written_counter()); + let storage_call = encoder.watch_storage_calls(); + wait.progress.watch_storage_calls(storage_call.clone()); + Some(storage_call) + } } fn finish_encoder_thread( @@ -280,8 +299,10 @@ fn finish_segmented_encoder_impl( thread_label: &str, finish_label: &str, health_tx: &SharedHealthSender, - limit: Duration, + wait: Option<&EncoderFinishWait>, ) -> anyhow::Result<()> { + let limit = EncoderFinishWait::limit(wait); + let progress = wait.map(EncoderFinishWait::progress); state.close_channel(thread_label); let thread_result = state @@ -295,9 +316,14 @@ fn finish_segmented_encoder_impl( BlockingThreadFinish::TimedOut(error) => return Err(error), }; + let storage_stage = progress.map(|progress| { + progress.step(); + progress.storage_stage(thread_label) + }); let finalize_error = state .finish_encoder(timestamp, finish_label, health_tx, limit) .err(); + drop(storage_stage); match (thread_error, finalize_error) { (None, None) => Ok(()), @@ -439,7 +465,7 @@ impl Muxer for WindowsFragmentedM4SMuxer { "Windows M4S encoder", "Failed to finish segmented encoder", &self.health_tx, - EncoderFinishWait::limit(self.finish_wait.as_ref()), + self.finish_wait.as_ref(), ) { return Ok(Err(error)); @@ -492,6 +518,7 @@ impl WindowsFragmentedM4SMuxer { if let Some(tx) = self.segment_tx.take() { encoder.set_segment_callback(tx); } + let storage_call = EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); @@ -518,6 +545,9 @@ impl WindowsFragmentedM4SMuxer { let mut total_frames = 0u64; let mut duplicated_frames = 0u64; let mut disk_monitor = DiskSpaceMonitor::new(); + if let Some(storage_call) = storage_call { + disk_monitor.report_query_to(storage_call); + } let mut disk_exhausted = false; const SLOW_THRESHOLD_MS: u128 = 5; let encode_failures = Cell::new(0u64); @@ -880,7 +910,7 @@ impl Muxer for WindowsFragmentedM4SCameraMuxer { "Windows M4S camera encoder", "Failed to finish camera segmented encoder", &self.health_tx, - EncoderFinishWait::limit(self.finish_wait.as_ref()), + self.finish_wait.as_ref(), ) { return Ok(Err(error)); @@ -972,6 +1002,7 @@ impl WindowsFragmentedM4SCameraMuxer { { warn!(%error, "Camera segment bookkeeping thread unavailable, keeping it on the encoder thread"); } + let storage_call = EncoderFinishWait::watch(self.finish_wait.as_ref(), &mut encoder); let encoder = Arc::new(Mutex::new(encoder)); let encoder_clone = encoder.clone(); @@ -1000,6 +1031,9 @@ impl WindowsFragmentedM4SCameraMuxer { let mut total_frames = 0u64; let mut duplicated_frames = 0u64; let mut disk_monitor = DiskSpaceMonitor::new(); + if let Some(storage_call) = storage_call { + disk_monitor.report_query_to(storage_call); + } let mut disk_exhausted = false; let mut mjpeg_decoder = MjpegDecoder::default(); const SLOW_THRESHOLD_MS: u128 = 5; @@ -1288,8 +1322,7 @@ mod tests { fn late_stop_still_ends_promptly_when_the_encoder_thread_died() { let wait = EncoderFinishWait::default(); wait.wait_without_limit(); - let limit = EncoderFinishWait::limit(Some(&wait)); - assert_eq!(limit, Duration::MAX); + assert_eq!(EncoderFinishWait::limit(Some(&wait)), Duration::MAX); let failed = std::thread::spawn(|| Err(anyhow::anyhow!("encoder failed"))); let panicked = std::thread::spawn(|| -> anyhow::Result<()> { panic!("encoder panicked") }); for (thread, expected) in [(failed, "encoder failed"), (panicked, "panicked")] { @@ -1300,7 +1333,7 @@ mod tests { "test encoder", "Failed to finish test encoder", &SharedHealthSender::new(), - limit, + Some(&wait), ) .expect_err("an encoder thread that died must fail the finish"); assert!(started.elapsed() < Duration::from_secs(2)); diff --git a/crates/recording/src/stop_progress.rs b/crates/recording/src/stop_progress.rs new file mode 100644 index 00000000000..53e2bf8919e --- /dev/null +++ b/crates/recording/src/stop_progress.rs @@ -0,0 +1,873 @@ +//! Tells a late Studio stop that is slow from one that is stuck. +//! +//! A stop whose tracks are still finishing at the stop limit is waited for. +//! That wait is only worth its time while the tracks are getting somewhere, +//! so the stop path reports what it does here and the waiter gives up once +//! nothing has moved for a while. + +use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, output_pipeline::HealthSender}; +use cap_enc_ffmpeg::StorageCall; +use cap_media_info::{AudioInfo, VideoInfo}; +use std::{ + path::{Path, PathBuf}, + sync::{ + Arc, Mutex, PoisonError, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + }, + time::{Duration, Instant, SystemTime}, +}; + +const SAMPLE_INTERVAL: Duration = Duration::from_secs(1); +const UNCHANGED_SAMPLES_FOR_A_STALL: u32 = 2; +/// In a folder with more files than this, only the newest are read one by +/// one: older segments are closed, and their listed size is final. +const FILES_READ_PER_FOLDER: usize = 16; + +/// What the tracks of one recording have done on their way to a stop. +#[derive(Clone, Debug, Default)] +pub(crate) struct StopProgress(Arc); + +#[derive(Debug, Default)] +struct Inner { + steps: AtomicU64, + storage_stages: AtomicU32, + packets: Mutex>>, + storage_calls: Mutex>, + storage_held: Mutex>, + tracks_finished: AtomicBool, + stop_began: AtomicBool, +} + +/// Held while a track's finish writes out what its encoder still holds and +/// then waits on storage (trailer, segment bookkeeping, fsync, manifest). A +/// file held open by a scan moves nothing in that time, on disk or in the +/// process, so the track counts as alive for as long as one of these exists. +pub(crate) struct StorageStage { + progress: StopProgress, + label: String, + started: Instant, +} + +impl Drop for StorageStage { + fn drop(&mut self) { + self.progress + .0 + .storage_held + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push((std::mem::take(&mut self.label), self.started.elapsed())); + self.progress + .0 + .storage_stages + .fetch_sub(1, Ordering::AcqRel); + self.progress.step(); + } +} + +impl StopProgress { + /// Counts every packet `written` gains as progress. + pub(crate) fn watch_packets(&self, written: Arc) { + self.0 + .packets + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(written); + } + + /// Counts a write `call` reports as not returned yet as progress: the + /// encoder making it is waiting on storage, not stuck. + pub(crate) fn watch_storage_calls(&self, call: StorageCall) { + self.0 + .storage_calls + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(call); + } + + pub(crate) fn step(&self) { + self.0.steps.fetch_add(1, Ordering::AcqRel); + } + + pub(crate) fn storage_stage(&self, label: &str) -> StorageStage { + self.0.storage_stages.fetch_add(1, Ordering::AcqRel); + StorageStage { + progress: self.clone(), + label: label.to_string(), + started: Instant::now(), + } + } + + /// From here on, an audio frame a track still muxes counts as progress. + pub(crate) fn stop_began(&self) { + self.0.stop_began.store(true, Ordering::Release); + } + + pub(crate) fn tracks_finished(&self) { + self.0.tracks_finished.store(true, Ordering::Release); + } + + fn are_tracks_finished(&self) -> bool { + self.0.tracks_finished.load(Ordering::Acquire) + } + + fn sample(&self) -> InProcess { + InProcess { + packets: self + .0 + .packets + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .map(|written| written.load(Ordering::Relaxed)) + .sum(), + steps: self.0.steps.load(Ordering::Acquire), + in_storage_stage: self.0.storage_stages.load(Ordering::Acquire) > 0, + in_storage_call: self + .0 + .storage_calls + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .any(StorageCall::in_progress), + } + } + + fn storage_held(&self) -> Vec<(String, Duration)> { + self.0 + .storage_held + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// Whether any muxer of the recording reports here. One whose muxers do + /// not (a recording that is not written as segments) cannot show that it + /// is waiting on storage, so it is never judged. + fn has_sources(&self) -> bool { + !self + .0 + .packets + .lock() + .unwrap_or_else(PoisonError::into_inner) + .is_empty() + || !self + .0 + .storage_calls + .lock() + .unwrap_or_else(PoisonError::into_inner) + .is_empty() + } + + /// Resolves once the tracks have shown no progress for `window`. Stays + /// pending for good once they finish, when no muxer reports here, and + /// when it cannot watch. + pub(crate) async fn stalled(&self, recording_dir: PathBuf, window: Duration) { + if !self.has_sources() { + return std::future::pending::<()>().await; + } + let (stalled_tx, stalled_rx) = tokio::sync::oneshot::channel(); + let progress = self.clone(); + let watcher = std::thread::Builder::new() + .name("studio-stop-progress".to_string()) + .spawn(move || watch(&progress, &recording_dir, window, stalled_tx)); + if let Err(error) = watcher { + tracing::warn!(%error, "Could not watch the progress of a late Studio stop"); + } else if stalled_rx.await.is_ok() { + return; + } + std::future::pending::<()>().await; + } +} + +/// Reports the finish of the muxer it wraps as a storage stage, a frame it +/// is still writing as a write in flight, and the frames it muxes once the +/// stop has begun as steps. The audio muxers write on the thread that calls +/// them, so a write or a finish held by storage has no limit of its own, and +/// what a track still drains after the stop reaches the folder only once per +/// fragment. +pub(crate) struct StopReportingMuxer { + inner: M, + progress: StopProgress, + write: StorageCall, + label: String, +} + +impl Muxer for StopReportingMuxer +where + M::Config: Send, +{ + type Config = (M::Config, StopProgress); + + async fn setup( + (config, progress): Self::Config, + output_path: PathBuf, + video_config: Option, + audio_config: Option, + pause_flag: Arc, + tasks: &mut TaskPool, + ) -> anyhow::Result { + let label = output_path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let inner = M::setup( + config, + output_path, + video_config, + audio_config, + pause_flag, + tasks, + ) + .await?; + let write = StorageCall::default(); + progress.watch_storage_calls(write.clone()); + Ok(Self { + inner, + progress, + write, + label, + }) + } + + fn stop(&mut self) { + self.inner.stop(); + } + + fn finish(&mut self, timestamp: Duration) -> anyhow::Result> { + let _storage_stage = self.progress.storage_stage(&self.label); + self.inner.finish(timestamp) + } + + fn set_health_sender(&mut self, tx: HealthSender) { + self.inner.set_health_sender(tx); + } +} + +impl AudioMuxer for StopReportingMuxer +where + M::Config: Send, +{ + fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> { + self.write.set(true); + let sent = self.inner.send_audio_frame(frame, timestamp); + self.write.set(false); + if self.progress.0.stop_began.load(Ordering::Relaxed) { + self.progress.step(); + } + sent + } +} + +/// Samples until the tracks stall or finish, or until nobody waits for the +/// answer. Runs on its own thread: reading the folder can block behind the +/// same file scans that hold the tracks up. +fn watch( + progress: &StopProgress, + recording_dir: &Path, + window: Duration, + stalled_tx: tokio::sync::oneshot::Sender<()>, +) { + let mut detector = StallDetector::new(window, Instant::now()); + let outcome = loop { + if progress.are_tracks_finished() { + break "finished"; + } + if stalled_tx.is_closed() { + break "abandoned"; + } + let folder = FolderSample::read(recording_dir); + if detector.observe(Instant::now(), progress.sample(), folder) { + break "stalled"; + } + std::thread::sleep(SAMPLE_INTERVAL); + }; + let quiet = detector.finish(Instant::now()); + tracing::info!( + path = %recording_dir.display(), + outcome, + samples = quiet.samples, + folder_unknown = quiet.folder_unknown, + storage_call_samples = quiet.storage_call_samples, + longest_quiet_ms = quiet.overall.as_millis() as u64, + longest_quiet_outside_storage_stages_ms = quiet.outside_storage_stages.as_millis() as u64, + longest_quiet_packets_ms = quiet.packets.as_millis() as u64, + longest_quiet_steps_ms = quiet.steps.as_millis() as u64, + longest_quiet_folder_ms = quiet.folder.as_millis() as u64, + storage_stages = ?progress.storage_held(), + "Late Studio stop progress" + ); + if outcome == "stalled" { + tracing::warn!( + path = %recording_dir.display(), + window_ms = window.as_millis() as u64, + "Studio tracks showed no progress; no longer waiting for them" + ); + let _ = stalled_tx.send(()); + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct InProcess { + packets: u64, + steps: u64, + in_storage_stage: bool, + in_storage_call: bool, +} + +impl InProcess { + fn waits_on_storage(&self) -> bool { + self.in_storage_stage || self.in_storage_call + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct FolderSample { + files: u64, + bytes: u64, + newest_modified: Option, +} + +impl FolderSample { + /// `None` when the folder could not be read: its state is unknown, which + /// is not the same as unchanged. + fn read(dir: &Path) -> Option { + let mut sample = Self { + files: 0, + bytes: 0, + newest_modified: None, + }; + sample.add_folder(dir).ok()?; + Some(sample) + } + + fn add_folder(&mut self, dir: &Path) -> std::io::Result<()> { + let mut files = Vec::new(); + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let listed = entry.metadata()?; + if listed.is_dir() { + self.add_folder(&entry.path())?; + } else { + files.push((entry.path(), listed)); + } + } + // A listing reports the size a file had when it was last closed, so a + // file still being written is read on its own. Only the newest files + // of a folder can still be open. + files.sort_by_key(|(_, listed)| std::cmp::Reverse(listed.created().ok())); + for (index, (path, listed)) in files.into_iter().enumerate() { + let metadata = if index < FILES_READ_PER_FOLDER { + match std::fs::metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => return Err(error), + } + } else { + listed + }; + self.files += 1; + self.bytes += metadata.len(); + self.newest_modified = self.newest_modified.max(metadata.modified().ok()); + } + Ok(()) + } +} + +/// The longest stretches without progress one watch saw, by source. +#[derive(Clone, Copy, Debug, Default)] +struct QuietGaps { + samples: u32, + folder_unknown: u32, + storage_call_samples: u32, + overall: Duration, + outside_storage_stages: Duration, + packets: Duration, + steps: Duration, + folder: Duration, +} + +struct Quiet { + since: Instant, + longest: Duration, +} + +impl Quiet { + fn new(at: Instant) -> Self { + Self { + since: at, + longest: Duration::ZERO, + } + } + + fn close(&mut self, at: Instant) { + self.longest = self.longest.max(at.saturating_duration_since(self.since)); + } + + fn moved(&mut self, at: Instant) { + self.close(at); + self.since = at; + } +} + +/// Decides a stall from samples. A stall takes a full window in which every +/// source was sampled and none moved, confirmed by at least +/// [`UNCHANGED_SAMPLES_FOR_A_STALL`] samples in a row equal to the one before +/// them. A sample that could not read the folder confirms nothing. +struct StallDetector { + window: Duration, + last: Option<(InProcess, FolderSample)>, + unchanged: u32, + overall: Quiet, + outside_storage_stages: Quiet, + packets: Quiet, + steps: Quiet, + folder: Quiet, + samples: u32, + folder_unknown: u32, + storage_call_samples: u32, + last_in_process: InProcess, +} + +impl StallDetector { + fn new(window: Duration, at: Instant) -> Self { + Self { + window, + last: None, + unchanged: 0, + overall: Quiet::new(at), + outside_storage_stages: Quiet::new(at), + packets: Quiet::new(at), + steps: Quiet::new(at), + folder: Quiet::new(at), + samples: 0, + folder_unknown: 0, + storage_call_samples: 0, + last_in_process: InProcess::default(), + } + } + + fn observe( + &mut self, + at: Instant, + in_process: InProcess, + folder: Option, + ) -> bool { + self.samples += 1; + let first = self.samples == 1; + let packets_moved = !first && in_process.packets != self.last_in_process.packets; + let steps_moved = !first && in_process.steps != self.last_in_process.steps; + self.last_in_process = in_process; + if packets_moved { + self.packets.moved(at); + } + if steps_moved { + self.steps.moved(at); + } + let folder_moved = match (folder, &self.last) { + (Some(folder), Some((_, last))) => folder != *last, + _ => false, + }; + if folder_moved { + self.folder.moved(at); + } + if packets_moved || steps_moved || folder_moved { + self.outside_storage_stages.moved(at); + } + if in_process.in_storage_call { + self.storage_call_samples += 1; + } + if packets_moved || steps_moved || folder_moved || in_process.waits_on_storage() { + self.overall.moved(at); + self.unchanged = 0; + } + + let Some(folder) = folder else { + self.folder_unknown += 1; + return false; + }; + let unchanged = self.last.replace((in_process, folder)) == Some((in_process, folder)) + && !in_process.waits_on_storage(); + if !unchanged { + self.unchanged = 0; + return false; + } + self.unchanged += 1; + self.unchanged >= UNCHANGED_SAMPLES_FOR_A_STALL + && at.saturating_duration_since(self.overall.since) >= self.window + } + + fn finish(mut self, at: Instant) -> QuietGaps { + for quiet in [ + &mut self.overall, + &mut self.outside_storage_stages, + &mut self.packets, + &mut self.steps, + &mut self.folder, + ] { + quiet.close(at); + } + QuietGaps { + samples: self.samples, + folder_unknown: self.folder_unknown, + storage_call_samples: self.storage_call_samples, + overall: self.overall.longest, + outside_storage_stages: self.outside_storage_stages.longest, + packets: self.packets.longest, + steps: self.steps.longest, + folder: self.folder.longest, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const WINDOW: Duration = Duration::from_secs(10); + + fn folder(bytes: u64) -> Option { + Some(FolderSample { + files: 3, + bytes, + newest_modified: None, + }) + } + + fn in_process(packets: u64, steps: u64) -> InProcess { + InProcess { + packets, + steps, + in_storage_stage: false, + in_storage_call: false, + } + } + + fn seconds(start: Instant, seconds: u64) -> Instant { + start + Duration::from_secs(seconds) + } + + #[test] + fn late_stop_stalls_after_a_window_in_which_nothing_moved() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + for second in 0..10 { + assert!( + !detector.observe(seconds(start, second), in_process(7, 1), folder(100)), + "stalled after {second} s" + ); + } + assert!(detector.observe(seconds(start, 10), in_process(7, 1), folder(100))); + } + + #[test] + fn late_stop_stays_alive_while_any_one_source_moves() { + type Step = fn(u64) -> (InProcess, Option); + let sources: [Step; 5] = [ + |second| (in_process(second, 0), folder(100)), + |second| (in_process(0, second / 5), folder(100)), + |second| (in_process(0, 0), folder(100 + second / 8)), + |_| { + ( + InProcess { + in_storage_stage: true, + ..in_process(0, 0) + }, + folder(100), + ) + }, + |_| { + ( + InProcess { + in_storage_call: true, + ..in_process(0, 0) + }, + folder(100), + ) + }, + ]; + for source in sources { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + for second in 0..600 { + let (in_process, folder) = source(second); + assert!(!detector.observe(seconds(start, second), in_process, folder)); + } + } + } + + #[test] + fn late_stop_is_not_stalled_by_one_late_sample() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + assert!(!detector.observe(start, in_process(7, 1), folder(100))); + assert!(!detector.observe(seconds(start, 45), in_process(7, 1), folder(100))); + assert!(detector.observe(seconds(start, 46), in_process(7, 1), folder(100))); + } + + #[test] + fn late_stop_is_not_stalled_while_the_folder_cannot_be_read() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + assert!(!detector.observe(start, in_process(7, 1), folder(100))); + for second in 1..300 { + assert!(!detector.observe(seconds(start, second), in_process(7, 1), None)); + } + assert!(!detector.observe(seconds(start, 300), in_process(7, 1), folder(100))); + assert!(detector.observe(seconds(start, 301), in_process(7, 1), folder(100))); + assert_eq!(detector.finish(seconds(start, 301)).folder_unknown, 299); + } + + #[test] + fn late_stop_counts_what_changed_while_the_folder_could_not_be_read() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + assert!(!detector.observe(start, in_process(7, 1), folder(100))); + for second in 1..30 { + assert!(!detector.observe(seconds(start, second), in_process(7, 1), None)); + } + assert!(!detector.observe(seconds(start, 30), in_process(7, 1), folder(101))); + assert!(!detector.observe(seconds(start, 31), in_process(7, 1), folder(101))); + for second in 32..40 { + assert!(!detector.observe(seconds(start, second), in_process(7, 1), folder(101))); + } + assert!(detector.observe(seconds(start, 40), in_process(7, 1), folder(101))); + } + + #[test] + fn late_stop_restarts_its_window_when_a_storage_stage_ends() { + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + let held = InProcess { + in_storage_stage: true, + ..in_process(7, 1) + }; + for second in 0..100 { + assert!(!detector.observe(seconds(start, second), held, folder(100))); + } + for second in 100..109 { + assert!(!detector.observe(seconds(start, second), in_process(7, 2), folder(100))); + } + assert!(detector.observe(seconds(start, 110), in_process(7, 2), folder(100))); + let quiet = detector.finish(seconds(start, 110)); + assert_eq!(quiet.overall, Duration::from_secs(10)); + assert_eq!(quiet.outside_storage_stages, Duration::from_secs(100)); + } + + #[test] + fn late_stop_storage_stage_counts_until_it_is_dropped() { + let progress = StopProgress::default(); + let written = Arc::new(AtomicU64::new(4)); + progress.watch_packets(written.clone()); + assert_eq!(progress.sample(), in_process(4, 0)); + let stage = progress.storage_stage("test"); + written.fetch_add(2, Ordering::Relaxed); + assert_eq!( + progress.sample(), + InProcess { + in_storage_stage: true, + ..in_process(6, 0) + } + ); + drop(stage); + assert_eq!(progress.sample(), in_process(6, 1)); + assert_eq!(progress.storage_held().len(), 1); + } + + #[test] + fn late_stop_write_that_has_not_returned_counts_until_it_returns() { + let progress = StopProgress::default(); + let call = StorageCall::default(); + progress.watch_storage_calls(call.clone()); + assert!(!progress.sample().waits_on_storage()); + + call.set(true); + assert!(progress.sample().in_storage_call); + let start = Instant::now(); + let mut detector = StallDetector::new(WINDOW, start); + for second in 0..60 { + assert!(!detector.observe(seconds(start, second), progress.sample(), folder(100))); + } + + call.set(false); + for second in 60..69 { + assert!(!detector.observe(seconds(start, second), progress.sample(), folder(100))); + } + assert!(detector.observe(seconds(start, 69), progress.sample(), folder(100))); + assert_eq!(detector.finish(seconds(start, 69)).storage_call_samples, 60); + } + + #[test] + fn late_stop_folder_sample_sees_bytes_written_to_an_open_file() { + use std::io::Write as _; + + let temp = tempfile::tempdir().unwrap(); + let nested = temp.path().join("content/segments/segment-0/display"); + std::fs::create_dir_all(&nested).unwrap(); + std::fs::write(nested.join("init.mp4"), [0u8; 10]).unwrap(); + let mut open = std::fs::File::create(nested.join("segment_000.m4s")).unwrap(); + let before = FolderSample::read(temp.path()).unwrap(); + assert_eq!((before.files, before.bytes), (2, 10)); + + open.write_all(&[0u8; 4096]).unwrap(); + open.flush().unwrap(); + let after = FolderSample::read(temp.path()).unwrap(); + assert_eq!((after.files, after.bytes), (2, 4106)); + assert_ne!(before, after); + + assert!(FolderSample::read(&temp.path().join("missing")).is_none()); + } + + #[derive(Default)] + struct Calls { + stops: AtomicU32, + finishes: AtomicU32, + health_senders: AtomicU32, + audio_frames: AtomicU32, + frames_seen_as_a_write_in_flight: AtomicU32, + progress: StopProgress, + } + + struct CountingMuxer(Arc); + + impl Muxer for CountingMuxer { + type Config = Arc; + + async fn setup( + calls: Self::Config, + _: PathBuf, + _: Option, + _: Option, + _: Arc, + _: &mut TaskPool, + ) -> anyhow::Result { + Ok(Self(calls)) + } + + fn stop(&mut self) { + self.0.stops.fetch_add(1, Ordering::Relaxed); + } + + fn finish(&mut self, _: Duration) -> anyhow::Result> { + self.0.finishes.fetch_add(1, Ordering::Relaxed); + Ok(Ok(())) + } + + fn set_health_sender(&mut self, _: HealthSender) { + self.0.health_senders.fetch_add(1, Ordering::Relaxed); + } + } + + impl AudioMuxer for CountingMuxer { + fn send_audio_frame(&mut self, _: AudioFrame, _: Duration) -> anyhow::Result<()> { + self.0.audio_frames.fetch_add(1, Ordering::Relaxed); + if self.0.progress.sample().in_storage_call { + self.0 + .frames_seen_as_a_write_in_flight + .fetch_add(1, Ordering::Relaxed); + } + Ok(()) + } + } + + #[tokio::test] + async fn late_stop_reporting_muxer_forwards_every_call_and_steps_only_once_the_stop_began() { + let progress = StopProgress::default(); + let calls = Arc::new(Calls { + progress: progress.clone(), + ..Default::default() + }); + let mut muxer = StopReportingMuxer::::setup( + (calls.clone(), progress.clone()), + PathBuf::from("content/segments/segment-0/audio-input.m4a"), + None, + None, + Arc::new(AtomicBool::new(false)), + &mut TaskPool::default(), + ) + .await + .unwrap(); + let frame = || { + AudioFrame::new( + ffmpeg::frame::Audio::empty(), + cap_timestamp::Timestamp::Instant(Instant::now()), + ) + }; + + muxer.set_health_sender(tokio::sync::mpsc::channel(1).0); + muxer.send_audio_frame(frame(), Duration::ZERO).unwrap(); + muxer.send_audio_frame(frame(), Duration::ZERO).unwrap(); + assert_eq!(progress.sample(), in_process(0, 0)); + + progress.stop_began(); + muxer.send_audio_frame(frame(), Duration::ZERO).unwrap(); + assert_eq!(progress.sample(), in_process(0, 1)); + + muxer.stop(); + muxer.finish(Duration::ZERO).unwrap().unwrap(); + assert_eq!(progress.sample(), in_process(0, 2)); + assert_eq!(progress.storage_held()[0].0, "audio-input.m4a"); + + assert_eq!(calls.stops.load(Ordering::Relaxed), 1); + assert_eq!(calls.finishes.load(Ordering::Relaxed), 1); + assert_eq!(calls.health_senders.load(Ordering::Relaxed), 1); + assert_eq!(calls.audio_frames.load(Ordering::Relaxed), 3); + assert_eq!( + calls + .frames_seen_as_a_write_in_flight + .load(Ordering::Relaxed), + 3, + "a frame being written counts as a write in flight, before and after the stop began" + ); + assert!(!progress.sample().in_storage_call); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_stop_watch_reports_a_stall_and_ends_when_the_tracks_finish() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("display.mp4"), [0u8; 10]).unwrap(); + + let unwatched = StopProgress::default(); + assert!( + tokio::time::timeout( + Duration::from_secs(5), + unwatched.stalled(temp.path().to_path_buf(), Duration::from_secs(2)), + ) + .await + .is_err(), + "a recording whose muxers report nothing must never be reported as stalled" + ); + + let stuck = StopProgress::default(); + stuck.watch_packets(Arc::new(AtomicU64::new(0))); + tokio::time::timeout( + Duration::from_secs(30), + stuck.stalled(temp.path().to_path_buf(), Duration::from_secs(2)), + ) + .await + .expect("a track that never moves must be reported as stalled"); + + let finishing = StopProgress::default(); + let written = Arc::new(AtomicU64::new(0)); + finishing.watch_packets(written.clone()); + let feeder = std::thread::spawn({ + let finishing = finishing.clone(); + move || { + for _ in 0..12 { + std::thread::sleep(Duration::from_millis(250)); + written.fetch_add(1, Ordering::Relaxed); + } + finishing.tracks_finished(); + } + }); + assert!( + tokio::time::timeout( + Duration::from_secs(6), + finishing.stalled(temp.path().to_path_buf(), Duration::from_secs(2)), + ) + .await + .is_err(), + "a track that keeps writing and then finishes must never be reported as stalled" + ); + feeder.join().unwrap(); + } +} diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs index 3762171bcea..6ca6916e58a 100644 --- a/crates/recording/src/studio_recording.rs +++ b/crates/recording/src/studio_recording.rs @@ -401,6 +401,7 @@ struct LateStopInner { late: watch::Sender, finishing: std::sync::Mutex>, inputs: std::sync::Mutex>, + progress: std::sync::OnceLock, } /// The microphone and camera a stopping recording still holds. A stop that @@ -419,6 +420,7 @@ impl Default for LateStopInner { late: watch::channel(false).0, finishing: std::sync::Mutex::new(None), inputs: std::sync::Mutex::new(None), + progress: std::sync::OnceLock::new(), } } } @@ -471,7 +473,19 @@ impl LateStop { .take() } + /// Follows `progress`, which the recording's encoders report to, unless + /// this stop already follows one. + fn follow(&self, progress: &crate::stop_progress::StopProgress) { + let _ = self.0.progress.set(progress.clone()); + self.progress().stop_began(); + } + + fn progress(&self) -> &crate::stop_progress::StopProgress { + self.0.progress.get_or_init(Default::default) + } + fn release(&self) { + self.progress().tracks_finished(); drop(self.take_inputs()); let finished = self .0 @@ -493,6 +507,13 @@ impl LateStop { } } +/// How long the tracks of a late stop may show no progress before waiting +/// for them is given up. A track that is only slow keeps writing packets, +/// growing its files or working through its storage stages; one that moves +/// nothing for this long is not expected to finish. +#[cfg(windows)] +pub const STUDIO_FINISH_STALL: Duration = Duration::from_secs(5); + /// Completes a stop that returned while its tracks were still finishing. #[cfg(windows)] #[derive(Clone)] @@ -525,6 +546,23 @@ impl StudioFinishing { }); studio_stop_outcome(report) } + + /// Resolves once the tracks still finishing have shown no progress for + /// [`STUDIO_FINISH_STALL`]: nothing written by their encoders, no stage + /// of their stop completed and nothing changed in the recording folder. + /// Stays pending for good once the tracks have finished, so it never + /// cuts short the saving that follows them. + pub async fn stalled(&self) { + self.stalled_for(STUDIO_FINISH_STALL).await; + } + + async fn stalled_for(&self, window: Duration) { + self.terminal + .late_stop + .progress() + .stalled(self.recording_dir.clone(), window) + .await; + } } #[cfg(any(target_os = "macos", windows))] @@ -545,6 +583,37 @@ fn studio_stop_outcome(report: WindowsStudioStopReport) -> StudioStopOutcome { } } +/// The muxer of a fragmented Studio audio track. On Windows its finish is +/// reported to the recording's stop progress. +#[cfg(windows)] +type StudioAudioMuxer = crate::stop_progress::StopReportingMuxer; +#[cfg(not(windows))] +type StudioAudioMuxer = M; + +#[cfg(windows)] +fn studio_audio_muxer_config( + config: C, + encoder_preferences: &crate::capture_pipeline::EncoderPreferences, +) -> (C, crate::stop_progress::StopProgress) { + (config, encoder_preferences.finish_wait().progress().clone()) +} + +#[cfg(not(windows))] +fn studio_audio_muxer_config(config: C) -> C { + config +} + +#[cfg(windows)] +async fn stop_track_or_late( + track: OutputPipeline, + late: impl FnOnce(), + progress: &crate::stop_progress::StopProgress, +) -> anyhow::Result { + let stopped = track.stop_with_outcome_or_late(late).await; + progress.step(); + stopped +} + #[derive(Clone)] pub struct ActorHandle { #[cfg(target_os = "linux")] @@ -876,10 +945,9 @@ impl Actor { #[cfg(windows)] let late_stop = (!discard).then(|| { - self.segment_factory - .encoder_preferences - .finish_wait() - .wait_without_limit(); + let finish_wait = self.segment_factory.encoder_preferences.finish_wait(); + finish_wait.wait_without_limit(); + self.late_stop.follow(finish_wait.progress()); self.late_stop.clone() }); match self @@ -2077,18 +2145,20 @@ impl Pipeline { ), Some((late_stop, recording_dir)) => { let late = || late_stop.mark(recording_dir); + let progress = late_stop.progress(); + let stop = |track: OutputPipeline| stop_track_or_late(track, late, progress); let (screen, microphone, camera, system_audio) = (self.screen, self.microphone, self.camera, self.system_audio); let stops = async { futures::join!( - screen.stop_with_outcome_or_late(late), - OptionFuture::from(microphone.map(|s| s.stop_with_outcome_or_late(late))), - OptionFuture::from(camera.map(|s| s.stop_with_outcome_or_late(late))), - OptionFuture::from(system_audio.map(|s| s.stop_with_outcome_or_late(late))) + stop(screen), + OptionFuture::from(microphone.map(stop)), + OptionFuture::from(camera.map(stop)), + OptionFuture::from(system_audio.map(stop)) ) }; let mut stops = std::pin::pin!(stops); - tokio::select! { + let stopped = tokio::select! { biased; stopped = &mut stops => stopped, () = late_stop.wait() => { @@ -2097,7 +2167,9 @@ impl Pipeline { } stops.await } - } + }; + progress.tracks_finished(); + stopped } }; @@ -4412,10 +4484,14 @@ async fn create_segment_pipeline( .with_audio_source::(mic_feed) .with_timestamps(start_time) .with_start_gate(start_gate.clone()) - .build::(FragmentedAudioMuxerConfig { - shared_pause_state: shared_pause_state.clone(), - write_behind: cfg!(target_os = "macos"), - }) + .build::>(studio_audio_muxer_config( + FragmentedAudioMuxerConfig { + shared_pause_state: shared_pause_state.clone(), + write_behind: cfg!(target_os = "macos"), + }, + #[cfg(windows)] + &encoder_preferences, + )) .instrument(error_span!("mic-out")) .await } else { @@ -4447,10 +4523,14 @@ async fn create_segment_pipeline( .with_timestamps(start_time) .with_start_gate(start_gate.clone()) .with_audio_anchor(AudioAnchor::PipelineEpoch) - .build::(FragmentedAudioMuxerConfig { - shared_pause_state: shared_pause_state.clone(), - write_behind: cfg!(target_os = "macos"), - }) + .build::>(studio_audio_muxer_config( + FragmentedAudioMuxerConfig { + shared_pause_state: shared_pause_state.clone(), + write_behind: cfg!(target_os = "macos"), + }, + #[cfg(windows)] + &encoder_preferences, + )) .instrument(error_span!("system-audio-out")) .await } else { @@ -5683,6 +5763,145 @@ mod tests { assert!(!crate::recovery::finishing::contains(path)); } + /// A track that never moves is reported as stalled, and giving up on it + /// changes nothing: the project is as a stop still waiting leaves it, and + /// is saved normally if the track does finish. + #[cfg(windows)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_stop_reports_a_stall_when_its_tracks_show_no_progress() { + let temp = tempfile::tempdir().unwrap(); + let project = temp.path().join("recording.cap"); + let path = project.as_path(); + let (handle, release, _screen_tx, _sent) = studio_with_slow_screen_finish(path).await; + + let outcome = tokio::time::timeout(Duration::from_secs(30), handle.stop_with_outcome()) + .await + .expect("Stop must return at its limit while a track is still finishing"); + let finishing = outcome.finishing.clone().unwrap(); + assert!( + tokio::time::timeout( + Duration::from_secs(6), + finishing.stalled_for(Duration::from_secs(2)), + ) + .await + .is_err(), + "a recording whose muxers report nothing must never be reported as stalled" + ); + handle + .terminal + .late_stop + .progress() + .watch_packets(Arc::new(std::sync::atomic::AtomicU64::new(0))); + let waiting = Instant::now(); + tokio::time::timeout( + Duration::from_secs(20), + finishing.stalled_for(Duration::from_secs(3)), + ) + .await + .expect("a track that shows no progress must be reported as stalled"); + assert!(waiting.elapsed() >= Duration::from_secs(3)); + + assert!(matches!( + studio_status(path), + StudioRecordingStatus::InProgress + )); + assert!(crate::recovery::finishing::contains(path)); + assert!(crate::recovery::RecoveryManager::find_incomplete(temp.path()).is_empty()); + + release.send(()).unwrap(); + let finished = finishing.wait().await; + assert!(matches!( + finished.result.unwrap().meta.status(), + StudioRecordingStatus::Complete + )); + assert!(!crate::recovery::finishing::contains(path)); + } + + /// A slow track is waited for as long as it reports progress, whichever + /// way it reports it, and nothing stalls once the tracks have finished and + /// the recording is being saved. + #[cfg(windows)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn late_stop_is_not_stalled_while_its_tracks_report_progress() { + let temp = tempfile::tempdir().unwrap(); + let project = temp.path().join("recording.cap"); + let path = project.as_path(); + let (handle, release, _screen_tx, _sent) = studio_with_slow_screen_finish(path).await; + + let outcome = tokio::time::timeout(Duration::from_secs(30), handle.stop_with_outcome()) + .await + .expect("Stop must return at its limit while a track is still finishing"); + let finishing = outcome.finishing.clone().unwrap(); + let progress = handle.terminal.late_stop.progress().clone(); + let window = Duration::from_secs(2); + let not_stalled = |what: &'static str| { + let finishing = finishing.clone(); + async move { + assert!( + tokio::time::timeout(Duration::from_secs(6), finishing.stalled_for(window)) + .await + .is_err(), + "{what} must keep the stop alive" + ); + } + }; + let feed = |feed: Box| { + let (stop, stopped) = std::sync::mpsc::channel::<()>(); + let feeder = std::thread::spawn(move || { + loop { + feed(); + if stopped.recv_timeout(Duration::from_millis(250)) + != Err(std::sync::mpsc::RecvTimeoutError::Timeout) + { + break; + } + } + }); + (stop, feeder) + }; + + let written = Arc::new(std::sync::atomic::AtomicU64::new(0)); + progress.watch_packets(written.clone()); + let (stop, feeder) = feed(Box::new(move || { + written.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + })); + not_stalled("an encoder writing packets").await; + drop(stop); + feeder.join().unwrap(); + + let steps = progress.clone(); + let (stop, feeder) = feed(Box::new(move || steps.step())); + not_stalled("a stop working through its stages").await; + drop(stop); + feeder.join().unwrap(); + + let media = path.join("content/display.mp4"); + let (stop, feeder) = feed(Box::new(move || { + use std::io::Write as _; + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&media) + .unwrap(); + file.write_all(&[0u8; 512]).unwrap(); + })); + not_stalled("a file that keeps growing").await; + drop(stop); + feeder.join().unwrap(); + + let stage = progress.storage_stage("test"); + not_stalled("a finish waiting on storage").await; + drop(stage); + + tokio::time::timeout(Duration::from_secs(20), finishing.stalled_for(window)) + .await + .expect("the stop must stall once nothing reports progress any more"); + + release.send(()).unwrap(); + finishing.wait().await.result.unwrap(); + not_stalled("a stop whose tracks have finished").await; + } + /// The user asks to stop, but the Stop reaches the recording long after /// (its runtime was busy): what the screen captured in between is not /// saved, and the stop still goes late and finishes normally. diff --git a/scripts/linux-desktop-harness/appimage-pipewire/run.sh b/scripts/linux-desktop-harness/appimage-pipewire/run.sh index 023b79cb598..1161cf48e22 100755 --- a/scripts/linux-desktop-harness/appimage-pipewire/run.sh +++ b/scripts/linux-desktop-harness/appimage-pipewire/run.sh @@ -20,8 +20,9 @@ chmod -R a+rX squashfs-root # Built like Cap: a host-ABI binary (Ubuntu's toolchain) that finds the # bundled FFmpeg through RUNPATH $ORIGIN/../lib. -docker run --rm -v "$here":/src:ro -v "$work":/work -w /work ubuntu:24.04 bash -euc ' - apt-get update -qq >/dev/null && apt-get install -y -qq gcc pkg-config libpipewire-0.3-dev >/dev/null +apt_install=(-v "$here/../apt-install.sh":/apt-install.sh:ro) +docker run --rm "${apt_install[@]}" -v "$here":/src:ro -v "$work":/work -w /work ubuntu:24.04 bash -euc ' + sh /apt-install.sh -qq gcc pkg-config libpipewire-0.3-dev >/dev/null gcc -o probe /src/probe.c $(pkg-config --cflags --libs libpipewire-0.3) \ -L squashfs-root/usr/lib -l:libavutil.so.59 -Wl,--allow-shlib-undefined -Wl,-rpath,"\$ORIGIN/../lib" chmod 755 probe' @@ -36,7 +37,18 @@ FINALIZE="$repo/scripts/finalize-linux-appimage.mjs" APPDIR_FIXED="$work/fixed" node --input-type=module -e ' const { isolateBundledLibva, directAppRunWrapper, fallbackLibvaDirectory } = await import(process.env.FINALIZE); const { writeFile } = await import("node:fs/promises"); - const replacement = await fallbackLibvaDirectory(process.env.LIBVA_WORK); + const mirrored = (url) => url.replace("http://archive.ubuntu.com/", "http://azure.archive.ubuntu.com/"); + const download = async (url) => { + try { + const response = await fetch(url, { signal: AbortSignal.timeout(30000) }); + if (!response.ok) throw new Error("HTTP " + response.status); + return new Response(await response.arrayBuffer()); + } catch (error) { + console.error("apt-install: " + url + " failed (" + (error.cause?.code ?? error.message) + "), falling back to " + mirrored(url)); + return fetch(mirrored(url)); + } + }; + const replacement = await fallbackLibvaDirectory(process.env.LIBVA_WORK, { download }); const moved = await isolateBundledLibva(process.env.APPDIR_FIXED, { replacement }); await writeFile(process.env.APPDIR_FIXED + "/AppRun", directAppRunWrapper, { mode: 0o755 }); console.log("moved " + moved.join(" ") + "; fallback from " + replacement); @@ -49,8 +61,8 @@ chmod -R a+rX "$work" # packed the way the original was. offset=$(./Cap.AppImage --appimage-offset) head -c "$offset" Cap.AppImage >runtime -docker run --rm -v "$work":/work -w /work ubuntu:24.04 bash -euc ' - apt-get update -qq >/dev/null && apt-get install -y -qq squashfs-tools >/dev/null +docker run --rm "${apt_install[@]}" -v "$work":/work -w /work ubuntu:24.04 bash -euc ' + sh /apt-install.sh -qq squashfs-tools >/dev/null for layout in shipped fixed; do mksquashfs "$layout" "$layout.squashfs" -root-owned -noappend -comp zstd -quiet >/dev/null cat runtime "$layout.squashfs" >"$layout.AppImage" diff --git a/scripts/linux-desktop-harness/apt-install.sh b/scripts/linux-desktop-harness/apt-install.sh new file mode 100755 index 00000000000..a57907b8b71 --- /dev/null +++ b/scripts/linux-desktop-harness/apt-install.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# apt-get install inside an Ubuntu container: from the image's own sources +# first, and from the Azure mirror (which also carries the -security pocket) +# when archive.ubuntu.com or security.ubuntu.com does not answer. +# Usage: apt-install.sh [--no-update] +set -u +mirror=http://azure.archive.ubuntu.com/ubuntu +update=yes +if [ "${1:-}" = --no-update ]; then + update=no + shift +fi + +fetch() { + opts=$1 + shift + if [ "$update" = yes ]; then + # shellcheck disable=SC2086 + apt-get $opts --error-on=any update || return + fi + # shellcheck disable=SC2086 + apt-get $opts install -y "$@" +} + +fetch "-o Acquire::Retries=1 -o Acquire::http::Timeout=10" "$@" && exit 0 +echo "apt-install: the Ubuntu archive failed, falling back to $mirror" | tee -a /var/log/apt-install.log >&2 +for list in /etc/apt/sources.list /etc/apt/sources.list.d/ubuntu.sources; do + [ -f "$list" ] && sed -i -E "s#https?://(archive|security)\.ubuntu\.com/ubuntu#$mirror#g" "$list" +done +update=yes +fetch "-o Acquire::Retries=4" "$@" diff --git a/scripts/linux-desktop-harness/gnome.Dockerfile b/scripts/linux-desktop-harness/gnome.Dockerfile index 138308103e0..89221a52a6c 100644 --- a/scripts/linux-desktop-harness/gnome.Dockerfile +++ b/scripts/linux-desktop-harness/gnome.Dockerfile @@ -5,24 +5,17 @@ # where the portal reads a host app's id from. FROM ubuntu:26.04 ENV DEBIAN_FRONTEND=noninteractive -# Ubuntu's mirrors answer 502 for minutes at a time: apt retries each file, -# and a failed install is tried again from another mirror. -RUN for mirror in "" http://azure.archive.ubuntu.com/ubuntu; do \ - if [ -n "$mirror" ]; then \ - sed -i "s#http://archive.ubuntu.com/ubuntu#$mirror#g" /etc/apt/sources.list.d/ubuntu.sources || continue; \ - fi; \ - apt-get -o Acquire::Retries=4 update \ - && apt-get -o Acquire::Retries=4 install -y --no-install-recommends \ - systemd systemd-sysv dbus dbus-user-session libpam-systemd \ - gnome-shell mutter xdg-desktop-portal xdg-desktop-portal-gnome \ - ubuntu-session yaru-theme-gnome-shell yaru-theme-icon yaru-theme-gtk \ - gnome-shell-extension-ubuntu-dock gnome-settings-daemon \ - gnome-shell-extension-appindicator pipewire wireplumber pipewire-pulse \ - mesa-vulkan-drivers libgl1-mesa-dri libegl-mesa0 python3 python3-gi gir1.2-glib-2.0 \ - at-spi2-core gir1.2-atspi-2.0 gnome-backgrounds \ - procps psmisc ca-certificates xdg-utils \ - && apt-get clean && exit 0; \ - done; exit 1 +COPY apt-install.sh /usr/local/bin/apt-install.sh +RUN sh /usr/local/bin/apt-install.sh --no-install-recommends \ + systemd systemd-sysv dbus dbus-user-session libpam-systemd \ + gnome-shell mutter xdg-desktop-portal xdg-desktop-portal-gnome \ + ubuntu-session yaru-theme-gnome-shell yaru-theme-icon yaru-theme-gtk \ + gnome-shell-extension-ubuntu-dock gnome-settings-daemon \ + gnome-shell-extension-appindicator pipewire wireplumber pipewire-pulse \ + mesa-vulkan-drivers libgl1-mesa-dri libegl-mesa0 python3 python3-gi gir1.2-glib-2.0 \ + at-spi2-core gir1.2-atspi-2.0 gnome-backgrounds \ + procps psmisc ca-certificates xdg-utils \ + && apt-get clean RUN useradd -m -u 1001 tester \ && mkdir -p /var/lib/systemd/linger && touch /var/lib/systemd/linger/tester \ && systemctl mask systemd-binfmt.service proc-sys-fs-binfmt_misc.automount \ diff --git a/scripts/linux-desktop-harness/run-desktop.sh b/scripts/linux-desktop-harness/run-desktop.sh index b8c67927554..e41bd00cad3 100644 --- a/scripts/linux-desktop-harness/run-desktop.sh +++ b/scripts/linux-desktop-harness/run-desktop.sh @@ -53,6 +53,7 @@ docker run -d --name "$name" --privileged --cgroupns=host "${docker_extra[@]}" \ -v "$package":/pkgs/"$(basename "$package")":ro -v "$here":/harness:ro -v "$out":/out \ "${cache_mounts[@]}" "${dev_mounts[@]}" "$image" >/dev/null trap 'docker rm -f "$name" >/dev/null 2>&1' EXIT +docker exec "$name" cat /var/log/apt-install.log 2>/dev/null || true for _ in $(seq 60); do state=$(docker exec "$name" systemctl is-system-running 2>/dev/null || true) [[ $state == running || $state == degraded ]] && break @@ -62,27 +63,19 @@ done # test user the access a seat grants it on a real machine. docker exec "$name" sh -c 'chmod 666 /dev/dri/* 2>/dev/null || true' envs=(-e HARNESS_OUT=/out -e DESKTOP="$desktop" "${extra_env[@]}") -# Ubuntu's mirrors answer 502 for minutes at a time: apt retries each file, -# a failed install is tried again, and then again from another mirror. +# Ubuntu's mirrors answer 502 for minutes at a time: apt-install.sh falls back +# to another mirror, and a failed install is tried again. install_deb() { - local deb mirror attempt + local deb attempt deb=/pkgs/$(basename "$package") : >"$out/install.log" # The image's apt deletes packages once installed; keep them in the cache. docker exec "$name" rm -f /etc/apt/apt.conf.d/docker-clean - for mirror in "" http://azure.archive.ubuntu.com/ubuntu; do - if [[ -n $mirror ]]; then - echo "switching to $mirror" >>"$out/install.log" - docker exec "$name" sed -i "s#http://archive.ubuntu.com/ubuntu#$mirror#g" \ - /etc/apt/sources.list.d/ubuntu.sources >>"$out/install.log" 2>&1 || continue - docker exec "$name" apt-get update -qq >>"$out/install.log" 2>&1 || continue - fi - for attempt in 1 2; do - docker exec "$name" apt-get install -y -qq -o Acquire::Retries=4 "$deb" \ - >>"$out/install.log" 2>&1 && return 0 - echo "install attempt $attempt failed" >>"$out/install.log" - sleep $((attempt * 15)) - done + for attempt in 1 2; do + docker exec "$name" sh /harness/apt-install.sh --no-update -qq "$deb" \ + >>"$out/install.log" 2>&1 && return 0 + echo "install attempt $attempt failed" >>"$out/install.log" + sleep $((attempt * 15)) done return 100 }