Debian Codegraph @

src/journal/journald-manager.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/audit.h>
4 #include <linux/sockios.h>
5 #include <sys/stat.h>
6 #include <sys/ioctl.h>
7 #include <sys/mman.h>
8 #include <sys/signalfd.h>
9 #include <sys/statvfs.h>
10 #include <unistd.h>
11
12 #include "sd-daemon.h"
13 #include "sd-journal.h"
14 #include "sd-messages.h"
15 #include "sd-varlink.h"
16
17 #include "acl-util.h"
18 #include "alloc-util.h"
19 #include "audit-util.h"
20 #include "cgroup-util.h"
21 #include "daemon-util.h"
22 #include "dirent-util.h"
23 #include "errno-util.h"
24 #include "event-util.h"
25 #include "fd-util.h"
26 #include "fdset.h"
27 #include "fileio.h"
28 #include "format-util.h"
29 #include "fs-util.h"
30 #include "hashmap.h"
31 #include "hostname-setup.h"
32 #include "initrd-util.h"
33 #include "iovec-util.h"
34 #include "journal-authenticate.h"
35 #include "journal-file-util.h"
36 #include "journal-internal.h"
37 #include "journal-vacuum.h"
38 #include "journald-audit.h"
39 #include "journald-config.h"
40 #include "journald-context.h"
41 #include "journald-kmsg.h"
42 #include "journald-manager.h"
43 #include "journald-native.h"
44 #include "journald-rate-limit.h"
45 #include "journald-socket.h"
46 #include "journald-stream.h"
47 #include "journald-sync.h"
48 #include "journald-syslog.h"
49 #include "journald-varlink.h"
50 #include "log.h"
51 #include "log-ratelimit.h"
52 #include "memory-util.h"
53 #include "mkdir.h"
54 #include "path-util.h"
55 #include "prioq.h"
56 #include "process-util.h"
57 #include "rm-rf.h"
58 #include "set.h"
59 #include "selinux-util.h"
60 #include "signal-util.h"
61 #include "socket-util.h"
62 #include "stdio-util.h"
63 #include "string-util.h"
64 #include "strv.h"
65 #include "syslog-util.h"
66 #include "time-util.h"
67 #include "uid-classification.h"
68 #include "user-util.h"
69
70 #define USER_JOURNALS_MAX 1024
71
72 #define DEFAULT_KMSG_OWN_INTERVAL (5 * USEC_PER_SEC)
73 #define DEFAULT_KMSG_OWN_BURST 50
74
75 #define RECHECK_SPACE_USEC (30*USEC_PER_SEC)
76
77 #define NOTIFY_SNDBUF_SIZE (8*1024*1024)
78
79 /* The period to insert between posting changes for coalescing */
80 #define POST_CHANGE_TIMER_INTERVAL_USEC (250*USEC_PER_MSEC)
81
82 #define DEFERRED_CLOSES_MAX (4096)
83
84 #define IDLE_TIMEOUT_USEC (30*USEC_PER_SEC)
85
86 #define FAILED_TO_WRITE_ENTRY_RATELIMIT ((const RateLimit) { .interval = 1 * USEC_PER_SEC, .burst = 1 })
87
88 static int manager_schedule_sync(Manager *m, int priority);
89 static int manager_refresh_idle_timer(Manager *m);
90
91 static int manager_determine_path_usage(
92 Manager *m,
93 const char *path,
94 uint64_t *ret_used,
95 uint64_t *ret_free) {
96
97 _cleanup_closedir_ DIR *d = NULL;
98 struct statvfs ss;
99
100 assert(m);
101 assert(path);
102 assert(ret_used);
103 assert(ret_free);
104
105 d = opendir(path);
106 if (!d)
107 return log_ratelimit_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR,
108 errno, JOURNAL_LOG_RATELIMIT, "Failed to open %s: %m", path);
109
110 if (fstatvfs(dirfd(d), &ss) < 0)
111 return log_ratelimit_error_errno(errno, JOURNAL_LOG_RATELIMIT,
112 "Failed to fstatvfs(%s): %m", path);
113
114 *ret_free = ss.f_bsize * ss.f_bavail;
115 *ret_used = 0;
116 FOREACH_DIRENT_ALL(de, d, break) {
117 struct stat st;
118
119 if (!endswith(de->d_name, ".journal") &&
120 !endswith(de->d_name, ".journal~"))
121 continue;
122
123 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
124 log_debug_errno(errno, "Failed to stat %s/%s, ignoring: %m", path, de->d_name);
125 continue;
126 }
127
128 if (!S_ISREG(st.st_mode))
129 continue;
130
131 *ret_used += (uint64_t) st.st_blocks * 512UL;
132 }
133
134 return 0;
135 }
136
137 static void cache_space_invalidate(JournalStorageSpace *space) {
138 assert(space);
139
140 zero(*space);
141 }
142
143 static int cache_space_refresh(Manager *m, JournalStorage *storage) {
144 JournalStorageSpace *space;
145 JournalMetrics *metrics;
146 uint64_t vfs_used, vfs_avail, avail;
147 usec_t ts;
148 int r;
149
150 assert(m);
151 assert(storage);
152
153 metrics = &storage->metrics;
154 space = &storage->space;
155
156 ts = now(CLOCK_MONOTONIC);
157
158 if (space->timestamp != 0 && usec_add(space->timestamp, RECHECK_SPACE_USEC) > ts)
159 return 0;
160
161 r = manager_determine_path_usage(m, storage->path, &vfs_used, &vfs_avail);
162 if (r < 0)
163 return r;
164
165 space->vfs_used = vfs_used;
166 space->vfs_available = vfs_avail;
167
168 avail = LESS_BY(vfs_avail, metrics->keep_free);
169
170 space->limit = CLAMP(vfs_used + avail, metrics->min_use, metrics->max_use);
171 space->available = LESS_BY(space->limit, vfs_used);
172 space->timestamp = ts;
173 return 1;
174 }
175
176 static void patch_min_use(JournalStorage *storage) {
177 assert(storage);
178
179 /* Let's bump the min_use limit to the current usage on disk. We do
180 * this when starting up and first opening the journal files. This way
181 * sudden spikes in disk usage will not cause journald to vacuum files
182 * without bounds. Note that this means that only a restart of journald
183 * will make it reset this value. */
184
185 storage->metrics.min_use = MAX(storage->metrics.min_use, storage->space.vfs_used);
186 }
187
188 static JournalStorage* manager_current_storage(Manager *m) {
189 assert(m);
190
191 return m->system_journal ? &m->system_storage : &m->runtime_storage;
192 }
193
194 static int manager_determine_space(Manager *m, uint64_t *available, uint64_t *limit) {
195 JournalStorage *js;
196 int r;
197
198 assert(m);
199
200 js = manager_current_storage(m);
201
202 r = cache_space_refresh(m, js);
203 if (r >= 0) {
204 if (available)
205 *available = js->space.available;
206 if (limit)
207 *limit = js->space.limit;
208 }
209 return r;
210 }
211
212 void manager_space_usage_message(Manager *m, JournalStorage *storage) {
213 assert(m);
214
215 if (!storage)
216 storage = manager_current_storage(m);
217
218 if (cache_space_refresh(m, storage) < 0)
219 return;
220
221 const JournalMetrics *metrics = &storage->metrics;
222
223 manager_driver_message(m, 0,
224 LOG_MESSAGE_ID(SD_MESSAGE_JOURNAL_USAGE_STR),
225 LOG_MESSAGE("%s (%s) is %s, max %s, %s free.",
226 storage->name, storage->path,
227 FORMAT_BYTES(storage->space.vfs_used),
228 FORMAT_BYTES(storage->space.limit),
229 FORMAT_BYTES(storage->space.available)),
230 LOG_ITEM("JOURNAL_NAME=%s", storage->name),
231 LOG_ITEM("JOURNAL_PATH=%s", storage->path),
232 LOG_ITEM("CURRENT_USE=%"PRIu64, storage->space.vfs_used),
233 LOG_ITEM("CURRENT_USE_PRETTY=%s", FORMAT_BYTES(storage->space.vfs_used)),
234 LOG_ITEM("MAX_USE=%"PRIu64, metrics->max_use),
235 LOG_ITEM("MAX_USE_PRETTY=%s", FORMAT_BYTES(metrics->max_use)),
236 LOG_ITEM("DISK_KEEP_FREE=%"PRIu64, metrics->keep_free),
237 LOG_ITEM("DISK_KEEP_FREE_PRETTY=%s", FORMAT_BYTES(metrics->keep_free)),
238 LOG_ITEM("DISK_AVAILABLE=%"PRIu64, storage->space.vfs_available),
239 LOG_ITEM("DISK_AVAILABLE_PRETTY=%s", FORMAT_BYTES(storage->space.vfs_available)),
240 LOG_ITEM("LIMIT=%"PRIu64, storage->space.limit),
241 LOG_ITEM("LIMIT_PRETTY=%s", FORMAT_BYTES(storage->space.limit)),
242 LOG_ITEM("AVAILABLE=%"PRIu64, storage->space.available),
243 LOG_ITEM("AVAILABLE_PRETTY=%s", FORMAT_BYTES(storage->space.available)));
244 }
245
246 static void manager_add_acls(JournalFile *f, uid_t uid) {
247 assert(f);
248
249 #if HAVE_ACL
250 int r;
251
252 if (uid_for_system_journal(uid))
253 return;
254
255 r = fd_add_uid_acl_permission(f->fd, uid, ACL_READ);
256 if (r < 0)
257 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
258 "Failed to set ACL on %s, ignoring: %m", f->path);
259 #endif
260 }
261
262 static JournalFileFlags manager_get_file_flags(Manager *m, bool seal) {
263 assert(m);
264
265 return (m->config.compress.enabled ? JOURNAL_COMPRESS : 0) |
266 (seal ? JOURNAL_SEAL : 0) |
267 JOURNAL_STRICT_ORDER;
268 }
269
270 static int manager_open_journal(
271 Manager *m,
272 bool reliably,
273 const char *fname,
274 int open_flags,
275 bool seal,
276 JournalMetrics *metrics,
277 JournalFile **ret) {
278
279 _cleanup_(journal_file_offline_closep) JournalFile *f = NULL;
280 JournalFileFlags file_flags;
281 int r;
282
283 assert(m);
284 assert(fname);
285 assert(ret);
286
287 file_flags = manager_get_file_flags(m, seal);
288
289 set_clear(m->deferred_closes);
290
291 if (reliably)
292 r = journal_file_open_reliably(
293 fname,
294 open_flags,
295 file_flags,
296 0640,
297 m->config.compress.threshold_bytes,
298 metrics,
299 m->mmap,
300 &f);
301 else
302 r = journal_file_open(
303 /* fd= */ -EBADF,
304 fname,
305 open_flags,
306 file_flags,
307 0640,
308 m->config.compress.threshold_bytes,
309 metrics,
310 m->mmap,
311 /* template= */ NULL,
312 &f);
313 if (r < 0)
314 return r;
315
316 r = journal_file_enable_post_change_timer(f, m->event, POST_CHANGE_TIMER_INTERVAL_USEC);
317 if (r < 0)
318 return r;
319
320 *ret = TAKE_PTR(f);
321 return r;
322 }
323
324 static bool manager_flushed_flag_is_set(Manager *m) {
325 const char *fn;
326
327 assert(m);
328
329 /* We don't support the "flushing" concept for namespace instances, we assume them to always have
330 * access to /var */
331 if (m->namespace)
332 return true;
333
334 fn = strjoina(m->runtime_directory, "/flushed");
335 return access(fn, F_OK) >= 0;
336 }
337
338 static void manager_drop_flushed_flag(Manager *m) {
339 const char *fn;
340
341 assert(m);
342
343 if (m->namespace)
344 return;
345
346 fn = strjoina(m->runtime_directory, "/flushed");
347 if (unlink(fn) < 0 && errno != ENOENT)
348 log_ratelimit_warning_errno(errno, JOURNAL_LOG_RATELIMIT,
349 "Failed to unlink %s, ignoring: %m", fn);
350 }
351
352 static int manager_system_journal_open(
353 Manager *m,
354 bool flush_requested,
355 bool relinquish_requested) {
356
357 const char *fn;
358 int r = 0;
359
360 if (!m->system_journal &&
361 IN_SET(m->config.storage, STORAGE_PERSISTENT, STORAGE_AUTO) &&
362 (flush_requested || manager_flushed_flag_is_set(m)) &&
363 !relinquish_requested) {
364
365 /* If in auto mode: first try to create the machine path, but not the prefix.
366 *
367 * If in persistent mode: create /var/log/journal and the machine path */
368
369 if (m->config.storage == STORAGE_PERSISTENT)
370 (void) mkdir_parents(m->system_storage.path, 0755);
371
372 (void) mkdir(m->system_storage.path, 0755);
373
374 fn = strjoina(m->system_storage.path, "/system.journal");
375 r = manager_open_journal(
376 m,
377 /* reliably= */ true,
378 fn,
379 O_RDWR|O_CREAT,
380 m->config.seal,
381 &m->system_storage.metrics,
382 &m->system_journal);
383 if (r >= 0) {
384 manager_add_acls(m->system_journal, 0);
385 (void) cache_space_refresh(m, &m->system_storage);
386 patch_min_use(&m->system_storage);
387 } else {
388 if (!IN_SET(r, -ENOENT, -EROFS))
389 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
390 "Failed to open system journal: %m");
391
392 r = 0;
393 }
394
395 /* If the runtime journal is open, and we're post-flush, we're recovering from a failed
396 * system journal rotate (ENOSPC) for which the runtime journal was reopened.
397 *
398 * Perform an implicit flush to var, leaving the runtime journal closed, now that the system
399 * journal is back.
400 */
401 if (!flush_requested)
402 (void) manager_flush_to_var(m, true);
403 }
404
405 if (!m->runtime_journal &&
406 (m->config.storage != STORAGE_NONE)) {
407
408 fn = strjoina(m->runtime_storage.path, "/system.journal");
409
410 if (!m->system_journal || relinquish_requested) {
411
412 /* OK, we really need the runtime journal, so create it if necessary. */
413
414 (void) mkdir_parents(m->runtime_storage.path, 0755);
415 (void) mkdir(m->runtime_storage.path, 0750);
416
417 r = manager_open_journal(
418 m,
419 /* reliably= */ true,
420 fn,
421 O_RDWR|O_CREAT,
422 /* seal= */ false,
423 &m->runtime_storage.metrics,
424 &m->runtime_journal);
425 if (r < 0)
426 return log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
427 "Failed to open runtime journal: %m");
428
429 } else if (!manager_flushed_flag_is_set(m)) {
430 /* Try to open the runtime journal, but only if it already exists, so that we can
431 * flush it into the system journal */
432
433 r = manager_open_journal(
434 m,
435 /* reliably= */ false,
436 fn,
437 O_RDWR,
438 /* seal= */ false,
439 &m->runtime_storage.metrics,
440 &m->runtime_journal);
441 if (r < 0) {
442 if (r != -ENOENT)
443 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
444 "Failed to open runtime journal: %m");
445
446 r = 0;
447 }
448 }
449
450 if (m->runtime_journal) {
451 manager_add_acls(m->runtime_journal, 0);
452 (void) cache_space_refresh(m, &m->runtime_storage);
453 patch_min_use(&m->runtime_storage);
454 manager_drop_flushed_flag(m);
455 }
456 }
457
458 return r;
459 }
460
461 static int manager_find_user_journal(Manager *m, uid_t uid, JournalFile **ret) {
462 _cleanup_(journal_file_offline_closep) JournalFile *f = NULL;
463 _cleanup_free_ char *p = NULL;
464 int r;
465
466 assert(m);
467 assert(!uid_for_system_journal(uid));
468 assert(ret);
469
470 f = ordered_hashmap_get(m->user_journals, UID_TO_PTR(uid));
471 if (f)
472 goto found;
473
474 if (asprintf(&p, "%s/user-" UID_FMT ".journal", m->system_storage.path, uid) < 0)
475 return log_oom();
476
477 /* Too many open? Then let's close one (or more) */
478 while (ordered_hashmap_size(m->user_journals) >= USER_JOURNALS_MAX) {
479 JournalFile *first;
480
481 assert_se(first = ordered_hashmap_steal_first(m->user_journals));
482 (void) journal_file_offline_close(first);
483 }
484
485 r = manager_open_journal(
486 m,
487 /* reliably= */ true,
488 p,
489 O_RDWR|O_CREAT,
490 m->config.seal,
491 &m->system_storage.metrics,
492 &f);
493 if (r < 0)
494 return r;
495
496 r = ordered_hashmap_put(m->user_journals, UID_TO_PTR(uid), f);
497 if (r < 0)
498 return r;
499
500 manager_add_acls(f, uid);
501
502 found:
503 *ret = TAKE_PTR(f);
504 return 0;
505 }
506
507 static JournalFile* manager_find_journal(Manager *m, uid_t uid) {
508 int r;
509
510 assert(m);
511
512 /* A rotate that fails to create the new journal (ENOSPC) leaves the rotated journal as NULL. Unless
513 * we revisit opening, even after space is made available we'll continue to return NULL indefinitely.
514 *
515 * system_journal_open() is a noop if the journals are already open, so we can just call it here to
516 * recover from failed rotates (or anything else that's left the journals as NULL).
517 *
518 * Fixes https://github.com/systemd/systemd/issues/3968 */
519 (void) manager_system_journal_open(m, /* flush_requested= */ false, /* relinquish_requested= */ false);
520
521 /* We split up user logs only on /var, not on /run. If the runtime file is open, we write to it
522 * exclusively, in order to guarantee proper order as soon as we flush /run to /var and close the
523 * runtime file. */
524
525 if (m->runtime_journal)
526 return m->runtime_journal;
527
528 /* If we are not in persistent mode, then we need return NULL immediately rather than opening a
529 * persistent journal of any sort.
530 *
531 * Fixes https://github.com/systemd/systemd/issues/20390 */
532 if (!IN_SET(m->config.storage, STORAGE_AUTO, STORAGE_PERSISTENT))
533 return NULL;
534
535 if (!uid_for_system_journal(uid)) {
536 JournalFile *f = NULL;
537
538 r = manager_find_user_journal(m, uid, &f);
539 if (r >= 0)
540 return ASSERT_PTR(f);
541
542 log_warning_errno(r, "Failed to open user journal file, falling back to system journal: %m");
543 }
544
545 return m->system_journal;
546 }
547
548 static int manager_do_rotate(
549 Manager *m,
550 JournalFile **f,
551 const char* name,
552 bool seal,
553 uint32_t uid) {
554
555 int r;
556
557 assert(f);
558 assert(m);
559
560 if (!*f)
561 return -EINVAL;
562
563 log_debug("Rotating journal file %s.", (*f)->path);
564
565 r = journal_file_rotate(f, m->mmap, manager_get_file_flags(m, seal), m->config.compress.threshold_bytes, m->deferred_closes);
566 if (r < 0) {
567 if (*f)
568 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT,
569 "Failed to rotate %s: %m", (*f)->path);
570 else
571 return log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT,
572 "Failed to create new %s journal: %m", name);
573 }
574
575 manager_add_acls(*f, uid);
576 return r;
577 }
578
579 static void manager_process_deferred_closes(Manager *m) {
580 JournalFile *f;
581
582 /* Perform any deferred closes which aren't still offlining. */
583 SET_FOREACH(f, m->deferred_closes) {
584 if (journal_file_is_offlining(f))
585 continue;
586
587 (void) set_remove(m->deferred_closes, f);
588 (void) journal_file_offline_close(f);
589 }
590 }
591
592 static void manager_vacuum_deferred_closes(Manager *m) {
593 assert(m);
594
595 /* Make some room in the deferred closes list, so that it doesn't grow without bounds */
596 if (set_size(m->deferred_closes) < DEFERRED_CLOSES_MAX)
597 return;
598
599 /* Let's first remove all journal files that might already have completed closing */
600 manager_process_deferred_closes(m);
601
602 /* And now, let's close some more until we reach the limit again. */
603 while (set_size(m->deferred_closes) >= DEFERRED_CLOSES_MAX) {
604 JournalFile *f;
605
606 assert_se(f = set_steal_first(m->deferred_closes));
607 journal_file_offline_close(f);
608 }
609 }
610
611 static int manager_archive_offline_user_journals(Manager *m) {
612 _cleanup_closedir_ DIR *d = NULL;
613 int r;
614
615 assert(m);
616
617 d = opendir(m->system_storage.path);
618 if (!d) {
619 if (errno == ENOENT)
620 return 0;
621
622 return log_ratelimit_error_errno(errno, JOURNAL_LOG_RATELIMIT,
623 "Failed to open %s: %m", m->system_storage.path);
624 }
625
626 for (;;) {
627 _cleanup_free_ char *full = NULL;
628 _cleanup_close_ int fd = -EBADF;
629 struct dirent *de;
630 JournalFile *f;
631 uid_t uid;
632
633 errno = 0;
634 de = readdir_no_dot(d);
635 if (!de) {
636 if (errno != 0)
637 log_ratelimit_warning_errno(errno, JOURNAL_LOG_RATELIMIT,
638 "Failed to enumerate %s, ignoring: %m",
639 m->system_storage.path);
640 break;
641 }
642
643 r = journal_file_parse_uid_from_filename(de->d_name, &uid);
644 if (r < 0) {
645 /* Don't warn if the file is not an online or offline user journal. */
646 if (r != -EREMOTE)
647 log_warning_errno(r, "Failed to parse UID from file name '%s', ignoring: %m", de->d_name);
648 continue;
649 }
650
651 /* Already rotated in the above loop? i.e. is it an open user journal? */
652 if (ordered_hashmap_contains(m->user_journals, UID_TO_PTR(uid)))
653 continue;
654
655 full = path_join(m->system_storage.path, de->d_name);
656 if (!full)
657 return log_oom();
658
659 fd = openat(dirfd(d), de->d_name, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK);
660 if (fd < 0) {
661 log_ratelimit_full_errno(IN_SET(errno, ELOOP, ENOENT) ? LOG_DEBUG : LOG_WARNING,
662 errno, JOURNAL_LOG_RATELIMIT,
663 "Failed to open journal file '%s' for rotation: %m", full);
664 continue;
665 }
666
667 /* Make some room in the set of deferred close()s */
668 manager_vacuum_deferred_closes(m);
669
670 /* Open the file briefly, so that we can archive it */
671 r = journal_file_open(
672 fd,
673 full,
674 O_RDWR,
675 manager_get_file_flags(m, m->config.seal) & ~JOURNAL_STRICT_ORDER, /* strict order does not matter here */
676 0640,
677 m->config.compress.threshold_bytes,
678 &m->system_storage.metrics,
679 m->mmap,
680 /* template= */ NULL,
681 &f);
682 if (r < 0) {
683 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
684 "Failed to read journal file %s for rotation, trying to move it out of the way: %m",
685 full);
686
687 r = journal_file_dispose(dirfd(d), de->d_name);
688 if (r < 0)
689 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
690 "Failed to move %s out of the way, ignoring: %m",
691 full);
692 else
693 log_debug("Successfully moved %s out of the way.", full);
694
695 continue;
696 }
697
698 TAKE_FD(fd); /* Donated to journal_file_open() */
699
700 journal_file_write_final_tag(f);
701 r = journal_file_archive(f, NULL);
702 if (r < 0)
703 log_debug_errno(r, "Failed to archive journal file '%s', ignoring: %m", full);
704
705 journal_file_initiate_close(TAKE_PTR(f), m->deferred_closes);
706 }
707
708 return 0;
709 }
710
711 void manager_rotate(Manager *m) {
712 JournalFile *f;
713 void *k;
714 int r;
715
716 log_debug("Rotating...");
717
718 /* First, rotate the system journal (either in its runtime flavour or in its runtime flavour) */
719 (void) manager_do_rotate(m, &m->runtime_journal, "runtime", /* seal= */ false, /* uid= */ 0);
720 (void) manager_do_rotate(m, &m->system_journal, "system", m->config.seal, /* uid= */ 0);
721
722 /* Then, rotate all user journals we have open (keeping them open) */
723 ORDERED_HASHMAP_FOREACH_KEY(f, k, m->user_journals) {
724 r = manager_do_rotate(m, &f, "user", m->config.seal, PTR_TO_UID(k));
725 if (r >= 0)
726 ordered_hashmap_replace(m->user_journals, k, f);
727 else if (!f)
728 /* Old file has been closed and deallocated */
729 ordered_hashmap_remove(m->user_journals, k);
730 }
731
732 /* Finally, also rotate all user journals we currently do not have open. (But do so only if we
733 * actually have access to /var, i.e. are not in the log-to-runtime-journal mode). */
734 if (!m->runtime_journal)
735 (void) manager_archive_offline_user_journals(m);
736
737 manager_process_deferred_closes(m);
738 }
739
740 static void manager_rotate_journal(Manager *m, JournalFile *f, uid_t uid) {
741 int r;
742
743 assert(m);
744 assert(f);
745
746 /* This is similar to manager_rotate(), but rotates only specified journal file.
747 *
748 * 💣💣💣 This invalidate 'f', and the caller cannot reuse the passed JournalFile object. 💣💣💣 */
749
750 if (f == m->system_journal)
751 (void) manager_do_rotate(m, &m->system_journal, "system", m->config.seal, /* uid= */ 0);
752 else if (f == m->runtime_journal)
753 (void) manager_do_rotate(m, &m->runtime_journal, "runtime", /* seal= */ false, /* uid= */ 0);
754 else {
755 assert(ordered_hashmap_get(m->user_journals, UID_TO_PTR(uid)) == f);
756 r = manager_do_rotate(m, &f, "user", m->config.seal, uid);
757 if (r >= 0)
758 ordered_hashmap_replace(m->user_journals, UID_TO_PTR(uid), f);
759 else if (!f)
760 /* Old file has been closed and deallocated */
761 ordered_hashmap_remove(m->user_journals, UID_TO_PTR(uid));
762 }
763
764 manager_process_deferred_closes(m);
765 }
766
767 static void manager_sync(Manager *m, bool wait) {
768 JournalFile *f;
769 int r;
770
771 if (m->system_journal) {
772 r = journal_file_set_offline(m->system_journal, wait);
773 if (r < 0)
774 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
775 "Failed to sync system journal, ignoring: %m");
776 }
777
778 ORDERED_HASHMAP_FOREACH(f, m->user_journals) {
779 r = journal_file_set_offline(f, wait);
780 if (r < 0)
781 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
782 "Failed to sync user journal, ignoring: %m");
783 }
784
785 r = sd_event_source_set_enabled(m->sync_event_source, SD_EVENT_OFF);
786 if (r < 0)
787 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
788 "Failed to disable sync timer source, ignoring: %m");
789
790 m->sync_scheduled = false;
791 }
792
793 static void manager_do_vacuum(Manager *m, JournalStorage *storage, bool verbose) {
794 int r;
795
796 assert(m);
797 assert(storage);
798
799 (void) cache_space_refresh(m, storage);
800
801 if (verbose)
802 manager_space_usage_message(m, storage);
803
804 r = journal_directory_vacuum(storage->path, storage->space.limit,
805 storage->metrics.n_max_files, m->config.max_retention_usec,
806 &m->oldest_file_usec, verbose);
807 if (r < 0 && r != -ENOENT)
808 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
809 "Failed to vacuum %s, ignoring: %m", storage->path);
810
811 cache_space_invalidate(&storage->space);
812 }
813
814 void manager_vacuum(Manager *m, bool verbose) {
815 assert(m);
816
817 log_debug("Vacuuming...");
818
819 m->oldest_file_usec = 0;
820
821 if (m->system_journal)
822 manager_do_vacuum(m, &m->system_storage, verbose);
823 if (m->runtime_journal)
824 manager_do_vacuum(m, &m->runtime_storage, verbose);
825 }
826
827 static void manager_cache_machine_id(Manager *m) {
828 sd_id128_t id;
829 int r;
830
831 assert(m);
832
833 r = sd_id128_get_machine(&id);
834 if (r < 0)
835 return;
836
837 sd_id128_to_string(id, stpcpy(m->machine_id_field, "_MACHINE_ID="));
838 }
839
840 static void manager_cache_boot_id(Manager *m) {
841 sd_id128_t id;
842 int r;
843
844 assert(m);
845
846 r = sd_id128_get_boot(&id);
847 if (r < 0)
848 return;
849
850 sd_id128_to_string(id, stpcpy(m->boot_id_field, "_BOOT_ID="));
851 }
852
853 static void manager_cache_hostname(Manager *m) {
854 _cleanup_free_ char *t = NULL;
855 char *x;
856
857 assert(m);
858
859 t = gethostname_malloc();
860 if (!t)
861 return;
862
863 x = strjoin("_HOSTNAME=", t);
864 if (!x)
865 return;
866
867 free_and_replace(m->hostname_field, x);
868 }
869
870 static bool shall_try_append_again(JournalFile *f, int r) {
871 switch (r) {
872
873 case -E2BIG: /* Hit configured limit */
874 case -EFBIG: /* Hit fs limit */
875 case -EDQUOT: /* Quota limit hit */
876 case -ENOSPC: /* Disk full */
877 log_debug_errno(r, "%s: Allocation limit reached, rotating.", f->path);
878 return true;
879
880 case -EROFS: /* Read-only file system */
881 /* When appending an entry fails if shall_try_append_again returns true, the journal is
882 * rotated. If the FS is read-only, rotation will fail and m->system_journal will be set to
883 * NULL. After that, when find_journal will try to open the journal since m->system_journal
884 * will be NULL, it will open the runtime journal. */
885 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Read-only file system, rotating.", f->path);
886 return true;
887
888 case -EIO: /* I/O error of some kind (mmap) */
889 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT, "%s: IO error, rotating.", f->path);
890 return true;
891
892 case -EHOSTDOWN: /* Other machine */
893 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file from other machine, rotating.", f->path);
894 return true;
895
896 case -EBUSY: /* Unclean shutdown */
897 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Unclean shutdown, rotating.", f->path);
898 return true;
899
900 case -EPROTONOSUPPORT: /* Unsupported feature */
901 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Unsupported feature, rotating.", f->path);
902 return true;
903
904 case -EBADMSG: /* Corrupted */
905 case -ENODATA: /* Truncated */
906 case -ESHUTDOWN: /* Already archived */
907 case -EADDRNOTAVAIL: /* Referenced object offset out of bounds */
908 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file corrupted, rotating.", f->path);
909 return true;
910
911 case -EIDRM: /* Journal file has been deleted */
912 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file has been deleted, rotating.", f->path);
913 return true;
914
915 case -EREMCHG: /* Wallclock time (CLOCK_REALTIME) jumped backwards relative to last journal entry */
916 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Realtime clock jumped backwards relative to last journal entry, rotating.", f->path);
917 return true;
918
919 case -ENOTNAM: /* Monotonic time (CLOCK_MONOTONIC) jumped backwards relative to last journal entry with the same boot ID */
920 log_ratelimit_info_errno(
921 r,
922 JOURNAL_LOG_RATELIMIT,
923 "%s: Monotonic clock jumped backwards relative to last journal entry with the same boot ID, rotating.",
924 f->path);
925 return true;
926
927 case -EILSEQ: /* seqnum ID last used in the file doesn't match the one we'd passed when writing an entry to it */
928 log_ratelimit_info_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Journal file uses a different sequence number ID, rotating.", f->path);
929 return true;
930
931 case -EAFNOSUPPORT:
932 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Underlying file system does not support memory mapping or another required file system feature.", f->path);
933 return false;
934
935 default:
936 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "%s: Unexpected error while writing to journal file: %m", f->path);
937 return false;
938 }
939 }
940
941 static void manager_write_to_journal(
942 Manager *m,
943 uid_t uid,
944 const struct iovec *iovec,
945 size_t n,
946 const dual_timestamp *ts,
947 int priority) {
948
949 bool vacuumed = false;
950 JournalFile *f;
951 int r;
952
953 assert(m);
954 assert(iovec);
955 assert(n > 0);
956 assert(ts);
957
958 if (ts->realtime < m->last_realtime_clock) {
959 /* When the time jumps backwards, let's immediately rotate. Of course, this should not happen during
960 * regular operation. However, when it does happen, then we should make sure that we start fresh files
961 * to ensure that the entries in the journal files are strictly ordered by time, in order to ensure
962 * bisection works correctly. */
963
964 log_ratelimit_info(JOURNAL_LOG_RATELIMIT, "Time jumped backwards, rotating.");
965 manager_rotate(m);
966 manager_vacuum(m, /* verbose= */ false);
967 vacuumed = true;
968 }
969
970 f = manager_find_journal(m, uid);
971 if (!f)
972 return;
973
974 if (journal_file_rotate_suggested(f, m->config.max_file_usec, LOG_DEBUG)) {
975 if (vacuumed) {
976 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
977 "Suppressing rotation, as we already rotated immediately before write attempt. Giving up.");
978 return;
979 }
980
981 log_debug("%s: Journal header limits reached or header out-of-date, rotating.", f->path);
982
983 manager_rotate_journal(m, TAKE_PTR(f), uid);
984 manager_vacuum(m, /* verbose= */ false);
985 vacuumed = true;
986
987 f = manager_find_journal(m, uid);
988 if (!f)
989 return;
990 }
991
992 m->last_realtime_clock = ts->realtime;
993
994 r = journal_file_append_entry(
995 f,
996 ts,
997 /* boot_id= */ NULL,
998 iovec, n,
999 &m->seqnum->seqnum,
1000 &m->seqnum->id,
1001 /* ret_object= */ NULL,
1002 /* ret_offset= */ NULL);
1003 if (r >= 0) {
1004 manager_schedule_sync(m, priority);
1005 return;
1006 }
1007
1008 log_debug_errno(r, "Failed to write entry to %s (%zu items, %zu bytes): %m", f->path, n, iovec_total_size(iovec, n));
1009
1010 if (!shall_try_append_again(f, r))
1011 return;
1012 if (vacuumed) {
1013 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
1014 "Suppressing rotation, as we already rotated immediately before write attempt. Giving up.");
1015 return;
1016 }
1017
1018 manager_rotate_journal(m, TAKE_PTR(f), uid);
1019 manager_vacuum(m, /* verbose= */ false);
1020
1021 f = manager_find_journal(m, uid);
1022 if (!f)
1023 return;
1024
1025 log_debug_errno(r, "Retrying write.");
1026 r = journal_file_append_entry(
1027 f,
1028 ts,
1029 /* boot_id= */ NULL,
1030 iovec, n,
1031 &m->seqnum->seqnum,
1032 &m->seqnum->id,
1033 /* ret_object= */ NULL,
1034 /* ret_offset= */ NULL);
1035 if (r < 0)
1036 log_ratelimit_error_errno(r, FAILED_TO_WRITE_ENTRY_RATELIMIT,
1037 "Failed to write entry to %s (%zu items, %zu bytes) despite vacuuming, ignoring: %m",
1038 f->path, n, iovec_total_size(iovec, n));
1039 else
1040 manager_schedule_sync(m, priority);
1041 }
1042
1043 #define IOVEC_ADD_NUMERIC_FIELD(iovec, n, value, type, isset, format, field) \
1044 if (isset(value)) { \
1045 char *k; \
1046 k = newa(char, STRLEN(field "=") + DECIMAL_STR_MAX(type) + 1); \
1047 sprintf(k, field "=" format, value); \
1048 iovec[n++] = IOVEC_MAKE_STRING(k); \
1049 }
1050
1051 #define IOVEC_ADD_STRING_FIELD(iovec, n, value, field) \
1052 if (!isempty(value)) { \
1053 char *k; \
1054 k = strjoina(field "=", value); \
1055 iovec[n++] = IOVEC_MAKE_STRING(k); \
1056 }
1057
1058 #define IOVEC_ADD_ID128_FIELD(iovec, n, value, field) \
1059 if (!sd_id128_is_null(value)) { \
1060 char *k; \
1061 k = newa(char, STRLEN(field "=") + SD_ID128_STRING_MAX); \
1062 sd_id128_to_string(value, stpcpy(k, field "=")); \
1063 iovec[n++] = IOVEC_MAKE_STRING(k); \
1064 }
1065
1066 static void manager_dispatch_message_real(
1067 Manager *m,
1068 struct iovec *iovec, size_t n, size_t mm,
1069 const ClientContext *c,
1070 const struct timeval *tv,
1071 int priority,
1072 pid_t object_pid) {
1073
1074 char source_time[STRLEN("_SOURCE_REALTIME_TIMESTAMP=") + DECIMAL_STR_MAX(usec_t)];
1075 _unused_ _cleanup_free_ char *cmdline1 = NULL, *cmdline2 = NULL;
1076 uid_t journal_uid;
1077 ClientContext *o;
1078
1079 assert(m);
1080 assert(iovec);
1081 assert(n > 0);
1082 assert(n +
1083 N_IOVEC_META_FIELDS +
1084 (pid_is_valid(object_pid) ? N_IOVEC_OBJECT_FIELDS : 0) +
1085 client_context_extra_fields_n_iovec(c) <= mm);
1086
1087 if (c) {
1088 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->pid, pid_t, pid_is_valid, PID_FMT, "_PID");
1089 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->uid, uid_t, uid_is_valid, UID_FMT, "_UID");
1090 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->gid, gid_t, gid_is_valid, GID_FMT, "_GID");
1091
1092 IOVEC_ADD_STRING_FIELD(iovec, n, c->comm, "_COMM"); /* At most TASK_COMM_LENGTH (16 bytes) */
1093 IOVEC_ADD_STRING_FIELD(iovec, n, c->exe, "_EXE"); /* A path, so at most PATH_MAX (4096 bytes) */
1094
1095 if (c->cmdline)
1096 /* At most _SC_ARG_MAX (2MB usually), which is too much to put on stack.
1097 * Let's use a heap allocation for this one. */
1098 cmdline1 = set_iovec_string_field(iovec, &n, "_CMDLINE=", c->cmdline);
1099
1100 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->capability_quintet.effective, uint64_t, capability_is_set, "%" PRIx64, "_CAP_EFFECTIVE");
1101 IOVEC_ADD_STRING_FIELD(iovec, n, c->label, "_SELINUX_CONTEXT");
1102 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "_AUDIT_SESSION");
1103 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->loginuid, uid_t, uid_is_valid, UID_FMT, "_AUDIT_LOGINUID");
1104
1105 IOVEC_ADD_STRING_FIELD(iovec, n, c->cgroup, "_SYSTEMD_CGROUP"); /* A path */
1106 IOVEC_ADD_STRING_FIELD(iovec, n, c->session, "_SYSTEMD_SESSION");
1107 IOVEC_ADD_NUMERIC_FIELD(iovec, n, c->owner_uid, uid_t, uid_is_valid, UID_FMT, "_SYSTEMD_OWNER_UID");
1108 IOVEC_ADD_STRING_FIELD(iovec, n, c->unit, "_SYSTEMD_UNIT"); /* Unit names are bounded by UNIT_NAME_MAX */
1109 IOVEC_ADD_STRING_FIELD(iovec, n, c->user_unit, "_SYSTEMD_USER_UNIT");
1110 IOVEC_ADD_STRING_FIELD(iovec, n, c->slice, "_SYSTEMD_SLICE");
1111 IOVEC_ADD_STRING_FIELD(iovec, n, c->user_slice, "_SYSTEMD_USER_SLICE");
1112
1113 IOVEC_ADD_ID128_FIELD(iovec, n, c->invocation_id, "_SYSTEMD_INVOCATION_ID");
1114
1115 if (c->extra_fields_n_iovec > 0) {
1116 memcpy(iovec + n, c->extra_fields_iovec, c->extra_fields_n_iovec * sizeof(struct iovec));
1117 n += c->extra_fields_n_iovec;
1118 }
1119 }
1120
1121 assert(n <= mm);
1122
1123 if (pid_is_valid(object_pid) && client_context_get(m, object_pid, /* ucred= */ NULL, /* label= */ NULL, /* unit_id= */ NULL, &o) >= 0) {
1124
1125 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->pid, pid_t, pid_is_valid, PID_FMT, "OBJECT_PID");
1126 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_UID");
1127 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->gid, gid_t, gid_is_valid, GID_FMT, "OBJECT_GID");
1128
1129 /* See above for size limits, only ->cmdline may be large, so use a heap allocation for it. */
1130 IOVEC_ADD_STRING_FIELD(iovec, n, o->comm, "OBJECT_COMM");
1131 IOVEC_ADD_STRING_FIELD(iovec, n, o->exe, "OBJECT_EXE");
1132 if (o->cmdline)
1133 cmdline2 = set_iovec_string_field(iovec, &n, "OBJECT_CMDLINE=", o->cmdline);
1134
1135 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->capability_quintet.effective, uint64_t, capability_is_set, "%" PRIx64, "OBJECT_CAP_EFFECTIVE");
1136 IOVEC_ADD_STRING_FIELD(iovec, n, o->label, "OBJECT_SELINUX_CONTEXT");
1137 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->auditid, uint32_t, audit_session_is_valid, "%" PRIu32, "OBJECT_AUDIT_SESSION");
1138 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->loginuid, uid_t, uid_is_valid, UID_FMT, "OBJECT_AUDIT_LOGINUID");
1139
1140 IOVEC_ADD_STRING_FIELD(iovec, n, o->cgroup, "OBJECT_SYSTEMD_CGROUP");
1141 IOVEC_ADD_STRING_FIELD(iovec, n, o->session, "OBJECT_SYSTEMD_SESSION");
1142 IOVEC_ADD_NUMERIC_FIELD(iovec, n, o->owner_uid, uid_t, uid_is_valid, UID_FMT, "OBJECT_SYSTEMD_OWNER_UID");
1143 IOVEC_ADD_STRING_FIELD(iovec, n, o->unit, "OBJECT_SYSTEMD_UNIT");
1144 IOVEC_ADD_STRING_FIELD(iovec, n, o->user_unit, "OBJECT_SYSTEMD_USER_UNIT");
1145 IOVEC_ADD_STRING_FIELD(iovec, n, o->slice, "OBJECT_SYSTEMD_SLICE");
1146 IOVEC_ADD_STRING_FIELD(iovec, n, o->user_slice, "OBJECT_SYSTEMD_USER_SLICE");
1147
1148 IOVEC_ADD_ID128_FIELD(iovec, n, o->invocation_id, "OBJECT_SYSTEMD_INVOCATION_ID");
1149 }
1150
1151 assert(n <= mm);
1152
1153 if (tv) {
1154 xsprintf(source_time, "_SOURCE_REALTIME_TIMESTAMP=" USEC_FMT, timeval_load(tv));
1155 iovec[n++] = IOVEC_MAKE_STRING(source_time);
1156 }
1157
1158 /* Note that strictly speaking storing the boot id here is
1159 * redundant since the entry includes this in-line
1160 * anyway. However, we need this indexed, too. */
1161 if (!isempty(m->boot_id_field))
1162 iovec[n++] = IOVEC_MAKE_STRING(m->boot_id_field);
1163
1164 if (!isempty(m->machine_id_field))
1165 iovec[n++] = IOVEC_MAKE_STRING(m->machine_id_field);
1166
1167 if (!isempty(m->hostname_field))
1168 iovec[n++] = IOVEC_MAKE_STRING(m->hostname_field);
1169
1170 if (!isempty(m->namespace_field))
1171 iovec[n++] = IOVEC_MAKE_STRING(m->namespace_field);
1172
1173 iovec[n++] = in_initrd() ? IOVEC_MAKE_STRING("_RUNTIME_SCOPE=initrd") : IOVEC_MAKE_STRING("_RUNTIME_SCOPE=system");
1174 assert(n <= mm);
1175
1176 if (m->config.split_mode == SPLIT_UID && c && uid_is_valid(c->uid))
1177 /* Split up strictly by (non-root) UID */
1178 journal_uid = c->uid;
1179 else if (m->config.split_mode == SPLIT_LOGIN && c && c->uid > 0 && uid_is_valid(c->owner_uid))
1180 /* Split up by login UIDs. We do this only if the
1181 * realuid is not root, in order not to accidentally
1182 * leak privileged information to the user that is
1183 * logged by a privileged process that is part of an
1184 * unprivileged session. */
1185 journal_uid = c->owner_uid;
1186 else
1187 journal_uid = 0;
1188
1189 /* Get the closest, linearized time we have for this log event from the event loop. (Note that we do
1190 * not use the source time, and not even the time the event was originally seen, but instead simply
1191 * the time we started processing it, as we want strictly linear ordering in what we write out.) */
1192 struct dual_timestamp ts;
1193 event_dual_timestamp_now(m->event, &ts);
1194
1195 (void) manager_forward_socket(m, iovec, n, &ts, priority);
1196
1197 manager_write_to_journal(m, journal_uid, iovec, n, &ts, priority);
1198 }
1199
1200 void manager_driver_message_internal(Manager *m, pid_t object_pid, const char *format, ...) {
1201 struct iovec *iovec;
1202 size_t n = 0, k, mm;
1203 va_list ap;
1204 int r;
1205
1206 assert(m);
1207 assert(format);
1208
1209 mm = N_IOVEC_META_FIELDS + 5 + N_IOVEC_PAYLOAD_FIELDS + client_context_extra_fields_n_iovec(m->my_context) + N_IOVEC_OBJECT_FIELDS;
1210 iovec = newa(struct iovec, mm);
1211
1212 assert_cc(3 == LOG_FAC(LOG_DAEMON));
1213 iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_FACILITY=3");
1214 iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_IDENTIFIER=systemd-journald");
1215
1216 iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=driver");
1217 assert_cc(6 == LOG_INFO);
1218 iovec[n++] = IOVEC_MAKE_STRING("PRIORITY=6");
1219
1220 k = n;
1221
1222 va_start(ap, format);
1223 DISABLE_WARNING_FORMAT_NONLITERAL;
1224 r = log_format_iovec(iovec, mm, &n, false, 0, format, ap);
1225 REENABLE_WARNING;
1226 /* Error handling below */
1227 va_end(ap);
1228
1229 if (r >= 0)
1230 manager_dispatch_message_real(m, iovec, n, mm, m->my_context, /* tv= */ NULL, LOG_INFO, object_pid);
1231
1232 while (k < n)
1233 free(iovec[k++].iov_base);
1234
1235 if (r < 0) {
1236 /* We failed to format the message. Emit a warning instead. */
1237 char buf[LINE_MAX];
1238
1239 errno = -r;
1240 xsprintf(buf, "MESSAGE=Entry printing failed: %m");
1241
1242 n = 3;
1243 iovec[n++] = IOVEC_MAKE_STRING("PRIORITY=4");
1244 iovec[n++] = IOVEC_MAKE_STRING(buf);
1245 manager_dispatch_message_real(m, iovec, n, mm, m->my_context, /* tv= */ NULL, LOG_INFO, object_pid);
1246 }
1247 }
1248
1249 void manager_dispatch_message(
1250 Manager *m,
1251 struct iovec *iovec, size_t n, size_t mm,
1252 ClientContext *c,
1253 const struct timeval *tv,
1254 int priority,
1255 pid_t object_pid) {
1256
1257 uint64_t available = 0;
1258 int rl;
1259
1260 assert(m);
1261 assert(iovec || n == 0);
1262
1263 if (n == 0)
1264 return;
1265
1266 if (LOG_PRI(priority) > m->config.max_level_store)
1267 return;
1268
1269 /* Stop early in case the information will not be stored
1270 * in a journal. */
1271 if (m->config.storage == STORAGE_NONE)
1272 return;
1273
1274 if (c && c->unit) {
1275 (void) manager_determine_space(m, &available, /* limit= */ NULL);
1276
1277 rl = journal_ratelimit_test(
1278 &m->ratelimit_groups_by_id,
1279 c->unit,
1280 c->log_ratelimit_interval,
1281 c->log_ratelimit_burst,
1282 LOG_PRI(priority),
1283 available);
1284 if (rl == 0)
1285 return;
1286
1287 /* Write a suppression message if we suppressed something */
1288 if (rl > 1)
1289 manager_driver_message(m, c->pid,
1290 LOG_MESSAGE_ID(SD_MESSAGE_JOURNAL_DROPPED_STR),
1291 LOG_MESSAGE("Suppressed %i messages from %s", rl - 1, c->unit),
1292 LOG_ITEM("N_DROPPED=%i", rl - 1));
1293 }
1294
1295 manager_dispatch_message_real(m, iovec, n, mm, c, tv, priority, object_pid);
1296 }
1297
1298 int manager_flush_to_var(Manager *m, bool require_flag_file) {
1299 sd_journal *j = NULL;
1300 const char *fn;
1301 unsigned n = 0;
1302 usec_t start;
1303 int r, k;
1304
1305 assert(m);
1306
1307 if (!IN_SET(m->config.storage, STORAGE_AUTO, STORAGE_PERSISTENT))
1308 return 0;
1309
1310 if (m->namespace) /* Flushing concept does not exist for namespace instances */
1311 return 0;
1312
1313 if (!m->runtime_journal) /* Nothing to flush? */
1314 return 0;
1315
1316 if (require_flag_file && !manager_flushed_flag_is_set(m))
1317 return 0;
1318
1319 (void) manager_system_journal_open(m, /* flush_requested= */ true, /* relinquish_requested= */ false);
1320
1321 if (!m->system_journal)
1322 return 0;
1323
1324 /* Offline and close the 'main' runtime journal file to allow the runtime journal to be opened with
1325 * the SD_JOURNAL_ASSUME_IMMUTABLE flag in the below. */
1326 m->runtime_journal = journal_file_offline_close(m->runtime_journal);
1327
1328 /* Reset current seqnum data to avoid unnecessary rotation when switching to system journal.
1329 * See issue #30092. */
1330 zero(*m->seqnum);
1331
1332 log_debug("Flushing to %s...", m->system_storage.path);
1333
1334 start = now(CLOCK_MONOTONIC);
1335
1336 r = sd_journal_open(&j, SD_JOURNAL_RUNTIME_ONLY | SD_JOURNAL_ASSUME_IMMUTABLE);
1337 if (r < 0) {
1338 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Failed to read runtime journal: %m");
1339 goto finish;
1340 }
1341
1342 sd_journal_set_data_threshold(j, 0);
1343
1344 SD_JOURNAL_FOREACH(j) {
1345 Object *o = NULL;
1346 JournalFile *f;
1347
1348 f = j->current_file;
1349 assert(f && f->current_offset > 0);
1350
1351 n++;
1352
1353 r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o);
1354 if (r < 0) {
1355 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Can't read entry: %m");
1356 goto finish;
1357 }
1358
1359 r = journal_file_copy_entry(
1360 f,
1361 m->system_journal,
1362 o,
1363 f->current_offset,
1364 &m->seqnum->seqnum,
1365 &m->seqnum->id);
1366 if (r >= 0)
1367 continue;
1368
1369 if (!shall_try_append_again(m->system_journal, r)) {
1370 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Can't write entry: %m");
1371 goto finish;
1372 }
1373
1374 log_ratelimit_info(JOURNAL_LOG_RATELIMIT, "Rotating system journal.");
1375
1376 manager_rotate_journal(m, m->system_journal, /* uid= */ 0);
1377 manager_vacuum(m, /* verbose= */ false);
1378
1379 if (!m->system_journal) {
1380 log_ratelimit_notice(JOURNAL_LOG_RATELIMIT,
1381 "Didn't flush runtime journal since rotation of system journal wasn't successful.");
1382 r = -EIO;
1383 goto finish;
1384 }
1385
1386 log_debug("Retrying write.");
1387 r = journal_file_copy_entry(
1388 f,
1389 m->system_journal,
1390 o,
1391 f->current_offset,
1392 &m->seqnum->seqnum,
1393 &m->seqnum->id);
1394 if (r < 0) {
1395 log_ratelimit_error_errno(r, JOURNAL_LOG_RATELIMIT, "Can't write entry: %m");
1396 goto finish;
1397 }
1398 }
1399
1400 r = 0;
1401
1402 finish:
1403 if (m->system_journal)
1404 journal_file_post_change(m->system_journal);
1405
1406 /* Save parent directories of runtime journals before closing runtime journals. */
1407 _cleanup_strv_free_ char **dirs = NULL;
1408 (void) journal_get_directories(j, &dirs);
1409
1410 /* First, close all runtime journals opened in the above. */
1411 sd_journal_close(j);
1412
1413 /* Remove the runtime directory if the all entries are successfully flushed to /var/. */
1414 if (r >= 0) {
1415 r = rm_rf(m->runtime_storage.path, REMOVE_ROOT);
1416 if (r < 0)
1417 log_debug_errno(r, "Failed to remove runtime journal directory %s, ignoring: %m", m->runtime_storage.path);
1418 else
1419 log_debug("Removed runtime journal directory %s.", m->runtime_storage.path);
1420
1421 /* The initrd may have a different machine ID from the host's one. Typically, that happens
1422 * when our tests running on qemu, as the host's initrd is picked as is without updating
1423 * the machine ID in the initrd with the one used in the image. Even in such the case, the
1424 * runtime journals in the subdirectory named with the initrd's machine ID are flushed to
1425 * the persistent journal. To make not the runtime journal flushed multiple times, let's
1426 * also remove the runtime directories. */
1427 STRV_FOREACH(p, dirs) {
1428 r = rm_rf(*p, REMOVE_ROOT);
1429 if (r < 0)
1430 log_debug_errno(r, "Failed to remove additional runtime journal directory %s, ignoring: %m", *p);
1431 else
1432 log_debug("Removed additional runtime journal directory %s.", *p);
1433 }
1434 }
1435
1436 manager_driver_message(m, 0,
1437 LOG_MESSAGE("Time spent on flushing to %s is %s for %u entries.",
1438 m->system_storage.path,
1439 FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0),
1440 n));
1441
1442 fn = strjoina(m->runtime_directory, "/flushed");
1443 k = touch(fn);
1444 if (k < 0)
1445 log_ratelimit_warning_errno(k, JOURNAL_LOG_RATELIMIT,
1446 "Failed to touch %s, ignoring: %m", fn);
1447
1448 manager_refresh_idle_timer(m);
1449 return r;
1450 }
1451
1452 int manager_relinquish_var(Manager *m) {
1453 assert(m);
1454
1455 if (m->config.storage == STORAGE_NONE)
1456 return 0;
1457
1458 if (m->namespace) /* Concept does not exist for namespaced instances */
1459 return -EOPNOTSUPP;
1460
1461 if (m->runtime_journal && !m->system_journal)
1462 return 0;
1463
1464 log_debug("Relinquishing %s...", m->system_storage.path);
1465
1466 (void) manager_system_journal_open(m, /* flush_requested= */ false, /* relinquish_requested= */ true);
1467
1468 m->system_journal = journal_file_offline_close(m->system_journal);
1469 ordered_hashmap_clear(m->user_journals);
1470 set_clear(m->deferred_closes);
1471
1472 manager_refresh_idle_timer(m);
1473 return 0;
1474 }
1475
1476 int manager_process_datagram(
1477 sd_event_source *es,
1478 int fd,
1479 uint32_t revents,
1480 void *userdata) {
1481
1482 size_t mm;
1483 Manager *m = ASSERT_PTR(userdata);
1484 struct ucred *ucred = NULL;
1485 struct timeval tv_buf, *tv = NULL;
1486 struct cmsghdr *cmsg;
1487 _cleanup_free_ char *label = NULL;
1488 struct iovec iovec;
1489 ssize_t n;
1490 int *fds = NULL, v = 0;
1491 size_t n_fds = 0;
1492
1493 /* We use NAME_MAX space for the SELinux label here. The kernel currently enforces no limit, but
1494 * according to suggestions from the SELinux people this will change and it will probably be
1495 * identical to NAME_MAX. For now we use that, but this should be updated one day when the final
1496 * limit is known.
1497 *
1498 * Here, we need to explicitly initialize the buffer with zero, as glibc has a bug in
1499 * __convert_scm_timestamps(), which assumes the buffer is initialized. See #20741.
1500 * The issue is fixed on glibc-2.35 (8fba672472ae0055387e9315fc2eddfa6775ca79). */
1501 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) +
1502 CMSG_SPACE_TIMEVAL +
1503 CMSG_SPACE(sizeof(int)) + /* fd */
1504 CMSG_SPACE(NAME_MAX) /* selinux label */) control = {};
1505
1506 union sockaddr_union sa = {};
1507
1508 struct msghdr msghdr = {
1509 .msg_iov = &iovec,
1510 .msg_iovlen = 1,
1511 .msg_control = &control,
1512 .msg_controllen = sizeof(control),
1513 .msg_name = &sa,
1514 .msg_namelen = sizeof(sa),
1515 };
1516
1517 assert(fd == m->native_fd || fd == m->syslog_fd || fd == m->audit_fd);
1518
1519 if (revents != EPOLLIN)
1520 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1521 "Got invalid event from epoll for datagram fd: %" PRIx32,
1522 revents);
1523
1524 /* Try to get the right size, if we can. (Not all sockets support SIOCINQ, hence we just try, but don't rely on
1525 * it.) */
1526 (void) ioctl(fd, SIOCINQ, &v);
1527
1528 /* Fix it up, if it is too small. We use the same fixed value as auditd here. Awful! */
1529 mm = PAGE_ALIGN(MAX3((size_t) v + 1,
1530 (size_t) LINE_MAX,
1531 ALIGN(sizeof(struct nlmsghdr)) + ALIGN((size_t) MAX_AUDIT_MESSAGE_LENGTH)) + 1);
1532
1533 if (!GREEDY_REALLOC(m->buffer, mm))
1534 return log_oom();
1535
1536 iovec = IOVEC_MAKE(m->buffer, MALLOC_ELEMENTSOF(m->buffer) - 1); /* Leave room for trailing NUL we add later */
1537
1538 n = recvmsg_safe(fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
1539 if (ERRNO_IS_NEG_TRANSIENT(n))
1540 return 0;
1541 if (n == -ECHRNG) {
1542 log_ratelimit_warning_errno(n, JOURNAL_LOG_RATELIMIT,
1543 "Got message with truncated control data (too many fds sent?), ignoring.");
1544 return 0;
1545 }
1546 if (n == -EXFULL) {
1547 log_ratelimit_warning_errno(n, JOURNAL_LOG_RATELIMIT, "Got message with truncated payload data, ignoring.");
1548 return 0;
1549 }
1550 if (n < 0)
1551 return log_ratelimit_error_errno(n, JOURNAL_LOG_RATELIMIT, "Failed to receive message: %m");
1552
1553 CMSG_FOREACH(cmsg, &msghdr) {
1554 if (cmsg->cmsg_level != SOL_SOCKET)
1555 continue;
1556
1557 if (cmsg->cmsg_type == SCM_CREDENTIALS &&
1558 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
1559 assert(!ucred);
1560 ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
1561 } else if (cmsg->cmsg_type == SCM_SECURITY && mac_selinux_use()) {
1562 assert(!label);
1563 /* Here, we ignore any errors including OOM, as the field is optional. */
1564 (void) make_cstring(CMSG_TYPED_DATA(cmsg, char), cmsg->cmsg_len - CMSG_LEN(0),
1565 MAKE_CSTRING_ALLOW_TRAILING_NUL, &label);
1566 } else if (cmsg->cmsg_type == SCM_TIMESTAMP &&
1567 cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval))) {
1568 assert(!tv);
1569 tv = memcpy(&tv_buf, CMSG_DATA(cmsg), sizeof(struct timeval));
1570 } else if (cmsg->cmsg_type == SCM_RIGHTS) {
1571 assert(!fds);
1572 fds = CMSG_TYPED_DATA(cmsg, int);
1573 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1574 }
1575 }
1576
1577 /* And a trailing NUL, just in case */
1578 m->buffer[n] = 0;
1579
1580 if (fd == m->syslog_fd) {
1581 if (n > 0 && n_fds == 0)
1582 manager_process_syslog_message(m, m->buffer, n, ucred, tv, label);
1583 else if (n_fds > 0)
1584 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
1585 "Got file descriptors via syslog socket. Ignoring.");
1586
1587 if (tv)
1588 m->syslog_timestamp = timeval_load(tv);
1589
1590 } else if (fd == m->native_fd) {
1591 if (n > 0 && n_fds == 0)
1592 manager_process_native_message(m, m->buffer, n, ucred, tv, label);
1593 else if (n == 0 && n_fds == 1)
1594 (void) manager_process_native_file(m, fds[0], ucred, tv, label);
1595 else if (n_fds > 0)
1596 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
1597 "Got too many file descriptors via native socket. Ignoring.");
1598
1599 if (tv)
1600 m->native_timestamp = timeval_load(tv);
1601
1602 } else {
1603 assert(fd == m->audit_fd);
1604
1605 if (n > 0 && n_fds == 0)
1606 manager_process_audit_message(m, m->buffer, n, ucred, &sa, msghdr.msg_namelen);
1607 else if (n_fds > 0)
1608 log_ratelimit_warning(JOURNAL_LOG_RATELIMIT,
1609 "Got file descriptors via audit socket. Ignoring.");
1610 }
1611
1612 close_many(fds, n_fds);
1613
1614 if (tv)
1615 sync_req_revalidate_by_timestamp(m);
1616
1617 manager_refresh_idle_timer(m);
1618 return 0;
1619 }
1620
1621 void manager_full_flush(Manager *m) {
1622 assert(m);
1623
1624 (void) manager_flush_to_var(m, false);
1625 manager_sync(m, /* wait= */ false);
1626 manager_vacuum(m, false);
1627
1628 manager_space_usage_message(m, NULL);
1629
1630 manager_refresh_idle_timer(m);
1631 }
1632
1633 static int dispatch_sigusr1(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1634 Manager *m = ASSERT_PTR(userdata);
1635 assert(si);
1636
1637 if (!si_code_from_process(si->ssi_code)) {
1638 log_warning("Received SIGUSR1 with unexpected .si_code %i, ignoring.", si->ssi_code);
1639 return 0;
1640 }
1641
1642 if (m->namespace) {
1643 log_warning("Received SIGUSR1 signal from PID %u, but flushing runtime journals not supported for namespaced instances, ignoring.", si->ssi_pid);
1644 return 0;
1645 }
1646
1647 log_info("Received SIGUSR1 signal from PID %u, as request to flush runtime journal.", si->ssi_pid);
1648 manager_full_flush(m);
1649
1650 return 0;
1651 }
1652
1653 void manager_full_rotate(Manager *m) {
1654 const char *fn;
1655 int r;
1656
1657 assert(m);
1658
1659 manager_rotate(m);
1660 manager_vacuum(m, true);
1661
1662 if (m->system_journal)
1663 patch_min_use(&m->system_storage);
1664 if (m->runtime_journal)
1665 patch_min_use(&m->runtime_storage);
1666
1667 /* Let clients know when the most recent rotation happened. */
1668 fn = strjoina(m->runtime_directory, "/rotated");
1669 r = write_timestamp_file_atomic(fn, now(CLOCK_MONOTONIC));
1670 if (r < 0)
1671 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
1672 "Failed to write %s, ignoring: %m", fn);
1673 }
1674
1675 static int dispatch_sigusr2(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1676 Manager *m = ASSERT_PTR(userdata);
1677 assert(si);
1678
1679 if (!si_code_from_process(si->ssi_code)) {
1680 log_warning("Received SIGUSR2 with unexpected .si_code %i, ignoring.", si->ssi_code);
1681 return 0;
1682 }
1683
1684 log_info("Received SIGUSR2 signal from PID %u, as request to rotate journal, rotating.", si->ssi_pid);
1685 manager_full_rotate(m);
1686
1687 return 0;
1688 }
1689
1690 static int dispatch_sigterm(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1691 _cleanup_(sd_event_source_disable_unrefp) sd_event_source *news = NULL;
1692 Manager *m = ASSERT_PTR(userdata);
1693 int r;
1694
1695 log_received_signal(LOG_INFO, si);
1696
1697 (void) sd_event_source_set_enabled(es, SD_EVENT_OFF); /* Make sure this handler is called at most once */
1698
1699 /* So on one hand we want to ensure that SIGTERMs are definitely handled in appropriate, bounded
1700 * time. On the other hand we want that everything pending is first comprehensively processed and
1701 * written to disk. These goals are incompatible, hence we try to find a middle ground: we'll process
1702 * SIGTERM with high priority, but from the handler (this one right here) we'll install two new event
1703 * sources: one low priority idle one that will issue the exit once everything else is processed (and
1704 * which is hopefully the regular, clean codepath); and one high priority timer that acts as safety
1705 * net: if our idle handler isn't run within 10s, we'll exit anyway.
1706 *
1707 * TLDR: we'll exit either when everything is processed, or after 10s max, depending on what happens
1708 * first.
1709 *
1710 * Note that exiting before the idle event is hit doesn't typically mean that we lose any data, as
1711 * messages will remain queued in the sockets they came in from, and thus can be processed when we
1712 * start up next – unless we are going down for the final system shutdown, in which case everything
1713 * is lost. */
1714
1715 r = sd_event_add_defer(m->event, &news, NULL, NULL); /* NULL handler means → exit when triggered */
1716 if (r < 0) {
1717 log_error_errno(r, "Failed to allocate exit idle event handler: %m");
1718 goto fail;
1719 }
1720
1721 (void) sd_event_source_set_description(news, "exit-idle");
1722
1723 /* Run everything relevant before this. */
1724 r = sd_event_source_set_priority(news, SD_EVENT_PRIORITY_NORMAL+20);
1725 if (r < 0) {
1726 log_error_errno(r, "Failed to adjust priority of exit idle event handler: %m");
1727 goto fail;
1728 }
1729
1730 /* Give up ownership, so that this event source is freed automatically when the event loop is freed. */
1731 r = sd_event_source_set_floating(news, true);
1732 if (r < 0) {
1733 log_error_errno(r, "Failed to make exit idle event handler floating: %m");
1734 goto fail;
1735 }
1736
1737 news = sd_event_source_unref(news);
1738
1739 r = sd_event_add_time_relative(m->event, &news, CLOCK_MONOTONIC, 10 * USEC_PER_SEC, 0, NULL, NULL);
1740 if (r < 0) {
1741 log_error_errno(r, "Failed to allocate exit timeout event handler: %m");
1742 goto fail;
1743 }
1744
1745 (void) sd_event_source_set_description(news, "exit-timeout");
1746
1747 r = sd_event_source_set_priority(news, SD_EVENT_PRIORITY_IMPORTANT-20); /* This is a safety net, with highest priority */
1748 if (r < 0) {
1749 log_error_errno(r, "Failed to adjust priority of exit timeout event handler: %m");
1750 goto fail;
1751 }
1752
1753 r = sd_event_source_set_floating(news, true);
1754 if (r < 0) {
1755 log_error_errno(r, "Failed to make exit timeout event handler floating: %m");
1756 goto fail;
1757 }
1758
1759 news = sd_event_source_unref(news);
1760
1761 log_debug("Exit event sources are now pending.");
1762 return 0;
1763
1764 fail:
1765 sd_event_exit(m->event, 0);
1766 return 0;
1767 }
1768
1769 void manager_full_sync(Manager *m, bool wait) {
1770 const char *fn;
1771 int r;
1772
1773 assert(m);
1774
1775 manager_sync(m, wait);
1776
1777 /* Let clients know when the most recent sync happened. */
1778 fn = strjoina(m->runtime_directory, "/synced");
1779 r = write_timestamp_file_atomic(fn, now(CLOCK_MONOTONIC));
1780 if (r < 0)
1781 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
1782 "Failed to write %s, ignoring: %m", fn);
1783 }
1784
1785 static int dispatch_sigrtmin1(sd_event_source *es, const struct signalfd_siginfo *si, void *userdata) {
1786 Manager *m = ASSERT_PTR(userdata);
1787 assert(si);
1788
1789 if (!si_code_from_process(si->ssi_code)) {
1790 log_warning("Received SIGRTMIN1 with unexpected .si_code %i, ignoring.", si->ssi_code);
1791 return 0;
1792 }
1793
1794 log_debug("Received SIGRTMIN1 signal from PID %u, as request to sync.", si->ssi_pid);
1795 manager_full_sync(m, /* wait= */ false);
1796
1797 return 0;
1798 }
1799
1800 static int manager_setup_signals(Manager *m) {
1801 int r;
1802
1803 assert(m);
1804
1805 r = sd_event_add_signal(m->event, &m->sigusr1_event_source, SIGUSR1|SD_EVENT_SIGNAL_PROCMASK, dispatch_sigusr1, m);
1806 if (r < 0)
1807 return r;
1808
1809 r = sd_event_add_signal(m->event, &m->sigusr2_event_source, SIGUSR2|SD_EVENT_SIGNAL_PROCMASK, dispatch_sigusr2, m);
1810 if (r < 0)
1811 return r;
1812
1813 r = sd_event_add_signal(m->event, &m->sigterm_event_source, SIGTERM|SD_EVENT_SIGNAL_PROCMASK, dispatch_sigterm, m);
1814 if (r < 0)
1815 return r;
1816
1817 /* Let's process SIGTERM early, so that we definitely react to it */
1818 r = sd_event_source_set_priority(m->sigterm_event_source, SD_EVENT_PRIORITY_IMPORTANT-10);
1819 if (r < 0)
1820 return r;
1821
1822 /* When journald is invoked on the terminal (when debugging), it's useful if C-c is handled
1823 * equivalent to SIGTERM. */
1824 r = sd_event_add_signal(m->event, &m->sigint_event_source, SIGINT|SD_EVENT_SIGNAL_PROCMASK, dispatch_sigterm, m);
1825 if (r < 0)
1826 return r;
1827
1828 r = sd_event_source_set_priority(m->sigint_event_source, SD_EVENT_PRIORITY_IMPORTANT-10);
1829 if (r < 0)
1830 return r;
1831
1832 /* SIGRTMIN+1 causes an immediate sync. We process this very late, so that everything else queued at
1833 * this point is really written to disk. Clients can watch /run/systemd/journal/synced with inotify
1834 * until its mtime changes to see when a sync happened. */
1835 r = sd_event_add_signal(m->event, &m->sigrtmin1_event_source, (SIGRTMIN+1)|SD_EVENT_SIGNAL_PROCMASK, dispatch_sigrtmin1, m);
1836 if (r < 0)
1837 return r;
1838
1839 r = sd_event_source_set_priority(m->sigrtmin1_event_source, SD_EVENT_PRIORITY_NORMAL+15);
1840 if (r < 0)
1841 return r;
1842
1843 r = sd_event_add_signal(m->event, /* ret= */ NULL, (SIGRTMIN+18)|SD_EVENT_SIGNAL_PROCMASK, sigrtmin18_handler, &m->sigrtmin18_info);
1844 if (r < 0)
1845 return r;
1846
1847 r = sd_event_add_signal(m->event, NULL, SIGHUP|SD_EVENT_SIGNAL_PROCMASK, manager_dispatch_reload_signal, m);
1848 if (r < 0)
1849 return r;
1850
1851 return 0;
1852 }
1853
1854 static int manager_dispatch_sync(sd_event_source *es, usec_t t, void *userdata) {
1855 Manager *m = ASSERT_PTR(userdata);
1856
1857 manager_sync(m, /* wait= */ false);
1858 return 0;
1859 }
1860
1861 static int manager_schedule_sync(Manager *m, int priority) {
1862 int r;
1863
1864 assert(m);
1865
1866 if (priority <= LOG_CRIT) {
1867 /* Immediately sync to disk when this is of priority CRIT, ALERT, EMERG */
1868 manager_sync(m, /* wait= */ false);
1869 return 0;
1870 }
1871
1872 if (!m->event || sd_event_get_state(m->event) == SD_EVENT_FINISHED) {
1873 /* Shutting down the server? Let's sync immediately. */
1874 manager_sync(m, /* wait= */ false);
1875 return 0;
1876 }
1877
1878 if (m->sync_scheduled)
1879 return 0;
1880
1881 if (m->config.sync_interval_usec > 0) {
1882
1883 if (!m->sync_event_source) {
1884 r = sd_event_add_time_relative(
1885 m->event,
1886 &m->sync_event_source,
1887 CLOCK_MONOTONIC,
1888 m->config.sync_interval_usec, 0,
1889 manager_dispatch_sync, m);
1890 if (r < 0)
1891 return r;
1892
1893 r = sd_event_source_set_priority(m->sync_event_source, SD_EVENT_PRIORITY_IMPORTANT);
1894 } else {
1895 r = sd_event_source_set_time_relative(m->sync_event_source, m->config.sync_interval_usec);
1896 if (r < 0)
1897 return r;
1898
1899 r = sd_event_source_set_enabled(m->sync_event_source, SD_EVENT_ONESHOT);
1900 }
1901 if (r < 0)
1902 return r;
1903
1904 m->sync_scheduled = true;
1905 }
1906
1907 return 0;
1908 }
1909
1910 static int dispatch_hostname_change(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
1911 Manager *m = ASSERT_PTR(userdata);
1912
1913 manager_cache_hostname(m);
1914 return 0;
1915 }
1916
1917 static int manager_open_hostname(Manager *m) {
1918 int r;
1919
1920 assert(m);
1921
1922 m->hostname_fd = open("/proc/sys/kernel/hostname",
1923 O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1924 if (m->hostname_fd < 0)
1925 return log_error_errno(errno, "Failed to open %s: %m", "/proc/sys/kernel/hostname");
1926
1927 r = sd_event_add_io(m->event, &m->hostname_event_source, m->hostname_fd, 0, dispatch_hostname_change, m);
1928 if (r < 0)
1929 return log_error_errno(r, "Failed to register hostname fd in event loop: %m");
1930
1931 r = sd_event_source_set_priority(m->hostname_event_source, SD_EVENT_PRIORITY_IMPORTANT-10);
1932 if (r < 0)
1933 return log_error_errno(r, "Failed to adjust priority of hostname event source: %m");
1934
1935 return 0;
1936 }
1937
1938 static int dispatch_notify_event(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
1939 Manager *m = ASSERT_PTR(userdata);
1940 int r;
1941
1942 assert(m->notify_event_source == es);
1943 assert(m->notify_fd == fd);
1944
1945 /* The $NOTIFY_SOCKET is writable again, now send exactly one
1946 * message on it. Either it's the watchdog event, the initial
1947 * READY=1 event or an stdout stream event. If there's nothing
1948 * to write anymore, turn our event source off. The next time
1949 * there's something to send it will be turned on again. */
1950
1951 if (!m->sent_notify_ready) {
1952 if (send(m->notify_fd, NOTIFY_READY_MESSAGE, strlen(NOTIFY_READY_MESSAGE), MSG_DONTWAIT) < 0) {
1953 if (errno == EAGAIN)
1954 return 0;
1955
1956 return log_error_errno(errno, "Failed to send READY=1 notification message: %m");
1957 }
1958
1959 m->sent_notify_ready = true;
1960 log_debug("Sent READY=1 notification.");
1961
1962 } else if (m->send_watchdog) {
1963 static const char p[] = "WATCHDOG=1";
1964
1965 if (send(m->notify_fd, p, strlen(p), MSG_DONTWAIT) < 0) {
1966 if (errno == EAGAIN)
1967 return 0;
1968
1969 return log_error_errno(errno, "Failed to send WATCHDOG=1 notification message: %m");
1970 }
1971
1972 m->send_watchdog = false;
1973 log_debug("Sent WATCHDOG=1 notification.");
1974
1975 } else if (m->stdout_streams_notify_queue)
1976 /* Dispatch one stream notification event */
1977 stdout_stream_send_notify(m->stdout_streams_notify_queue);
1978
1979 /* Leave us enabled if there's still more to do. */
1980 if (m->send_watchdog || m->stdout_streams_notify_queue)
1981 return 0;
1982
1983 /* There was nothing to do anymore, let's turn ourselves off. */
1984 r = sd_event_source_set_enabled(es, SD_EVENT_OFF);
1985 if (r < 0)
1986 return log_error_errno(r, "Failed to turn off notify event source: %m");
1987
1988 return 0;
1989 }
1990
1991 static int dispatch_watchdog(sd_event_source *es, uint64_t usec, void *userdata) {
1992 Manager *m = ASSERT_PTR(userdata);
1993 int r;
1994
1995 m->send_watchdog = true;
1996
1997 r = sd_event_source_set_enabled(m->notify_event_source, SD_EVENT_ON);
1998 if (r < 0)
1999 log_warning_errno(r, "Failed to turn on notify event source: %m");
2000
2001 r = sd_event_source_set_time(m->watchdog_event_source, usec + m->watchdog_usec / 2);
2002 if (r < 0)
2003 return log_error_errno(r, "Failed to restart watchdog event source: %m");
2004
2005 r = sd_event_source_set_enabled(m->watchdog_event_source, SD_EVENT_ON);
2006 if (r < 0)
2007 return log_error_errno(r, "Failed to enable watchdog event source: %m");
2008
2009 return 0;
2010 }
2011
2012 static int manager_connect_notify(Manager *m) {
2013 union sockaddr_union sa;
2014 socklen_t sa_len;
2015 const char *e;
2016 int r;
2017
2018 assert(m);
2019 assert(m->notify_fd < 0);
2020 assert(!m->notify_event_source);
2021
2022 /*
2023 * So here's the problem: we'd like to send notification messages to PID 1, but we cannot do that via
2024 * sd_notify(), since that's synchronous, and we might end up blocking on it. Specifically: given
2025 * that PID 1 might block on dbus-daemon during IPC, and dbus-daemon is logging to us, and might
2026 * hence block on us, we might end up in a deadlock if we block on sending PID 1 notification
2027 * messages — by generating a full blocking circle. To avoid this, let's create a non-blocking
2028 * socket, and connect it to the notification socket, and then wait for POLLOUT before we send
2029 * anything. This should efficiently avoid any deadlocks, as we'll never block on PID 1, hence PID 1
2030 * can safely block on dbus-daemon which can safely block on us again.
2031 *
2032 * Don't think that this issue is real? It is, see: https://github.com/systemd/systemd/issues/1505
2033 */
2034
2035 e = getenv("NOTIFY_SOCKET");
2036 if (!e)
2037 return 0;
2038
2039 r = sockaddr_un_set_path(&sa.un, e);
2040 if (r < 0)
2041 return log_error_errno(r, "NOTIFY_SOCKET set to invalid value '%s': %m", e);
2042 sa_len = r;
2043
2044 m->notify_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2045 if (m->notify_fd < 0)
2046 return log_error_errno(errno, "Failed to create notify socket: %m");
2047
2048 (void) fd_inc_sndbuf(m->notify_fd, NOTIFY_SNDBUF_SIZE);
2049
2050 r = connect(m->notify_fd, &sa.sa, sa_len);
2051 if (r < 0)
2052 return log_error_errno(errno, "Failed to connect to notify socket: %m");
2053
2054 r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLOUT, dispatch_notify_event, m);
2055 if (r < 0)
2056 return log_error_errno(r, "Failed to watch notification socket: %m");
2057
2058 if (sd_watchdog_enabled(false, &m->watchdog_usec) > 0) {
2059 m->send_watchdog = true;
2060
2061 r = sd_event_add_time_relative(m->event, &m->watchdog_event_source, CLOCK_MONOTONIC, m->watchdog_usec/2, m->watchdog_usec/4, dispatch_watchdog, m);
2062 if (r < 0)
2063 return log_error_errno(r, "Failed to add watchdog time event: %m");
2064 }
2065
2066 /* This should fire pretty soon, which we'll use to send the READY=1 event. */
2067
2068 return 0;
2069 }
2070
2071 int manager_map_seqnum_file(
2072 Manager *m,
2073 const char *fname,
2074 size_t size,
2075 void **ret) {
2076
2077 _cleanup_free_ char *fn = NULL;
2078 _cleanup_close_ int fd = -EBADF;
2079 uint64_t *p;
2080 int r;
2081
2082 assert(m);
2083 assert(fname);
2084 assert(size > 0);
2085 assert(ret);
2086
2087 fn = path_join(m->runtime_directory, fname);
2088 if (!fn)
2089 return -ENOMEM;
2090
2091 fd = open(fn, O_RDWR|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0644);
2092 if (fd < 0)
2093 return -errno;
2094
2095 r = posix_fallocate_loop(fd, 0, size);
2096 if (r < 0)
2097 return r;
2098
2099 p = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
2100 if (p == MAP_FAILED)
2101 return -errno;
2102
2103 *ret = p;
2104 return 0;
2105 }
2106
2107 void manager_unmap_seqnum_file(void *p, size_t size) {
2108 assert(size > 0);
2109
2110 if (!p)
2111 return;
2112
2113 assert_se(munmap(p, size) >= 0);
2114 }
2115
2116 int manager_unlink_seqnum_file(Manager *m, const char *fname) {
2117 assert(m);
2118 assert(fname);
2119
2120 _cleanup_free_ char *fn = path_join(m->runtime_directory, fname);
2121 if (!fn)
2122 return log_oom();
2123
2124 if (unlink(fn) < 0 && errno != ENOENT)
2125 return log_warning_errno(errno, "Failed to remove '%s': %m", fname);
2126
2127 return 0;
2128 }
2129
2130 static bool manager_is_idle(Manager *m) {
2131 assert(m);
2132
2133 /* The server for the main namespace is never idle */
2134 if (!m->namespace)
2135 return false;
2136
2137 /* If a retention maximum is set larger than the idle time we need to be running to enforce it, hence
2138 * turn off the idle logic. */
2139 if (m->config.max_retention_usec > IDLE_TIMEOUT_USEC)
2140 return false;
2141
2142 /* We aren't idle if we have a varlink client */
2143 if (sd_varlink_server_current_connections(m->varlink_server) > 0)
2144 return false;
2145
2146 /* If we have stdout streams we aren't idle */
2147 if (m->n_stdout_streams > 0)
2148 return false;
2149
2150 return true;
2151 }
2152
2153 static int manager_idle_handler(sd_event_source *source, uint64_t usec, void *userdata) {
2154 Manager *m = ASSERT_PTR(userdata);
2155
2156 assert(source);
2157
2158 log_debug("Manager is idle, exiting.");
2159 sd_event_exit(m->event, 0);
2160 return 0;
2161 }
2162
2163 int manager_start_or_stop_idle_timer(Manager *m) {
2164 _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
2165 int r;
2166
2167 assert(m);
2168
2169 if (sd_event_get_state(m->event) == SD_EVENT_FINISHED ||
2170 !manager_is_idle(m)) {
2171 m->idle_event_source = sd_event_source_disable_unref(m->idle_event_source);
2172 return 0;
2173 }
2174
2175 if (m->idle_event_source)
2176 return 1;
2177
2178 r = sd_event_add_time_relative(m->event, &source, CLOCK_MONOTONIC, IDLE_TIMEOUT_USEC, 0, manager_idle_handler, m);
2179 if (r < 0)
2180 return log_error_errno(r, "Failed to allocate idle timer: %m");
2181
2182 r = sd_event_source_set_priority(source, SD_EVENT_PRIORITY_IDLE);
2183 if (r < 0)
2184 return log_error_errno(r, "Failed to set idle timer priority: %m");
2185
2186 (void) sd_event_source_set_description(source, "idle-timer");
2187
2188 m->idle_event_source = TAKE_PTR(source);
2189 return 1;
2190 }
2191
2192 static int manager_refresh_idle_timer(Manager *m) {
2193 int r;
2194
2195 assert(m);
2196
2197 if (!m->idle_event_source)
2198 return 0;
2199
2200 r = sd_event_source_set_time_relative(m->idle_event_source, IDLE_TIMEOUT_USEC);
2201 if (r < 0)
2202 return log_error_errno(r, "Failed to refresh idle timer: %m");
2203
2204 return 1;
2205 }
2206
2207 int manager_set_namespace(Manager *m, const char *namespace) {
2208 assert(m);
2209
2210 if (!namespace)
2211 return 0;
2212
2213 if (!log_namespace_name_valid(namespace))
2214 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified namespace name not valid, refusing: %s", namespace);
2215
2216 m->namespace = strdup(namespace);
2217 if (!m->namespace)
2218 return log_oom();
2219
2220 m->namespace_field = strjoin("_NAMESPACE=", namespace);
2221 if (!m->namespace_field)
2222 return log_oom();
2223
2224 return 1;
2225 }
2226
2227 static int manager_memory_pressure(sd_event_source *es, void *userdata) {
2228 Manager *m = ASSERT_PTR(userdata);
2229
2230 log_info("Under memory pressure, flushing caches.");
2231
2232 /* Flushed the cached info we might have about client processes */
2233 client_context_flush_regular(m);
2234
2235 /* Let's also close all user files (but keep the system/runtime one open) */
2236 for (;;) {
2237 JournalFile *first = ordered_hashmap_steal_first(m->user_journals);
2238
2239 if (!first)
2240 break;
2241
2242 (void) journal_file_offline_close(first);
2243 }
2244
2245 sd_event_trim_memory();
2246
2247 return 0;
2248 }
2249
2250 static int manager_setup_memory_pressure(Manager *m) {
2251 int r;
2252
2253 assert(m);
2254
2255 r = sd_event_add_memory_pressure(m->event, NULL, manager_memory_pressure, m);
2256 if (r < 0)
2257 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r) || (r == -EHOSTDOWN) ? LOG_DEBUG : LOG_NOTICE, r,
2258 "Failed to install memory pressure event source, ignoring: %m");
2259
2260 return 0;
2261 }
2262
2263 void manager_reopen_journals(Manager *m, const JournalConfig *old) {
2264 assert(m);
2265
2266 if (m->config.storage == old->storage &&
2267 m->config.compress.enabled == old->compress.enabled &&
2268 m->config.compress.threshold_bytes == old->compress.threshold_bytes &&
2269 m->config.seal == old->seal &&
2270 m->config.sync_interval_usec == old->sync_interval_usec &&
2271 journal_metrics_equal(&m->config.system_storage_metrics, &old->system_storage_metrics) &&
2272 journal_metrics_equal(&m->config.runtime_storage_metrics, &old->runtime_storage_metrics))
2273 return; /* no-op */
2274
2275 /* Explicitly close the runtime journal to make it reopened later by manager_system_journal_open().
2276 * But only when volatile (or no) storage is requested. If auto or persistent storage is requested,
2277 * we may need to flush the runtime journal to the persistent storage, it will done through
2278 * manager_system_journal_open(). Hence, we should not touch the runtime journal here in that case. */
2279 if (IN_SET(m->config.storage, STORAGE_VOLATILE, STORAGE_NONE))
2280 m->runtime_journal = journal_file_offline_close(m->runtime_journal);
2281
2282 /* Close other journals unconditionally to make the new settings applied. */
2283 m->system_journal = journal_file_offline_close(m->system_journal);
2284 ordered_hashmap_clear(m->user_journals);
2285 set_clear(m->deferred_closes);
2286
2287 (void) manager_system_journal_open(m, /* flush_requested= */ false, /* relinquish_requested= */ false);
2288
2289 /* To make the storage related settings applied, vacuum the storage. */
2290 cache_space_invalidate(&m->system_storage.space);
2291 cache_space_invalidate(&m->runtime_storage.space);
2292 manager_vacuum(m, /* verbose= */ false);
2293 }
2294
2295 int manager_new(Manager **ret) {
2296 _cleanup_(manager_freep) Manager *m = NULL;
2297
2298 assert(ret);
2299
2300 m = new(Manager, 1);
2301 if (!m)
2302 return -ENOMEM;
2303
2304 *m = (Manager) {
2305 .syslog_fd = -EBADF,
2306 .native_fd = -EBADF,
2307 .stdout_fd = -EBADF,
2308 .dev_kmsg_fd = -EBADF,
2309 .audit_fd = -EBADF,
2310 .hostname_fd = -EBADF,
2311 .notify_fd = -EBADF,
2312 .forward_socket_fd = -EBADF,
2313
2314 .system_storage.name = "System Journal",
2315 .runtime_storage.name = "Runtime Journal",
2316
2317 .watchdog_usec = USEC_INFINITY,
2318
2319 .sync_scheduled = false,
2320
2321 .kmsg_own_ratelimit = {
2322 .interval = DEFAULT_KMSG_OWN_INTERVAL,
2323 .burst = DEFAULT_KMSG_OWN_BURST,
2324 },
2325
2326 .sigrtmin18_info.memory_pressure_handler = manager_memory_pressure,
2327 .sigrtmin18_info.memory_pressure_userdata = m,
2328 };
2329
2330 journal_config_set_defaults(&m->config_by_conf);
2331 journal_config_set_defaults(&m->config_by_cred);
2332 journal_config_set_defaults(&m->config_by_cmdline);
2333
2334 *ret = TAKE_PTR(m);
2335 return 0;
2336 }
2337
2338 int manager_init(Manager *m) {
2339 const char *native_socket, *syslog_socket, *stdout_socket, *varlink_socket, *e;
2340 _cleanup_fdset_free_ FDSet *fds = NULL;
2341 int n, r, varlink_fd = -EBADF;
2342 bool no_sockets;
2343
2344 assert(m);
2345
2346 e = getenv("RUNTIME_DIRECTORY");
2347 if (e)
2348 m->runtime_directory = strdup(e);
2349 else if (m->namespace)
2350 m->runtime_directory = strjoin("/run/systemd/journal.", m->namespace);
2351 else
2352 m->runtime_directory = strdup("/run/systemd/journal");
2353 if (!m->runtime_directory)
2354 return log_oom();
2355
2356 (void) mkdir_p(m->runtime_directory, 0755);
2357
2358 m->user_journals = ordered_hashmap_new(&journal_file_hash_ops_offline_close);
2359 if (!m->user_journals)
2360 return log_oom();
2361
2362 m->mmap = mmap_cache_new();
2363 if (!m->mmap)
2364 return log_oom();
2365
2366 m->deferred_closes = set_new(&journal_file_hash_ops_offline_close);
2367 if (!m->deferred_closes)
2368 return log_oom();
2369
2370 r = sd_event_default(&m->event);
2371 if (r < 0)
2372 return log_error_errno(r, "Failed to create event loop: %m");
2373
2374 n = sd_listen_fds(true);
2375 if (n < 0)
2376 return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
2377
2378 native_socket = strjoina(m->runtime_directory, "/socket");
2379 stdout_socket = strjoina(m->runtime_directory, "/stdout");
2380 syslog_socket = strjoina(m->runtime_directory, "/dev-log");
2381 varlink_socket = strjoina(m->runtime_directory, "/io.systemd.journal");
2382
2383 for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++)
2384
2385 if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, native_socket, 0) > 0) {
2386
2387 if (m->native_fd >= 0)
2388 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2389 "Too many native sockets passed.");
2390
2391 m->native_fd = fd;
2392
2393 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, stdout_socket, 0) > 0) {
2394
2395 if (m->stdout_fd >= 0)
2396 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2397 "Too many stdout sockets passed.");
2398
2399 m->stdout_fd = fd;
2400
2401 } else if (sd_is_socket_unix(fd, SOCK_DGRAM, -1, syslog_socket, 0) > 0) {
2402
2403 if (m->syslog_fd >= 0)
2404 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2405 "Too many /dev/log sockets passed.");
2406
2407 m->syslog_fd = fd;
2408
2409 } else if (sd_is_socket_unix(fd, SOCK_STREAM, 1, varlink_socket, 0) > 0) {
2410
2411 if (varlink_fd >= 0)
2412 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2413 "Too many varlink sockets passed.");
2414
2415 varlink_fd = fd;
2416 } else if (sd_is_socket(fd, AF_NETLINK, SOCK_RAW, -1) > 0) {
2417
2418 if (m->audit_fd >= 0)
2419 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2420 "Too many audit sockets passed.");
2421
2422 m->audit_fd = fd;
2423
2424 } else {
2425
2426 if (!fds) {
2427 fds = fdset_new();
2428 if (!fds)
2429 return log_oom();
2430 }
2431
2432 r = fdset_put(fds, fd);
2433 if (r < 0)
2434 return log_oom();
2435 }
2436
2437 /* Try to restore streams, but don't bother if this fails */
2438 (void) manager_restore_streams(m, fds);
2439
2440 if (!fdset_isempty(fds)) {
2441 log_warning("%u unknown file descriptors passed, closing.", fdset_size(fds));
2442 fds = fdset_free(fds);
2443 }
2444
2445 no_sockets = m->native_fd < 0 && m->stdout_fd < 0 && m->syslog_fd < 0 && m->audit_fd < 0 && varlink_fd < 0;
2446
2447 /* always open stdout, syslog, native, and kmsg sockets */
2448
2449 /* systemd-journald.socket: /run/systemd/journal/stdout */
2450 r = manager_open_stdout_socket(m, stdout_socket);
2451 if (r < 0)
2452 return r;
2453
2454 /* systemd-journald-dev-log.socket: /run/systemd/journal/dev-log */
2455 r = manager_open_syslog_socket(m, syslog_socket);
2456 if (r < 0)
2457 return r;
2458
2459 /* systemd-journald.socket: /run/systemd/journal/socket */
2460 r = manager_open_native_socket(m, native_socket);
2461 if (r < 0)
2462 return r;
2463
2464 /* /dev/kmsg */
2465 r = manager_open_dev_kmsg(m);
2466 if (r < 0)
2467 return r;
2468
2469 /* Unless we got *some* sockets and not audit, open audit socket */
2470 if (m->audit_fd >= 0 || no_sockets) {
2471 log_info("Collecting audit messages is enabled.");
2472
2473 r = manager_open_audit(m);
2474 if (r < 0)
2475 return r;
2476 } else
2477 log_info("Collecting audit messages is disabled.");
2478
2479 r = manager_open_varlink(m, varlink_socket, varlink_fd);
2480 if (r < 0)
2481 return r;
2482
2483 r = manager_map_seqnum_file(m, "seqnum", sizeof(SeqnumData), (void**) &m->seqnum);
2484 if (r < 0)
2485 return log_error_errno(r, "Failed to map main seqnum file: %m");
2486
2487 r = manager_open_kernel_seqnum(m);
2488 if (r < 0)
2489 return r;
2490
2491 r = manager_open_hostname(m);
2492 if (r < 0)
2493 return r;
2494
2495 r = manager_setup_signals(m);
2496 if (r < 0)
2497 return r;
2498
2499 r = manager_setup_memory_pressure(m);
2500 if (r < 0)
2501 return r;
2502
2503 r = cg_get_root_path(&m->cgroup_root);
2504 if (r < 0)
2505 return log_error_errno(r, "Failed to acquire cgroup root path: %m");
2506
2507 manager_cache_hostname(m);
2508 manager_cache_boot_id(m);
2509 manager_cache_machine_id(m);
2510
2511 if (m->namespace)
2512 m->runtime_storage.path = strjoin("/run/log/journal/", MANAGER_MACHINE_ID(m), ".", m->namespace);
2513 else
2514 m->runtime_storage.path = strjoin("/run/log/journal/", MANAGER_MACHINE_ID(m));
2515 if (!m->runtime_storage.path)
2516 return log_oom();
2517
2518 e = getenv("LOGS_DIRECTORY");
2519 if (e)
2520 m->system_storage.path = strdup(e);
2521 else if (m->namespace)
2522 m->system_storage.path = strjoin("/var/log/journal/", MANAGER_MACHINE_ID(m), ".", m->namespace);
2523 else
2524 m->system_storage.path = strjoin("/var/log/journal/", MANAGER_MACHINE_ID(m));
2525 if (!m->system_storage.path)
2526 return log_oom();
2527
2528 (void) manager_connect_notify(m);
2529
2530 client_context_acquire_default(m);
2531
2532 r = manager_system_journal_open(m, /* flush_requested= */ false, /* relinquish_requested= */ false);
2533 if (r < 0)
2534 return r;
2535
2536 manager_start_or_stop_idle_timer(m);
2537
2538 return 0;
2539 }
2540
2541 void manager_maybe_append_tags(Manager *m) {
2542 #if HAVE_GCRYPT
2543 JournalFile *f;
2544 usec_t n;
2545
2546 n = now(CLOCK_REALTIME);
2547
2548 if (m->system_journal)
2549 journal_file_maybe_append_tag(m->system_journal, n);
2550
2551 ORDERED_HASHMAP_FOREACH(f, m->user_journals)
2552 journal_file_maybe_append_tag(f, n);
2553 #endif
2554 }
2555
2556 Manager* manager_free(Manager *m) {
2557 if (!m)
2558 return NULL;
2559
2560 free(m->namespace);
2561 free(m->namespace_field);
2562
2563 set_free(m->deferred_closes);
2564
2565 while (m->stdout_streams)
2566 stdout_stream_free(m->stdout_streams);
2567
2568 client_context_flush_all(m);
2569
2570 (void) journal_file_offline_close(m->system_journal);
2571 (void) journal_file_offline_close(m->runtime_journal);
2572
2573 ordered_hashmap_free(m->user_journals);
2574
2575 sd_varlink_server_unref(m->varlink_server);
2576
2577 sd_event_source_unref(m->syslog_event_source);
2578 sd_event_source_unref(m->native_event_source);
2579 sd_event_source_unref(m->stdout_event_source);
2580 sd_event_source_unref(m->dev_kmsg_event_source);
2581 sd_event_source_unref(m->audit_event_source);
2582 sd_event_source_unref(m->sync_event_source);
2583 sd_event_source_unref(m->sigusr1_event_source);
2584 sd_event_source_unref(m->sigusr2_event_source);
2585 sd_event_source_unref(m->sigterm_event_source);
2586 sd_event_source_unref(m->sigint_event_source);
2587 sd_event_source_unref(m->sigrtmin1_event_source);
2588 sd_event_source_unref(m->hostname_event_source);
2589 sd_event_source_unref(m->notify_event_source);
2590 sd_event_source_unref(m->watchdog_event_source);
2591 sd_event_source_unref(m->idle_event_source);
2592 sd_event_unref(m->event);
2593
2594 safe_close(m->syslog_fd);
2595 safe_close(m->native_fd);
2596 safe_close(m->stdout_fd);
2597 safe_close(m->dev_kmsg_fd);
2598 safe_close(m->audit_fd);
2599 safe_close(m->hostname_fd);
2600 safe_close(m->notify_fd);
2601 safe_close(m->forward_socket_fd);
2602
2603 ordered_hashmap_free(m->ratelimit_groups_by_id);
2604
2605 manager_unmap_seqnum_file(m->seqnum, sizeof(*m->seqnum));
2606 manager_close_kernel_seqnum(m);
2607
2608 free(m->buffer);
2609 free(m->cgroup_root);
2610 free(m->hostname_field);
2611 free(m->runtime_storage.path);
2612 free(m->system_storage.path);
2613 free(m->runtime_directory);
2614
2615 mmap_cache_unref(m->mmap);
2616
2617 SyncReq *req;
2618 while ((req = prioq_peek(m->sync_req_realtime_prioq)))
2619 sync_req_free(req);
2620 prioq_free(m->sync_req_realtime_prioq);
2621
2622 while ((req = prioq_peek(m->sync_req_boottime_prioq)))
2623 sync_req_free(req);
2624 prioq_free(m->sync_req_boottime_prioq);
2625
2626 journal_config_done(&m->config);
2627 journal_config_done(&m->config_by_cred);
2628 journal_config_done(&m->config_by_conf);
2629 journal_config_done(&m->config_by_cmdline);
2630
2631 return mfree(m);
2632 }