11use futures:: StreamExt ;
22use iroh:: protocol:: ProtocolHandler ;
3+ use nvml_wrapper:: Nvml ;
4+ use serde:: { Deserialize , Serialize } ;
5+ use sysinfo:: System ;
36use tarpc:: {
47 serde_transport as transport, server, server:: Channel , tokio_serde:: formats:: Bincode ,
58 tokio_util:: codec:: LengthDelimitedCodec ,
@@ -8,9 +11,18 @@ use tokio_duplex::Duplex;
811
912use crate :: cli:: app:: COMAN_VERSION ;
1013
14+ #[ derive( Debug , Clone , Serialize , Deserialize ) ]
15+ pub struct ResourceUsage {
16+ pub cpu : f32 ,
17+ pub mem_used : u64 ,
18+ pub mem_total : u64 ,
19+ pub gpu : Option < u64 > ,
20+ }
21+
1122#[ tarpc:: service]
1223pub trait ComanRPC {
1324 async fn version ( ) -> String ;
25+ async fn resource_usage ( ) -> ResourceUsage ;
1426}
1527#[ derive( Debug , Clone ) ]
1628struct RpcServer ;
@@ -19,6 +31,41 @@ impl ComanRPC for RpcServer {
1931 async fn version ( self , _: tarpc:: context:: Context ) -> String {
2032 COMAN_VERSION . to_string ( )
2133 }
34+
35+ async fn resource_usage ( self , _context : :: tarpc:: context:: Context ) -> ResourceUsage {
36+ let mut sys = System :: new_all ( ) ;
37+ sys. refresh_all ( ) ;
38+ let mut cpu_usage = 0.0 ;
39+ for cpu in sys. cpus ( ) {
40+ cpu_usage += cpu. cpu_usage ( ) ;
41+ }
42+ cpu_usage /= sys. cpus ( ) . len ( ) as f32 ;
43+ let gpu_usage = match Nvml :: init ( ) {
44+ Ok ( nvml) => match nvml. device_by_index ( 0 ) {
45+ Ok ( device) => match device. memory_info ( ) {
46+ Ok ( memory_info) => Some ( memory_info. used ) ,
47+ Err ( e) => {
48+ println ! ( "Couldn't get GPU memory info: {e:?}" ) ;
49+ None
50+ }
51+ } ,
52+ Err ( e) => {
53+ println ! ( "couldn't load nvidia device 0: {e:?}" ) ;
54+ None
55+ }
56+ } ,
57+ Err ( e) => {
58+ println ! ( "Nvidia Device Info not available: {e:?}" ) ;
59+ None
60+ }
61+ } ;
62+ ResourceUsage {
63+ cpu : cpu_usage,
64+ mem_used : sys. used_memory ( ) ,
65+ mem_total : sys. total_memory ( ) ,
66+ gpu : gpu_usage,
67+ }
68+ }
2269}
2370
2471#[ derive( Debug , Default ) ]
0 commit comments