forked from rfjakob/earlyoom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkill.c
330 lines (294 loc) · 9.73 KB
/
kill.c
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
// SPDX-License-Identifier: MIT
/* Kill the most memory-hungy process */
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h> // for PATH_MAX
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "globals.h"
#include "kill.h"
#include "meminfo.h"
#include "msg.h"
#define BADNESS_PREFER 300
#define BADNESS_AVOID -300
static int isnumeric(char* str)
{
int i = 0;
// Empty string is not numeric
if (str[0] == 0)
return 0;
while (1) {
if (str[i] == 0) // End of string
return 1;
if (isdigit(str[i]) == 0)
return 0;
i++;
}
}
static void notify(const char* summary, const char* body)
{
int pid = fork();
if (pid > 0) {
// parent
return;
}
char summary2[1024] = { 0 };
snprintf(summary2, sizeof(summary2), "string:%s", summary);
char body2[1024] = "string:";
if (body != NULL) {
snprintf(body2, sizeof(body2), "string:%s", body);
}
// Complete command line looks like this:
// dbus-send --system / net.nuetzlich.SystemNotifications.Notify 'string:summary text' 'string:and body text'
execl("/usr/bin/dbus-send", "dbus-send", "--system", "/", "net.nuetzlich.SystemNotifications.Notify",
summary2, body2, NULL);
warn("notify: exec failed: %s\n", strerror(errno));
exit(1);
}
/*
* Send the selected signal to "pid" and wait for the process to exit
* (max 10 seconds)
*/
int kill_wait(const poll_loop_args_t* args, pid_t pid, int sig)
{
if (args->dryrun && sig != 0) {
warn("dryrun, not actually sending any signal\n");
return 0;
}
meminfo_t m = { 0 };
const unsigned poll_ms = 100;
int res = kill(pid, sig);
if (res != 0) {
return res;
}
/* signal 0 does not kill the process. Don't wait for it to exit */
if (sig == 0) {
return 0;
}
for (unsigned i = 0; i < 100; i++) {
float secs = (float)(i * poll_ms) / 1000;
// We have sent SIGTERM but now have dropped below SIGKILL limits.
// Escalate to SIGKILL.
if (sig != SIGKILL) {
m = parse_meminfo();
print_mem_stats(debug, m);
if (m.MemAvailablePercent <= args->mem_kill_percent && m.SwapFreePercent <= args->swap_kill_percent) {
sig = SIGKILL;
res = kill(pid, sig);
// kill first, print after
warn("escalating to SIGKILL after %.1f seconds\n", secs);
if (res != 0) {
return res;
}
}
} else if (enable_debug) {
m = parse_meminfo();
print_mem_stats(printf, m);
}
if (!is_alive(pid)) {
warn("process exited after %.1f seconds\n", secs);
return 0;
}
struct timespec req = { .tv_sec = (time_t)(poll_ms / 1000), .tv_nsec = (poll_ms % 1000) * 1000000 };
nanosleep(&req, NULL);
}
errno = ETIME;
return -1;
}
/*
* Find the process with the largest oom_score and kill it.
*/
void kill_largest_process(const poll_loop_args_t* args, int sig)
{
struct procinfo victim = { 0 };
struct timespec t0 = { 0 }, t1 = { 0 };
if (enable_debug) {
clock_gettime(CLOCK_MONOTONIC, &t0);
}
DIR* procdir = opendir("/proc");
if (procdir == NULL) {
fatal(5, "Could not open /proc: %s", strerror(errno));
}
int candidates = 0;
while (1) {
errno = 0;
struct dirent* d = readdir(procdir);
if (d == NULL) {
if (errno != 0)
warn("userspace_kill: readdir error: %s", strerror(errno));
break;
}
// proc contains lots of directories not related to processes,
// skip them
if (!isnumeric(d->d_name))
continue;
struct procinfo cur = {
.pid = (int)strtol(d->d_name, NULL, 10),
.uid = -1,
.badness = -1,
.VmRSSkiB = -1,
};
if (cur.pid <= 1)
// Let's not kill init.
continue;
debug("pid %5d:", cur.pid);
{
int res = get_oom_score(cur.pid);
if (res < 0) {
debug(" error reading oom_score: %s\n", strerror(-res));
continue;
}
cur.badness = res;
}
if (args->ignore_oom_score_adj) {
int oom_score_adj = 0;
int res = get_oom_score_adj(cur.pid, &oom_score_adj);
if (res < 0) {
debug(" error reading oom_score_adj: %s\n", strerror(-res));
continue;
}
if (oom_score_adj > 0) {
cur.badness -= oom_score_adj;
}
}
if ((args->prefer_regex || args->avoid_regex)) {
int res = get_comm(cur.pid, cur.name, sizeof(cur.name));
if (res < 0) {
debug(" error reading process name: %s\n", strerror(-res));
continue;
}
if (args->prefer_regex && regexec(args->prefer_regex, cur.name, (size_t)0, NULL, 0) == 0) {
cur.badness += BADNESS_PREFER;
}
if (args->avoid_regex && regexec(args->avoid_regex, cur.name, (size_t)0, NULL, 0) == 0) {
cur.badness += BADNESS_AVOID;
}
}
debug(" badness %3d", cur.badness);
candidates++;
if (cur.badness < victim.badness) {
// skip "type 1", encoded as 1 space
debug(" \n");
continue;
}
{
long long res = get_vm_rss_kib(cur.pid);
if (res < 0) {
debug(" error reading rss: %s\n", strerror((int)-res));
continue;
}
cur.VmRSSkiB = res;
}
debug(" vm_rss %7llu", cur.VmRSSkiB);
if (cur.VmRSSkiB == 0) {
// Kernel threads have zero rss
// skip "type 2", encoded as 2 spaces
debug(" \n");
continue;
}
if (cur.badness == victim.badness && cur.VmRSSkiB <= victim.VmRSSkiB) {
// skip "type 3", encoded as 3 spaces
debug(" \n");
continue;
}
// Skip processes with oom_score_adj = -1000, like the
// kernel oom killer would.
int oom_score_adj = 0;
{
int res = get_oom_score_adj(cur.pid, &oom_score_adj);
if (res < 0) {
debug(" error reading oom_score_adj: %s\n", strerror(-res));
continue;
}
if (oom_score_adj == -1000) {
// skip "type 4", encoded as 3 spaces
debug(" \n");
continue;
}
}
// Fill out remaining fields
if (strlen(cur.name) == 0) {
int res = get_comm(cur.pid, cur.name, sizeof(cur.name));
if (res < 0) {
debug(" error reading process name: %s\n", strerror(-res));
continue;
}
}
{
int res = get_uid(cur.pid);
if (res < 0) {
debug(" error reading uid: %s\n", strerror(-res));
continue;
}
cur.uid = res;
}
// Save new victim
victim = cur;
debug(" uid %4d oom_score_adj %4d \"%s\" <--- new victim\n", victim.uid, oom_score_adj, victim.name);
} // end of while(1) loop
closedir(procdir);
if (candidates <= 1 && victim.pid == getpid()) {
warn("Only found myself (pid %d) in /proc. Do you use hidpid? See https://github.com/rfjakob/earlyoom/wiki/proc-hidepid\n",
victim.pid);
victim.pid = 0;
}
if (victim.pid <= 0) {
warn("Could not find a process to kill. Sleeping 1 second.\n");
if (args->notify) {
notify("earlyoom", "Error: Could not find a process to kill. Sleeping 1 second.");
}
sleep(1);
return;
}
if (enable_debug) {
clock_gettime(CLOCK_MONOTONIC, &t1);
long delta = (t1.tv_sec - t0.tv_sec) * 1000000 + (t1.tv_nsec - t0.tv_nsec) / 1000;
debug("selecting victim took %ld.%03ld ms\n", delta / 1000, delta % 1000);
}
char* sig_name = "?";
if (sig == SIGTERM) {
sig_name = "SIGTERM";
} else if (sig == SIGKILL) {
sig_name = "SIGKILL";
} else if (sig == 0) {
sig_name = "0 (no-op signal)";
}
// sig == 0 is used as a self-test during startup. Don't notifiy the user.
if (sig != 0 || enable_debug) {
warn("sending %s to process %d uid %d \"%s\": badness %d, VmRSS %lld MiB\n",
sig_name, victim.pid, victim.uid, victim.name, victim.badness, victim.VmRSSkiB / 1024);
}
int res = kill_wait(args, victim.pid, sig);
int saved_errno = errno;
// Send the GUI notification AFTER killing a process. This makes it more likely
// that there is enough memory to spawn the notification helper.
if (sig != 0) {
char notif_args[PATH_MAX + 1000];
snprintf(notif_args, sizeof(notif_args),
"Low memory! Killing process %d %s", victim.pid, victim.name);
if (args->notify) {
notify("earlyoom", notif_args);
}
}
if (sig == 0) {
return;
}
if (res != 0) {
warn("kill failed: %s\n", strerror(saved_errno));
if (args->notify) {
notify("earlyoom", "Error: Failed to kill process");
}
// Killing the process may have failed because we are not running as root.
// In that case, trying again in 100ms will just yield the same error.
// Throttle ourselves to not spam the log.
if (saved_errno == EPERM) {
warn("sleeping 1 second\n");
sleep(1);
}
}
}