Debian Codegraph @

src/oom/oomd-conf.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "conf-files.h"
4 #include "conf-parser.h"
5 #include "hashmap.h"
6 #include "log.h"
7 #include "oomd-conf.h"
8 #include "oomd-manager.h"
9 #include "parse-util.h"
10 #include "path-util.h"
11 #include "percent-util.h"
12 #include "stat-util.h"
13 #include "string-table.h"
14 #include "string-util.h"
15 #include "strv.h"
16 #include "time-util.h"
17
18 static int config_parse_duration(
19 const char *unit,
20 const char *filename,
21 unsigned line,
22 const char *section,
23 unsigned section_line,
24 const char *lvalue,
25 int ltype,
26 const char *rvalue,
27 void *data,
28 void *userdata) {
29
30 usec_t usec, *duration = ASSERT_PTR(data);
31 int r;
32
33 if (isempty(rvalue)) {
34 *duration = DEFAULT_MEM_PRESSURE_DURATION_USEC;
35 return 0;
36 }
37
38 r = parse_sec(rvalue, &usec);
39 if (r < 0)
40 return log_syntax_parse_error(unit, filename, line, r, lvalue, rvalue);
41
42 if (usec == 0) {
43 /* Map zero -> default for backwards compatibility. */
44 *duration = DEFAULT_MEM_PRESSURE_DURATION_USEC;
45 return 0;
46 }
47
48 if (usec < 1 * USEC_PER_SEC || usec == USEC_INFINITY)
49 return log_syntax(
50 unit,
51 LOG_WARNING,
52 filename,
53 line,
54 0,
55 "%s= must be at least 1s and less than infinity, ignoring: %s",
56 lvalue,
57 rvalue);
58
59 *duration = usec;
60 return 0;
61 }
62
63 void manager_set_defaults(Manager *m) {
64 int r;
65
66 assert(m);
67
68 m->default_mem_pressure_duration_usec = DEFAULT_MEM_PRESSURE_DURATION_USEC;
69
70 m->swap_used_limit_permyriad = DEFAULT_SWAP_USED_LIMIT_PERCENT * 100;
71 r = store_loadavg_fixed_point(DEFAULT_MEM_PRESSURE_LIMIT_PERCENT, 0, &m->default_mem_pressure_limit);
72 if (r < 0)
73 log_warning_errno(r, "Failed to set default for default_mem_pressure_limit, ignoring: %m");
74 }
75
76 /* OOMD_ACTION_NONE is intentionally omitted — it's the "unset" sentinel. Rulesets with
77 * .action == OOMD_ACTION_NONE are rejected at load time, so oomd_action_to_string() must
78 * only be called on rulesets that have already passed ruleset_load_one's validation
79 * (otherwise it returns NULL). */
80 static const char* const oomd_action_table[] = {
81 [OOMD_ACTION_KILL_ALL] = "kill-all",
82 [OOMD_ACTION_KILL_BY_PGSCAN] = "kill-by-pgscan",
83 [OOMD_ACTION_KILL_BY_SWAP] = "kill-by-swap",
84 };
85
86 DEFINE_STRING_TABLE_LOOKUP(oomd_action, OomdAction);
87 static DEFINE_CONFIG_PARSE_ENUM(config_parse_oomd_action, oomd_action, OomdAction);
88
89 void oomd_ruleset_free(OomdRuleset *ruleset) {
90 if (!ruleset)
91 return;
92 hashmap_free(ruleset->start_times);
93 free(ruleset->name);
94 free(ruleset);
95 }
96
97 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(OomdRuleset*, oomd_ruleset_free, NULL);
98 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(oomd_ruleset_hash_ops, char, string_hash_func, string_compare_func, OomdRuleset, oomd_ruleset_free);
99
100 static int ruleset_load_one(Manager *m, const char *filename) {
101 _cleanup_free_ char *name = NULL;
102 _cleanup_(oomd_ruleset_freep) OomdRuleset *ruleset = NULL;
103 _cleanup_fclose_ FILE *f = NULL;
104 struct stat st;
105 int r;
106
107 assert(m);
108 assert(filename);
109
110 /* Pin the file via an fd so the empty-file check and the parse operate on the same
111 * inode (avoids TOCTOU between null_or_empty_path() and a subsequent open()). */
112 f = fopen(filename, "re");
113 if (!f)
114 return log_warning_errno(errno, "Failed to open '%s': %m", filename);
115
116 if (fstat(fileno(f), &st) < 0)
117 return log_warning_errno(errno, "Failed to stat '%s': %m", filename);
118
119 if (null_or_empty(&st)) {
120 log_debug("Skipping empty file: %s", filename);
121 return 0;
122 }
123
124 r = path_extract_filename(filename, &name);
125 if (r < 0)
126 return log_error_errno(r, "Failed to extract file name of '%s': %m", filename);
127
128 char *e = ASSERT_PTR(endswith(name, ".oomrule"));
129 *e = 0;
130
131 /* Apply the same validation the DBus setter and the config parser use, so that any
132 * ruleset we accept here is actually referenceable via OOMRules= from a unit. */
133 if (!string_is_safe(name, STRING_FILENAME)) {
134 log_warning("Invalid ruleset name '%s' derived from '%s', ignoring.", name, filename);
135 return 0;
136 }
137
138 ruleset = new(OomdRuleset, 1);
139 if (!ruleset)
140 return log_oom();
141
142 *ruleset = (OomdRuleset) {
143 .name = TAKE_PTR(name),
144 .memory_pressure_above = -1,
145 .swap_above = -1,
146 };
147
148 const ConfigTableItem items[] = {
149 { "Rule", "MemoryPressureAbove", config_parse_permyriad, 0, &ruleset->memory_pressure_above },
150 { "Rule", "SwapUsageMax", config_parse_permyriad, 0, &ruleset->swap_above },
151 { "Rule", "Action", config_parse_oomd_action, 0, &ruleset->action },
152 { "Rule", "LastingSec", config_parse_sec, 0, &ruleset->lasting_usec },
153 {}
154 };
155
156 r = config_parse(
157 /* unit= */ NULL,
158 filename,
159 f,
160 "Rule\0",
161 config_item_table_lookup,
162 items,
163 CONFIG_PARSE_WARN,
164 /* userdata= */ NULL,
165 /* ret_stat= */ NULL);
166 if (r < 0)
167 return log_error_errno(r, "Failed to parse ruleset file '%s': %m", filename);
168
169 if (ruleset->memory_pressure_above < 0 && ruleset->swap_above < 0) {
170 log_warning("Ruleset '%s' has no conditions configured (MemoryPressureAbove= or SwapUsageMax=), ignoring.", ruleset->name);
171 return 0;
172 }
173
174 if (ruleset->action == OOMD_ACTION_NONE) {
175 log_warning("Ruleset '%s' has no Action= configured, ignoring.", ruleset->name);
176 return 0;
177 }
178
179 if (ruleset->lasting_usec == USEC_INFINITY) {
180 log_warning("Ruleset '%s' has LastingSec=infinity which can never be satisfied, ignoring.", ruleset->name);
181 return 0;
182 }
183
184 /* A threshold at the maximum can never be exceeded, so the condition would never fire.
185 * Report the normalized percent value so the warning matches regardless of whether the
186 * user wrote '100%', '1000‰' or '10000‱'. */
187 if (ruleset->memory_pressure_above == 10000) {
188 log_warning("Ruleset '%s' has MemoryPressureAbove=" PERMYRIAD_AS_PERCENT_FORMAT_STR " (the maximum) which can never be exceeded, ignoring.",
189 ruleset->name, PERMYRIAD_AS_PERCENT_FORMAT_VAL(ruleset->memory_pressure_above));
190 return 0;
191 }
192
193 if (ruleset->swap_above == 10000) {
194 log_warning("Ruleset '%s' has SwapUsageMax=" PERMYRIAD_AS_PERCENT_FORMAT_STR " (the maximum) which can never be exceeded, ignoring.",
195 ruleset->name, PERMYRIAD_AS_PERCENT_FORMAT_VAL(ruleset->swap_above));
196 return 0;
197 }
198
199 /* Duplicates cannot occur here: conf_files_list_strv deduplicates filenames across
200 * directories, and hashmap_clear is called before loading. The value destructor in
201 * oomd_ruleset_hash_ops handles cleanup during hashmap_clear/hashmap_free. */
202 r = hashmap_ensure_replace(&m->rulesets, &oomd_ruleset_hash_ops, ruleset->name, ruleset);
203 if (r < 0)
204 return log_error_errno(r, "Failed to register ruleset '%s': %m", ruleset->name);
205
206 TAKE_PTR(ruleset);
207
208 return 0;
209 }
210
211 void manager_parse_config_file(Manager *m) {
212 _cleanup_strv_free_ char **files = NULL;
213 int r;
214
215 assert(m);
216
217 const ConfigTableItem items[] = {
218 { "OOM", "SwapUsedLimit", config_parse_permyriad, 0, &m->swap_used_limit_permyriad },
219 { "OOM", "DefaultMemoryPressureLimit", config_parse_loadavg, 0, &m->default_mem_pressure_limit },
220 { "OOM", "DefaultMemoryPressureDurationSec", config_parse_duration, 0, &m->default_mem_pressure_duration_usec },
221 { "OOM", "PrekillHookTimeoutSec", config_parse_sec, 0, &m->prekill_timeout },
222 {}
223 };
224
225 r = config_parse_standard_file_with_dropins(
226 "systemd/oomd.conf",
227 "OOM\0",
228 config_item_table_lookup,
229 items,
230 CONFIG_PARSE_WARN,
231 /* userdata= */ m);
232 if (r >= 0)
233 log_debug("Config file successfully parsed.");
234
235 r = conf_files_list_strv(&files, ".oomrule", /* root= */ NULL, CONF_FILES_WARN, RULESET_DIRS);
236 if (r < 0) {
237 /* On enumeration failure, keep the previously loaded rulesets rather than clearing them —
238 * a transient I/O error shouldn't cause in-flight units to silently lose their OOM policy. */
239 log_error_errno(r, "Failed to enumerate ruleset files, keeping previously loaded rulesets: %m");
240 return;
241 }
242
243 /* Clear all rulesets and re-parse. This intentionally resets any accumulated
244 * start_times (LastingSec timers), since the ruleset definitions may have changed. */
245 hashmap_clear(m->rulesets);
246
247 STRV_FOREACH(f, files)
248 (void) ruleset_load_one(m, *f);
249
250 if (DEBUG_LOGGING) {
251 char *name;
252 OomdRuleset *ruleset;
253 HASHMAP_FOREACH_KEY(ruleset, name, m->rulesets) {
254 log_debug("Registered ruleset: %s", name);
255 if (ruleset->memory_pressure_above >= 0)
256 log_debug(" MemoryPressureAbove=" PERMYRIAD_AS_PERCENT_FORMAT_STR, PERMYRIAD_AS_PERCENT_FORMAT_VAL(ruleset->memory_pressure_above));
257 else
258 log_debug(" MemoryPressureAbove=unset");
259 if (ruleset->swap_above >= 0)
260 log_debug(" SwapUsageMax=" PERMYRIAD_AS_PERCENT_FORMAT_STR, PERMYRIAD_AS_PERCENT_FORMAT_VAL(ruleset->swap_above));
261 else
262 log_debug(" SwapUsageMax=unset");
263 log_debug(" Action=%s", oomd_action_to_string(ruleset->action));
264 log_debug(" LastingSec=%s", FORMAT_TIMESPAN(ruleset->lasting_usec, USEC_PER_SEC));
265 }
266 }
267 }