A library for writing host-specific, single-binary configuration management and deployment tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

155 lines
5.4 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. use std::error::Error;
  2. use std::os::unix::fs::PermissionsExt;
  3. use std::fmt;
  4. use std::io;
  5. use std::fs;
  6. use std::process::Output;
  7. use std::path::Path;
  8. use std::thread::sleep;
  9. use std::time::Duration;
  10. use std::ops::Deref;
  11. use command_runner::CommandRunner;
  12. use symbols::Symbol;
  13. use symbols::file::File as FileSymbol;
  14. #[derive(Debug)]
  15. pub enum NodeJsSystemdUserServiceError<E: Error> {
  16. ActivationFailed(io::Result<Output>),
  17. ExecError(E),
  18. GenericError
  19. }
  20. impl From<io::Error> for NodeJsSystemdUserServiceError<io::Error> {
  21. fn from(err: io::Error) -> NodeJsSystemdUserServiceError<io::Error> {
  22. NodeJsSystemdUserServiceError::ExecError(err)
  23. }
  24. }
  25. impl<E: Error> Error for NodeJsSystemdUserServiceError<E> {
  26. fn description(&self) -> &str {
  27. match self {
  28. &NodeJsSystemdUserServiceError::ExecError(ref e) => e.description(),
  29. &NodeJsSystemdUserServiceError::GenericError => "Generic error",
  30. &NodeJsSystemdUserServiceError::ActivationFailed(_) => "Activation of service failed"
  31. }
  32. }
  33. fn cause(&self) -> Option<&Error> {
  34. match self {
  35. &NodeJsSystemdUserServiceError::ExecError(ref e) => Some(e),
  36. _ => None
  37. }
  38. }
  39. }
  40. impl<E: Error> fmt::Display for NodeJsSystemdUserServiceError<E> {
  41. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  42. try!(write!(f, "{}", self.description()));
  43. if let &NodeJsSystemdUserServiceError::ActivationFailed(Ok(ref log)) = self {
  44. try!(write!(f, ": {:?}", log));
  45. };
  46. Ok(())
  47. }
  48. }
  49. pub struct NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  50. name: &'a str,
  51. home: &'a str,
  52. path: P,
  53. command_runner: &'a CommandRunner,
  54. file: FileSymbol<C, Cow<'a, str>>
  55. }
  56. use std::borrow::Cow;
  57. impl<'a> NodeJsSystemdUserService<'a, Cow<'a, str>, String> {
  58. pub fn new(home: &'a str, name: &'a str, path: &'a str, command_runner: &'a CommandRunner) -> Self {
  59. let file_path: Cow<str> = Cow::from(String::from(home.trim_right()) + "/.config/systemd/user/" + name + ".service");
  60. let content = format!("[Service]
  61. ExecStart=/usr/bin/nodejs {}
  62. Restart=always
  63. Environment=NODE_ENV=production
  64. Environment=PORT={}/var/service.socket
  65. [Install]
  66. WantedBy=default.target
  67. ", path, home);
  68. NodeJsSystemdUserService {
  69. name: name,
  70. home: home,
  71. path: file_path.clone(),
  72. command_runner: command_runner,
  73. file: FileSymbol::new(file_path, content)
  74. }
  75. }
  76. }
  77. impl<'a, P, C> NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  78. fn check_if_service(&self) -> Result<bool, Box<Error>> {
  79. loop {
  80. // Check if service is registered
  81. let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.name]));
  82. if !active_state.status.success() {
  83. return Ok(false);
  84. }
  85. // Check if service is running
  86. match String::from_utf8(active_state.stdout).unwrap().trim_right() {
  87. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  88. "ActiveState=active" => return Ok(true),
  89. "ActiveState=failed" => return Err(Box::new(NodeJsSystemdUserServiceError::ActivationFailed(self.command_runner.run_with_args("journalctl", &["--user", &format!("--user-unit={}", self.name)])) as NodeJsSystemdUserServiceError<io::Error>)),
  90. _ => return Ok(false)
  91. }
  92. }
  93. }
  94. }
  95. impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  96. fn target_reached(&self) -> Result<bool, Box<Error>> {
  97. match self.file.target_reached() {
  98. Ok(false) => return Ok(false),
  99. Ok(true) => {},
  100. Err(e) => return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>))
  101. }
  102. /*
  103. if !(try!(self.file.target_reached())) {
  104. return Ok(false)
  105. }
  106. */
  107. self.check_if_service()
  108. }
  109. fn execute(&self) -> Result<(), Box<Error>> {
  110. try!(self.command_runner.run_with_args("mkdir", &["-p", &format!("{}/var", self.home)]));
  111. try!(self.command_runner.run_with_args("rm", &[&format!("{}/var/service.socket", self.home)]));
  112. try!(self.command_runner.run_with_args("mkdir", &["-p", Path::new(self.path.as_ref()).parent().unwrap().to_str().unwrap()]));
  113. // FIXME: Permissions
  114. // try!(create_dir_all(Path::new(&path).parent().unwrap()));
  115. match self.file.execute() {
  116. Ok(_) => {},
  117. Err(e) => return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>))
  118. }
  119. try!(self.command_runner.run_with_args("systemctl", &["--user", "enable", self.name]));
  120. try!(self.command_runner.run_with_args("systemctl", &["--user", "start", self.name]));
  121. if !(try!(self.check_if_service())) { return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>)); }
  122. let file_name = format!("{}/var/service.socket", self.home);
  123. // try!(self.command_runner.run_with_args("chmod", &["666", &file_name]));
  124. sleep(Duration::from_millis(500));
  125. let metadata = try!(fs::metadata(file_name.clone()));
  126. let mut perms = metadata.permissions();
  127. perms.set_mode(0o666);
  128. try!(fs::set_permissions(file_name, perms));
  129. Ok(())
  130. }
  131. }
  132. impl<'a, P, C> fmt::Display for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  133. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
  134. write!(f, "Systemd Node.js user service unit for {}", self.path)
  135. }
  136. }