diff --git a/Cargo.toml b/Cargo.toml index b7d467ed3d5d3e1f404aef6dab83e87be3bd6f08..f06d345ffea1681f6552b31970f23411b5ba2a3a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ linux = [ "column", "setsid", "sha256sum", + "vmstat", "killall", "md5sum", "sysctl", @@ -82,6 +83,7 @@ members = [ "src/oe/column", "src/oe/setsid", "src/oe/sha256sum", + "src/oe/vmstat", "src/oe/killall", "src/oe/md5sum", "src/oe/iostat", @@ -128,6 +130,7 @@ usleep = { optional=true, version="0.0.1", package="oe_usleep", path="src/oe/usl column = { optional=true, version="0.0.1", package="oe_column", path="src/oe/column" } setsid = { optional=true, version="0.0.1", package="oe_setsid", path="src/oe/setsid" } sha256sum = { optional=true, version="0.0.1", package="oe_sha256sum", path="src/oe/sha256sum" } +vmstat = { optional=true, version="0.0.1", package="oe_vmstat", path="src/oe/vmstat" } killall = { optional=true, version="0.0.1", package="oe_killall", path="src/oe/killall" } md5sum = { optional=true, version="0.0.1", package="oe_md5sum", path="src/oe/md5sum" } iostat = { optional=true, version="0.0.1", package="oe_iostat", path="src/oe/iostat" } diff --git a/src/oe/vmstat/Cargo.toml b/src/oe/vmstat/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..671b68905d39977d37854971e565ec958c2740e0 --- /dev/null +++ b/src/oe/vmstat/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "oe_vmstat" +version = "0.0.1" +authors = ["openeuler developers"] +license = "MulanPSL-2.0" +description = "" + +homepage = "https://gitee.com/openeuler/easybox" +repository = "https://gitee.com/openeuler/easybox/tree/master/src/oe/vmstat" +keywords = ["coreutils", "easybox", "util-linux", "cli", "utility"] +categories = ["command-line-utilities"] +edition = "2021" + +[lib] +path = "src/vmstat.rs" + +[dependencies] +clap = { version = "3.2.0", features = ["wrap_help", "cargo"] } +uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features = ["pretty_float"] } + +[[bin]] +name = "vmstat" +path = "src/main.rs" diff --git a/src/oe/vmstat/LICENSE b/src/oe/vmstat/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a589e86a28c0a587f8647e4c416fbbaaf55be347 --- /dev/null +++ b/src/oe/vmstat/LICENSE @@ -0,0 +1,127 @@ + 木兰宽松许可证, 第2版 + + 木兰宽松许可证, 第2版 + 2020年1月 http://license.coscl.org.cn/MulanPSL2 + + + 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束: + + 0. 定义 + + “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 + + “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 + + “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 + + “法人实体”是指提交贡献的机构及其“关联实体”。 + + “关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 + + 1. 授予版权许可 + + 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 + + 2. 授予专利许可 + + 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 + + 3. 无商标许可 + + “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 + + 4. 分发限制 + + 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 + + 5. 免责声明与责任限制 + + “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 + + 6. 语言 + “本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。 + + 条款结束 + + 如何将木兰宽松许可证,第2版,应用到您的软件 + + 如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: + + 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; + + 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; + + 3, 请将如下声明文本放入每个源文件的头部注释中。 + + Copyright (c) [Year] [name of copyright holder] + [Software Name] is licensed under Mulan PSL v2. + You can use this software according to the terms and conditions of the Mulan PSL v2. + You may obtain a copy of Mulan PSL v2 at: + http://license.coscl.org.cn/MulanPSL2 + THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + See the Mulan PSL v2 for more details. + + + Mulan Permissive Software License,Version 2 + + Mulan Permissive Software License,Version 2 (Mulan PSL v2) + January 2020 http://license.coscl.org.cn/MulanPSL2 + + Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions: + + 0. Definition + + Software means the program and related documents which are licensed under this License and comprise all Contribution(s). + + Contribution means the copyrightable work licensed by a particular Contributor under this License. + + Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. + + Legal Entity means the entity making a Contribution and all its Affiliates. + + Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. + + 1. Grant of Copyright License + + Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. + + 2. Grant of Patent License + + Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. + + 3. No Trademark License + + No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4. + + 4. Distribution Restriction + + You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. + + 5. Disclaimer of Warranty and Limitation of Liability + + THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 6. Language + + THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL. + + END OF THE TERMS AND CONDITIONS + + How to Apply the Mulan Permissive Software License,Version 2 (Mulan PSL v2) to Your Software + + To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps: + + i Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner; + + ii Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package; + + iii Attach the statement to the appropriate annotated syntax at the beginning of each source file. + + + Copyright (c) [Year] [name of copyright holder] + [Software Name] is licensed under Mulan PSL v2. + You can use this software according to the terms and conditions of the Mulan PSL v2. + You may obtain a copy of Mulan PSL v2 at: + http://license.coscl.org.cn/MulanPSL2 + THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + See the Mulan PSL v2 for more details. diff --git a/src/oe/vmstat/src/lib_vmstat.rs b/src/oe/vmstat/src/lib_vmstat.rs new file mode 100644 index 0000000000000000000000000000000000000000..c9aa2ffb76887cb7ba5f5f6633067a43e97f846b --- /dev/null +++ b/src/oe/vmstat/src/lib_vmstat.rs @@ -0,0 +1,1017 @@ +//! This file is part of the easybox package. +// +// (c) Chenhao Fang +// +// For the full copyright and license information, please view the LICENSE file +// that was distributed with this source code. + +use std::cmp::Ordering; +use std::ffi::CString; +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::PathBuf; +use uucore::libc; + +#[derive(Debug, Default)] +/// +pub struct ProcStatInfo { + /// cpu user + pub cpu_use: [u64; 2], + /// cpu nice + pub cpu_nic: [u64; 2], + /// cpu system + pub cpu_sys: [u64; 2], + /// cpu idle + pub cpu_idl: [u64; 2], + /// cpu iowait + pub cpu_iow: [u64; 2], + /// cpu irq + pub cpu_xxx: [u64; 2], + /// cpu softirq + pub cpu_yyy: [u64; 2], + /// cpu softirq + pub cpu_zzz: [u64; 2], + /// cpu guest + pub cpu_gst: [u64; 2], + /// cpu guest_nice + pub cpu_gni: [u64; 2], + /// interrupt + pub intr: [u64; 2], + /// context switch + pub ctxt: [u64; 2], + /// btime + pub btime: u64, + /// processes + pub process: u64, + /// procs_runing + pub running: u64, + /// procs_blocked + pub blocked: u64, +} + +#[derive(Debug, Default)] +/// +pub struct ProcMemInfo { + /// + pub kb_active: u64, + /// + pub kb_active_file: u64, + /// + pub kb_anon_pages: u64, + /// + pub kb_bounce: u64, + /// + pub kb_main_buffers: u64, + /// + pub kb_page_cache: u64, + /// + pub kb_commit_limit: u64, + /// + pub kb_committed_as: u64, + /// + pub kb_dirty: u64, // kB version of vmstat nr_dirty + /// + pub kb_high_free: u64, + /// + pub kb_high_total: u64, + /// + pub kb_inact_clean: u64, + /// + pub kb_inact_dirty: u64, + /// + pub kb_inact_laundry: u64, + /// + pub kb_inact_target: u64, + /// + pub kb_inactive: u64, // important + /// + pub kb_inactive_file: u64, + /// + pub kb_low_free: u64, + /// + pub kb_low_total: u64, + /// + pub kb_mapped: u64, // kB version of vmstat nr_mapped + /// + pub kb_main_available: u64, // important + /// + pub kb_main_free: u64, // important + /// + pub kb_main_total: u64, // important + /// + pub kb_nfs_unstable: u64, + /// + pub kb_pagetables: u64, // kB version of vmstat nr_page_table_pages + /// + pub nr_reversemaps: u64, // same as vmstat nr_page_table_pages + /// + pub kb_slab_reclaimable: u64, // "slab reclaimable" (dentry and inode structures) + /// + pub kb_slab_unreclaimable: u64, + /// + pub kb_main_shared: u64, // kernel 2.6.32 and later + /// + pub kb_slab: u64, // kB version of vmstat nr_slab + /// + pub kb_swap_cached: u64, + /// + pub kb_swap_free: u64, // important + /// + pub kb_swap_total: u64, // important + /// + pub kb_vmalloc_chunk: u64, + /// + pub kb_vmalloc_total: u64, + /// + pub kb_vmalloc_used: u64, + /// + pub kb_writeback: u64, + /// + pub kb_main_cached: u64, + /// + pub kb_swap_used: u64, + /// + pub kb_main_used: u64, + /// + pub kb_min_free: u64, +} + +#[derive(Debug, Default)] +/// +pub struct ProcVmStatInfo { + /// + pub vm_allocstall: u64, + /// + pub vm_kswapd_inodesteal: u64, + /// + pub vm_kswapd_steal: u64, + /// + pub vm_nr_active_file: u64, + /// + pub vm_nr_dirty: u64, + /// + pub vm_nr_free_pages: u64, + /// + pub vm_nr_inactive_file: u64, + /// + pub vm_nr_mapped: u64, + /// + pub vm_nr_page_table_pages: u64, + /// + pub vm_nr_pagecache: u64, + /// + pub vm_nr_reverse_maps: u64, + /// + pub vm_nr_slab: u64, + /// + pub vm_nr_slab_reclaimable: u64, + /// + pub vm_nr_slab_unreclaimable: u64, + /// + pub vm_nr_unstable: u64, + /// + pub vm_nr_writeback: u64, + /// + pub vm_pageoutrun: u64, + /// + pub vm_pgactivate: u64, + /// + pub vm_pgalloc: u64, + /// + pub vm_pgalloc_dma: u64, + /// + pub vm_pgalloc_high: u64, + /// + pub vm_pgalloc_normal: u64, + /// + pub vm_pgdeactivate: u64, + /// + pub vm_pgfault: u64, + /// + pub vm_pgfree: u64, + /// + pub vm_pginodesteal: u64, + /// + pub vm_pgmajfault: u64, + /// + pub vm_pgpgin: [u64; 2], + /// + pub vm_pgpgout: [u64; 2], + /// + pub vm_pgrefill: u64, + /// + pub vm_pgrefill_dma: u64, + /// + pub vm_pgrefill_high: u64, + /// + pub vm_pgrefill_normal: u64, + /// + pub vm_pgrotated: u64, + /// + pub vm_pgscan: u64, + /// + pub vm_pgscan_direct_dma: u64, + /// + pub vm_pgscan_direct_high: u64, + /// + pub vm_pgscan_direct_normal: u64, + /// + pub vm_pgscan_kswapd_dma: u64, + /// + pub vm_pgscan_kswapd_high: u64, + /// + pub vm_pgscan_kswapd_normal: u64, + /// + pub vm_pgsteal: u64, + /// + pub vm_pgsteal_dma: u64, + /// + pub vm_pgsteal_high: u64, + /// + pub vm_pgsteal_normal: u64, + /// + pub vm_pswpin: [u64; 2], + /// + pub vm_pswpout: [u64; 2], + /// + pub vm_slabs_scanned: u64, +} + +#[derive(Debug, Default)] +/// +pub struct CalInfo { + /// + pub duse: u64, + /// + pub dsys: u64, + /// + pub didl: u64, + /// + pub diow: u64, + /// + pub dstl: u64, + /// + pub dgue: u64, + /// + pub div: u64, + /// + pub divo2: u64, + /// + pub pgpgin: u64, + /// + pub pgpgout: u64, + /// + pub pswpin: u64, + /// + pub pswpout: u64, + /// + pub intr: u64, + /// + pub ctxt: u64, +} + +/// +pub struct Stat { + /// + pub stat_fd: File, + /// + pub mem_fd: File, + /// + pub vmstat_fd: File, + /// + pub tog: usize, + /// + pub mem_info: ProcMemInfo, + /// + pub cpu_info: ProcStatInfo, + /// + pub vmstat_info: ProcVmStatInfo, + /// + pub cal: CalInfo, +} + +impl Stat { + /// + pub fn new() -> Self { + let tog = 0; + let mem_fd = File::open("/proc/meminfo").unwrap(); + let stat_fd = File::open("/proc/stat").unwrap(); + let vmstat_fd = File::open("/proc/vmstat").unwrap(); + + Self { + stat_fd, + mem_fd, + vmstat_fd, + tog, + mem_info: ProcMemInfo::default(), + cpu_info: ProcStatInfo::default(), + vmstat_info: ProcVmStatInfo::default(), + cal: CalInfo::default(), + } + } + + /// refresh stat info + pub fn refresh(&mut self) { + self.stat_fd.seek(SeekFrom::Start(0)).unwrap(); + self.vmstat_fd.seek(SeekFrom::Start(0)).unwrap(); + self.mem_fd.seek(SeekFrom::Start(0)).unwrap(); + + self.get_mem_info(); + self.get_cpu_info(); + self.get_vm_info(); + self.tog = 1 - self.tog; + + //self.cal.duse = self.cpu_info.cpu_use[self.tog] - self.cpu_info.cpu_use[1 - self.tog] + + // self.cpu_info.cpu_nic[self.tog] - self.cpu_info.cpu_nic[1 - self.tog]; + } + + /// get cpu info + fn get_cpu_info(&mut self) { + let mut contents = String::new(); + self.stat_fd.read_to_string(&mut contents).unwrap(); + + for line in contents.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + match parts.get(0) { + Some(&"cpu") if parts.len() > 1 => { + self.cpu_info.cpu_use[self.tog] = parts.get(1).unwrap().parse::().unwrap(); + self.cpu_info.cpu_nic[self.tog] = parts.get(2).unwrap().parse::().unwrap(); + self.cpu_info.cpu_sys[self.tog] = parts.get(3).unwrap().parse::().unwrap(); + self.cpu_info.cpu_idl[self.tog] = parts.get(4).unwrap().parse::().unwrap(); + self.cpu_info.cpu_iow[self.tog] = parts.get(5).unwrap().parse::().unwrap(); + self.cpu_info.cpu_xxx[self.tog] = parts.get(6).unwrap().parse::().unwrap(); + self.cpu_info.cpu_yyy[self.tog] = parts.get(7).unwrap().parse::().unwrap(); + self.cpu_info.cpu_zzz[self.tog] = parts.get(8).unwrap().parse::().unwrap(); + self.cpu_info.cpu_gst[self.tog] = parts.get(9).unwrap().parse::().unwrap(); + self.cpu_info.cpu_gni[self.tog] = + parts.get(10).unwrap().parse::().unwrap(); + } + Some(&"intr") => { + self.cpu_info.intr[self.tog] = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"ctxt") => { + self.cpu_info.ctxt[self.tog] = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"btime") => { + self.cpu_info.btime = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"processes") => { + self.cpu_info.process = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"procs_running") => { + self.cpu_info.running = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"procs_blocked") => { + self.cpu_info.blocked = parts.get(1).unwrap().parse::().unwrap(); + } + + _ => {} + } + } + + self.cal.duse = self.cpu_info.cpu_use[self.tog] - self.cpu_info.cpu_use[1 - self.tog] + + self.cpu_info.cpu_nic[self.tog] + - self.cpu_info.cpu_nic[1 - self.tog]; + self.cal.dsys = self.cpu_info.cpu_sys[self.tog] - self.cpu_info.cpu_sys[1 - self.tog] + + self.cpu_info.cpu_xxx[self.tog] + - self.cpu_info.cpu_xxx[1 - self.tog] + + self.cpu_info.cpu_yyy[self.tog] + - self.cpu_info.cpu_yyy[1 - self.tog]; + + self.cal.didl = self.cpu_info.cpu_idl[self.tog] - self.cpu_info.cpu_idl[1 - self.tog]; + + self.cal.diow = self.cpu_info.cpu_iow[self.tog] - self.cpu_info.cpu_iow[1 - self.tog]; + + self.cal.dstl = self.cpu_info.cpu_zzz[self.tog] - self.cpu_info.cpu_zzz[1 - self.tog]; + + self.cal.dgue = self.cpu_info.cpu_gst[self.tog] - self.cpu_info.cpu_gst[1 - self.tog] + + self.cpu_info.cpu_gni[self.tog] + - self.cpu_info.cpu_gni[1 - self.tog]; + + self.cal.div = + self.cal.duse + self.cal.dsys + self.cal.didl + self.cal.diow + self.cal.dstl; + if self.cal.div == 0 { + self.cal.div = 1; + self.cal.didl = 1; + } + self.cal.divo2 = self.cal.div / 2; + + self.cal.intr = self.cpu_info.intr[self.tog] - self.cpu_info.intr[1 - self.tog]; + self.cal.ctxt = self.cpu_info.ctxt[self.tog] - self.cpu_info.ctxt[1 - self.tog]; + } + + /// get mem info + fn get_mem_info(&mut self) { + let mut contents = String::new(); + self.mem_fd.read_to_string(&mut contents).unwrap(); + + let watermark_low: u64; + let mut mem_available: i64; + let mut mem_used: i64; + + self.mem_info.kb_inactive = u64::MAX; + self.mem_info.kb_low_total = 0; + self.mem_info.kb_main_available = 0; + + for line in contents.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + match parts.get(0) { + Some(&"Active:") => { + self.mem_info.kb_active = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Active(file):") => { + self.mem_info.kb_active_file = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"AnonPages:") => { + self.mem_info.kb_anon_pages = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Bounce:") => { + self.mem_info.kb_bounce = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Buffers:") => { + self.mem_info.kb_main_buffers = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Cached:") => { + self.mem_info.kb_page_cache = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"CommitLimit:") => { + self.mem_info.kb_commit_limit = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Committed_AS:") => { + self.mem_info.kb_committed_as = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Dirty:") => { + self.mem_info.kb_dirty = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"HighFree:") => { + self.mem_info.kb_high_free = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"HighTotal:") => { + self.mem_info.kb_high_total = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Inact_clean:") => { + self.mem_info.kb_inact_clean = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Inact_dirty:") => { + self.mem_info.kb_inact_dirty = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Inact_laundry:") => { + self.mem_info.kb_inact_laundry = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Inact_target:") => { + self.mem_info.kb_inact_target = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Inactive:") => { + self.mem_info.kb_inactive = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Inactive(file):") => { + self.mem_info.kb_inactive_file = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"LowFree:") => { + self.mem_info.kb_low_free = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"LowTotal:") => { + self.mem_info.kb_low_total = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Mapped:") => { + self.mem_info.kb_mapped = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"MemAvailable:") => { + self.mem_info.kb_main_available = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"MemFree:") => { + self.mem_info.kb_main_free = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"MemTotal:") => { + self.mem_info.kb_main_total = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"NFS_Unstable:") => { + self.mem_info.kb_nfs_unstable = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"PageTables:") => { + self.mem_info.kb_pagetables = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"ReverseMaps:") => { + self.mem_info.nr_reversemaps = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"SReclaimable:") => { + self.mem_info.kb_slab_reclaimable = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"SUnreclaim:") => { + self.mem_info.kb_slab_unreclaimable = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Shmem:") => { + self.mem_info.kb_main_shared = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Slab:") => { + self.mem_info.kb_slab = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"SwapCached:") => { + self.mem_info.kb_swap_cached = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"SwapFree:") => { + self.mem_info.kb_swap_free = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"SwapTotal:") => { + self.mem_info.kb_swap_total = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"VmallocChunk:") => { + self.mem_info.kb_vmalloc_chunk = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"VmallocTotal:") => { + self.mem_info.kb_vmalloc_total = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"VmallocUsed:") => { + self.mem_info.kb_vmalloc_used = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"Writeback:") => { + self.mem_info.kb_writeback = parts.get(1).unwrap().parse::().unwrap(); + } + + _ => {} + } + } + if self.mem_info.kb_low_total == 0 { + self.mem_info.kb_low_total = self.mem_info.kb_main_total; + self.mem_info.kb_low_free = self.mem_info.kb_main_free; + } + if self.mem_info.kb_inactive == u64::MAX { + self.mem_info.kb_inactive = + self.mem_info.kb_inact_clean + self.mem_info.kb_inact_laundry; + } + + self.mem_info.kb_main_cached = + self.mem_info.kb_page_cache + self.mem_info.kb_slab_reclaimable; + self.mem_info.kb_swap_used = self.mem_info.kb_swap_total - self.mem_info.kb_swap_free; + + if self.mem_info.kb_main_available > self.mem_info.kb_main_total { + self.mem_info.kb_main_available = self.mem_info.kb_main_free; + } + + mem_used = (self.mem_info.kb_main_total - self.mem_info.kb_main_available) as i64; + if mem_used < 0 { + mem_used = (self.mem_info.kb_main_total - self.mem_info.kb_main_free) as i64; + } + self.mem_info.kb_main_used = mem_used as u64; + + if self.mem_info.kb_main_available == 0 { + let mut file = File::open("/proc/sys/vm/min_free_kbytes").unwrap(); + let mut contents = String::new(); + file.read_to_string(&mut contents).unwrap(); + self.mem_info.kb_min_free = contents.trim().parse::().unwrap(); + + watermark_low = self.mem_info.kb_min_free * 5 / 4; + mem_available = (self.mem_info.kb_min_free - watermark_low + + self.mem_info.kb_inactive_file + + self.mem_info.kb_active_file + - std::cmp::min( + (self.mem_info.kb_inactive_file + self.mem_info.kb_active_file) / 2, + watermark_low, + ) + + self.mem_info.kb_slab_reclaimable + - std::cmp::min(self.mem_info.kb_slab_reclaimable / 2, watermark_low)) + as i64; + + if mem_available < 0 { + mem_available = 0; + }; + self.mem_info.kb_main_available = mem_available as u64; + } + } + + /// get vmstat info + fn get_vm_info(&mut self) { + let mut conens = String::new(); + self.vmstat_fd.read_to_string(&mut conens).unwrap(); + + for line in conens.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + match parts.get(0) { + Some(&"allocstall") => { + self.vmstat_info.vm_allocstall = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"kswapd_inodesteal") => { + self.vmstat_info.vm_kswapd_inodesteal = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"kswapd_steal") => { + self.vmstat_info.vm_kswapd_steal = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_active_file") => { + self.vmstat_info.vm_nr_active_file = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_dirty") => { + self.vmstat_info.vm_nr_dirty = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_free_pages") => { + self.vmstat_info.vm_nr_free_pages = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_inactive_file") => { + self.vmstat_info.vm_nr_inactive_file = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_mapped") => { + self.vmstat_info.vm_nr_mapped = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_page_table_pages") => { + self.vmstat_info.vm_nr_page_table_pages = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_pagecache") => { + self.vmstat_info.vm_nr_pagecache = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_reverse_maps") => { + self.vmstat_info.vm_nr_reverse_maps = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_slab") => { + self.vmstat_info.vm_nr_slab = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_slab_reclaimable") => { + self.vmstat_info.vm_nr_slab_reclaimable = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_slab_unreclaimable") => { + self.vmstat_info.vm_nr_slab_unreclaimable = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_unstable") => { + self.vmstat_info.vm_nr_unstable = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"nr_writeback") => { + self.vmstat_info.vm_nr_writeback = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pageoutrun") => { + self.vmstat_info.vm_pageoutrun = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgactivate") => { + self.vmstat_info.vm_pgactivate = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgalloc") => { + self.vmstat_info.vm_pgalloc = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgalloc_dma") => { + self.vmstat_info.vm_pgalloc_dma = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgalloc_high") => { + self.vmstat_info.vm_pgalloc_high = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgalloc_normal") => { + self.vmstat_info.vm_pgalloc_normal = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgdeactivate") => { + self.vmstat_info.vm_pgactivate = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgfault") => { + self.vmstat_info.vm_pgfault = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgfree") => { + self.vmstat_info.vm_pgfree = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pginodesteal") => { + self.vmstat_info.vm_pginodesteal = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgmajfault") => { + self.vmstat_info.vm_pgmajfault = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgpgin") => { + self.vmstat_info.vm_pgpgin[self.tog] = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgpgout") => { + self.vmstat_info.vm_pgpgout[self.tog] = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgrefill") => { + self.vmstat_info.vm_pgrefill = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgrefill_dma") => { + self.vmstat_info.vm_pgrefill_dma = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgrefill_high") => { + self.vmstat_info.vm_pgrefill_high = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgrotated") => { + self.vmstat_info.vm_pgrotated = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgscan") => { + self.vmstat_info.vm_pgscan = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgscan_direct_dma") => { + self.vmstat_info.vm_pgscan_direct_dma = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgscan_direct_high") => { + self.vmstat_info.vm_pgscan_direct_high = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgscan_direct_normal") => { + self.vmstat_info.vm_pgscan_direct_normal = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgscan_kswapd_dma") => { + self.vmstat_info.vm_pgscan_kswapd_dma = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgscan_kswapd_high") => { + self.vmstat_info.vm_pgscan_kswapd_high = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgscan_kswapd_normal") => { + self.vmstat_info.vm_pgscan_kswapd_normal = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgsteal") => { + self.vmstat_info.vm_pgsteal = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgsteal_dma") => { + self.vmstat_info.vm_pgsteal_dma = parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgsteal_high") => { + self.vmstat_info.vm_pgsteal_high = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pgsteal_normal") => { + self.vmstat_info.vm_pgsteal_normal = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pswpin") => { + self.vmstat_info.vm_pswpin[self.tog] = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"pswpout") => { + self.vmstat_info.vm_pswpout[self.tog] = + parts.get(1).unwrap().parse::().unwrap(); + } + Some(&"slabs_scanned") => { + self.vmstat_info.vm_slabs_scanned = + parts.get(1).unwrap().parse::().unwrap(); + } + _ => {} + } + } + if self.vmstat_info.vm_pgalloc == 0 { + self.vmstat_info.vm_pgalloc = self.vmstat_info.vm_pgalloc_dma + + self.vmstat_info.vm_pgalloc_high + + self.vmstat_info.vm_pgalloc_normal; + } + if self.vmstat_info.vm_pgrefill == 0 { + self.vmstat_info.vm_pgrefill = self.vmstat_info.vm_pgrefill_dma + + self.vmstat_info.vm_pgrefill_high + + self.vmstat_info.vm_pgrefill_normal; + } + if self.vmstat_info.vm_pgsteal == 0 { + self.vmstat_info.vm_pgsteal = self.vmstat_info.vm_pgsteal_dma + + self.vmstat_info.vm_pgsteal_high + + self.vmstat_info.vm_pgsteal_normal; + } + if self.vmstat_info.vm_pgscan == 0 { + self.vmstat_info.vm_pgscan = self.vmstat_info.vm_pgscan_direct_dma + + self.vmstat_info.vm_pgscan_direct_high + + self.vmstat_info.vm_pgscan_direct_normal + + self.vmstat_info.vm_pgscan_kswapd_dma + + self.vmstat_info.vm_pgscan_kswapd_high + + self.vmstat_info.vm_pgscan_kswapd_normal; + } + + self.cal.pgpgin = + self.vmstat_info.vm_pgpgin[self.tog] - self.vmstat_info.vm_pgpgin[1 - self.tog]; + self.cal.pgpgout = + self.vmstat_info.vm_pgpgout[self.tog] - self.vmstat_info.vm_pgpgout[1 - self.tog]; + self.cal.pswpin = + self.vmstat_info.vm_pswpin[self.tog] - self.vmstat_info.vm_pswpin[1 - self.tog]; + self.cal.pswpout = + self.vmstat_info.vm_pswpout[self.tog] - self.vmstat_info.vm_pswpout[1 - self.tog]; + } +} + +/// obtaining the clock frequency +pub fn get_hertz() -> u64 { + unsafe { + let hz = libc::sysconf(libc::_SC_CLK_TCK); + if hz > 0 { + return hz as u64; + } else { + 100 + } + } +} + +/// +fn is_disk(dev: &str) -> bool { + let adjusted_dev = dev.replace('/', "!"); + let path = PathBuf::from("/sys/block").join(adjusted_dev); + + // Convert the path to a C-style string for compatibility with the `access` function. + let c_path = match CString::new(path.to_string_lossy().into_owned()) { + Ok(cstr) => cstr, + Err(_) => return false, // Handle NulError if conversion fails. + }; + unsafe { libc::access(c_path.as_ptr(), libc::F_OK) == 0 } +} + +#[derive(Debug, Default)] +/// +pub struct Disk { + /// + pub disk_name: String, + /// + pub reads: u64, + /// + pub merged_reads: u64, + /// + pub reads_sectors: u64, + /// + pub milli_reading: u64, + /// + pub writes: u64, + /// + pub merged_writes: u64, + /// + pub written_sectors: u64, + /// + pub milli_writing: u64, + /// + pub inprogress_io: u64, + /// + pub milli_spent_io: u64, + /// + pub weighted_milli_spent_io: u64, + /// + pub partitions: u32, +} + +#[derive(Debug, Default)] +/// +pub struct Partition { + /// + pub partition_name: String, + /// + pub reads: u64, + /// + pub reads_sectors: u64, + /// + pub writes: u64, + /// + pub requested_writes: u64, + /// + pub parent_disk: usize, +} + +/// +pub struct Disks { + /// + pub disks: Vec, + /// + pub partitions: Vec, +} + +impl Disks { + /// + pub fn new() -> Self { + Self { + disks: Vec::new(), + partitions: Vec::new(), + } + } + + /// + pub fn refresh(&mut self) { + self.disks.clear(); + self.partitions.clear(); + + let mut disk_fd = File::open("/proc/diskstats").unwrap(); + let mut conens = String::new(); + disk_fd.read_to_string(&mut conens).unwrap(); + + let mut c_disk = 0; + + for line in conens.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() < 14 { + continue; + } + let dev_name = parts[2]; + if is_disk(dev_name) { + let disk = Disk { + disk_name: dev_name.to_string(), + reads: parts[3].parse().unwrap_or(0), + merged_reads: parts[4].parse().unwrap_or(0), + reads_sectors: parts[5].parse().unwrap_or(0), + milli_reading: parts[6].parse().unwrap_or(0), + writes: parts[7].parse().unwrap_or(0), + merged_writes: parts[8].parse().unwrap_or(0), + written_sectors: parts[9].parse().unwrap_or(0), + milli_writing: parts[10].parse().unwrap_or(0), + inprogress_io: parts[11].parse().unwrap_or(0), + milli_spent_io: parts[12].parse().unwrap_or(0), + weighted_milli_spent_io: parts[13].parse().unwrap_or(0), + partitions: 0, + }; + self.disks.push(disk); + c_disk += 1; + } else { + if let (Some(reads), Some(reads_sectors), Some(writes), Some(requested_writes)) = ( + parts[3].parse().ok(), + parts[5].parse().ok(), + parts[7].parse().ok(), + parts[9].parse().ok(), + ) { + let partition = Partition { + partition_name: dev_name.to_string(), + reads, + reads_sectors, + writes, + requested_writes, + parent_disk: c_disk - 1, + }; + self.partitions.push(partition); + } + } + } + } +} + +#[derive(Debug, Clone)] +/// +pub struct SlabInfo { + /// + pub name: String, + /// + pub active_objs: u64, + /// + pub num_objs: u64, + /// + pub obj_size: u64, + /// + pub objs_per_slab: u64, + /// + pub pages_per_slab: u64, + /// + pub active_slabs: u64, + /// + pub total_slabs: u64, +} + +/// +pub fn sort_slabs(slabs: &mut [SlabInfo]) { + slabs.sort_by(|a, b| { + let key_a = CString::new(a.name.clone()).expect("CString::new failed"); + + let key_b = CString::new(b.name.clone()).expect("CString::new failed"); + + unsafe { + let result = libc::strcoll(key_a.as_ptr(), key_b.as_ptr()); + if result < 0 { + Ordering::Less + } else if result > 0 { + Ordering::Greater + } else { + Ordering::Equal + } + } + }); +} + +/// +pub fn read_slabinfo() -> Vec { + let mut disk_fd = File::open("/proc/slabinfo").unwrap(); + let mut conens = String::new(); + disk_fd.read_to_string(&mut conens).unwrap(); + + let mut slabs = Vec::new(); + for line in conens.lines().skip(2) { + if line.starts_with('#') || line.trim().is_empty() { + continue; + } + + let parts: Vec<_> = line.split_whitespace().collect(); + if parts.len() >= 15 { + let slab = SlabInfo { + name: parts[0].to_string(), + active_objs: parts[1].parse::().unwrap_or(0), + num_objs: parts[2].parse::().unwrap_or(0), + obj_size: parts[3].parse::().unwrap_or(0), + objs_per_slab: parts[4].parse::().unwrap_or(0), + pages_per_slab: parts[5].parse::().unwrap_or(0), + active_slabs: parts[13].parse::().unwrap_or(0), + total_slabs: parts[14].parse::().unwrap_or(0), + }; + slabs.push(slab); + } + } + + return slabs; +} diff --git a/src/oe/vmstat/src/main.rs b/src/oe/vmstat/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..ff77cb84e71ecb8988c981716976819c49c06048 --- /dev/null +++ b/src/oe/vmstat/src/main.rs @@ -0,0 +1 @@ +uucore::bin!(oe_vmstat); diff --git a/src/oe/vmstat/src/vmstat.rs b/src/oe/vmstat/src/vmstat.rs new file mode 100644 index 0000000000000000000000000000000000000000..a8e6d27e16143fd1429a9d7a9dd31eb81d71dfe8 --- /dev/null +++ b/src/oe/vmstat/src/vmstat.rs @@ -0,0 +1,28 @@ +//! This file is part of the easybox package. +// +// (c) Chenhao Fang +// +// For the full copyright and license information, please view the LICENSE file +// that was distributed with this source code. + +use clap::Command; +use uucore::{error::UResult, help_section, help_usage}; +pub mod lib_vmstat; +/// +pub mod vmstat_common; + +const ABOUT: &str = help_section!("about", "vmstat.md"); +const USAGE: &str = help_usage!("vmstat.md"); + +#[uucore::main] +/// This the main of vmstat +pub fn oemain(args: impl uucore::Args) -> UResult<()> { + let config: vmstat_common::Config = vmstat_common::parse_vmstat_cmd_args(args, ABOUT, USAGE)?; + vmstat_common::handle_input(config) +} + +/// This the oe_app of vmstat +/// +pub fn oe_app<'a>() -> Command<'a> { + vmstat_common::vmstat_app(ABOUT, USAGE) +} diff --git a/src/oe/vmstat/src/vmstat_common.rs b/src/oe/vmstat/src/vmstat_common.rs new file mode 100644 index 0000000000000000000000000000000000000000..8d1701556b85ddb70a889cf9b73f65901adb60c5 --- /dev/null +++ b/src/oe/vmstat/src/vmstat_common.rs @@ -0,0 +1,1087 @@ +//! This file is part of the easybox package. +// +// (c) Chenhao Fang +// +// For the full copyright and license information, please view the LICENSE file +// that was distributed with this source code. + +use clap::{crate_version, Arg, Command}; +use uucore::display::Quotable; +use uucore::format_usage; + +use uucore::error::{UResult, USimpleError}; +use uucore::libc::{self, ioctl, localtime, strftime, winsize, STDOUT_FILENO, TIOCGWINSZ}; + +use crate::lib_vmstat::*; +use std::ffi::CString; + +/// +pub static VMSTAT_DELAY_PARSE_ERROR: i32 = 1; +/// +pub static VMSTAT_COUNT_PARSE_ERROR: i32 = 2; +/// +pub static VMSTAT_UNIT_PARSE_ERROR: i32 = 3; +/// +pub static VMSTAT_PARTITION_ERROR: i32 = 4; + +/// +pub enum DataUnit { + /// UNIT_B 1 + UnitB((char, u64)), + /// UNIT_k 1000 + Unitk((char, u64)), + /// UNIT_K 1024 + UnitK((char, u64)), + /// UNIT_m 1000000 + Unitm((char, u64)), + /// UNIT_M 1048576 + UnitM((char, u64)), +} + +/// +pub enum Display { + /// -f + FORKS, + /// -d + DISKSTAT, + /// -s + STATS, + /// -m + SLABSTAT, + /// -p + PARTITIONSTAT(String), + /// -D + DISKSUMSTAT, +} + +/// +pub struct Config { + /// + pub display_stat: Option, + /// + pub units: Option, + /// + pub active: bool, // a_option + /// + pub timestamp: bool, // t_option + /// + pub wide: bool, // w_option + /// + pub one_header: bool, // moreheaders + /// + pub height: u16, + /// + pub no_first: bool, + /// + pub sleep_time: u64, + /// + pub infinite_updates: bool, + /// + pub num_updates: u64, +} + +/// +pub mod options { + /// + pub static ACTIVE: &str = "active"; + /// + pub static FORKS: &str = "forks"; + /// + pub static SLABS: &str = "slabs"; + /// + pub static ONE_HEADER: &str = "one-header"; + /// + pub static STATS: &str = "stats"; + /// + pub static DISK: &str = "disk"; + /// + pub static DISK_SUM: &str = "disk-sum"; + /// + pub static PARTITION: &str = "partition"; + /// + pub static UNIT: &str = "unit"; + /// + pub static WIDE: &str = "wide"; + /// + pub static TIMESTAMP: &str = "timestamp"; + /// + pub static NO_FIRST: &str = "no-first"; + /// + pub static HELP: &str = "help"; + /// + pub static VERSION: &str = "version"; + /// + pub static DELAY: &str = "delay"; + /// + pub static COUNT: &str = "count"; +} + +impl Config { + /// + pub fn from(args_matches: &clap::ArgMatches) -> UResult { + let mut infinite_updates; + + let display_stat = match () { + _ if args_matches.contains_id(options::FORKS) => Some(Display::FORKS), + _ if args_matches.contains_id(options::STATS) => Some(Display::STATS), + _ if args_matches.contains_id(options::DISK) => Some(Display::DISKSTAT), + _ if args_matches.contains_id(options::DISK_SUM) => Some(Display::DISKSUMSTAT), + _ if args_matches.contains_id(options::SLABS) => Some(Display::SLABSTAT), + _ if args_matches.contains_id(options::PARTITION) => { + let partition = args_matches + .get_one::(options::PARTITION) + .cloned() + .ok_or_else(|| { + USimpleError::new( + VMSTAT_PARTITION_ERROR, + format!("option requires an argument"), + ) + })?; + Some(Display::PARTITIONSTAT(partition)) + } + _ => None, // + }; + + let unit = args_matches + .get_one::(options::UNIT) + .map(|u| match u.as_str() { + "b" => Ok(DataUnit::UnitB(('b', 1))), + "B" => Ok(DataUnit::UnitB(('B', 1))), + "k" => Ok(DataUnit::Unitk(('k', 1000))), + "K" => Ok(DataUnit::UnitK(('K', 1024))), + "m" => Ok(DataUnit::Unitm(('m', 1000000))), + "M" => Ok(DataUnit::UnitM(('M', 1048576))), + _ => Err(USimpleError::new( + VMSTAT_UNIT_PARSE_ERROR, + format!("-S requires k, K, m or M (default is KiB)"), + )), + }) + .transpose()?; + + let sleep_time = match args_matches.get_one::(options::DELAY) { + Some(s) => { + infinite_updates = true; + let st = s.parse::().map_err(|_| { + USimpleError::new( + VMSTAT_DELAY_PARSE_ERROR, + format!("invalid delay value: {}", s.quote()), + ) + })?; + if st < 1 { + return Err(USimpleError::new( + VMSTAT_DELAY_PARSE_ERROR, + format!("delay must be positive integer: {}", s.quote()), + )); + } + st + } + None => { + infinite_updates = false; + 1 + } + }; + + let num_updates = match args_matches.get_one::(options::COUNT) { + Some(s) => { + infinite_updates = false; + let nu = s.parse::().map_err(|e| { + USimpleError::new(VMSTAT_COUNT_PARSE_ERROR, format!("invalid count: {}", e)) + })?; + nu + } + None => 1, + }; + + Ok(Self { + display_stat, + units: unit, + active: args_matches.contains_id(options::ACTIVE), + timestamp: args_matches.contains_id(options::TIMESTAMP), + wide: args_matches.contains_id(options::WIDE), + one_header: args_matches.contains_id(options::ONE_HEADER), + height: 0, + no_first: args_matches.contains_id(options::NO_FIRST), + sleep_time, + infinite_updates, + num_updates, + }) + } +} + +/// +pub fn parse_vmstat_cmd_args(args: impl uucore::Args, about: &str, usage: &str) -> UResult { + let command = vmstat_app(about, usage); + let arg_list = args.collect_lossy(); + Config::from(&command.try_get_matches_from(arg_list)?) +} + +/// +pub fn vmstat_app<'a>(about: &'a str, usage: &'a str) -> Command<'a> { + Command::new(uucore::util_name()) + .version(crate_version!()) + .about(about) + .override_usage(format_usage(&usage)) + .arg( + Arg::new(options::ACTIVE) + .short('a') + .long(options::ACTIVE) + .help("active/inactive memory"), + ) + .arg( + Arg::new(options::FORKS) + .short('f') + .long(options::FORKS) + .help("number of forks since boot"), + ) + .arg( + Arg::new(options::SLABS) + .short('m') + .long(options::SLABS) + .help("slabinfo") + .conflicts_with_all(&[ + options::STATS, + options::DISK, + options::DISK_SUM, + options::PARTITION, + ]), + ) + .arg( + Arg::new(options::ONE_HEADER) + .short('n') + .long(options::ONE_HEADER) + .help("do not redisplay header"), + ) + .arg( + Arg::new(options::STATS) + .short('s') + .long(options::STATS) + .help("event counter statistics") + .conflicts_with_all(&[ + options::SLABS, + options::DISK, + options::DISK_SUM, + options::PARTITION, + ]), + ) + .arg( + Arg::new(options::DISK) + .short('d') + .long(options::DISK) + .help("disk statistics") + .conflicts_with_all(&[ + options::STATS, + options::SLABS, + options::DISK_SUM, + options::PARTITION, + ]), + ) + .arg( + Arg::new(options::DISK_SUM) + .short('D') + .long(options::DISK_SUM) + .help("summarize disk statistics") + .conflicts_with_all(&[ + options::STATS, + options::DISK, + options::SLABS, + options::PARTITION, + ]), + ) + .arg( + Arg::new(options::PARTITION) + .short('p') + .long(options::PARTITION) + .value_name("dev") + .takes_value(true) + .help("partition specific statistics") + .conflicts_with_all(&[ + options::STATS, + options::DISK, + options::DISK_SUM, + options::SLABS, + ]), + ) + .arg( + Arg::new(options::UNIT) + .short('S') + .long(options::UNIT) + .value_name("char") + .takes_value(true) + .help("define display unit"), + ) + .arg( + Arg::new(options::WIDE) + .short('w') + .long(options::WIDE) + .help("wide output"), + ) + .arg( + Arg::new(options::TIMESTAMP) + .short('t') + .long(options::TIMESTAMP) + .help("show timestamp"), + ) + .arg( + Arg::new(options::NO_FIRST) + .short('y') + .long(options::NO_FIRST) + .help("skips first line of output"), + ) + .arg(Arg::new(options::HELP).short('h').long(options::HELP)) + .arg(Arg::new(options::VERSION).short('V').long(options::VERSION)) + .arg( + Arg::new(options::DELAY) + .help("Delay between updates in seconds") + .takes_value(true) + .required(false) + .index(1), + ) + .arg( + Arg::new(options::COUNT) + .help("Number of updates") + .takes_value(true) + .required(false) + .index(2), + ) +} + +/// +pub fn handle_input(mut config: Config) -> UResult<()> { + set_local(); + let w_height = winhi() - 3; + config.height = if w_height > 0 { w_height } else { 22 }; + + match &config.display_stat { + Option::Some(display) => match display { + Display::FORKS => { + let mut stat = Stat::new(); + stat.refresh(); + println!("{:13} forks\n", stat.cpu_info.process); + return Ok(()); + } + Display::SLABSTAT => { + slab_format(&config); + return Ok(()); + } + Display::STATS => { + sum_format(&config); + return Ok(()); + } + Display::DISKSTAT => { + disk_format(&config); + return Ok(()); + } + Display::DISKSUMSTAT => { + return disksum_format(); + } + Display::PARTITIONSTAT(dev) => { + return diskpartition_format(dev, &config); + } + }, + Option::None => { + new_format(&config); + } + } + + Ok(()) +} + +/// get window height +fn winhi() -> u16 { + let mut win: winsize = unsafe { std::mem::zeroed() }; + let mut rows = 24; + let result = unsafe { ioctl(STDOUT_FILENO, TIOCGWINSZ.into(), &mut win as *mut _) }; + if result != -1 && win.ws_row > 0 { + rows = win.ws_row; + } + rows +} + +/// +fn set_local() { + #[cfg(target_arch = "x86_64")] + unsafe { + libc::setlocale(libc::LC_ALL, b"\0".as_ptr() as *const i8); + } + + #[cfg(target_arch = "aarch64")] + unsafe { + libc::setlocale(libc::LC_ALL, b"\0".as_ptr()); + } +} + +/// new format +fn new_format(config: &Config) { + let mut stat = Stat::new(); + let sleep_time = config.sleep_time; + let sleep_half = sleep_time / 2; + let hz = get_hertz(); + stat.refresh(); + + new_header(config.wide, config.timestamp, config.active); + + let mut num_updates = config.num_updates; + + let kb_per_page: u64; + unsafe { + kb_per_page = libc::sysconf(libc::_SC_PAGESIZE) as u64 / 1024 as u64; + } + + if !config.no_first { + new_body( + config, + &mut stat, + kb_per_page, + hz, + false, + sleep_time, + sleep_half, + ); + } else { + num_updates += 1; + } + let mut i = 1; + while config.infinite_updates || i < num_updates { + std::thread::sleep(std::time::Duration::from_secs(config.sleep_time)); + if !config.one_header && (i % config.height as u64) == 0 { + new_header(config.wide, config.timestamp, config.active); + } + + stat.refresh(); + new_body( + config, + &mut stat, + kb_per_page, + hz, + true, + sleep_time, + sleep_half, + ); + + //new_body(config, &mut stat, kb_per_page, hz); + + i += 1; + } +} + +/// new body +fn new_body( + config: &Config, + stat: &mut Stat, + kb_per_page: u64, + hz: u64, + in_loop: bool, + sleep_time: u64, + sleep_half: u64, +) { + if config.wide { + print!( + "{:>4} {:>4} {:>12} {:>12} {:>12} {:>12} {:>4} {:>4} {:>5} {:>5} {:>4} {:>4} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3}", + stat.cpu_info.running, + stat.cpu_info.blocked, + unit_convert(stat.mem_info.kb_swap_used, config), + unit_convert(stat.mem_info.kb_main_free, config), + if config.active { unit_convert(stat.mem_info.kb_inactive, config) } else {unit_convert(stat.mem_info.kb_main_buffers, config)}, + if config.active { unit_convert(stat.mem_info.kb_active, config) } else {unit_convert(stat.mem_info.kb_main_cached, config)}, + + calculate_output(unit_convert(stat.cal.pswpin * kb_per_page, config), hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(unit_convert(stat.cal.pswpout * kb_per_page, config), hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.pgpgin, hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.pgpgout, hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.intr, hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.ctxt, hz, stat, sleep_time, sleep_half, in_loop), + + ((100 * stat.cal.duse + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.dsys + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.didl + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.diow + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.dstl + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.dgue + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64 + //si, so, bi, bo, vm_in, cs, us, sy, id, wa, st + ); + } else { + print!( + "{:>2} {:>2} {:>6} {:>6} {:>6} {:>6} {:>4} {:>4} {:>5} {:>5} {:>4} {:>4} {:>2} {:>2} {:>2} {:>2} {:>2} {:>2}", + stat.cpu_info.running, stat.cpu_info.blocked, + unit_convert(stat.mem_info.kb_swap_used, config), + unit_convert(stat.mem_info.kb_main_free, config), + if config.active { unit_convert(stat.mem_info.kb_inactive, config) } else {unit_convert(stat.mem_info.kb_main_buffers, config)}, + if config.active { unit_convert(stat.mem_info.kb_active, config) } else {unit_convert(stat.mem_info.kb_main_cached, config)}, + calculate_output(unit_convert(stat.cal.pswpin * kb_per_page, config), hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(unit_convert(stat.cal.pswpout * kb_per_page, config), hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.pgpgin, hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.pgpgout, hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.intr, hz, stat, sleep_time, sleep_half, in_loop), + calculate_output(stat.cal.ctxt, hz, stat, sleep_time, sleep_half, in_loop), + ((100 * stat.cal.duse + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.dsys + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.didl + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.diow + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.dstl + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64, + ((100 * stat.cal.dgue + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64 + //si, so, bi, bo, vm_in, cs, us, sy, id, wa, st, gu + ); + } + if config.timestamp { + let timebuf_str = get_time_str(); + print!(" {}", timebuf_str); + } + println!(""); +} + +/// calculate output +fn calculate_output( + value: u64, + hz: u64, + stat: &Stat, + sleep_time: u64, + sleep_half: u64, + in_loop: bool, +) -> u64 { + if in_loop { + (value + sleep_half) / sleep_time + } else { + ((value * hz + stat.cal.divo2) as f64 / stat.cal.div as f64) as u64 + } +} + +/// get time +fn get_time_str() -> String { + let mut timebuf: [u8; 32] = [0; 32]; + let mut the_time = libc::time_t::default(); + let fmt = CString::new("%Y-%m-%d %H:%M:%S") + .expect("CString::new failed") + .into_raw() as *mut libc::c_char; + unsafe { + libc::time(&mut the_time); + let tm_ptr = libc::localtime(&mut the_time); + if !tm_ptr.is_null() + && strftime( + timebuf.as_mut_ptr() as *mut libc::c_char, + timebuf.len() as libc::size_t, + fmt, + tm_ptr, + ) != 0 + { + } else { + timebuf[0] = 0; + } + let _ = CString::from_raw(fmt); + } + let filtered_bytes: Vec = timebuf.iter().cloned().filter(|&b| b != 0).collect(); + + String::from_utf8(filtered_bytes).expect("Invalid UTF-8") +} + +/// get time zone +fn get_time_zone(timestamp_header: &str) -> String { + let mut timebuf: [u8; 32] = [0; 32]; + + let fmt = CString::new("%Z").expect("CString::new failed").into_raw() as *mut libc::c_char; + + let mut the_time = libc::time_t::default(); + unsafe { + libc::time(&mut the_time); + let tm_ptr = localtime(&mut the_time); + + if !tm_ptr.is_null() + && strftime( + timebuf.as_mut_ptr() as *mut libc::c_char, + timebuf.len() as libc::size_t, + fmt, + tm_ptr, + ) != 0 + { + let len = timestamp_header.len() as libc::size_t; + if len >= 1 && timebuf.len() as libc::size_t - 1 < len { + timebuf[len - 1] = 0; + } + } else { + timebuf[0] = 0; + } + + let _ = CString::from_raw(fmt); + } + let filtered_bytes: Vec = timebuf.iter().cloned().filter(|&b| b != 0).collect(); + String::from_utf8(filtered_bytes).expect("Invalid UTF-8") +} + +/// new header +fn new_header(w_option: bool, t_option: bool, a_option: bool) { + let header = + "procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------"; + let wide_header = "--procs-- -----------------------memory---------------------- ---swap-- -----io---- -system-- ----------cpu----------"; + let timestamp_header = " -----timestamp-----"; + + let display_header = if w_option { wide_header } else { header }; + print!("{}", display_header); + + if t_option { + print!("{}", timestamp_header); + } + println!(""); + + let r = "r"; // Example values, replace these with actual system data + let b = "b"; + let swpd = "swpd"; + let free = "free"; + let buff = if a_option { "inact" } else { "buff" }; + let cache = if a_option { "active" } else { "cache" }; + let si = "si"; + let so = "so"; + let bi = "bi"; + let bo = "bo"; + let vm_in = "in"; + let cs = "cs"; + let us = "us"; + let sy = "sy"; + let id = "id"; + let wa = "wa"; + let st = "st"; + let gu = "gu"; + + if w_option { + print!( + "{:>4} {:>4} {:>12} {:>12} {:>12} {:>12} {:>4} {:>4} {:>5} {:>5} {:>4} {:>4} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3}", + r, b, swpd, free, buff, cache, si, so, bi, bo, vm_in, cs, us, sy, id, wa, st, gu + ); + } else { + print!( + "{:>2} {:>2} {:>6} {:>6} {:>6} {:>6} {:>4} {:>4} {:>5} {:>5} {:>4} {:>4} {:>2} {:>2} {:>2} {:>2} {:>2} {:>2}", + r, b, swpd, free, buff, cache, si, so, bi, bo, vm_in, cs, us, sy, id, wa, st, gu + ); + } + + if t_option { + let timebuf_str = get_time_zone(timestamp_header); + print!("{:>width$}", timebuf_str, width = timestamp_header.len()); + } + + println!(""); +} + +/// unit convert +fn unit_convert(size: u64, config: &Config) -> u64 { + let cv_size: f64; + + let data_unit_value = match config.units { + Some(ref data_unit) => match data_unit { + DataUnit::UnitB(v) + | DataUnit::Unitk(v) + | DataUnit::UnitK(v) + | DataUnit::Unitm(v) + | DataUnit::UnitM(v) => (*v).1, + }, + None => 1024, + }; + + if let Some(Display::SLABSTAT) = config.display_stat { + cv_size = size as f64 / data_unit_value as f64 * 1 as f64; + cv_size as u64 + } else { + cv_size = size as f64 / data_unit_value as f64 * 1024 as f64; + cv_size as u64 + } +} + +/// sum format +fn sum_format(config: &Config) { + let mut stat = Stat::new(); + stat.refresh(); + let unit_char = match config.units { + Some(ref data_unit) => match data_unit { + DataUnit::UnitB(v) + | DataUnit::Unitk(v) + | DataUnit::UnitK(v) + | DataUnit::Unitm(v) + | DataUnit::UnitM(v) => (*v).0, + }, + None => 'K', + }; + println!( + "{:>13} {} total memory", + unit_convert(stat.mem_info.kb_main_total, config), + unit_char + ); + println!( + "{:>13} {} total memory", + unit_convert(stat.mem_info.kb_main_used, config), + unit_char + ); + println!( + "{:>13} {} active memory", + unit_convert(stat.mem_info.kb_active, config), + unit_char + ); + println!( + "{:>13} {} inactive memory", + unit_convert(stat.mem_info.kb_inactive, config), + unit_char + ); + println!( + "{:>13} {} free memory", + unit_convert(stat.mem_info.kb_main_free, config), + unit_char + ); + println!( + "{:>13} {} buffer memory", + unit_convert(stat.mem_info.kb_main_buffers, config), + unit_char + ); + println!( + "{:>13} {} swap cache", + unit_convert(stat.mem_info.kb_main_cached, config), + unit_char + ); + println!( + "{:>13} {} total swap", + unit_convert(stat.mem_info.kb_swap_total, config), + unit_char + ); + println!( + "{:>13} {} used swap", + unit_convert(stat.mem_info.kb_swap_used, config), + unit_char + ); + println!( + "{:>13} {} free swap", + unit_convert(stat.mem_info.kb_swap_free, config), + unit_char + ); + + println!( + "{:>13} non-nice user cpu ticks", + stat.cpu_info.cpu_use[1 - stat.tog] + ); + println!( + "{:>13} nice user cpu ticks", + stat.cpu_info.cpu_nic[1 - stat.tog] + ); + println!( + "{:>13} system cpu ticks", + stat.cpu_info.cpu_sys[1 - stat.tog] + ); + println!("{:>13} idle cpu ticks", stat.cpu_info.cpu_idl[1 - stat.tog]); + println!( + "{:>13} IO-wait cpu ticks", + stat.cpu_info.cpu_iow[1 - stat.tog] + ); + println!("{:>13} IRQ cpu ticks", stat.cpu_info.cpu_xxx[1 - stat.tog]); + println!( + "{:>13} softirq cpu ticks", + stat.cpu_info.cpu_yyy[1 - stat.tog] + ); + println!( + "{:>13} stolen cpu ticks", + stat.cpu_info.cpu_zzz[1 - stat.tog] + ); + println!( + "{:>13} non-nice guest cpu ticks", + stat.cpu_info.cpu_gst[1 - stat.tog] + ); + println!( + "{:>13} nice guest cpu ticks", + stat.cpu_info.cpu_gni[1 - stat.tog] + ); + println!( + "{:>13} {} pages paged in", + unit_convert(stat.vmstat_info.vm_pgpgin[1 - stat.tog], config), + unit_char + ); + println!( + "{:>13} {} pages paged out", + unit_convert(stat.vmstat_info.vm_pgpgout[1 - stat.tog], config), + unit_char + ); + println!( + "{:>13} pages swapped in", + stat.vmstat_info.vm_pswpin[1 - stat.tog] + ); + println!( + "{:>13} pages swapped out", + stat.vmstat_info.vm_pswpout[1 - stat.tog] + ); + println!("{:>13} interrupts", stat.cpu_info.intr[1 - stat.tog]); + println!( + "{:>13} CPU context switches", + stat.cpu_info.ctxt[1 - stat.tog] + ); + println!("{:>13} boot time", stat.cpu_info.btime); + println!("{:>13} forks", stat.cpu_info.process); +} + +/// disk format +fn disk_format(config: &Config) { + let mut proc_disk_stat = Disks::new(); + + if config.one_header { + diskheader(config.wide, config.timestamp); + } + + let mut i = 0; + while config.infinite_updates || i < config.num_updates { + if !config.one_header { + diskheader(config.wide, config.timestamp); + } + + proc_disk_stat.refresh(); + let timebuf_str; + if config.timestamp { + timebuf_str = get_time_str(); + } else { + timebuf_str = "".to_string(); + } + + for disk in proc_disk_stat.disks.iter() { + if config.wide { + print!( + "{:>5} {:>9} {:>9} {:>11} {:>11} {:>9} {:>9} {:>11} {:>11} {:>7} {:>7}", + disk.disk_name, + disk.reads, + disk.merged_reads, + disk.reads_sectors, + disk.milli_reading, + disk.writes, + disk.merged_writes, + disk.written_sectors, + disk.milli_writing, + disk.inprogress_io / 1000, + disk.milli_spent_io / 1000 + ); + } else { + print!( + "{:>5} {:>6} {:>6} {:>7} {:>7} {:>6} {:>6} {:>7} {:>7} {:>6} {:>6}", + disk.disk_name, + disk.reads, + disk.merged_reads, + disk.reads_sectors, + disk.milli_reading, + disk.writes, + disk.merged_writes, + disk.written_sectors, + disk.milli_writing, + disk.inprogress_io / 1000, + disk.milli_spent_io / 1000 + ); + } + + if config.timestamp { + println!(" {}", timebuf_str); + } else { + println!(""); + } + } + + i += 1; + if config.infinite_updates || i < config.num_updates { + std::thread::sleep(std::time::Duration::from_secs(config.sleep_time)); + } + } +} + +/// disk header +fn diskheader(w_option: bool, t_option: bool) { + let header = "disk- ------------reads------------ ------------writes----------- -----IO------"; + let wide_header = "disk- -------------------reads------------------- -------------------writes------------------ ------IO-------"; + let timestamp_header = " -----timestamp-----"; + + let display_header = if w_option { wide_header } else { header }; + print!("{}", display_header); + + if t_option { + print!("{}", timestamp_header); + } + println!(""); + + let name = " "; + let r_total: &str = "total"; // Example values, replace these with actual system data + let r_merged = "merged"; + let r_sectors = "sectors"; + let r_ms = "ms"; + let w_total = "total"; + let w_merged = "merged"; + let w_sectors = "sectors"; + let w_ms = "ms"; + let cur = "cur"; + let sec = "sec"; + + if w_option { + print!( + "{:>5} {:>9} {:>9} {:>11} {:>11} {:>9} {:>9} {:>11} {:>11} {:>7} {:>7}", + name, r_total, r_merged, r_sectors, r_ms, w_total, w_merged, w_sectors, w_ms, cur, sec + ); + } else { + print!( + "{:>5} {:>6} {:>6} {:>7} {:>7} {:>6} {:>6} {:>7} {:>7} {:>6} {:>6}", + name, r_total, r_merged, r_sectors, r_ms, w_total, w_merged, w_sectors, w_ms, cur, sec + ); + } + + if t_option { + let timebuf_str = get_time_zone(timestamp_header); + print!("{:>width$}", timebuf_str, width = timestamp_header.len()); + } + + println!(""); +} + +/// disk-sum format +fn disksum_format() -> UResult<()> { + let mut proc_disk_stat = Disks::new(); + proc_disk_stat.refresh(); + + let mut reads = 0; + let mut merged_reads = 0; + let mut read_sectors = 0; + let mut milli_reading = 0; + let mut writes = 0; + let mut merged_writes = 0; + let mut written_sectors = 0; + let mut milli_writing = 0; + let mut inprogress_io = 0; + let mut milli_spent_io = 0; + let mut weighted_milli_spent_io = 0; + + for disk in proc_disk_stat.disks.iter() { + reads += disk.reads; + merged_reads += disk.merged_reads; + read_sectors += disk.reads_sectors; + milli_reading += disk.milli_reading; + writes += disk.writes; + merged_writes += disk.merged_writes; + written_sectors += disk.written_sectors; + milli_writing += disk.milli_writing; + inprogress_io += if disk.inprogress_io > 0 { + disk.inprogress_io / 1000 + } else { + 0 + }; + milli_spent_io += if disk.milli_spent_io > 0 { + disk.milli_spent_io / 1000 + } else { + 0 + }; + weighted_milli_spent_io += if disk.weighted_milli_spent_io > 0 { + disk.weighted_milli_spent_io / 1000 + } else { + 0 + }; + } + + println!("{:>13} disks", proc_disk_stat.disks.len()); + println!("{:>13} partitions", proc_disk_stat.partitions.len()); + println!("{:>13} total reads", reads); + println!("{:>13} merged reads", merged_reads); + println!("{:>13} read sectors", read_sectors); + println!("{:>13} milli reading", milli_reading); + println!("{:>13} writes", writes); + println!("{:>13} merged writes", merged_writes); + println!("{:>13} written sectors", written_sectors); + println!("{:>13} milli writing", milli_writing); + println!("{:>13} inprogress IO", inprogress_io); + println!("{:>13} milli spent IO", milli_spent_io); + println!("{:>13} milli weighted IO", weighted_milli_spent_io); + + Ok(()) +} + +/// slabs format +fn slab_format(config: &Config) { + if config.one_header { + slabheader(); + } + + let mut slabs: Vec; + + let mut i = 0; + while config.infinite_updates || i < config.num_updates { + slabs = read_slabinfo(); + sort_slabs(&mut slabs); + + for (index, slab) in slabs.iter().enumerate() { + if !config.one_header && index % config.height as usize == 0 { + slabheader(); + } + println!( + "{:<24} {:>6} {:>6} {:>6} {:>6}", + slab.name, slab.active_objs, slab.num_objs, slab.obj_size, slab.objs_per_slab + ); + } + + i += 1; + if config.infinite_updates || i < config.num_updates { + std::thread::sleep(std::time::Duration::from_secs(config.sleep_time)); + } + } +} + +/// slabs header +fn slabheader() { + let cache = "Cache"; + let num = "Num"; + let total = "Total"; + let size = "Size"; + let pages = "Pages"; + println!( + "{:<24} {:>6} {:>6} {:>6} {:>6}", + cache, num, total, size, pages + ); +} + +/// partition format +fn diskpartition_format(partion_name: &String, config: &Config) -> UResult<()> { + let mut proc_disk_stat = Disks::new(); + proc_disk_stat.refresh(); + let maybe_item = proc_disk_stat + .partitions + .iter() + .find(|item| &item.partition_name == partion_name); + match maybe_item { + Some(_) => { + diskpartition_header(partion_name); + } + None => { + return Err(USimpleError::new( + VMSTAT_UNIT_PARSE_ERROR, + format!("Disk/Partition {} not found", partion_name), + )); + } + } + + let mut i = 0; + while config.infinite_updates || i < config.num_updates { + proc_disk_stat.refresh(); + + let maybe_item: &Partition = proc_disk_stat + .partitions + .iter() + .find(|item| &item.partition_name == partion_name) + .unwrap(); + + println!( + "{:>21} {:>16} {:>10} {:>16}", + maybe_item.reads, + maybe_item.reads_sectors, + maybe_item.writes, + maybe_item.requested_writes + ); + + i += 1; + if config.infinite_updates || i < config.num_updates { + std::thread::sleep(std::time::Duration::from_secs(config.sleep_time)); + } + } + Ok(()) +} + +/// partition header +fn diskpartition_header(partion_name: &String) { + let reads = "reads"; + let read_sectors = "read sectors"; + let writes = "writes"; + let requested_writes = "requested writes"; + println!( + "{:<10} {:>10} {:>16} {:>10} {:>16}", + partion_name, reads, read_sectors, writes, requested_writes + ); +} diff --git a/src/oe/vmstat/vmstat.md b/src/oe/vmstat/vmstat.md new file mode 100644 index 0000000000000000000000000000000000000000..dbbc44e30f6176e93b1cb4829ddcf31706a490d4 --- /dev/null +++ b/src/oe/vmstat/vmstat.md @@ -0,0 +1,30 @@ +# vmstat + +## Usage +``` +vmstat [options] [delay [count]] +``` + +## About +vmstat (virtual memory statistics) is a utility that reports information about processes, memory, paging, block IO, traps, disks, and CPU activity. + ++ No options: Show a one-time snapshot of various system statistics. ++ With `delay`: Repeat the report every `delay` seconds. ++ With `delay` and count: Repeat the report every `delay` seconds for count times. + +## Arguments ++ **`-a`**, **`--active`** active/inactive memory. ++ **`-f`**, **`--forks`** number of forks since boot. ++ **`-m`**, **`--slabs`** slabinfo. ++ **`-n`**, **`--one-header`** do not redisplay header. ++ **`-s`**, **`--stats`** event counter statistics. ++ **`-d`**, **`--disk`** disk statistics. ++ **`-D`**, **`--disk-sum`** summarize disk statistics. ++ **`-p`**, **`--partition`** **``** partition specific statistics. ++ **`-S`**, **`--version`** define display unit. ++ **`-w`**, **`--unit`** **``** wide output. ++ **`-t`**, **`--timestamp`** show timestamp. ++ **`-y`**, **`--no-first`** skips first line of output. +

++ **`-h`**, **`--help`** display this help and exit. ++ **`-v`**, **`--version`** output version information and exit. diff --git a/tests/by-util/test_vmstat.rs b/tests/by-util/test_vmstat.rs new file mode 100644 index 0000000000000000000000000000000000000000..b88773a68268db17920f01910cbec6a5f12fcefd --- /dev/null +++ b/tests/by-util/test_vmstat.rs @@ -0,0 +1,241 @@ +use crate::common::util::*; +use regex::Regex; +use std::ffi::OsStr; +use std::fs; +use std::path::Path; + +const C_VMSTAT_PATH: &str = "/usr/bin/vmstat"; +const UUTILS_WARNING: &str = "uutils-tests-warning"; + +#[cfg(unix)] +pub fn run_cmd_as_root_ignore_ci>( + ts: &TestScenario, + bin: S, + args: &[&str], +) -> std::result::Result { + use std::process::Command; + + // check if we can run 'sudo' + log_info("run", "sudo -E --non-interactive whoami"); + match Command::new("sudo") + .env("LC_ALL", "C") + .args(["-E", "--non-interactive", "whoami"]) + .output() + { + Ok(output) if String::from_utf8_lossy(&output.stdout).eq("root\n") => { + // we can run sudo and we're root + // run ucmd as root: + Ok(ts + .cmd_keepenv("sudo") + .env("LC_ALL", "C") + .arg("-E") + .arg("--non-interactive") + .arg(bin) + .args(args) + .run()) + } + Ok(output) + if String::from_utf8_lossy(&output.stderr).eq("sudo: a password is required\n") => + { + Err("Cannot run non-interactive sudo".to_string()) + } + Ok(_output) => Err("\"sudo whoami\" didn't return \"root\"".to_string()), + Err(e) => Err(format!("{}: {}", UUTILS_WARNING, e)), + } +} + +#[cfg(unix)] +pub fn run_ucmd_as_root_ignore_ci( + ts: &TestScenario, + args: &[&str], +) -> std::result::Result { + use std::process::Command; + + // check if we can run 'sudo' + log_info("run", "sudo -E --non-interactive whoami"); + match Command::new("sudo") + .env("LC_ALL", "C") + .args(["-E", "--non-interactive", "whoami"]) + .output() + { + Ok(output) if String::from_utf8_lossy(&output.stdout).eq("root\n") => { + // we can run sudo and we're root + // run ucmd as root: + Ok(ts + .cmd_keepenv("sudo") + .env("LC_ALL", "C") + .arg("-E") + .arg("--non-interactive") + .arg(&ts.bin_path) + .arg(&ts.util_name) + .args(args) + .run()) + } + Ok(output) + if String::from_utf8_lossy(&output.stderr).eq("sudo: a password is required\n") => + { + Err("Cannot run non-interactive sudo".to_string()) + } + Ok(_output) => Err("\"sudo whoami\" didn't return \"root\"".to_string()), + Err(e) => Err(format!("{}: {}", UUTILS_WARNING, e)), + } +} + +#[test] +fn test_vmstat() { + // Check if the /proc/vmstat file is readable. + if !fs::metadata("/proc/vmstat") + .map(|m| m.is_file()) + .unwrap_or(false) + { + println!("vmstat with no arguments - /proc/vmstat is unreadable"); + return; + } + + let task = TestScenario::new(util_name!()); + let c_task = TestScenario::new(util_name!()); + // Run original C taskset from system path + let c_res = task.cmd(C_VMSTAT_PATH).succeeds(); + let res = c_task.ucmd().succeeds(); + let regex = Regex::new(r"^procs\s[-]+memory[-]+\s[-]+swap[-]+\s[-]+io[-]+\s[-]+system[-]+\s[-]+cpu[-]+\s*r\s+b\s+swpd\s+free\s+buff\s+cache\s+si\s+so\s+bi\s+bo\s+in\s+cs us sy id wa st(?:\s*gu\s*(\d+\s*){18}|\s*(\d+\s*){17})\s*$").unwrap(); + + println!("vmstat output: {}", c_res.stdout_str()); + println!("vmstat output: {}", res.stdout_str()); + + assert!(regex.is_match(&c_res.stdout_move_str())); + assert!(regex.is_match(&res.stdout_move_str())); +} + +#[test] +fn test_vmstat_with_a() { + // Check if the /proc/vmstat file is readable. + if !fs::metadata("/proc/vmstat") + .map(|m| m.is_file()) + .unwrap_or(false) + { + println!("vmstat with -a flag - /proc/vmstat is unreadable"); + return; + } + let task = TestScenario::new(util_name!()); + let c_task = TestScenario::new(util_name!()); + // Run original C taskset from system path + let c_res = task.cmd(C_VMSTAT_PATH).args(&["-a"]).succeeds(); + let res = c_task.ucmd().args(&["-a"]).succeeds(); + let regex = Regex::new(r"^procs\s[-]+memory[-]+\s[-]+swap[-]+\s[-]+io[-]+\s[-]+system[-]+\s[-]+cpu[-]+\s*r\s+b\s+swpd\s+free\s+inact\s+active\s+si\s+so\s+bi\s+bo\s+in\s+cs us sy id wa st(?:\s*gu\s*(\d+\s*){18}|\s*(\d+\s*){17})\s*$").unwrap(); + + println!("vmstat -a output: {}", c_res.stdout_str()); + println!("vmstat -a output: {}", res.stdout_str()); + + assert!(regex.is_match(&c_res.stdout_move_str())); + assert!(regex.is_match(&res.stdout_move_str())); +} + +#[test] +fn test_vmstat_with_f() { + // Check if the /proc/vmstat file is readable. + if !fs::metadata("/proc/vmstat") + .map(|m| m.is_file()) + .unwrap_or(false) + { + println!("vmstat fork option - /proc/vmstat is unreadable"); + return; + } + let task = TestScenario::new(util_name!()); + // Run original C taskset from system path + let c_res = task.cmd(C_VMSTAT_PATH).args(&["-f"]).succeeds(); + let res = task.ucmd().args(&["-f"]).succeeds(); + let regex = Regex::new(r"^\s+\d+\s+forks\s*$").unwrap(); + + assert!(regex.is_match(&c_res.stdout_move_str())); + assert!(regex.is_match(&res.stdout_move_str())); +} + +#[test] +fn test_vmstat_slabinfo_information() { + if !fs::metadata("/proc/vmstat") + .map(|m| m.is_file()) + .unwrap_or(false) + { + println!("slabinfo (-m option) test disabled as /proc/slabinfo is unreadable"); + } + + let task = TestScenario::new(util_name!()); + let c_task = TestScenario::new(util_name!()); + // Run original C taskset from system path + let test_args1 = &["-m"]; + let c_res = run_cmd_as_root_ignore_ci(&c_task, C_VMSTAT_PATH, test_args1).unwrap(); + let res = run_ucmd_as_root_ignore_ci(&task, test_args1).unwrap(); + + let regex = + Regex::new(r"^Cache\s+Num\s+Total\s+Size\s+Pages\s*(\S+\s+\d+\s+\d+\s+\d+\s+\d+\s*){1,}") + .unwrap(); + assert!(regex.is_match(&c_res.stdout_move_str())); + assert!(regex.is_match(&res.stdout_move_str())); +} + +#[test] +fn test_vmstat_disk_information() { + let test_name = "vmstat disk information (-d option)"; + // Check if the /sys/block file is readable. + if !Path::new("/sys/block").exists() { + panic!("{test_name} /sys/block not readable"); + } + + // Check if the /proc/diskstats file is readable. + let diskstats_content = + fs::read_to_string("/proc/diskstats").expect("Failed to read /proc/diskstats"); + if diskstats_content.trim().is_empty() { + panic!("{test_name} /proc/diskstats empty"); + } + + let task = TestScenario::new(util_name!()); + let c_task = TestScenario::new(util_name!()); + // Run original C taskset from system path + let c_res = c_task.cmd(C_VMSTAT_PATH).args(&["-d"]).succeeds(); + let res = task.ucmd().args(&["-d"]).succeeds(); + let regex = Regex::new(r"^disk[-]+\s+[-]+reads[-]+\s+[-]+writes[-]+\s+[-]+IO[-]+\s+total\s+merged\s+sectors\s+ms\s+total\s+merged\s+sectors\s+ms\s+cur\s+sec\s*").unwrap(); + assert!(regex.is_match(&c_res.stdout_move_str())); + assert!(regex.is_match(&res.stdout_move_str())); +} + +#[test] +fn test_vmstat_partition() { + let test_name = "vmstat disk information (-d option)"; + // Check if the /sys/block file is readable. + if !Path::new("/sys/block").exists() { + panic!("{test_name} /sys/block not readable"); + } + + // Check if the /proc/diskstats file is readable. + let diskstats_content = + fs::read_to_string("/proc/diskstats").expect("Failed to read /proc/diskstats"); + if diskstats_content.trim().is_empty() { + panic!("{test_name} /proc/diskstats empty"); + } + + if let Some(cpas) = Regex::new(r"((?:hd|sd|vd)[a-z]\d+)") + .unwrap() + .captures(&diskstats_content) + { + if let Some(partition) = cpas.get(0) { + let test_name = format!("vmstat partition (using {})", partition.as_str()); + println!("{}", test_name); + let task = TestScenario::new(util_name!()); + let c_task = TestScenario::new(util_name!()); + let c_res = c_task + .cmd(C_VMSTAT_PATH) + .args(&["-p", partition.as_str()]) + .succeeds(); + let res = task.ucmd().args(&["-p", partition.as_str()]).succeeds(); + let fmt = format!( + r"^{}\s*reads\s*read sectors\s*writes\s*requested writes\s*\d+\s*\d+\s*\d+\s*\d+\s*", + partition.as_str() + ); + let regex = Regex::new(&fmt).unwrap(); + assert!(regex.is_match(&c_res.stdout_move_str())); + assert!(regex.is_match(&res.stdout_move_str())) + } else { + panic!("vmstat partition (cannot find partition)"); + } + } +} diff --git a/tests/tests.rs b/tests/tests.rs index 79362ce53b660d3c361a88c123ba3bb795908d74..08993b95b61c2df19e773d7797cfa39ad1cd26e3 100755 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -123,3 +123,7 @@ mod test_useradd; #[cfg(feature = "find")] #[path = "by-util/test_find.rs"] mod test_find; + +#[cfg(feature = "vmstat")] +#[path = "by-util/test_vmstat.rs"] +mod test_vmstat;