http_api_msg.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. /*************************************************************************
  2. *
  3. * Copyright (C) 2018-2025 Ruilin Peng (Nick) <[email protected]>.
  4. *
  5. * smartdns is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * smartdns is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. use crate::data_server::*;
  19. use crate::data_upstream_server::UpstreamServerInfo;
  20. use crate::db::*;
  21. use crate::smartdns::LogLevel;
  22. use crate::whois::WhoIsInfo;
  23. use serde_json::json;
  24. use std::collections::HashMap;
  25. use std::error::Error;
  26. #[derive(Debug)]
  27. pub struct AuthUser {
  28. pub username: String,
  29. pub password: String,
  30. }
  31. #[derive(Debug)]
  32. pub struct TokenResponse {
  33. pub token: String,
  34. pub expires_in: String,
  35. }
  36. pub fn api_msg_parse_auth(data: &str) -> Result<AuthUser, Box<dyn Error>> {
  37. let v: serde_json::Value = serde_json::from_str(data)?;
  38. let username = v["username"].as_str();
  39. if username.is_none() {
  40. return Err("username not found".into());
  41. }
  42. let password = v["password"].as_str();
  43. if password.is_none() {
  44. return Err("password not found".into());
  45. }
  46. Ok(AuthUser {
  47. username: username.unwrap().to_string(),
  48. password: password.unwrap().to_string(),
  49. })
  50. }
  51. pub fn api_msg_parse_auth_password_change(data: &str) -> Result<(String, String), Box<dyn Error>> {
  52. let v: serde_json::Value = serde_json::from_str(data)?;
  53. let old_password = v["old_password"].as_str();
  54. if old_password.is_none() {
  55. return Err("old_password not found".into());
  56. }
  57. let password = v["password"].as_str();
  58. if password.is_none() {
  59. return Err("password not found".into());
  60. }
  61. Ok((
  62. old_password.unwrap().to_string(),
  63. password.unwrap().to_string(),
  64. ))
  65. }
  66. pub fn api_msg_gen_auth_password_change(old_password: &str, password: &str) -> String {
  67. let json_str = json!({
  68. "old_password": old_password,
  69. "password": password,
  70. });
  71. json_str.to_string()
  72. }
  73. pub fn api_msg_gen_auth_login(auth: &AuthUser) -> String {
  74. let json_str = json!({
  75. "username": auth.username,
  76. "password": auth.password,
  77. });
  78. json_str.to_string()
  79. }
  80. pub fn api_msg_parse_count(data: &str) -> Result<i64, Box<dyn Error>> {
  81. let v: serde_json::Value = serde_json::from_str(data)?;
  82. let count = v["count"].as_i64();
  83. if count.is_none() {
  84. return Err("count not found".into());
  85. }
  86. Ok(count.unwrap())
  87. }
  88. pub fn api_msg_gen_count(count: i64) -> String {
  89. let json_str = json!({
  90. "count": count,
  91. });
  92. json_str.to_string()
  93. }
  94. pub fn api_msg_parse_json_object_domain_value(
  95. data: &serde_json::Value,
  96. ) -> Result<DomainData, Box<dyn Error>> {
  97. let id = data["id"].as_u64();
  98. if id.is_none() {
  99. return Err("id not found".into());
  100. }
  101. let timestamp = data["timestamp"].as_u64();
  102. if timestamp.is_none() {
  103. return Err("timestamp not found".into());
  104. }
  105. let domain = data["domain"].as_str();
  106. if domain.is_none() {
  107. return Err("domain not found".into());
  108. }
  109. let domain_type = data["domain_type"].as_u64();
  110. if domain_type.is_none() {
  111. return Err("domain_type not found".into());
  112. }
  113. let client = data["client"].as_str();
  114. if client.is_none() {
  115. return Err("client not found".into());
  116. }
  117. let domain_group = data["domain_group"].as_str();
  118. if domain_group.is_none() {
  119. return Err("domain_group not found".into());
  120. }
  121. let reply_code = data["reply_code"].as_u64();
  122. if reply_code.is_none() {
  123. return Err("reply_code not found".into());
  124. }
  125. let query_time = data["query_time"].as_i64();
  126. if query_time.is_none() {
  127. return Err("query_time not found".into());
  128. }
  129. let ping_time = data["ping_time"].as_f64();
  130. if ping_time.is_none() {
  131. return Err("ping_time not found".into());
  132. }
  133. let is_blocked = data["is_blocked"].as_bool();
  134. if is_blocked.is_none() {
  135. return Err("is_blocked not found".into());
  136. }
  137. let is_cached = data["is_cached"].as_bool();
  138. if is_cached.is_none() {
  139. return Err("is_cached not found".into());
  140. }
  141. Ok(DomainData {
  142. id: id.unwrap(),
  143. timestamp: timestamp.unwrap(),
  144. domain: domain.unwrap().to_string(),
  145. domain_type: domain_type.unwrap() as u32,
  146. client: client.unwrap().to_string(),
  147. domain_group: domain_group.unwrap().to_string(),
  148. reply_code: reply_code.unwrap() as u16,
  149. query_time: query_time.unwrap() as i32,
  150. ping_time: ping_time.unwrap(),
  151. is_blocked: is_blocked.unwrap(),
  152. is_cached: is_cached.unwrap(),
  153. })
  154. }
  155. pub fn api_msg_parse_domain(data: &str) -> Result<DomainData, Box<dyn Error>> {
  156. let v: serde_json::Value = serde_json::from_str(data)?;
  157. api_msg_parse_json_object_domain_value(&v)
  158. }
  159. pub fn api_msg_gen_json_object_domain(domain: &DomainData) -> serde_json::Value {
  160. json!({
  161. "id": domain.id,
  162. "timestamp": domain.timestamp,
  163. "domain": domain.domain,
  164. "domain_type": domain.domain_type,
  165. "client": domain.client,
  166. "domain_group": domain.domain_group,
  167. "reply_code": domain.reply_code,
  168. "query_time": domain.query_time,
  169. "ping_time": domain.ping_time,
  170. "is_blocked": domain.is_blocked,
  171. "is_cached": domain.is_cached,
  172. })
  173. }
  174. pub fn api_msg_gen_domain(domain: &DomainData) -> String {
  175. let json_str = api_msg_gen_json_object_domain(domain);
  176. json_str.to_string()
  177. }
  178. pub fn api_msg_parse_domain_list(data: &str) -> Result<Vec<DomainData>, Box<dyn Error>> {
  179. let v: serde_json::Value = serde_json::from_str(data)?;
  180. let list_count = v["list_count"].as_u64();
  181. if list_count.is_none() {
  182. return Err("list_count not found".into());
  183. }
  184. let list_count = list_count.unwrap();
  185. let mut domain_list = Vec::new();
  186. for i in 0..list_count {
  187. let domain_object = &v["domain_list"][i as usize];
  188. let domain_data = api_msg_parse_json_object_domain_value(domain_object)?;
  189. domain_list.push(domain_data);
  190. }
  191. Ok(domain_list)
  192. }
  193. pub fn api_msg_gen_domain_list(
  194. domain_list_result: &QueryDomainListResult,
  195. total_page: u64,
  196. total_count: u64,
  197. ) -> String {
  198. let json_str = json!({
  199. "list_count": domain_list_result.domain_list.len(),
  200. "total_page": total_page,
  201. "total_count": total_count,
  202. "step_by_cursor": domain_list_result.step_by_cursor,
  203. "domain_list":
  204. domain_list_result.domain_list
  205. .iter()
  206. .map(|x| {
  207. api_msg_gen_json_object_domain(x)
  208. })
  209. .collect::<Vec<serde_json::Value>>()
  210. });
  211. json_str.to_string()
  212. }
  213. pub fn api_msg_parse_client_list(data: &str) -> Result<Vec<ClientData>, Box<dyn Error>> {
  214. let v: serde_json::Value = serde_json::from_str(data)?;
  215. let list_count = v["list_count"].as_u64();
  216. if list_count.is_none() {
  217. return Err("list_count not found".into());
  218. }
  219. let list_count = list_count.unwrap();
  220. let mut client_list = Vec::new();
  221. for i in 0..list_count {
  222. let client_object = &v["client_list"][i as usize];
  223. let id = client_object["id"].as_u64();
  224. if id.is_none() {
  225. return Err("id not found".into());
  226. }
  227. let client_ip = client_object["client_ip"].as_str();
  228. if client_ip.is_none() {
  229. return Err("client_ip not found".into());
  230. }
  231. let mac = client_object["mac"].as_str();
  232. if mac.is_none() {
  233. return Err("mac not found".into());
  234. }
  235. let hostname = client_object["hostname"].as_str();
  236. if hostname.is_none() {
  237. return Err("hostname not found".into());
  238. }
  239. let last_query_timestamp = client_object["last_query_timestamp"].as_u64();
  240. if last_query_timestamp.is_none() {
  241. return Err("last_query_timestamp not found".into());
  242. }
  243. client_list.push(ClientData {
  244. id: id.unwrap() as u32,
  245. client_ip: client_ip.unwrap().to_string(),
  246. mac: mac.unwrap().to_string(),
  247. hostname: hostname.unwrap().to_string(),
  248. last_query_timestamp: last_query_timestamp.unwrap(),
  249. });
  250. }
  251. Ok(client_list)
  252. }
  253. pub fn api_msg_gen_json_object_client(client: &ClientData) -> serde_json::Value {
  254. json!({
  255. "id": client.id,
  256. "client_ip": client.client_ip,
  257. "mac": client.mac,
  258. "hostname": client.hostname,
  259. "last_query_timestamp": client.last_query_timestamp,
  260. })
  261. }
  262. pub fn api_msg_gen_client_list(
  263. client_list_result: &QueryClientListResult,
  264. total_page: u64,
  265. total_count: u64,
  266. ) -> String {
  267. let json_str = json!({
  268. "list_count": client_list_result.client_list.len(),
  269. "total_page": total_page,
  270. "total_count": total_count,
  271. "step_by_cursor": client_list_result.step_by_cursor,
  272. "client_list":
  273. client_list_result.client_list
  274. .iter()
  275. .map(|x| {
  276. api_msg_gen_json_object_client(x)
  277. })
  278. .collect::<Vec<serde_json::Value>>()
  279. });
  280. json_str.to_string()
  281. }
  282. pub fn api_msg_auth_token(token: &str, expired: &str) -> String {
  283. let json_str = json!({
  284. "token": token,
  285. "token_type": "Bearer",
  286. "expires_in": expired,
  287. });
  288. json_str.to_string()
  289. }
  290. pub fn api_msg_parse_auth_token(data: &str) -> Result<TokenResponse, Box<dyn Error>> {
  291. let v: serde_json::Value = serde_json::from_str(data)?;
  292. let token = v["token"].as_str();
  293. if token.is_none() {
  294. return Err("token not found".into());
  295. }
  296. let expired = v["expires_in"].as_str();
  297. if expired.is_none() {
  298. return Err("expires_in not found".into());
  299. }
  300. Ok(TokenResponse {
  301. token: token.unwrap().to_string(),
  302. expires_in: expired.unwrap().to_string(),
  303. })
  304. }
  305. pub fn api_msg_gen_cache_number(cache_number: i32) -> String {
  306. let json_str = json!({
  307. "cache_number": cache_number,
  308. });
  309. json_str.to_string()
  310. }
  311. pub fn api_msg_parse_cache_number(data: &str) -> Result<i32, Box<dyn Error>> {
  312. let v: serde_json::Value = serde_json::from_str(data)?;
  313. let cache_number = v["cache_number"].as_i64();
  314. if cache_number.is_none() {
  315. return Err("cache_number not found".into());
  316. }
  317. Ok(cache_number.unwrap() as i32)
  318. }
  319. pub fn api_msg_error(msg: &str) -> String {
  320. let json_str = json!({
  321. "error": msg,
  322. });
  323. json_str.to_string()
  324. }
  325. pub fn api_msg_parse_error(data: &str) -> Result<String, Box<dyn Error>> {
  326. let v: serde_json::Value = serde_json::from_str(data)?;
  327. let error = v["error"].as_str();
  328. if error.is_none() {
  329. return Err("error not found".into());
  330. }
  331. Ok(error.unwrap().to_string())
  332. }
  333. pub fn api_msg_parse_loglevel(data: &str) -> Result<LogLevel, Box<dyn Error>> {
  334. let v: serde_json::Value = serde_json::from_str(data)?;
  335. let loglevel = v["log_level"].as_str();
  336. if loglevel.is_none() {
  337. return Err("loglevel not found".into());
  338. }
  339. let ret = loglevel.unwrap().try_into();
  340. if ret.is_err() {
  341. return Err("log level is invalid".into());
  342. }
  343. Ok(ret.unwrap())
  344. }
  345. pub fn api_msg_gen_loglevel(loglevel: LogLevel) -> String {
  346. let loglevel_str = loglevel.to_string();
  347. let json_str = json!({
  348. "log_level": loglevel_str,
  349. });
  350. json_str.to_string()
  351. }
  352. pub fn api_msg_gen_version(smartdns_version: &str, ui_version: &str) -> String {
  353. let json_str = json!({
  354. "smartdns": smartdns_version,
  355. "smartdns_ui": ui_version,
  356. });
  357. json_str.to_string()
  358. }
  359. pub fn api_msg_gen_upstream_server_list(upstream_server_list: &Vec<UpstreamServerInfo>) -> String {
  360. let json_str = json!({
  361. "upstream_server_list":
  362. upstream_server_list
  363. .iter()
  364. .map(|x| {
  365. let s = json!({
  366. "host": x.host,
  367. "ip": x.ip,
  368. "port": x.port,
  369. "server_type": x.server_type.to_string(),
  370. "total_query_count": x.total_query_count,
  371. "total_query_success": x.total_query_success,
  372. "total_query_recv_count": x.total_query_recv_count,
  373. "query_success_rate": x.query_success_rate,
  374. "avg_time": x.avg_time,
  375. "status": x.status,
  376. "security": x.security,
  377. });
  378. s
  379. })
  380. .collect::<Vec<serde_json::Value>>()
  381. });
  382. json_str.to_string()
  383. }
  384. pub fn api_msg_parse_upstream_server_list(
  385. data: &str,
  386. ) -> Result<Vec<UpstreamServerInfo>, Box<dyn Error>> {
  387. let v: serde_json::Value = serde_json::from_str(data)?;
  388. let mut upstream_server_list = Vec::new();
  389. let server_list = v["upstream_server_list"].as_array();
  390. if server_list.is_none() {
  391. return Err("list_count not found".into());
  392. }
  393. for item in server_list.unwrap() {
  394. let host = item["host"].as_str();
  395. if host.is_none() {
  396. return Err("host not found".into());
  397. }
  398. let ip = item["ip"].as_str();
  399. if ip.is_none() {
  400. return Err("ip not found".into());
  401. }
  402. let port = item["port"].as_u64();
  403. if port.is_none() {
  404. return Err("port not found".into());
  405. }
  406. let server_type = item["server_type"].as_str();
  407. if server_type.is_none() {
  408. return Err("server_type not found".into());
  409. }
  410. let total_query_count = item["total_query_count"].as_u64();
  411. if total_query_count.is_none() {
  412. return Err("total_query_count not found".into());
  413. }
  414. let total_query_success = item["total_query_success"].as_u64();
  415. if total_query_success.is_none() {
  416. return Err("total_query_success not found".into());
  417. }
  418. let total_query_recv_count = item["total_query_recv_count"].as_u64();
  419. if total_query_recv_count.is_none() {
  420. return Err("total_query_recv_count not found".into());
  421. }
  422. let query_success_rate = item["query_success_rate"].as_f64();
  423. if query_success_rate.is_none() {
  424. return Err("query_success_rate not found".into());
  425. }
  426. let avg_time = item["avg_time"].as_f64();
  427. if avg_time.is_none() {
  428. return Err("avg_time not found".into());
  429. }
  430. let status = item["status"].as_str();
  431. if status.is_none() {
  432. return Err("status not found".into());
  433. }
  434. let security = item["security"].as_str();
  435. if security.is_none() {
  436. return Err("security not found".into());
  437. }
  438. upstream_server_list.push(UpstreamServerInfo {
  439. host: host.unwrap().to_string(),
  440. ip: ip.unwrap().to_string(),
  441. port: port.unwrap() as u16,
  442. server_type: server_type.unwrap().parse()?,
  443. total_query_count: total_query_count.unwrap() as u64,
  444. total_query_success: total_query_success.unwrap() as u64,
  445. total_query_recv_count: total_query_recv_count.unwrap() as u64,
  446. query_success_rate: query_success_rate.unwrap(),
  447. avg_time: avg_time.unwrap(),
  448. status: status.unwrap().to_string(),
  449. security: security.unwrap().to_string(),
  450. });
  451. }
  452. Ok(upstream_server_list)
  453. }
  454. pub fn api_msg_parse_version(data: &str) -> Result<(String, String), Box<dyn Error>> {
  455. let v: serde_json::Value = serde_json::from_str(data)?;
  456. let smartdns = v["smartdns"].as_str();
  457. if smartdns.is_none() {
  458. return Err("smartdns not found".into());
  459. }
  460. let ui = v["smartdns_ui"].as_str();
  461. if ui.is_none() {
  462. return Err("ui not found".into());
  463. }
  464. Ok((smartdns.unwrap().to_string(), ui.unwrap().to_string()))
  465. }
  466. pub fn api_msg_gen_key_value(data: &HashMap<String, String>) -> String {
  467. let mut json_map = serde_json::Map::new();
  468. for (key, value) in data {
  469. json_map.insert(key.clone(), serde_json::Value::String(value.clone()));
  470. }
  471. serde_json::Value::Object(json_map).to_string()
  472. }
  473. pub fn api_msg_parse_key_value(data: &str) -> Result<HashMap<String, String>, Box<dyn Error>> {
  474. let v: serde_json::Value = serde_json::from_str(data)?;
  475. let mut conf_map = HashMap::new();
  476. if let serde_json::Value::Object(map) = v {
  477. for (key, value) in map {
  478. if let serde_json::Value::String(value_str) = value {
  479. conf_map.insert(key, value_str);
  480. }
  481. }
  482. }
  483. Ok(conf_map)
  484. }
  485. pub fn api_msg_gen_top_client_list(client_list: &Vec<ClientQueryCount>) -> String {
  486. let json_str = json!({
  487. "client_top_list":
  488. client_list
  489. .iter()
  490. .map(|x| {
  491. let s = json!({
  492. "client_ip": x.client_ip,
  493. "query_count": x.count,
  494. "timestamp_start": x.timestamp_start,
  495. "timestamp_end": x.timestamp_end,
  496. });
  497. s
  498. })
  499. .collect::<Vec<serde_json::Value>>()
  500. });
  501. json_str.to_string()
  502. }
  503. pub fn api_msg_parse_top_client_list(data: &str) -> Result<Vec<ClientQueryCount>, Box<dyn Error>> {
  504. let v: serde_json::Value = serde_json::from_str(data)?;
  505. let mut client_list = Vec::new();
  506. let top_list = v["client_top_list"].as_array();
  507. if top_list.is_none() {
  508. return Err("list_count not found".into());
  509. }
  510. for item in top_list.unwrap() {
  511. let client_ip = item["client_ip"].as_str();
  512. if client_ip.is_none() {
  513. return Err("client_ip not found".into());
  514. }
  515. let query_count = item["query_count"].as_u64();
  516. if query_count.is_none() {
  517. return Err("query_count not found".into());
  518. }
  519. let timestamp_start = item["timestamp_start"].as_u64();
  520. if timestamp_start.is_none() {
  521. return Err("timestamp_start not found".into());
  522. }
  523. let timestamp_end = item["timestamp_end"].as_u64();
  524. if timestamp_end.is_none() {
  525. return Err("timestamp_end not found".into());
  526. }
  527. client_list.push(ClientQueryCount {
  528. client_ip: client_ip.unwrap().to_string(),
  529. count: query_count.unwrap() as u32,
  530. timestamp_start: timestamp_start.unwrap(),
  531. timestamp_end: timestamp_end.unwrap(),
  532. });
  533. }
  534. Ok(client_list)
  535. }
  536. pub fn api_msg_gen_top_domain_list(domain_list: &Vec<DomainQueryCount>) -> String {
  537. let json_str = json!({
  538. "domain_top_list":
  539. domain_list
  540. .iter()
  541. .map(|x| {
  542. let s = json!({
  543. "domain": x.domain,
  544. "query_count": x.count,
  545. "timestamp_start": x.timestamp_start,
  546. "timestamp_end": x.timestamp_end,
  547. });
  548. s
  549. })
  550. .collect::<Vec<serde_json::Value>>()
  551. });
  552. json_str.to_string()
  553. }
  554. pub fn api_msg_parse_top_domain_list(data: &str) -> Result<Vec<DomainQueryCount>, Box<dyn Error>> {
  555. let v: serde_json::Value = serde_json::from_str(data)?;
  556. let mut domain_list = Vec::new();
  557. let top_list = v["domain_top_list"].as_array();
  558. if top_list.is_none() {
  559. return Err("list_count not found".into());
  560. }
  561. for item in top_list.unwrap() {
  562. let domain = item["domain"].as_str();
  563. if domain.is_none() {
  564. return Err("domain not found".into());
  565. }
  566. let query_count = item["query_count"].as_u64();
  567. if query_count.is_none() {
  568. return Err("query_count not found".into());
  569. }
  570. let timestamp_start = item["timestamp_start"].as_u64();
  571. if timestamp_start.is_none() {
  572. return Err("timestamp_start not found".into());
  573. }
  574. let timestamp_end = item["timestamp_end"].as_u64();
  575. if timestamp_end.is_none() {
  576. return Err("timestamp_end not found".into());
  577. }
  578. domain_list.push(DomainQueryCount {
  579. domain: domain.unwrap().to_string(),
  580. count: query_count.unwrap() as u32,
  581. timestamp_start: timestamp_start.unwrap(),
  582. timestamp_end: timestamp_end.unwrap(),
  583. });
  584. }
  585. Ok(domain_list)
  586. }
  587. pub fn api_msg_gen_metrics_data(data: &MetricsData) -> String {
  588. let json_str = json!({
  589. "total_query_count": data.total_query_count,
  590. "block_query_count": data.block_query_count,
  591. "fail_query_count": data.fail_query_count,
  592. "avg_query_time": data.avg_query_time,
  593. "cache_hit_rate": data.cache_hit_rate,
  594. "cache_number": data.cache_number,
  595. "cache_memory_size": data.cache_memory_size,
  596. "qps": data.qps,
  597. "memory_usage": data.memory_usage,
  598. "is_metrics_suspended": data.is_metrics_suspended,
  599. });
  600. json_str.to_string()
  601. }
  602. pub fn api_msg_parse_metrics_data(data: &str) -> Result<MetricsData, Box<dyn Error>> {
  603. let v: serde_json::Value = serde_json::from_str(data)?;
  604. let total_query_count = v["total_query_count"].as_u64();
  605. if total_query_count.is_none() {
  606. return Err("total_query_count not found".into());
  607. }
  608. let block_query_count = v["block_query_count"].as_u64();
  609. if block_query_count.is_none() {
  610. return Err("block_query_count not found".into());
  611. }
  612. let fail_query_count = v["fail_query_count"].as_u64();
  613. if fail_query_count.is_none() {
  614. return Err("fail_query_count not found".into());
  615. }
  616. let avg_query_time = v["avg_query_time"].as_f64();
  617. if avg_query_time.is_none() {
  618. return Err("avg_query_time not found".into());
  619. }
  620. let cache_hit_rate = v["cache_hit_rate"].as_f64();
  621. if cache_hit_rate.is_none() {
  622. return Err("cache_hit_rate not found".into());
  623. }
  624. let cache_number = v["cache_number"].as_u64();
  625. if cache_number.is_none() {
  626. return Err("cache_number not found".into());
  627. }
  628. let cache_memory_size = v["cache_memory_size"].as_u64();
  629. if cache_memory_size.is_none() {
  630. return Err("cache_memory_size not found".into());
  631. }
  632. let qps = v["qps"].as_u64();
  633. if qps.is_none() {
  634. return Err("qps not found".into());
  635. }
  636. let memory_usage = v["memory_usage"].as_u64();
  637. if memory_usage.is_none() {
  638. return Err("memory_usage not found".into());
  639. }
  640. let is_metrics_suspended = v["is_metrics_suspended"].as_bool();
  641. Ok(MetricsData {
  642. total_query_count: total_query_count.unwrap() as u64,
  643. block_query_count: block_query_count.unwrap() as u64,
  644. fail_query_count: fail_query_count.unwrap() as u64,
  645. avg_query_time: avg_query_time.unwrap(),
  646. cache_hit_rate: cache_hit_rate.unwrap(),
  647. cache_number: cache_number.unwrap() as u64,
  648. cache_memory_size: cache_memory_size.unwrap() as u64,
  649. qps: qps.unwrap() as u32,
  650. memory_usage: memory_usage.unwrap() as u64,
  651. is_metrics_suspended: is_metrics_suspended.unwrap_or(false),
  652. })
  653. }
  654. pub fn api_msg_gen_stats_overview(data: &OverviewData) -> String {
  655. let json_str = json!({
  656. "server_name": data.server_name,
  657. "database_size": data.db_size,
  658. "startup_timestamp": data.startup_timestamp,
  659. "free_disk_space": data.free_disk_space,
  660. "is_process_suspended": data.is_process_suspended,
  661. });
  662. json_str.to_string()
  663. }
  664. pub fn api_msg_parse_stats_overview(data: &str) -> Result<OverviewData, Box<dyn Error>> {
  665. let v: serde_json::Value = serde_json::from_str(data)?;
  666. let server_name = v["server_name"].as_str();
  667. if server_name.is_none() {
  668. return Err("server_name not found".into());
  669. }
  670. let db_size = v["database_size"].as_u64();
  671. if db_size.is_none() {
  672. return Err("database_size not found".into());
  673. }
  674. let startup_timestamp = v["startup_timestamp"].as_u64();
  675. if startup_timestamp.is_none() {
  676. return Err("startup_timestamp not found".into());
  677. }
  678. let free_disk_space = v["free_disk_space"].as_u64();
  679. if free_disk_space.is_none() {
  680. return Err("free_disk_space not found".into());
  681. }
  682. let is_process_suspended = v["is_process_suspended"].as_bool();
  683. if is_process_suspended.is_none() {
  684. return Err("is_process_suspended not found".into());
  685. }
  686. Ok(OverviewData {
  687. server_name: server_name.unwrap().to_string(),
  688. db_size: db_size.unwrap() as u64,
  689. startup_timestamp: startup_timestamp.unwrap() as u64,
  690. free_disk_space: free_disk_space.unwrap() as u64,
  691. is_process_suspended: is_process_suspended.unwrap(),
  692. })
  693. }
  694. pub fn api_msg_gen_hourly_query_count(hourly_count: &HourlyQueryCount) -> String {
  695. let json_str = json!({
  696. "query_timestamp": hourly_count.query_timestamp,
  697. "hourly_query_count":
  698. hourly_count.hourly_query_count
  699. .iter()
  700. .map(|x| {
  701. let s = json!({
  702. "hour": x.hour,
  703. "query_count": x.query_count,
  704. });
  705. s
  706. })
  707. .collect::<Vec<serde_json::Value>>()
  708. });
  709. json_str.to_string()
  710. }
  711. pub fn api_msg_parse_hourly_query_count(data: &str) -> Result<HourlyQueryCount, Box<dyn Error>> {
  712. let v: serde_json::Value = serde_json::from_str(data)?;
  713. let query_timestamp = v["query_timestamp"].as_u64();
  714. if query_timestamp.is_none() {
  715. return Err("query_timestamp not found".into());
  716. }
  717. let mut hourly_query_count = Vec::new();
  718. let hourly_list = v["hourly_query_count"].as_array();
  719. if hourly_list.is_none() {
  720. return Err("hourly_query_count not found".into());
  721. }
  722. for item in hourly_list.unwrap() {
  723. let hour = item["hour"].as_str();
  724. if hour.is_none() {
  725. return Err("hour not found".into());
  726. }
  727. let query_count = item["query_count"].as_u64();
  728. if query_count.is_none() {
  729. return Err("query_count not found".into());
  730. }
  731. hourly_query_count.push(HourlyQueryCountItem {
  732. hour: hour.unwrap().to_string(),
  733. query_count: query_count.unwrap() as u32,
  734. });
  735. }
  736. Ok(HourlyQueryCount {
  737. query_timestamp: query_timestamp.unwrap(),
  738. hourly_query_count: hourly_query_count,
  739. })
  740. }
  741. pub fn api_msg_gen_request_qps(qps: u32) -> String {
  742. let json_str = json!({
  743. "qps": qps,
  744. });
  745. json_str.to_string()
  746. }
  747. pub fn api_msg_gen_daily_query_count(daily_count: &DailyQueryCount) -> String {
  748. let json_str = json!({
  749. "query_timestamp": daily_count.query_timestamp,
  750. "daily_query_count":
  751. daily_count.daily_query_count
  752. .iter()
  753. .map(|x| {
  754. let s = json!({
  755. "day": x.day,
  756. "query_count": x.query_count,
  757. });
  758. s
  759. })
  760. .collect::<Vec<serde_json::Value>>()
  761. });
  762. json_str.to_string()
  763. }
  764. pub fn api_msg_parse_daily_query_count(data: &str) -> Result<DailyQueryCount, Box<dyn Error>> {
  765. let v: serde_json::Value = serde_json::from_str(data)?;
  766. let mut daily_query_count = Vec::new();
  767. let query_timestamp = v["query_timestamp"].as_u64();
  768. if query_timestamp.is_none() {
  769. return Err("query_timestamp not found".into());
  770. }
  771. let daily_list = v["daily_query_count"].as_array();
  772. if daily_list.is_none() {
  773. return Err("daily_query_count not found".into());
  774. }
  775. for item in daily_list.unwrap() {
  776. let day = item["day"].as_str();
  777. if day.is_none() {
  778. return Err("day not found".into());
  779. }
  780. let query_count = item["query_count"].as_u64();
  781. if query_count.is_none() {
  782. return Err("query_count not found".into());
  783. }
  784. daily_query_count.push(DailyQueryCountItem {
  785. day: day.unwrap().to_string(),
  786. query_count: query_count.unwrap() as u32,
  787. });
  788. }
  789. Ok(DailyQueryCount {
  790. query_timestamp: query_timestamp.unwrap(),
  791. daily_query_count: daily_query_count,
  792. })
  793. }
  794. pub fn api_msg_gen_whois_info(data: &WhoIsInfo) -> String {
  795. let json_str = json!({
  796. "domain": data.domain,
  797. "registrar": data.registrar,
  798. "organization": data.organization,
  799. "address": data.address,
  800. "city": data.city,
  801. "country": data.country,
  802. });
  803. json_str.to_string()
  804. }
  805. pub fn api_msg_parse_whois_info(data: &str) -> Result<WhoIsInfo, Box<dyn Error>> {
  806. let v: serde_json::Value = serde_json::from_str(data)?;
  807. let domain = v["domain"].as_str();
  808. if domain.is_none() {
  809. return Err("domain not found".into());
  810. }
  811. let registrar = v["registrar"].as_str();
  812. if registrar.is_none() {
  813. return Err("registrar not found".into());
  814. }
  815. let organization = v["organization"].as_str();
  816. if organization.is_none() {
  817. return Err("organization not found".into());
  818. }
  819. let address = v["address"].as_str();
  820. if address.is_none() {
  821. return Err("address not found".into());
  822. }
  823. let city = v["city"].as_str();
  824. if city.is_none() {
  825. return Err("city not found".into());
  826. }
  827. let country = v["country"].as_str();
  828. if country.is_none() {
  829. return Err("country not found".into());
  830. }
  831. let refer = v["refer"].as_str();
  832. let refer = if refer.is_none() {
  833. String::new()
  834. } else {
  835. refer.unwrap().to_string()
  836. };
  837. Ok(WhoIsInfo {
  838. refer: refer,
  839. domain: domain.unwrap().to_string(),
  840. registrar: registrar.unwrap().to_string(),
  841. organization: organization.unwrap().to_string(),
  842. address: address.unwrap().to_string(),
  843. city: city.unwrap().to_string(),
  844. country: country.unwrap().to_string(),
  845. })
  846. }