Skip to content

Commit

Permalink
update nix to 0.27.1 (#3)
Browse files Browse the repository at this point in the history
Signed-off-by: 闹钟大魔王 <1348651580@qq.com>
  • Loading branch information
anti-entropy123 authored Sep 26, 2023
1 parent 055f483 commit 033a34f
Show file tree
Hide file tree
Showing 22 changed files with 285 additions and 123 deletions.
26 changes: 19 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions crates/libcgroups/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,24 @@ keywords = ["youki", "container", "cgroups"]

[features]
default = ["v1", "v2", "systemd"]
v1 = []
v2 = []
systemd = ["v2", "dep:dbus"]
cgroupsv2_devices = ["rbpf", "libbpf-sys", "errno", "libc"]
v1 = ["nix/process", "nix/fs", "nix/signal"]
v2 = ["nix/process", "nix/fs", "nix/signal"]
systemd = ["v2", "dep:dbus", "nix/user"]
cgroupsv2_devices = ["rbpf", "libbpf-sys", "errno", "libc", "nix/dir"]

[dependencies]
nix = "0.26.2"
nix = { version = "0.27.1" }
procfs = "0.15.1"
oci-spec = { version = "~0.6.2", features = ["runtime"] }
dbus = { version = "0.9.7", optional = true }
fixedbitset = "0.4.2"
serde = { version = "1.0", features = ["derive"] }
rbpf = {version = "0.2.0", optional = true }
rbpf = { version = "0.2.0", optional = true }
libbpf-sys = { version = "1.2.1", optional = true }
errno = { version = "0.3.3", optional = true }
libc = { version = "0.2.148", optional = true }
thiserror = "1.0.48"
tracing = { version = "0.1.37", features = ["attributes"]}
tracing = { version = "0.1.37", features = ["attributes"] }

[dev-dependencies]
anyhow = "1.0"
Expand Down
15 changes: 14 additions & 1 deletion crates/libcontainer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,20 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "serd
fastrand = "^2.0.1"
futures = { version = "0.3", features = ["thread-pool"] }
libc = "0.2.148"
nix = "0.26.2"
nix = { version = "0.27.1", features = [
"fs",
"process",
"signal",
"socket",
"mount",
"sched",
"hostname",
"mman",
"resource",
"dir",
"term",
"user",
] }
oci-spec = { version = "~0.6.2", features = ["runtime"] }
once_cell = "1.18.0"
procfs = "0.15.1"
Expand Down
91 changes: 72 additions & 19 deletions crates/libcontainer/src/channel.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use nix::{
sys::socket::{self, UnixAddr},
unistd::{self},
};
use nix::sys::socket::{self, UnixAddr};
use serde::{Deserialize, Serialize};
use std::{
io::{IoSlice, IoSliceMut},
marker::PhantomData,
os::unix::prelude::RawFd,
os::{
fd::{AsRawFd, OwnedFd},
unix::prelude::RawFd,
},
sync::Arc,
};

#[derive(Debug, thiserror::Error)]
Expand All @@ -17,16 +18,18 @@ pub enum ChannelError {
Serde(#[from] serde_json::Error),
#[error("channel connection broken")]
BrokenChannel,
#[error("Unable to be closed")]
Unclosed,
}
#[derive(Clone)]
pub struct Receiver<T> {
receiver: RawFd,
receiver: Option<Arc<OwnedFd>>,
phantom: PhantomData<T>,
}

#[derive(Clone)]
pub struct Sender<T> {
sender: RawFd,
sender: Option<Arc<OwnedFd>>,
phantom: PhantomData<T>,
}

Expand All @@ -44,8 +47,14 @@ where
} else {
vec![]
};
socket::sendmsg::<UnixAddr>(self.sender, iov, &cmsgs, socket::MsgFlags::empty(), None)
.map_err(|e| e.into())
socket::sendmsg::<UnixAddr>(
self.sender.as_ref().unwrap().as_raw_fd(),
iov,
&cmsgs,
socket::MsgFlags::empty(),
None,
)
.map_err(|e| e.into())
}

fn send_slice_with_len(
Expand Down Expand Up @@ -81,8 +90,30 @@ where
Ok(())
}

pub fn close(&self) -> Result<(), ChannelError> {
Ok(unistd::close(self.sender)?)
pub fn close(&mut self) -> Result<(), ChannelError> {
// must ensure that the fd is closed immediately.
let count = Arc::strong_count(self.sender.as_ref().unwrap());
if count != 1 {
tracing::trace!(?count, "incorrect reference count value");
return Err(ChannelError::Unclosed)?;
};
self.sender = None;

Ok(())
}

/// Enforce a decrement of the inner reference counter by 1.
///
/// # Safety
/// The reason for `unsafe` is the caller must ensure that it's only called
/// when absolutely necessary. For instance, in the current implementation,
/// `clone()` can cause a leak of references residing on the stack in the
/// childprocess. This function allows for manual adjustment of the counter
/// to correct such situations.
pub unsafe fn decrement_count(&self) {
let rc = Arc::into_raw(Arc::clone(self.sender.as_ref().unwrap()));
Arc::decrement_strong_count(rc);
Arc::from_raw(rc);
}
}

Expand All @@ -98,8 +129,12 @@ where
std::mem::size_of::<u64>(),
)
})];
let _ =
socket::recvmsg::<UnixAddr>(self.receiver, &mut iov, None, socket::MsgFlags::MSG_PEEK)?;
let _ = socket::recvmsg::<UnixAddr>(
self.receiver.as_ref().unwrap().as_raw_fd(),
&mut iov,
None,
socket::MsgFlags::MSG_PEEK,
)?;
match len {
0 => Err(ChannelError::BrokenChannel),
_ => Ok(len),
Expand All @@ -115,7 +150,7 @@ where
{
let mut cmsgspace = nix::cmsg_space!(F);
let msg = socket::recvmsg::<UnixAddr>(
self.receiver,
self.receiver.as_ref().unwrap().as_raw_fd(),
iov,
Some(&mut cmsgspace),
socket::MsgFlags::MSG_CMSG_CLOEXEC,
Expand Down Expand Up @@ -187,8 +222,26 @@ where
Ok((serde_json::from_slice(&buf[..])?, fds))
}

pub fn close(&self) -> Result<(), ChannelError> {
Ok(unistd::close(self.receiver)?)
pub fn close(&mut self) -> Result<(), ChannelError> {
// must ensure that the fd is closed immediately.
let count = Arc::strong_count(self.receiver.as_ref().unwrap());
if count != 1 {
tracing::trace!(?count, "incorrect reference count value");
return Err(ChannelError::Unclosed)?;
};
self.receiver = None;

Ok(())
}

/// Enforce a decrement of the inner reference counter by 1.
///
/// # Safety
/// The reason for `unsafe` is same as `Sender::decrement_count()`.
pub unsafe fn decrement_count(&self) {
let rc = Arc::into_raw(Arc::clone(self.receiver.as_ref().unwrap()));
Arc::decrement_strong_count(rc);
Arc::from_raw(rc);
}
}

Expand All @@ -198,18 +251,18 @@ where
{
let (os_sender, os_receiver) = unix_channel()?;
let receiver = Receiver {
receiver: os_receiver,
receiver: Some(Arc::from(os_receiver)),
phantom: PhantomData,
};
let sender = Sender {
sender: os_sender,
sender: Some(Arc::from(os_sender)),
phantom: PhantomData,
};
Ok((sender, receiver))
}

// Use socketpair as the underlying pipe.
fn unix_channel() -> Result<(RawFd, RawFd), ChannelError> {
fn unix_channel() -> Result<(OwnedFd, OwnedFd), ChannelError> {
Ok(socket::socketpair(
socket::AddressFamily::Unix,
socket::SockType::SeqPacket,
Expand Down
6 changes: 3 additions & 3 deletions crates/libcontainer/src/container/builder_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{
use libcgroups::common::CgroupManager;
use nix::unistd::Pid;
use oci_spec::runtime::Spec;
use std::{fs, io::Write, os::unix::prelude::RawFd, path::PathBuf, rc::Rc};
use std::{fs, io::Write, os::fd::OwnedFd, path::PathBuf, rc::Rc};

pub(super) struct ContainerBuilderImpl {
/// Flag indicating if an init or a tenant container should be created
Expand All @@ -35,7 +35,7 @@ pub(super) struct ContainerBuilderImpl {
/// container process to the higher level runtime
pub pid_file: Option<PathBuf>,
/// Socket to communicate the file descriptor of the ptty
pub console_socket: Option<RawFd>,
pub console_socket: Option<OwnedFd>,
/// Options for new user namespace
pub user_ns_config: Option<UserNamespaceConfig>,
/// Path to the Unix Domain Socket to communicate container start
Expand Down Expand Up @@ -140,7 +140,7 @@ impl ContainerBuilderImpl {
syscall: self.syscall,
spec: Rc::clone(&self.spec),
rootfs: self.rootfs.to_owned(),
console_socket: self.console_socket,
console_socket: self.console_socket.take().map(Rc::from),
notify_listener,
preserve_fds: self.preserve_fds,
container: self.container.to_owned(),
Expand Down
6 changes: 1 addition & 5 deletions crates/libcontainer/src/container/init_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,7 @@ impl InitContainerBuilder {
// if socket file path is given in commandline options,
// get file descriptors of console socket
let csocketfd = if let Some(console_socket) = &self.base.console_socket {
Some(tty::setup_console_socket(
&container_dir,
console_socket,
"console-socket",
)?)
tty::setup_console_socket(&container_dir, console_socket, "console-socket")?
} else {
None
};
Expand Down
10 changes: 3 additions & 7 deletions crates/libcontainer/src/container/tenant_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ use oci_spec::runtime::{
};
use procfs::process::Namespace;

use std::os::fd::OwnedFd;
use std::rc::Rc;
use std::{
collections::HashMap,
convert::TryFrom,
ffi::{OsStr, OsString},
fs,
io::BufReader,
os::unix::prelude::RawFd,
path::{Path, PathBuf},
str::FromStr,
};
Expand Down Expand Up @@ -430,14 +430,10 @@ impl TenantContainerBuilder {
Ok(socket_path)
}

fn setup_tty_socket(&self, container_dir: &Path) -> Result<Option<RawFd>, LibcontainerError> {
fn setup_tty_socket(&self, container_dir: &Path) -> Result<Option<OwnedFd>, LibcontainerError> {
let tty_name = Self::generate_name(container_dir, TENANT_TTY);
let csocketfd = if let Some(console_socket) = &self.base.console_socket {
Some(tty::setup_console_socket(
container_dir,
console_socket,
&tty_name,
)?)
tty::setup_console_socket(container_dir, console_socket, &tty_name)?
} else {
None
};
Expand Down
Loading

0 comments on commit 033a34f

Please sign in to comment.