|
| 1 | +/* |
| 2 | + * Parseable Server (C) 2022 - 2024 Parseable, Inc. |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU Affero General Public License as |
| 6 | + * published by the Free Software Foundation, either version 3 of the |
| 7 | + * License, or (at your option) any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU Affero General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU Affero General Public License |
| 15 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | + * |
| 17 | + */ |
| 18 | + |
| 19 | +use std::ffi::CString; |
| 20 | +use std::time::Duration; |
| 21 | + |
| 22 | +use clokwerk::AsyncScheduler; |
| 23 | +use tracing::{info, warn}; |
| 24 | + |
| 25 | +/// Force memory release using jemalloc |
| 26 | +pub fn force_memory_release() { |
| 27 | + // Advance epoch to refresh statistics and trigger potential cleanup |
| 28 | + if let Err(e) = tikv_jemalloc_ctl::epoch::mib().and_then(|mib| mib.advance()) { |
| 29 | + warn!("Failed to advance jemalloc epoch: {:?}", e); |
| 30 | + } |
| 31 | + |
| 32 | + // Purge each initialized arena |
| 33 | + if let Ok(n) = tikv_jemalloc_ctl::arenas::narenas::read() { |
| 34 | + for i in 0..n { |
| 35 | + if let Ok(name) = CString::new(format!("arena.{i}.purge")) { |
| 36 | + unsafe { |
| 37 | + let ret = tikv_jemalloc_sys::mallctl( |
| 38 | + name.as_ptr(), |
| 39 | + std::ptr::null_mut(), |
| 40 | + std::ptr::null_mut(), |
| 41 | + std::ptr::null_mut(), |
| 42 | + 0, |
| 43 | + ); |
| 44 | + if ret != 0 { |
| 45 | + warn!("Arena purge failed for index {i} with code: {ret}"); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } else { |
| 51 | + warn!("Failed to read jemalloc arenas.narenas"); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/// Initialize memory management scheduler |
| 56 | +pub fn init_memory_release_scheduler() -> anyhow::Result<()> { |
| 57 | + info!("Setting up scheduler for memory release"); |
| 58 | + |
| 59 | + let mut scheduler = AsyncScheduler::new(); |
| 60 | + scheduler |
| 61 | + .every(clokwerk::Interval::Hours(1)) |
| 62 | + .run(move || async { |
| 63 | + info!("Running scheduled memory release"); |
| 64 | + force_memory_release(); |
| 65 | + }); |
| 66 | + |
| 67 | + tokio::spawn(async move { |
| 68 | + loop { |
| 69 | + scheduler.run_pending().await; |
| 70 | + tokio::time::sleep(Duration::from_secs(60)).await; // Check every minute |
| 71 | + } |
| 72 | + }); |
| 73 | + |
| 74 | + Ok(()) |
| 75 | +} |
0 commit comments