diff --git a/src/symbols/file.rs b/src/symbols/file.rs index d749ed0..59a1b2f 100644 --- a/src/symbols/file.rs +++ b/src/symbols/file.rs @@ -79,10 +79,8 @@ impl Symbol for File where C: Deref, D: AsRef + fmt } fn execute(&self) -> Result<(), Self::Error> { - //try!(self.command_runner.run_with_args("mkdir", &["-p", Path::new(&path).parent().unwrap().to_str().unwrap()])); - // FIXME: Permissions - // try!(create_dir_all(Path::new(&path).parent().unwrap())); - try!(try!(FsFile::create(self.path.as_ref())).write_all(self.content.as_bytes())); + let mut file = try!(FsFile::create(self.path.as_ref())); + try!(file.write_all(self.content.as_bytes())); Ok(()) } } diff --git a/src/symbols/mod.rs b/src/symbols/mod.rs index c7cee44..0e397ed 100644 --- a/src/symbols/mod.rs +++ b/src/symbols/mod.rs @@ -9,5 +9,7 @@ pub trait Symbol: Display { pub mod file; pub mod git; +pub mod npm; pub mod user; pub mod systemd; +pub mod nginx; diff --git a/src/symbols/nginx/mod.rs b/src/symbols/nginx/mod.rs new file mode 100644 index 0000000..74f47ad --- /dev/null +++ b/src/symbols/nginx/mod.rs @@ -0,0 +1 @@ +pub mod server; diff --git a/src/symbols/nginx/server.rs b/src/symbols/nginx/server.rs new file mode 100644 index 0000000..b5f4db5 --- /dev/null +++ b/src/symbols/nginx/server.rs @@ -0,0 +1,116 @@ +use std::error::Error; +use std::fmt; +use std::io; +use std::ops::Deref; + +use command_runner::CommandRunner; +use symbols::Symbol; +use symbols::file::File as FileSymbol; +use symbols::file::FileError; + +#[derive(Debug)] +pub enum NginxServerError { + ExecError(E), + GenericError +} + +impl From> for NginxServerError> { + fn from(err: FileError) -> NginxServerError> { + NginxServerError::ExecError(err) + } +} + +impl From for NginxServerError> { + fn from(err: io::Error) -> NginxServerError> { + NginxServerError::GenericError + } +} + +impl Error for NginxServerError { + fn description(&self) -> &str { + match self { + &NginxServerError::ExecError(ref e) => e.description(), + &NginxServerError::GenericError => "Generic error" + } + } + fn cause(&self) -> Option<&Error> { + match self { + &NginxServerError::ExecError(ref e) => Some(e), + _ => None + } + } +} + +impl fmt::Display for NginxServerError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + write!(f, "{}", self.description()) + } +} + +pub struct NginxServer<'a, C> where C: Deref { + command_runner: &'a CommandRunner, + file: FileSymbol>, +} + +use std::borrow::Cow; + +impl<'a> NginxServer<'a, String> { + pub fn new(home: &'a str, domain: &'a str, static_path: &'a str, redir_domains: &[&'a str], command_runner: &'a CommandRunner) -> Self { + let file_path: Cow = Cow::from(String::from("/etc/nginx/sites-enabled/") + domain); + + let redir_content = redir_domains.iter().map(|redir_domain| format!("server {{ + listen 80; + + server_name {}; + return 302 $scheme://{}$request_uri; + }} + + ", redir_domain, domain)).fold(String::new(), |s, v| s + &v); + let content = String::from(redir_content) + &format!("server {{ + listen 80; + # listen 443 ssl; + # ssl_certificate /etc/ssl/.crt; + # ssl_certificate_key /etc/ssl/.key; + server_name {}; + + root {}; + + location / {{ + try_files $uri @proxy; + }} + + location @proxy {{ + include fastcgi_params; + proxy_pass http://unix:{}/var/service.socket:; + proxy_redirect off; + }} +}}", domain, static_path, home); + NginxServer { + command_runner: command_runner, + file: FileSymbol::new(file_path, content) + } + } +} + +impl<'a, C> Symbol for NginxServer<'a, C> where C: Deref { + type Error = NginxServerError<> as Symbol>::Error>; + fn target_reached(&self) -> Result { + if !try!(self.file.target_reached()) { + return Ok(false); + } + // TODO: Could try to find out if the server is in the live config + Ok(true) + } + + fn execute(&self) -> Result<(), Self::Error> { + try!(self.file.execute()); + try!(self.command_runner.run_with_args("systemctl", &["reload-or-restart", "nginx"])); + Ok(()) + } +} + +impl<'a, C> fmt::Display for NginxServer<'a, C> where C: Deref { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{ + write!(f, "Nginx server config") + } +} diff --git a/src/symbols/npm.rs b/src/symbols/npm.rs new file mode 100644 index 0000000..80092df --- /dev/null +++ b/src/symbols/npm.rs @@ -0,0 +1,42 @@ +use std::fmt; +use std::io; + +use command_runner::CommandRunner; +use symbols::Symbol; + +pub struct NpmInstall<'a> { + target: &'a str, + command_runner: &'a CommandRunner +} + +impl<'a> NpmInstall<'a> { + pub fn new(target: &'a str, command_runner: &'a CommandRunner) -> NpmInstall<'a> { + NpmInstall { + target: target, + command_runner: command_runner + } + } +} + +impl<'a> fmt::Display for NpmInstall<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "npm install in {}", self.target) + } +} + +impl<'a> Symbol for NpmInstall<'a> { + type Error = io::Error; + fn target_reached(&self) -> Result { + let result = try!(self.command_runner.run_with_args("sh", &["-c", &format!("cd '{}' && npm ls", self.target)])); + Ok(result.status.success() && !String::from_utf8(result.stdout).unwrap().contains("(empty)")) + } + + fn execute(&self) -> Result<(), Self::Error> { + try!(self.command_runner.run_with_args("sh", &["-c", &format!("cd '{}' && npm install --production", self.target)])); + Ok(()) + } +} + +#[cfg(test)] +mod test { +} diff --git a/src/symbols/systemd/node_js_user_service.rs b/src/symbols/systemd/node_js_user_service.rs index 63e2f82..8e89bbd 100644 --- a/src/symbols/systemd/node_js_user_service.rs +++ b/src/symbols/systemd/node_js_user_service.rs @@ -1,6 +1,9 @@ use std::error::Error; +use std::os::unix::fs::PermissionsExt; use std::fmt; use std::io; +use std::fs; +use std::process::Output; use std::path::Path; use std::thread::sleep; use std::time::Duration; @@ -12,6 +15,7 @@ use symbols::file::File as FileSymbol; #[derive(Debug)] pub enum NodeJsSystemdUserServiceError { + ActivationFailed(io::Result), ExecError(E), GenericError } @@ -26,7 +30,8 @@ impl Error for NodeJsSystemdUserServiceError { fn description(&self) -> &str { match self { &NodeJsSystemdUserServiceError::ExecError(ref e) => e.description(), - &NodeJsSystemdUserServiceError::GenericError => "Generic error" + &NodeJsSystemdUserServiceError::GenericError => "Generic error", + &NodeJsSystemdUserServiceError::ActivationFailed(_) => "Activation of service failed" } } fn cause(&self) -> Option<&Error> { @@ -39,12 +44,17 @@ impl Error for NodeJsSystemdUserServiceError { impl fmt::Display for NodeJsSystemdUserServiceError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - write!(f, "{}", self.description()) + try!(write!(f, "{}", self.description())); + if let &NodeJsSystemdUserServiceError::ActivationFailed(Ok(ref log)) = self { + try!(write!(f, ": {:?}", log)); + }; + Ok(()) } } pub struct NodeJsSystemdUserService<'a, P, C> where P: AsRef + fmt::Display, C: Deref { name: &'a str, + home: &'a str, path: P, command_runner: &'a CommandRunner, file: FileSymbol> @@ -53,8 +63,7 @@ pub struct NodeJsSystemdUserService<'a, P, C> where P: AsRef + fmt::Display use std::borrow::Cow; impl<'a> NodeJsSystemdUserService<'a, Cow<'a, str>, String> { - pub fn new(name: &'a str, path: &'a str, command_runner: &'a CommandRunner) -> Self { - let home = String::from_utf8(command_runner.run_with_args("sh", &["-c", "echo \"$HOME\""]).unwrap().stdout).unwrap(); + pub fn new(home: &'a str, name: &'a str, path: &'a str, command_runner: &'a CommandRunner) -> Self { let file_path: Cow = Cow::from(String::from(home.trim_right()) + "/.config/systemd/user/" + name + ".service"); let content = format!("[Service] @@ -68,6 +77,7 @@ WantedBy=default.target ", path, home); NodeJsSystemdUserService { name: name, + home: home, path: file_path.clone(), command_runner: command_runner, file: FileSymbol::new(file_path, content) @@ -75,19 +85,8 @@ WantedBy=default.target } } -impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef + fmt::Display, C: Deref { - type Error = NodeJsSystemdUserServiceError; - fn target_reached(&self) -> Result { - match self.file.target_reached() { - Ok(false) => return Ok(false), - Ok(true) => {}, - Err(e) => return Err(NodeJsSystemdUserServiceError::GenericError) - } -/* - if !(try!(self.file.target_reached())) { - return Ok(false) - } -*/ +impl<'a, P, C> NodeJsSystemdUserService<'a, P, C> where P: AsRef + fmt::Display, C: Deref { + fn check_if_service(&self) -> Result::Error> { loop { // Check if service is registered let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.name])); @@ -98,12 +97,33 @@ impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef 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(NodeJsSystemdUserServiceError::ActivationFailed(self.command_runner.run_with_args("journalctl", &["--user", &format!("--user-unit={}", self.name)]))), _ => return Ok(false) } } } +} + +impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef + fmt::Display, C: Deref { + type Error = NodeJsSystemdUserServiceError; + fn target_reached(&self) -> Result { + match self.file.target_reached() { + Ok(false) => return Ok(false), + Ok(true) => {}, + Err(e) => return Err(NodeJsSystemdUserServiceError::GenericError) + } +/* + if !(try!(self.file.target_reached())) { + return Ok(false) + } +*/ + self.check_if_service() + } fn execute(&self) -> Result<(), Self::Error> { + try!(self.command_runner.run_with_args("mkdir", &["-p", &format!("{}/var", self.home)])); + try!(self.command_runner.run_with_args("rm", &[&format!("{}/var/service.socket", self.home)])); + try!(self.command_runner.run_with_args("mkdir", &["-p", Path::new(self.path.as_ref()).parent().unwrap().to_str().unwrap()])); // FIXME: Permissions // try!(create_dir_all(Path::new(&path).parent().unwrap())); @@ -113,6 +133,18 @@ impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef } try!(self.command_runner.run_with_args("systemctl", &["--user", "enable", self.name])); try!(self.command_runner.run_with_args("systemctl", &["--user", "start", self.name])); + + if !(try!(self.check_if_service())) { return Err(NodeJsSystemdUserServiceError::GenericError); } + + let file_name = format!("{}/var/service.socket", self.home); +// try!(self.command_runner.run_with_args("chmod", &["666", &file_name])); + + sleep(Duration::from_millis(500)); + let metadata = try!(fs::metadata(file_name.clone())); + let mut perms = metadata.permissions(); + perms.set_mode(0o666); + try!(fs::set_permissions(file_name, perms)); + Ok(()) } }