data_stats.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 std::{
  19. collections::HashMap,
  20. error::Error,
  21. sync::{atomic::AtomicU32, RwLock},
  22. };
  23. use crate::{data_server::DataServerConfig, db::*, dns_log, smartdns::*, utils};
  24. use std::sync::{
  25. atomic::{AtomicBool, Ordering},
  26. Arc, Mutex,
  27. };
  28. #[cfg(target_has_atomic = "64")]
  29. use std::sync::atomic::AtomicU64;
  30. use std::time::Duration;
  31. use tokio::sync::mpsc;
  32. use tokio::time::{interval_at, Instant};
  33. #[cfg(target_has_atomic = "64")]
  34. struct DataStatsItem {
  35. total_request: AtomicU64,
  36. total_blocked_request: AtomicU64,
  37. total_failed_request: AtomicU64,
  38. qps: AtomicU32,
  39. qps_count: AtomicU32,
  40. request_dropped: AtomicU64,
  41. }
  42. #[cfg(not(target_has_atomic = "64"))]
  43. struct DataStatsItem {
  44. total_request: Arc<Mutex<u64>>,
  45. total_blocked_request: Arc<Mutex<u64>>,
  46. total_failed_request: Arc<Mutex<u64>>,
  47. qps: AtomicU32,
  48. qps_count: AtomicU32,
  49. request_dropped: Arc<Mutex<u64>>,
  50. }
  51. impl DataStatsItem {
  52. pub fn new() -> Self {
  53. #[cfg(target_has_atomic = "64")]
  54. let ret = DataStatsItem {
  55. total_request: 0.into(),
  56. total_blocked_request: 0.into(),
  57. total_failed_request: 0.into(),
  58. qps: 0.into(),
  59. qps_count: 0.into(),
  60. request_dropped: 0.into(),
  61. };
  62. #[cfg(not(target_has_atomic = "64"))]
  63. let ret = DataStatsItem {
  64. total_request: Arc::new(Mutex::new(0)),
  65. total_blocked_request: Arc::new(Mutex::new(0)),
  66. total_failed_request: Arc::new(Mutex::new(0)),
  67. qps: 0.into(),
  68. qps_count: 0.into(),
  69. request_dropped: Arc::new(Mutex::new(0)),
  70. };
  71. return ret;
  72. }
  73. pub fn get_qps(&self) -> u32 {
  74. return self.qps.load(Ordering::Relaxed);
  75. }
  76. pub fn add_qps_count(&self, count: u32) {
  77. self.qps_count.fetch_add(count, Ordering::Relaxed);
  78. }
  79. pub fn update_qps(&self) {
  80. let qps = self.qps_count.fetch_and(0, Ordering::Relaxed);
  81. self.qps.store(qps, Ordering::Relaxed);
  82. }
  83. pub fn add_request_drop(&self, count: u64) {
  84. #[cfg(target_has_atomic = "64")]
  85. {
  86. self.request_dropped.fetch_and(count, Ordering::Relaxed);
  87. }
  88. #[cfg(not(target_has_atomic = "64"))]
  89. {
  90. let mut dropped = self.request_dropped.lock().unwrap();
  91. *dropped += count;
  92. }
  93. }
  94. pub fn get_request_drop(&self) -> u64 {
  95. #[cfg(target_has_atomic = "64")]
  96. {
  97. return self.request_dropped.load(Ordering::Relaxed);
  98. }
  99. #[cfg(not(target_has_atomic = "64"))]
  100. {
  101. let dropped = self.request_dropped.lock().unwrap();
  102. return *dropped;
  103. }
  104. }
  105. pub fn get_total_request(&self) -> u64 {
  106. #[cfg(target_has_atomic = "64")]
  107. {
  108. return self.total_request.load(Ordering::Relaxed);
  109. }
  110. #[cfg(not(target_has_atomic = "64"))]
  111. {
  112. let total = self.total_request.lock().unwrap();
  113. return *total;
  114. }
  115. }
  116. pub fn add_total_request(&self, total: u64) {
  117. #[cfg(target_has_atomic = "64")]
  118. {
  119. self.total_request.fetch_add(total, Ordering::Relaxed);
  120. }
  121. #[cfg(not(target_has_atomic = "64"))]
  122. {
  123. let mut total_request = self.total_request.lock().unwrap();
  124. *total_request += total;
  125. }
  126. }
  127. pub fn get_total_blocked_request(&self) -> u64 {
  128. #[cfg(target_has_atomic = "64")]
  129. {
  130. return self.total_blocked_request.load(Ordering::Relaxed);
  131. }
  132. #[cfg(not(target_has_atomic = "64"))]
  133. {
  134. let total = self.total_blocked_request.lock().unwrap();
  135. return *total;
  136. }
  137. }
  138. pub fn add_total_blocked_request(&self, total: u64) {
  139. #[cfg(target_has_atomic = "64")]
  140. {
  141. self.total_blocked_request
  142. .fetch_add(total, Ordering::Relaxed);
  143. }
  144. #[cfg(not(target_has_atomic = "64"))]
  145. {
  146. let mut total_blocked_request = self.total_blocked_request.lock().unwrap();
  147. *total_blocked_request += total;
  148. }
  149. }
  150. pub fn add_total_failed_request(&self, total: u64) {
  151. #[cfg(target_has_atomic = "64")]
  152. {
  153. self.total_failed_request
  154. .fetch_add(total, Ordering::Relaxed);
  155. }
  156. #[cfg(not(target_has_atomic = "64"))]
  157. {
  158. let mut total_failed_request = self.total_failed_request.lock().unwrap();
  159. *total_failed_request += total;
  160. }
  161. }
  162. pub fn get_total_failed_request(&self) -> u64 {
  163. #[cfg(target_has_atomic = "64")]
  164. {
  165. return self.total_failed_request.load(Ordering::Relaxed);
  166. }
  167. #[cfg(not(target_has_atomic = "64"))]
  168. {
  169. let total = self.total_failed_request.lock().unwrap();
  170. return *total;
  171. }
  172. }
  173. #[allow(dead_code)]
  174. pub fn get_current_hour_total(&self) -> u64 {
  175. return Stats::get_request_total();
  176. }
  177. }
  178. pub struct DataStats {
  179. task: Mutex<Option<tokio::task::JoinHandle<()>>>,
  180. notify_tx: Option<mpsc::Sender<()>>,
  181. notify_rx: Mutex<Option<mpsc::Receiver<()>>>,
  182. is_run: AtomicBool,
  183. data: DataStatsItem,
  184. db: Arc<crate::db::DB>,
  185. conf: Arc<RwLock<DataServerConfig>>,
  186. is_hourly_work_running: AtomicBool,
  187. }
  188. impl DataStats {
  189. pub fn new(db: Arc<crate::db::DB>, conf: Arc<RwLock<DataServerConfig>>) -> Arc<Self> {
  190. let (tx, rx) = mpsc::channel(100);
  191. Arc::new(DataStats {
  192. task: Mutex::new(None),
  193. notify_rx: Mutex::new(Some(rx)),
  194. notify_tx: Some(tx),
  195. is_run: AtomicBool::new(false),
  196. data: DataStatsItem::new(),
  197. db: db,
  198. conf: conf,
  199. is_hourly_work_running: AtomicBool::new(false),
  200. })
  201. }
  202. pub fn get_qps(&self) -> u32 {
  203. return self.data.get_qps();
  204. }
  205. pub fn add_qps_count(&self, count: u32) {
  206. self.data.add_qps_count(count);
  207. }
  208. pub fn update_qps(&self) {
  209. self.data.update_qps();
  210. }
  211. pub fn add_request_drop(&self, count: u64) {
  212. self.data.add_request_drop(count);
  213. }
  214. pub fn get_request_drop(&self) -> u64 {
  215. return self.data.get_request_drop();
  216. }
  217. pub fn get_total_blocked_request(&self) -> u64 {
  218. return self.data.get_total_blocked_request();
  219. }
  220. pub fn add_total_blocked_request(&self, total: u64) {
  221. self.data.add_total_blocked_request(total);
  222. }
  223. pub fn get_total_failed_request(&self) -> u64 {
  224. return self.data.get_total_failed_request();
  225. }
  226. pub fn add_total_failed_request(&self, total: u64) {
  227. self.data.add_total_failed_request(total);
  228. }
  229. pub fn get_total_request(&self) -> u64 {
  230. return self.data.get_total_request();
  231. }
  232. pub fn get_current_hour_total(&self) -> u64 {
  233. return self.data.get_current_hour_total();
  234. }
  235. pub fn add_total_request(&self, total: u64) {
  236. self.data.add_total_request(total);
  237. }
  238. pub fn get_memory_usage(&self) -> u64 {
  239. let statm_path = "/proc/self/statm";
  240. let statm = std::fs::read_to_string(statm_path);
  241. if let Err(_) = statm {
  242. return 0;
  243. }
  244. let statm = statm.unwrap();
  245. let statm: Vec<&str> = statm.split_whitespace().collect();
  246. if statm.len() < 2 {
  247. return 0;
  248. }
  249. let pages = statm[1].parse::<u64>();
  250. if let Err(_) = pages {
  251. return 0;
  252. }
  253. let pages = pages.unwrap();
  254. let pagesizie = utils::get_page_size() as u64;
  255. return pages * pagesizie;
  256. }
  257. pub fn init(self: &Arc<Self>) -> Result<(), Box<dyn Error>> {
  258. dns_log!(LogLevel::DEBUG, "init data stats");
  259. self.load_status_data()?;
  260. Ok(())
  261. }
  262. pub fn load_status_data(self: &Arc<Self>) -> Result<(), Box<dyn Error>> {
  263. let status_data = match self.db.get_status_data_list() {
  264. Ok(data) => data,
  265. Err(_) => HashMap::new(),
  266. };
  267. // load total request count
  268. let mut total_count = 0 as u64;
  269. let status_data_total_count = status_data.get("total_request");
  270. if status_data_total_count.is_some() {
  271. let count = status_data_total_count.unwrap().parse::<u64>();
  272. if let Ok(count) = count {
  273. total_count = count;
  274. } else {
  275. total_count = 0;
  276. }
  277. }
  278. if total_count == 0 {
  279. let count = self.db.get_domain_list_count(None);
  280. total_count = count;
  281. }
  282. self.data.add_total_request(total_count);
  283. // load total blocked request
  284. let mut total_blocked_count = 0 as u64;
  285. let status_data_total_blocked_count = status_data.get("total_blocked_request");
  286. if status_data_total_blocked_count.is_some() {
  287. let count = status_data_total_blocked_count.unwrap().parse::<u64>();
  288. if let Ok(count) = count {
  289. total_blocked_count = count;
  290. } else {
  291. total_blocked_count = 0;
  292. }
  293. }
  294. if total_blocked_count == 0 {
  295. let mut parm = DomainListGetParam::new();
  296. parm.is_blocked = Some(true);
  297. let count = self.db.get_domain_list_count(Some(&parm));
  298. total_blocked_count = count;
  299. }
  300. self.data.add_total_blocked_request(total_blocked_count);
  301. // load request drop count
  302. let mut request_drop = 0 as u64;
  303. let status_data_request_drop = status_data.get("request_drop");
  304. if status_data_request_drop.is_some() {
  305. let count = status_data_request_drop.unwrap().parse::<u64>();
  306. if let Ok(count) = count {
  307. request_drop = count;
  308. } else {
  309. request_drop = 0;
  310. }
  311. }
  312. self.data.add_request_drop(request_drop);
  313. // load total failed request
  314. let mut total_failed_count = 0 as u64;
  315. let status_data_total_failed_count = status_data.get("total_failed_request");
  316. if status_data_total_failed_count.is_some() {
  317. let count = status_data_total_failed_count.unwrap().parse::<u64>();
  318. if let Ok(count) = count {
  319. total_failed_count = count;
  320. } else {
  321. total_failed_count = 0;
  322. }
  323. }
  324. self.data.add_total_failed_request(total_failed_count);
  325. Ok(())
  326. }
  327. pub fn save_status_data(self: &Arc<Self>) -> Result<(), Box<dyn Error>> {
  328. self.db.set_status_data(
  329. "total_request",
  330. self.get_total_request().to_string().as_str(),
  331. )?;
  332. self.db.set_status_data(
  333. "total_blocked_request",
  334. self.get_total_blocked_request().to_string().as_str(),
  335. )?;
  336. self.db.set_status_data(
  337. "total_failed_request",
  338. self.get_total_failed_request().to_string().as_str(),
  339. )?;
  340. self.db.set_status_data(
  341. "request_drop",
  342. self.get_request_drop().to_string().as_str(),
  343. )?;
  344. Ok(())
  345. }
  346. pub fn start_worker(self: &Arc<Self>) -> Result<(), Box<dyn Error>> {
  347. let this = self.clone();
  348. let task = tokio::spawn(async move {
  349. DataStats::worker_loop(&this).await;
  350. });
  351. *(self.task.lock().unwrap()) = Some(task);
  352. self.is_run.store(true, Ordering::Relaxed);
  353. Ok(())
  354. }
  355. pub fn refresh(self: &Arc<Self>) {
  356. let now = get_utc_time_ms();
  357. let ret = self
  358. .db
  359. .delete_domain_before_timestamp(now - self.conf.read().unwrap().max_log_age_ms as u64);
  360. if let Err(e) = ret {
  361. if e.to_string() == "Query returned no rows" {
  362. return;
  363. }
  364. dns_log!(
  365. LogLevel::WARN,
  366. "delete domain before timestamp error: {}",
  367. e
  368. );
  369. }
  370. let ret = self.db.refresh_client_top_list(now - 7 * 24 * 3600 * 1000);
  371. if let Err(e) = ret {
  372. dns_log!(LogLevel::WARN, "refresh client top list error: {}", e);
  373. }
  374. let ret = self.db.refresh_domain_top_list(now - 7 * 24 * 3600 * 1000);
  375. if let Err(e) = ret {
  376. dns_log!(LogLevel::WARN, "refresh domain top list error: {}", e);
  377. }
  378. let _ = self
  379. .db
  380. .delete_hourly_query_count_before_timestamp(30 * 24 * 3600 * 1000);
  381. let _ = self
  382. .db
  383. .delete_daily_query_count_before_timestamp(90 * 24 * 3600 * 1000);
  384. }
  385. async fn update_stats(self: &Arc<Self>) {
  386. if self
  387. .is_hourly_work_running
  388. .fetch_or(true, Ordering::Acquire)
  389. {
  390. return;
  391. }
  392. let this = self.clone();
  393. tokio::task::spawn_blocking(move || {
  394. this.refresh();
  395. this.is_hourly_work_running.store(false, Ordering::Release);
  396. });
  397. }
  398. async fn worker_loop(this: &Arc<Self>) {
  399. let mut rx: mpsc::Receiver<()>;
  400. {
  401. let mut _rx = this.notify_rx.lock().unwrap();
  402. rx = _rx.take().unwrap();
  403. }
  404. this.clone().update_stats().await;
  405. let start: Instant = Instant::now() + Duration::from_secs(utils::seconds_until_next_hour());
  406. let mut hour_timer = interval_at(start, Duration::from_secs(60 * 60));
  407. let mut second_timer = interval_at(Instant::now(), Duration::from_secs(1));
  408. loop {
  409. tokio::select! {
  410. _ = rx.recv() => {
  411. break;
  412. }
  413. _ = second_timer.tick() => {
  414. this.update_qps();
  415. }
  416. _ = hour_timer.tick() => {
  417. this.update_stats().await;
  418. }
  419. }
  420. }
  421. let ret = this.save_status_data();
  422. if let Err(e) = ret {
  423. dns_log!(LogLevel::WARN, "save status data error: {}", e);
  424. }
  425. }
  426. pub fn stop_worker(&self) {
  427. if self.is_run.load(Ordering::Relaxed) == false {
  428. return;
  429. }
  430. if let Some(tx) = self.notify_tx.as_ref().cloned() {
  431. let _ = tx.try_send(());
  432. }
  433. let mut task = self.task.lock().unwrap();
  434. if let Some(task) = task.take() {
  435. tokio::task::block_in_place(|| {
  436. let _ = tokio::runtime::Handle::current().block_on(task);
  437. });
  438. }
  439. self.is_run.store(false, Ordering::Relaxed);
  440. }
  441. }
  442. impl Drop for DataStats {
  443. fn drop(&mut self) {
  444. self.stop_worker();
  445. }
  446. }