Skip to content

Commit

Permalink
Merge branch 'main' into feature/v1-blkio
Browse files Browse the repository at this point in the history
  • Loading branch information
utam0k authored Aug 24, 2021
2 parents 6724d5c + 3572f7e commit d69c498
Show file tree
Hide file tree
Showing 13 changed files with 508 additions and 741 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ youki is not at the practical stage yet. However, it is getting closer to practi
| Seccomp | Filtering system calls | WIP on [#25](https://github.com/containers/youki/issues/25) |
| Hooks | Add custom processing during container creation ||
| Rootless | Running a container without root privileges | It works, but cgroups isn't supported. WIP on [#77](https://github.com/containers/youki/issues/77) |
| OCI Compliance | Compliance with OCI Runtime Spec | 37 out of 55 test cases passing |
| OCI Compliance | Compliance with OCI Runtime Spec | 39 out of 5 test cases passing |

# Getting Started

Expand Down
2 changes: 1 addition & 1 deletion Vagrantfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Vagrant.configure("2") do |config|

config.vm.provision "shell", inline: <<-SHELL
set -e -u -o pipefail
yum install -y git gcc docker
yum install -y git gcc docker systemd-devel dbus-devel
grubby --update-kernel=ALL --args="systemd.unified_cgroup_hierarchy=0"
service docker start
SHELL
Expand Down
38 changes: 23 additions & 15 deletions docs/doc-draft.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,26 @@ This is diagram as given in #14, which is not actually how this works, but helpf
sequenceDiagram
participant U as User
participant D as Docker
participant YP as Youki(Parent Process)
participant YI as Youki(Init Process)
participant Y_Main as Youki(Main Process)
participant Y_Intermediate as Youki(Intermeidate Process)
participant Y_init as Youki(Init Process)
U ->> D : $ docker run --rm -it --runtime youki $image
D ->> YP : youki create $container_id
YP ->> YI : clone(2) to create new process and new namespaces
YI ->> YP : set user id mapping if entering into usernamespaces
YI ->> YI : configure resource limits, mount the devices, and etc.
YI -->> YP : ready message (Unix domain socket)
YP ->> : set cgroup configuration for YI
YP ->> D : exit $code
D ->> YP : $ youki start $container_id
YP -->> YI : start message (Unix domain socket)
YI ->> YI : run the commands in dockerfile
D ->> Y_Main : youki create $container_id
Y_Main ->> Y_Intermediate : fork(2) to create new intermediate process, entering into user and pid namespaces.
Y_Intermediate ->> Y_Main : set user id mapping if entering into usernamespaces
Y_Intermediate ->> Y_Init: fork(2) to create the container init process.
Y_Init ->> Y_Init : configure resource limits, mount the devices, entering into rest of namespaces, and etc.
Y_Init ->> Y_Intermediate : ready message (Unix domain socket)
Y_Intermediate ->> Y_Main : ready message (Unix domain socket)
Y_Main ->> Y_Main: set cgroup configuration for Y_Init
Y_Main ->> D : exit $code
D ->> Y_Main : $ youki start $container_id
Y_Main -->> Y_Init : start message through notify listener (Unix domain socket)
Y_Init ->> Y_Init : run the commands in dockerfile, using `execv`
D ->> D : monitor pid written in pid file
D ->> U : exit $code
```

---
Expand All @@ -59,7 +61,7 @@ One thing to note is that in the end, container is just another process in Linux

When given create command, Youki will load the specification, configuration, sockets etc., use clone syscall to create the container process (init process),applies the limits, namespaces, and etc. to the cloned container process. The container process will wait on a unix domain socket before exec into the command/program.

The main youki process will setup pipes used to communicate and syncronize with the init process. The init process will notify the youki process that it is ready and start to wait on a unix domain socket. The youki process will then write the container state and exit.
The main youki process will setup pipes used to communicate and syncronize with the intermediate and init process. The init process will notify the intermediate process, and then intermediate process to the main youki process that it is ready and start to wait on a unix domain socket. The youki process will then write the container state and exit.

- [mio Token definition](https://docs.rs/mio/0.7.11/mio/struct.Token.html)
- [oom-score-adj](https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9)
Expand All @@ -69,9 +71,15 @@ The main youki process will setup pipes used to communicate and syncronize with

### Process

This handles creation of the container process. The main youki process creates the container process (init process) using clone syscall. The main youki process will set up pipes used as message passing and synchronization mechanism with the init process. Youki uses clone instead of fork to create the container process. Using clone, Youki can directly pass the namespace creation flag to the syscall. Otherwise, if using fork, Youki would need to fork two processes, the first to enter into usernamespace, and a second time to enter into pid namespace correctly.
This handles creation of the container process. The main youki process creates the intermediate process and the intermediate process creates the container process (init process). The hierarchy is: `main youki process -> intermediate process -> init process`

The main youki process will set up pipes used as message passing and synchronization mechanism with the init process. Youki needs to create/fork two process instead of one is because nuances for the user and pid namespaces. In rootless container, we need to first enter user namespace, since all other namespaces requires CAP_SYSADMIN. When unshare or set_ns into pid namespace, only the children of the current process will enter into a different pid namespace. As a result, we must first fork a process to enter into user namespace, call unshare or set_ns for pid namespace, then fork again to enter into the correct pid namespace.

Note: clone(2) offers us the ability to enter into user and pid namespace by creatng only one process. However, clone(2) can only create new pid namespace, but cannot enter into existing pid namespaces. Therefore, to enter into existing pid namespaces, we would need to fork twice. Currently, there is no getting around this limitation.

- [fork(2) man page](https://man7.org/linux/man-pages/man2/fork.2.html)
- [clone(2) man page](https://man7.org/linux/man-pages/man2/clone.2.html)
- [pid namespace man page](https://man7.org/linux/man-pages/man7/pid_namespaces.7.html)

### Container

Expand Down
12 changes: 8 additions & 4 deletions integration_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ test_cases=(
# "linux_ns_path/linux_ns_path.t"
# "linux_ns_path_type/linux_ns_path_type.t"
# "linux_process_apparmor_profile/linux_process_apparmor_profile.t"
# "linux_readonly_paths/linux_readonly_paths.t"
"linux_readonly_paths/linux_readonly_paths.t"
# "linux_rootfs_propagation/linux_rootfs_propagation.t"
# "linux_seccomp/linux_seccomp.t"
"linux_sysctl/linux_sysctl.t"
Expand All @@ -57,7 +57,7 @@ test_cases=(
"poststop_fail/poststop_fail.t"
"prestart/prestart.t"
"prestart_fail/prestart_fail.t"
# "process/process.t"
"process/process.t"
"process_capabilities/process_capabilities.t"
"process_capabilities_fail/process_capabilities_fail.t"
# "process_oom_score_adj/process_oom_score_adj.t"
Expand All @@ -81,7 +81,7 @@ check_enviroment() {

for case in "${test_cases[@]}"; do
if [[ ! -e "${ROOT}/integration_test/src/github.com/opencontainers/runtime-tools/validation/$case" ]]; then
GOPATH=${ROOT}/integration_test make runtimetest validation-executables
GO111MODULE=auto GOPATH=${ROOT}/integration_test make runtimetest validation-executables
break
fi
done
Expand All @@ -94,7 +94,11 @@ for case in "${test_cases[@]}"; do
fi

echo "Running $case"
if [ 0 -ne $(sudo RUST_BACKTRACE=1 YOUKI_LOG_LEVEL=debug RUNTIME=${RUNTIME} ${ROOT}/integration_test/src/github.com/opencontainers/runtime-tools/validation/$case | grep "not ok" | wc -l) ]; then
logfile="./log/$case.log"
mkdir -p "$(dirname $logfile)"
sudo RUST_BACKTRACE=1 RUNTIME=${RUNTIME} ${ROOT}/integration_test/src/github.com/opencontainers/runtime-tools/validation/$case >$logfile 2>&1
if [ 0 -ne $(grep "not ok" $logfile | wc -l ) ]; then
cat $logfile
exit 1
fi
sleep 1
Expand Down
110 changes: 76 additions & 34 deletions src/container/builder_impl.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
use anyhow::{Context, Result};
use nix::sched::CloneFlags;

use cgroups;

use oci_spec::Spec;
use std::{fs, os::unix::prelude::RawFd, path::PathBuf};

use crate::{
hooks,
namespaces::Namespaces,
process::{child, fork, init, parent},
process::{channel, fork, init},
rootless::Rootless,
syscall::linux::LinuxSyscall,
utils,
};
use anyhow::{Context, Result};
use cgroups;
use nix::unistd::Pid;
use oci_spec::Spec;
use std::path::Path;
use std::process::Command;
use std::{fs, os::unix::prelude::RawFd, path::PathBuf};

use super::{Container, ContainerStatus};

Expand Down Expand Up @@ -59,16 +57,16 @@ impl<'a> ContainerBuilderImpl<'a> {
let cgroups_path = utils::get_cgroup_path(&linux.cgroups_path, &self.container_id);
let cmanager = cgroups::common::create_cgroup_manager(&cgroups_path, self.use_systemd)?;

// create the parent and child process structure so the parent and child process can sync with each other
let (mut parent, parent_channel) = parent::ParentProcess::new(&self.rootless)?;
let child = child::ChildProcess::new(parent_channel)?;

if self.init {
if let Some(hooks) = self.spec.hooks.as_ref() {
hooks::run_hooks(hooks.create_runtime.as_ref(), self.container.as_ref())?
}
}

// We use a set of channels to communicate between parent and child process. Each channel is uni-directional.
let parent_to_child = &mut channel::Channel::new()?;
let child_to_parent = &mut channel::Channel::new()?;

// This init_args will be passed to the container init process,
// therefore we will have to move all the variable by value. Since self
// is a shared reference, we have to clone these variables here.
Expand All @@ -82,30 +80,25 @@ impl<'a> ContainerBuilderImpl<'a> {
notify_path: self.notify_path.clone(),
preserve_fds: self.preserve_fds,
container: self.container.clone(),
child,
};
let intermediate_pid = fork::container_fork(|| {
init::container_intermidiate(init_args, parent_to_child, child_to_parent)
})?;
// If creating a rootless container, the intermediate process will ask
// the main process to set up uid and gid mapping, once the intermediate
// process enters into a new user namespace.
if self.rootless.is_some() {
child_to_parent.wait_for_mapping_request()?;
log::debug!("write mapping for pid {:?}", intermediate_pid);
utils::write_file(format!("/proc/{}/setgroups", intermediate_pid), "deny")?;
write_uid_mapping(intermediate_pid, self.rootless.as_ref())?;
write_gid_mapping(intermediate_pid, self.rootless.as_ref())?;
parent_to_child.send_mapping_written()?;
}

// We have to box up this closure to correctly pass to the init function
// of the new process.
let cb = Box::new(move || {
if let Err(error) = init::container_init(init_args) {
log::debug!("failed to run container_init: {:?}", error);
return -1;
}

0
});

let clone_flags = linux
.namespaces
.as_ref()
.map(|ns| Namespaces::from(ns).clone_flags)
.unwrap_or_else(CloneFlags::empty);
let init_pid = fork::clone(cb, clone_flags)?;
let init_pid = child_to_parent.wait_for_child_ready()?;
log::debug!("init pid is {:?}", init_pid);

parent.wait_for_child_ready(init_pid)?;

cmanager.add_task(init_pid)?;
if self.rootless.is_none() && linux.resources.is_some() && self.init {
cmanager.apply(linux.resources.as_ref().unwrap())?;
Expand All @@ -128,3 +121,52 @@ impl<'a> ContainerBuilderImpl<'a> {
Ok(())
}
}

fn write_uid_mapping(target_pid: Pid, rootless: Option<&Rootless>) -> Result<()> {
if let Some(rootless) = rootless {
if let Some(uid_mappings) = rootless.gid_mappings {
return write_id_mapping(
&format!("/proc/{}/uid_map", target_pid),
uid_mappings,
rootless.newuidmap.as_deref(),
);
}
}

Ok(())
}

fn write_gid_mapping(target_pid: Pid, rootless: Option<&Rootless>) -> Result<()> {
if let Some(rootless) = rootless {
if let Some(gid_mappings) = rootless.gid_mappings {
return write_id_mapping(
&format!("/proc/{}/gid_map", target_pid),
gid_mappings,
rootless.newgidmap.as_deref(),
);
}
}

Ok(())
}

fn write_id_mapping(
map_file: &str,
mappings: &[oci_spec::LinuxIdMapping],
map_binary: Option<&Path>,
) -> Result<()> {
let mappings: Vec<String> = mappings
.iter()
.map(|m| format!("{} {} {}", m.container_id, m.host_id, m.size))
.collect();
if mappings.len() == 1 {
utils::write_file(map_file, mappings.first().unwrap())?;
} else {
Command::new(map_binary.unwrap())
.args(mappings)
.output()
.with_context(|| format!("failed to execute {:?}", map_binary))?;
}

Ok(())
}
Loading

0 comments on commit d69c498

Please sign in to comment.