use core::fmt;
use std::path::PathBuf;
use shep_core::config::{AppConfig, ResolvedApp, normalize};
use shep_core::paths::ShepPaths;
use shep_core::protocol::DogSource;
use crate::bus::Bus;
use crate::supervisor::SupervisorHandle;
use super::narrate::narrate;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DogSpec {
pub name: String,
pub source: DogSource,
}
#[non_exhaustive]
#[derive(Debug)]
pub enum DogError {
NoBinary(std::io::Error),
UnsupportedSource(String),
Config(String),
Io(std::io::Error),
}
impl fmt::Display for DogError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoBinary(err) => write!(f, "this binary's own path is unresolvable: {err}"),
Self::UnsupportedSource(source) => {
write!(f, "no way to spawn a dog from source {source}")
}
Self::Config(msg) => write!(f, "dog configuration is unusable: {msg}"),
Self::Io(err) => write!(f, "dog configuration could not be read: {err}"),
}
}
}
impl core::error::Error for DogError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::NoBinary(err) | Self::Io(err) => Some(err),
Self::UnsupportedSource(_) | Self::Config(_) => None,
}
}
}
#[cfg(unix)]
fn builtin_program() -> Result<PathBuf, DogError> {
crate::handover::exec_target().map_err(DogError::NoBinary)
}
#[cfg(windows)]
fn builtin_program() -> Result<PathBuf, DogError> {
std::env::current_exe().map_err(DogError::NoBinary)
}
pub fn dog_app(spec: &DogSpec, paths: &ShepPaths) -> Result<ResolvedApp, DogError> {
let (script, args) = match &spec.source {
DogSource::BuiltIn => (
builtin_program()?.display().to_string(),
vec!["dog".to_string(), spec.name.clone()],
),
DogSource::Adopted { path } => (path.clone(), Vec::new()),
source => return Err(DogError::UnsupportedSource(format!("{source:?}"))),
};
let mut config = AppConfig::minimal(&spec.name, &script);
config.args = args;
config
.env
.insert("SHEP_HOME".to_string(), paths.home.display().to_string());
config
.env
.insert("SHEP_DOG_NAME".to_string(), spec.name.clone());
normalize(config).map_err(|err| DogError::Config(err.to_string()))
}
pub async fn spawn_enabled_dogs(
specs: &[DogSpec],
paths: &ShepPaths,
supervisor: &SupervisorHandle,
events: &Bus,
) {
for spec in specs {
let app = match dog_app(spec, paths) {
Ok(app) => app,
Err(err) => {
tracing::warn!(dog = %spec.name, %err, "a dog did not start");
continue;
}
};
let script = app.config().script.clone();
match supervisor.start_dog(app, spec.source.clone()).await {
Ok(info) if info.dog.is_none() => tracing::warn!(
dog = %spec.name,
"a sheep is already registered under this name; the dog did not start"
),
Ok(info) => {
narrate(
events,
&info,
&format!("shep has this dog enabled, running the binary at {script}"),
)
.await;
}
Err(err) => tracing::warn!(dog = %spec.name, %err, "a dog did not start"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::test_paths;
#[cfg(unix)]
#[test]
fn a_deleted_inode_answer_from_current_exe_never_becomes_a_dogs_script() {
let refusal = crate::handover::resolve_target(
[None, Some(PathBuf::from("/opt/shep/shep (deleted)"))],
None,
)
.unwrap_err();
let err = DogError::NoBinary(refusal);
assert_eq!(
err.to_string(),
"this binary's own path is unresolvable: no binary to exec: \
/opt/shep/shep (deleted) (names a deleted inode, not a file)"
);
}
#[test]
fn a_dogs_child_environment_carries_shep_home_and_its_name_and_no_configuration() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
std::fs::write(
&paths.dogs_config,
"[bark]\nwebhook = \"https://example.invalid/hook\"\n",
)
.unwrap();
let spec = DogSpec {
name: "bark".to_string(),
source: DogSource::BuiltIn,
};
let app = dog_app(&spec, &paths).unwrap();
let assembled = crate::assemble::assemble(
&app,
0,
&paths,
None,
&shep_core::secrets::SecretView::empty("production".to_string()),
)
.expect("a dog's own config carries no template to refuse");
assert_eq!(
assembled.env.get("SHEP_HOME"),
Some(&paths.home.display().to_string())
);
assert_eq!(
assembled.env.get("SHEP_DOG_NAME"),
Some(&"bark".to_string()),
"a dog is told the name its own section lives under"
);
assert!(
!assembled
.env
.values()
.any(|v| v.contains("example.invalid")),
"a dog's configuration never travels in its environment: {:?}",
assembled.env
);
}
#[test]
fn a_built_in_dog_runs_this_binary_and_an_adopted_one_runs_its_own() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
let built_in = dog_app(
&DogSpec {
name: "metrics".to_string(),
source: DogSource::BuiltIn,
},
&paths,
)
.unwrap();
assert_eq!(
built_in.config().script,
std::env::current_exe().unwrap().display().to_string()
);
assert_eq!(built_in.config().args, vec!["dog", "metrics"]);
let adopted = dog_app(
&DogSpec {
name: "otel".to_string(),
source: DogSource::Adopted {
path: "/usr/local/bin/shep-otel".to_string(),
},
},
&paths,
)
.unwrap();
assert_eq!(adopted.config().script, "/usr/local/bin/shep-otel");
assert!(adopted.config().args.is_empty());
assert_eq!(
adopted.config().name,
"otel",
"the NAME is the config key, never the filename"
);
}
#[test]
fn an_adopted_dog_is_told_the_name_it_was_registered_under() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
let adopted = dog_app(
&DogSpec {
name: "telemetry".to_string(),
source: DogSource::Adopted {
path: "/usr/local/bin/shep-otel".to_string(),
},
},
&paths,
)
.unwrap();
assert!(
adopted.config().args.is_empty(),
"the name arrives without shep inventing an argv for a foreign binary"
);
assert_eq!(
adopted.config().env.get("SHEP_DOG_NAME"),
Some(&"telemetry".to_string())
);
}
}