]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/journal/journald-context.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2017 Lennart Poettering
7 #include <selinux/selinux.h>
10 #include "alloc-util.h"
11 #include "audit-util.h"
12 #include "cgroup-util.h"
17 #include "journal-util.h"
18 #include "journald-context.h"
19 #include "process-util.h"
20 #include "string-util.h"
21 #include "syslog-util.h"
22 #include "unaligned.h"
23 #include "user-util.h"
25 /* This implements a metadata cache for clients, which are identified by their PID. Requesting metadata through /proc
26 * is expensive, hence let's cache the data if we can. Note that this means the metadata might be out-of-date when we
27 * store it, but it might already be anyway, as we request the data asynchronously from /proc at a different time the
28 * log entry was originally created. We hence just increase the "window of inaccuracy" a bit.
30 * The cache is indexed by the PID. Entries may be "pinned" in the cache, in which case the entries are not removed
31 * until they are unpinned. Unpinned entries are kept around until cache pressure is seen. Cache entries older than 5s
32 * are never used (a sad attempt to deal with the UNIX weakness of PIDs reuse), cache entries older than 1s are
33 * refreshed in an incremental way (meaning: data is reread from /proc, but any old data we can't refresh is not
34 * flushed out). Data newer than 1s is used immediately without refresh.
36 * Log stream clients (i.e. all clients using the AF_UNIX/SOCK_STREAM stdout/stderr transport) will pin a cache entry
37 * as long as their socket is connected. Note that cache entries are shared between different transports. That means a
38 * cache entry pinned for the stream connection logic may be reused for the syslog or native protocols.
40 * Caching metadata like this has two major benefits:
42 * 1. Reading metadata is expensive, and we can thus substantially speed up log processing under flood.
44 * 2. Because metadata caching is shared between stream and datagram transports and stream connections pin a cache
45 * entry there's a good chance we can properly map a substantial set of datagram log messages to their originating
46 * service, as all services (unless explicitly configured otherwise) will have their stdout/stderr connected to a
47 * stream connection. This should improve cases where a service process logs immediately before exiting and we
48 * previously had trouble associating the log message with the service.
50 * NB: With and without the metadata cache: the implicitly added entry metadata in the journal (with the exception of
51 * UID/PID/GID and SELinux label) must be understood as possibly slightly out of sync (i.e. sometimes slighly older
52 * and sometimes slightly newer than what was current at the log event).
55 /* We refresh every 1s */
56 #define REFRESH_USEC (1*USEC_PER_SEC)
58 /* Data older than 5s we flush out */
59 #define MAX_USEC (5*USEC_PER_SEC)
61 /* Keep at most 16K entries in the cache. (Note though that this limit may be violated if enough streams pin entries in
62 * the cache, in which case we *do* permit this limit to be breached. That's safe however, as the number of stream
63 * clients itself is limited.) */
64 #define CACHE_MAX (16*1024)
66 static int client_context_compare(const void *a
, const void *b
) {
67 const ClientContext
*x
= a
, *y
= b
;
69 if (x
->timestamp
< y
->timestamp
)
71 if (x
->timestamp
> y
->timestamp
)
82 static int client_context_new(Server
*s
, pid_t pid
, ClientContext
**ret
) {
87 assert(pid_is_valid(pid
));
90 r
= hashmap_ensure_allocated(&s
->client_contexts
, NULL
);
94 r
= prioq_ensure_allocated(&s
->client_contexts_lru
, client_context_compare
);
98 c
= new0(ClientContext
, 1);
104 c
->uid
= UID_INVALID
;
105 c
->gid
= GID_INVALID
;
106 c
->auditid
= AUDIT_SESSION_INVALID
;
107 c
->loginuid
= UID_INVALID
;
108 c
->owner_uid
= UID_INVALID
;
109 c
->lru_index
= PRIOQ_IDX_NULL
;
110 c
->timestamp
= USEC_INFINITY
;
111 c
->extra_fields_mtime
= NSEC_INFINITY
;
112 c
->log_level_max
= -1;
114 r
= hashmap_put(s
->client_contexts
, PID_TO_PTR(pid
), c
);
124 static void client_context_reset(ClientContext
*c
) {
127 c
->timestamp
= USEC_INFINITY
;
129 c
->uid
= UID_INVALID
;
130 c
->gid
= GID_INVALID
;
132 c
->comm
= mfree(c
->comm
);
133 c
->exe
= mfree(c
->exe
);
134 c
->cmdline
= mfree(c
->cmdline
);
135 c
->capeff
= mfree(c
->capeff
);
137 c
->auditid
= AUDIT_SESSION_INVALID
;
138 c
->loginuid
= UID_INVALID
;
140 c
->cgroup
= mfree(c
->cgroup
);
141 c
->session
= mfree(c
->session
);
142 c
->owner_uid
= UID_INVALID
;
143 c
->unit
= mfree(c
->unit
);
144 c
->user_unit
= mfree(c
->user_unit
);
145 c
->slice
= mfree(c
->slice
);
146 c
->user_slice
= mfree(c
->user_slice
);
148 c
->invocation_id
= SD_ID128_NULL
;
150 c
->label
= mfree(c
->label
);
153 c
->extra_fields_iovec
= mfree(c
->extra_fields_iovec
);
154 c
->extra_fields_n_iovec
= 0;
155 c
->extra_fields_data
= mfree(c
->extra_fields_data
);
156 c
->extra_fields_mtime
= NSEC_INFINITY
;
158 c
->log_level_max
= -1;
161 static ClientContext
* client_context_free(Server
*s
, ClientContext
*c
) {
167 assert_se(hashmap_remove(s
->client_contexts
, PID_TO_PTR(c
->pid
)) == c
);
170 assert_se(prioq_remove(s
->client_contexts_lru
, c
, &c
->lru_index
) >= 0);
172 client_context_reset(c
);
177 static void client_context_read_uid_gid(ClientContext
*c
, const struct ucred
*ucred
) {
179 assert(pid_is_valid(c
->pid
));
181 /* The ucred data passed in is always the most current and accurate, if we have any. Use it. */
182 if (ucred
&& uid_is_valid(ucred
->uid
))
185 (void) get_process_uid(c
->pid
, &c
->uid
);
187 if (ucred
&& gid_is_valid(ucred
->gid
))
190 (void) get_process_gid(c
->pid
, &c
->gid
);
193 static void client_context_read_basic(ClientContext
*c
) {
197 assert(pid_is_valid(c
->pid
));
199 if (get_process_comm(c
->pid
, &t
) >= 0)
200 free_and_replace(c
->comm
, t
);
202 if (get_process_exe(c
->pid
, &t
) >= 0)
203 free_and_replace(c
->exe
, t
);
205 if (get_process_cmdline(c
->pid
, 0, false, &t
) >= 0)
206 free_and_replace(c
->cmdline
, t
);
208 if (get_process_capeff(c
->pid
, &t
) >= 0)
209 free_and_replace(c
->capeff
, t
);
212 static int client_context_read_label(
214 const char *label
, size_t label_size
) {
217 assert(pid_is_valid(c
->pid
));
218 assert(label_size
== 0 || label
);
220 if (label_size
> 0) {
223 /* If we got an SELinux label passed in it counts. */
225 l
= newdup_suffix0(char, label
, label_size
);
229 free_and_replace(c
->label
, l
);
230 c
->label_size
= label_size
;
236 /* If we got no SELinux label passed in, let's try to acquire one */
238 if (getpidcon(c
->pid
, &con
) >= 0) {
239 free_and_replace(c
->label
, con
);
240 c
->label_size
= strlen(c
->label
);
248 static int client_context_read_cgroup(Server
*s
, ClientContext
*c
, const char *unit_id
) {
254 /* Try to acquire the current cgroup path */
255 r
= cg_pid_get_path_shifted(c
->pid
, s
->cgroup_root
, &t
);
258 /* If that didn't work, we use the unit ID passed in as fallback, if we have nothing cached yet */
259 if (unit_id
&& !c
->unit
) {
260 c
->unit
= strdup(unit_id
);
268 /* Let's shortcut this if the cgroup path didn't change */
269 if (streq_ptr(c
->cgroup
, t
)) {
274 free_and_replace(c
->cgroup
, t
);
276 (void) cg_path_get_session(c
->cgroup
, &t
);
277 free_and_replace(c
->session
, t
);
279 if (cg_path_get_owner_uid(c
->cgroup
, &c
->owner_uid
) < 0)
280 c
->owner_uid
= UID_INVALID
;
282 (void) cg_path_get_unit(c
->cgroup
, &t
);
283 free_and_replace(c
->unit
, t
);
285 (void) cg_path_get_user_unit(c
->cgroup
, &t
);
286 free_and_replace(c
->user_unit
, t
);
288 (void) cg_path_get_slice(c
->cgroup
, &t
);
289 free_and_replace(c
->slice
, t
);
291 (void) cg_path_get_user_slice(c
->cgroup
, &t
);
292 free_and_replace(c
->user_slice
, t
);
297 static int client_context_read_invocation_id(
301 _cleanup_free_
char *value
= NULL
;
308 /* Read the invocation ID of a unit off a unit. PID 1 stores it in a per-unit symlink in /run/systemd/units/ */
313 p
= strjoina("/run/systemd/units/invocation:", c
->unit
);
314 r
= readlink_malloc(p
, &value
);
318 return sd_id128_from_string(value
, &c
->invocation_id
);
321 static int client_context_read_log_level_max(
325 _cleanup_free_
char *value
= NULL
;
332 p
= strjoina("/run/systemd/units/log-level-max:", c
->unit
);
333 r
= readlink_malloc(p
, &value
);
337 ll
= log_level_from_string(value
);
341 c
->log_level_max
= ll
;
345 static int client_context_read_extra_fields(
349 size_t size
= 0, n_iovec
= 0, n_allocated
= 0, left
;
350 _cleanup_free_
struct iovec
*iovec
= NULL
;
351 _cleanup_free_
void *data
= NULL
;
352 _cleanup_fclose_
FILE *f
= NULL
;
361 p
= strjoina("/run/systemd/units/log-extra-fields:", c
->unit
);
363 if (c
->extra_fields_mtime
!= NSEC_INFINITY
) {
364 if (stat(p
, &st
) < 0) {
371 if (timespec_load_nsec(&st
.st_mtim
) == c
->extra_fields_mtime
)
383 if (fstat(fileno(f
), &st
) < 0) /* The file might have been replaced since the stat() above, let's get a new
384 * one, that matches the stuff we are reading */
387 r
= read_full_stream(f
, (char**) &data
, &size
);
391 q
= data
, left
= size
;
396 if (left
< sizeof(uint64_t))
399 v
= unaligned_read_le64(q
);
403 n
= sizeof(uint64_t) + v
;
407 field
= q
+ sizeof(uint64_t);
409 eq
= memchr(field
, '=', v
);
413 if (!journal_field_valid((const char *) field
, eq
- field
, false))
416 if (!GREEDY_REALLOC(iovec
, n_allocated
, n_iovec
+1))
419 iovec
[n_iovec
++] = IOVEC_MAKE(field
, v
);
424 free(c
->extra_fields_iovec
);
425 free(c
->extra_fields_data
);
427 c
->extra_fields_iovec
= TAKE_PTR(iovec
);
428 c
->extra_fields_n_iovec
= n_iovec
;
429 c
->extra_fields_data
= TAKE_PTR(data
);
430 c
->extra_fields_mtime
= timespec_load_nsec(&st
.st_mtim
);
435 static void client_context_really_refresh(
438 const struct ucred
*ucred
,
439 const char *label
, size_t label_size
,
445 assert(pid_is_valid(c
->pid
));
447 if (timestamp
== USEC_INFINITY
)
448 timestamp
= now(CLOCK_MONOTONIC
);
450 client_context_read_uid_gid(c
, ucred
);
451 client_context_read_basic(c
);
452 (void) client_context_read_label(c
, label
, label_size
);
454 (void) audit_session_from_pid(c
->pid
, &c
->auditid
);
455 (void) audit_loginuid_from_pid(c
->pid
, &c
->loginuid
);
457 (void) client_context_read_cgroup(s
, c
, unit_id
);
458 (void) client_context_read_invocation_id(s
, c
);
459 (void) client_context_read_log_level_max(s
, c
);
460 (void) client_context_read_extra_fields(s
, c
);
462 c
->timestamp
= timestamp
;
465 assert(c
->n_ref
== 0);
466 assert_se(prioq_reshuffle(s
->client_contexts_lru
, c
, &c
->lru_index
) >= 0);
470 void client_context_maybe_refresh(
473 const struct ucred
*ucred
,
474 const char *label
, size_t label_size
,
481 if (timestamp
== USEC_INFINITY
)
482 timestamp
= now(CLOCK_MONOTONIC
);
484 /* No cached data so far? Let's fill it up */
485 if (c
->timestamp
== USEC_INFINITY
)
488 /* If the data isn't pinned and if the cashed data is older than the upper limit, we flush it out
489 * entirely. This follows the logic that as long as an entry is pinned the PID reuse is unlikely. */
490 if (c
->n_ref
== 0 && c
->timestamp
+ MAX_USEC
< timestamp
) {
491 client_context_reset(c
);
495 /* If the data is older than the lower limit, we refresh, but keep the old data for all we can't update */
496 if (c
->timestamp
+ REFRESH_USEC
< timestamp
)
499 /* If the data passed along doesn't match the cached data we also do a refresh */
500 if (ucred
&& uid_is_valid(ucred
->uid
) && c
->uid
!= ucred
->uid
)
503 if (ucred
&& gid_is_valid(ucred
->gid
) && c
->gid
!= ucred
->gid
)
506 if (label_size
> 0 && (label_size
!= c
->label_size
|| memcmp(label
, c
->label
, label_size
) != 0))
512 client_context_really_refresh(s
, c
, ucred
, label
, label_size
, unit_id
, timestamp
);
515 static void client_context_try_shrink_to(Server
*s
, size_t limit
) {
518 /* Bring the number of cache entries below the indicated limit, so that we can create a new entry without
519 * breaching the limit. Note that we only flush out entries that aren't pinned here. This means the number of
520 * cache entries may very well grow beyond the limit, if all entries stored remain pinned. */
522 while (hashmap_size(s
->client_contexts
) > limit
) {
525 c
= prioq_pop(s
->client_contexts_lru
);
527 break; /* All remaining entries are pinned, give up */
530 assert(c
->n_ref
== 0);
534 client_context_free(s
, c
);
538 void client_context_flush_all(Server
*s
) {
541 /* Flush out all remaining entries. This assumes all references are already dropped. */
543 s
->my_context
= client_context_release(s
, s
->my_context
);
544 s
->pid1_context
= client_context_release(s
, s
->pid1_context
);
546 client_context_try_shrink_to(s
, 0);
548 assert(prioq_size(s
->client_contexts_lru
) == 0);
549 assert(hashmap_size(s
->client_contexts
) == 0);
551 s
->client_contexts_lru
= prioq_free(s
->client_contexts_lru
);
552 s
->client_contexts
= hashmap_free(s
->client_contexts
);
555 static int client_context_get_internal(
558 const struct ucred
*ucred
,
559 const char *label
, size_t label_len
,
562 ClientContext
**ret
) {
570 if (!pid_is_valid(pid
))
573 c
= hashmap_get(s
->client_contexts
, PID_TO_PTR(pid
));
578 /* The entry wasn't pinned so far, let's remove it from the LRU list then */
579 assert(c
->n_ref
== 0);
580 assert_se(prioq_remove(s
->client_contexts_lru
, c
, &c
->lru_index
) >= 0);
587 client_context_maybe_refresh(s
, c
, ucred
, label
, label_len
, unit_id
, USEC_INFINITY
);
593 client_context_try_shrink_to(s
, CACHE_MAX
-1);
595 r
= client_context_new(s
, pid
, &c
);
602 r
= prioq_put(s
->client_contexts_lru
, c
, &c
->lru_index
);
604 client_context_free(s
, c
);
611 client_context_really_refresh(s
, c
, ucred
, label
, label_len
, unit_id
, USEC_INFINITY
);
617 int client_context_get(
620 const struct ucred
*ucred
,
621 const char *label
, size_t label_len
,
623 ClientContext
**ret
) {
625 return client_context_get_internal(s
, pid
, ucred
, label
, label_len
, unit_id
, false, ret
);
628 int client_context_acquire(
631 const struct ucred
*ucred
,
632 const char *label
, size_t label_len
,
634 ClientContext
**ret
) {
636 return client_context_get_internal(s
, pid
, ucred
, label
, label_len
, unit_id
, true, ret
);
639 ClientContext
*client_context_release(Server
*s
, ClientContext
*c
) {
645 assert(c
->n_ref
> 0);
652 /* The entry is not pinned anymore, let's add it to the LRU prioq if we can. If we can't we'll drop it
655 if (prioq_put(s
->client_contexts_lru
, c
, &c
->lru_index
) < 0)
656 client_context_free(s
, c
);
663 void client_context_acquire_default(Server
*s
) {
668 /* Ensure that our own and PID1's contexts are always pinned. Our own context is particularly useful to
669 * generate driver messages. */
671 if (!s
->my_context
) {
672 struct ucred ucred
= {
673 .pid
= getpid_cached(),
678 r
= client_context_acquire(s
, ucred
.pid
, &ucred
, NULL
, 0, NULL
, &s
->my_context
);
680 log_warning_errno(r
, "Failed to acquire our own context, ignoring: %m");
683 if (!s
->pid1_context
) {
685 r
= client_context_acquire(s
, 1, NULL
, NULL
, 0, NULL
, &s
->pid1_context
);
687 log_warning_errno(r
, "Failed to acquire PID1's context, ignoring: %m");