feat: tracing

This commit is contained in:
Nova
2022-12-02 20:46:28 -05:00
parent 692ee95500
commit 42d2a41d57
9 changed files with 82 additions and 49 deletions

View File

@@ -30,11 +30,13 @@ thiserror = "1.0.31"
send_wrapper = "0.6.0" send_wrapper = "0.6.0"
prisma = "0.1.1" prisma = "0.1.1"
slog = "2.7.0" slog = "2.7.0"
slog-stdlog = "4.1.1"
xkbcommon = { version = "0.5.0", default-features = false, optional = true } xkbcommon = { version = "0.5.0", default-features = false, optional = true }
stardust-xr = "0.8.0" stardust-xr = "0.8.0"
directories = "4.0.1" directories = "4.0.1"
serde = { version = "1.0.145", features = ["derive"] } serde = { version = "1.0.145", features = ["derive"] }
tracing = "0.1.37"
tracing-subscriber = "0.3.16"
tracing-slog = "0.2.0"
[dependencies.stereokit] [dependencies.stereokit]
default-features = false default-features = false

View File

@@ -3,22 +3,29 @@ use crate::{
core::registry::Registry, core::registry::Registry,
nodes::{data, drawable, fields, hmd, input, items, root::Root, spatial, startup, Node}, nodes::{data, drawable, fields, hmd, input, items, root::Root, spatial, startup, Node},
}; };
use color_eyre::eyre::{eyre, Result}; use color_eyre::{
eyre::{eyre, Result},
Report,
};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use stardust_xr::messenger::{self, MessageSenderHandle}; use stardust_xr::messenger::{self, MessageSenderHandle};
use std::{ use std::{
fs,
path::PathBuf, path::PathBuf,
sync::{Arc, Weak}, sync::{Arc, Weak},
}; };
use tokio::{net::UnixStream, sync::Notify, task::JoinHandle}; use tokio::{net::UnixStream, sync::Notify, task::JoinHandle};
use tracing::{info, warn};
lazy_static! { lazy_static! {
pub static ref CLIENTS: Registry<Client> = Registry::new(); pub static ref CLIENTS: Registry<Client> = Registry::new();
pub static ref INTERNAL_CLIENT: Arc<Client> = CLIENTS.add(Client { pub static ref INTERNAL_CLIENT: Arc<Client> = CLIENTS.add(Client {
event_loop: Weak::new(), event_loop: Weak::new(),
index: 0, index: 0,
pid: None,
exe: None,
stop_notifier: Default::default(), stop_notifier: Default::default(),
join_handle: OnceCell::new(), join_handle: OnceCell::new(),
@@ -33,6 +40,8 @@ lazy_static! {
pub struct Client { pub struct Client {
event_loop: Weak<EventLoop>, event_loop: Weak<EventLoop>,
index: usize, index: usize,
pid: Option<i32>,
exe: Option<PathBuf>,
stop_notifier: Arc<Notify>, stop_notifier: Arc<Notify>,
join_handle: OnceCell<JoinHandle<Result<()>>>, join_handle: OnceCell<JoinHandle<Result<()>>>,
@@ -47,7 +56,16 @@ impl Client {
event_loop: &Arc<EventLoop>, event_loop: &Arc<EventLoop>,
connection: UnixStream, connection: UnixStream,
) -> Arc<Self> { ) -> Arc<Self> {
println!("New client connected"); let pid = connection.peer_cred().ok().and_then(|c| c.pid());
let exe = pid.and_then(|pid| fs::read_link(format!("/proc/{}/exe", pid)).ok());
info!(
index = index,
pid,
exe = exe
.as_ref()
.and_then(|exe| exe.to_str().map(|s| s.to_string())),
"New client connected"
);
let (mut messenger_tx, mut messenger_rx) = messenger::create(connection); let (mut messenger_tx, mut messenger_rx) = messenger::create(connection);
let scenegraph = Arc::new(Scenegraph::default()); let scenegraph = Arc::new(Scenegraph::default());
@@ -55,6 +73,8 @@ impl Client {
let client = CLIENTS.add(Client { let client = CLIENTS.add(Client {
event_loop: Arc::downgrade(event_loop), event_loop: Arc::downgrade(event_loop),
index, index,
pid,
exe,
stop_notifier: Default::default(), stop_notifier: Default::default(),
join_handle: OnceCell::new(), join_handle: OnceCell::new(),
@@ -88,11 +108,14 @@ impl Client {
} }
}; };
let result = tokio::select! { let result: Result<(), Report> = tokio::select! {
_ = client.stop_notifier.notified() => Ok(()), _ = client.stop_notifier.notified() => Ok(()),
e = dispatch_loop => e, e = dispatch_loop => e,
e = flush_loop => e, e = flush_loop => e,
}; };
if let Err(e) = &result {
warn!(error = e.root_cause(), "Client disconnected with error!");
}
client.disconnect().await; client.disconnect().await;
result result
} }
@@ -118,6 +141,14 @@ impl Drop for Client {
fn drop(&mut self) { fn drop(&mut self) {
self.stop_notifier.notify_one(); self.stop_notifier.notify_one();
CLIENTS.remove(self); CLIENTS.remove(self);
println!("Client disconnected"); info!(
index = self.index,
pid = self.pid,
exe = self
.exe
.as_ref()
.and_then(|exe| exe.to_str().map(|s| s.to_string())),
"Client disconnected"
);
} }
} }

View File

@@ -21,6 +21,7 @@ use stereokit::render::SphericalHarmonics;
use stereokit::texture::Texture; use stereokit::texture::Texture;
use stereokit::{lifecycle::DisplayMode, Settings}; use stereokit::{lifecycle::DisplayMode, Settings};
use tokio::{runtime::Handle, sync::oneshot}; use tokio::{runtime::Handle, sync::oneshot};
use tracing::info;
#[derive(Parser)] #[derive(Parser)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
@@ -39,6 +40,7 @@ struct CliArgs {
} }
fn main() -> Result<()> { fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let project_dirs = ProjectDirs::from("", "", "stardust").unwrap(); let project_dirs = ProjectDirs::from("", "", "stardust").unwrap();
let cli_args = Arc::new(CliArgs::parse()); let cli_args = Arc::new(CliArgs::parse());
@@ -55,7 +57,7 @@ fn main() -> Result<()> {
.depth_mode(DepthMode::D32) .depth_mode(DepthMode::D32)
.init() .init()
.expect("StereoKit failed to initialize"); .expect("StereoKit failed to initialize");
println!("Init StereoKit"); info!("Init StereoKit");
// Skytex/light stuff // Skytex/light stuff
{ {
@@ -104,7 +106,7 @@ fn main() -> Result<()> {
#[cfg(feature = "wayland")] #[cfg(feature = "wayland")]
let mut wayland = wayland::Wayland::new()?; let mut wayland = wayland::Wayland::new()?;
println!("Stardust ready!"); info!("Stardust ready!");
stereokit.run( stereokit.run(
|sk, draw_ctx| { |sk, draw_ctx| {
hmd::frame(sk); hmd::frame(sk);
@@ -131,7 +133,7 @@ fn main() -> Result<()> {
wayland.make_context_current(); wayland.make_context_current();
}, },
|_| { |_| {
println!("Cleanly shut down StereoKit"); info!("Cleanly shut down StereoKit");
}, },
); );
@@ -142,7 +144,7 @@ fn main() -> Result<()> {
event_thread event_thread
.join() .join()
.expect("Failed to cleanly shut down event loop")?; .expect("Failed to cleanly shut down event loop")?;
println!("Cleanly shut down Stardust"); info!("Cleanly shut down Stardust");
Ok(()) Ok(())
} }
@@ -157,8 +159,8 @@ async fn event_loop(
let (event_loop, event_loop_join_handle) = let (event_loop, event_loop_join_handle) =
EventLoop::new().expect("Couldn't create server socket"); EventLoop::new().expect("Couldn't create server socket");
println!("Init event loop"); info!("Init event loop");
println!("Stardust socket created at {}", event_loop.socket_path); info!("Stardust socket created at {}", event_loop.socket_path);
let result = tokio::select! { let result = tokio::select! {
biased; biased;
@@ -167,7 +169,7 @@ async fn event_loop(
e = event_loop_join_handle => e?, e = event_loop_join_handle => e?,
}; };
println!("Cleanly shut down event loop"); info!("Cleanly shut down event loop");
unsafe { unsafe {
stereokit::sys::sk_quit(); stereokit::sys::sk_quit();

View File

@@ -94,7 +94,7 @@ impl Text {
.font_path .font_path
.as_deref() .as_deref()
.and_then(|path| Font::from_file(sk, path)) .and_then(|path| Font::from_file(sk, path))
.unwrap_or(Font::default(sk)); .unwrap_or_else(|| Font::default(sk));
Ok(SendWrapper::new(TextStyle::new( Ok(SendWrapper::new(TextStyle::new(
sk, sk,
font, font,

View File

@@ -9,10 +9,11 @@ pub mod root;
pub mod spatial; pub mod spatial;
pub mod startup; pub mod startup;
use color_eyre::eyre::{bail, eyre, Result}; use color_eyre::eyre::{eyre, Result};
use nanoid::nanoid; use nanoid::nanoid;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use stardust_xr::messenger::MessageSenderHandle;
use stardust_xr::scenegraph::ScenegraphError; use stardust_xr::scenegraph::ScenegraphError;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
@@ -44,6 +45,8 @@ pub type Method = fn(&Node, Arc<Client>, &[u8]) -> Result<Vec<u8>>;
pub struct Node { pub struct Node {
pub(super) uid: String, pub(super) uid: String,
path: String, path: String,
client: Weak<Client>,
message_sender_handle: Option<MessageSenderHandle>,
// trailing_slash_pos: usize, // trailing_slash_pos: usize,
local_signals: DashMap<String, Signal, BuildHasherDefault<FxHasher>>, local_signals: DashMap<String, Signal, BuildHasherDefault<FxHasher>>,
local_methods: DashMap<String, Method, BuildHasherDefault<FxHasher>>, local_methods: DashMap<String, Method, BuildHasherDefault<FxHasher>>,
@@ -76,8 +79,6 @@ pub struct Node {
// Startup // Startup
pub startup_settings: OnceCell<Mutex<StartupSettings>>, pub startup_settings: OnceCell<Mutex<StartupSettings>>,
pub(crate) client: Weak<Client>,
} }
impl Node { impl Node {
@@ -101,6 +102,7 @@ impl Node {
let node = Node { let node = Node {
uid: nanoid!(), uid: nanoid!(),
client: Arc::downgrade(client), client: Arc::downgrade(client),
message_sender_handle: client.message_sender_handle.clone(),
path, path,
// trailing_slash_pos: parent.len(), // trailing_slash_pos: parent.len(),
local_signals: Default::default(), local_signals: Default::default(),
@@ -132,9 +134,9 @@ impl Node {
self.get_client().unwrap().scenegraph.add_node(self) self.get_client().unwrap().scenegraph.add_node(self)
} }
pub fn destroy(&self) { pub fn destroy(&self) {
let _ = self if let Some(client) = self.get_client() {
.get_client() client.scenegraph.remove_node(self.get_path());
.map(|c| c.scenegraph.remove_node(self.get_path())); }
} }
pub fn destroy_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<()> { pub fn destroy_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<()> {
@@ -220,29 +222,24 @@ impl Node {
.get_valid_contents() .get_valid_contents()
.iter() .iter()
.filter(|alias| alias.info.remote_signals.iter().any(|e| e == &method)) .filter(|alias| alias.info.remote_signals.iter().any(|e| e == &method))
.for_each(|alias| { .filter_map(|alias| alias.node.upgrade())
let _ = alias .for_each(|node| {
.node let _ = node.send_remote_signal(method, data);
.upgrade()
.unwrap()
.send_remote_signal(method, data);
}); });
let path = self.path.clone(); let path = self.path.clone();
let method = method.to_string(); let method = method.to_string();
let data = data.to_vec(); let data = data.to_vec();
if let Some(client) = self.get_client() { self.message_sender_handle
if let Some(message_sender_handle) = client.message_sender_handle.as_ref() { .as_ref()
message_sender_handle.signal(path.as_str(), method.as_str(), data.as_slice())?; .map(|handle| handle.signal(path.as_str(), method.as_str(), data.as_slice()))
} .transpose()?;
}
Ok(()) Ok(())
} }
pub async fn execute_remote_method(&self, method: &str, data: Vec<u8>) -> Result<Vec<u8>> { pub async fn execute_remote_method(&self, method: &str, data: Vec<u8>) -> Result<Vec<u8>> {
let Some(client) = self.get_client() else {bail!("Client does not exist somehow?")}; let message_sender_handle = self
let message_sender_handle = client
.message_sender_handle .message_sender_handle
.as_ref() .as_ref()
.ok_or(eyre!("Messenger does not exist for this node's client"))?; .ok_or(eyre!("Messenger does not exist for this node"))?;
message_sender_handle message_sender_handle
.method(self.path.as_str(), method, &data)? .method(self.path.as_str(), method, &data)?

View File

@@ -17,7 +17,7 @@ use stereokit::{
StereoKit, StereoKit,
}; };
const SK_KEYMAP: &'static str = include_str!("sk.kmp"); const SK_KEYMAP: &str = include_str!("sk.kmp");
pub struct MousePointer { pub struct MousePointer {
node: Arc<Node>, node: Arc<Node>,

View File

@@ -19,12 +19,13 @@ use smithay::{
backend::{egl::EGLContext, renderer::gles2::Gles2Renderer}, backend::{egl::EGLContext, renderer::gles2::Gles2Renderer},
reexports::wayland_server::{backend::GlobalId, Display, ListeningSocket, Resource}, reexports::wayland_server::{backend::GlobalId, Display, ListeningSocket, Resource},
}; };
use tracing::info;
use std::{ use std::{
ffi::c_void, ffi::c_void,
os::unix::{net::UnixListener, prelude::FromRawFd}, os::unix::{net::UnixListener, prelude::FromRawFd},
sync::Arc, sync::Arc,
}; };
use std::{os::unix::prelude::AsRawFd, time::Duration}; use std::{os::unix::prelude::AsRawFd};
use stereokit as sk; use stereokit as sk;
use stereokit::StereoKit; use stereokit::StereoKit;
use tokio::{ use tokio::{
@@ -64,8 +65,7 @@ pub struct Wayland {
} }
impl Wayland { impl Wayland {
pub fn new() -> Result<Self> { pub fn new() -> Result<Self> {
let log = ::slog::Logger::root(::slog_stdlog::StdLog.fuse(), slog::o!()); let log = ::slog::Logger::root(::tracing_slog::TracingSlogDrain.fuse(), slog::o!());
slog_stdlog::init()?;
let egl_raw_handles = get_sk_egl()?; let egl_raw_handles = get_sk_egl()?;
let renderer = unsafe { let renderer = unsafe {
@@ -108,7 +108,7 @@ impl Wayland {
) -> Result<JoinHandle<Result<()>>> { ) -> Result<JoinHandle<Result<()>>> {
let socket = ListeningSocket::bind_auto("wayland", 0..33)?; let socket = ListeningSocket::bind_auto("wayland", 0..33)?;
if let Some(socket_name) = socket.socket_name() { if let Some(socket_name) = socket.socket_name() {
println!("Wayland compositor {:?} active", socket_name); info!("Wayland compositor {:?} active", socket_name);
} }
let listen_async = let listen_async =
@@ -146,8 +146,6 @@ impl Wayland {
} }
pub fn frame(&mut self, sk: &StereoKit) { pub fn frame(&mut self, sk: &StereoKit) {
let time_ms = (sk.time_getf() * 1000.) as u64;
for core_surface in CORE_SURFACES.get_valid_contents() { for core_surface in CORE_SURFACES.get_valid_contents() {
let Some(client_id) = let Some(client_id) =
core_surface core_surface
@@ -161,7 +159,6 @@ impl Wayland {
sk, sk,
&mut self.renderer, &mut self.renderer,
output, output,
Duration::from_millis(time_ms),
&self.log, &self.log,
|data| { |data| {
PanelItem::on_mapped(&core_surface, data, seat_data); PanelItem::on_mapped(&core_surface, data, seat_data);

View File

@@ -27,15 +27,16 @@ use smithay::{
}, },
}; };
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
use tracing::info;
pub struct ClientState; pub struct ClientState;
impl ClientData for ClientState { impl ClientData for ClientState {
fn initialized(&self, client_id: ClientId) { fn initialized(&self, client_id: ClientId) {
println!("Wayland client {:?} connected", client_id); info!("Wayland client {:?} connected", client_id);
} }
fn disconnected(&self, client_id: ClientId, reason: DisconnectReason) { fn disconnected(&self, client_id: ClientId, reason: DisconnectReason) {
println!( info!(
"Wayland client {:?} disconnected because {:#?}", "Wayland client {:?} disconnected because {:#?}",
client_id, reason client_id, reason
); );
@@ -98,7 +99,7 @@ impl WaylandState {
); );
display_handle.create_global::<Self, WlDataDeviceManager, _>(3, ()); display_handle.create_global::<Self, WlDataDeviceManager, _>(3, ());
println!("Init Wayland compositor"); info!("Init Wayland compositor");
Arc::new_cyclic(|weak| { Arc::new_cyclic(|weak| {
Mutex::new(WaylandState { Mutex::new(WaylandState {
@@ -127,7 +128,7 @@ impl WaylandState {
} }
impl Drop for WaylandState { impl Drop for WaylandState {
fn drop(&mut self) { fn drop(&mut self) {
println!("Cleanly shut down the Wayland compositor"); info!("Cleanly shut down the Wayland compositor");
} }
} }
impl BufferHandler for WaylandState { impl BufferHandler for WaylandState {

View File

@@ -135,7 +135,6 @@ impl CoreSurface {
sk: &StereoKit, sk: &StereoKit,
renderer: &mut Gles2Renderer, renderer: &mut Gles2Renderer,
output: Output, output: Output,
time: Duration,
log: &Logger, log: &Logger,
on_mapped: F, on_mapped: F,
if_mapped: M, if_mapped: M,
@@ -182,9 +181,13 @@ impl CoreSurface {
if_mapped(data); if_mapped(data);
}); });
send_frames_surface_tree(&wl_surface, &output, time, None, |_, _| { send_frames_surface_tree(
Some(output.clone()) &wl_surface,
}); &output,
Duration::from_secs_f64(sk.time_get()),
None,
|_, _| Some(output.clone()),
);
} }
pub fn set_material_offset(&self, material_offset: u32) { pub fn set_material_offset(&self, material_offset: u32) {