Debian Codegraph @

src/journal/journald-context.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/stat.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "audit-util.h"
8 #include "cgroup-util.h"
9 #include "env-util.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "fs-util.h"
13 #include "iovec-util.h"
14 #include "journal-internal.h"
15 #include "journald-client.h"
16 #include "journald-context.h"
17 #include "journald-manager.h"
18 #include "log.h"
19 #include "log-ratelimit.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "pidref.h"
23 #include "prioq.h"
24 #include "process-util.h"
25 #include "procfs-util.h"
26 #include "selinux-util.h"
27 #include "set.h"
28 #include "string-util.h"
29 #include "syslog-util.h"
30 #include "time-util.h"
31 #include "unaligned.h"
32 #include "user-util.h"
33
34 /* This implements a metadata cache for clients, which are identified by their PID. Requesting metadata through /proc
35 * is expensive, hence let's cache the data if we can. Note that this means the metadata might be out-of-date when we
36 * store it, but it might already be anyway, as we request the data asynchronously from /proc at a different time the
37 * log entry was originally created. We hence just increase the "window of inaccuracy" a bit.
38 *
39 * The cache is indexed by the PID. Entries may be "pinned" in the cache, in which case the entries are not removed
40 * until they are unpinned. Unpinned entries are kept around until cache pressure is seen. Cache entries older than 5s
41 * are never used (a sad attempt to deal with the UNIX weakness of PIDs reuse), cache entries older than 1s are
42 * refreshed in an incremental way (meaning: data is reread from /proc, but any old data we can't refresh is not
43 * flushed out). Data newer than 1s is used immediately without refresh.
44 *
45 * Log stream clients (i.e. all clients using the AF_UNIX/SOCK_STREAM stdout/stderr transport) will pin a cache entry
46 * as long as their socket is connected. Note that cache entries are shared between different transports. That means a
47 * cache entry pinned for the stream connection logic may be reused for the syslog or native protocols.
48 *
49 * Caching metadata like this has two major benefits:
50 *
51 * 1. Reading metadata is expensive, and we can thus substantially speed up log processing under flood.
52 *
53 * 2. Because metadata caching is shared between stream and datagram transports and stream connections pin a cache
54 * entry there's a good chance we can properly map a substantial set of datagram log messages to their originating
55 * service, as all services (unless explicitly configured otherwise) will have their stdout/stderr connected to a
56 * stream connection. This should improve cases where a service process logs immediately before exiting and we
57 * previously had trouble associating the log message with the service.
58 *
59 * NB: With and without the metadata cache: the implicitly added entry metadata in the journal (with the exception of
60 * UID/PID/GID and SELinux label) must be understood as possibly slightly out of sync (i.e. sometimes slightly older
61 * and sometimes slightly newer than what was current at the log event).
62 */
63
64 /* We refresh every 1s */
65 #define REFRESH_USEC (1*USEC_PER_SEC)
66
67 /* Data older than 5s we flush out */
68 #define MAX_USEC (5*USEC_PER_SEC)
69
70 /* Keep at most 16K entries in the cache. (Note though that this limit may be violated if enough streams pin entries in
71 * the cache, in which case we *do* permit this limit to be breached. That's safe however, as the number of stream
72 * clients itself is limited.) */
73 #define CACHE_MAX_FALLBACK 128U
74 #define CACHE_MAX_MAX (16*1024U)
75 #define CACHE_MAX_MIN 64U
76
77 static size_t cache_max(void) {
78 static size_t cached = -1;
79
80 if (cached == SIZE_MAX) {
81 uint64_t mem_total;
82 int r;
83
84 r = procfs_memory_get(&mem_total, NULL);
85 if (r < 0) {
86 log_warning_errno(r, "Cannot query /proc/meminfo for MemTotal: %m");
87 cached = CACHE_MAX_FALLBACK;
88 } else
89 /* Cache entries are usually a few kB, but the process cmdline is controlled by the
90 * user and can be up to _SC_ARG_MAX, usually 2MB. Let's say that approximately up to
91 * 1/8th of memory may be used by the cache.
92 *
93 * In the common case, this formula gives 64 cache entries for each GB of RAM.
94 */
95 cached = CLAMP(mem_total / 8 / sc_arg_max(), CACHE_MAX_MIN, CACHE_MAX_MAX);
96 }
97
98 return cached;
99 }
100
101 static int client_context_compare(const void *a, const void *b) {
102 const ClientContext *x = a, *y = b;
103 int r;
104
105 r = CMP(x->timestamp, y->timestamp);
106 if (r != 0)
107 return r;
108
109 return CMP(x->pid, y->pid);
110 }
111
112 static int client_context_new(Manager *m, pid_t pid, ClientContext **ret) {
113 _cleanup_free_ ClientContext *c = NULL;
114 int r;
115
116 assert(m);
117 assert(pid_is_valid(pid));
118 assert(ret);
119
120 r = prioq_ensure_allocated(&m->client_contexts_lru, client_context_compare);
121 if (r < 0)
122 return r;
123
124 c = new(ClientContext, 1);
125 if (!c)
126 return -ENOMEM;
127
128 *c = (ClientContext) {
129 .pid = pid,
130 .uid = UID_INVALID,
131 .gid = GID_INVALID,
132 .auditid = AUDIT_SESSION_INVALID,
133 .loginuid = UID_INVALID,
134 .owner_uid = UID_INVALID,
135 .lru_index = PRIOQ_IDX_NULL,
136 .timestamp = USEC_INFINITY,
137 .extra_fields_mtime = NSEC_INFINITY,
138 .log_level_max = -1,
139 .log_ratelimit_interval = m->config.ratelimit_interval,
140 .log_ratelimit_burst = m->config.ratelimit_burst,
141 .capability_quintet = CAPABILITY_QUINTET_NULL,
142 };
143
144 r = hashmap_ensure_put(&m->client_contexts, NULL, PID_TO_PTR(pid), c);
145 if (r < 0)
146 return r;
147
148 *ret = TAKE_PTR(c);
149 return 0;
150 }
151
152 static void client_context_reset(Manager *m, ClientContext *c) {
153 assert(m);
154 assert(c);
155
156 c->timestamp = USEC_INFINITY;
157
158 c->uid = UID_INVALID;
159 c->gid = GID_INVALID;
160
161 c->comm = mfree(c->comm);
162 c->exe = mfree(c->exe);
163 c->cmdline = mfree(c->cmdline);
164
165 c->auditid = AUDIT_SESSION_INVALID;
166 c->loginuid = UID_INVALID;
167
168 c->cgroup = mfree(c->cgroup);
169 c->session = mfree(c->session);
170 c->owner_uid = UID_INVALID;
171 c->unit = mfree(c->unit);
172 c->user_unit = mfree(c->user_unit);
173 c->slice = mfree(c->slice);
174 c->user_slice = mfree(c->user_slice);
175
176 c->invocation_id = SD_ID128_NULL;
177
178 c->label = mfree(c->label);
179
180 c->extra_fields_iovec = mfree(c->extra_fields_iovec);
181 c->extra_fields_n_iovec = 0;
182 c->extra_fields_data = mfree(c->extra_fields_data);
183 c->extra_fields_mtime = NSEC_INFINITY;
184
185 c->log_level_max = -1;
186
187 c->log_ratelimit_interval = m->config.ratelimit_interval;
188 c->log_ratelimit_burst = m->config.ratelimit_burst;
189 c->log_ratelimit_interval_from_unit = false;
190 c->log_ratelimit_burst_from_unit = false;
191
192 c->log_filter_allowed_patterns = set_free(c->log_filter_allowed_patterns);
193 c->log_filter_denied_patterns = set_free(c->log_filter_denied_patterns);
194
195 c->capability_quintet = CAPABILITY_QUINTET_NULL;
196 }
197
198 static ClientContext* client_context_free(Manager *m, ClientContext *c) {
199 assert(m);
200
201 if (!c)
202 return NULL;
203
204 assert_se(hashmap_remove(m->client_contexts, PID_TO_PTR(c->pid)) == c);
205
206 if (c->in_lru)
207 assert_se(prioq_remove(m->client_contexts_lru, c, &c->lru_index) >= 0);
208
209 client_context_reset(m, c);
210
211 return mfree(c);
212 }
213
214 static void client_context_read_uid_gid(ClientContext *c, const struct ucred *ucred) {
215 assert(c);
216 assert(pid_is_valid(c->pid));
217
218 /* The ucred data passed in is always the most current and accurate, if we have any. Use it. */
219 if (ucred && uid_is_valid(ucred->uid))
220 c->uid = ucred->uid;
221 else
222 (void) pid_get_uid(c->pid, &c->uid);
223
224 if (ucred && gid_is_valid(ucred->gid))
225 c->gid = ucred->gid;
226 else
227 (void) get_process_gid(c->pid, &c->gid);
228 }
229
230 static void client_context_read_basic(ClientContext *c) {
231 char *t;
232
233 assert(c);
234 assert(pid_is_valid(c->pid));
235
236 if (pid_get_comm(c->pid, &t) >= 0)
237 free_and_replace(c->comm, t);
238
239 if (get_process_exe(c->pid, &t) >= 0)
240 free_and_replace(c->exe, t);
241
242 if (pid_get_cmdline(c->pid, SIZE_MAX, PROCESS_CMDLINE_QUOTE, &t) >= 0)
243 free_and_replace(c->cmdline, t);
244
245 (void) pidref_get_capability(&PIDREF_MAKE_FROM_PID(c->pid), &c->capability_quintet);
246 }
247
248 static int client_context_read_label(
249 ClientContext *c,
250 const char *label) {
251
252 int r;
253
254 assert(c);
255 assert(pid_is_valid(c->pid));
256
257 if (!mac_selinux_use())
258 return 0;
259
260 if (label) {
261 /* If we got an SELinux label passed in it counts. */
262 r = free_and_strdup(&c->label, label);
263 if (r < 0)
264 return -ENOMEM;
265 }
266 #if HAVE_SELINUX
267 else {
268 char *con;
269
270 /* If we got no SELinux label passed in, let's try to acquire one */
271
272 if (sym_getpidcon_raw(c->pid, &con) >= 0 && con)
273 free_and_replace(c->label, con);
274 }
275 #endif
276
277 return 0;
278 }
279
280 static int client_context_read_cgroup(Manager *m, ClientContext *c, const char *unit_id) {
281 _cleanup_free_ char *t = NULL;
282 int r;
283
284 assert(c);
285
286 /* Try to acquire the current cgroup path */
287 r = cg_pid_get_path_shifted(c->pid, m->cgroup_root, &t);
288 if (r < 0 || empty_or_root(t)) {
289 /* We use the unit ID passed in as fallback if we have nothing cached yet and cg_pid_get_path_shifted()
290 * failed or process is running in a root cgroup. Zombie processes are automatically migrated to root cgroup
291 * on cgroup v1 and we want to be able to map log messages from them too. */
292 if (unit_id && !c->unit) {
293 c->unit = strdup(unit_id);
294 if (c->unit)
295 return 0;
296 }
297
298 return r;
299 }
300
301 (void) client_context_read_log_filter_patterns(c, t);
302
303 /* Let's shortcut this if the cgroup path didn't change */
304 if (streq_ptr(c->cgroup, t))
305 return 0;
306
307 free_and_replace(c->cgroup, t);
308
309 (void) cg_path_get_session(c->cgroup, &t);
310 free_and_replace(c->session, t);
311
312 if (cg_path_get_owner_uid(c->cgroup, &c->owner_uid) < 0)
313 c->owner_uid = UID_INVALID;
314
315 (void) cg_path_get_unit(c->cgroup, &t);
316 free_and_replace(c->unit, t);
317
318 (void) cg_path_get_user_unit(c->cgroup, &t);
319 free_and_replace(c->user_unit, t);
320
321 (void) cg_path_get_slice(c->cgroup, &t);
322 free_and_replace(c->slice, t);
323
324 (void) cg_path_get_user_slice(c->cgroup, &t);
325 free_and_replace(c->user_slice, t);
326
327 return 0;
328 }
329
330 static int client_context_read_invocation_id(
331 Manager *m,
332 ClientContext *c) {
333
334 _cleanup_free_ char *p = NULL, *value = NULL;
335 int r;
336
337 assert(m);
338 assert(c);
339
340 /* Read the invocation ID of a unit off a unit.
341 * PID 1 stores it in a per-unit symlink in /run/systemd/units/
342 * User managers store it in a per-unit symlink under /run/user/<uid>/systemd/units/ */
343
344 if (!c->unit)
345 return 0;
346
347 if (c->user_unit) {
348 r = asprintf(&p, "/run/user/" UID_FMT "/systemd/units/invocation:%s", c->owner_uid, c->user_unit);
349 if (r < 0)
350 return r;
351 } else {
352 p = strjoin("/run/systemd/units/invocation:", c->unit);
353 if (!p)
354 return -ENOMEM;
355 }
356
357 r = readlink_malloc(p, &value);
358 if (r < 0)
359 return r;
360
361 return sd_id128_from_string(value, &c->invocation_id);
362 }
363
364 static int client_context_read_log_level_max(
365 Manager *m,
366 ClientContext *c) {
367
368 _cleanup_free_ char *value = NULL;
369 const char *p;
370 int r, ll;
371
372 if (!c->unit)
373 return 0;
374
375 p = strjoina("/run/systemd/units/log-level-max:", c->unit);
376 r = readlink_malloc(p, &value);
377 if (r < 0)
378 return r;
379
380 ll = log_level_from_string(value);
381 if (ll < 0)
382 return ll;
383
384 c->log_level_max = ll;
385 return 0;
386 }
387
388 static int client_context_read_extra_fields(
389 Manager *m,
390 ClientContext *c) {
391
392 _cleanup_free_ struct iovec *iovec = NULL;
393 size_t size = 0, n_iovec = 0, left;
394 _cleanup_free_ void *data = NULL;
395 _cleanup_fclose_ FILE *f = NULL;
396 struct stat st;
397 const char *p;
398 uint8_t *q;
399 int r;
400
401 if (!c->unit)
402 return 0;
403
404 p = strjoina("/run/systemd/units/log-extra-fields:", c->unit);
405
406 if (c->extra_fields_mtime != NSEC_INFINITY) {
407 if (stat(p, &st) < 0) {
408 if (errno == ENOENT)
409 return 0;
410
411 return -errno;
412 }
413
414 if (timespec_load_nsec(&st.st_mtim) == c->extra_fields_mtime)
415 return 0;
416 }
417
418 f = fopen(p, "re");
419 if (!f) {
420 if (errno == ENOENT)
421 return 0;
422
423 return -errno;
424 }
425
426 if (fstat(fileno(f), &st) < 0) /* The file might have been replaced since the stat() above, let's get a new
427 * one, that matches the stuff we are reading */
428 return -errno;
429
430 r = read_full_stream(f, (char**) &data, &size);
431 if (r < 0)
432 return r;
433
434 q = data, left = size;
435 while (left > 0) {
436 uint8_t *field, *eq;
437 uint64_t v, n;
438
439 if (left < sizeof(uint64_t))
440 return -EBADMSG;
441
442 v = unaligned_read_le64(q);
443 if (v < 2)
444 return -EBADMSG;
445
446 n = sizeof(uint64_t) + v;
447 if (left < n)
448 return -EBADMSG;
449
450 field = q + sizeof(uint64_t);
451
452 eq = memchr(field, '=', v);
453 if (!eq)
454 return -EBADMSG;
455
456 if (!journal_field_valid((const char *) field, eq - field, false))
457 return -EBADMSG;
458
459 if (!GREEDY_REALLOC(iovec, n_iovec+1))
460 return -ENOMEM;
461
462 iovec[n_iovec++] = IOVEC_MAKE(field, v);
463
464 left -= n, q += n;
465 }
466
467 free(c->extra_fields_iovec);
468 free(c->extra_fields_data);
469
470 c->extra_fields_iovec = TAKE_PTR(iovec);
471 c->extra_fields_n_iovec = n_iovec;
472 c->extra_fields_data = TAKE_PTR(data);
473 c->extra_fields_mtime = timespec_load_nsec(&st.st_mtim);
474
475 return 0;
476 }
477
478 static int client_context_read_log_ratelimit_interval(ClientContext *c) {
479 _cleanup_free_ char *value = NULL;
480 const char *p;
481 int r;
482
483 assert(c);
484
485 if (!c->unit)
486 return 0;
487
488 p = strjoina("/run/systemd/units/log-rate-limit-interval:", c->unit);
489 r = readlink_malloc(p, &value);
490 if (r < 0)
491 return r;
492
493 r = safe_atou64(value, &c->log_ratelimit_interval);
494 if (r < 0)
495 return r;
496
497 c->log_ratelimit_interval_from_unit = true;
498 return 0;
499 }
500
501 static int client_context_read_log_ratelimit_burst(ClientContext *c) {
502 _cleanup_free_ char *value = NULL;
503 const char *p;
504 int r;
505
506 assert(c);
507
508 if (!c->unit)
509 return 0;
510
511 p = strjoina("/run/systemd/units/log-rate-limit-burst:", c->unit);
512 r = readlink_malloc(p, &value);
513 if (r < 0)
514 return r;
515
516 r = safe_atou(value, &c->log_ratelimit_burst);
517 if (r < 0)
518 return r;
519
520 c->log_ratelimit_burst_from_unit = true;
521 return 0;
522 }
523
524 static void client_context_really_refresh(
525 Manager *m,
526 ClientContext *c,
527 const struct ucred *ucred,
528 const char *label,
529 const char *unit_id,
530 usec_t timestamp) {
531
532 assert(m);
533 assert(c);
534 assert(pid_is_valid(c->pid));
535
536 if (timestamp == USEC_INFINITY)
537 timestamp = now(CLOCK_MONOTONIC);
538
539 client_context_read_uid_gid(c, ucred);
540 client_context_read_basic(c);
541 (void) client_context_read_label(c, label);
542
543 (void) audit_session_from_pid(&PIDREF_MAKE_FROM_PID(c->pid), &c->auditid);
544 (void) audit_loginuid_from_pid(&PIDREF_MAKE_FROM_PID(c->pid), &c->loginuid);
545
546 (void) client_context_read_cgroup(m, c, unit_id);
547 (void) client_context_read_invocation_id(m, c);
548 (void) client_context_read_log_level_max(m, c);
549 (void) client_context_read_extra_fields(m, c);
550 (void) client_context_read_log_ratelimit_interval(c);
551 (void) client_context_read_log_ratelimit_burst(c);
552
553 c->timestamp = timestamp;
554
555 if (c->in_lru) {
556 assert(c->n_ref == 0);
557 prioq_reshuffle(m->client_contexts_lru, c, &c->lru_index);
558 }
559 }
560
561 void client_context_maybe_refresh(
562 Manager *m,
563 ClientContext *c,
564 const struct ucred *ucred,
565 const char *label,
566 const char *unit_id,
567 usec_t timestamp) {
568
569 assert(m);
570 assert(c);
571
572 if (timestamp == USEC_INFINITY)
573 timestamp = now(CLOCK_MONOTONIC);
574
575 /* No cached data so far? Let's fill it up */
576 if (c->timestamp == USEC_INFINITY)
577 goto refresh;
578
579 /* If the data isn't pinned and if the cashed data is older than the upper limit, we flush it out
580 * entirely. This follows the logic that as long as an entry is pinned the PID reuse is unlikely. */
581 if (c->n_ref == 0 && c->timestamp + MAX_USEC < timestamp) {
582 client_context_reset(m, c);
583 goto refresh;
584 }
585
586 /* If the data is older than the lower limit, we refresh, but keep the old data for all we can't update */
587 if (c->timestamp + REFRESH_USEC < timestamp)
588 goto refresh;
589
590 /* If the data passed along doesn't match the cached data we also do a refresh */
591 if (ucred && uid_is_valid(ucred->uid) && c->uid != ucred->uid)
592 goto refresh;
593
594 if (ucred && gid_is_valid(ucred->gid) && c->gid != ucred->gid)
595 goto refresh;
596
597 if (label && !streq_ptr(label, c->label))
598 goto refresh;
599
600 return;
601
602 refresh:
603 client_context_really_refresh(m, c, ucred, label, unit_id, timestamp);
604 }
605
606 static void client_context_refresh_on_reload(Manager *m, ClientContext *c) {
607 assert(m);
608
609 if (!c)
610 return;
611
612 if (!c->log_ratelimit_interval_from_unit)
613 c->log_ratelimit_interval = m->config.ratelimit_interval;
614
615 if (!c->log_ratelimit_burst_from_unit)
616 c->log_ratelimit_burst = m->config.ratelimit_burst;
617 }
618
619 void manager_refresh_client_contexts_on_reload(Manager *m, usec_t old_interval, unsigned old_burst) {
620 assert(m);
621
622 if (m->config.ratelimit_interval == old_interval && m->config.ratelimit_burst == old_burst)
623 return;
624
625 client_context_refresh_on_reload(m, m->my_context);
626 client_context_refresh_on_reload(m, m->pid1_context);
627
628 ClientContext *c;
629 HASHMAP_FOREACH(c, m->client_contexts)
630 client_context_refresh_on_reload(m, c);
631 }
632
633 static void client_context_try_shrink_to(Manager *m, size_t limit) {
634 ClientContext *c;
635 usec_t t;
636
637 assert(m);
638
639 /* Flush any cache entries for PIDs that have already moved on. Don't do this
640 * too often, since it's a slow process. */
641 t = now(CLOCK_MONOTONIC);
642 if (m->last_cache_pid_flush + MAX_USEC < t) {
643 unsigned n = prioq_size(m->client_contexts_lru), idx = 0;
644
645 /* We do a number of iterations based on the initial size of the prioq. When we remove an
646 * item, a new item is moved into its places, and items to the right might be reshuffled.
647 */
648 for (unsigned i = 0; i < n; i++) {
649 c = prioq_peek_by_index(m->client_contexts_lru, idx);
650
651 assert(c->n_ref == 0);
652
653 if (pid_is_unwaited(c->pid) == 0)
654 client_context_free(m, c);
655 else
656 idx++;
657 }
658
659 m->last_cache_pid_flush = t;
660 }
661
662 /* Bring the number of cache entries below the indicated limit, so that we can create a new entry without
663 * breaching the limit. Note that we only flush out entries that aren't pinned here. This means the number of
664 * cache entries may very well grow beyond the limit, if all entries stored remain pinned. */
665
666 while (hashmap_size(m->client_contexts) > limit) {
667 c = prioq_pop(m->client_contexts_lru);
668 if (!c)
669 break; /* All remaining entries are pinned, give up */
670
671 assert(c->in_lru);
672 assert(c->n_ref == 0);
673
674 c->in_lru = false;
675
676 client_context_free(m, c);
677 }
678 }
679
680 void client_context_flush_regular(Manager *m) {
681 client_context_try_shrink_to(m, 0);
682 }
683
684 void client_context_flush_all(Manager *m) {
685 assert(m);
686
687 /* Flush out all remaining entries. This assumes all references are already dropped. */
688
689 m->my_context = client_context_release(m, m->my_context);
690 m->pid1_context = client_context_release(m, m->pid1_context);
691
692 client_context_flush_regular(m);
693
694 assert(prioq_isempty(m->client_contexts_lru));
695 assert(hashmap_isempty(m->client_contexts));
696
697 m->client_contexts_lru = prioq_free(m->client_contexts_lru);
698 m->client_contexts = hashmap_free(m->client_contexts);
699 }
700
701 static int client_context_get_internal(
702 Manager *m,
703 pid_t pid,
704 const struct ucred *ucred,
705 const char *label,
706 const char *unit_id,
707 bool add_ref,
708 ClientContext **ret) {
709
710 ClientContext *c;
711 int r;
712
713 assert(m);
714 assert(ret);
715
716 if (!pid_is_valid(pid))
717 return -EINVAL;
718
719 c = hashmap_get(m->client_contexts, PID_TO_PTR(pid));
720 if (c) {
721
722 if (add_ref) {
723 if (c->in_lru) {
724 /* The entry wasn't pinned so far, let's remove it from the LRU list then */
725 assert(c->n_ref == 0);
726 assert_se(prioq_remove(m->client_contexts_lru, c, &c->lru_index) >= 0);
727 c->in_lru = false;
728 }
729
730 c->n_ref++;
731 }
732
733 client_context_maybe_refresh(m, c, ucred, label, unit_id, USEC_INFINITY);
734
735 *ret = c;
736 return 0;
737 }
738
739 client_context_try_shrink_to(m, cache_max()-1);
740
741 r = client_context_new(m, pid, &c);
742 if (r < 0)
743 return r;
744
745 if (add_ref)
746 c->n_ref++;
747 else {
748 r = prioq_put(m->client_contexts_lru, c, &c->lru_index);
749 if (r < 0) {
750 client_context_free(m, c);
751 return r;
752 }
753
754 c->in_lru = true;
755 }
756
757 client_context_really_refresh(m, c, ucred, label, unit_id, USEC_INFINITY);
758
759 *ret = c;
760 return 0;
761 }
762
763 int client_context_get(
764 Manager *m,
765 pid_t pid,
766 const struct ucred *ucred,
767 const char *label,
768 const char *unit_id,
769 ClientContext **ret) {
770
771 return client_context_get_internal(m, pid, ucred, label, unit_id, /* add_ref= */ false, ret);
772 }
773
774 int client_context_acquire(
775 Manager *m,
776 pid_t pid,
777 const struct ucred *ucred,
778 const char *label,
779 const char *unit_id,
780 ClientContext **ret) {
781
782 return client_context_get_internal(m, pid, ucred, label, unit_id, /* add_ref= */ true, ret);
783 };
784
785 ClientContext *client_context_release(Manager *m, ClientContext *c) {
786 assert(m);
787
788 if (!c)
789 return NULL;
790
791 assert(c->n_ref > 0);
792 assert(!c->in_lru);
793
794 c->n_ref--;
795 if (c->n_ref > 0)
796 return NULL;
797
798 /* 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
799 * right-away */
800
801 if (prioq_put(m->client_contexts_lru, c, &c->lru_index) < 0)
802 client_context_free(m, c);
803 else
804 c->in_lru = true;
805
806 return NULL;
807 }
808
809 void client_context_acquire_default(Manager *m) {
810 int r;
811
812 assert(m);
813
814 /* Ensure that our own and PID1's contexts are always pinned. Our own context is particularly useful to
815 * generate driver messages. */
816
817 if (!m->my_context) {
818 struct ucred ucred = {
819 .pid = getpid_cached(),
820 .uid = getuid(),
821 .gid = getgid(),
822 };
823
824 r = client_context_acquire(m, ucred.pid, &ucred, /* label= */ NULL, /* unit_id= */ NULL, &m->my_context);
825 if (r < 0)
826 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
827 "Failed to acquire our own context, ignoring: %m");
828 }
829
830 if (!m->namespace && !m->pid1_context) {
831 /* Acquire PID1's context, but only if we are in non-namespaced mode, since PID 1 is only
832 * going to log to the non-namespaced journal instance. */
833
834 r = client_context_acquire(m, 1, /* ucred= */ NULL, /* label= */ NULL, /* unit_id= */ NULL, &m->pid1_context);
835 if (r < 0)
836 log_ratelimit_warning_errno(r, JOURNAL_LOG_RATELIMIT,
837 "Failed to acquire PID1's context, ignoring: %m");
838
839 }
840 }