Переглянути джерело

add get_info() hook for p2p and sessions

narodnik 4 роки тому
батько
коміт
198061daa2

+ 4 - 53
bin/ircd/src/main.rs

@@ -162,7 +162,8 @@ async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<(
     //
     let ex2 = executor.clone();
     let ex3 = ex2.clone();
-    let rpc_interface = Arc::new(JsonRpcInterface { rpc_listen_addr: options.rpc_listen_addr });
+    let rpc_interface =
+        Arc::new(JsonRpcInterface { p2p: p2p.clone(), rpc_listen_addr: options.rpc_listen_addr });
     executor
         .spawn(async move { listen_and_serve(server_config, rpc_interface, ex3).await })
         .detach();
@@ -189,6 +190,7 @@ async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<(
 }
 
 struct JsonRpcInterface {
+    p2p: net::P2pPtr,
     rpc_listen_addr: SocketAddr,
 }
 
@@ -219,58 +221,7 @@ impl JsonRpcInterface {
     //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
     // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
     async fn get_info(&self, id: Value, _params: Value) -> JsonResult {
-        let resp: serde_json::Value = json!({
-            "id": self.rpc_listen_addr,
-            "connections": {
-                "outgoing": [
-                {
-                    "id": "127.2.1.1:0000",
-                    "message": [
-                        "addr",
-                        "get_addr",
-                        "info",
-                        "get_info",
-                        "ping",
-                        "pong",
-                    ]
-                },
-                {
-                    "id": "121.1.6.7:9000",
-                    "message": [
-                        "addr",
-                        "get_addr",
-                        "info",
-                        "get_info",
-                        "ping",
-                        "pong",
-                    ]
-                }],
-                "incoming": [
-                {
-                    "id": "124.1.1.6:9333",
-                    "message": [
-                        "addr",
-                        "get_addr",
-                        "info",
-                        "get_info",
-                        "ping",
-                        "pong",
-                    ]
-                },
-                {
-                    "id": "120.1.0.5:2111",
-                    "message": [
-                        "addr",
-                        "get_addr",
-                        "info",
-                        "get_info",
-                        "ping",
-                        "pong",
-                    ]
-                }
-                ],
-            },
-        });
+        let resp = self.p2p.get_info().await;
         JsonResult::Resp(jsonresp(resp, id))
     }
 }

+ 45 - 5
src/net/p2p.rs

@@ -1,6 +1,7 @@
 use async_executor::Executor;
 use async_std::sync::Mutex;
 use log::debug;
+use serde_json::{json, Value};
 use std::{
     collections::{HashMap, HashSet},
     net::SocketAddr,
@@ -12,7 +13,7 @@ use crate::{
     net::{
         message::Message,
         protocol::{register_default_protocols, ProtocolRegistry},
-        session::{InboundSession, ManualSession, OutboundSession, SeedSession},
+        session::{InboundSession, ManualSession, OutboundSession, SeedSession, Session},
         Channel, ChannelPtr, Hosts, HostsPtr, Settings, SettingsPtr,
     },
     system::{Subscriber, SubscriberPtr, Subscription},
@@ -34,6 +35,12 @@ pub struct P2p {
     stop_subscriber: SubscriberPtr<Error>,
     hosts: HostsPtr,
     protocol_registry: ProtocolRegistry,
+
+    // We keep a reference to the sessions used for get info
+    session_manual: Mutex<Option<Arc<ManualSession>>>,
+    session_inbound: Mutex<Option<Arc<InboundSession>>>,
+    session_outbound: Mutex<Option<Arc<OutboundSession>>>,
+
     settings: SettingsPtr,
 }
 
@@ -42,21 +49,44 @@ impl P2p {
     pub async fn new(settings: Settings) -> Arc<Self> {
         let settings = Arc::new(settings);
 
-        let self_ = Arc::new(Self {
+        let mut self_ = Arc::new(Self {
             pending: Mutex::new(HashSet::new()),
             channels: Mutex::new(HashMap::new()),
             channel_subscriber: Subscriber::new(),
             stop_subscriber: Subscriber::new(),
             hosts: Hosts::new(),
             protocol_registry: ProtocolRegistry::new(),
+            session_manual: Mutex::new(None),
+            session_inbound: Mutex::new(None),
+            session_outbound: Mutex::new(None),
             settings,
         });
 
+        let parent = Arc::downgrade(&self_);
+
+        *self_.session_manual.lock().await = Some(ManualSession::new(parent.clone()));
+        *self_.session_inbound.lock().await = Some(InboundSession::new(parent.clone()));
+        *self_.session_outbound.lock().await = Some(OutboundSession::new(parent));
+
         register_default_protocols(self_.clone()).await;
 
         self_
     }
 
+    pub async fn get_info(&self) -> serde_json::Value {
+        json!({
+            "session_manual": self.session_manual().await.get_info(),
+            "session_inbound": self.session_inbound().await.get_info(),
+            "session_outbound": self.session_inbound().await.get_info(),
+            // Possible states:
+            //   open - the p2p object has been created but not yet started.
+            //   start - we are performing the initial seed session
+            //   started - seed session finished, but not yet running
+            //   run - p2p is running and the network is active.
+            "state": "open",
+        })
+    }
+
     /// Invoke startup and seeding sequence. Call from constructing thread.
     pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
         debug!(target: "net", "P2p::start() [BEGIN]");
@@ -70,20 +100,30 @@ impl P2p {
         Ok(())
     }
 
+    pub async fn session_manual(&self) -> Arc<ManualSession> {
+        self.session_manual.lock().await.as_ref().unwrap().clone()
+    }
+    pub async fn session_inbound(&self) -> Arc<InboundSession> {
+        self.session_inbound.lock().await.as_ref().unwrap().clone()
+    }
+    pub async fn session_outbound(&self) -> Arc<OutboundSession> {
+        self.session_outbound.lock().await.as_ref().unwrap().clone()
+    }
+
     /// Synchronize the blockchain and then begin long running sessions,
     /// call after start() is invoked.
     pub async fn run(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
         debug!(target: "net", "P2p::run() [BEGIN]");
 
-        let manual = ManualSession::new(Arc::downgrade(&self));
+        let manual = self.session_manual().await;
         for peer in &self.settings.peers {
             manual.clone().connect(peer, executor.clone()).await;
         }
 
-        let inbound = InboundSession::new(Arc::downgrade(&self));
+        let inbound = self.session_inbound().await;
         inbound.clone().start(executor.clone())?;
 
-        let outbound = OutboundSession::new(Arc::downgrade(&self));
+        let outbound = self.session_outbound().await;
         outbound.clone().start(executor.clone()).await?;
 
         let stop_sub = self.subscribe_stop().await;

+ 8 - 0
src/net/session/inbound_session.rs

@@ -1,3 +1,4 @@
+use serde_json::{json, Value};
 use std::{
     net::SocketAddr,
     sync::{Arc, Weak},
@@ -29,6 +30,7 @@ impl InboundSession {
 
         Arc::new(Self { p2p, acceptor, accept_task: StoppableTask::new() })
     }
+
     /// Starts the inbound session. Begins by accepting connections and fails if
     /// the address is not configured. Then runs the channel subscription
     /// loop.
@@ -119,6 +121,12 @@ impl InboundSession {
 }
 
 impl Session for InboundSession {
+    fn get_info(&self) -> serde_json::Value {
+        json!({
+            "key": 110
+        })
+    }
+
     fn p2p(&self) -> Arc<P2p> {
         self.p2p.upgrade().unwrap()
     }

+ 7 - 0
src/net/session/manual_session.rs

@@ -1,4 +1,5 @@
 use async_std::sync::Mutex;
+use serde_json::{json, Value};
 use std::{
     net::SocketAddr,
     sync::{Arc, Weak},
@@ -131,6 +132,12 @@ impl ManualSession {
 }
 
 impl Session for ManualSession {
+    fn get_info(&self) -> serde_json::Value {
+        json!({
+            "key": 110
+        })
+    }
+
     fn p2p(&self) -> Arc<P2p> {
         self.p2p.upgrade().unwrap()
     }

+ 8 - 0
src/net/session/outbound_session.rs

@@ -1,6 +1,7 @@
 use async_executor::Executor;
 use async_std::{sync::Mutex, task::yield_now};
 use log::*;
+use serde_json::{json, Value};
 use std::{
     net::SocketAddr,
     sync::{Arc, Weak},
@@ -26,6 +27,7 @@ impl OutboundSession {
     pub fn new(p2p: Weak<P2p>) -> Arc<Self> {
         Arc::new(Self { p2p, connect_slots: Mutex::new(Vec::new()) })
     }
+
     /// Start the outbound session. Runs the channel connect loop.
     pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
         let slots_count = self.p2p().settings().outbound_connections;
@@ -169,6 +171,12 @@ impl OutboundSession {
 }
 
 impl Session for OutboundSession {
+    fn get_info(&self) -> serde_json::Value {
+        json!({
+            "key": 110
+        })
+    }
+
     fn p2p(&self) -> Arc<P2p> {
         self.p2p.upgrade().unwrap()
     }

+ 7 - 0
src/net/session/seed_session.rs

@@ -1,4 +1,5 @@
 use async_std::future::timeout;
+use serde_json::{json, Value};
 use std::{
     net::SocketAddr,
     sync::{Arc, Weak},
@@ -136,6 +137,12 @@ impl SeedSession {
 }
 
 impl Session for SeedSession {
+    fn get_info(&self) -> serde_json::Value {
+        json!({
+            "key": 110
+        })
+    }
+
     fn p2p(&self) -> Arc<P2p> {
         self.p2p.upgrade().unwrap()
     }

+ 3 - 0
src/net/session/session.rs

@@ -1,5 +1,6 @@
 use async_trait::async_trait;
 use log::debug;
+use serde_json::Value;
 use smol::Executor;
 use std::sync::Arc;
 
@@ -95,6 +96,8 @@ pub trait Session: Sync {
         Ok(())
     }
 
+    fn get_info(&self) -> serde_json::Value;
+
     /// Returns a pointer to the p2p network interface.
     fn p2p(&self) -> P2pPtr;