Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions crates/cardwire-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ async fn main() -> anyhow::Result<()> {
}
} else {
let mut map = std::collections::BTreeMap::new();
let objects = client.get_managed_objects().await.unwrap_or_default();
let objects = match client.get_managed_objects().await {
Ok(objects) => objects,
Err(e) => handle_error(e.into()),
};
for (path, interfaces) in objects {
let path_str = path.as_str();
if let Some(id_str) =
Expand Down Expand Up @@ -376,7 +379,7 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}

fn handle_error(err: zbus::Error) {
fn handle_error(err: zbus::Error) -> ! {
match err {
zbus::Error::MethodError(name, description, _) => {
if let Some(msg) = description {
Expand All @@ -397,4 +400,5 @@ fn handle_error(err: zbus::Error) {
},
_ => eprintln!("{}", err),
}
std::process::exit(1)
}
22 changes: 22 additions & 0 deletions crates/cardwire-daemon/src/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,28 @@ async fn main() -> Result<()> {
}
};

// Give the shim its signal emitter so it can notify clients (e.g. gnome) when the GPU list
// changes
if let Some(switcheroo_conn) = _conn.as_ref() {
match switcheroo_conn
.object_server()
.interface::<_, crate::interface::SwitcherooInterface>("/net/hadess/SwitcherooControl")
.await
{
Ok(switcheroo_ref) => {
daemon
.switcheroo_interface
.signal_emitter
.get_or_init(|| switcheroo_ref.signal_emitter().to_owned());
}
Err(e) => {
log::warn!(
"Failed to get the Switcheroo shim interface ({e}); GPU change notifications will not be emitted"
);
}
}
}

let object_server: &zbus::ObjectServer = conn.object_server();
spawn_dbus_api(object_server, &mut daemon).await?;
// Spawn background tasks
Expand Down
96 changes: 84 additions & 12 deletions crates/cardwire-daemon/src/file/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ use crate::{
file::common::{FileKind, create_default_file}, interface::Modes
};
use anyhow::Context;
use log::warn;
use tokio::io::AsyncWriteExt;

use serde::{Deserialize, Serialize};
use std::{fs, io};
use std::{
fs, io, time::{SystemTime, UNIX_EPOCH}
};
const CONFIG_PATH: &str = "/etc/cardwire";

#[derive(Deserialize, Serialize, Debug)]
Expand Down Expand Up @@ -49,31 +53,78 @@ impl CardwireConfig {
/// Read TOML config file and return it's settings as a struct
pub fn build() -> anyhow::Result<CardwireConfig> {
let config_file = format!("{}/cardwire.toml", CONFIG_PATH);
Self::parse_config(&config_file)
}
/// Parse the .toml file into a CardwireConfig
fn parse_config(config_file: &str) -> anyhow::Result<CardwireConfig> {
// create the config if it doesnt exist
if !(fs::exists(config_file)?) {
if !(fs::exists(&config_file)?) {
Self::create_default_config().context("Could not create default dir for config")?;
}
// remove leftover temp files from a save interrupted by a crash
Self::cleanup_stale_tmp_files();
// read the config into a string and parse it
let config_content =
fs::read_to_string(config_file).context("Could not read cardwire.toml")?;
toml::from_str(&config_content).context("Failed to parse the toml config")
fs::read_to_string(&config_file).context("Could not read cardwire.toml")?;
Ok(Self::parse_or_default(&config_content))
}
/// Remove leftover cardwire.toml.*.tmp files from a save interrupted by a crash
fn cleanup_stale_tmp_files() {
let Ok(entries) = fs::read_dir(CONFIG_PATH) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with("cardwire.toml.") && name.ends_with(".tmp") {
let _ = fs::remove_file(entry.path());
}
}
}
/// Parse the .toml content into a CardwireConfig, on parse failure fall back to
/// defaults instead of taking the daemon down, leaving the broken file untouched
fn parse_or_default(config_content: &str) -> CardwireConfig {
match toml::from_str(config_content) {
Ok(config) => config,
Err(e) => {
warn!(
"Failed to parse cardwire.toml ({e}); running with default settings, fix the file and restart the daemon"
);
CardwireConfig::default()
}
}
}
/// Create a default cardwire.toml if not present
fn create_default_config() -> anyhow::Result<()> {
create_default_file(FileKind::Config)?;
Ok(())
}
/// Save the config into cardwire.toml
/// Save the config into cardwire.toml, atomically: write to a unique temp file in the same
/// directory (exclusive create so concurrent saves never share a file), fsync, then rename
/// over the target so a crash can't truncate the config
pub async fn save_config(&self) -> io::Result<()> {
let path = format!("{}/cardwire.toml", CONFIG_PATH);
match toml::to_string_pretty(&self) {
Ok(config_toml) => tokio::fs::write(path, config_toml).await,
Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e)),
let unique = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(io::Error::other)?
.as_nanos();
let tmp_path = format!("{}/cardwire.toml.{}.tmp", CONFIG_PATH, unique);
let config_toml = match toml::to_string_pretty(&self) {
Ok(config_toml) => config_toml,
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidData, e)),
};
let result = async {
let mut tmp_file = tokio::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_path)
.await?;
tmp_file.write_all(config_toml.as_bytes()).await?;
tmp_file.sync_all().await?;
drop(tmp_file);
tokio::fs::rename(&tmp_path, &path).await
}
.await;
if result.is_err() {
let _ = tokio::fs::remove_file(&tmp_path).await;
}
result
Comment thread
luytan marked this conversation as resolved.
}
pub fn experimental_nvidia_block(&self) -> bool {
self.experimental_nvidia_block
Expand Down Expand Up @@ -174,4 +225,25 @@ external_display_auto_switch = true
assert_eq!(parsed.battery_auto_switch_mode(), Modes::Smart);
assert!(parsed.external_display_auto_switch());
}

#[test]
fn test_cardwire_config_parse_or_default_on_valid_toml() {
let config = CardwireConfig::parse_or_default(
"auto_apply_gpu_state = false\nbattery_auto_switch_mode = \"smart\"\n",
);
assert!(!config.auto_apply_gpu_state());
assert_eq!(config.battery_auto_switch_mode(), Modes::Smart);
assert!(!config.experimental_nvidia_block());
assert!(!config.external_display_auto_switch());
}

#[test]
fn test_cardwire_config_parse_or_default_on_invalid_toml_uses_defaults() {
let config = CardwireConfig::parse_or_default("this is not [[[ valid toml");
assert!(config.auto_apply_gpu_state());
assert!(!config.experimental_nvidia_block());
assert!(!config.battery_auto_switch());
assert_eq!(config.battery_auto_switch_mode(), Modes::Hybrid);
assert!(!config.external_display_auto_switch());
}
}
7 changes: 7 additions & 0 deletions crates/cardwire-daemon/src/interface/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub struct ConfigMemory {
pub battery_auto_switch: Arc<AtomicBool>,
pub battery_auto_switch_mode: Arc<AtomicU32>,
pub external_display_auto_switch: Arc<AtomicBool>,
save_lock: Arc<tokio::sync::Mutex<()>>,
}
impl ConfigMemory {
/// build a ConfigMemory from CardwireConfig
Expand All @@ -36,6 +37,7 @@ impl ConfigMemory {
battery_auto_switch,
battery_auto_switch_mode,
external_display_auto_switch,
save_lock: Arc::new(tokio::sync::Mutex::new(())),
}
}
}
Expand Down Expand Up @@ -111,6 +113,8 @@ impl ConfigInterface {
}
#[zbus(property)]
pub async fn set_battery_auto_switch_mode(&self, mode: u32) -> fdo::Result<()> {
// Validate before storing so an invalid value can't poison the in-memory state
Modes::try_from(mode).map_err(|err| fdo::Error::InvalidArgs(err.to_string()))?;
self.config
.battery_auto_switch_mode
.store(mode, Ordering::Relaxed);
Expand All @@ -119,6 +123,9 @@ impl ConfigInterface {
}
/// Save the daemon's configuration to cardwire.toml
pub async fn save_to_file(&self) -> fdo::Result<()> {
// Serialize saves so concurrent setters can't interleave writes and the final file
// always reflects the last stored state
let _save_guard = self.config.save_lock.lock().await;
// Include monitor-owned settings whenever any D-Bus property rewrites the whole file.
let config = CardwireConfig::new(
self.config.auto_apply_gpu_state.load(Ordering::Relaxed),
Expand Down
6 changes: 5 additions & 1 deletion crates/cardwire-daemon/src/interface/debug.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
core::{
gpu::GpuEnumerator, pci::{self, DbusPciDevice, PciDevice}
}, tasks::watch_power_state
}, interface::SwitcherooInterface, tasks::watch_power_state
};
use cardwire_ebpf_userspace::EbpfBlocker;
use log::{info, warn};
Expand All @@ -24,6 +24,7 @@ pub struct DebugInterface {
pub pci_list: Arc<RwLock<BTreeMap<String, PciDevice>>>,
pub object_server: Option<zbus::ObjectServer>,
pub power_tasks: Arc<RwLock<BTreeMap<usize, task::JoinHandle<anyhow::Result<()>>>>>,
pub switcheroo: SwitcherooInterface,
}
impl DebugInterface {
#[allow(clippy::too_many_arguments)]
Expand All @@ -37,6 +38,7 @@ impl DebugInterface {
pci_list: Arc<RwLock<BTreeMap<String, PciDevice>>>,
object_server: Option<zbus::ObjectServer>,
power_tasks: Arc<RwLock<BTreeMap<usize, task::JoinHandle<anyhow::Result<()>>>>>,
switcheroo: SwitcherooInterface,
) -> anyhow::Result<DebugInterface> {
Ok(DebugInterface {
mode_state,
Expand All @@ -48,6 +50,7 @@ impl DebugInterface {
pci_list,
object_server,
power_tasks,
switcheroo,
})
}
}
Expand Down Expand Up @@ -155,6 +158,7 @@ impl DebugInterface {
warn!("failed to re-apply mode on hotplug: {e}");
return Err(e);
}
self.switcheroo.emit_gpu_list_changed().await;
}

Ok(())
Expand Down
4 changes: 2 additions & 2 deletions crates/cardwire-daemon/src/interface/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ impl GpuInterface {
// now get fd directory
let fd_dir: PathBuf = read_dir(&path)
.map_err(|e| fdo::Error::IOError(e.to_string()))?
.filter(|r| r.is_ok())
.map(|r| r.unwrap().path())
.flatten()
.map(|r| r.path())
.filter(|r| r.file_name() == Some(OsStr::new("fd")))
.collect();
for entry in read_dir(fd_dir)
Expand Down
Loading