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

feat: spec a config file #8

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ nix = "0.21.0"
log = { version = "0.4.14", features = ["std"] }
lazy_static = "1.4.0"
chrono = "0.4"
anyhow = "1.0"
oci-spec = { git = "https://github.com/containers/oci-spec-rs", rev = "d6fb1e91742313cd0d0085937e2d6df5d4669720" }

[dev-dependencies]
serial_test = "0.5.1"
8 changes: 4 additions & 4 deletions src/core/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use super::{
/// # Returns
///
/// Pid of the running container process inside the root PID namespace
///
///
pub fn fork_container(
spec: &Spec,
state: &State,
Expand Down Expand Up @@ -208,12 +208,12 @@ pub fn fork_container(
match ipc_channel.recv() {
Ok(msg) => {
if !msg.eq("start") {
println!("[ERROR]: {}", msg);
println!("[ERROR]: {} on ipc channel msg", msg);
exit(1);
}
}
Err(err) => {
println!("[ERROR]: {}", err);
println!("[ERROR]: {} on ipc channel error", err);
exit(1);
}
}
Expand All @@ -228,7 +228,7 @@ pub fn fork_container(
Ok(_) => (),
Err(err) => {
// We can't log this error because it doesn't see the log file
println!("[ERROR]: {}", err.to_string());
println!("[ERROR]: {} execvp", err);
exit(1);
}
}
Expand Down
117 changes: 117 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,104 @@ use oci::{
spec::Spec,
};

use anyhow::Result;
use nix;
use oci_spec::runtime::Mount;
use oci_spec::runtime::{
LinuxBuilder, LinuxIdMappingBuilder, LinuxNamespace, LinuxNamespaceBuilder, LinuxNamespaceType,
Spec as SpecConfigOci,
};
use serde_json::to_writer_pretty;
use std::fs::File;
use std::path::PathBuf;

const PURA_ROOT_PATH: &str = "/tmp/pura";

pub struct SpecConfig {
rootless: bool
}

pub fn get_default() -> Result<SpecConfigOci> {
Ok(SpecConfigOci::default())
}

pub fn get_rootless() -> Result<SpecConfigOci> {
// Remove network and user namespace from the default spec
let mut namespaces: Vec<LinuxNamespace> = oci_spec::runtime::get_default_namespaces()
.into_iter()
.filter(|ns| {
ns.typ() != LinuxNamespaceType::Network && ns.typ() != LinuxNamespaceType::User
})
.collect();

// Add user namespace
namespaces.push(
LinuxNamespaceBuilder::default()
.typ(LinuxNamespaceType::User)
.build()?,
);

let uid = nix::unistd::geteuid().as_raw();
let gid = nix::unistd::getegid().as_raw();

let linux = LinuxBuilder::default()
.namespaces(namespaces)
.uid_mappings(vec![LinuxIdMappingBuilder::default()
.host_id(uid)
.container_id(0_u32)
.size(1_u32)
.build()?])
.gid_mappings(vec![LinuxIdMappingBuilder::default()
.host_id(gid)
.container_id(0_u32)
.size(1_u32)
.build()?])
.build()?;

// Prepare the mounts

let mut mounts: Vec<Mount> = oci_spec::runtime::get_default_mounts();
for mount in &mut mounts {
if mount.destination().eq(Path::new("/sys")) {
mount
.set_source(Some(PathBuf::from("/sys")))
.set_typ(Some(String::from("none")))
.set_options(Some(vec![
"rbind".to_string(),
"nosuid".to_string(),
"noexec".to_string(),
"nodev".to_string(),
"ro".to_string(),
]));
} else {
let options: Vec<String> = mount
.options()
.as_ref()
.unwrap_or(&vec![])
.iter()
.filter(|&o| !o.starts_with("gid=") && !o.starts_with("uid="))
.map(|o| o.to_string())
.collect();
mount.set_options(Some(options));
}
}

let mut spec = get_default()?;
spec.set_linux(Some(linux)).set_mounts(Some(mounts));
Ok(spec)
}

pub fn spec(spec: SpecConfig) -> Result<()> {
let spec = if spec.rootless {
get_rootless()?
} else {
get_default()?
};

to_writer_pretty(&File::create("config.json")?, &spec)?;
Ok(())
}

pub fn create(create: Create) {
let container_id = create.id;
let root = create.root;
Expand Down Expand Up @@ -332,6 +428,16 @@ pub fn main() {
.help("log format (e.q. json, txt)"),
)
// Subcommands
.subcommand(
SubCommand::with_name("spec")
.arg(
Arg::with_name("rootless")
.long("rootless")
.required(false)
.takes_value(false)
.help("spec container as rootless mode")
),
)
.subcommand(
SubCommand::with_name("create")
.arg(
Expand Down Expand Up @@ -411,6 +517,17 @@ pub fn main() {
let _ = ContainerLogger::init(&log_path.unwrap(), Level::Info).unwrap();

match matches.subcommand() {
("spec", _spec_cmd) => {
// spec(SpecConfig {
// rootless: matches.is_present("rootless")
// }).map_err(|err| println!("{:?}", err));
match spec(SpecConfig {
rootless: matches.is_present("rootless")
}) {
Err(e) => println!("{:?}", e),
_ => ()
}
}
("create", create_cmd) => {
let args = create_cmd.unwrap();
create(Create {
Expand Down