From 813c8d756d41e3179cd047a639ee969f94cfa640 Mon Sep 17 00:00:00 2001 From: Giuseppe Scrivano Date: Thu, 16 Mar 2023 22:14:02 +0100 Subject: [PATCH] oom: restore old OOM score restore the original OOM score before running the OCI runtime so that the container process will inherit the OOM score from the environment instead of the default value of 0. Signed-off-by: Giuseppe Scrivano --- src/conmon.c | 5 +++-- src/oom.c | 14 +++++++++++--- src/oom.h | 2 +- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/conmon.c b/src/conmon.c index c53b437d..71f4d499 100644 --- a/src/conmon.c +++ b/src/conmon.c @@ -43,6 +43,7 @@ int main(int argc, char *argv[]) _cleanup_gerror_ GError *err = NULL; char buf[BUF_SIZE]; int num_read; + int old_oom_score = 0; _cleanup_close_ int dev_null_r_cleanup = -1; _cleanup_close_ int dev_null_w_cleanup = -1; _cleanup_close_ int dummyfd = -1; @@ -54,7 +55,7 @@ int main(int argc, char *argv[]) process_cli(); - attempt_oom_adjust("-1000"); + attempt_oom_adjust(-1000, &old_oom_score); /* ignoring SIGPIPE prevents conmon from being spuriously killed */ signal(SIGPIPE, SIG_IGN); @@ -290,7 +291,7 @@ int main(int argc, char *argv[]) } // We don't want runc to be unkillable so we reset the oom_score_adj back to 0 - attempt_oom_adjust("0"); + attempt_oom_adjust(old_oom_score, NULL); execv(g_ptr_array_index(runtime_argv, 0), (char **)runtime_argv->pdata); exit(127); } diff --git a/src/oom.c b/src/oom.c index 5ab56891..a55d4558 100644 --- a/src/oom.c +++ b/src/oom.c @@ -5,15 +5,23 @@ #include #include -void attempt_oom_adjust(const char *const oom_score) +void attempt_oom_adjust(int oom_score, int *old_value) { #ifdef __linux__ - int oom_score_fd = open("/proc/self/oom_score_adj", O_WRONLY); + char fmt_oom_score[16]; + int oom_score_fd = open("/proc/self/oom_score_adj", O_RDWR); if (oom_score_fd < 0) { ndebugf("failed to open /proc/self/oom_score_adj: %s\n", strerror(errno)); return; } - if (write(oom_score_fd, oom_score, strlen(oom_score)) < 0) { + if (old_value) { + if (read(oom_score_fd, fmt_oom_score, sizeof(fmt_oom_score)) < 0) { + ndebugf("failed to read from /proc/self/oom_score_adj: %s\n", strerror(errno)); + } + *old_value = atoi(fmt_oom_score); + } + sprintf(fmt_oom_score, "%d", oom_score); + if (write(oom_score_fd, fmt_oom_score, strlen(fmt_oom_score)) < 0) { ndebugf("failed to write to /proc/self/oom_score_adj: %s\n", strerror(errno)); } close(oom_score_fd); diff --git a/src/oom.h b/src/oom.h index 9408c3b4..cc27340a 100644 --- a/src/oom.h +++ b/src/oom.h @@ -1,6 +1,6 @@ #if !defined(OOM_H) #define OOM_H -void attempt_oom_adjust(const char *const oom_score); +void attempt_oom_adjust(int oom_score, int *old_value); #endif // OOM_H