Browse Source

Update

master
Adrian Heine 8 years ago
parent
commit
301b39a80a
  1. 6
      src/symbols/file.rs
  2. 2
      src/symbols/mod.rs
  3. 1
      src/symbols/nginx/mod.rs
  4. 116
      src/symbols/nginx/server.rs
  5. 42
      src/symbols/npm.rs
  6. 66
      src/symbols/systemd/node_js_user_service.rs

6
src/symbols/file.rs

@ -79,10 +79,8 @@ impl<C, D> Symbol for File<C, D> where C: Deref<Target=str>, D: AsRef<str> + fmt
} }
fn execute(&self) -> Result<(), Self::Error> { 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(()) Ok(())
} }
} }

2
src/symbols/mod.rs

@ -9,5 +9,7 @@ pub trait Symbol: Display {
pub mod file; pub mod file;
pub mod git; pub mod git;
pub mod npm;
pub mod user; pub mod user;
pub mod systemd; pub mod systemd;
pub mod nginx;

1
src/symbols/nginx/mod.rs

@ -0,0 +1 @@
pub mod server;

116
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<E: Error> {
ExecError(E),
GenericError
}
impl<E: Error> From<FileError<E>> for NginxServerError<FileError<E>> {
fn from(err: FileError<E>) -> NginxServerError<FileError<E>> {
NginxServerError::ExecError(err)
}
}
impl<E: Error> From<io::Error> for NginxServerError<FileError<E>> {
fn from(err: io::Error) -> NginxServerError<FileError<E>> {
NginxServerError::GenericError
}
}
impl<E: Error> Error for NginxServerError<E> {
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<E: Error> fmt::Display for NginxServerError<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.description())
}
}
pub struct NginxServer<'a, C> where C: Deref<Target=str> {
command_runner: &'a CommandRunner,
file: FileSymbol<C, Cow<'a, str>>,
}
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<str> = 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<Target=str> {
type Error = NginxServerError<<FileSymbol<C, Cow<'a, str>> as Symbol>::Error>;
fn target_reached(&self) -> Result<bool, Self::Error> {
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<Target=str> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
write!(f, "Nginx server config")
}
}

42
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<bool, Self::Error> {
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 {
}

66
src/symbols/systemd/node_js_user_service.rs

@ -1,6 +1,9 @@
use std::error::Error; use std::error::Error;
use std::os::unix::fs::PermissionsExt;
use std::fmt; use std::fmt;
use std::io; use std::io;
use std::fs;
use std::process::Output;
use std::path::Path; use std::path::Path;
use std::thread::sleep; use std::thread::sleep;
use std::time::Duration; use std::time::Duration;
@ -12,6 +15,7 @@ use symbols::file::File as FileSymbol;
#[derive(Debug)] #[derive(Debug)]
pub enum NodeJsSystemdUserServiceError<E: Error> { pub enum NodeJsSystemdUserServiceError<E: Error> {
ActivationFailed(io::Result<Output>),
ExecError(E), ExecError(E),
GenericError GenericError
} }
@ -26,7 +30,8 @@ impl<E: Error> Error for NodeJsSystemdUserServiceError<E> {
fn description(&self) -> &str { fn description(&self) -> &str {
match self { match self {
&NodeJsSystemdUserServiceError::ExecError(ref e) => e.description(), &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> { fn cause(&self) -> Option<&Error> {
@ -39,12 +44,17 @@ impl<E: Error> Error for NodeJsSystemdUserServiceError<E> {
impl<E: Error> fmt::Display for NodeJsSystemdUserServiceError<E> { impl<E: Error> fmt::Display for NodeJsSystemdUserServiceError<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 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<str> + fmt::Display, C: Deref<Target=str> { pub struct NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
name: &'a str, name: &'a str,
home: &'a str,
path: P, path: P,
command_runner: &'a CommandRunner, command_runner: &'a CommandRunner,
file: FileSymbol<C, Cow<'a, str>> file: FileSymbol<C, Cow<'a, str>>
@ -53,8 +63,7 @@ pub struct NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display
use std::borrow::Cow; use std::borrow::Cow;
impl<'a> NodeJsSystemdUserService<'a, Cow<'a, str>, String> { 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<str> = Cow::from(String::from(home.trim_right()) + "/.config/systemd/user/" + name + ".service"); let file_path: Cow<str> = Cow::from(String::from(home.trim_right()) + "/.config/systemd/user/" + name + ".service");
let content = format!("[Service] let content = format!("[Service]
@ -68,6 +77,7 @@ WantedBy=default.target
", path, home); ", path, home);
NodeJsSystemdUserService { NodeJsSystemdUserService {
name: name, name: name,
home: home,
path: file_path.clone(), path: file_path.clone(),
command_runner: command_runner, command_runner: command_runner,
file: FileSymbol::new(file_path, content) 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<str> + fmt::Display, C: Deref<Target=str> {
type Error = NodeJsSystemdUserServiceError<io::Error>;
fn target_reached(&self) -> Result<bool, Self::Error> {
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<str> + fmt::Display, C: Deref<Target=str> {
fn check_if_service(&self) -> Result<bool, <Self as Symbol>::Error> {
loop { loop {
// Check if service is registered // Check if service is registered
let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.name])); 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<str>
match String::from_utf8(active_state.stdout).unwrap().trim_right() { match String::from_utf8(active_state.stdout).unwrap().trim_right() {
"ActiveState=activating" => sleep(Duration::from_millis(500)), "ActiveState=activating" => sleep(Duration::from_millis(500)),
"ActiveState=active" => return Ok(true), "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) _ => return Ok(false)
} }
} }
} }
}
impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
type Error = NodeJsSystemdUserServiceError<io::Error>;
fn target_reached(&self) -> Result<bool, Self::Error> {
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> { 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()])); try!(self.command_runner.run_with_args("mkdir", &["-p", Path::new(self.path.as_ref()).parent().unwrap().to_str().unwrap()]));
// FIXME: Permissions // FIXME: Permissions
// try!(create_dir_all(Path::new(&path).parent().unwrap())); // 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<str>
} }
try!(self.command_runner.run_with_args("systemctl", &["--user", "enable", self.name])); try!(self.command_runner.run_with_args("systemctl", &["--user", "enable", self.name]));
try!(self.command_runner.run_with_args("systemctl", &["--user", "start", 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(()) Ok(())
} }
} }

Loading…
Cancel
Save