LINE1 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300 310 320 330 340 350 360 370 380 390 400 410 420 430 440 450 460 470 480 490 500 510 5201use std::{2 fs,3 path::{Path, PathBuf},4 process::Command,5 time::Duration,6};78use super::{9 backup,10 cli::{BackgroundCommand, BackgroundRunArgs},11 docker::DockerEngine,12 error::OnceError,13 model::OnceState,14 namespace::Namespace,15 operations, proxy, updater,16};1718use crate::error::ContextError;1920const CHECK_INTERVAL: Duration = Duration::from_mins(5);21const SYSTEMD_DIR: &str = "/etc/systemd/system";22const LAUNCHD_DIR: &str = "/Library/LaunchDaemons";23const LAUNCHD_PREFIX: &str = "com.basecamp.";2425pub fn run(namespace: String, command: BackgroundCommand) -> Result<(), OnceError> {26 match command {27 BackgroundCommand::Install(args) => install(&namespace, args.take_over_once)?,28 BackgroundCommand::Uninstall => uninstall(&namespace)?,29 BackgroundCommand::Run(args) => {30 let runtime = tokio::runtime::Builder::new_multi_thread()31 .enable_all()32 .build()?;33 runtime.block_on(run_foreground(namespace, args))?;34 }35 }36 Ok(())37}3839fn install(namespace: &str, take_over_once: bool) -> Result<(), OnceError> {40 require_root()?;41 let manager = ServiceManager::new()?;42 let upstream = format!("{namespace}-background");43 let upstream_installed = manager.is_installed(&upstream);44 require_handoff_confirmation(upstream_installed, take_over_once)?;4546 let service_name = ino_service_name(namespace);47 if manager.is_installed(&service_name) {48 println!("Ino background service is already installed");49 return Ok(());50 }51 if upstream_installed {52 manager.stop_service(&upstream)?;53 }5455 let executable = std::env::current_exe()56 .and_then(fs::canonicalize)57 .map_err(|error| {58 OnceError::Context(59 ContextError::new(60 "finding the Ino executable for background-service installation",61 error,62 )63 .with_suggestion("verify that the Ino executable still exists and is accessible"),64 )65 })?;66 if let Err(error) = manager.install(&service_name, &executable, namespace) {67 if upstream_installed {68 let _ = manager.start_service(&upstream);69 }70 return Err(error);71 }72 println!("Installed and started Ino background service");73 Ok(())74}7576fn uninstall(namespace: &str) -> Result<(), OnceError> {77 require_root()?;78 let manager = ServiceManager::new()?;79 let service_name = ino_service_name(namespace);80 if !manager.is_installed(&service_name) {81 println!("Ino background service is not installed");82 return Ok(());83 }84 manager.remove(&service_name)?;85 println!("Uninstalled Ino background service");86 Ok(())87}8889fn require_root() -> Result<(), OnceError> {90 #[cfg(unix)]91 if unsafe { libc::geteuid() } != 0 {92 return Err(OnceError::Io(93 "background service install/uninstall must be run as root".into(),94 ));95 }96 Ok(())97}9899fn ino_service_name(namespace: &str) -> String {100 format!("ino-{namespace}-background")101}102103fn require_handoff_confirmation(104 once_service_installed: bool,105 take_over_once: bool,106) -> Result<(), OnceError> {107 if once_service_installed && !take_over_once {108 return Err(OnceError::Io(109 "Once background service is installed; rerun with --take-over-once to hand it to Ino"110 .into(),111 ));112 }113 Ok(())114}115116#[derive(Clone, Copy)]117enum ServiceKind {118 Systemd,119 Launchd,120}121122struct ServiceManager {123 kind: ServiceKind,124}125126impl ServiceManager {127 fn new() -> Result<Self, OnceError> {128 let kind = match std::env::consts::OS {129 "linux" => ServiceKind::Systemd,130 "macos" => ServiceKind::Launchd,131 os => return Err(OnceError::Io(format!("unsupported service platform: {os}"))),132 };133 Ok(Self { kind })134 }135136 fn is_installed(&self, name: &str) -> bool {137 self.service_path(name).is_file()138 }139140 fn service_path(&self, name: &str) -> PathBuf {141 match self.kind {142 ServiceKind::Systemd => Path::new(SYSTEMD_DIR).join(format!("{name}.service")),143 ServiceKind::Launchd => {144 Path::new(LAUNCHD_DIR).join(format!("{LAUNCHD_PREFIX}{name}.plist"))145 }146 }147 }148149 fn install(&self, name: &str, executable: &Path, namespace: &str) -> Result<(), OnceError> {150 let path = self.service_path(name);151 create_service_parent(&path)?;152 let content = match self.kind {153 ServiceKind::Systemd => systemd_unit(executable, namespace),154 ServiceKind::Launchd => launchd_plist(name, executable, namespace),155 };156 write_service_file(&path, &content)?;157 #[cfg(unix)]158 {159 use std::os::unix::fs::PermissionsExt;160 fs::set_permissions(&path, fs::Permissions::from_mode(0o644))161 .map_err(|error| service_file_error("setting permissions on", &path, error))?;162 }163 let result = match self.kind {164 ServiceKind::Systemd => {165 Self::command("systemctl", &["daemon-reload"])?;166 Self::command(167 "systemctl",168 &["enable", "--now", &format!("{name}.service")],169 )170 }171 ServiceKind::Launchd => Self::command(172 "launchctl",173 &["bootstrap", "system", path.to_string_lossy().as_ref()],174 ),175 };176 if let Err(error) = result {177 let _ = fs::remove_file(&path);178 return Err(error);179 }180 Ok(())181 }182183 fn remove(&self, name: &str) -> Result<(), OnceError> {184 let path = self.service_path(name);185 match self.kind {186 ServiceKind::Systemd => {187 Self::command(188 "systemctl",189 &["disable", "--now", &format!("{name}.service")],190 )?;191 remove_service_file(&path)?;192 Self::command("systemctl", &["daemon-reload"])193 }194 ServiceKind::Launchd => {195 let label = format!("{LAUNCHD_PREFIX}{name}");196 Self::command("launchctl", &["bootout", &format!("system/{label}")])?;197 remove_service_file(&path)198 }199 }200 }201202 fn stop_service(&self, name: &str) -> Result<(), OnceError> {203 match self.kind {204 ServiceKind::Systemd => Self::command(205 "systemctl",206 &["disable", "--now", &format!("{name}.service")],207 ),208 ServiceKind::Launchd => {209 let label = format!("{LAUNCHD_PREFIX}{name}");210 Self::command("launchctl", &["bootout", &format!("system/{label}")])211 }212 }213 }214215 fn start_service(&self, name: &str) -> Result<(), OnceError> {216 match self.kind {217 ServiceKind::Systemd => Self::command(218 "systemctl",219 &["enable", "--now", &format!("{name}.service")],220 ),221 ServiceKind::Launchd => Self::command(222 "launchctl",223 &[224 "bootstrap",225 "system",226 self.service_path(name).to_string_lossy().as_ref(),227 ],228 ),229 }230 }231232 fn command(program: &str, args: &[&str]) -> Result<(), OnceError> {233 let status = Command::new(program).args(args).status().map_err(|error| {234 OnceError::Context(235 ContextError::new(format!("starting service manager `{program}`"), error)236 .with_suggestion(237 "check that the system service manager is installed and available on PATH",238 ),239 )240 })?;241 if status.success() {242 Ok(())243 } else {244 Err(OnceError::Context(ContextError::new(245 format!("running service manager `{program}`"),246 std::io::Error::other(format!("command exited with status {status}")),247 )))248 }249 }250}251252fn create_service_parent(path: &Path) -> Result<(), OnceError> {253 let parent = path.parent().expect("service path has parent");254 fs::create_dir_all(parent)255 .map_err(|error| service_file_error("creating service directory", parent, error))256}257258fn write_service_file(path: &Path, content: &str) -> Result<(), OnceError> {259 fs::write(path, content)260 .map_err(|error| service_file_error("writing service file", path, error))261}262263fn remove_service_file(path: &Path) -> Result<(), OnceError> {264 match fs::remove_file(path) {265 Ok(()) => Ok(()),266 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),267 Err(error) => Err(service_file_error("removing service file", path, error)),268 }269}270271fn service_file_error(action: &str, path: &Path, error: std::io::Error) -> OnceError {272 let suggestion = match error.kind() {273 std::io::ErrorKind::PermissionDenied => {274 Some("check that you have permission to access the system service directory")275 }276 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory => {277 Some("check that the service path points to a valid directory and file")278 }279 _ => None,280 };281 let context = ContextError::new(format!("{action} `{}`", path.display()), error);282 let context = match suggestion {283 Some(suggestion) => context.with_suggestion(suggestion),284 None => context,285 };286 OnceError::Context(context)287}288289fn systemd_unit(executable: &Path, namespace: &str) -> String {290 format!(291 "[Unit]\nDescription=Ino background tasks ({namespace})\nAfter=network.target docker.service\n\n[Service]\nType=simple\nExecStart={} once --namespace {} background run\nRestart=always\nRestartSec=5\n\n[Install]\nWantedBy=multi-user.target\n",292 systemd_escape(&executable.to_string_lossy()),293 systemd_escape(namespace),294 )295}296297fn systemd_escape(value: &str) -> String {298 if value299 .chars()300 .all(|character| character.is_ascii_alphanumeric() || "/_-.:".contains(character))301 {302 return value.to_owned();303 }304 format!(305 "\"{}\"",306 value307 .replace('%', "%%")308 .replace('\\', "\\\\")309 .replace('"', "\\\"")310 )311}312313fn launchd_plist(name: &str, executable: &Path, namespace: &str) -> String {314 let label = format!("{LAUNCHD_PREFIX}{name}");315 format!(316 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict><key>Label</key><string>{}</string><key>ProgramArguments</key><array><string>{}</string><string>once</string><string>--namespace</string><string>{}</string><string>background</string><string>run</string></array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer></dict></plist>\n",317 xml_escape(&label),318 xml_escape(&executable.to_string_lossy()),319 xml_escape(namespace),320 )321}322323fn xml_escape(value: &str) -> String {324 value325 .replace('&', "&")326 .replace('<', "<")327 .replace('>', ">")328 .replace('"', """)329 .replace('\'', "'")330}331332async fn run_foreground(namespace: String, args: BackgroundRunArgs) -> Result<(), OnceError> {333 loop {334 match check_once(&namespace, args.no_self_update).await {335 Ok(updated) if updated => return Ok(()),336 Ok(_) => {}337 Err(error) if args.once => return Err(error),338 Err(error) => report_background_error("running an Ino background check", error),339 }340 if args.once || wait_or_shutdown().await? {341 return Ok(());342 }343 }344}345346async fn check_once(namespace_name: &str, no_self_update: bool) -> Result<bool, OnceError> {347 let engine = std::sync::Arc::new(DockerEngine::connect()?);348 let mut namespace = Namespace::restore(engine, namespace_name.to_owned()).await?;349 let has_proxy = namespace.proxy_settings.is_some();350 let mut state = if has_proxy {351 proxy::load_state(&namespace).await?352 } else {353 OnceState::default()354 };355356 if !no_self_update357 && std::env::var_os("INO_NO_SELF_UPDATE").is_none()358 && state.self_update_due()359 {360 let result = updater::run();361 let error = result.as_ref().err().map(ToString::to_string);362 state.record_self_update(error.as_deref());363 if has_proxy {364 let _ = proxy::save_state(&namespace, &state).await;365 }366 if result.is_ok() {367 return Ok(true);368 }369 }370371 let app_names = namespace372 .applications373 .iter()374 .filter(|app| app.running)375 .map(|app| app.settings.name.clone())376 .collect::<Vec<_>>();377 for app_name in app_names {378 let Some(app) = namespace379 .applications380 .iter()381 .find(|app| app.settings.name == app_name)382 .cloned()383 else {384 continue;385 };386 if app.settings.auto_update && state.update_due(&app_name) {387 match operations::auto_update(&mut namespace, &app_name).await {388 Ok(_) => state.record_update(&app_name, None),389 Err(error) => {390 state.record_update(&app_name, Some(&error.to_string()));391 report_background_error(392 format!(393 "automatically updating application at {:?}",394 app.settings.host395 ),396 error,397 );398 }399 }400 }401402 let current_app = namespace403 .applications404 .iter()405 .find(|app| app.settings.name == app_name)406 .cloned()407 .unwrap_or(app);408 if current_app.settings.backup.auto_backup && state.backup_due(&app_name) {409 let path = Path::new(¤t_app.settings.backup.path);410 let filename = path.join(format!("{}-{}.tar.gz", app_name, backup_timestamp()));411 match backup::create(&namespace, ¤t_app, &filename).await {412 Ok(_) => state.record_backup(&app_name, None),413 Err(error) => {414 state.record_backup(&app_name, Some(&error.to_string()));415 report_background_error(416 format!(417 "automatically backing up application at {:?} to `{}`",418 current_app.settings.host,419 filename.display()420 ),421 error,422 );423 }424 }425 if let Err(error) = backup::trim_old_backups(&app_name, path) {426 report_background_error(427 format!(428 "removing expired backups for application at {:?} from `{}`",429 current_app.settings.host,430 path.display()431 ),432 error,433 );434 }435 }436 }437438 if has_proxy {439 proxy::save_state(&namespace, &state).await?;440 }441 Ok(false)442}443444fn backup_timestamp() -> String {445 let now = time::OffsetDateTime::now_utc();446 format!(447 "{:04}{:02}{:02}-{:02}{:02}{:02}",448 now.year(),449 u8::from(now.month()),450 now.day(),451 now.hour(),452 now.minute(),453 now.second()454 )455}456457fn report_background_error(context: impl Into<String>, error: OnceError) {458 let error = OnceError::context(context, error);459 eprintln!("{}", crate::error::format_cli_error(&error));460}461462async fn wait_or_shutdown() -> Result<bool, OnceError> {463 #[cfg(unix)]464 {465 let mut terminate =466 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())467 .map_err(|error| OnceError::Io(format!("registering SIGTERM handler: {error}")))?;468 tokio::select! {469 result = tokio::signal::ctrl_c() => {470 result.map_err(|error| OnceError::Io(format!("registering SIGINT handler: {error}")))?;471 Ok(true)472 }473 _ = terminate.recv() => Ok(true),474 () = tokio::time::sleep(CHECK_INTERVAL) => Ok(false),475 }476 }477 #[cfg(not(unix))]478 {479 tokio::select! {480 result = tokio::signal::ctrl_c() => {481 result.map_err(|error| OnceError::Io(format!("registering Ctrl-C handler: {error}")))?;482 Ok(true)483 }484 () = tokio::time::sleep(CHECK_INTERVAL) => Ok(false),485 }486 }487}488489#[cfg(test)]490mod tests {491 use std::{fs, path::Path};492493 use crate::error::format_cli_error;494495 use super::{496 ServiceManager, launchd_plist, require_handoff_confirmation, systemd_escape, systemd_unit,497 write_service_file,498 };499500 #[test]501 fn background_handoff_requires_explicit_flag_when_once_service_exists() {502 assert!(require_handoff_confirmation(false, false).is_ok());503 assert!(require_handoff_confirmation(true, false).is_err());504 assert!(require_handoff_confirmation(true, true).is_ok());505 }506507 #[test]508 fn systemd_unit_runs_ino_once_background_and_restarts_it() {509 let unit = systemd_unit(Path::new("/opt/ino"), "once");510 assert!(unit.contains("ExecStart=/opt/ino once --namespace once background run"));511 assert!(unit.contains("Restart=always"));512 assert!(unit.contains("After=network.target docker.service"));513 }514515 #[test]516 fn service_arguments_are_escaped_for_systemd_and_launchd() {517 assert_eq!(systemd_escape("/opt/My Ino"), "\"/opt/My Ino\"");518 let plist = launchd_plist(519 "ino-once-background",520 Path::new("/opt/Ino & Tools/ino"),521 "once",522 );523 assert!(plist.contains("/opt/Ino & Tools/ino"));524 assert!(plist.contains("<string>background</string>"));525 }526527 #[test]528 fn service_file_write_error_reports_path_cause_and_recovery_hint() {529 let directory = tempfile::tempdir().unwrap();530 let blocker = directory.path().join("not-a-directory");531 fs::write(&blocker, "file").unwrap();532 let path = blocker.join("ino-background.service");533534 let error = write_service_file(&path, "service contents").unwrap_err();535 let report = format_cli_error(&error);536537 assert!(report.contains("writing service file"));538 assert!(report.contains(path.to_string_lossy().as_ref()));539 assert!(report.contains("Caused by:"));540 assert!(541 report542 .contains("Try: check that the service path points to a valid directory and file")543 );544 }545546 #[cfg(unix)]547 #[test]548 fn missing_service_manager_reports_program_and_os_cause() {549 let error =550 ServiceManager::command("ino-service-manager-that-does-not-exist", &[]).unwrap_err();551 let report = format_cli_error(&error);552553 assert!(554 report.contains("starting service manager `ino-service-manager-that-does-not-exist`")555 );556 assert!(report.contains("Caused by: No such file or directory"));557 assert!(report.contains(558 "Try: check that the system service manager is installed and available on PATH"559 ));560 }561}