use std::error::Error; use std::fmt; use std::fs; use std::io; use std::ops::Deref; 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) -> UserServiceError { UserServiceError::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> { try!(write!(f, "{}", self.description())); if let UserServiceError::ActivationFailed(Ok(ref log)) = self { try!(write!(f, ": {:?}", log)); }; Ok(()) } } pub struct UserService<'a, C, R> where C: Deref, R: CommandRunner, { service_name: &'a str, user_name: &'a str, command_runner: R, file: FileSymbol, } impl<'a, R> UserService<'a, String, SetuidCommandRunner<'a, R>> where R: CommandRunner, { pub fn new_nodejs( home: &'a str, user_name: &'a str, service_name: &'a str, path: &'a str, command_runner: &'a R, ) -> Self { let port = format!("/var/tmp/{}-{}.socket", user_name, service_name); 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, port ); UserService::new(home, user_name, service_name, command_runner, content) } pub fn new( home: &'a str, user_name: &'a str, service_name: &'a str, command_runner: &'a R, content: String, ) -> Self { let file_path = format!( "{}/.config/systemd/user/{}.service", home.trim_end(), service_name ); UserService { service_name, user_name, command_runner: SetuidCommandRunner::new(user_name, command_runner), file: FileSymbol::new(file_path, content), } } } impl<'a, C, R> UserService<'a, C, R> where C: Deref, R: CommandRunner, { fn systemctl_wait_for_dbus(&self, args: &[&str]) -> Result> { let mut tries = 5; loop { let result = try!(self.command_runner.run_with_args("systemctl", args)); if !result.status.success() { let raw_stderr = try!(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( try!(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 = try!(self.systemctl_wait_for_dbus(&[ "--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", &["--user", &format!("--user-unit={}", self.service_name)], )) as UserServiceError, )) } _ => return Ok(false), } } } } impl<'a, C, R> Symbol for UserService<'a, C, R> where C: Deref, R: CommandRunner, { fn target_reached(&self) -> Result> { if !(try!(self.file.target_reached())) { return Ok(false); } self.check_if_service() } fn execute(&self) -> Result<(), Box> { try!(self.file.execute()); try!(self.systemctl_wait_for_dbus(&["--user", "enable", self.service_name])); try!(self.systemctl_wait_for_dbus(&["--user", "restart", self.service_name])); if !(try!(self.check_if_service())) { return Err(Box::new( UserServiceError::GenericError as UserServiceError, )); } let file_name = format!("/var/tmp/{}-{}.socket", self.user_name, self.service_name); fs::metadata(&file_name) .map(|_| ()) .map_err(|e| Box::new(e) as Box) } fn get_prerequisites(&self) -> Vec { let mut r = vec![Resource::new( "file", format!("/var/lib/systemd/linger/{}", self.user_name), )]; r.extend(self.file.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, R> fmt::Display for UserService<'a, C, R> where C: Deref, R: CommandRunner, { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "Systemd user service unit for {}", self.service_name) } }