-
Notifications
You must be signed in to change notification settings - Fork 119
Use an RAII wrapper for stdio redirection #260
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
2 commits
Select commit
Hold shift + click to select a range
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,66 @@ | ||
| use std::fs::{File, OpenOptions}; | ||
| use std::io::ErrorKind::NotFound; | ||
| use std::io::{Error, Result}; | ||
| use std::path::Path; | ||
| use std::sync::{Arc, Mutex}; | ||
|
|
||
| use crate::sys::stdio::*; | ||
|
|
||
| #[derive(Default, Clone)] | ||
| pub struct Stdio { | ||
| pub stdin: Stdin, | ||
| pub stdout: Stdout, | ||
| pub stderr: Stderr, | ||
| } | ||
|
|
||
| impl Stdio { | ||
| pub fn redirect(&self) -> Result<()> { | ||
| self.stdin.redirect()?; | ||
| self.stdout.redirect()?; | ||
| self.stderr.redirect()?; | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| macro_rules! stdio_impl { | ||
| ( $stdio_type:ident, $fd:expr ) => { | ||
| #[derive(Default, Clone)] | ||
| pub struct $stdio_type(Arc<Mutex<Option<File>>>); | ||
|
|
||
| impl<P: AsRef<Path>> TryFrom<Option<P>> for $stdio_type { | ||
| type Error = std::io::Error; | ||
| fn try_from(path: Option<P>) -> Result<Self> { | ||
| path.and_then(|path| match path.as_ref() { | ||
| path if path.as_os_str().is_empty() => None, | ||
| path => Some(path.to_owned()), | ||
| }) | ||
| .map( | ||
| |path| match OpenOptions::new().read(true).write(true).open(path) { | ||
| Err(err) if err.kind() == NotFound => Ok(None), | ||
| Ok(f) => Ok(Some(f)), | ||
| Err(err) => Err(err), | ||
| }, | ||
| ) | ||
| .transpose() | ||
| .map(|opt| Self(Arc::new(Mutex::new(opt.flatten())))) | ||
| } | ||
| } | ||
|
|
||
| impl $stdio_type { | ||
| pub fn redirect(&self) -> Result<()> { | ||
| if let Some(f) = self.0.try_lock().ok().and_then(|mut f| f.take()) { | ||
| let f = try_into_fd(f)?; | ||
| let _ = unsafe { libc::dup($fd) }; | ||
| if unsafe { libc::dup2(f.as_raw_fd(), $fd) } == -1 { | ||
| return Err(Error::last_os_error()); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| stdio_impl!(Stdin, STDIN_FILENO); | ||
| stdio_impl!(Stdout, STDOUT_FILENO); | ||
| stdio_impl!(Stderr, STDERR_FILENO); | ||
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,3 @@ | ||
| pub mod metrics; | ||
| pub mod networking; | ||
| pub mod stdio; |
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,44 @@ | ||
| use std::fs::File; | ||
| use std::os::unix::io::AsRawFd; | ||
|
|
||
| use anyhow::Result; | ||
| use containerd_shim::error::Error as ShimError; | ||
| use containerd_shim::{self as shim}; | ||
| use nix::sched::{setns, unshare, CloneFlags}; | ||
| use oci_spec::runtime; | ||
|
|
||
| pub fn setup_namespaces(spec: &runtime::Spec) -> Result<()> { | ||
| let namespaces = spec | ||
| .linux() | ||
| .as_ref() | ||
| .unwrap() | ||
| .namespaces() | ||
| .as_ref() | ||
| .unwrap(); | ||
| for ns in namespaces { | ||
| if ns.typ() == runtime::LinuxNamespaceType::Network { | ||
| if let Some(p) = ns.path() { | ||
| let f = File::open(p).map_err(|err| { | ||
| ShimError::Other(format!( | ||
| "could not open network namespace {}: {}", | ||
| p.display(), | ||
| err | ||
| )) | ||
| })?; | ||
| setns(f.as_raw_fd(), CloneFlags::CLONE_NEWNET).map_err(|err| { | ||
| ShimError::Other(format!("could not set network namespace: {0}", err)) | ||
| })?; | ||
| } else { | ||
| unshare(CloneFlags::CLONE_NEWNET).map_err(|err| { | ||
| ShimError::Other(format!("could not unshare network namespace: {0}", err)) | ||
| })?; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Keep all mounts changes (such as for the rootfs) private to the shim | ||
| // This way mounts will automatically be cleaned up when the shim exits. | ||
| unshare(CloneFlags::CLONE_NEWNS) | ||
| .map_err(|err| shim::Error::Other(format!("failed to unshare mount namespace: {}", err)))?; | ||
| Ok(()) | ||
| } |
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,9 @@ | ||
| use std::io::Result; | ||
| pub use std::os::fd::AsRawFd as StdioAsRawFd; | ||
| use std::os::fd::OwnedFd; | ||
|
|
||
| pub use libc::{STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO}; | ||
|
|
||
| pub fn try_into_fd(f: impl Into<OwnedFd>) -> Result<impl StdioAsRawFd> { | ||
| Ok(f.into()) | ||
| } |
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,3 @@ | ||
| pub mod metrics; | ||
| pub mod networking; | ||
| pub mod stdio; |
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,4 @@ | ||
| pub fn setup_namespaces(spec: &oci_spec::runtime::Spec) -> anyhow::Result<()> { | ||
| // noop for now | ||
| Ok(()) | ||
| } |
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,39 @@ | ||
| use std::io::ErrorKind::Other; | ||
| use std::io::{Error, Result}; | ||
| use std::os::windows::prelude::{AsRawHandle, IntoRawHandle, OwnedHandle}; | ||
|
|
||
| use libc::{c_int, close, intptr_t, open_osfhandle, O_APPEND}; | ||
|
|
||
| type StdioRawFd = libc::c_int; | ||
|
|
||
| pub static STDIN_FILENO: StdioRawFd = 0; | ||
| pub static STDOUT_FILENO: StdioRawFd = 1; | ||
| pub static STDERR_FILENO: StdioRawFd = 2; | ||
|
|
||
| struct StdioOwnedFd(c_int); | ||
|
|
||
| pub fn try_into_fd(f: impl Into<OwnedHandle>) -> Result<impl StdioAsRawFd> { | ||
| let handle = f.into(); | ||
| let fd = unsafe { open_osfhandle(handle.as_raw_handle() as intptr_t, O_APPEND) }; | ||
| if fd == -1 { | ||
| return Err(Error::new(Other, "Failed to open file descriptor")); | ||
| } | ||
| let _ = handle.into_raw_handle(); // drop ownership of the handle, it's managed by fd now | ||
| Ok(StdioOwnedFd(fd)) | ||
| } | ||
|
|
||
| pub trait StdioAsRawFd { | ||
| fn as_raw_fd(&self) -> c_int; | ||
| } | ||
|
|
||
| impl StdioAsRawFd for StdioOwnedFd { | ||
| fn as_raw_fd(&self) -> c_int { | ||
| self.0 | ||
| } | ||
| } | ||
|
|
||
| impl Drop for StdioOwnedFd { | ||
| fn drop(&mut self) { | ||
| unsafe { close(self.0) }; | ||
| } | ||
| } |
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.