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.

160 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
  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. use resources::Resource;
  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. home: &'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, 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. ExecStart=/usr/bin/nodejs {}
  63. Restart=always
  64. Environment=NODE_ENV=production
  65. Environment=PORT={}/var/service.socket
  66. [Install]
  67. WantedBy=default.target
  68. ", path, home);
  69. NodeJsSystemdUserService {
  70. name: name,
  71. home: home,
  72. path: file_path.clone(),
  73. command_runner: command_runner,
  74. file: FileSymbol::new(file_path, content)
  75. }
  76. }
  77. }
  78. impl<'a, P, C> NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  79. fn check_if_service(&self) -> Result<bool, Box<Error>> {
  80. loop {
  81. // Check if service is registered
  82. let active_state = try!(self.command_runner.run_with_args("systemctl", &["--user", "show", "--property", "ActiveState", self.name]));
  83. if !active_state.status.success() {
  84. return Ok(false);
  85. }
  86. // Check if service is running
  87. match String::from_utf8(active_state.stdout).unwrap().trim_right() {
  88. "ActiveState=activating" => sleep(Duration::from_millis(500)),
  89. "ActiveState=active" => return Ok(true),
  90. "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>)),
  91. _ => return Ok(false)
  92. }
  93. }
  94. }
  95. }
  96. impl<'a, P, C> Symbol for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  97. fn target_reached(&self) -> Result<bool, Box<Error>> {
  98. match self.file.target_reached() {
  99. Ok(false) => return Ok(false),
  100. Ok(true) => {},
  101. Err(e) => return Err(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>))
  102. }
  103. /*
  104. if !(try!(self.file.target_reached())) {
  105. return Ok(false)
  106. }
  107. */
  108. self.check_if_service()
  109. }
  110. fn execute(&self) -> Result<(), Box<Error>> {
  111. try!(self.command_runner.run_with_args("mkdir", &["-p", &format!("{}/var", self.home)]));
  112. try!(self.command_runner.run_with_args("rm", &[&format!("{}/var/service.socket", self.home)]));
  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(Box::new(NodeJsSystemdUserServiceError::GenericError as NodeJsSystemdUserServiceError<io::Error>))
  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/service.socket", self.home);
  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. fn get_prerequisites(&self) -> Vec<Box<Resource>> {
  133. self.file.get_prerequisites()
  134. }
  135. }
  136. impl<'a, P, C> fmt::Display for NodeJsSystemdUserService<'a, P, C> where P: AsRef<str> + fmt::Display, C: Deref<Target=str> {
  137. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error>{
  138. write!(f, "Systemd Node.js user service unit for {}", self.path)
  139. }
  140. }