-
Notifications
You must be signed in to change notification settings - Fork 10
fix: detect systemd unit directory at runtime for cross-distro compatibility #35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -6,7 +6,7 @@ use std::process::Command; | |||||
| use std::sync::mpsc; | ||||||
|
|
||||||
| use ctrlc; | ||||||
| use log::{debug, info}; | ||||||
| use log::{debug, info, warn}; | ||||||
|
|
||||||
| use crate::controller::{ControllerInterface, ServiceMainFn}; | ||||||
| use crate::session; | ||||||
|
|
@@ -53,12 +53,8 @@ fn systemd_install_daemon(name: &str) -> Result<(), Error> { | |||||
|
|
||||||
| fn systemd_uninstall_daemon(name: &str) -> Result<(), Error> { | ||||||
| systemctl_execute(&["disable", name])?; | ||||||
| systemctl_execute(&["daemon-reload"]) | ||||||
| .map_err(|e| debug!("{}", e)) | ||||||
| .ok(); | ||||||
| systemctl_execute(&["reset-failed"]) | ||||||
| .map_err(|e| debug!("{}", e)) | ||||||
| .ok(); | ||||||
| systemctl_execute(&["daemon-reload"]).map_err(|e| debug!("{}", e)).ok(); | ||||||
| systemctl_execute(&["reset-failed"]).map_err(|e| debug!("{}", e)).ok(); | ||||||
|
|
||||||
| Ok(()) | ||||||
| } | ||||||
|
|
@@ -71,6 +67,80 @@ fn systemd_stop_daemon(name: &str) -> Result<(), Error> { | |||||
| systemctl_execute(&["stop", name]) | ||||||
| } | ||||||
|
|
||||||
| /// Detect the systemd system unit directory at runtime. | ||||||
| /// | ||||||
| /// # Rationale | ||||||
| /// | ||||||
| /// This isn't the best approach for Linux — packagers should normally choose the | ||||||
| /// destination and rely on distro tooling (e.g., Debian's dh_installsystemd or | ||||||
| /// RPM's %{_unitdir} macros). Using pkg-config at build/packaging time is a | ||||||
| /// pragmatic, good-enough approach in many situations to discover the vendor | ||||||
| /// unit dir without hardcoding paths. | ||||||
| /// | ||||||
| /// # Caveat | ||||||
| /// | ||||||
| /// We can't automatically determine whether it should go into user/ or | ||||||
| /// system/, and we default to system/. Use CEVICHE_SYSTEMD_UNITDIR if you need | ||||||
| /// to override this behavior. | ||||||
| /// | ||||||
| /// # Detection order | ||||||
| /// | ||||||
| /// 1. CEVICHE_SYSTEMD_UNITDIR environment variable (takes precedence) | ||||||
| /// 2. pkg-config --variable=systemdsystemunitdir systemd | ||||||
| /// 3. Fallback probing: /usr/lib/systemd/system, then /lib/systemd/system | ||||||
| fn detect_systemd_unit_dir() -> Result<PathBuf, Error> { | ||||||
| // 1. Check for environment variable override. | ||||||
| if let Ok(dir) = env::var("CEVICHE_SYSTEMD_UNITDIR") { | ||||||
| if !dir.is_empty() { | ||||||
| info!("Using systemd unit directory from CEVICHE_SYSTEMD_UNITDIR: {dir}"); | ||||||
| return Ok(PathBuf::from(dir)); | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| // 2. Try pkg-config. | ||||||
| match Command::new("pkg-config") | ||||||
| .args(["--variable=systemdsystemunitdir", "systemd"]) | ||||||
| .output() | ||||||
| { | ||||||
| Ok(output) if output.status.success() => { | ||||||
| let dir = String::from_utf8_lossy(&output.stdout).trim().to_string(); | ||||||
| if !dir.is_empty() { | ||||||
| info!("Detected systemd unit directory via pkg-config: {dir}"); | ||||||
| return Ok(PathBuf::from(dir)); | ||||||
| } | ||||||
| } | ||||||
| Ok(_) => { | ||||||
| debug!("pkg-config returned no systemd unit directory"); | ||||||
| } | ||||||
| Err(e) => { | ||||||
| debug!("pkg-config not available or failed: {e}"); | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| // 3. Fallback: probe common directories. | ||||||
| warn!( | ||||||
| "pkg-config unavailable or didn't return a systemd unit directory. \ | ||||||
| Falling back to heuristic probing of common vendor directories. \ | ||||||
| This may be distro-specific. Consider setting CEVICHE_SYSTEMD_UNITDIR \ | ||||||
| environment variable to specify the correct path." | ||||||
| ); | ||||||
|
|
||||||
| let candidates = ["/usr/lib/systemd/system", "/lib/systemd/system"]; | ||||||
|
|
||||||
| for &candidate in &candidates { | ||||||
| let path = Path::new(candidate); | ||||||
| if path.exists() && path.is_dir() { | ||||||
| info!("Found systemd unit directory via fallback probing: {candidate}"); | ||||||
| return Ok(PathBuf::from(candidate)); | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| Err(Error::new( | ||||||
| "Unable to detect systemd unit directory. \ | ||||||
| Please set CEVICHE_SYSTEMD_UNITDIR environment variable to specify the correct path.", | ||||||
| )) | ||||||
| } | ||||||
|
|
||||||
| pub struct LinuxController { | ||||||
| pub service_name: String, | ||||||
| pub display_name: String, | ||||||
|
|
@@ -88,10 +158,7 @@ impl LinuxController { | |||||
| } | ||||||
| } | ||||||
|
|
||||||
| pub fn register( | ||||||
| &mut self, | ||||||
| service_main_wrapper: LinuxServiceMainWrapperFn, | ||||||
| ) -> Result<(), Error> { | ||||||
| pub fn register(&mut self, service_main_wrapper: LinuxServiceMainWrapperFn) -> Result<(), Error> { | ||||||
| service_main_wrapper(env::args().collect()); | ||||||
| Ok(()) | ||||||
| } | ||||||
|
|
@@ -100,12 +167,14 @@ impl LinuxController { | |||||
| format!("{}.service", &self.service_name) | ||||||
| } | ||||||
|
|
||||||
| fn get_service_unit_path(&self) -> PathBuf { | ||||||
| Path::new("/lib/systemd/system/").join(self.get_service_file_name()) | ||||||
| fn get_service_unit_path(&self) -> Result<PathBuf, Error> { | ||||||
| let unit_dir = detect_systemd_unit_dir()?; | ||||||
| Ok(unit_dir.join(self.get_service_file_name())) | ||||||
| } | ||||||
|
|
||||||
| fn get_service_dropin_dir(&self) -> PathBuf { | ||||||
| Path::new("/lib/systemd/system/").join(format!("{}.d", self.get_service_file_name())) | ||||||
| fn get_service_dropin_dir(&self) -> Result<PathBuf, Error> { | ||||||
| let unit_dir = detect_systemd_unit_dir()?; | ||||||
| Ok(unit_dir.join(format!("{}.d", self.get_service_file_name()))) | ||||||
| } | ||||||
|
|
||||||
| fn get_service_unit_content(&self) -> Result<String, Error> { | ||||||
|
|
@@ -128,21 +197,20 @@ WantedBy=multi-user.target"#, | |||||
| } | ||||||
|
|
||||||
| fn write_service_config(&self) -> Result<(), Error> { | ||||||
| let path = self.get_service_unit_path(); | ||||||
| let path = self.get_service_unit_path()?; | ||||||
| let content = self.get_service_unit_content()?; | ||||||
| info!("Writing service file {}", path.display()); | ||||||
| File::create(&path) | ||||||
| .and_then(|mut file| file.write_all(content.as_bytes())) | ||||||
| .map_err(|e| Error::new(&format!("Failed to write {}: {}", path.display(), e)))?; | ||||||
|
|
||||||
| if let Some(ref config) = self.config { | ||||||
| let dropin_dir = self.get_service_dropin_dir(); | ||||||
| let dropin_dir = self.get_service_dropin_dir()?; | ||||||
| let path = dropin_dir.join(format!("{}.conf", self.service_name)); | ||||||
|
|
||||||
| if !Path::exists(&dropin_dir) { | ||||||
| fs::create_dir(dropin_dir).map_err(|e| { | ||||||
| Error::new(&format!("Failed to create {}: {}", path.display(), e)) | ||||||
| })?; | ||||||
| fs::create_dir(&dropin_dir) | ||||||
| .map_err(|e| Error::new(&format!("Failed to create {}: {}", path.display(), e)))?; | ||||||
|
||||||
| .map_err(|e| Error::new(&format!("Failed to create {}: {}", path.display(), e)))?; | |
| .map_err(|e| Error::new(&format!("Failed to create {}: {}", dropin_dir.display(), e)))?; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
detect_systemd_unit_dir()function is called separately in bothget_service_unit_path()andget_service_dropin_dir(). When both methods are called (e.g., inwrite_service_config()anddelete()), this results in redundant detection work including potential Command execution and filesystem probing. Consider caching the detected directory in theLinuxControllerstruct or calling the detection once at a higher level.