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.

176 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
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 resources::{ FileResource, Resource };
  13. use symbols::Symbol;
  14. use symbols::file::File as FileSymbol;
  15. #[derive(Debug)]
  16. pub enum NodeJsSystemdUserServiceError<E: Error> {
  17. ActivationFailed(io::Result<Output>),
  18. ExecError(E),
  19. GenericError
  20. }
  21. impl From<io::Error> for NodeJsSystemdUserServiceError<io::Error> {
  22. fn from(err: io::Error) -> NodeJsSystemdUserServiceError<io::Error> {
  23. NodeJsSystemdUserServiceError::ExecError(err)
  24. }
  25. }
  26. impl<E: Error> Error for NodeJsSystemdUserServiceError<E> {
  27. fn description(&self) -> &str {
  28. match self {
  29. &NodeJsSystemdUserServiceError::ExecError(ref e) => e.description(),
  30. &NodeJsSystemdUserServiceError::GenericError => "Generic error",
  31. &NodeJsSystemdUserServiceError::ActivationFailed(_) => "Activation of service failed"
  32. }
  33. }
  34. fn cause(&self) -> Option<&Error> {
  35. match self {
  36. &NodeJsSystemdUserServiceError::ExecError(ref e) => Some(e),
  37. _ => None
  38. }
  39. }
  40. }
  41. impl<E: Error> fmt::Display for NodeJsSystemdUserServiceError<E> {
  42. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  43. try!(write!(f, "{}", self.description()));
  44. if let &NodeJsSystemdUserServiceError::ActivationFailed(Ok(ref log)) = self {
  45. try!(write!(f, ": {:?}", log));
  46. };
  47. Ok(())
  48. }
  49. }
  50. pub struct NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  51. name: &'a str,
  52. user_name: &'a str,
  53. path: P,
  54. command_runner: &'a CommandRunner,
  55. file: FileSymbol<C, Cow<'a, str>>
  56. }
  57. use std::borrow::Cow;
  58. impl<'a> NodeJsSystemdUserService<'a, Cow<'a, str>, String> {
  59. pub fn new(home: &'a str, user_name: &'a str, name: &'a str, path: &'a str, command_runner: &'a CommandRunner) -> Self {
  60. let file_path: Cow<str> = Cow::from(String::from(home.trim_right()) + "/.config/systemd/user/" + name + ".service");
  61. let content = format!("[Service]
  62. ExecStartPre=rm /var/tmp/{1}-{2}.socket
  63. # This only works if the path is a directory
  64. WorkingDirectory={0}
  65. ExecStart=/usr/bin/nodejs {0}
  66. Restart=always
  67. Environment=NODE_ENV=production
  68. Environment=PORT=/var/tmp/{1}-{2}.socket
  69. #RuntimeDirectory=service
  70. #RuntimeDirectoryMode=766
  71. [Install]
  72. WantedBy=default.target
  73. ", path, user_name, name);
  74. NodeJsSystemdUserService {
  75. name: name,
  76. user_name: user_name,
  77. path: file_path.clone(),
  78. command_runner: command_runner,
  79. file: FileSymbol::new(file_path, content)
  80. }
  81. }
  82. }
  83. impl<'a, P, C> NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  84. fn check_if_service(&self) -> Result<bool, Box<Error>> {
  85. loop {
  86. // Check if service is registered
  87. let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.name]));
  88. if !active_state.status.success() {
  89. return Err(String::from_utf8(active_state.stderr).unwrap().trim_right().into());
  90. }
  91. // Check if service is running
  92. match String::from_utf8(active_state.stdout).unwrap().trim_right() {
  93. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  94. "ActiveState=active" => return Ok(true),
  95. "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>)),
  96. _ => return Ok(false)
  97. }
  98. }
  99. }
  100. }
  101. impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  102. fn target_reached(&self) -> Result<bool, Box<Error>> {
  103. match self.file.target_reached() {
  104. Ok(false) => return Ok(false),
  105. Ok(true) => {},
  106. Err(e) => return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>))
  107. }
  108. /*
  109. if !(try!(self.file.target_reached())) {
  110. return Ok(false)
  111. }
  112. */
  113. self.check_if_service()
  114. }
  115. fn execute(&self) -> Result<(), Box<Error>> {
  116. match self.file.execute() {
  117. Ok(_) => {},
  118. Err(e) => return Err(e)
  119. }
  120. try!(self.command_runner.run_with_args("systemctl", &["--user", "enable", self.name]));
  121. try!(self.command_runner.run_with_args("systemctl", &["--user", "start", self.name]));
  122. if !(try!(self.check_if_service())) { return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>)); }
  123. let file_name = format!("/var/tmp/{}-{}.socket", self.user_name, self.name);
  124. // try!(self.command_runner.run_with_args("chmod", &["666", &file_name]));
  125. let mut tries = 5;
  126. loop {
  127. let metadata = fs::metadata(file_name.clone());
  128. match metadata {
  129. Ok(metadata) => {
  130. let mut perms = metadata.permissions();
  131. perms.set_mode(0o666);
  132. try!(fs::set_permissions(file_name, perms));
  133. break;
  134. },
  135. Err(e) => {
  136. if e.kind() == io::ErrorKind::NotFound {
  137. tries -= 1;
  138. if tries == 0 { return Err("Gave up waiting for socket to appear".to_string().into()); }
  139. sleep(Duration::from_millis(500));
  140. } else {
  141. return Err(Box::new(e));
  142. }
  143. }
  144. }
  145. }
  146. Ok(())
  147. }
  148. fn get_prerequisites(&self) -> Vec<Box<Resource>> {
  149. let mut r: Vec<Box<Resource>> = vec![ Box::new(FileResource { path: ("/var/lib/systemd/linger/".to_string() + self.user_name).into() }) ];
  150. r.extend(self.file.get_prerequisites().into_iter());
  151. r
  152. }
  153. }
  154. impl<'a, P, C> fmt::Display for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  155. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
  156. write!(f, "Systemd Node.js user service unit for {}", self.path)
  157. }
  158. }