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",
457 "ReadWritePaths", "ReadOnlyPaths", "InaccessiblePaths")) {
460 r
= sd_bus_message_open_container(m
, 'v', "as");
462 return bus_log_create_error(r
);
464 r
= sd_bus_message_open_container(m
, 'a', "s");
466 return bus_log_create_error(r
);
471 _cleanup_free_
char *word
= NULL
;
474 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
);
476 log_error("Failed to parse %s value %s", field
, eq
);
482 if (!utf8_is_valid(word
)) {
483 log_error("Failed to parse %s value %s", field
, eq
);
487 offset
= word
[0] == '-';
488 if (!path_is_absolute(word
+ offset
)) {
489 log_error("Failed to parse %s value %s", field
, eq
);
493 path_kill_slashes(word
+ offset
);
495 r
= sd_bus_message_append_basic(m
, 's', word
);
497 return bus_log_create_error(r
);
500 r
= sd_bus_message_close_container(m
);
502 return bus_log_create_error(r
);
504 r
= sd_bus_message_close_container(m
);
506 } else if (streq(field
, "RuntimeDirectory")) {
509 r
= sd_bus_message_open_container(m
, 'v', "as");
511 return bus_log_create_error(r
);
513 r
= sd_bus_message_open_container(m
, 'a', "s");
515 return bus_log_create_error(r
);
520 _cleanup_free_
char *word
= NULL
;
522 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
);
524 return log_error_errno(r
, "Failed to parse %s value %s", field
, eq
);
529 r
= sd_bus_message_append_basic(m
, 's', word
);
531 return bus_log_create_error(r
);
534 r
= sd_bus_message_close_container(m
);
536 return bus_log_create_error(r
);
538 r
= sd_bus_message_close_container(m
);
541 log_error("Unknown assignment %s.", assignment
);
547 return bus_log_create_error(r
);
549 r
= sd_bus_message_close_container(m
);
551 return bus_log_create_error(r
);
556 typedef struct BusWaitForJobs
{
563 sd_bus_slot
*slot_job_removed
;
564 sd_bus_slot
*slot_disconnected
;
567 static int match_disconnected(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
570 log_error("Warning! D-Bus connection terminated.");
571 sd_bus_close(sd_bus_message_get_bus(m
));
576 static int match_job_removed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
577 const char *path
, *unit
, *result
;
578 BusWaitForJobs
*d
= userdata
;
586 r
= sd_bus_message_read(m
, "uoss", &id
, &path
, &unit
, &result
);
588 bus_log_parse_error(r
);
592 found
= set_remove(d
->jobs
, (char*) path
);
598 if (!isempty(result
))
599 d
->result
= strdup(result
);
602 d
->name
= strdup(unit
);
607 void bus_wait_for_jobs_free(BusWaitForJobs
*d
) {
611 set_free_free(d
->jobs
);
613 sd_bus_slot_unref(d
->slot_disconnected
);
614 sd_bus_slot_unref(d
->slot_job_removed
);
616 sd_bus_unref(d
->bus
);
624 int bus_wait_for_jobs_new(sd_bus
*bus
, BusWaitForJobs
**ret
) {
625 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*d
= NULL
;
631 d
= new0(BusWaitForJobs
, 1);
635 d
->bus
= sd_bus_ref(bus
);
637 /* When we are a bus client we match by sender. Direct
638 * connections OTOH have no initialized sender field, and
639 * hence we ignore the sender then */
640 r
= sd_bus_add_match(
642 &d
->slot_job_removed
,
645 "sender='org.freedesktop.systemd1',"
646 "interface='org.freedesktop.systemd1.Manager',"
647 "member='JobRemoved',"
648 "path='/org/freedesktop/systemd1'" :
650 "interface='org.freedesktop.systemd1.Manager',"
651 "member='JobRemoved',"
652 "path='/org/freedesktop/systemd1'",
653 match_job_removed
, d
);
657 r
= sd_bus_add_match(
659 &d
->slot_disconnected
,
661 "sender='org.freedesktop.DBus.Local',"
662 "interface='org.freedesktop.DBus.Local',"
663 "member='Disconnected'",
664 match_disconnected
, d
);
674 static int bus_process_wait(sd_bus
*bus
) {
678 r
= sd_bus_process(bus
, NULL
);
684 r
= sd_bus_wait(bus
, (uint64_t) -1);
690 static int bus_job_get_service_result(BusWaitForJobs
*d
, char **result
) {
691 _cleanup_free_
char *dbus_path
= NULL
;
697 dbus_path
= unit_dbus_path_from_name(d
->name
);
701 return sd_bus_get_property_string(d
->bus
,
702 "org.freedesktop.systemd1",
704 "org.freedesktop.systemd1.Service",
710 static const struct {
711 const char *result
, *explanation
;
712 } explanations
[] = {
713 { "resources", "of unavailable resources or another system error" },
714 { "timeout", "a timeout was exceeded" },
715 { "exit-code", "the control process exited with error code" },
716 { "signal", "a fatal signal was delivered to the control process" },
717 { "core-dump", "a fatal signal was delivered causing the control process to dump core" },
718 { "watchdog", "the service failed to send watchdog ping" },
719 { "start-limit", "start of the service was attempted too often" }
722 static void log_job_error_with_service_result(const char* service
, const char *result
, const char* const* extra_args
) {
723 _cleanup_free_
char *service_shell_quoted
= NULL
;
724 const char *systemctl
= "systemctl", *journalctl
= "journalctl";
728 service_shell_quoted
= shell_maybe_quote(service
);
730 if (extra_args
&& extra_args
[1]) {
731 _cleanup_free_
char *t
;
733 t
= strv_join((char**) extra_args
, " ");
734 systemctl
= strjoina("systemctl ", t
? : "<args>");
735 journalctl
= strjoina("journalctl ", t
? : "<args>");
738 if (!isempty(result
)) {
741 for (i
= 0; i
< ELEMENTSOF(explanations
); ++i
)
742 if (streq(result
, explanations
[i
].result
))
745 if (i
< ELEMENTSOF(explanations
)) {
746 log_error("Job for %s failed because %s.\n"
747 "See \"%s status %s\" and \"%s -xe\" for details.\n",
749 explanations
[i
].explanation
,
751 service_shell_quoted
?: "<service>",
757 log_error("Job for %s failed.\n"
758 "See \"%s status %s\" and \"%s -xe\" for details.\n",
761 service_shell_quoted
?: "<service>",
765 /* For some results maybe additional explanation is required */
766 if (streq_ptr(result
, "start-limit"))
767 log_info("To force a start use \"%1$s reset-failed %2$s\"\n"
768 "followed by \"%1$s start %2$s\" again.",
770 service_shell_quoted
?: "<service>");
773 static int check_wait_response(BusWaitForJobs
*d
, bool quiet
, const char* const* extra_args
) {
779 if (streq(d
->result
, "canceled"))
780 log_error("Job for %s canceled.", strna(d
->name
));
781 else if (streq(d
->result
, "timeout"))
782 log_error("Job for %s timed out.", strna(d
->name
));
783 else if (streq(d
->result
, "dependency"))
784 log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d
->name
));
785 else if (streq(d
->result
, "invalid"))
786 log_error("%s is not active, cannot reload.", strna(d
->name
));
787 else if (streq(d
->result
, "assert"))
788 log_error("Assertion failed on job for %s.", strna(d
->name
));
789 else if (streq(d
->result
, "unsupported"))
790 log_error("Operation on or unit type of %s not supported on this system.", strna(d
->name
));
791 else if (!streq(d
->result
, "done") && !streq(d
->result
, "skipped")) {
794 _cleanup_free_
char *result
= NULL
;
796 q
= bus_job_get_service_result(d
, &result
);
798 log_debug_errno(q
, "Failed to get Result property of service %s: %m", d
->name
);
800 log_job_error_with_service_result(d
->name
, result
, extra_args
);
802 log_error("Job failed. See \"journalctl -xe\" for details.");
806 if (streq(d
->result
, "canceled"))
808 else if (streq(d
->result
, "timeout"))
810 else if (streq(d
->result
, "dependency"))
812 else if (streq(d
->result
, "invalid"))
814 else if (streq(d
->result
, "assert"))
816 else if (streq(d
->result
, "unsupported"))
818 else if (!streq(d
->result
, "done") && !streq(d
->result
, "skipped"))
824 int bus_wait_for_jobs(BusWaitForJobs
*d
, bool quiet
, const char* const* extra_args
) {
829 while (!set_isempty(d
->jobs
)) {
832 q
= bus_process_wait(d
->bus
);
834 return log_error_errno(q
, "Failed to wait for response: %m");
837 q
= check_wait_response(d
, quiet
, extra_args
);
838 /* Return the first error as it is most likely to be
843 log_debug_errno(q
, "Got result %s/%m for job %s", strna(d
->result
), strna(d
->name
));
846 d
->name
= mfree(d
->name
);
847 d
->result
= mfree(d
->result
);
853 int bus_wait_for_jobs_add(BusWaitForJobs
*d
, const char *path
) {
858 r
= set_ensure_allocated(&d
->jobs
, &string_hash_ops
);
862 return set_put_strdup(d
->jobs
, path
);
865 int bus_wait_for_jobs_one(BusWaitForJobs
*d
, const char *path
, bool quiet
) {
868 r
= bus_wait_for_jobs_add(d
, path
);
872 return bus_wait_for_jobs(d
, quiet
, NULL
);
875 int bus_deserialize_and_dump_unit_file_changes(sd_bus_message
*m
, bool quiet
, UnitFileChange
**changes
, unsigned *n_changes
) {
876 const char *type
, *path
, *source
;
879 /* changes is dereferenced when calling unit_file_dump_changes() later,
880 * so we have to make sure this is not NULL. */
884 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "(sss)");
886 return bus_log_parse_error(r
);
888 while ((r
= sd_bus_message_read(m
, "(sss)", &type
, &path
, &source
)) > 0) {
889 /* We expect only "success" changes to be sent over the bus.
890 Hence, reject anything negative. */
891 UnitFileChangeType ch
= unit_file_change_type_from_string(type
);
894 log_notice("Manager reported unknown change type \"%s\" for path \"%s\", ignoring.", type
, path
);
898 r
= unit_file_changes_add(changes
, n_changes
, ch
, path
, source
);
903 return bus_log_parse_error(r
);
905 r
= sd_bus_message_exit_container(m
);
907 return bus_log_parse_error(r
);
909 unit_file_dump_changes(0, NULL
, *changes
, *n_changes
, false);
915 bool is_const
; /* If false, cgroup_path should be free()'d */
917 Hashmap
*pids
; /* PID → process name */
920 struct CGroupInfo
*parent
;
921 LIST_FIELDS(struct CGroupInfo
, siblings
);
922 LIST_HEAD(struct CGroupInfo
, children
);
926 static bool IS_ROOT(const char *p
) {
927 return isempty(p
) || streq(p
, "/");
930 static int add_cgroup(Hashmap
*cgroups
, const char *path
, bool is_const
, struct CGroupInfo
**ret
) {
931 struct CGroupInfo
*parent
= NULL
, *cg
;
940 cg
= hashmap_get(cgroups
, path
);
946 if (!IS_ROOT(path
)) {
949 e
= strrchr(path
, '/');
953 pp
= strndupa(path
, e
- path
);
957 r
= add_cgroup(cgroups
, pp
, false, &parent
);
962 cg
= new0(struct CGroupInfo
, 1);
967 cg
->cgroup_path
= (char*) path
;
969 cg
->cgroup_path
= strdup(path
);
970 if (!cg
->cgroup_path
) {
976 cg
->is_const
= is_const
;
979 r
= hashmap_put(cgroups
, cg
->cgroup_path
, cg
);
982 free(cg
->cgroup_path
);
988 LIST_PREPEND(siblings
, parent
->children
, cg
);
989 parent
->n_children
++;
996 static int add_process(
1002 struct CGroupInfo
*cg
;
1009 r
= add_cgroup(cgroups
, path
, true, &cg
);
1013 r
= hashmap_ensure_allocated(&cg
->pids
, &trivial_hash_ops
);
1017 return hashmap_put(cg
->pids
, PID_TO_PTR(pid
), (void*) name
);
1020 static void remove_cgroup(Hashmap
*cgroups
, struct CGroupInfo
*cg
) {
1024 while (cg
->children
)
1025 remove_cgroup(cgroups
, cg
->children
);
1027 hashmap_remove(cgroups
, cg
->cgroup_path
);
1030 free(cg
->cgroup_path
);
1032 hashmap_free(cg
->pids
);
1035 LIST_REMOVE(siblings
, cg
->parent
->children
, cg
);
1040 static int cgroup_info_compare_func(const void *a
, const void *b
) {
1041 const struct CGroupInfo
*x
= *(const struct CGroupInfo
* const*) a
, *y
= *(const struct CGroupInfo
* const*) b
;
1046 return strcmp(x
->cgroup_path
, y
->cgroup_path
);
1049 static int dump_processes(
1051 const char *cgroup_path
,
1054 OutputFlags flags
) {
1056 struct CGroupInfo
*cg
;
1061 if (IS_ROOT(cgroup_path
))
1064 cg
= hashmap_get(cgroups
, cgroup_path
);
1068 if (!hashmap_isempty(cg
->pids
)) {
1076 /* Order processes by their PID */
1077 pids
= newa(pid_t
, hashmap_size(cg
->pids
));
1079 HASHMAP_FOREACH_KEY(name
, pidp
, cg
->pids
, j
)
1080 pids
[n
++] = PTR_TO_PID(pidp
);
1082 assert(n
== hashmap_size(cg
->pids
));
1083 qsort_safe(pids
, n
, sizeof(pid_t
), pid_compare_func
);
1085 width
= DECIMAL_STR_WIDTH(pids
[n
-1]);
1087 for (i
= 0; i
< n
; i
++) {
1088 _cleanup_free_
char *e
= NULL
;
1089 const char *special
;
1092 name
= hashmap_get(cg
->pids
, PID_TO_PTR(pids
[i
]));
1095 if (n_columns
!= 0) {
1098 k
= MAX(LESS_BY(n_columns
, 2U + width
+ 1U), 20U);
1100 e
= ellipsize(name
, k
, 100);
1105 more
= i
+1 < n
|| cg
->children
;
1106 special
= special_glyph(more
? TREE_BRANCH
: TREE_RIGHT
);
1108 fprintf(stdout
, "%s%s%*"PID_PRI
" %s\n",
1117 struct CGroupInfo
**children
, *child
;
1120 /* Order subcgroups by their name */
1121 children
= newa(struct CGroupInfo
*, cg
->n_children
);
1122 LIST_FOREACH(siblings
, child
, cg
->children
)
1123 children
[n
++] = child
;
1124 assert(n
== cg
->n_children
);
1125 qsort_safe(children
, n
, sizeof(struct CGroupInfo
*), cgroup_info_compare_func
);
1128 n_columns
= MAX(LESS_BY(n_columns
, 2U), 20U);
1130 for (i
= 0; i
< n
; i
++) {
1131 _cleanup_free_
char *pp
= NULL
;
1132 const char *name
, *special
;
1135 child
= children
[i
];
1137 name
= strrchr(child
->cgroup_path
, '/');
1143 special
= special_glyph(more
? TREE_BRANCH
: TREE_RIGHT
);
1145 fputs(prefix
, stdout
);
1146 fputs(special
, stdout
);
1147 fputs(name
, stdout
);
1148 fputc('\n', stdout
);
1150 special
= special_glyph(more
? TREE_VERTICAL
: TREE_SPACE
);
1152 pp
= strappend(prefix
, special
);
1156 r
= dump_processes(cgroups
, child
->cgroup_path
, pp
, n_columns
, flags
);
1166 static int dump_extra_processes(
1170 OutputFlags flags
) {
1172 _cleanup_free_ pid_t
*pids
= NULL
;
1173 _cleanup_hashmap_free_ Hashmap
*names
= NULL
;
1174 struct CGroupInfo
*cg
;
1175 size_t n_allocated
= 0, n
= 0, k
;
1179 /* Prints the extra processes, i.e. those that are in cgroups we haven't displayed yet. We show them as
1180 * combined, sorted, linear list. */
1182 HASHMAP_FOREACH(cg
, cgroups
, i
) {
1190 if (hashmap_isempty(cg
->pids
))
1193 r
= hashmap_ensure_allocated(&names
, &trivial_hash_ops
);
1197 if (!GREEDY_REALLOC(pids
, n_allocated
, n
+ hashmap_size(cg
->pids
)))
1200 HASHMAP_FOREACH_KEY(name
, pidp
, cg
->pids
, j
) {
1201 pids
[n
++] = PTR_TO_PID(pidp
);
1203 r
= hashmap_put(names
, pidp
, (void*) name
);
1212 qsort_safe(pids
, n
, sizeof(pid_t
), pid_compare_func
);
1213 width
= DECIMAL_STR_WIDTH(pids
[n
-1]);
1215 for (k
= 0; k
< n
; k
++) {
1216 _cleanup_free_
char *e
= NULL
;
1219 name
= hashmap_get(names
, PID_TO_PTR(pids
[k
]));
1222 if (n_columns
!= 0) {
1225 z
= MAX(LESS_BY(n_columns
, 2U + width
+ 1U), 20U);
1227 e
= ellipsize(name
, z
, 100);
1232 fprintf(stdout
, "%s%s %*" PID_PRI
" %s\n",
1234 special_glyph(TRIANGULAR_BULLET
),
1242 int unit_show_processes(
1245 const char *cgroup_path
,
1249 sd_bus_error
*error
) {
1251 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1252 Hashmap
*cgroups
= NULL
;
1253 struct CGroupInfo
*cg
;
1259 if (flags
& OUTPUT_FULL_WIDTH
)
1261 else if (n_columns
<= 0)
1262 n_columns
= columns();
1264 prefix
= strempty(prefix
);
1266 r
= sd_bus_call_method(
1268 "org.freedesktop.systemd1",
1269 "/org/freedesktop/systemd1",
1270 "org.freedesktop.systemd1.Manager",
1279 cgroups
= hashmap_new(&string_hash_ops
);
1283 r
= sd_bus_message_enter_container(reply
, 'a', "(sus)");
1288 const char *path
= NULL
, *name
= NULL
;
1291 r
= sd_bus_message_read(reply
, "(sus)", &path
, &pid
, &name
);
1297 r
= add_process(cgroups
, path
, pid
, name
);
1302 r
= sd_bus_message_exit_container(reply
);
1306 r
= dump_processes(cgroups
, cgroup_path
, prefix
, n_columns
, flags
);
1310 r
= dump_extra_processes(cgroups
, prefix
, n_columns
, flags
);
1313 while ((cg
= hashmap_first(cgroups
)))
1314 remove_cgroup(cgroups
, cg
);
1316 hashmap_free(cgroups
);