2 This file is part of systemd.
4 Copyright 2016 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 #include "alloc-util.h"
21 #include "bus-internal.h"
22 #include "bus-unit-util.h"
24 #include "cgroup-util.h"
29 #include "locale-util.h"
30 #include "parse-util.h"
31 #include "path-util.h"
32 #include "process-util.h"
33 #include "rlimit-util.h"
34 #include "signal-util.h"
35 #include "string-util.h"
36 #include "syslog-util.h"
37 #include "terminal-util.h"
41 int bus_parse_unit_info(sd_bus_message
*message
, UnitInfo
*u
) {
47 return sd_bus_message_read(
62 int bus_append_unit_property_assignment(sd_bus_message
*m
, const char *assignment
) {
63 const char *eq
, *field
;
69 eq
= strchr(assignment
, '=');
71 log_error("Not an assignment: %s", assignment
);
75 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_STRUCT
, "sv");
77 return bus_log_create_error(r
);
79 field
= strndupa(assignment
, eq
- assignment
);
82 if (streq(field
, "CPUQuota")) {
85 r
= sd_bus_message_append(m
, "sv", "CPUQuotaPerSecUSec", "t", USEC_INFINITY
);
87 r
= parse_percent(eq
);
89 log_error_errno(r
, "CPU quota '%s' invalid.", eq
);
93 r
= sd_bus_message_append(m
, "sv", "CPUQuotaPerSecUSec", "t", (usec_t
) r
* USEC_PER_SEC
/ 100U);
98 } else if (streq(field
, "EnvironmentFile")) {
100 r
= sd_bus_message_append(m
, "sv", "EnvironmentFiles", "a(sb)", 1,
101 eq
[0] == '-' ? eq
+ 1 : eq
,
105 } else if (STR_IN_SET(field
, "AccuracySec", "RandomizedDelaySec", "RuntimeMaxSec")) {
110 r
= parse_sec(eq
, &t
);
112 return log_error_errno(r
, "Failed to parse %s= parameter: %s", field
, eq
);
115 n
= newa(char, l
+ 2);
119 /* Change suffix Sec → USec */
120 strcpy(mempcpy(n
, field
, l
- 3), "USec");
121 r
= sd_bus_message_append(m
, "sv", n
, "t", t
);
124 } else if (STR_IN_SET(field
, "MemoryLow", "MemoryHigh", "MemoryMax", "MemoryLimit")) {
127 if (isempty(eq
) || streq(eq
, "infinity"))
128 bytes
= CGROUP_LIMIT_MAX
;
130 r
= parse_percent(eq
);
134 /* When this is a percentage we'll convert this into a relative value in the range
135 * 0…UINT32_MAX and pass it in the MemoryLowByPhysicalMemory property (and related
136 * ones). This way the physical memory size can be determined server-side */
138 n
= strjoina(field
, "ByPhysicalMemory");
139 r
= sd_bus_message_append(m
, "sv", n
, "u", (uint32_t) (((uint64_t) UINT32_MAX
* r
) / 100U));
143 r
= parse_size(eq
, 1024, &bytes
);
145 return log_error_errno(r
, "Failed to parse bytes specification %s", assignment
);
149 r
= sd_bus_message_append(m
, "sv", field
, "t", bytes
);
153 r
= sd_bus_message_append_basic(m
, SD_BUS_TYPE_STRING
, field
);
155 return bus_log_create_error(r
);
157 rl
= rlimit_from_string(field
);
162 r
= rlimit_parse(rl
, eq
, &l
);
164 return log_error_errno(r
, "Failed to parse resource limit: %s", eq
);
166 r
= sd_bus_message_append(m
, "v", "t", l
.rlim_max
);
168 return bus_log_create_error(r
);
170 r
= sd_bus_message_close_container(m
);
172 return bus_log_create_error(r
);
174 r
= sd_bus_message_open_container(m
, SD_BUS_TYPE_STRUCT
, "sv");
176 return bus_log_create_error(r
);
178 sn
= strjoina(field
, "Soft");
179 r
= sd_bus_message_append(m
, "sv", sn
, "t", l
.rlim_cur
);
181 } else if (STR_IN_SET(field
,
182 "CPUAccounting", "MemoryAccounting", "IOAccounting", "BlockIOAccounting", "TasksAccounting",
183 "SendSIGHUP", "SendSIGKILL", "WakeSystem", "DefaultDependencies",
184 "IgnoreSIGPIPE", "TTYVHangup", "TTYReset", "RemainAfterExit",
185 "PrivateTmp", "PrivateDevices", "PrivateNetwork", "NoNewPrivileges",
186 "SyslogLevelPrefix", "Delegate", "RemainAfterElapse", "MemoryDenyWriteExecute")) {
188 r
= parse_boolean(eq
);
190 return log_error_errno(r
, "Failed to parse boolean assignment %s.", assignment
);
192 r
= sd_bus_message_append(m
, "v", "b", r
);
194 } else if (streq(field
, "TasksMax")) {
197 if (isempty(eq
) || streq(eq
, "infinity"))
200 r
= safe_atou64(eq
, &n
);
202 log_error("Failed to parse maximum tasks specification %s", assignment
);
207 r
= sd_bus_message_append(m
, "v", "t", n
);
209 } else if (STR_IN_SET(field
, "CPUShares", "StartupCPUShares")) {
212 r
= cg_cpu_shares_parse(eq
, &u
);
214 log_error("Failed to parse %s value %s.", field
, eq
);
218 r
= sd_bus_message_append(m
, "v", "t", u
);
220 } else if (STR_IN_SET(field
, "IOWeight", "StartupIOWeight")) {
223 r
= cg_weight_parse(eq
, &u
);
225 log_error("Failed to parse %s value %s.", field
, eq
);
229 r
= sd_bus_message_append(m
, "v", "t", u
);
231 } else if (STR_IN_SET(field
, "BlockIOWeight", "StartupBlockIOWeight")) {
234 r
= cg_blkio_weight_parse(eq
, &u
);
236 log_error("Failed to parse %s value %s.", field
, eq
);
240 r
= sd_bus_message_append(m
, "v", "t", u
);
242 } else if (STR_IN_SET(field
,
243 "User", "Group", "DevicePolicy", "KillMode",
244 "UtmpIdentifier", "UtmpMode", "PAMName", "TTYPath",
245 "StandardInput", "StandardOutput", "StandardError",
246 "Description", "Slice", "Type", "WorkingDirectory",
247 "RootDirectory", "SyslogIdentifier", "ProtectSystem",
248 "ProtectHome", "SELinuxContext"))
249 r
= sd_bus_message_append(m
, "v", "s", eq
);
251 else if (streq(field
, "SyslogLevel")) {
254 level
= log_level_from_string(eq
);
256 log_error("Failed to parse %s value %s.", field
, eq
);
260 r
= sd_bus_message_append(m
, "v", "i", level
);
262 } else if (streq(field
, "SyslogFacility")) {
265 facility
= log_facility_unshifted_from_string(eq
);
267 log_error("Failed to parse %s value %s.", field
, eq
);
271 r
= sd_bus_message_append(m
, "v", "i", facility
);
273 } else if (streq(field
, "DeviceAllow")) {
276 r
= sd_bus_message_append(m
, "v", "a(ss)", 0);
278 const char *path
, *rwm
, *e
;
282 path
= strndupa(eq
, e
- eq
);
289 if (!path_startswith(path
, "/dev")) {
290 log_error("%s is not a device file in /dev.", path
);
294 r
= sd_bus_message_append(m
, "v", "a(ss)", 1, path
, rwm
);
297 } else if (cgroup_io_limit_type_from_string(field
) >= 0 || STR_IN_SET(field
, "BlockIOReadBandwidth", "BlockIOWriteBandwidth")) {
300 r
= sd_bus_message_append(m
, "v", "a(st)", 0);
302 const char *path
, *bandwidth
, *e
;
307 path
= strndupa(eq
, e
- eq
);
310 log_error("Failed to parse %s value %s.", field
, eq
);
314 if (!path_startswith(path
, "/dev")) {
315 log_error("%s is not a device file in /dev.", path
);
319 if (streq(bandwidth
, "infinity")) {
320 bytes
= CGROUP_LIMIT_MAX
;
322 r
= parse_size(bandwidth
, 1000, &bytes
);
324 log_error("Failed to parse byte value %s.", bandwidth
);
329 r
= sd_bus_message_append(m
, "v", "a(st)", 1, path
, bytes
);
332 } else if (STR_IN_SET(field
, "IODeviceWeight", "BlockIODeviceWeight")) {
335 r
= sd_bus_message_append(m
, "v", "a(st)", 0);
337 const char *path
, *weight
, *e
;
342 path
= strndupa(eq
, e
- eq
);
345 log_error("Failed to parse %s value %s.", field
, eq
);
349 if (!path_startswith(path
, "/dev")) {
350 log_error("%s is not a device file in /dev.", path
);
354 r
= safe_atou64(weight
, &u
);
356 log_error("Failed to parse %s value %s.", field
, weight
);
359 r
= sd_bus_message_append(m
, "v", "a(st)", 1, path
, u
);
362 } else if (streq(field
, "Nice")) {
365 r
= safe_atoi32(eq
, &i
);
367 log_error("Failed to parse %s value %s.", field
, eq
);
371 r
= sd_bus_message_append(m
, "v", "i", i
);
373 } else if (STR_IN_SET(field
, "Environment", "PassEnvironment")) {
376 r
= sd_bus_message_open_container(m
, 'v', "as");
378 return bus_log_create_error(r
);
380 r
= sd_bus_message_open_container(m
, 'a', "s");
382 return bus_log_create_error(r
);
387 _cleanup_free_
char *word
= NULL
;
389 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_CUNESCAPE
);
391 log_error("Failed to parse Environment value %s", eq
);
397 if (streq(field
, "Environment")) {
398 if (!env_assignment_is_valid(word
)) {
399 log_error("Invalid environment assignment: %s", word
);
402 } else { /* PassEnvironment */
403 if (!env_name_is_valid(word
)) {
404 log_error("Invalid environment variable name: %s", word
);
409 r
= sd_bus_message_append_basic(m
, 's', word
);
411 return bus_log_create_error(r
);
414 r
= sd_bus_message_close_container(m
);
416 return bus_log_create_error(r
);
418 r
= sd_bus_message_close_container(m
);
420 } else if (streq(field
, "KillSignal")) {
423 sig
= signal_from_string_try_harder(eq
);
425 log_error("Failed to parse %s value %s.", field
, eq
);
429 r
= sd_bus_message_append(m
, "v", "i", sig
);
431 } else if (streq(field
, "TimerSlackNSec")) {
434 r
= parse_nsec(eq
, &n
);
436 log_error("Failed to parse %s value %s", field
, eq
);
440 r
= sd_bus_message_append(m
, "v", "t", n
);
441 } else if (streq(field
, "OOMScoreAdjust")) {
444 r
= safe_atoi(eq
, &oa
);
446 log_error("Failed to parse %s value %s", field
, eq
);
450 if (!oom_score_adjust_is_valid(oa
)) {
451 log_error("OOM score adjust value out of range");
455 r
= sd_bus_message_append(m
, "v", "i", oa
);
456 } else if (STR_IN_SET(field
, "ReadWriteDirectories", "ReadOnlyDirectories", "InaccessibleDirectories")) {
459 r
= sd_bus_message_open_container(m
, 'v', "as");
461 return bus_log_create_error(r
);
463 r
= sd_bus_message_open_container(m
, 'a', "s");
465 return bus_log_create_error(r
);
470 _cleanup_free_
char *word
= NULL
;
473 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
);
475 log_error("Failed to parse %s value %s", field
, eq
);
481 if (!utf8_is_valid(word
)) {
482 log_error("Failed to parse %s value %s", field
, eq
);
486 offset
= word
[0] == '-';
487 if (!path_is_absolute(word
+ offset
)) {
488 log_error("Failed to parse %s value %s", field
, eq
);
492 path_kill_slashes(word
+ offset
);
494 r
= sd_bus_message_append_basic(m
, 's', word
);
496 return bus_log_create_error(r
);
499 r
= sd_bus_message_close_container(m
);
501 return bus_log_create_error(r
);
503 r
= sd_bus_message_close_container(m
);
505 } else if (streq(field
, "RuntimeDirectory")) {
508 r
= sd_bus_message_open_container(m
, 'v', "as");
510 return bus_log_create_error(r
);
512 r
= sd_bus_message_open_container(m
, 'a', "s");
514 return bus_log_create_error(r
);
519 _cleanup_free_
char *word
= NULL
;
521 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
);
523 return log_error_errno(r
, "Failed to parse %s value %s", field
, eq
);
528 r
= sd_bus_message_append_basic(m
, 's', word
);
530 return bus_log_create_error(r
);
533 r
= sd_bus_message_close_container(m
);
535 return bus_log_create_error(r
);
537 r
= sd_bus_message_close_container(m
);
540 log_error("Unknown assignment %s.", assignment
);
546 return bus_log_create_error(r
);
548 r
= sd_bus_message_close_container(m
);
550 return bus_log_create_error(r
);
555 typedef struct BusWaitForJobs
{
562 sd_bus_slot
*slot_job_removed
;
563 sd_bus_slot
*slot_disconnected
;
566 static int match_disconnected(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
569 log_error("Warning! D-Bus connection terminated.");
570 sd_bus_close(sd_bus_message_get_bus(m
));
575 static int match_job_removed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
576 const char *path
, *unit
, *result
;
577 BusWaitForJobs
*d
= userdata
;
585 r
= sd_bus_message_read(m
, "uoss", &id
, &path
, &unit
, &result
);
587 bus_log_parse_error(r
);
591 found
= set_remove(d
->jobs
, (char*) path
);
597 if (!isempty(result
))
598 d
->result
= strdup(result
);
601 d
->name
= strdup(unit
);
606 void bus_wait_for_jobs_free(BusWaitForJobs
*d
) {
610 set_free_free(d
->jobs
);
612 sd_bus_slot_unref(d
->slot_disconnected
);
613 sd_bus_slot_unref(d
->slot_job_removed
);
615 sd_bus_unref(d
->bus
);
623 int bus_wait_for_jobs_new(sd_bus
*bus
, BusWaitForJobs
**ret
) {
624 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*d
= NULL
;
630 d
= new0(BusWaitForJobs
, 1);
634 d
->bus
= sd_bus_ref(bus
);
636 /* When we are a bus client we match by sender. Direct
637 * connections OTOH have no initialized sender field, and
638 * hence we ignore the sender then */
639 r
= sd_bus_add_match(
641 &d
->slot_job_removed
,
644 "sender='org.freedesktop.systemd1',"
645 "interface='org.freedesktop.systemd1.Manager',"
646 "member='JobRemoved',"
647 "path='/org/freedesktop/systemd1'" :
649 "interface='org.freedesktop.systemd1.Manager',"
650 "member='JobRemoved',"
651 "path='/org/freedesktop/systemd1'",
652 match_job_removed
, d
);
656 r
= sd_bus_add_match(
658 &d
->slot_disconnected
,
660 "sender='org.freedesktop.DBus.Local',"
661 "interface='org.freedesktop.DBus.Local',"
662 "member='Disconnected'",
663 match_disconnected
, d
);
673 static int bus_process_wait(sd_bus
*bus
) {
677 r
= sd_bus_process(bus
, NULL
);
683 r
= sd_bus_wait(bus
, (uint64_t) -1);
689 static int bus_job_get_service_result(BusWaitForJobs
*d
, char **result
) {
690 _cleanup_free_
char *dbus_path
= NULL
;
696 dbus_path
= unit_dbus_path_from_name(d
->name
);
700 return sd_bus_get_property_string(d
->bus
,
701 "org.freedesktop.systemd1",
703 "org.freedesktop.systemd1.Service",
709 static const struct {
710 const char *result
, *explanation
;
711 } explanations
[] = {
712 { "resources", "of unavailable resources or another system error" },
713 { "timeout", "a timeout was exceeded" },
714 { "exit-code", "the control process exited with error code" },
715 { "signal", "a fatal signal was delivered to the control process" },
716 { "core-dump", "a fatal signal was delivered causing the control process to dump core" },
717 { "watchdog", "the service failed to send watchdog ping" },
718 { "start-limit", "start of the service was attempted too often" }
721 static void log_job_error_with_service_result(const char* service
, const char *result
, const char* const* extra_args
) {
722 _cleanup_free_
char *service_shell_quoted
= NULL
;
723 const char *systemctl
= "systemctl", *journalctl
= "journalctl";
727 service_shell_quoted
= shell_maybe_quote(service
);
729 if (extra_args
&& extra_args
[1]) {
730 _cleanup_free_
char *t
;
732 t
= strv_join((char**) extra_args
, " ");
733 systemctl
= strjoina("systemctl ", t
? : "<args>");
734 journalctl
= strjoina("journalctl ", t
? : "<args>");
737 if (!isempty(result
)) {
740 for (i
= 0; i
< ELEMENTSOF(explanations
); ++i
)
741 if (streq(result
, explanations
[i
].result
))
744 if (i
< ELEMENTSOF(explanations
)) {
745 log_error("Job for %s failed because %s.\n"
746 "See \"%s status %s\" and \"%s -xe\" for details.\n",
748 explanations
[i
].explanation
,
750 service_shell_quoted
?: "<service>",
756 log_error("Job for %s failed.\n"
757 "See \"%s status %s\" and \"%s -xe\" for details.\n",
760 service_shell_quoted
?: "<service>",
764 /* For some results maybe additional explanation is required */
765 if (streq_ptr(result
, "start-limit"))
766 log_info("To force a start use \"%1$s reset-failed %2$s\"\n"
767 "followed by \"%1$s start %2$s\" again.",
769 service_shell_quoted
?: "<service>");
772 static int check_wait_response(BusWaitForJobs
*d
, bool quiet
, const char* const* extra_args
) {
778 if (streq(d
->result
, "canceled"))
779 log_error("Job for %s canceled.", strna(d
->name
));
780 else if (streq(d
->result
, "timeout"))
781 log_error("Job for %s timed out.", strna(d
->name
));
782 else if (streq(d
->result
, "dependency"))
783 log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d
->name
));
784 else if (streq(d
->result
, "invalid"))
785 log_error("%s is not active, cannot reload.", strna(d
->name
));
786 else if (streq(d
->result
, "assert"))
787 log_error("Assertion failed on job for %s.", strna(d
->name
));
788 else if (streq(d
->result
, "unsupported"))
789 log_error("Operation on or unit type of %s not supported on this system.", strna(d
->name
));
790 else if (!streq(d
->result
, "done") && !streq(d
->result
, "skipped")) {
793 _cleanup_free_
char *result
= NULL
;
795 q
= bus_job_get_service_result(d
, &result
);
797 log_debug_errno(q
, "Failed to get Result property of service %s: %m", d
->name
);
799 log_job_error_with_service_result(d
->name
, result
, extra_args
);
801 log_error("Job failed. See \"journalctl -xe\" for details.");
805 if (streq(d
->result
, "canceled"))
807 else if (streq(d
->result
, "timeout"))
809 else if (streq(d
->result
, "dependency"))
811 else if (streq(d
->result
, "invalid"))
813 else if (streq(d
->result
, "assert"))
815 else if (streq(d
->result
, "unsupported"))
817 else if (!streq(d
->result
, "done") && !streq(d
->result
, "skipped"))
823 int bus_wait_for_jobs(BusWaitForJobs
*d
, bool quiet
, const char* const* extra_args
) {
828 while (!set_isempty(d
->jobs
)) {
831 q
= bus_process_wait(d
->bus
);
833 return log_error_errno(q
, "Failed to wait for response: %m");
836 q
= check_wait_response(d
, quiet
, extra_args
);
837 /* Return the first error as it is most likely to be
842 log_debug_errno(q
, "Got result %s/%m for job %s", strna(d
->result
), strna(d
->name
));
845 d
->name
= mfree(d
->name
);
846 d
->result
= mfree(d
->result
);
852 int bus_wait_for_jobs_add(BusWaitForJobs
*d
, const char *path
) {
857 r
= set_ensure_allocated(&d
->jobs
, &string_hash_ops
);
861 return set_put_strdup(d
->jobs
, path
);
864 int bus_wait_for_jobs_one(BusWaitForJobs
*d
, const char *path
, bool quiet
) {
867 r
= bus_wait_for_jobs_add(d
, path
);
871 return bus_wait_for_jobs(d
, quiet
, NULL
);
874 int bus_deserialize_and_dump_unit_file_changes(sd_bus_message
*m
, bool quiet
, UnitFileChange
**changes
, unsigned *n_changes
) {
875 const char *type
, *path
, *source
;
878 /* changes is dereferenced when calling unit_file_dump_changes() later,
879 * so we have to make sure this is not NULL. */
883 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sss)");
885 return bus_log_parse_error(r
);
887 while ((r
= sd_bus_message_read(m
, "(sss)", &type
, &path
, &source
)) > 0) {
888 /* We expect only "success" changes to be sent over the bus.
889 Hence, reject anything negative. */
890 UnitFileChangeType ch
= unit_file_change_type_from_string(type
);
893 log_notice("Manager reported unknown change type \"%s\" for path \"%s\", ignoring.", type
, path
);
897 r
= unit_file_changes_add(changes
, n_changes
, ch
, path
, source
);
902 return bus_log_parse_error(r
);
904 r
= sd_bus_message_exit_container(m
);
906 return bus_log_parse_error(r
);
908 unit_file_dump_changes(0, NULL
, *changes
, *n_changes
, false);
914 bool is_const
; /* If false, cgroup_path should be free()'d */
916 Hashmap
*pids
; /* PID → process name */
919 struct CGroupInfo
*parent
;
920 LIST_FIELDS(struct CGroupInfo
, siblings
);
921 LIST_HEAD(struct CGroupInfo
, children
);
925 static bool IS_ROOT(const char *p
) {
926 return isempty(p
) || streq(p
, "/");
929 static int add_cgroup(Hashmap
*cgroups
, const char *path
, bool is_const
, struct CGroupInfo
**ret
) {
930 struct CGroupInfo
*parent
= NULL
, *cg
;
939 cg
= hashmap_get(cgroups
, path
);
945 if (!IS_ROOT(path
)) {
948 e
= strrchr(path
, '/');
952 pp
= strndupa(path
, e
- path
);
956 r
= add_cgroup(cgroups
, pp
, false, &parent
);
961 cg
= new0(struct CGroupInfo
, 1);
966 cg
->cgroup_path
= (char*) path
;
968 cg
->cgroup_path
= strdup(path
);
969 if (!cg
->cgroup_path
) {
975 cg
->is_const
= is_const
;
978 r
= hashmap_put(cgroups
, cg
->cgroup_path
, cg
);
981 free(cg
->cgroup_path
);
987 LIST_PREPEND(siblings
, parent
->children
, cg
);
988 parent
->n_children
++;
995 static int add_process(
1001 struct CGroupInfo
*cg
;
1008 r
= add_cgroup(cgroups
, path
, true, &cg
);
1012 r
= hashmap_ensure_allocated(&cg
->pids
, &trivial_hash_ops
);
1016 return hashmap_put(cg
->pids
, PID_TO_PTR(pid
), (void*) name
);
1019 static void remove_cgroup(Hashmap
*cgroups
, struct CGroupInfo
*cg
) {
1023 while (cg
->children
)
1024 remove_cgroup(cgroups
, cg
->children
);
1026 hashmap_remove(cgroups
, cg
->cgroup_path
);
1029 free(cg
->cgroup_path
);
1031 hashmap_free(cg
->pids
);
1034 LIST_REMOVE(siblings
, cg
->parent
->children
, cg
);
1039 static int cgroup_info_compare_func(const void *a
, const void *b
) {
1040 const struct CGroupInfo
*x
= *(const struct CGroupInfo
* const*) a
, *y
= *(const struct CGroupInfo
* const*) b
;
1045 return strcmp(x
->cgroup_path
, y
->cgroup_path
);
1048 static int dump_processes(
1050 const char *cgroup_path
,
1053 OutputFlags flags
) {
1055 struct CGroupInfo
*cg
;
1060 if (IS_ROOT(cgroup_path
))
1063 cg
= hashmap_get(cgroups
, cgroup_path
);
1067 if (!hashmap_isempty(cg
->pids
)) {
1075 /* Order processes by their PID */
1076 pids
= newa(pid_t
, hashmap_size(cg
->pids
));
1078 HASHMAP_FOREACH_KEY(name
, pidp
, cg
->pids
, j
)
1079 pids
[n
++] = PTR_TO_PID(pidp
);
1081 assert(n
== hashmap_size(cg
->pids
));
1082 qsort_safe(pids
, n
, sizeof(pid_t
), pid_compare_func
);
1084 width
= DECIMAL_STR_WIDTH(pids
[n
-1]);
1086 for (i
= 0; i
< n
; i
++) {
1087 _cleanup_free_
char *e
= NULL
;
1088 const char *special
;
1091 name
= hashmap_get(cg
->pids
, PID_TO_PTR(pids
[i
]));
1094 if (n_columns
!= 0) {
1097 k
= MAX(LESS_BY(n_columns
, 2U + width
+ 1U), 20U);
1099 e
= ellipsize(name
, k
, 100);
1104 more
= i
+1 < n
|| cg
->children
;
1105 special
= special_glyph(more
? TREE_BRANCH
: TREE_RIGHT
);
1107 fprintf(stdout
, "%s%s%*"PID_PRI
" %s\n",
1116 struct CGroupInfo
**children
, *child
;
1119 /* Order subcgroups by their name */
1120 children
= newa(struct CGroupInfo
*, cg
->n_children
);
1121 LIST_FOREACH(siblings
, child
, cg
->children
)
1122 children
[n
++] = child
;
1123 assert(n
== cg
->n_children
);
1124 qsort_safe(children
, n
, sizeof(struct CGroupInfo
*), cgroup_info_compare_func
);
1126 n_columns
= MAX(LESS_BY(n_columns
, 2U), 20U);
1128 for (i
= 0; i
< n
; i
++) {
1129 _cleanup_free_
char *pp
= NULL
;
1130 const char *name
, *special
;
1133 child
= children
[i
];
1135 name
= strrchr(child
->cgroup_path
, '/');
1141 special
= special_glyph(more
? TREE_BRANCH
: TREE_RIGHT
);
1143 fputs(prefix
, stdout
);
1144 fputs(special
, stdout
);
1145 fputs(name
, stdout
);
1146 fputc('\n', stdout
);
1148 special
= special_glyph(more
? TREE_VERTICAL
: TREE_SPACE
);
1150 pp
= strappend(prefix
, special
);
1154 r
= dump_processes(cgroups
, child
->cgroup_path
, pp
, n_columns
, flags
);
1164 static int dump_extra_processes(
1168 OutputFlags flags
) {
1170 _cleanup_free_ pid_t
*pids
= NULL
;
1171 _cleanup_hashmap_free_ Hashmap
*names
= NULL
;
1172 struct CGroupInfo
*cg
;
1173 size_t n_allocated
= 0, n
= 0, k
;
1177 /* Prints the extra processes, i.e. those that are in cgroups we haven't displayed yet. We show them as
1178 * combined, sorted, linear list. */
1180 HASHMAP_FOREACH(cg
, cgroups
, i
) {
1188 if (hashmap_isempty(cg
->pids
))
1191 r
= hashmap_ensure_allocated(&names
, &trivial_hash_ops
);
1195 if (!GREEDY_REALLOC(pids
, n_allocated
, n
+ hashmap_size(cg
->pids
)))
1198 HASHMAP_FOREACH_KEY(name
, pidp
, cg
->pids
, j
) {
1199 pids
[n
++] = PTR_TO_PID(pidp
);
1201 r
= hashmap_put(names
, pidp
, (void*) name
);
1210 qsort_safe(pids
, n
, sizeof(pid_t
), pid_compare_func
);
1211 width
= DECIMAL_STR_WIDTH(pids
[n
-1]);
1213 for (k
= 0; k
< n
; k
++) {
1214 _cleanup_free_
char *e
= NULL
;
1217 name
= hashmap_get(names
, PID_TO_PTR(pids
[k
]));
1220 if (n_columns
!= 0) {
1223 z
= MAX(LESS_BY(n_columns
, 2U + width
+ 1U), 20U);
1225 e
= ellipsize(name
, z
, 100);
1230 fprintf(stdout
, "%s%s %*" PID_PRI
" %s\n",
1232 special_glyph(TRIANGULAR_BULLET
),
1240 int unit_show_processes(
1243 const char *cgroup_path
,
1247 sd_bus_error
*error
) {
1249 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1250 Hashmap
*cgroups
= NULL
;
1251 struct CGroupInfo
*cg
;
1257 if (flags
& OUTPUT_FULL_WIDTH
)
1259 else if (n_columns
<= 0)
1260 n_columns
= columns();
1262 prefix
= strempty(prefix
);
1264 r
= sd_bus_call_method(
1266 "org.freedesktop.systemd1",
1267 "/org/freedesktop/systemd1",
1268 "org.freedesktop.systemd1.Manager",
1277 cgroups
= hashmap_new(&string_hash_ops
);
1281 r
= sd_bus_message_enter_container(reply
, 'a', "(sus)");
1286 const char *path
= NULL
, *name
= NULL
;
1289 r
= sd_bus_message_read(reply
, "(sus)", &path
, &pid
, &name
);
1295 r
= add_process(cgroups
, path
, pid
, name
);
1300 r
= sd_bus_message_exit_container(reply
);
1304 r
= dump_processes(cgroups
, cgroup_path
, prefix
, n_columns
, flags
);
1308 r
= dump_extra_processes(cgroups
, prefix
, n_columns
, flags
);
1311 while ((cg
= hashmap_first(cgroups
)))
1312 remove_cgroup(cgroups
, cg
);
1314 hashmap_free(cgroups
);