Repository navigation
fix(serial): stop holding ports after deploy; name the holder on EBUSY (#1429) #1599
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
352e7d9
fix(serial): name the port holder instead of blaming the driver on op…
zackees 2829197
fix(serial): reopen instead of reusing a session whose reader exited …
zackees b7fdf88
fix(daemon): always release the ws writer on cleanup so idle close ca…
zackees f6edfdb
refactor(serial): make port-holder matching pure so it needs no cfg o…
zackees 8a1e325
fix(serial): use NormalizedPath and async canonicalize in port_holder…
zackees 251e7ee
fix(serial): address review — keep alias on stale reopen, bound the /…
zackees File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| //! Identify which process holds a serial port open (FastLED/fbuild#1429). | ||
| //! | ||
| //! An `open()` that fails with `EBUSY` was previously reported as | ||
| //! "serial driver may be wedged", which sent investigations to the device | ||
| //! and USB layer when the port was simply held by another fd (often the | ||
| //! daemon itself). This scans `/proc/*/fd` so the error can name the holder. | ||
| //! On hosts without `/proc` the scan finds nothing and callers fall back to | ||
| //! the generic message. | ||
|
|
||
| use std::path::Path; | ||
|
|
||
| use fbuild_core::path::{NormalizedPath, canonicalize_existing}; | ||
|
|
||
| /// A process that has the port's device node open. | ||
| #[derive(Debug, Clone, PartialEq, Eq)] | ||
| pub struct PortHolder { | ||
| pub pid: u32, | ||
| pub name: String, | ||
| } | ||
|
|
||
| /// Pure matcher: `procs` yields `(pid, name, fd link targets)`; returns the | ||
| /// processes with an fd pointing at `port` or at its resolved `canonical` | ||
| /// path. | ||
| pub fn match_port_holders( | ||
| procs: impl IntoIterator<Item = (u32, String, Vec<NormalizedPath>)>, | ||
| port: &NormalizedPath, | ||
| canonical: &NormalizedPath, | ||
| ) -> Vec<PortHolder> { | ||
| let mut holders: Vec<PortHolder> = procs | ||
| .into_iter() | ||
| .filter(|(_, _, links)| links.iter().any(|link| link == canonical || link == port)) | ||
| .map(|(pid, name, _)| PortHolder { pid, name }) | ||
| .collect(); | ||
| holders.sort_by_key(|h| h.pid); | ||
| holders | ||
| } | ||
|
|
||
| /// Read a `/proc`-shaped tree rooted at `proc_root` into `(pid, comm, fds)`. | ||
| fn read_proc_tree(proc_root: &Path) -> Vec<(u32, String, Vec<NormalizedPath>)> { | ||
| let Ok(entries) = std::fs::read_dir(proc_root) else { | ||
| return Vec::new(); | ||
| }; | ||
| entries | ||
| .flatten() | ||
| .filter_map(|entry| { | ||
| let pid = entry.file_name().to_str()?.parse::<u32>().ok()?; | ||
| let fds = std::fs::read_dir(entry.path().join("fd")).ok()?; | ||
| let links = fds | ||
| .flatten() | ||
| .filter_map(|fd| std::fs::read_link(fd.path()).ok()) | ||
| .map(NormalizedPath::from) | ||
| .collect(); | ||
| let name = std::fs::read_to_string(entry.path().join("comm")) | ||
| .map(|s| s.trim().to_string()) | ||
| .unwrap_or_else(|_| "unknown".to_string()); | ||
| Some((pid, name, links)) | ||
| }) | ||
| .collect() | ||
| } | ||
|
|
||
| /// Longest the diagnostic may delay an error response. | ||
| const SCAN_BUDGET: std::time::Duration = std::time::Duration::from_millis(500); | ||
|
|
||
| /// Scan a `/proc`-shaped tree for processes holding `port` open. The scan | ||
| /// walks every process's fd table, so it runs on the blocking pool with a | ||
| /// bounded wait; `None` means the scan did not finish in time. | ||
| pub async fn find_port_holders_in( | ||
| proc_root: &NormalizedPath, | ||
| port: &str, | ||
| ) -> Option<Vec<PortHolder>> { | ||
| let port_path = NormalizedPath::new(port); | ||
| let canonical = canonicalize_existing(port) | ||
| .await | ||
| .unwrap_or_else(|_| port_path.clone()); | ||
| let root = proc_root.clone(); | ||
| let scan = tokio::task::spawn_blocking(move || read_proc_tree(root.as_path())); | ||
| let procs = tokio::time::timeout(SCAN_BUDGET, scan).await.ok()?.ok()?; | ||
| Some(match_port_holders(procs, &port_path, &canonical)) | ||
| } | ||
|
|
||
| /// Processes currently holding `port` open (Linux `/proc`; empty elsewhere). | ||
| pub async fn find_port_holders(port: &str) -> Vec<PortHolder> { | ||
| find_port_holders_in(&NormalizedPath::new("/proc"), port) | ||
| .await | ||
| .unwrap_or_default() | ||
| } | ||
|
|
||
| /// Human-readable contention hint, e.g. `port held by fbuild-daemon (pid 42)`. | ||
| /// `None` when no holder is visible. | ||
| pub async fn describe_port_holders(port: &str) -> Option<String> { | ||
| let holders = find_port_holders(port).await; | ||
| if holders.is_empty() { | ||
| return None; | ||
| } | ||
| let list = holders | ||
| .iter() | ||
| .map(|h| format!("{} (pid {})", h.name, h.pid)) | ||
| .collect::<Vec<_>>() | ||
| .join(", "); | ||
| Some(format!("port held by {list}")) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn matches_only_processes_with_an_fd_on_the_port() { | ||
| let procs = vec![ | ||
| ( | ||
| 10, | ||
| "other".to_string(), | ||
| vec![NormalizedPath::new("/dev/null")], | ||
| ), | ||
| ( | ||
| 42, | ||
| "fbuild-daemon".to_string(), | ||
| vec![NormalizedPath::new("/dev/ttyFAKE")], | ||
| ), | ||
| ]; | ||
| assert_eq!( | ||
| match_port_holders( | ||
| procs, | ||
| &NormalizedPath::new("/dev/ttyFAKE"), | ||
| &NormalizedPath::new("/dev/ttyFAKE") | ||
| ), | ||
| vec![PortHolder { | ||
| pid: 42, | ||
| name: "fbuild-daemon".to_string() | ||
| }] | ||
| ); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn missing_proc_root_yields_no_holders() { | ||
| let dir = tempfile::TempDir::new().unwrap(); | ||
| let missing = NormalizedPath::new(dir.path().join("nope")); | ||
| assert_eq!( | ||
| find_port_holders_in(&missing, "/dev/ttyX").await, | ||
| Some(Vec::new()) | ||
| ); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.