From b6275290d35e8276cd7e46178fbcf4a0bd74c616 Mon Sep 17 00:00:00 2001 From: BlueFunny Date: Sat, 27 Jan 2024 23:22:54 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BA=86=20Config=20?= =?UTF-8?q?=E7=9A=84=E8=BD=AC=E6=8D=A2=E4=B8=8E=E4=BF=9D=E5=AD=98=E9=83=A8?= =?UTF-8?q?=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 2 +- src/config.rs | 161 +++++++++++++++++++++++++++++--------------------- 2 files changed, 94 insertions(+), 69 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4f54470..8797702 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ axum = "0.7.4" tokio = { version = "1.35.1", features = ["full"] } serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" +serde_json = "1.0.112" toml = "0.8.8" apache-avro = "0.16.0" diff --git a/src/config.rs b/src/config.rs index 63693ca..28d1a2a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,102 +1,127 @@ -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum ClusterByoc { - http, - https, -} +use log::{debug, error, info, warn}; -impl ClusterByoc { - pub fn to_string(&self) -> String { - match self { - ClusterByoc::http => "http".to_string(), - ClusterByoc::https => "https".to_string(), - } - } -} +use serde::{Deserialize, Serialize}; +use serde_json::Result; -#[derive(Debug, Clone, PartialEq, Eq, Hash)] +use std::{env, fs, io::Error}; + +const CONFIG_PATH: &str = "config.json"; + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Config { + /// http or https + /// CLUSTER_BYOC + CENTER_URL pub center_url: String, - pub cluster_port: u32, + /// CLUSTER_IP + pub host_ip: String, + /// CLUSTER_PORT + pub host_port: u32, + /// CLUSTER_ID pub cluster_id: String, + /// CLUSTER_SECRET pub cluster_secret: String, - /// CLUSTER_BYOC - pub cluster_byoc: ClusterByoc, + /// NO_DEMAON pub no_demaon: bool, - /// DISABLE_ACCESS_LOG - pub disable_access_log: bool, - /// FORCE_NOOPEN - pub force_noopen: bool, - /// ENABLE_NGINX - pub enable_nginx: bool, + // DISABLE_ACCESS_LOG [DECRAPEATED] + // pub disable_access_log: bool, + // FORCE_NOOPEN [DECRAPEATED] + // pub force_noopen: bool, + // ENABLE_NGINX [DECRAPEATED] + // pub enable_nginx: bool, } impl Config { pub fn new( center_url: String, - cluster_port: u32, + host_ip: String, + host_port: u32, cluster_id: String, cluster_secret: String, - cluster_byoc: ClusterByoc, no_demaon: bool, - disable_access_log: bool, - force_noopen: bool, - enable_nginx: bool, ) -> Self { Self { center_url, - cluster_port, + host_ip, + host_port, cluster_id, cluster_secret, - cluster_byoc, no_demaon, - disable_access_log, - force_noopen, - enable_nginx, } } - pub fn new_from_env() -> Self { - let center_url = - std::env::var("CENTER_URL").unwrap_or("openbmclapi.bangbang93.com".to_string()); - let cluster_port = std::env::var("CLUSTER_PORT") + + pub fn convert_from_env() { + // Load from env + let center_url = env::var("CENTER_URL").unwrap_or("openbmclapi.bangbang93.com".to_string()); + let host_ip: String = env::var("CLUSTER_IP").unwrap_or("0.0.0.0".to_string()); + let host_port = env::var("CLUSTER_PORT") .unwrap_or("8080".to_string()) .parse::() - .expect("CLUSTER_PORT must be a number"); - let cluster_id = std::env::var("CLUSTER_ID").unwrap_or("1".to_string()); - let cluster_secret = std::env::var("CLUSTER_SECRET").expect("CLUSTER_SECRET must be set"); - let cluster_byoc = match std::env::var("CLUSTER_BYOC") - .unwrap_or("http".to_string()) - .as_str() - { - "http" => ClusterByoc::http, - "https" => ClusterByoc::https, - _ => panic!("CLUSTER_BYOC must be http or https"), - }; - let no_demaon = std::env::var("NO_DAEMON") + .unwrap_or_else(|_| { + error!("CLUSTER_PORT must be a number"); + std::process::exit(1); + }); + let cluster_id = env::var("CLUSTER_ID").unwrap_or_else(|_| { + error!("CLUSTER_ID must be set"); + std::process::exit(1); + }); + let cluster_secret = env::var("CLUSTER_SECRET").unwrap_or_else(|_| { + error!("CLUSTER_SECRET must be set"); + std::process::exit(1); + }); + let no_demaon = env::var("NO_DAEMON") .unwrap_or("false".to_string()) .parse::() - .expect("NO_DAEMON must be true or false"); - let disable_access_log = std::env::var("DISABLE_ACCESS_LOG") - .unwrap_or("false".to_string()) - .parse::() - .expect("DISABLE_ACCESS_LOG must be true or false"); - let force_noopen = std::env::var("FORCE_NOOPEN") - .unwrap_or("false".to_string()) - .parse::() - .expect("FORCE_NOOPEN must be true or false"); - let enable_nginx = std::env::var("ENABLE_NGINX") - .unwrap_or("false".to_string()) - .parse::() - .expect("ENABLE_NGINX must be true or false"); - Self { + .unwrap_or_else(|_| { + error!("NO_DAEMON must be true or false"); + std::process::exit(1); + }); + + // Create config + let config = Config::new( center_url, - cluster_port, + host_ip, + host_port, cluster_id, cluster_secret, - cluster_byoc, no_demaon, - disable_access_log, - force_noopen, - enable_nginx, + ); + + // Decrapated warning + if env::var("CLUSTER_BYOC").is_ok() { + warn!("CLUSTER_BYOC is deprecated, ignored"); } + if env::var("DISABLE_ACCESS_LOG").is_ok() { + warn!("DISABLE_ACCESS_LOG is deprecated, ignored"); + } + if env::var("FORCE_NOOPEN").is_ok() { + warn!("FORCE_NOOPEN is deprecated, ignored"); + } + if env::var("ENABLE_NGINX").is_ok() { + warn!("ENABLE_NGINX is deprecated, ignored"); + // If you want to use Nginx, why would you choose this program? + } + + // Save config + Self::save(config); + } + pub fn save(config: Config) { + if ! fs::canonicalize(CONFIG_PATH).is_ok() { + fs::File::create(CONFIG_PATH).unwrap_or_else(|_| { + error!("Failed to create config file"); + std::process::exit(1); + }); + } + fs::write(CONFIG_PATH, serde_json::to_string(&config).unwrap()).unwrap_or_else(|_| { + error!("Failed to save config"); + std::process::exit(1); + }); + } + + pub fn load() -> Result { + todo!("Not implemented yet") + } + + pub fn join_center_url(&self, path: &str) -> String { + format!("{}{}", self.center_url, path) } } From 76ce0c4952a9d1edad48b5928921bc0bcf831459 Mon Sep 17 00:00:00 2001 From: BlueFunny Date: Sat, 27 Jan 2024 23:48:49 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BA=86=E5=87=A0?= =?UTF-8?q?=E4=B8=AA=E5=B0=8F=E9=97=AE=E9=A2=98=EF=BC=8C=E6=9B=B4=E6=8D=A2?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/config.rs | 54 +++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/src/config.rs b/src/config.rs index 6beae3d..7140ff3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,11 +1,11 @@ -use log::{debug, error, info, warn}; +use { + log::{error, warn}, + serde::{Deserialize, Serialize}, + serde_json::Result, + std::{env, fs, io::Error}, +}; -use serde::{Deserialize, Serialize}; -use serde_json::Result; - -use std::{env, fs, io::Error}; - -const CONFIG_PATH: &str = "config.json"; +const CONFIG_PATH: &str = "config.toml"; #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Config { @@ -59,34 +59,24 @@ impl Config { .parse::() .unwrap_or_else(|_| { error!("CLUSTER_PORT must be a number"); - std::process::exit(1); + panic!(); }); let cluster_id = env::var("CLUSTER_ID").unwrap_or_else(|_| { error!("CLUSTER_ID must be set"); - std::process::exit(1); + panic!(); }); let cluster_secret = env::var("CLUSTER_SECRET").unwrap_or_else(|_| { error!("CLUSTER_SECRET must be set"); - std::process::exit(1); + panic!(); }); let no_demaon = env::var("NO_DAEMON") .unwrap_or("false".to_string()) .parse::() .unwrap_or_else(|_| { error!("NO_DAEMON must be true or false"); - std::process::exit(1); + panic!(); }); - // Create config - let config = Config::new( - center_url, - host_ip, - host_port, - cluster_id, - cluster_secret, - no_demaon, - ); - // Decrapated warning if env::var("CLUSTER_BYOC").is_ok() { warn!("CLUSTER_BYOC is deprecated, ignored"); @@ -102,19 +92,29 @@ impl Config { // If you want to use Nginx, why would you choose this program? } + // Create config + let config = Config::new( + center_url, + host_ip, + host_port, + cluster_id, + cluster_secret, + no_demaon, + ); + // Save config - Self::save(config); + config.save(); } - pub fn save(config: Config) { - if ! fs::canonicalize(CONFIG_PATH).is_ok() { + pub fn save(&self) { + if !fs::canonicalize(CONFIG_PATH).is_ok() { fs::File::create(CONFIG_PATH).unwrap_or_else(|_| { error!("Failed to create config file"); - std::process::exit(1); + panic!(); }); } - fs::write(CONFIG_PATH, serde_json::to_string(&config).unwrap()).unwrap_or_else(|_| { + fs::write(CONFIG_PATH, toml::to_string(&self).unwrap()).unwrap_or_else(|_| { error!("Failed to save config"); - std::process::exit(1); + panic!(); }); } From c98acf824d7646fe0fefa99d13f338a879a18927 Mon Sep 17 00:00:00 2001 From: BlueFunny Date: Sun, 28 Jan 2024 00:20:02 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E6=8F=90=E4=BE=9B=E4=BA=86=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E9=85=8D=E7=BD=AE,=20=E5=B0=8F=E4=BF=AE=E4=BA=86?= =?UTF-8?q?=E5=87=A0=E4=B8=AA=E5=9C=B0=E6=96=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/config.rs | 73 ++++++++++++++++++++------------------------------- 1 file changed, 29 insertions(+), 44 deletions(-) diff --git a/src/config.rs b/src/config.rs index 7140ff3..a5ddb90 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,7 +2,7 @@ use { log::{error, warn}, serde::{Deserialize, Serialize}, serde_json::Result, - std::{env, fs, io::Error}, + std::{env, fs}, }; const CONFIG_PATH: &str = "config.toml"; @@ -10,7 +10,7 @@ const CONFIG_PATH: &str = "config.toml"; #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Config { /// http or https - /// CLUSTER_BYOC + CENTER_URL + /// CENTER_URL pub center_url: String, /// CLUSTER_IP pub host_ip: String, @@ -22,61 +22,45 @@ pub struct Config { pub cluster_secret: String, /// NO_DEMAON pub no_demaon: bool, - // DISABLE_ACCESS_LOG [DECRAPEATED] - // pub disable_access_log: bool, - // FORCE_NOOPEN [DECRAPEATED] - // pub force_noopen: bool, - // ENABLE_NGINX [DECRAPEATED] - // pub enable_nginx: bool, } impl Config { pub fn new( - center_url: String, - host_ip: String, - host_port: u32, + center_url: Option, + host_ip: Option, + host_port: Option, cluster_id: String, cluster_secret: String, - no_demaon: bool, + no_demaon: Option, ) -> Self { // https://openbmclapi.bangbang93.com Self { - center_url, - host_ip, - host_port, + center_url: center_url.unwrap_or("https://openbmclapi.bangbang93.com".to_string()), + host_ip: host_ip.unwrap_or("0.0.0.0".to_string()), + host_port: host_port.unwrap_or(8080), cluster_id, cluster_secret, - no_demaon, + no_demaon: no_demaon.unwrap_or(false), } } pub fn convert_from_env() { // Load from env - let center_url = env::var("CENTER_URL").unwrap_or("openbmclapi.bangbang93.com".to_string()); - let host_ip: String = env::var("CLUSTER_IP").unwrap_or("0.0.0.0".to_string()); - let host_port = env::var("CLUSTER_PORT") - .unwrap_or("8080".to_string()) - .parse::() - .unwrap_or_else(|_| { - error!("CLUSTER_PORT must be a number"); - panic!(); - }); - let cluster_id = env::var("CLUSTER_ID").unwrap_or_else(|_| { - error!("CLUSTER_ID must be set"); - panic!(); - }); - let cluster_secret = env::var("CLUSTER_SECRET").unwrap_or_else(|_| { - error!("CLUSTER_SECRET must be set"); - panic!(); - }); - let no_demaon = env::var("NO_DAEMON") - .unwrap_or("false".to_string()) - .parse::() - .unwrap_or_else(|_| { - error!("NO_DAEMON must be true or false"); - panic!(); - }); + let center_url = env::var("CENTER_URL").ok(); + let host_ip = env::var("CLUSTER_IP").ok(); + let host_port = env::var("CLUSTER_PORT").unwrap().parse::().ok(); + let no_demaon = env::var("NO_DAEMON").unwrap().parse::().ok(); + // Load from env + let cluster_id = env::var("CLUSTER_ID").unwrap_or_else(|err| { + error!("CLUSTER_ID must be set"); + panic!("{}", err); + }); + let cluster_secret = env::var("CLUSTER_SECRET").unwrap_or_else(|err| { + error!("CLUSTER_SECRET must be set"); + panic!("{}", err); + }); + // Decrapated warning if env::var("CLUSTER_BYOC").is_ok() { warn!("CLUSTER_BYOC is deprecated, ignored"); @@ -107,14 +91,15 @@ impl Config { } pub fn save(&self) { if !fs::canonicalize(CONFIG_PATH).is_ok() { - fs::File::create(CONFIG_PATH).unwrap_or_else(|_| { + fs::File::create(CONFIG_PATH).unwrap_or_else(|err| { error!("Failed to create config file"); - panic!(); + panic!("{}", err); }); + //TODO: Trigger initialization } - fs::write(CONFIG_PATH, toml::to_string(&self).unwrap()).unwrap_or_else(|_| { + fs::write(CONFIG_PATH, toml::to_string(&self).unwrap()).unwrap_or_else(|err| { error!("Failed to save config"); - panic!(); + panic!("{}", err); }); } From 837b6bbbbd0c7b6ccd1868b1d37cecc740adb1e5 Mon Sep 17 00:00:00 2001 From: shenjack <3695888@qq.com> Date: Sun, 28 Jan 2024 00:20:05 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E6=95=B4=E4=B8=AA=E5=A4=A7=E7=9A=84?= =?UTF-8?q?=EF=BC=8C=E7=BB=A7=E7=BB=AD=E6=94=B6=E6=8B=BE=E4=B8=9C=E8=A5=BF?= =?UTF-8?q?=E5=8E=BB=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 1 + src/cluster.rs | 12 +++++++++--- src/config.rs | 45 ++++++++++++++++++++++++++++----------------- src/log.rs | 23 ++++++++++++++++++++++- src/main.rs | 4 +++- src/utils.rs | 17 ++++++++++++++--- 6 files changed, 77 insertions(+), 25 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8797702..a4bd084 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ sha1 = "0.10.6" zstd = "0.13.0" log = "0.4.20" +simple_logger = "4.3.3" # [dependencies.db_logger] # version = "0.1" # optional = true diff --git a/src/cluster.rs b/src/cluster.rs index 7fab1fa..ca91f32 100644 --- a/src/cluster.rs +++ b/src/cluster.rs @@ -1,4 +1,4 @@ -use crate::config::{Config}; +use crate::config::Config; use crate::utils::avro_data_to_file_list; use crate::PROTOCOL_VERSION; @@ -63,7 +63,11 @@ impl Cluster { let url = self.config.join_center_url("/openbmclapi/files"); let password = self.config.cluster_secret.clone(); let username = self.config.cluster_id.clone(); - let client = Client::builder().user_agent(self.ua.clone()).build().unwrap(); + let client = Client::builder() + .user_agent(self.ua.clone()) + .build() + .unwrap(); + info!("getting file list from: {}", url); let res = client .get(url) .basic_auth(username, Some(password)) @@ -78,6 +82,7 @@ impl Cluster { match res.status() { StatusCode::OK => { let body = res.bytes().await.unwrap(); + info!("got file list len: {}, decompressing", body.len()); let cur = std::io::Cursor::new(body); let raw_data = decode_all(cur); if raw_data.is_err() { @@ -117,12 +122,13 @@ mod tests { test_conf.cluster_port, test_conf.cluster_id, test_conf.cluster_secret, - false, + None, ) } #[tokio::test] async fn test_get_file_list() { + crate::log::init_log_with_cli(); let config = gen_config(); let cluster = Cluster::new(config); cluster.get_file_list().await.unwrap(); diff --git a/src/config.rs b/src/config.rs index a5ddb90..daf07c4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,7 +1,8 @@ +use crate::fatal; + use { - log::{error, warn}, + log::{error, info, warn}, serde::{Deserialize, Serialize}, - serde_json::Result, std::{env, fs}, }; @@ -27,8 +28,8 @@ pub struct Config { impl Config { pub fn new( center_url: Option, - host_ip: Option, - host_port: Option, + host_ip: String, + host_port: u32, cluster_id: String, cluster_secret: String, no_demaon: Option, @@ -36,29 +37,39 @@ impl Config { // https://openbmclapi.bangbang93.com Self { center_url: center_url.unwrap_or("https://openbmclapi.bangbang93.com".to_string()), - host_ip: host_ip.unwrap_or("0.0.0.0".to_string()), - host_port: host_port.unwrap_or(8080), + host_ip, + host_port, cluster_id, cluster_secret, no_demaon: no_demaon.unwrap_or(false), } } - pub fn convert_from_env() { + pub fn new_from_env() { // Load from env - let center_url = env::var("CENTER_URL").ok(); - let host_ip = env::var("CLUSTER_IP").ok(); - let host_port = env::var("CLUSTER_PORT").unwrap().parse::().ok(); + let center_url = env::var("CENTER_URL"); + let center_url = match center_url { + Ok(url) => Some(url), + Err(_) => { + info!("center url not set, use default"); + None + } + }; + let host_ip: String = env::var("CLUSTER_IP").unwrap_or("0.0.0.0".to_string()); + let host_port = env::var("CLUSTER_PORT") + .unwrap_or("8080".to_string()) + .parse::() + .unwrap_or_else(|_| { + fatal!("CLUSTER_PORT must be a number"); + }); let no_demaon = env::var("NO_DAEMON").unwrap().parse::().ok(); // Load from env let cluster_id = env::var("CLUSTER_ID").unwrap_or_else(|err| { - error!("CLUSTER_ID must be set"); - panic!("{}", err); + fatal!("CLUSTER_ID must be set"); }); let cluster_secret = env::var("CLUSTER_SECRET").unwrap_or_else(|err| { - error!("CLUSTER_SECRET must be set"); - panic!("{}", err); + fatal!("CLUSTER_SECRET must be set"); }); // Decrapated warning @@ -103,9 +114,9 @@ impl Config { }); } - pub fn load() -> Result { - todo!("Not implemented yet") - } + // pub fn load() -> Result { + // todo!("Not implemented yet") + // } pub fn join_center_url(&self, path: &str) -> String { format!("{}{}", self.center_url, path) diff --git a/src/log.rs b/src/log.rs index ed79b27..739ebb2 100644 --- a/src/log.rs +++ b/src/log.rs @@ -1 +1,22 @@ -pub fn init_logging() {} +pub fn init_log_with_cli() { + // 命令行参数 + // --warn + // --debug + // --trace + // 从低级开始判断 + let log_level; + if std::env::args().any(|x| x == "--trace") { + log_level = log::LevelFilter::Trace; + } else if std::env::args().any(|x| x == "--debug") { + log_level = log::LevelFilter::Debug; + } else if std::env::args().any(|x| x == "--warn") { + log_level = log::LevelFilter::Warn; + } else { + log_level = log::LevelFilter::Info; + } + simple_logger::SimpleLogger::new() + .with_level(log_level) + .env() + .init() + .unwrap(); +} diff --git a/src/main.rs b/src/main.rs index ac562f2..3c3f315 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,4 +6,6 @@ mod utils; pub const PROTOCOL_VERSION: &str = "1.6.11"; -fn main() {} +fn main() { + log::init_log_with_cli(); +} diff --git a/src/utils.rs b/src/utils.rs index fb5f3f7..6da638c 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,12 +1,12 @@ -use crate::cluster::{SyncFile}; +use crate::cluster::SyncFile; use std::io::Cursor; -use log::{info, warn}; -use std::path::PathBuf; use apache_avro::{from_avro_datum, from_value, types::Value}; +use log::{info, warn}; use md5::{Digest, Md5}; use sha1::Sha1; +use std::path::PathBuf; /// import {join} from 'path' /// @@ -92,6 +92,7 @@ pub fn avro_data_to_file_list(data: Vec) -> Option> { } files.push(try_item.unwrap()); } + info!("parsed {} files", len); Some(files) } _ => { @@ -101,6 +102,16 @@ pub fn avro_data_to_file_list(data: Vec) -> Option> { } } +#[macro_export] +macro_rules! fatal { + ($($arg:tt)+) => { + use log::error; + // error!() + panic!() + error!($($arg)+); + panic!($($arg)+); + }; +} + #[test] fn test_hash_to_filename() { assert_eq!( From c817ec6779b44ecd8ec30ca185ee8126d9a7c2d3 Mon Sep 17 00:00:00 2001 From: shenjack <3695888@qq.com> Date: Sun, 28 Jan 2024 00:31:10 +0800 Subject: [PATCH 5/6] more logger feature! --- Cargo.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a4bd084..a2f4a5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,9 @@ sha1 = "0.10.6" zstd = "0.13.0" log = "0.4.20" -simple_logger = "4.3.3" +[dependencies.simple_logger] +version = "4.3.3" +features = ["colors", "threads", "timestamps", "stderr"] # [dependencies.db_logger] # version = "0.1" # optional = true From 312bb60f721969cc213379f3c077e5a9cd634cba Mon Sep 17 00:00:00 2001 From: BlueFunny Date: Sun, 28 Jan 2024 00:51:45 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E4=B9=9F=E8=AE=B8=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E4=BA=86=E8=A7=A3=E6=9E=90=E9=83=A8=E5=88=86=20(=E6=9C=AA?= =?UTF-8?q?=E7=BB=8F=E9=AA=8C=E8=AF=81)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 4 +++- src/config.rs | 49 +++++++++++++++++-------------------------------- 2 files changed, 20 insertions(+), 33 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a4bd084..a2f4a5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,9 @@ sha1 = "0.10.6" zstd = "0.13.0" log = "0.4.20" -simple_logger = "4.3.3" +[dependencies.simple_logger] +version = "4.3.3" +features = ["colors", "threads", "timestamps", "stderr"] # [dependencies.db_logger] # version = "0.1" # optional = true diff --git a/src/config.rs b/src/config.rs index daf07c4..79a75ab 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,6 @@ -use crate::fatal; - use { + crate::fatal, log::{error, info, warn}, - serde::{Deserialize, Serialize}, std::{env, fs}, }; @@ -28,40 +26,27 @@ pub struct Config { impl Config { pub fn new( center_url: Option, - host_ip: String, - host_port: u32, + host_ip: Option, + host_port: Option, cluster_id: String, cluster_secret: String, no_demaon: Option, ) -> Self { - // https://openbmclapi.bangbang93.com Self { center_url: center_url.unwrap_or("https://openbmclapi.bangbang93.com".to_string()), - host_ip, - host_port, + host_ip: host_ip.unwrap_or("0.0.0.0".to_string()), + host_port: host_port.unwrap_or(8080), cluster_id, cluster_secret, no_demaon: no_demaon.unwrap_or(false), } } - pub fn new_from_env() { + pub fn convert_from_env() { // Load from env - let center_url = env::var("CENTER_URL"); - let center_url = match center_url { - Ok(url) => Some(url), - Err(_) => { - info!("center url not set, use default"); - None - } - }; - let host_ip: String = env::var("CLUSTER_IP").unwrap_or("0.0.0.0".to_string()); - let host_port = env::var("CLUSTER_PORT") - .unwrap_or("8080".to_string()) - .parse::() - .unwrap_or_else(|_| { - fatal!("CLUSTER_PORT must be a number"); - }); + let center_url = env::var("CENTER_URL").ok(); + let host_ip = env::var("CLUSTER_IP").ok(); + let host_port = env::var("CLUSTER_PORT").unwrap().parse::().ok(); let no_demaon = env::var("NO_DAEMON").unwrap().parse::().ok(); // Load from env @@ -71,7 +56,7 @@ impl Config { let cluster_secret = env::var("CLUSTER_SECRET").unwrap_or_else(|err| { fatal!("CLUSTER_SECRET must be set"); }); - + // Decrapated warning if env::var("CLUSTER_BYOC").is_ok() { warn!("CLUSTER_BYOC is deprecated, ignored"); @@ -103,20 +88,20 @@ impl Config { pub fn save(&self) { if !fs::canonicalize(CONFIG_PATH).is_ok() { fs::File::create(CONFIG_PATH).unwrap_or_else(|err| { - error!("Failed to create config file"); - panic!("{}", err); + fatal!("Failed to create config file"); }); //TODO: Trigger initialization } fs::write(CONFIG_PATH, toml::to_string(&self).unwrap()).unwrap_or_else(|err| { - error!("Failed to save config"); - panic!("{}", err); + fatal!("Failed to save config file"); }); } - // pub fn load() -> Result { - // todo!("Not implemented yet") - // } + pub fn load() -> Result { + toml::from_str(&self.load_raw()?).map_err(|err| { + fatal!("Failed to parse config file"); + }) + } pub fn join_center_url(&self, path: &str) -> String { format!("{}{}", self.center_url, path)