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.

161 lines
5.5 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
  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. ExecStart=/usr/bin/nodejs {0}
  63. Restart=always
  64. Environment=NODE_ENV=production
  65. Environment=PORT=/var/tmp/{1}-{2}.socket
  66. #RuntimeDirectory=service
  67. #RuntimeDirectoryMode=766
  68. [Install]
  69. WantedBy=default.target
  70. ", path, user_name, name);
  71. NodeJsSystemdUserService {
  72. name: name,
  73. user_name: user_name,
  74. path: file_path.clone(),
  75. command_runner: command_runner,
  76. file: FileSymbol::new(file_path, content)
  77. }
  78. }
  79. }
  80. impl<'a, P, C> NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  81. fn check_if_service(&self) -> Result<bool, Box<Error>> {
  82. loop {
  83. // Check if service is registered
  84. let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.name]));
  85. if !active_state.status.success() {
  86. return Err(String::from_utf8(active_state.stderr).unwrap().trim_right().into());
  87. }
  88. // Check if service is running
  89. match String::from_utf8(active_state.stdout).unwrap().trim_right() {
  90. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  91. "ActiveState=active" => return Ok(true),
  92. "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>)),
  93. _ => return Ok(false)
  94. }
  95. }
  96. }
  97. }
  98. impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  99. fn target_reached(&self) -> Result<bool, Box<Error>> {
  100. match self.file.target_reached() {
  101. Ok(false) => return Ok(false),
  102. Ok(true) => {},
  103. Err(e) => return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>))
  104. }
  105. /*
  106. if !(try!(self.file.target_reached())) {
  107. return Ok(false)
  108. }
  109. */
  110. self.check_if_service()
  111. }
  112. fn execute(&self) -> Result<(), Box<Error>> {
  113. try!(self.command_runner.run_with_args("mkdir", &["-p", Path::new(self.path.as_ref()).parent().unwrap().to_str().unwrap()]));
  114. // FIXME: Permissions
  115. // try!(create_dir_all(Path::new(&path).parent().unwrap()));
  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. sleep(Duration::from_millis(500));
  126. let metadata = try!(fs::metadata(file_name.clone()));
  127. let mut perms = metadata.permissions();
  128. perms.set_mode(0o666);
  129. try!(fs::set_permissions(file_name, perms));
  130. Ok(())
  131. }
  132. /* // FIXME
  133. fn get_prerequisites(&self) -> Vec<Box<Resource>> {
  134. self.file.get_prerequisites()
  135. }
  136. */
  137. }
  138. impl<'a, P, C> fmt::Display for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  139. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
  140. write!(f, "Systemd Node.js user service unit for {}", self.path)
  141. }
  142. }