Skip to content

Commit

Permalink
Merge pull request #27 from tinythings/isbm-defaults
Browse files Browse the repository at this point in the history
Add defaults, close issue
  • Loading branch information
isbm authored Jun 28, 2024
2 parents 3f6fa8c + 1d0add3 commit d12c23b
Show file tree
Hide file tree
Showing 9 changed files with 129 additions and 100 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/target
alfad-compile
init
18 changes: 18 additions & 0 deletions core/src/action.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::def::{APLT_COMPILE, APLT_CTL, APLT_INIT, APLT_MAIN};
use clap::{Parser, ValueEnum};
use std::{
fmt::{Debug, Display},
Expand Down Expand Up @@ -123,8 +124,25 @@ impl Display for Action {
pub enum ActionError {
#[error("Could not parse command '{}'", .0)]
SyntaxError(String),

#[error("Unknown action '{}'", .0)]
ActionNotFound(String),

#[error("Task does not exist '{}'", .0)]
TaskNotFound(String),

#[error(
"Do not call this binary directly as {:?}! Name or link to an applet expected instead.
The following applets are available:
- {}
- {}
- {}
",
APLT_MAIN,
APLT_INIT,
APLT_CTL,
APLT_COMPILE
)]
MainAppletCalled,
}
41 changes: 20 additions & 21 deletions core/src/builtin/ctl.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
use super::IntoConfig;
use crate::{
builtin_fn,
def::{APLT_CTL, DIR_RUN},
task::{ContextMap, TaskContext, TaskState},
};
use crate::{config::yaml::TaskConfigYaml, task::ExitReason};
use anyhow::Result;
use nix::{sys::stat::Mode, unistd::mkfifo};
Expand All @@ -6,15 +12,12 @@ use smol::{
fs::{create_dir_all, File},
io::{AsyncBufReadExt, BufReader},
};
use std::{ops::ControlFlow, path::Path, time::Duration};
use tracing::{error, info};

use crate::{
builtin_fn,
task::{ContextMap, TaskContext, TaskState},
use std::{
ops::ControlFlow,
path::{Path, PathBuf},
time::Duration,
};

use super::IntoConfig;
use tracing::{error, info};

builtin_fn!(CreateCtlPipe: create_ctl);

Expand All @@ -30,8 +33,8 @@ impl IntoConfig for CreateCtlPipe {
}

async fn create_ctl(_: &TaskContext, _context: ContextMap<'static>) -> Result<()> {
create_dir_all("/run/var").await?;
mkfifo("/run/var/alfad-ctl", Mode::S_IRWXU | Mode::S_IWOTH)?;
create_dir_all(DIR_RUN).await?;
mkfifo(&PathBuf::from(DIR_RUN).join(APLT_CTL), Mode::S_IRWXU | Mode::S_IWOTH)?;
Ok(())
}

Expand All @@ -52,9 +55,7 @@ async fn wait_for_commands(context: &TaskContext, context_map: ContextMap<'stati
let mut buf = String::new();
loop {
if context.state().await == TaskState::Terminating {
context
.update_state(TaskState::Concluded(ExitReason::Terminated))
.await;
context.update_state(TaskState::Concluded(ExitReason::Terminated)).await;
break Ok(());
};
let mut pipe = match create_pipe().await {
Expand Down Expand Up @@ -83,12 +84,10 @@ async fn wait_for_commands(context: &TaskContext, context_map: ContextMap<'stati
}

async fn create_pipe() -> Result<BufReader<File>> {
let dir = if cfg!(debug_assertions) {
"test"
} else {
"/run/var"
};
let path = Path::new(dir).join("alfad-ctl");
let file = smol::fs::OpenOptions::new().read(true).open(&path).await?;
Ok(BufReader::new(file))
Ok(BufReader::new(
smol::fs::OpenOptions::new()
.read(true)
.open(&Path::new(if cfg!(debug_assertions) { "test" } else { DIR_RUN }).join(APLT_CTL))
.await?,
))
}
32 changes: 6 additions & 26 deletions core/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ pub struct TaskConfig {

impl TaskConfig {
pub fn new(name: String) -> Self {
Self {
name,
..Default::default()
}
Self { name, ..Default::default() }
}

pub fn after(&mut self, name: &str) -> &mut Self {
Expand All @@ -62,21 +59,12 @@ impl TaskConfig {
}

pub fn read_config(builtin: Vec<TaskConfigYaml>) -> Vec<TaskConfig> {
let configs = if cfg!(debug_assertions) {
"test"
} else {
"/etc/alfad"
};
let configs = if cfg!(debug_assertions) { "test" } else { "/etc/alfad" };
let configs = Path::new(configs);

match read_binary(configs.join("alfad.bin").as_path()) {
Some(mut configs) => {
configs.extend(
builtin
.into_iter()
.map(TaskConfigYaml::into_config)
.filter_map(drop_errors),
);
configs.extend(builtin.into_iter().map(TaskConfigYaml::into_config).filter_map(drop_errors));
configs
}
None => read_yaml_configs(configs.join("alfad.d").as_path(), builtin),
Expand All @@ -85,12 +73,8 @@ pub fn read_config(builtin: Vec<TaskConfigYaml>) -> Vec<TaskConfig> {

#[instrument]
pub fn read_binary(path: &Path) -> Option<Vec<TaskConfig>> {
let packed = fs::read(path)
.map_err(|error| error!("Can't find alfad.bin {error}"))
.ok()?;
let (version, res) = postcard::from_bytes::<(String, Vec<_>)>(&packed)
.map_err(|error| error!(?error))
.ok()?;
let packed = fs::read(path).map_err(|error| error!("Can't find alfad.bin {error}")).ok()?;
let (version, res) = postcard::from_bytes::<(String, Vec<_>)>(&packed).map_err(|error| error!(?error)).ok()?;
if version == crate::VERSION {
Some(res)
} else {
Expand Down Expand Up @@ -128,11 +112,7 @@ pub fn read_yaml_configs(path: &Path, builtin: Vec<TaskConfigYaml>) -> Vec<TaskC
#[cfg(feature = "before")]
let configs = resolve_before(configs);

let configs = configs
.into_iter()
.map(TaskConfigYaml::into_config)
.filter_map(drop_errors)
.collect();
let configs = configs.into_iter().map(TaskConfigYaml::into_config).filter_map(drop_errors).collect();

#[cfg(feature = "validate")]
let configs = validate::validate(configs);
Expand Down
26 changes: 26 additions & 0 deletions core/src/def.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/// Defaults and constants
///
// Main binary name
pub const APLT_MAIN: &str = "alfad";

// Ctl applet
pub const APLT_CTL: &str = "alfad-ctl";

// Compilation applet
pub const APLT_COMPILE: &str = "alfad-compile";

// The /sbin/init
pub const APLT_INIT: &str = "init";

/// Sockets
pub const DIR_RUN: &str = "/run/var";

/// Configuration directory
pub const DIR_CFG: &str = "/etc/alfad";

/// Directory for the run states
pub const DIR_CFG_D: &str = "/etc/alfad/alfad.d";

/// Configuration bytecode
pub const FILE_CFG_BT: &str = "alfad.d.cache";
14 changes: 4 additions & 10 deletions core/src/init.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::config::yaml::TaskConfigYaml;
use crate::task::ContextMap;
use crate::{config::read_config, task::TaskContext};
use crate::{config::yaml::TaskConfigYaml, def::APLT_MAIN};
use anyhow::Result;
use futures::StreamExt;
use nix::libc::{SIGABRT, SIGHUP, SIGPIPE, SIGTERM, SIGTSTP};
Expand All @@ -27,19 +27,13 @@ impl Alfad {
.detach();

env::set_var("SMOL_THREADS", "8");
info!("Starting alfad");
info!("Starting {}", APLT_MAIN);
let configs = read_config(self.builtin);
let context: ContextMap = ContextMap(Box::leak(Box::new(
configs
.into_iter()
.map(|config| (&*config.name.clone().leak(), TaskContext::new(config)))
.collect(),
configs.into_iter().map(|config| (&*config.name.clone().leak(), TaskContext::new(config))).collect(),
)));
info!("Done parsing ({} tasks)", context.0.len());
context
.0
.values()
.for_each(|config| crate::task::spawn(config, context));
context.0.values().for_each(|config| crate::task::spawn(config, context));
// smol::block_on(async { wait_for_commands(context).await });
smol::block_on(smol::Timer::never());
Ok(())
Expand Down
11 changes: 6 additions & 5 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
pub mod action;
pub mod config;
pub mod task;
pub mod ordering;
pub mod validate;
pub mod builtin;
pub mod command_line;
pub mod config;
pub mod def;
pub mod ordering;
pub mod perform_action;
pub mod task;
pub mod validate;

pub static VERSION: &str = "0.1";
pub static VERSION: &str = "0.1";
63 changes: 25 additions & 38 deletions core/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub mod action;
pub mod builtin;
pub mod command_line;
pub mod config;
pub mod def;
mod init;
pub mod ordering;
mod perform_action;
Expand All @@ -12,7 +13,11 @@ use crate::builtin::{
ctl::{CreateCtlPipe, WaitForCommands},
IntoConfig,
};
use alfad::action::{Action, SystemCommand};
use action::ActionError;
use alfad::{
action::{Action, SystemCommand},
def::{APLT_COMPILE, APLT_CTL, APLT_INIT, APLT_MAIN, DIR_CFG, DIR_CFG_D, DIR_RUN, FILE_CFG_BT},
};
use anyhow::{Context, Result};
use clap::Parser;
use config::{read_yaml_configs, yaml::TaskConfigYaml, TaskConfig};
Expand All @@ -32,62 +37,44 @@ fn main() -> Result<()> {
let name = env::args().next().unwrap();
let name = Path::new(&name).file_name().unwrap().to_str().unwrap();

let subscriber = FmtSubscriber::builder()
.with_max_level(Level::TRACE)
.finish();

tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
tracing::subscriber::set_global_default(FmtSubscriber::builder().with_max_level(Level::TRACE).finish())
.expect("setting default subscriber failed");

let action = match name {
"alfad-ctl" => Action::parse_from(env::args()),
"alfad-compile" => return compile(),
"init" => {
return init::Alfad {
builtin: get_built_in(),
}
.run()
APLT_CTL => Action::parse_from(env::args()),
APLT_COMPILE => return compile(),
APLT_MAIN => {
return Err(ActionError::MainAppletCalled.into());
}
_ => Action::System {
command: SystemCommand::parse_from([String::new()].into_iter().chain(env::args())),
},
APLT_INIT => return init::Alfad { builtin: get_built_in() }.run(),
_ => Action::System { command: SystemCommand::parse_from([String::new()].into_iter().chain(env::args())) },
};

let payload = action.to_string();

OpenOptions::new()
.write(true)
.open("/run/var/alfad-ctl")
.context("alfad pipe not found")?
.write_all(payload.as_bytes())?;
.open(PathBuf::from(DIR_RUN).join(APLT_CTL))
.context("alfad communication socket not found")?
.write_all(action.to_string().as_bytes())?;
Ok(())
}

fn get_built_in() -> Vec<TaskConfigYaml> {
vec![CreateCtlPipe.into_config(), WaitForCommands.into_config()]
}

#[derive(Parser)]
struct Cli {
#[clap(default_value = "/etc/alfad")]
target: PathBuf,
}

/// Byte-compile configuration into a cache file for faster load.
/// NOTE: Optional operation.
fn compile() -> Result<()> {
let cli = Cli::parse();

let builtin = get_built_in();

let configs = (
let tgt = PathBuf::from(DIR_CFG);
let data = postcard::to_allocvec(&(
VERSION,
read_yaml_configs(&cli.target.join("alfad.d"), get_built_in())
read_yaml_configs(&PathBuf::from(DIR_CFG_D), get_built_in())
.into_iter()
.filter(|x| builtin.iter().all(|bi| bi.name != x.name))
.filter(|x| get_built_in().iter().all(|bi| bi.name != x.name))
.collect_vec(),
);

let data = postcard::to_allocvec(&configs)?;
))?;
let (_, _): (String, Vec<TaskConfig>) = postcard::from_bytes(data.as_ref())?;

fs::write(cli.target.join("alfad.bin"), data)?;
fs::write(tgt.join(FILE_CFG_BT), data)?;
Ok(())
}
23 changes: 23 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Don't argue on 130 width. :-) Just don't.
# No more IBM punchcards here, and your monitor
# is at least 28 inches wide with a decent resolution.
#
# Welcome to the 21st century. Shush!

max_width = 130
fn_call_width = 130
chain_width = 130
single_line_let_else_max_width = 130
single_line_if_else_max_width = 130
use_small_heuristics = "Max"

# Parser version
edition = "2021"

# Emacs!
tab_spaces = 4

# Perks
use_field_init_shorthand = true
fn_args_layout = "Compressed"
use_try_shorthand = true

0 comments on commit d12c23b

Please sign in to comment.