Skip to content

Commit

Permalink
chores: better files layout (#7)
Browse files Browse the repository at this point in the history
* chores: moved dive to bin directory
* chores: merged image builder with root crate
  • Loading branch information
raphaelcoeffic authored Nov 10, 2024
1 parent 3e9c4a2 commit 8667041
Show file tree
Hide file tree
Showing 15 changed files with 671 additions and 272 deletions.
326 changes: 275 additions & 51 deletions Cargo.lock

Large diffs are not rendered by default.

37 changes: 12 additions & 25 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,27 @@ edition = "2021"
[features]
embedded_image = []

[workspace]
members = [
"image_builder",
]

[workspace.dependencies]
[dependencies]
anyhow = "1.0.89"
clap = { version = "4.5.20", features = ["derive", "env"] }
dirs = "5.0"
env_logger = "0.11.5"
exitcode = "1.1.2"
fd-lock = "4.0.2"
include_dir = "0.7.4"
indicatif = "0.17.8"
log = "0.4.22"
liblzma = { version = "0.3.4", features = ["static"] }
rustix = { version = "0.38.37", features = ["process", "thread", "mount", "fs"] }
tar = "0.4.42"
tempfile = "3.13.0"

[dependencies]
anyhow = { workspace = true }
clap = { workspace = true }
dirs = "5.0"
env_logger = { workspace = true }
exitcode = "1.1.2"
image_builder = { path = "image_builder" }
indicatif = { workspace = true }
log = { workspace = true }
liblzma = { workspace = true }
log = "0.4.22"
procfs = { version= "0.17.0" }
rustix = { workspace = true }
regex = "1.11.1"
rustix = { version = "0.38.37", features = ["process", "thread", "mount", "fs", "runtime"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tar = { workspace = true }
tempfile = { workspace = true }
sha2 = "0.10.8"
tar = "0.4.42"
tempfile = "3.13.0"
ureq = { version = "2.10.1", default-features = false, features = ["tls", "native-certs", "gzip"] }
which = "6.0.3"
fd-lock = "4.0.2"

[[bin]]
name = "dive"
Expand Down
19 changes: 0 additions & 19 deletions image_builder/Cargo.toml

This file was deleted.

14 changes: 10 additions & 4 deletions src/base_image.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use std::{fs, io, path::Path};

use anyhow::{bail, Result};
use image_builder::progress_bar;
use liblzma::read::XzDecoder;
use tar::Archive;

use crate::image_builder::*;

#[cfg(feature = "embedded_image")]
use crate::embedded_image;

#[cfg(not(feature = "embedded_image"))]
use image_builder::BaseImageBuilder;
use crate::image_builder::BaseImageBuilder;

pub fn update_base_image<P>(dest: &Path, image: Option<P>) -> Result<()>
where
Expand Down Expand Up @@ -96,15 +97,20 @@ where
log::info!("removing current base image");
for dir in dest.read_dir()? {
let path = dir?.path();
if let Err(err) = image_builder::chmod(&path, |mode| mode | 0o700) {
if let Err(err) = chmod(&path, |mode| mode | 0o700) {
log::error!(
"could not fix permissions for {}: {}",
path.display(),
err
);
bail!(err);
}
if let Err(err) = fs::remove_dir_all(&path) {
if path.is_dir() {
if let Err(err) = fs::remove_dir_all(&path) {
log::error!("could not remove {}: {}", path.display(), err);
bail!(err);
}
} else if let Err(err) = fs::remove_file(&path) {
log::error!("could not remove {}: {}", path.display(), err);
bail!(err);
}
Expand Down
12 changes: 10 additions & 2 deletions src/bin/build-img.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ use std::{

use anyhow::{bail, Result};
use clap::Parser;

use image_builder::*;
use tempfile::TempDir;

use dive::image_builder::*;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
Expand All @@ -28,6 +28,10 @@ struct Args {
#[arg(short, long, env)]
uncompressed: bool,

/// Shell
#[arg(long)]
shell_exec: bool,

/// Output name
#[arg(short, long, env, default_value = "base")]
output: String,
Expand Down Expand Up @@ -104,6 +108,10 @@ fn main() -> Result<()> {
base_builder.flake_dir(flake_dir);
}

if args.shell_exec {
base_builder.shell_exec(true);
}

if let Some(arch) = args.arch {
if !is_native_arch(&arch) && !is_qemu_supported_arch(&arch) {
bail!(
Expand Down
110 changes: 21 additions & 89 deletions src/main.rs → src/bin/dive.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::{
ffi::OsString,
fs::read_link,
io,
os::unix::process::CommandExt,
Expand All @@ -15,28 +14,17 @@ use rustix::{
runtime::{fork, Fork},
};

mod base_image;
mod namespaces;
mod overlay;
mod pid_file;
mod pid_lookup;
mod shared_mount;

#[cfg(feature = "embedded_image")]
mod embedded_image;

use base_image::*;
use namespaces::*;
use overlay::*;
use pid_lookup::*;
use shared_mount::*;
use dive::base_image::*;
use dive::namespaces::*;
use dive::overlay::*;
use dive::pid_lookup::*;
use dive::shared_mount::*;
use dive::shell::*;

const APP_NAME: &str = "dive";
const IMG_DIR: &str = "base-img";
const OVL_DIR: &str = "overlay";

const DEFAULT_PATH: &str = "/usr/local/bin:/usr/bin:/bin";

const ENV_IMG_DIR: &str = "_IMG_DIR";
const ENV_OVL_DIR: &str = "_OVL_DIR";
const ENV_LEAD_PID: &str = "_LEAD_PID";
Expand Down Expand Up @@ -133,76 +121,6 @@ fn prepare_shell_environment(
Ok(())
}

fn exec_shell(container_id: &str) -> Result<()> {
//
// TODO: path HOME w/ user as defined by /etc/passwd
//
// TODO: find shell in this order:
// - zsh
// - bash
// - sh at last

let proc_env = match Process::new(1).and_then(|p| p.environ()) {
Err(err) => {
bail!("could not fetch the process environment: {err}");
}
Ok(env) => env,
};

let mut cmd = Command::new("zsh");
cmd.env_clear();
cmd.envs(&proc_env);

let proc_path = if let Some(path) = proc_env
.get(&OsString::from("PATH"))
.filter(|v| !v.is_empty())
{
path.to_string_lossy().into_owned()
} else {
DEFAULT_PATH.to_string()
};

// TODO: these variable except for TERM should be initialized in zshenv
let nix_bin_path = "/nix/.base/sbin:/nix/.base/bin:/nix/.bin";
cmd.env("PATH", format!("{nix_bin_path}:{proc_path}"));

if let Ok(term) = std::env::var("TERM") {
cmd.env("TERM", term);
} else {
cmd.env("TERM", "xterm");
}

if let Ok(lang) = std::env::var("LANG") {
cmd.env("LANG", lang);
} else {
cmd.env("LANG", "C.UTF-8");
}

let prompt = format!(
"%F{{cyan}}({container_id}) %F{{blue}}%~ %(?.%F{{green}}.%F{{red}})%#%f "
);
cmd.env("PROMPT", &prompt);

let nix_base = "/nix/.base";
let data_dir = format!("/usr/local/share:/usr/share:{nix_base}/share");
cmd.envs([
("ZDOTDIR", "/nix/etc"),
("NIX_CONF_DIR", "/nix/etc"),
("XDG_CACHE_HOME", "/nix/.cache"),
("XDG_CONFIG_HOME", "/nix/.config"),
("XDG_DATA_DIR", &data_dir),
]);

cmd.envs([
("TERMINFO_DIRS", format!("{nix_base}/share/terminfo")),
("LIBEXEC_PATH", format!("{nix_base}/libexec")),
("INFOPATH", format!("{nix_base}/share/info")),
]);

let err = cmd.exec();
bail!("cannot exec: {}", err)
}

fn wait_for_child(child_pid: rustix::thread::Pid) -> Result<()> {
// TODO: propagate return code properly
log::debug!("parent pid = {}", process::id());
Expand Down Expand Up @@ -246,8 +164,22 @@ fn main() -> Result<()> {
log::error!("{err}");
exit(1);
}

let proc_env = match Process::new(1).and_then(|p| p.environ()) {
Err(err) => {
log::error!(
"could not fetch the process environment: {err}"
);
exit(1);
}
Ok(env) => env,
};

let mut shell = Shell::new(&args.container_id);
shell.env(proc_env);

// in normal cases, there is no return from exec_shell()
if let Err(err) = exec_shell(&args.container_id) {
if let Err(err) = shell.exec() {
log::error!("cannot execute shell: {err}");
exit(1);
}
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
kitty.terminfo
less
lsof
man
nano
netcat-openbsd
procps
Expand Down
4 changes: 2 additions & 2 deletions src/embedded_image.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::path::Path;

use anyhow::Result;
use image_builder::progress_bar;
use liblzma::read::XzDecoder;

use crate::install_base_image_from_reader;
use crate::base_image::install_base_image_from_reader;
use crate::image_builder::progress_bar;

pub fn install_base_image<P>(dest: P) -> Result<()>
where
Expand Down
File renamed without changes.
Loading

0 comments on commit 8667041

Please sign in to comment.