use std::borrow::Cow; use std::error::Error; use std::ffi::OsStr; use std::fmt; use std::io; use std::path::Path; use std::path::PathBuf; use std::process::Output; use std::thread::sleep; use std::time::Duration; use command_runner::{CommandRunner, SetuidCommandRunner}; use resources::Resource; use symbols::file::File as FileSymbol; use symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner}; #[derive(Debug)] pub enum UserServiceError { ActivationFailed(io::Result), ExecError(E), GenericError, } impl From for UserServiceError { fn from(err: io::Error) -> Self { Self::ExecError(err) } } impl Error for UserServiceError { fn description(&self) -> &str { match self { UserServiceError::ExecError(ref e) => e.description(), UserServiceError::GenericError => "Generic error", UserServiceError::ActivationFailed(_) => "Activation of service failed", } } fn cause(&self) -> Option<&dyn Error> { match self { UserServiceError::ExecError(ref e) => Some(e), _ => None, } } } impl fmt::Display for UserServiceError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.description())?; if let UserServiceError::ActivationFailed(Ok(ref log)) = self { write!(f, ": {:?}", log)?; }; Ok(()) } } pub struct UserService<'a, C: AsRef, R: CommandRunner> { socket_path: Cow<'a, Path>, service_name: &'a str, user_name: Cow<'a, str>, command_runner: R, config: FileSymbol, } impl<'a, R: CommandRunner> UserService<'a, String, SetuidCommandRunner<'a, Cow<'a, str>, R>> { pub fn new_nodejs( home: Cow<'a, Path>, user_name: Cow<'a, str>, service_name: &'a str, path: Cow<'a, Path>, command_runner: &'a R, socket_path: Cow<'a, Path>, ) -> Self { let content = format!( "[Service] Environment=NODE_ENV=production Environment=PORT={1} ExecStartPre=/bin/rm -f {1} ExecStart=/usr/bin/nodejs {0} ExecStartPost=/bin/sh -c 'sleep 1 && chmod 666 {1}' # FIXME: This only works if the nodejs path is a directory WorkingDirectory={0} #RuntimeDirectory=service #RuntimeDirectoryMode=766 Restart=always [Install] WantedBy=default.target ", path.to_str().unwrap(), socket_path.to_str().unwrap() ); UserService::new( socket_path, home, user_name, service_name, command_runner, content, ) } pub fn new( socket_path: Cow<'a, Path>, home: Cow<'a, Path>, user_name: Cow<'a, str>, service_name: &'a str, command_runner: &'a R, content: String, ) -> Self { let config_path: PathBuf = [ home.as_ref(), format!(".config/systemd/user/{}.service", service_name).as_ref(), ] .iter() .collect(); UserService { socket_path, service_name, user_name: user_name.clone(), command_runner: SetuidCommandRunner::new(user_name, command_runner), config: FileSymbol::new(config_path, content), } } } impl<'a, C: AsRef, R: CommandRunner> UserService<'a, C, R> { fn systemctl_wait_for_dbus(&self, args: &[&OsStr]) -> Result> { let mut tries = 5; loop { let result = self.command_runner.run_with_args("systemctl", args)?; if !result.status.success() { let raw_stderr = String::from_utf8(result.stderr)?; let stderr = raw_stderr.trim_end(); if stderr != "Failed to connect to bus: No such file or directory" { return Err(stderr.into()); } } else { return Ok(String::from_utf8(result.stdout)?.trim_end().to_string()); } tries -= 1; if tries == 0 { return Err("Gave up waiting for dbus to appear".to_string().into()); } sleep(Duration::from_millis(500)); } } fn check_if_service(&self) -> Result> { loop { let active_state = self.systemctl_wait_for_dbus(args![ "--user", "show", "--property", "ActiveState", self.service_name, ])?; match active_state.as_ref() { "ActiveState=activating" => sleep(Duration::from_millis(500)), "ActiveState=active" => return Ok(true), "ActiveState=failed" => { return Err(Box::new( UserServiceError::ActivationFailed(self.command_runner.run_with_args( "journalctl", args!["--user", format!("--user-unit={}", self.service_name)], )) as UserServiceError, )) } _ => return Ok(false), } } } } impl<'a, C: AsRef, R: CommandRunner> Symbol for UserService<'a, C, R> { fn target_reached(&self) -> Result> { if !(self.config.target_reached()?) { return Ok(false); } self.check_if_service() } fn execute(&self) -> Result<(), Box> { self.config.execute()?; self.systemctl_wait_for_dbus(args!["--user", "enable", self.service_name])?; self.systemctl_wait_for_dbus(args!["--user", "restart", self.service_name])?; loop { if !(self.check_if_service()?) { return Err(Box::new( UserServiceError::GenericError as UserServiceError, )); } if self.socket_path.exists() { return Ok(()); } sleep(Duration::from_millis(500)); } } fn get_prerequisites(&self) -> Vec { let mut r = vec![Resource::new( "file", format!("/var/lib/systemd/linger/{}", self.user_name), )]; r.extend(self.config.get_prerequisites().into_iter()); r } fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box { Box::new(SymbolAction::new(runner, self)) } fn into_action<'b>(self: Box, runner: &'b dyn SymbolRunner) -> Box where Self: 'b, { Box::new(OwnedSymbolAction::new(runner, *self)) } } impl<'a, C: AsRef, R: CommandRunner> fmt::Display for UserService<'a, C, R> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Systemd user service unit for {}", self.service_name) } }