use std::error::Error; use std::os::unix::fs::PermissionsExt; use std::fmt; use std::io; use std::fs::{self, Metadata}; use std::process::Output; use std::thread::sleep; use std::time::Duration; use std::ops::Deref; use command_runner::{CommandRunner, SetuidCommandRunner}; use resources::Resource; use symbols::Symbol; use symbols::file::File as FileSymbol; #[derive(Debug)] pub enum NodeJsSystemdUserServiceError { ActivationFailed(io::Result), ExecError(E), GenericError } impl From for NodeJsSystemdUserServiceError { fn from(err: io::Error) -> NodeJsSystemdUserServiceError { NodeJsSystemdUserServiceError::ExecError(err) } } impl Error for NodeJsSystemdUserServiceError { fn description(&self) -> &str { match self { &NodeJsSystemdUserServiceError::ExecError(ref e) => e.description(), &NodeJsSystemdUserServiceError::GenericError => "Generic error", &NodeJsSystemdUserServiceError::ActivationFailed(_) => "Activation of service failed" } } fn cause(&self) -> Option<&Error> { match self { &NodeJsSystemdUserServiceError::ExecError(ref e) => Some(e), _ => None } } } impl fmt::Display for NodeJsSystemdUserServiceError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { try!(write!(f, "{}", self.description())); if let &NodeJsSystemdUserServiceError::ActivationFailed(Ok(ref log)) = self { try!(write!(f, ": {:?}", log)); }; Ok(()) } } pub struct NodeJsSystemdUserService<'a, C, R> where C: Deref, R: CommandRunner { service_name: &'a str, user_name: &'a str, command_runner: R, file: FileSymbol } impl<'a, R> NodeJsSystemdUserService<'a, String, SetuidCommandRunner<'a, R>> where R: CommandRunner { pub fn new(home: &'a str, user_name: &'a str, name: &'a str, path: &'a str, command_runner: &'a R) -> Self { let file_path = format!("{}/.config/systemd/user/{}.service", home.trim_right(), name); let content = format!("[Service] ExecStartPre=rm /var/tmp/{1}-{2}.socket # This only works if the path is a directory WorkingDirectory={0} ExecStart=/usr/bin/nodejs {0} Restart=always Environment=NODE_ENV=production Environment=PORT=/var/tmp/{1}-{2}.socket #RuntimeDirectory=service #RuntimeDirectoryMode=766 [Install] WantedBy=default.target ", path, user_name, name); NodeJsSystemdUserService { service_name: name, user_name: user_name, command_runner: SetuidCommandRunner::new(user_name, command_runner), file: FileSymbol::new(file_path, content) } } } impl<'a, C, R> NodeJsSystemdUserService<'a, C, R> where C: Deref, R: CommandRunner { fn check_if_service(&self) -> Result> { loop { // Check if service is registered let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.service_name])); if !active_state.status.success() { return Err(String::from_utf8(active_state.stderr).unwrap().trim_right().into()); } // Check if service is running match String::from_utf8(active_state.stdout).unwrap().trim_right() { "ActiveState=activating" => sleep(Duration::from_millis(500)), "ActiveState=active" => return Ok(true), "ActiveState=failed" => return Err(Box::new(NodeJsSystemdUserServiceError::ActivationFailed(self.command_runner.run_with_args("journalctl", &["--user", &format!("--user-unit={}", self.service_name)])) as NodeJsSystemdUserServiceError)), _ => return Ok(false) } } } } fn wait_for_metadata(file_name: &str) -> Result> { let result; let mut tries = 5; loop { let metadata = fs::metadata(file_name.clone()); match metadata { Ok(metadata) => { result = metadata; break; }, Err(e) => { if e.kind() != io::ErrorKind::NotFound { return Err(Box::new(e)); } } } tries -= 1; if tries == 0 { return Err("Gave up waiting for socket to appear".to_string().into()); } sleep(Duration::from_millis(500)); } Ok(result) } impl<'a, C, R> Symbol for NodeJsSystemdUserService<'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.command_runner.run_with_args("systemctl", &["--user", "enable", self.service_name])); try!(self.command_runner.run_with_args("systemctl", &["--user", "start", self.service_name])); if !(try!(self.check_if_service())) { return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError)); } let file_name = format!("/var/tmp/{}-{}.socket", self.user_name, self.service_name); let metadata = try!(wait_for_metadata(&file_name)); let mut perms = metadata.permissions(); perms.set_mode(0o666); try!(fs::set_permissions(file_name, perms)); Ok(()) } 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 } } impl<'a, C, R> fmt::Display for NodeJsSystemdUserService<'a, C, R> where C: Deref, R: CommandRunner { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{ write!(f, "Systemd Node.js user service unit for {}", self.service_name) } }