Skip to content

Commit

Permalink
refactor: moved determine_rootdir to containerd-shim-wasm
Browse files Browse the repository at this point in the history
Signed-off-by: jiaxiao zhou <[email protected]>
  • Loading branch information
Mossaka committed Aug 17, 2023
1 parent 6287dff commit c809ea3
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 128 deletions.
2 changes: 0 additions & 2 deletions Cargo.lock

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

87 changes: 83 additions & 4 deletions crates/containerd-shim-wasm/src/sandbox/instance_utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! Common utilities for the containerd shims.
use crate::sandbox::error::Error;
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::{
fs::{self, File, OpenOptions},
io::ErrorKind,
io::{ErrorKind, Read},
path::{Path, PathBuf},
};

Expand Down Expand Up @@ -45,6 +46,38 @@ pub fn maybe_open_stdio(path: &str) -> Result<Option<File>, Error> {
}
}

#[derive(Serialize, Deserialize)]
struct Options {
root: Option<PathBuf>,
}

pub fn determine_rootdir<P: AsRef<Path>>(
bundle: P,
namespace: &str,
container_root_dir: P,
) -> Result<PathBuf, Error> {
log::info!(
"determining rootdir for bundle: {}",
bundle.as_ref().display()
);
let mut file = match File::open(bundle.as_ref().join("options.json")) {
Ok(f) => f,
Err(err) => match err.kind() {
ErrorKind::NotFound => return Ok(container_root_dir.as_ref().join(namespace)),
_ => return Err(err.into()),
},
};
let mut data = String::new();
file.read_to_string(&mut data)?;
let options: Options = serde_json::from_str(&data)?;
let path = options
.root
.unwrap_or(container_root_dir.as_ref().to_path_buf())
.join(namespace);
log::info!("youki root path is: {}", path.display());
Ok(path)
}

fn construct_instance_root<P: AsRef<Path>>(root_path: P, container_id: &str) -> Result<PathBuf> {
let root_path = fs::canonicalize(&root_path).with_context(|| {
format!(
Expand All @@ -58,11 +91,13 @@ fn construct_instance_root<P: AsRef<Path>>(root_path: P, container_id: &str) ->

#[cfg(test)]
mod tests {
use std::fs::File;

use tempfile::tempdir;
use std::{
fs::{File, OpenOptions},
io::Write,
};

use super::*;
use tempfile::tempdir;

#[test]
fn test_maybe_open_stdio() -> Result<(), Error> {
Expand All @@ -79,4 +114,48 @@ mod tests {
assert!(f.is_some());
Ok(())
}

#[test]
fn test_determine_rootdir_with_options_file() -> Result<(), Error> {
let namespace = "test_namespace";
let dir = tempdir()?;
let rootdir = dir.path().join("runwasi");
let opts = Options {
root: Some(rootdir.clone()),
};
let opts_file = OpenOptions::new()
.read(true)
.create(true)
.truncate(true)
.write(true)
.open(dir.path().join("options.json"))?;
write!(&opts_file, "{}", serde_json::to_string(&opts)?)?;
let root = determine_rootdir(
dir.path(),
namespace.into(),
&PathBuf::from("/run/containerd/runtime"),
)?;
assert_eq!(root, rootdir.join(namespace));
Ok(())
}

#[test]
fn test_determine_rootdir_without_options_file() -> Result<(), Error> {
let dir = tempdir()?;
let namespace = "test_namespace";
let root = determine_rootdir(
dir.path(),
namespace.into(),
&PathBuf::from("/run/containerd/runtime"),
)?;
assert!(root.is_absolute());
assert_eq!(
root,
PathBuf::from("/run/containerd/runtime").join(namespace)
);
Ok(())
}
}

#[cfg(test)]
mod rootdirtest {}
1 change: 0 additions & 1 deletion crates/containerd-shim-wasmedge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ anyhow = { workspace = true }
cap-std = { workspace = true }
oci-spec = { workspace = true, features = ["runtime"] }
thiserror = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
nix = { workspace = true }
libc = { workspace = true }
Expand Down
93 changes: 15 additions & 78 deletions crates/containerd-shim-wasmedge/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,14 @@ use containerd_shim_wasm::libcontainer_instance::LibcontainerInstance;
use containerd_shim_wasm::libcontainer_instance::LinuxContainerExecutor;
use containerd_shim_wasm::sandbox::error::Error;
use containerd_shim_wasm::sandbox::instance::ExitCode;
use containerd_shim_wasm::sandbox::instance_utils::determine_rootdir;
use containerd_shim_wasm::sandbox::instance_utils::maybe_open_stdio;
use containerd_shim_wasm::sandbox::InstanceConfig;
use nix::unistd::close;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::prelude::*;
use std::io::ErrorKind;
use std::os::fd::IntoRawFd;
use std::sync::{Arc, Condvar, Mutex};

use std::{
fs,
path::{Path, PathBuf},
};
use std::{fs, path::PathBuf};

use libcontainer::container::builder::ContainerBuilder;
use libcontainer::container::Container;
Expand All @@ -40,30 +34,6 @@ pub struct Wasi {
rootdir: PathBuf,
}

#[derive(Serialize, Deserialize)]
struct Options {
root: Option<PathBuf>,
}

fn determine_rootdir<P: AsRef<Path>>(bundle: P, namespace: String) -> Result<PathBuf, Error> {
let mut file = match File::open(bundle.as_ref().join("options.json")) {
Ok(f) => f,
Err(err) => match err.kind() {
ErrorKind::NotFound => {
return Ok(<&str as Into<PathBuf>>::into(DEFAULT_CONTAINER_ROOT_DIR).join(namespace))
}
_ => return Err(err.into()),
},
};
let mut data = String::new();
file.read_to_string(&mut data)?;
let options: Options = serde_json::from_str(&data)?;
Ok(options
.root
.unwrap_or(PathBuf::from(DEFAULT_CONTAINER_ROOT_DIR))
.join(namespace))
}

impl LibcontainerInstance for Wasi {
type Engine = ();

Expand All @@ -73,7 +43,12 @@ impl LibcontainerInstance for Wasi {
let namespace = cfg.get_namespace();
Wasi {
id,
rootdir: determine_rootdir(bundle.as_str(), namespace).unwrap(),
rootdir: determine_rootdir(
bundle.as_str(),
namespace.as_str(),
DEFAULT_CONTAINER_ROOT_DIR,
)
.unwrap(),
exit_code: Arc::new((Mutex::new(None), Condvar::new())),
stdin: cfg.get_stdin().unwrap_or_default(),
stdout: cfg.get_stdout().unwrap_or_default(),
Expand Down Expand Up @@ -134,7 +109,9 @@ impl LibcontainerInstance for Wasi {
#[cfg(test)]
mod wasitest {
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::{create_dir, read_to_string, File, OpenOptions};
use std::io::Write;
use std::os::unix::io::RawFd;
use std::os::unix::prelude::OpenOptionsExt;
use std::sync::mpsc::channel;
Expand Down Expand Up @@ -215,16 +192,17 @@ mod wasitest {
create_dir(dir.path().join("rootfs"))?;
let rootdir = dir.path().join("runwasi");
create_dir(&rootdir)?;
let opts = Options {
root: Some(rootdir),
};
let rootdir = PathBuf::from("/path/to/root");
let mut opts = HashMap::new();
opts.insert("root", rootdir);
let serialized = serde_json::to_string(&opts)?;
let opts_file = OpenOptions::new()
.read(true)
.create(true)
.truncate(true)
.write(true)
.open(dir.path().join("options.json"))?;
write!(&opts_file, "{}", serde_json::to_string(&opts)?)?;
write!(&opts_file, "{}", serialized)?;

let wasm_path = dir.path().join("rootfs/hello.wasm");
let mut f = OpenOptions::new()
Expand Down Expand Up @@ -335,44 +313,3 @@ mod wasitest {
Ok(())
}
}

#[cfg(test)]
mod rootdirtest {
use std::fs::OpenOptions;

use super::*;
use tempfile::tempdir;

#[test]
fn test_determine_rootdir_with_options_file() -> Result<(), Error> {
let namespace = "test_namespace";
let dir = tempdir()?;
let rootdir = dir.path().join("runwasi");
let opts = Options {
root: Some(rootdir.clone()),
};
let opts_file = OpenOptions::new()
.read(true)
.create(true)
.truncate(true)
.write(true)
.open(dir.path().join("options.json"))?;
write!(&opts_file, "{}", serde_json::to_string(&opts)?)?;
let root = determine_rootdir(dir.path(), namespace.into())?;
assert_eq!(root, rootdir.join(namespace));
Ok(())
}

#[test]
fn test_determine_rootdir_without_options_file() -> Result<(), Error> {
let dir = tempdir()?;
let namespace = "test_namespace";
let root = determine_rootdir(dir.path(), namespace.into())?;
assert!(root.is_absolute());
assert_eq!(
root,
PathBuf::from(DEFAULT_CONTAINER_ROOT_DIR).join(namespace)
);
Ok(())
}
}
1 change: 0 additions & 1 deletion crates/containerd-shim-wasmtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ serde_json = { workspace = true }
nix = { workspace = true }
libcontainer = { workspace = true }
dbus = { version = "*", optional = true }
serde = { workspace = true }
libc = { workspace = true }

[dev-dependencies]
Expand Down
Loading

0 comments on commit c809ea3

Please sign in to comment.