fix cgroup finding, fix UDError

This commit is contained in:
Alexey Avramov 2019-03-31 15:16:32 +09:00
parent f4cac53313
commit d14d418cac
4 changed files with 82 additions and 79 deletions

View File

@ -232,6 +232,7 @@ Please create [issues](https://github.com/hakavlad/nohang/issues). Use cases, fe
- [x] Reduced memory usage and startup time (using `sys.argv` instead of `argparse`) - [x] Reduced memory usage and startup time (using `sys.argv` instead of `argparse`)
- [x] Reduced memory usage with `mlockall()` using `MCL_ONFAULT` ([rfjakob/earlyoom#112](https://github.com/rfjakob/earlyoom/issues/112)) and lock all memory by default - [x] Reduced memory usage with `mlockall()` using `MCL_ONFAULT` ([rfjakob/earlyoom#112](https://github.com/rfjakob/earlyoom/issues/112)) and lock all memory by default
- [x] Improve poll rate algorithm - [x] Improve poll rate algorithm
- [x] Fixed crash at startup due to `UnicodeDecodeError` on some systems
- [x] Fixed Makefile for installation on CentOS 7 (remove gzip `-k` option). - [x] Fixed Makefile for installation on CentOS 7 (remove gzip `-k` option).
- [x] Added `max_post_sigterm_victim_lifetime` option: send SIGKILL to the victim if it doesn't respond to SIGTERM for a certain time - [x] Added `max_post_sigterm_victim_lifetime` option: send SIGKILL to the victim if it doesn't respond to SIGTERM for a certain time
- [x] Added `post_kill_exe` option (the ability to run any command after killing the victim) - [x] Added `post_kill_exe` option (the ability to run any command after killing the victim)

View File

@ -131,23 +131,47 @@ rate_zram = 500
See also https://github.com/rfjakob/earlyoom/issues/61 See also https://github.com/rfjakob/earlyoom/issues/61
Максимальное время сна между проверками памяти.
Положительное число.
max_sleep_time = 3 max_sleep_time = 3
Минимальное время сна между проверками памяти.
Положительное число, не превышающее max_sleep_time.
min_sleep_time = 0.1 min_sleep_time = 0.1
##################################################################### #####################################################################
4. The prevention of killing innocent victims 4. The prevention of killing innocent victims
Минимальное значение bandess (по умолчанию равно oom_score),
которым должен обладать
процесс для того, чтобы ему был отправлен сигнал.
Позволяет предотвратить убийство невиновных если что-то
пойдет не так.
Valid values are integers from the range [0; 1000]. Valid values are integers from the range [0; 1000].
min_badness = 20 min_badness = 20
Минимальная задержка после отправки соответствующих сигналов
для предотвращения риска убийства сразу множества процессов.
Valid values are non-negative floating-point numbers. Valid values are non-negative floating-point numbers.
min_delay_after_sigterm = 0.2 min_delay_after_sigterm = 0.2
min_delay_after_sigkill = 1 min_delay_after_sigkill = 1
Процессы браузера chromium обычно имеют oom_score_adj
200 или 300. Это приводит к тому, что процессы хрома умирают
первыми вместо действительно тяжелых процессов.
Если параметр decrease_oom_score_adj установлен
в значение True, то у процессов, имеющих oom_score_adj выше
oom_score_adj_max значение oom_score_adj будет опущено
до oom_score_adj_max перед поиском жертвы.
Enabling the option requires root privileges. Enabling the option requires root privileges.
Valid values are True and False. Valid values are True and False.
Values are case sensitive. Values are case sensitive.
@ -207,6 +231,7 @@ re_match_cmdline = False
@CMDLINE_RE -200 /// ^/usr/lib/virtualbox @CMDLINE_RE -200 /// ^/usr/lib/virtualbox
5.3 Matching UIDs with RE patterns 5.3 Matching UIDs with RE patterns
The most slow option The most slow option
@ -289,12 +314,21 @@ $ETC apache2 /// systemctl restart apache2
- OOM prevention results and - OOM prevention results and
- low memory warnings - low memory warnings
gui_notifications = True Включение этой опции требует наличия notify-send в системе.
В Debian/Ubuntu это обеспечивается установкой пакета
libnotify-bin. В Fedora и Arch Linux - пакет libnotify.
Также требуется наличие сервера уведомлений.
При запуске nohang от рута уведомления рассылаются всем
залогиненным пользователям.
See also wiki.archlinux.org/index.php/Desktop_notifications
Valid values are True and False.
gui_notifications = False
Enable GUI notifications about the low level of available memory. Enable GUI notifications about the low level of available memory.
Valid values are True and False. Valid values are True and False.
gui_low_memory_warnings = True gui_low_memory_warnings = False
Execute the command instead of sending GUI notifications if the value is Execute the command instead of sending GUI notifications if the value is
not empty line. For example: not empty line. For example:
@ -302,6 +336,9 @@ gui_low_memory_warnings = True
warning_exe = warning_exe =
Если значения MemAvailable и SwapFree одновременно будут ниже
соотвестствующих значений, то будут отправлены уведомления.
Can be specified in % (percent) and M (MiB). Can be specified in % (percent) and M (MiB).
Valid values are floating-point numbers from the range [0; 100] %. Valid values are floating-point numbers from the range [0; 100] %.
@ -309,8 +346,13 @@ mem_min_warnings = 25 %
swap_min_warnings = 25 % swap_min_warnings = 25 %
Если доля zram в памяти превысит значение zram_max_warnings,
то будут отправляться уведомления с минимальным периодом равным
min_time_between_warnings.
zram_max_warnings = 40 % zram_max_warnings = 40 %
Минимальное время между отправками уведомлений в секундах.
Valid values are floating-point numbers from the range [1; 300]. Valid values are floating-point numbers from the range [1; 300].
min_time_between_warnings = 15 min_time_between_warnings = 15
@ -332,6 +374,10 @@ print_config = False
print_mem_check_results = False print_mem_check_results = False
Минимальная периодичность печати состояния памяти.
0 - печатать все проверки памяти.
Неотрицательное число.
min_mem_report_interval = 60 min_mem_report_interval = 60
Print sleep periods between memory checks. Print sleep periods between memory checks.
@ -339,12 +385,21 @@ min_mem_report_interval = 60
print_sleep_periods = False print_sleep_periods = False
Печатать общую статистику по корректирующим действиям с момента
запуска nohang после каждого корректирующего действия.
print_total_stat = True print_total_stat = True
print_proc_table = True Печатать таблицу процессов перед каждым корректирующим действием.
print_proc_table = False
print_victim_info = True print_victim_info = True
Максимальная глубина показа родословной жертвы.
По умолчанию (1) показывается только родитель - PPID.
Целое положительное число.
max_ancestry_depth = 1 max_ancestry_depth = 1
separate_log = False separate_log = False
@ -355,8 +410,17 @@ psi_debug = False
9. Misc 9. Misc
Жертва может не реагировать на SIGTERM.
max_post_sigterm_victim_lifetime - это время, при превышении
которого жертва получит SIGKILL.
Неотрицательные числа.
max_post_sigterm_victim_lifetime = 10 max_post_sigterm_victim_lifetime = 10
Execute the command after sending SIGKILL to the victim if the value is
not empty line. For example:
post_kill_exe = cat /proc/meminfo &
post_kill_exe = post_kill_exe =
forbid_negative_badness = True forbid_negative_badness = True

17
nohang
View File

@ -61,14 +61,18 @@ stat_dict = dict()
separate_log = False # will be overwritten after parse config separate_log = False # will be overwritten after parse config
with open('/proc/self/cgroup') as f:
# Find cgroup-line position in /proc/*/cgroup file."""
for cgroup_index, line in enumerate(f):
if ':name=' in line:
break
########################################################################## ##########################################################################
# define functions # define functions
def exe(cmd): def exe(cmd):
""" """
""" """
@ -80,9 +84,6 @@ def exe(cmd):
return err return err
def valid_re(reg_exp): def valid_re(reg_exp):
"""Validate regular expression. """Validate regular expression.
""" """
@ -97,8 +98,8 @@ def pid_to_cgroup(pid):
""" """
""" """
with open('/proc/' + pid + '/cgroup') as f: with open('/proc/' + pid + '/cgroup') as f:
for line in f: for n, line in enumerate(f):
if line.startswith('1:'): if n == cgroup_index:
return '/' + line.partition('/')[2][:-1] return '/' + line.partition('/')[2][:-1]

View File

@ -131,47 +131,23 @@ rate_zram = 500
See also https://github.com/rfjakob/earlyoom/issues/61 See also https://github.com/rfjakob/earlyoom/issues/61
Максимальное время сна между проверками памяти.
Положительное число.
max_sleep_time = 3 max_sleep_time = 3
Минимальное время сна между проверками памяти.
Положительное число, не превышающее max_sleep_time.
min_sleep_time = 0.1 min_sleep_time = 0.1
##################################################################### #####################################################################
4. The prevention of killing innocent victims 4. The prevention of killing innocent victims
Минимальное значение bandess (по умолчанию равно oom_score),
которым должен обладать
процесс для того, чтобы ему был отправлен сигнал.
Позволяет предотвратить убийство невиновных если что-то
пойдет не так.
Valid values are integers from the range [0; 1000]. Valid values are integers from the range [0; 1000].
min_badness = 20 min_badness = 20
Минимальная задержка после отправки соответствующих сигналов
для предотвращения риска убийства сразу множества процессов.
Valid values are non-negative floating-point numbers. Valid values are non-negative floating-point numbers.
min_delay_after_sigterm = 0.2 min_delay_after_sigterm = 0.2
min_delay_after_sigkill = 1 min_delay_after_sigkill = 1
Процессы браузера chromium обычно имеют oom_score_adj
200 или 300. Это приводит к тому, что процессы хрома умирают
первыми вместо действительно тяжелых процессов.
Если параметр decrease_oom_score_adj установлен
в значение True, то у процессов, имеющих oom_score_adj выше
oom_score_adj_max значение oom_score_adj будет опущено
до oom_score_adj_max перед поиском жертвы.
Enabling the option requires root privileges. Enabling the option requires root privileges.
Valid values are True and False. Valid values are True and False.
Values are case sensitive. Values are case sensitive.
@ -231,7 +207,6 @@ re_match_cmdline = False
@CMDLINE_RE -200 /// ^/usr/lib/virtualbox @CMDLINE_RE -200 /// ^/usr/lib/virtualbox
5.3 Matching UIDs with RE patterns 5.3 Matching UIDs with RE patterns
The most slow option The most slow option
@ -247,7 +222,8 @@ re_match_cgroup = True
@CGROUP_RE -50 /// system.slice @CGROUP_RE -50 /// system.slice
@CGROUP_RE 50 /// foo.service @CGROUP_RE 50 /// foo.service
@CGROUP_RE 2000 /// user.slice
@CGROUP_RE -50 /// user.slice
5.5 Matching realpath with RE patterns 5.5 Matching realpath with RE patterns
@ -314,21 +290,12 @@ $ETC apache2 /// systemctl restart apache2
- OOM prevention results and - OOM prevention results and
- low memory warnings - low memory warnings
Включение этой опции требует наличия notify-send в системе. gui_notifications = True
В Debian/Ubuntu это обеспечивается установкой пакета
libnotify-bin. В Fedora и Arch Linux - пакет libnotify.
Также требуется наличие сервера уведомлений.
При запуске nohang от рута уведомления рассылаются всем
залогиненным пользователям.
See also wiki.archlinux.org/index.php/Desktop_notifications
Valid values are True and False.
gui_notifications = False
Enable GUI notifications about the low level of available memory. Enable GUI notifications about the low level of available memory.
Valid values are True and False. Valid values are True and False.
gui_low_memory_warnings = False gui_low_memory_warnings = True
Execute the command instead of sending GUI notifications if the value is Execute the command instead of sending GUI notifications if the value is
not empty line. For example: not empty line. For example:
@ -336,9 +303,6 @@ gui_low_memory_warnings = False
warning_exe = warning_exe =
Если значения MemAvailable и SwapFree одновременно будут ниже
соотвестствующих значений, то будут отправлены уведомления.
Can be specified in % (percent) and M (MiB). Can be specified in % (percent) and M (MiB).
Valid values are floating-point numbers from the range [0; 100] %. Valid values are floating-point numbers from the range [0; 100] %.
@ -346,13 +310,8 @@ mem_min_warnings = 25 %
swap_min_warnings = 25 % swap_min_warnings = 25 %
Если доля zram в памяти превысит значение zram_max_warnings,
то будут отправляться уведомления с минимальным периодом равным
min_time_between_warnings.
zram_max_warnings = 40 % zram_max_warnings = 40 %
Минимальное время между отправками уведомлений в секундах.
Valid values are floating-point numbers from the range [1; 300]. Valid values are floating-point numbers from the range [1; 300].
min_time_between_warnings = 15 min_time_between_warnings = 15
@ -374,10 +333,6 @@ print_config = False
print_mem_check_results = False print_mem_check_results = False
Минимальная периодичность печати состояния памяти.
0 - печатать все проверки памяти.
Неотрицательное число.
min_mem_report_interval = 60 min_mem_report_interval = 60
Print sleep periods between memory checks. Print sleep periods between memory checks.
@ -385,21 +340,12 @@ min_mem_report_interval = 60
print_sleep_periods = False print_sleep_periods = False
Печатать общую статистику по корректирующим действиям с момента
запуска nohang после каждого корректирующего действия.
print_total_stat = True print_total_stat = True
Печатать таблицу процессов перед каждым корректирующим действием. print_proc_table = True
print_proc_table = False
print_victim_info = True print_victim_info = True
Максимальная глубина показа родословной жертвы.
По умолчанию (1) показывается только родитель - PPID.
Целое положительное число.
max_ancestry_depth = 1 max_ancestry_depth = 1
separate_log = False separate_log = False
@ -410,17 +356,8 @@ psi_debug = False
9. Misc 9. Misc
Жертва может не реагировать на SIGTERM.
max_post_sigterm_victim_lifetime - это время, при превышении
которого жертва получит SIGKILL.
Неотрицательные числа.
max_post_sigterm_victim_lifetime = 10 max_post_sigterm_victim_lifetime = 10
Execute the command after sending SIGKILL to the victim if the value is
not empty line. For example:
post_kill_exe = cat /proc/meminfo &
post_kill_exe = post_kill_exe =
forbid_negative_badness = True forbid_negative_badness = True