Selaa lähdekoodia

script/research/seedd: generalize network configuration

aggstam 4 vuotta sitten
vanhempi
sitoutus
75bb4a291b

+ 2 - 0
script/research/seedd/Cargo.toml

@@ -14,6 +14,7 @@ async-std = "1.12.0"
 ctrlc-async = {version = "3.2.2", default-features = false, features = ["async-std", "termination"]}
 easy-parallel = "3.2.0"
 futures-lite = "1.12.0"
+fxhash = "0.2.1"
 log = "0.4.17"
 simplelog = "0.12.0"
 url = "2.2.2"
@@ -23,5 +24,6 @@ serde = "1.0.138"
 serde_derive = "1.0.138"
 structopt = "0.3.26"
 structopt-toml = "0.5.0"
+toml = "0.5.9"
 
 [workspace]

+ 17 - 46
script/research/seedd/seedd_config.toml

@@ -7,49 +7,20 @@
 ## uncommenting, or by using the command-line.
 
 # Daemon published url, common for all enabled networks
-url = "tcp://127.0.0.1"
-
-# Darkfid activation flag
-#darkfid = true
-
-# Ircd activation flag
-#ircd = true
-
-# Taud activation flag
-#taud = true
-
-# Following specific network settings shouldn't be commended even if 
-# their corresponding network is not enabled.
-
-# Darkfid network settings.
-[darkfid_opts]
-# Network port
-port = 7650
-
-# Seed nodes to connect to
-seeds = []
-
-# Peers to connect to
-peers = []
-
-# Ircd network settings.
-[ircd_opts]
-# Network port
-port = 8760
-
-# Seed nodes to connect to
-seeds = []
-
-# Peers to connect to
-peers = []
-
-# Taud network settings.
-[taud_opts]
-# Network port
-port = 9870
-
-# Seed nodes to connect to
-seeds = []
-
-# Peers to connect to
-peers = []
+#url = "tcp://127.0.0.1"
+
+## Per-network settings
+#[network."darkfid"]
+#port = 7650
+#seeds = []
+#peers = []
+
+#[network."ircd"]
+#port = 8760
+#seeds = []
+#peers = []
+
+#[network."taud"]
+#port = 9870
+#seeds = []
+#peers = []

+ 66 - 33
script/research/seedd/src/config.rs

@@ -1,9 +1,12 @@
+use fxhash::FxHashMap;
+use log::{info, warn};
 use serde_derive::Deserialize;
 use structopt::StructOpt;
 use structopt_toml::StructOptToml;
+use toml::Value;
 use url::Url;
 
-use darkfi::cli_desc;
+use darkfi::{cli_desc, Result};
 
 #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
 #[serde(default)]
@@ -17,48 +20,78 @@ pub struct Args {
     /// Daemon published url, common for all enabled networks
     pub url: Url,
 
-    #[structopt(long)]
-    /// Darkfid activation flag
-    pub darkfid: bool,
-
-    #[structopt(flatten)]
-    /// Darkfid network specific settings
-    pub darkfid_opts: NetOpt,
-
-    #[structopt(long)]
-    /// Ircd activation flag
-    pub ircd: bool,
-
-    #[structopt(flatten)]
-    /// Ircd network specific settings
-    pub ircd_opts: NetOpt,
-
-    #[structopt(long)]
-    /// Taud activation flag
-    pub taud: bool,
-
-    #[structopt(flatten)]
-    /// Taud network specific settings
-    pub taud_opts: NetOpt,
-
     #[structopt(short, parse(from_occurrences))]
     /// Increase verbosity (-vvv supported)
     pub verbose: u8,
 }
 
 /// Defines the network specific settings
-#[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
-#[structopt()]
-pub struct NetOpt {
-    #[structopt(skip)]
+#[derive(Clone)]
+pub struct NetInfo {
     /// Specific port the network will use
     pub port: u16,
-
-    #[structopt(skip)]
     /// Connect to seeds (repeatable flag)
     pub seeds: Vec<Url>,
-
-    #[structopt(skip)]
     /// Connect to peers (repeatable flag)
     pub peers: Vec<Url>,
 }
+
+/// Parse a TOML string for any configured network and return
+/// a map containing said configurations.
+///
+/// ```toml
+/// [network."darkfid"]
+/// port = 7650
+/// seeds = []
+/// peers = []
+/// ```
+pub fn parse_configured_networks(data: &str) -> Result<FxHashMap<String, NetInfo>> {
+    let mut ret = FxHashMap::default();
+
+    if let Value::Table(map) = toml::from_str(data)? {
+        if map.contains_key("network") && map["network"].is_table() {
+            for net in map["network"].as_table().unwrap() {
+                info!("Found configuration for network: {}", net.0);
+                let table = net.1.as_table().unwrap();
+                if !table.contains_key("port") {
+                    warn!("Network port is mandatory, skipping network.");
+                    continue
+                }
+
+                let name = net.0.to_string();
+                let port = table["port"].as_integer().unwrap().try_into().unwrap();
+
+                let mut seeds = vec![];
+                if table.contains_key("seeds") {
+                    if let Some(s) = table["seeds"].as_array() {
+                        for seed in s {
+                            if let Some(u) = seed.as_str() {
+                                if let Ok(url) = Url::parse(u) {
+                                    seeds.push(url);
+                                }
+                            }
+                        }
+                    }
+                }
+
+                let mut peers = vec![];
+                if table.contains_key("peers") {
+                    if let Some(p) = table["peers"].as_array() {
+                        for peer in p {
+                            if let Some(u) = peer.as_str() {
+                                if let Ok(url) = Url::parse(u) {
+                                    peers.push(url);
+                                }
+                            }
+                        }
+                    }
+                }
+
+                let net_info = NetInfo { port, seeds, peers };
+                ret.insert(name, net_info);
+            }
+        }
+    };
+
+    Ok(ret)
+}

+ 15 - 29
script/research/seedd/src/main.rs

@@ -15,25 +15,23 @@ use darkfi::{
 };
 
 mod config;
-use config::{Args, NetOpt};
-
-// TODO: disable unregistered protocols message subscription warning
+use config::{parse_configured_networks, Args, NetInfo};
 
 const CONFIG_FILE: &str = "seedd_config.toml";
 const CONFIG_FILE_CONTENTS: &str = include_str!("../seedd_config.toml");
 
 async fn spawn_network(
     name: &str,
+    info: NetInfo,
     mut url: Url,
-    opts: NetOpt,
     ex: Arc<Executor<'_>>,
 ) -> Result<()> {
-    url.set_port(Some(opts.port))?;
+    url.set_port(Some(info.port))?;
     let network_settings = net::Settings {
         inbound: Some(url.clone()),
         external_addr: Some(url.clone()),
-        seeds: opts.seeds,
-        peers: opts.peers,
+        seeds: info.seeds,
+        peers: info.peers,
         outbound_connections: 0,
         ..Default::default()
     };
@@ -64,33 +62,21 @@ async fn realmain(args: Args, ex: Arc<Executor<'_>>) -> Result<()> {
     })
     .unwrap();
 
+    // Pick up network settings from the TOML configuration
+    let cfg_path = get_config_path(args.config, CONFIG_FILE)?;
+    let toml_contents = std::fs::read_to_string(cfg_path)?;
+    let configured_nets = parse_configured_networks(&toml_contents)?;
+
     // Verify any daemon network is enabled
-    let check = args.darkfid || args.ircd || args.taud;
-    if !check {
+    if configured_nets.is_empty() {
         info!("No daemon network is enabled!");
         return Ok(())
     }
 
-    // Spawn darkfid network, if configured
-    if args.darkfid {
-        if let Err(e) =
-            spawn_network("darkfid", args.url.clone(), args.darkfid_opts, ex.clone()).await
-        {
-            error!("Failed starting darkfid P2P network seed: {}", e);
-        }
-    }
-
-    // Spawn ircd network, if configured
-    if args.ircd {
-        if let Err(e) = spawn_network("ircd", args.url.clone(), args.ircd_opts, ex.clone()).await {
-            error!("Failed starting ircd P2P network seed: {}", e);
-        }
-    }
-
-    // Spawn taud network, if configured
-    if args.taud {
-        if let Err(e) = spawn_network("taud", args.url, args.taud_opts, ex).await {
-            error!("Failed starting taud P2P network seed: {}", e);
+    // Spawn configured networks
+    for (name, info) in &configured_nets {
+        if let Err(e) = spawn_network(name, info.clone(), args.url.clone(), ex.clone()).await {
+            error!("Failed starting {} P2P network seed: {}", name, e);
         }
     }