Skip to content
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

traial implementation of async/await. #4

Merged
merged 1 commit into from
Apr 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ authors = ["utam0k <[email protected]>"]
edition = "2018"

[dependencies]
futures = "0.3"
clap = "3.0.0-beta.2"
nix = "0.19.1"
serde = { version = "1.0", features = ["derive"] }
Expand All @@ -17,4 +16,5 @@ anyhow = "1.0"
mio = { version = "0.7", features = ["os-ext", "os-poll"] }
chrono = "0.4"
once_cell = "1.6.0"
procfs = "0.9.1"
procfs = "0.9.1"
futures = { version = "0.3", features = ["thread-pool"] }
27 changes: 17 additions & 10 deletions src/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ impl Create {
let process = run_container(
self.pid_file.as_ref(),
&mut notify_socket,
&rootfs,
&spec,
rootfs,
spec,
csocketfd,
container,
)?;
Expand All @@ -88,8 +88,8 @@ impl Create {
fn run_container<P: AsRef<Path>>(
pid_file: Option<P>,
notify_socket: &mut NotifyListener,
rootfs: &PathBuf,
spec: &spec::Spec,
rootfs: PathBuf,
spec: spec::Spec,
csocketfd: Option<FileDescriptor>,
container: Container,
) -> Result<Process> {
Expand All @@ -116,6 +116,8 @@ fn run_container<P: AsRef<Path>>(
)? {
Process::Parent(parent) => Ok(Process::Parent(parent)),
Process::Child(child) => {
sched::unshare(cf & !sched::CloneFlags::CLONE_NEWUSER)?;

if let Some(csocketfd) = csocketfd {
tty::ready(csocketfd)?;
}
Expand All @@ -128,23 +130,28 @@ fn run_container<P: AsRef<Path>>(
}
}

sched::unshare(cf & !sched::CloneFlags::CLONE_NEWUSER)?;

match fork::fork_init(child)? {
Process::Child(child) => Ok(Process::Child(child)),
Process::Init(mut init) => {
let spec_args: &Vec<String> = &spec.process.args.clone();

let clone_spec = std::sync::Arc::new(spec);
let clone_rootfs = std::sync::Arc::new(rootfs.clone());

futures::executor::block_on(rootfs::prepare_rootfs(
spec,
rootfs,
clone_spec,
clone_rootfs,
cf.contains(sched::CloneFlags::CLONE_NEWUSER),
))?;
rootfs::pivot_rootfs(&*rootfs)?;

rootfs::pivot_rootfs(&rootfs)?;

init.ready()?;

notify_socket.wait_for_container_start()?;

utils::do_exec(&spec.process.args[0], &spec.process.args)?;
// utils::do_exec(&spec.process.args[0], &spec.process.args)?;
utils::do_exec(&spec_args[0], spec_args)?;
container.update_status(ContainerStatus::Stopped)?.save()?;

Ok(Process::Init(init))
Expand Down
3 changes: 1 addition & 2 deletions src/process/parent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ impl ParentProcess {

pub fn wait_for_child_ready(&mut self) -> Result<i32> {
let mut events = Events::with_capacity(128);
self.poll
.poll(&mut events, Some(Duration::from_millis(1000)))?;
self.poll.poll(&mut events, Some(Duration::from_secs(5)))?;
for event in events.iter() {
if let PARENT = event.token() {
let mut buf = [0; 1];
Expand Down
116 changes: 78 additions & 38 deletions src/rootfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ use std::fs::OpenOptions;
use std::fs::{canonicalize, create_dir_all, remove_file};
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{bail, Result};
use futures::future;
use futures::future::{self, try_join_all};
use futures::stream::{self, StreamExt};
use futures::task::SpawnExt;
use nix::errno::Errno;
use nix::fcntl::{open, OFlag};
use nix::mount::MsFlags;
use nix::mount::*;
use nix::mount::mount as nix_mount;
use nix::mount::{umount2, MntFlags, MsFlags};
use nix::sys::stat::{mknod, umask};
use nix::sys::stat::{Mode, SFlag};
use nix::unistd::{chdir, chown, close, fchdir, getcwd, pivot_root};
Expand Down Expand Up @@ -76,7 +79,11 @@ fn default_devices() -> Vec<LinuxDevice> {
]
}

pub async fn prepare_rootfs(spec: &Spec, rootfs: &PathBuf, bind_devices: bool) -> Result<()> {
pub async fn prepare_rootfs(
spec: Arc<Spec>,
rootfs: Arc<PathBuf>,
bind_devices: bool,
) -> Result<()> {
let mut flags = MsFlags::MS_REC;
match spec.linux {
Some(ref linux) => match linux.rootfs_propagation.as_ref() {
Expand All @@ -87,51 +94,78 @@ pub async fn prepare_rootfs(spec: &Spec, rootfs: &PathBuf, bind_devices: bool) -
},
None => flags |= MsFlags::MS_SLAVE,
};
let linux = spec.linux.as_ref().unwrap();
mount(None::<&str>, "/", None::<&str>, flags, None::<&str>)?;
nix_mount(None::<&str>, "/", None::<&str>, flags, None::<&str>)?;

log::debug!("mount root fs {:?}", rootfs);
mount(
Some(rootfs),
rootfs,
nix_mount(
Some(rootfs.as_ref()),
rootfs.as_ref(),
None::<&str>,
MsFlags::MS_BIND | MsFlags::MS_REC,
None::<&str>,
)?;

future::try_join_all(spec.mounts.iter().map(|m| { async move {
let (flags, data) = parse_mount(m);
let pool = futures::executor::ThreadPool::new()?;
let can_parall = spec.mounts.clone().into_iter().filter(|m| m.typ != "tmpfs");
let cannot_parall = spec.mounts.iter().filter(|m| m.typ == "tmpfs");

for m in cannot_parall {
let (flags, data) = parse_mount(&m);
let ml = &spec.linux.as_ref().unwrap().mount_label;
if m.typ == "cgroup" {
log::warn!("A feature of cgoup is unimplemented.");
Ok(())
// skip
log::warn!("A feature of cgoup is unimplemented.");
} else if m.destination == PathBuf::from("/dev") {
mount_from(
m,
rootfs,
flags & !MsFlags::MS_RDONLY,
&data,
&linux.mount_label,
)
mount_to_container(&m, rootfs.as_ref(), flags & !MsFlags::MS_RDONLY, &data, &ml)?;
} else {
mount_from(m, rootfs, flags, &data, &linux.mount_label)
mount_to_container(&m, rootfs.as_ref(), flags, &data, &ml)?;
}
}
})).await?;

try_join_all(
stream::iter(can_parall)
.map(|m| {
let spec = Arc::clone(&spec);
let rootfs = Arc::clone(&rootfs);
pool.spawn_with_handle(async move {
let (flags, data) = parse_mount(&m);
let ml = &spec.linux.as_ref().unwrap().mount_label;
if m.typ == "cgroup" {
// skip
log::warn!("A feature of cgoup is unimplemented.");
Ok(())
} else if m.destination == PathBuf::from("/dev") {
mount_to_container(
&m,
rootfs.as_ref(),
flags & !MsFlags::MS_RDONLY,
&data,
&ml,
)
} else {
mount_to_container(&m, rootfs.as_ref(), flags, &data, &ml)
}
})
.unwrap()
})
.collect::<Vec<_>>()
.await,
)
.await?;

let olddir = getcwd()?;
chdir(rootfs)?;
chdir(rootfs.as_ref())?;

setup_default_symlinks(rootfs)?;
create_devices(&linux.devices, bind_devices).await?;
setup_ptmx(rootfs)?;
setup_default_symlinks(&rootfs.as_ref())?;
create_devices(&spec.linux.as_ref().unwrap().devices, bind_devices).await?;
setup_ptmx(rootfs.as_ref())?;

chdir(&olddir)?;

Ok(())
}

fn setup_ptmx(rootfs: &PathBuf) -> Result<()> {
fn setup_ptmx(rootfs: &Path) -> Result<()> {
if let Err(e) = remove_file(rootfs.join("dev/ptmx")) {
if e.kind() != ::std::io::ErrorKind::NotFound {
bail!("could not delete /dev/ptmx")
Expand Down Expand Up @@ -188,7 +222,7 @@ async fn bind_dev(dev: &LinuxDevice) -> Result<()> {
Mode::from_bits_truncate(0o644),
)?;
close(fd)?;
mount(
nix_mount(
Some(&*dev.path),
&dev.path[1..],
None::<&str>,
Expand Down Expand Up @@ -227,17 +261,22 @@ fn to_sflag(t: LinuxDeviceType) -> Result<SFlag> {
})
}

fn mount_from(m: &Mount, rootfs: &PathBuf, flags: MsFlags, data: &str, label: &str) -> Result<()> {
let d;
if !label.is_empty() && m.typ != "proc" && m.typ != "sysfs" {
fn mount_to_container(
m: &Mount,
rootfs: &PathBuf,
flags: MsFlags,
data: &str,
label: &str,
) -> Result<()> {
let d = if !label.is_empty() && m.typ != "proc" && m.typ != "sysfs" {
if data.is_empty() {
d = format! {"context=\"{}\"", label};
format!("context=\"{}\"", label)
} else {
d = format! {"{},context=\"{}\"", data, label};
format!("{},context=\"{}\"", data, label)
}
} else {
d = data.to_string();
}
data.to_string()
};

let dest_for_host = format!(
"{}{}",
Expand Down Expand Up @@ -267,12 +306,13 @@ fn mount_from(m: &Mount, rootfs: &PathBuf, flags: MsFlags, data: &str, label: &s
PathBuf::from(&m.source)
};

if let Err(::nix::Error::Sys(errno)) = mount(Some(&*src), dest, Some(&*m.typ), flags, Some(&*d))
if let Err(::nix::Error::Sys(errno)) =
nix_mount(Some(&*src), dest, Some(&*m.typ), flags, Some(&*d))
{
if errno != Errno::EINVAL {
bail!("mount of {} failed", m.destination.display());
}
mount(Some(&*src), dest, Some(&*m.typ), flags, Some(data))?;
nix_mount(Some(&*src), dest, Some(&*m.typ), flags, Some(data))?;
}
if flags.contains(MsFlags::MS_BIND)
&& flags.intersects(
Expand All @@ -284,7 +324,7 @@ fn mount_from(m: &Mount, rootfs: &PathBuf, flags: MsFlags, data: &str, label: &s
| MsFlags::MS_SLAVE),
)
{
mount(
nix_mount(
Some(&*dest),
&*dest,
None::<&str>,
Expand Down
Loading