forked from aristocratos/btop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbtop_shared.cpp
More file actions
360 lines (320 loc) · 12.8 KB
/
Copy pathbtop_shared.cpp
File metadata and controls
360 lines (320 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/* 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
*/
#include <sys/resource.h>
#include <filesystem>
#include <fstream>
#include <ranges>
#include <regex>
#include <string>
#include <unordered_set>
#include "btop_config.hpp"
#include "btop_shared.hpp"
#include "btop_tools.hpp"
namespace fs = std::filesystem;
namespace rng = std::ranges;
using namespace Tools;
namespace Cpu {
std::optional<std::string> container_engine;
string trim_name(string name) {
auto name_vec = ssplit(name);
if ((name.contains("Xeon") or v_contains(name_vec, "Duo"s)) and v_contains(name_vec, "CPU"s)) {
auto cpu_pos = v_index(name_vec, "CPU"s);
if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')'))
name = name_vec.at(cpu_pos + 1);
else
name.clear();
} else if (v_contains(name_vec, "Ryzen"s)) {
auto ryz_pos = v_index(name_vec, "Ryzen"s);
name = "Ryzen";
int tokens = 0;
for (auto i = ryz_pos + 1; i < name_vec.size() && tokens < 2; i++) {
const std::string& p = name_vec.at(i);
if (p != "AI" && p != "PRO" && p != "H" && p != "HX")
tokens++;
name += " " + p;
}
} else if (name.contains("Intel") and v_contains(name_vec, "CPU"s)) {
auto cpu_pos = v_index(name_vec, "CPU"s);
if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')') and name_vec.at(cpu_pos + 1) != "@")
name = name_vec.at(cpu_pos + 1);
else
name.clear();
} else
name.clear();
if (name.empty() and not name_vec.empty()) {
for (const auto &n : name_vec) {
if (n == "@") break;
name += n + ' ';
}
name.pop_back();
for (const auto& replace : {"Processor", "CPU", "(R)", "(TM)", "Intel", "AMD", "Apple", "Core"}) {
name = s_replace(name, replace, "");
name = s_replace(name, " ", " ");
}
name = trim(name);
}
return name;
}
}
#ifdef GPU_SUPPORT
namespace Gpu {
vector<string> gpu_names;
vector<int> gpu_b_height_offsets;
std::unordered_map<string, deque<long long>> shared_gpu_percent = {
{"gpu-average", {}},
{"gpu-vram-total", {}},
{"gpu-pwr-total", {}},
};
long long gpu_pwr_total_max = 0;
}
#endif
namespace Proc {
bool set_priority(pid_t pid, int priority) {
if (setpriority(PRIO_PROCESS, pid, priority) == 0) {
return true;
}
return false;
}
void proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree) {
if (reverse) {
switch (v_index(sort_vector, sorting)) {
case 0: rng::stable_sort(proc_vec, rng::less{}, &proc_info::pid); break;
case 1: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::name); break;
case 2: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cmd); break;
case 3: rng::stable_sort(proc_vec, rng::less{}, &proc_info::threads); break;
case 4: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::user); break;
case 5: rng::stable_sort(proc_vec, rng::less{}, &proc_info::mem); break;
case 6: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_p); break;
case 7: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_c); break;
}
}
else {
switch (v_index(sort_vector, sorting)) {
case 0: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::pid); break;
case 1: rng::stable_sort(proc_vec, rng::less{}, &proc_info::name); break;
case 2: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cmd); break;
case 3: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::threads); break;
case 4: rng::stable_sort(proc_vec, rng::less{}, &proc_info::user); break;
case 5: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::mem); break;
case 6: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_p); break;
case 7: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_c); break;
}
}
//* When sorting with "cpu lazy" push processes over threshold cpu usage to the front regardless of cumulative usage
if (not tree and not reverse and sorting == "cpu lazy") {
double max = 10.0, target = 30.0;
for (size_t i = 0, x = 0, offset = 0; i < proc_vec.size(); i++) {
if (i <= 5 and proc_vec.at(i).cpu_p > max)
max = proc_vec.at(i).cpu_p;
else if (i == 6)
target = (max > 30.0) ? max : 10.0;
if (i == offset and proc_vec.at(i).cpu_p > 30.0)
offset++;
else if (proc_vec.at(i).cpu_p > target) {
rotate(proc_vec.begin() + offset, proc_vec.begin() + i, proc_vec.begin() + i + 1);
if (++x > 10) break;
}
}
}
}
void tree_sort(vector<tree_proc>& proc_vec, const string& sorting, bool reverse, bool paused, int& c_index, const int index_max, bool collapsed) {
if (proc_vec.size() > 1 and not paused) {
if (reverse) {
switch (v_index(sort_vector, sorting)) {
case 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads < b.entry.get().threads; }); break;
case 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem < b.entry.get().mem; }); break;
case 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p < b.entry.get().cpu_p; }); break;
case 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c < b.entry.get().cpu_c; }); break;
}
}
else {
switch (v_index(sort_vector, sorting)) {
case 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads > b.entry.get().threads; }); break;
case 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem > b.entry.get().mem; }); break;
case 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p > b.entry.get().cpu_p; }); break;
case 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c > b.entry.get().cpu_c; }); break;
}
}
}
for (auto& r : proc_vec) {
r.entry.get().tree_index = (collapsed or r.entry.get().filtered ? index_max : c_index++);
if (not r.children.empty()) {
tree_sort(r.children, sorting, reverse, paused, c_index, (collapsed or r.entry.get().collapsed or r.entry.get().tree_index == (size_t)index_max));
}
}
}
auto matches_filter(const proc_info& proc, const std::string& filter) -> bool {
if (filter.starts_with("!")) {
if (filter.size() == 1) {
return true;
}
// An incomplete regex throws, see issue https://github.com/aristocratos/btop/issues/1133
try {
std::regex regex { filter.substr(1), std::regex::extended };
return std::regex_search(std::to_string(proc.pid), regex) || std::regex_search(proc.name, regex) ||
std::regex_match(proc.cmd, regex) || std::regex_search(proc.user, regex);
} catch (std::regex_error& /* unused */) {
return false;
}
}
return std::to_string(proc.pid).contains(filter) || s_contains_ic(proc.name, filter) ||
s_contains_ic(proc.cmd, filter) || s_contains_ic(proc.user, filter);
}
void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs,
int cur_depth, bool collapsed, const string& filter, bool found, bool no_update, bool should_filter) {
bool filtering = false;
//? If filtering, include children of matching processes
if (not found and (should_filter or not filter.empty())) {
if (!matches_filter(cur_proc, filter)) {
filtering = true;
cur_proc.filtered = true;
filter_found++;
}
else {
found = true;
cur_depth = 0;
}
}
else if (cur_proc.filtered) cur_proc.filtered = false;
cur_proc.depth = cur_depth;
//? Set tree index position for process if not filtered out or currently in a collapsed sub-tree
out_procs.push_back({ cur_proc, {} });
if (not collapsed and not filtering) {
cur_proc.tree_index = out_procs.size() - 1;
//? Try to find name of the binary file and append to program name if not the same
if (cur_proc.short_cmd.empty() and not cur_proc.cmd.empty()) {
std::string_view cmd_view = cur_proc.cmd;
cmd_view = cmd_view.substr((size_t)0, std::min(cmd_view.find(' '), cmd_view.size()));
cmd_view = cmd_view.substr(std::min(cmd_view.find_last_of('/') + 1, cmd_view.size()));
cur_proc.short_cmd = string{cmd_view};
}
}
else {
cur_proc.tree_index = in_procs.size();
}
//? Recursive iteration over all children
for (auto& p : rng::equal_range(in_procs, cur_proc.pid, rng::less{}, &proc_info::ppid)) {
if (collapsed and not filtering) {
cur_proc.filtered = true;
}
_tree_gen(p, in_procs, out_procs.back().children, cur_depth + 1, (collapsed or cur_proc.collapsed), filter, found, no_update, should_filter);
if (not no_update and not filtering and (collapsed or cur_proc.collapsed)) {
//auto& parent = cur_proc;
if (p.state != 'X') {
cur_proc.cpu_p += p.cpu_p;
cur_proc.cpu_c += p.cpu_c;
cur_proc.mem += p.mem;
cur_proc.threads += p.threads;
}
filter_found++;
p.filtered = true;
}
else if (Config::getB("proc_aggregate") and p.state != 'X') {
cur_proc.cpu_p += p.cpu_p;
cur_proc.cpu_c += p.cpu_c;
cur_proc.mem += p.mem;
cur_proc.threads += p.threads;
}
}
}
void _collect_prefixes(tree_proc &t, const bool is_last, const string &header) {
const bool is_filtered = t.entry.get().filtered;
if (is_filtered) t.entry.get().depth = 0;
if (!t.children.empty()) t.entry.get().prefix = header + (t.entry.get().collapsed ? "[+]─": "[-]─");
else t.entry.get().prefix = header + (is_last ? " └─": " ├─");
for (auto child = t.children.begin(); child != t.children.end(); ++child) {
_collect_prefixes(*child, child == (t.children.end() - 1),
is_filtered ? "": header + (is_last ? " ": " │ "));
}
}
void toggle_tree_collapse(std::vector<proc_info>& current_procs) {
//? Build sets of all pids and parent pids to identify root processes
std::unordered_set<size_t> pid_set, parent_pids;
for (const auto& p : current_procs) {
pid_set.insert(p.pid);
parent_pids.insert(static_cast<size_t>(p.ppid));
}
//? If any non-root parent is expanded, collapse; otherwise expand
const bool do_collapse = rng::any_of(current_procs, [&parent_pids, &pid_set](const proc_info& p) {
return parent_pids.contains(p.pid)
and pid_set.contains(static_cast<size_t>(p.ppid))
and not p.collapsed;
});
//? Root processes (parent not in tracked list) are never touched
for (auto& p : current_procs) {
if (not pid_set.contains(static_cast<size_t>(p.ppid))) continue;
p.collapsed = do_collapse;
}
}
void _auto_collapse_oversized(std::vector<proc_info>& current_procs, const bool tree_mode_change) {
//? Only act when the user just switched into tree view
const int threshold = Config::getI("proc_tree_auto_collapse");
if (threshold <= 0 or not tree_mode_change) return;
//? Never collapse the root process or its direct children, only deeper busy parents
const size_t root_ppid = static_cast<size_t>(current_procs.at(0).ppid);
std::unordered_set<size_t> root_pids;
for (const auto& p : current_procs) {
if (static_cast<size_t>(p.ppid) == root_ppid) root_pids.insert(p.pid);
}
for (auto& p : current_procs) {
if (static_cast<size_t>(p.ppid) == root_ppid or root_pids.contains(static_cast<size_t>(p.ppid))) continue;
if (rng::count(current_procs, p.pid, &proc_info::ppid) >= threshold) {
p.collapsed = true;
}
}
}
}
auto detect_container() -> std::optional<std::string> {
std::error_code err;
if (fs::exists(fs::path("/run/.containerenv"), err)) {
return std::make_optional(std::string { "podman" });
}
if (fs::exists(fs::path("/.dockerenv"), err)) {
return std::make_optional(std::string { "docker" });
}
auto systemd_container = fs::path("/run/systemd/container");
if (fs::exists(systemd_container, err)) {
auto stream = std::ifstream { systemd_container };
auto buf = std::string {};
stream >> buf;
return std::make_optional(buf);
}
return std::nullopt;
}
#if defined(GPU_SUPPORT)
const array<string, 2> Gpu::mem_names { "used", "free" };
#endif
const vector<string> Proc::sort_vector = {
"pid",
"name",
"command",
"threads",
"user",
"memory",
"cpu direct",
"cpu lazy",
};
const std::unordered_map<char, string> Proc::proc_states = {
{'R', "Running"},
{'S', "Sleeping"},
{'D', "Waiting"},
{'Z', "Zombie"},
{'T', "Stopped"},
{'t', "Tracing"},
{'X', "Dead"},
{'x', "Dead"},
{'K', "Wakekill"},
{'W', "Unknown"},
{'P', "Parked"}
};