Skip to content

Commit

Permalink
implemented LXD basics
Browse files Browse the repository at this point in the history
  • Loading branch information
htngr committed Mar 25, 2024
1 parent 0f3feda commit 0c3ed3c
Show file tree
Hide file tree
Showing 52 changed files with 1,629 additions and 1,314 deletions.
7 changes: 7 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"recommendations": [
"rust-lang.rust-analyzer",
"jnoortheen.nix-ide",
"mkhl.direnv"
]
}
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"editor.formatOnSave": true,
"files.autoSave": "onFocusChange",
}
1 change: 1 addition & 0 deletions codchi/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,4 @@ once_cell = "1.19.0"
url = "2.5.0"
git-url-parse = "0.4.4"
lazy-regex = "3.1.0"
log = "0.4"
63 changes: 46 additions & 17 deletions codchi/cli/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
use std::{fmt::Display, str::FromStr};
pub use self::module::*;

use clap::builder::*;
use clap::*;
use clap_verbosity_flag::{Verbosity, WarnLevel};
use clap_verbosity_flag::{InfoLevel, LogLevel, Verbosity};
use git_url_parse::GitUrl;
use lazy_regex::regex_captures;

// pub use self::ctrl::*;
pub use self::module::*;

// pub static CLI_ARGS: OnceCell<Cli> = OnceCell::new();

type DefaultLogLevel = WarnLevel;
use log::Level;
use once_cell::sync::Lazy;
use std::{fmt::Display, str::FromStr, sync::OnceLock};

#[allow(dead_code)]
pub static CLI_ARGS: OnceLock<Cli> = OnceLock::new();
#[allow(dead_code)]
pub static DEBUG: Lazy<bool> = Lazy::new(|| {
CLI_ARGS
.get()
.and_then(|cli| cli.verbose.log_level())
.or(<DefaultLogLevel as LogLevel>::default())
.unwrap()
> Level::Debug
});

type DefaultLogLevel = InfoLevel;

/// codchi
#[derive(Debug, Parser, Clone)]
Expand All @@ -21,7 +31,7 @@ type DefaultLogLevel = WarnLevel;
long_version = format!("v{}\n{}",
option_env!("CARGO_PKG_VERSION").unwrap_or(""),
option_env!("CODCHI_GIT_COMMIT").unwrap_or(""),
)
),
)]
pub struct Cli {
#[command(flatten)]
Expand All @@ -40,7 +50,6 @@ pub enum Cmd {
// #[command(subcommand)]
// #[clap(aliases = &["ctrl"])]
// Controller(ControllerCmd),

Status {},

/// Create a new code machine
Expand All @@ -53,6 +62,17 @@ pub enum Cmd {
options: AddModuleOptions,
},

/// Execute (interactive) command inside machine.
#[clap(aliases = &["run"])]
Exec {
/// Name of the code machine
name: String,

/// Command with arguments to run
#[arg(trailing_var_arg = true)]
cmd: Vec<String>,
},

/// Apply changes to a code machine
Rebuild {
/// Name of the code machine
Expand All @@ -65,6 +85,16 @@ pub enum Cmd {
name: String,
},

/// Delete code machine with all associated files
Delete {
/// Don't prompt for confirmation and delete immediately
#[arg(long)]
im_really_sure: bool,

/// Name of the code machine
name: String,
},

/// Manage modules of code machines
#[command(subcommand)]
#[clap(aliases = &["mod"])]
Expand Down Expand Up @@ -147,12 +177,11 @@ mod module {
/// Id of the module (You can list them with `codchi module ls NAME`)
id: usize,
},

/// Fetch module updates
Update {
/// Name of the code machine
name: String,
},
// /// Fetch module updates
// Update {
// /// Name of the code machine
// name: String,
// },
}

#[derive(clap::Args, Debug, Clone)]
Expand Down
62 changes: 6 additions & 56 deletions codchi/cli/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{
consts::{self, host, ToPath, NIX_SYSTEM}, platform, util::UtilExt
consts::{host, ToPath},
util::UtilExt,
};
use anyhow::{Context, Result};
use fs4::FileExt;
Expand Down Expand Up @@ -56,6 +57,8 @@ impl MutableConfig {
}

pub fn write(mut self) -> Result<()> {
self.get_machines().set_implicit(false);

let res = self.doc.to_string();
let bytes = res.as_bytes();
self.file.set_len(bytes.len() as u64)?;
Expand All @@ -68,11 +71,9 @@ impl MutableConfig {
if !self.doc.contains_table("machines") {
self.doc["machines"] = table();
}
let table = self.doc["machines"]
self.doc["machines"]
.as_table_mut()
.expect("Config toml doesn't contain key 'machines'");
table.set_implicit(true);
table
.expect("Config toml doesn't contain key 'machines'")
}

pub fn get_machine(&mut self, name: &str) -> Option<&mut toml_edit::Table> {
Expand Down Expand Up @@ -135,57 +136,6 @@ pub struct MachineConfig {
pub modules: Vec<CodchiModule>,
}

impl MachineConfig {
pub fn read_config(name: &str) -> Result<Option<Self>> {
Ok(Config::read()?.machines.get(name).cloned())
}

pub fn gen_flake(&self) -> String {
let codchi_url = consts::CODCHI_FLAKE_URL;
let module_inputs = self
.modules
.iter()
.enumerate()
.map(|(idx, url)| format!(r#" "{idx}".url = "{}";"#, url.to_nix_url()))
.join("\n");
let driver = platform::NIXOS_DRIVER_NAME;
let nixpkgs = if let Some(idx) = self.nixpkgs_from {
format!(r#"inputs."{idx}".inputs.nixpkgs"#)
} else {
"inputs.codchi.inputs.nixpkgs".to_string()
};
let modules = self
.modules
.iter()
.enumerate()
.map(|(idx, url)| {
format!(
r#" {{ module = inputs."{idx}".{module_name}; }}"#,
module_name = url.flake_attr.0
)
})
.join("\n");
format!(
r#"{{
inputs = {{
codchi.url = "{codchi_url}";
{module_inputs}
}};
outputs = inputs: {{
nixosConfigurations.default = inputs.codchi.lib.codeMachine {{
driver = "{driver}";
system = "{NIX_SYSTEM}";
nixpkgs = {nixpkgs};
modules = [
{modules}
];
}};
}};
}}"#
)
}
}

pub type CodchiModule = FlakeUrl<flake_attr::With>;

pub mod flake_attr {
Expand Down
11 changes: 11 additions & 0 deletions codchi/cli/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,14 @@ pub mod machine {
format!("codchi-{name}")
}
}

pub mod user {
pub const ROOT_UID: &str = "0";
pub const ROOT_GID: &str = "0";
pub const ROOT_HOME: &str = "/root";

pub const DEFAULT_NAME: &str = "codchi";
pub const DEFAULT_HOME: &str = "/home/codchi";
pub const DEFAULT_UID: &str = "1000";
pub const DEFAULT_GID: &str = "100";
}
54 changes: 42 additions & 12 deletions codchi/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
#![deny(unused_crate_dependencies)]

use crate::{
cli::{Cli, Cmd},
platform::{ConfigStatus, Driver, Machine, MachineDriver, PlatformStatus},
cli::{Cli, Cmd, CLI_ARGS},
platform::{ConfigStatus, Driver, Machine, PlatformStatus},
};
use base64::{prelude::BASE64_STANDARD, Engine};
use clap::*;
Expand All @@ -30,22 +30,26 @@ fn main() -> anyhow::Result<()> {

trace!("Started codchi with args: {:?}", cli);

// CLI_ARGS
// .set(cli.clone())
// .expect("Only main is allowed to set CLI_ARGS.");
CLI_ARGS
.set(cli.clone())
.expect("Only main is allowed to set CLI_ARGS.");

let _ = Driver::store();

match &cli.command.unwrap_or(Cmd::Status {}) {
Cmd::Status {} => print_status(Machine::list()?),
Cmd::Init { empty, options } => module::init(*empty, &options)?,
Cmd::Rebuild { name } => Machine::build(name)?,
Cmd::Update { name } => Machine::update(name)?,
Cmd::Init { empty, options } => alert_dirty(module::init(*empty, &options)?),
Cmd::Rebuild { name } => Machine::by_name(name)?.build()?,
Cmd::Update { name } => alert_dirty(Machine::by_name(name)?.update()?),
Cmd::Exec { name, cmd } => Machine::by_name(name)?.exec(cmd)?,
Cmd::Delete {
name,
im_really_sure,
} => Machine::by_name(name)?.delete(*im_really_sure)?,
Cmd::Module(cmd) => match cmd {
cli::ModuleCmd::List { name } => module::list(name)?,
cli::ModuleCmd::Add(opts) => module::add(opts)?,
cli::ModuleCmd::Delete { name, id } => module::delete(name, *id)?,
cli::ModuleCmd::Update { name: _ } => todo!(),
cli::ModuleCmd::Add(opts) => alert_dirty(module::add(opts)?),
cli::ModuleCmd::Delete { name, id } => alert_dirty(module::delete(name, *id)?),
},
}

Expand All @@ -54,6 +58,32 @@ fn main() -> anyhow::Result<()> {
Ok(())
}

fn alert_dirty(machine: Machine) {
match machine.config_status {
ConfigStatus::NotInstalled => {
info!(
"{} is not installed yet. Install with `codchi rebuild {}`",
machine.name, machine.name
);
}
ConfigStatus::Modified => {
info!(
"{} was modified. Apply changes with `codchi rebuild {}`",
machine.name, machine.name
);
}
ConfigStatus::UpdatesAvailable => {
info!(
"{} has been updated upstream. Update with `codchi rebuild {}`",
machine.name, machine.name
);
}
ConfigStatus::UpToDate => {
info!("Everything up to date!");
}
}
}

fn print_status(machines: Vec<Machine>) {
use comfy_table::*;
let mut table = Table::new();
Expand All @@ -67,7 +97,7 @@ fn print_status(machines: Vec<Machine>) {
table.add_row(vec![
Cell::new(&machine.name),
match machine.config_status {
ConfigStatus::NotInstalled => Cell::new("Never built").fg(Color::DarkYellow),
ConfigStatus::NotInstalled => Cell::new("Not installed yet").fg(Color::Red),
ConfigStatus::Modified => Cell::new("Modified").fg(Color::Yellow),
ConfigStatus::UpdatesAvailable => Cell::new("Updates available").fg(Color::Yellow),
ConfigStatus::UpToDate => Cell::new("Up to date").fg(Color::Green),
Expand Down
Loading

0 comments on commit 0c3ed3c

Please sign in to comment.