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.

178 lines
5.9 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
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. user_name: &'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, user_name: &'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. ExecStartPre=rm /var/tmp/{1}-{2}.socket
  62. # This only works if the path is a directory
  63. WorkingDirectory={0}
  64. ExecStart=/usr/bin/nodejs {0}
  65. Restart=always
  66. Environment=NODE_ENV=production
  67. Environment=PORT=/var/tmp/{1}-{2}.socket
  68. #RuntimeDirectory=service
  69. #RuntimeDirectoryMode=766
  70. [Install]
  71. WantedBy=default.target
  72. ", path, user_name, name);
  73. NodeJsSystemdUserService {
  74. name: name,
  75. user_name: user_name,
  76. path: file_path.clone(),
  77. command_runner: command_runner,
  78. file: FileSymbol::new(file_path, content)
  79. }
  80. }
  81. }
  82. impl<'a, P, C> NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  83. fn check_if_service(&self) -> Result<bool, Box<Error>> {
  84. loop {
  85. // Check if service is registered
  86. let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.name]));
  87. if !active_state.status.success() {
  88. return Err(String::from_utf8(active_state.stderr).unwrap().trim_right().into());
  89. }
  90. // Check if service is running
  91. match String::from_utf8(active_state.stdout).unwrap().trim_right() {
  92. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  93. "ActiveState=active" => return Ok(true),
  94. "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>)),
  95. _ => return Ok(false)
  96. }
  97. }
  98. }
  99. }
  100. impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  101. fn target_reached(&self) -> Result<bool, Box<Error>> {
  102. match self.file.target_reached() {
  103. Ok(false) => return Ok(false),
  104. Ok(true) => {},
  105. Err(e) => return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>))
  106. }
  107. /*
  108. if !(try!(self.file.target_reached())) {
  109. return Ok(false)
  110. }
  111. */
  112. self.check_if_service()
  113. }
  114. fn execute(&self) -> Result<(), Box<Error>> {
  115. try!(self.command_runner.run_with_args("mkdir", &["-p", Path::new(self.path.as_ref()).parent().unwrap().to_str().unwrap()]));
  116. // FIXME: Permissions
  117. // try!(create_dir_all(Path::new(&path).parent().unwrap()));
  118. match self.file.execute() {
  119. Ok(_) => {},
  120. Err(e) => return Err(e)
  121. }
  122. try!(self.command_runner.run_with_args("systemctl", &["--user", "enable", self.name]));
  123. try!(self.command_runner.run_with_args("systemctl", &["--user", "start", self.name]));
  124. if !(try!(self.check_if_service())) { return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>)); }
  125. let file_name = format!("/var/tmp/{}-{}.socket", self.user_name, self.name);
  126. // try!(self.command_runner.run_with_args("chmod", &["666", &file_name]));
  127. let mut tries = 5;
  128. loop {
  129. let metadata = fs::metadata(file_name.clone());
  130. match metadata {
  131. Ok(metadata) => {
  132. let mut perms = metadata.permissions();
  133. perms.set_mode(0o666);
  134. try!(fs::set_permissions(file_name, perms));
  135. break;
  136. },
  137. Err(e) => {
  138. if e.kind() == io::ErrorKind::NotFound {
  139. tries -= 1;
  140. if tries == 0 { return Err("Gave up waiting for socket to appear".to_string().into()); }
  141. sleep(Duration::from_millis(500));
  142. } else {
  143. return Err(Box::new(e));
  144. }
  145. }
  146. }
  147. }
  148. Ok(())
  149. }
  150. /* // FIXME
  151. fn get_prerequisites(&self) -> Vec<Box<Resource>> {
  152. self.file.get_prerequisites()
  153. }
  154. */
  155. }
  156. impl<'a, P, C> fmt::Display for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  157. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
  158. write!(f, "Systemd Node.js user service unit for {}", self.path)
  159. }
  160. }