use anyhow::{Context, Error};
use fidl_fuchsia_scheduler::{
RoleManagerMarker, RoleManagerSetRoleRequest, RoleManagerSynchronousProxy, RoleName, RoleTarget,
};
use fuchsia_component::client::connect_to_protocol_sync;
use fuchsia_sync::RwLock;
use std::sync::Arc;
use zx::{HandleBased, MonotonicInstant, Rights, Status, Thread};
static ROLE_MANAGER: RwLock<Option<Arc<RoleManagerSynchronousProxy>>> = RwLock::new(None);
fn connect() -> Result<Arc<RoleManagerSynchronousProxy>, Error> {
if let Some(ref proxy) = *ROLE_MANAGER.read() {
return Ok(Arc::clone(&proxy));
}
let mut proxy = ROLE_MANAGER.write();
if let Some(ref proxy) = *proxy {
return Ok(Arc::clone(&proxy));
}
let p = Arc::new(connect_to_protocol_sync::<RoleManagerMarker>()?);
*proxy = Some(Arc::clone(&p));
Ok(p)
}
fn disconnect() {
let mut proxy = ROLE_MANAGER.write();
*proxy = None;
}
pub fn set_role_for_thread(thread: &Thread, role_name: &str) -> Result<(), Error> {
let role_manager = connect()?;
let thread = thread
.duplicate_handle(Rights::SAME_RIGHTS)
.context("Failed to duplicate thread handle")?;
let request = RoleManagerSetRoleRequest {
target: Some(RoleTarget::Thread(thread)),
role: Some(RoleName { role: role_name.to_string() }),
..Default::default()
};
let _ = role_manager
.set_role(request, MonotonicInstant::INFINITE)
.context("fuchsia.scheduler.RoleManager::SetRole failed")
.and_then(|result| {
match result {
Ok(_) => Ok(()),
Err(status) => {
if status == Status::PEER_CLOSED.into_raw() {
disconnect();
}
Status::ok(status).context(format!(
"fuchsia.scheduler.RoleManager::SetRole returned error: {:?}",
status
))
}
}
})?;
Ok(())
}
pub fn set_role_for_this_thread(role_name: &str) -> Result<(), Error> {
set_role_for_thread(&fuchsia_runtime::thread_self(), role_name)
}