btop/src/btop_linux.h

428 lines
12 KiB
C
Raw Normal View History

2021-05-10 23:46:41 +02:00
/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
indent = tab
tab-size = 4
*/
#ifndef _btop_linux_included_
2021-06-06 01:41:36 +02:00
#define _btop_linux_included_
2021-05-10 23:46:41 +02:00
#include <string>
#include <vector>
2021-05-19 23:21:56 +02:00
#include <deque>
#include <array>
2021-05-10 23:46:41 +02:00
#include <atomic>
2021-05-26 16:23:29 +02:00
#include <future>
#include <thread>
2021-05-10 23:46:41 +02:00
#include <fstream>
2021-05-26 16:23:29 +02:00
#include <streambuf>
2021-05-10 23:46:41 +02:00
#include <filesystem>
#include <ranges>
2021-05-19 23:21:56 +02:00
#include <list>
2021-05-29 02:32:36 +02:00
#include <robin_hood.h>
2021-05-19 23:21:56 +02:00
2021-05-10 23:46:41 +02:00
#include <unistd.h>
#include <btop_config.h>
#include <btop_tools.h>
2021-05-29 02:32:36 +02:00
using std::string, std::vector, std::array, std::ifstream, std::atomic, std::numeric_limits, std::streamsize;
2021-06-13 23:12:11 +02:00
using std::cout, std::flush, std::endl, std::string_literals::operator""s;
2021-05-10 23:46:41 +02:00
namespace fs = std::filesystem;
using namespace Tools;
2021-05-10 23:46:41 +02:00
//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------
2021-06-05 01:41:24 +02:00
namespace Tools {
double system_uptime(){
string upstr;
ifstream pread("/proc/uptime");
getline(pread, upstr, ' ');
pread.close();
return stod(upstr);
}
}
2021-05-14 18:54:37 +02:00
namespace Proc {
namespace {
struct p_cache {
string name, cmd, user;
uint64_t cpu_t = 0, cpu_s = 0;
2021-06-12 18:49:27 +02:00
string prefix = "";
size_t depth = 0;
2021-06-13 23:12:11 +02:00
int collapsed = -1;
};
2021-05-27 22:29:36 +02:00
unordered_flat_map<uint, p_cache> cache;
unordered_flat_map<string, string> uid_user;
2021-05-14 18:54:37 +02:00
fs::path passwd_path;
fs::file_time_type passwd_time;
uint counter = 0;
long page_size;
long clk_tck;
2021-05-14 18:54:37 +02:00
}
2021-06-05 01:41:24 +02:00
fs::path proc_path;
uint64_t old_cputimes = 0;
2021-05-22 02:13:56 +02:00
size_t numpids = 500;
atomic<bool> stop (false);
atomic<bool> collecting (false);
atomic<bool> drawing (false);
2021-06-13 23:12:11 +02:00
vector<string> sort_vector = {
2021-05-14 18:54:37 +02:00
"pid",
"name",
"command",
"threads",
"user",
"memory",
"cpu direct",
"cpu lazy",
};
2021-06-12 18:49:27 +02:00
//* Container for process information
struct proc_info {
uint pid;
2021-06-05 01:41:24 +02:00
string name = "", cmd = "";
size_t threads = 0;
string user = "";
uint64_t mem = 0;
double cpu_p = 0.0, cpu_c = 0.0;
char state = '0';
int cpu_n = 0, p_nice = 0;
2021-06-12 18:49:27 +02:00
int ppid = -1;
string prefix = "";
};
2021-05-14 18:54:37 +02:00
2021-06-13 23:12:11 +02:00
//* Generate process tree list
void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<proc_info>& out_procs, int cur_depth=0, bool collapsed=false){
auto cur_pos = out_procs.size();
if (!collapsed)
out_procs.push_back(cur_proc);
int children = 0;
for (auto& p : in_procs) {
if (p.ppid == (int)cur_proc.pid) {
children++;
if (collapsed) {
out_procs.back().cpu_p += p.cpu_p;
out_procs.back().mem += p.mem;
out_procs.back().threads += p.threads;
_tree_gen(p, in_procs, out_procs, cur_depth + 1, collapsed);
}
else _tree_gen(p, in_procs, out_procs, cur_depth + 1, (cache.at(cur_proc.pid).collapsed == 1));
}
}
if (collapsed) return;
if (out_procs.size() > cur_pos + 1 && !out_procs.back().prefix.ends_with("] ")) {
std::string_view n_prefix = out_procs.back().prefix;
n_prefix.remove_suffix(8);
out_procs.back().prefix = (string)n_prefix + " └─ ";
}
string prefix = " ├─ ";
if (children > 0) prefix = (cache.at(cur_proc.pid).collapsed == 1) ? "[+] " : "[-] ";
out_procs.at(cur_pos).prefix = ""s * cur_depth + prefix;
}
vector<proc_info> current_procs;
2021-06-12 18:49:27 +02:00
//* Collects and sorts process information from /proc, saves to and returns reference to Proc::current_procs;
2021-06-13 23:12:11 +02:00
auto& collect(){
atomic_wait_set(collecting);
2021-06-13 23:12:11 +02:00
auto& sorting = Config::getS("proc_sorting");
auto& reverse = Config::getB("proc_reversed");
auto& filter = Config::getS("proc_filter");
auto& per_core = Config::getB("proc_per_core");
auto& tree = Config::getB("proc_tree");
ifstream pread;
auto uptime = system_uptime();
vector<proc_info> procs;
2021-06-12 18:49:27 +02:00
vector<uint> pid_list;
2021-05-19 23:21:56 +02:00
procs.reserve((numpids + 10));
2021-06-12 18:49:27 +02:00
pid_list.reserve(numpids + 10);
int npids = 0;
2021-06-05 01:41:24 +02:00
int cmult = (per_core) ? Global::coreCount : 1;
2021-06-12 18:49:27 +02:00
(void)tree;
//* Update uid_user map if /etc/passwd changed since last run
2021-05-13 21:11:10 +02:00
if (!passwd_path.empty() && fs::last_write_time(passwd_path) != passwd_time) {
string r_uid, r_user;
2021-05-13 21:11:10 +02:00
passwd_time = fs::last_write_time(passwd_path);
uid_user.clear();
2021-05-22 02:13:56 +02:00
pread.open(passwd_path);
2021-05-13 21:11:10 +02:00
if (pread.good()) {
2021-05-27 22:29:36 +02:00
while (!pread.eof()){
2021-05-13 21:11:10 +02:00
getline(pread, r_user, ':');
2021-05-22 02:13:56 +02:00
pread.ignore(SSmax, ':');
2021-05-13 21:11:10 +02:00
getline(pread, r_uid, ':');
uid_user[r_uid] = r_user;
2021-05-22 02:13:56 +02:00
pread.ignore(SSmax, '\n');
2021-05-13 21:11:10 +02:00
}
}
pread.close();
}
2021-05-10 23:46:41 +02:00
2021-06-05 01:41:24 +02:00
//* Get cpu total times from /proc/stat
uint64_t cputimes = 0;
pread.open(proc_path / "stat");
if (pread.good()) {
pread.ignore(SSmax, ' ');
for (uint64_t times; pread >> times; cputimes += times);
pread.close();
}
else return current_procs;
2021-06-05 01:41:24 +02:00
//* Iterate over all pids in /proc
for (auto& d: fs::directory_iterator(proc_path)){
2021-05-22 02:13:56 +02:00
if (pread.is_open()) pread.close();
if (stop.load()) {
collecting.store(false);
stop.store(false);
return current_procs;
}
2021-06-05 01:41:24 +02:00
bool new_cache = false;
2021-06-09 19:47:49 +02:00
string pid_str = d.path().filename();
if (d.is_directory() && isdigit(pid_str[0])) {
npids++;
2021-06-05 01:41:24 +02:00
proc_info new_proc (stoul(pid_str));
2021-06-12 18:49:27 +02:00
pid_list.push_back(new_proc.pid);
2021-05-13 21:11:10 +02:00
//* Cache program name, command and username
2021-06-05 01:41:24 +02:00
if (!cache.contains(new_proc.pid)) {
string name, cmd, user;
new_cache = true;
2021-05-22 02:13:56 +02:00
pread.open(d.path() / "comm");
if (pread.good()) {
getline(pread, name);
2021-05-10 23:46:41 +02:00
pread.close();
}
2021-05-22 02:13:56 +02:00
else continue;
pread.open(d.path() / "cmdline");
if (pread.good()) {
2021-06-05 01:41:24 +02:00
string tmpstr = "";
2021-05-22 02:13:56 +02:00
while(getline(pread, tmpstr, '\0')) cmd += tmpstr + " ";
2021-05-10 23:46:41 +02:00
pread.close();
if (!cmd.empty()) cmd.pop_back();
2021-05-10 23:46:41 +02:00
}
2021-05-22 02:13:56 +02:00
else continue;
pread.open(d.path() / "status");
if (pread.good()) {
2021-06-05 01:41:24 +02:00
string uid;
2021-05-22 02:13:56 +02:00
while (!pread.eof()){
2021-06-05 01:41:24 +02:00
string line;
getline(pread, line, ':');
if (line == "Uid") {
2021-05-22 02:13:56 +02:00
pread.ignore();
getline(pread, uid, '\t');
break;
} else {
pread.ignore(SSmax, '\n');
}
}
pread.close();
2021-05-13 21:11:10 +02:00
user = (!uid.empty() && uid_user.contains(uid)) ? uid_user.at(uid) : uid;
2021-05-10 23:46:41 +02:00
}
2021-05-22 02:13:56 +02:00
else continue;
2021-06-05 01:41:24 +02:00
cache[new_proc.pid] = {name, cmd, user};
2021-05-10 23:46:41 +02:00
}
2021-05-22 02:13:56 +02:00
//* Match filter if defined
2021-05-27 22:29:36 +02:00
if (!filter.empty()
&& pid_str.find(filter) == string::npos
2021-06-05 01:41:24 +02:00
&& cache[new_proc.pid].name.find(filter) == string::npos
&& cache[new_proc.pid].cmd.find(filter) == string::npos
&& cache[new_proc.pid].user.find(filter) == string::npos) {
if (new_cache) cache.erase(new_proc.pid);
2021-05-22 02:13:56 +02:00
continue;
}
2021-06-05 01:41:24 +02:00
new_proc.name = cache[new_proc.pid].name;
new_proc.cmd = cache[new_proc.pid].cmd;
new_proc.user = cache[new_proc.pid].user;
2021-05-22 02:13:56 +02:00
//* Parse /proc/[pid]/stat
2021-05-22 02:13:56 +02:00
pread.open(d.path() / "stat");
if (pread.good()) {
2021-06-05 01:41:24 +02:00
string instr;
2021-05-22 02:13:56 +02:00
getline(pread, instr);
pread.close();
2021-06-05 01:41:24 +02:00
size_t s_pos = 0, c_pos = 0, s_count = 0;
uint64_t cpu_t = 0;
//? Skip pid and comm field and find comm fields closing ')'
2021-05-22 02:13:56 +02:00
s_pos = instr.find_last_of(')') + 2;
2021-05-26 16:23:29 +02:00
if (s_pos == string::npos) continue;
2021-05-22 02:13:56 +02:00
do {
c_pos = instr.find(' ', s_pos);
if (c_pos == string::npos) break;
2021-05-22 02:13:56 +02:00
switch (s_count) {
case 0: { //? Process state
2021-06-05 01:41:24 +02:00
new_proc.state = instr[s_pos];
2021-05-22 02:13:56 +02:00
break;
}
case 1: { //? Process parent pid
2021-06-12 18:49:27 +02:00
new_proc.ppid = stoi(instr.substr(s_pos, c_pos - s_pos));
2021-05-22 02:13:56 +02:00
break;
}
case 11: { //? Process utime
cpu_t = stoull(instr.substr(s_pos, c_pos - s_pos));
break;
}
case 12: { //? Process stime
cpu_t += stoull(instr.substr(s_pos, c_pos - s_pos));
break;
}
case 16: { //? Process nice value
2021-06-05 01:41:24 +02:00
new_proc.p_nice = stoi(instr.substr(s_pos, c_pos - s_pos));
2021-05-22 02:13:56 +02:00
break;
}
case 17: { //? Process number of threads
2021-06-05 01:41:24 +02:00
new_proc.threads = stoul(instr.substr(s_pos, c_pos - s_pos));
2021-05-22 02:13:56 +02:00
break;
}
2021-06-05 01:41:24 +02:00
case 19: { //? Cache cpu seconds
if (new_cache) cache[new_proc.pid].cpu_s = stoull(instr.substr(s_pos, c_pos - s_pos));
2021-05-22 02:13:56 +02:00
break;
}
case 36: { //? CPU number last executed on
2021-06-05 01:41:24 +02:00
new_proc.cpu_n = stoi(instr.substr(s_pos, c_pos - s_pos));
2021-05-22 02:13:56 +02:00
break;
}
}
s_pos = c_pos + 1;
} while (s_count++ < 36);
2021-05-19 23:21:56 +02:00
2021-05-26 16:23:29 +02:00
if (s_count < 19) continue;
2021-06-05 01:41:24 +02:00
//? Process cpu usage since last update
new_proc.cpu_p = round(cmult * 1000 * (cpu_t - cache[new_proc.pid].cpu_t) / (cputimes - old_cputimes)) / 10.0;
//? Process cumulative cpu usage since process start
2021-06-05 01:41:24 +02:00
new_proc.cpu_c = ((double)cpu_t / clk_tck) / (uptime - (cache[new_proc.pid].cpu_s / clk_tck));
2021-05-20 15:04:06 +02:00
//? Update cache with latest cpu times
2021-06-05 01:41:24 +02:00
cache[new_proc.pid].cpu_t = cpu_t;
}
2021-05-22 02:13:56 +02:00
else continue;
//* Get RSS memory in bytes from /proc/[pid]/statm
2021-05-22 02:13:56 +02:00
pread.open(d.path() / "statm");
if (pread.good()) {
pread.ignore(SSmax, ' ');
2021-06-05 01:41:24 +02:00
pread >> new_proc.mem;
pread.close();
2021-06-05 01:41:24 +02:00
new_proc.mem *= page_size;
}
//* Create proc_info
2021-06-05 01:41:24 +02:00
procs.push_back(new_proc);
2021-05-10 23:46:41 +02:00
}
}
2021-06-12 18:49:27 +02:00
//* Sort processes
2021-06-13 23:12:11 +02:00
std::ranges::sort(procs, [sortint = v_index(sort_vector, sorting), &reverse](proc_info& a, proc_info& b) {
switch (sortint) {
case 0: return (reverse) ? a.pid < b.pid : a.pid > b.pid;
case 1: return (reverse) ? a.name < b.name : a.name > b.name;
case 2: return (reverse) ? a.cmd < b.cmd : a.cmd > b.cmd;
case 3: return (reverse) ? a.threads < b.threads : a.threads > b.threads;
case 4: return (reverse) ? a.user < b.user : a.user > b.user;
case 5: return (reverse) ? a.mem < b.mem : a.mem > b.mem;
case 6: return (reverse) ? a.cpu_p < b.cpu_p : a.cpu_p > b.cpu_p;
case 7: return (reverse) ? a.cpu_c < b.cpu_c : a.cpu_c > b.cpu_c;
2021-05-10 23:46:41 +02:00
}
2021-06-13 23:12:11 +02:00
return false;
});
2021-05-13 21:11:10 +02:00
//* When using "cpu lazy" sorting push processes with high cpu usage to the front regardless of cumulative usage
2021-06-09 19:47:49 +02:00
if (sorting == "cpu lazy" && !reverse) {
double max = 10.0, target = 30.0;
for (size_t i = 0, offset = 0; i < procs.size(); i++) {
if (i <= 5 && procs[i].cpu_p > max) max = procs[i].cpu_p;
else if (i == 6) target = (max > 30.0) ? max : 10.0;
if (i == offset && procs[i].cpu_p > 30.0) offset++;
else if (procs[i].cpu_p > target) rotate(procs.begin() + offset, procs.begin() + i, procs.begin() + i + 1);
}
}
2021-06-13 23:12:11 +02:00
//* Generate tree view if enabled
if (tree) {
auto min_ppid = std::ranges::min(procs, [](proc_info& a, proc_info& b) { return a.ppid < b.ppid; }).ppid;
vector<proc_info> tree_procs;
for (auto& p : procs) {
if (p.ppid == min_ppid) _tree_gen(p, procs, tree_procs);
}
procs.swap(tree_procs);
}
//* Clear dead processes from cache at a regular interval
if (++counter >= 10000 || ((int)cache.size() > npids + 100)) {
counter = 0;
2021-06-12 18:49:27 +02:00
unordered_flat_map<uint, p_cache> r_cache;
r_cache.reserve(pid_list.size());
for (auto& p : pid_list) {
if (cache.contains(p)) r_cache[p] = cache.at(p);
}
2021-06-12 18:49:27 +02:00
cache.swap(r_cache);
}
2021-06-05 01:41:24 +02:00
old_cputimes = cputimes;
atomic_wait(drawing);
current_procs.swap(procs);
numpids = npids;
collecting.store(false);
return current_procs;
2021-05-10 23:46:41 +02:00
}
//* Initialize needed variables for collect
2021-05-14 18:54:37 +02:00
void init(){
2021-06-05 01:41:24 +02:00
proc_path = (fs::is_directory(fs::path("/proc")) && access("/proc", R_OK) != -1) ? "/proc" : "";
if (proc_path.empty()) {
string errmsg = "Proc filesystem not found or no permission to read from it!";
Logger::error(errmsg);
cout << "ERROR: " << errmsg << endl;
exit(1);
}
2021-05-23 22:25:07 +02:00
passwd_path = (access("/etc/passwd", R_OK) != -1) ? fs::path("/etc/passwd") : passwd_path;
if (passwd_path.empty()) Logger::warning("Could not read /etc/passwd, will show UID instead of username.");
page_size = sysconf(_SC_PAGE_SIZE);
if (page_size <= 0) {
page_size = 4096;
Logger::warning("Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.");
}
2021-05-23 22:25:07 +02:00
clk_tck = sysconf(_SC_CLK_TCK);
if (clk_tck <= 0) {
clk_tck = 100;
Logger::warning("Could not get system clocks per second. Defaulting to 100, processes cpu usage might be incorrect.");
}
}
}
2021-05-10 23:46:41 +02:00
#endif