1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <netinet/in.h>
10 #include <sys/mount.h>
11 #include <sys/socket.h>
16 #include "alloc-util.h"
18 #include "bus-common-errors.h"
19 #include "bus-error.h"
20 #include "bus-locator.h"
21 #include "bus-map-properties.h"
22 #include "bus-print-properties.h"
23 #include "bus-unit-procs.h"
24 #include "bus-unit-util.h"
25 #include "bus-wait-for-jobs.h"
26 #include "cgroup-show.h"
27 #include "cgroup-util.h"
28 #include "constants.h"
30 #include "edit-util.h"
33 #include "format-table.h"
34 #include "hostname-util.h"
35 #include "import-util.h"
36 #include "locale-util.h"
38 #include "logs-show.h"
39 #include "machine-dbus.h"
41 #include "main-func.h"
43 #include "nulstr-util.h"
45 #include "parse-argument.h"
46 #include "parse-util.h"
47 #include "path-util.h"
48 #include "pretty-print.h"
49 #include "process-util.h"
51 #include "rlimit-util.h"
53 #include "signal-util.h"
54 #include "sort-util.h"
55 #include "spawn-ask-password-agent.h"
56 #include "spawn-polkit-agent.h"
57 #include "stdio-util.h"
58 #include "string-table.h"
60 #include "terminal-util.h"
61 #include "unit-name.h"
65 static char **arg_property
= NULL
;
66 static bool arg_all
= false;
67 static BusPrintPropertyFlags arg_print_flags
= 0;
68 static bool arg_full
= false;
69 static PagerFlags arg_pager_flags
= 0;
70 static bool arg_legend
= true;
71 static const char *arg_kill_whom
= NULL
;
72 static int arg_signal
= SIGTERM
;
73 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
74 static const char *arg_host
= NULL
;
75 static bool arg_read_only
= false;
76 static bool arg_mkdir
= false;
77 static bool arg_quiet
= false;
78 static bool arg_ask_password
= true;
79 static unsigned arg_lines
= 10;
80 static OutputMode arg_output
= OUTPUT_SHORT
;
81 static bool arg_now
= false;
82 static bool arg_force
= false;
83 static ImportVerify arg_verify
= IMPORT_VERIFY_SIGNATURE
;
84 static const char* arg_format
= NULL
;
85 static const char *arg_uid
= NULL
;
86 static char **arg_setenv
= NULL
;
87 static unsigned arg_max_addresses
= 1;
89 STATIC_DESTRUCTOR_REGISTER(arg_property
, strv_freep
);
90 STATIC_DESTRUCTOR_REGISTER(arg_setenv
, strv_freep
);
92 static OutputFlags
get_output_flags(void) {
94 FLAGS_SET(arg_print_flags
, BUS_PRINT_PROPERTY_SHOW_EMPTY
) * OUTPUT_SHOW_ALL
|
95 (arg_full
|| !on_tty() || pager_have()) * OUTPUT_FULL_WIDTH
|
96 colors_enabled() * OUTPUT_COLOR
|
97 !arg_quiet
* OUTPUT_WARN_CUTOFF
;
100 static int call_get_os_release(sd_bus
*bus
, const char *method
, const char *name
, const char *query
, ...) {
101 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
102 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
103 const char *k
, *v
, **query_res
= NULL
;
104 size_t count
= 0, awaited_args
= 0;
112 NULSTR_FOREACH(iter
, query
)
114 query_res
= newa0(const char *, awaited_args
);
116 r
= bus_call_method(bus
, bus_machine_mgr
, method
, &error
, &reply
, "s", name
);
118 return log_debug_errno(r
, "Failed to call '%s()': %s", method
, bus_error_message(&error
, r
));
120 r
= sd_bus_message_enter_container(reply
, 'a', "{ss}");
122 return bus_log_parse_error(r
);
124 while ((r
= sd_bus_message_read(reply
, "{ss}", &k
, &v
)) > 0) {
126 NULSTR_FOREACH(iter
, query
) {
127 if (streq(k
, iter
)) {
128 query_res
[count
] = v
;
135 return bus_log_parse_error(r
);
137 r
= sd_bus_message_exit_container(reply
);
139 return bus_log_parse_error(r
);
142 for (count
= 0; count
< awaited_args
; count
++) {
145 out
= va_arg(ap
, char **);
147 if (query_res
[count
]) {
148 val
= strdup(query_res
[count
]);
161 static int call_get_addresses(
169 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
170 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
171 _cleanup_free_
char *addresses
= NULL
;
180 r
= bus_call_method(bus
, bus_machine_mgr
, "GetMachineAddresses", NULL
, &reply
, "s", name
);
182 return log_debug_errno(r
, "Could not get addresses: %s", bus_error_message(&error
, r
));
184 addresses
= strdup(prefix
);
189 r
= sd_bus_message_enter_container(reply
, 'a', "(iay)");
191 return bus_log_parse_error(r
);
193 while ((r
= sd_bus_message_enter_container(reply
, 'r', "iay")) > 0) {
197 char buf_ifi
[1 + DECIMAL_STR_MAX(int)] = "";
199 r
= sd_bus_message_read(reply
, "i", &family
);
201 return bus_log_parse_error(r
);
203 r
= sd_bus_message_read_array(reply
, 'y', &a
, &sz
);
205 return bus_log_parse_error(r
);
207 if (family
== AF_INET6
&& ifi
> 0)
208 xsprintf(buf_ifi
, "%%%i", ifi
);
210 if (!strextend(&addresses
, prefix
, IN_ADDR_TO_STRING(family
, a
), buf_ifi
))
213 r
= sd_bus_message_exit_container(reply
);
215 return bus_log_parse_error(r
);
222 return bus_log_parse_error(r
);
224 r
= sd_bus_message_exit_container(reply
);
226 return bus_log_parse_error(r
);
228 *ret
= TAKE_PTR(addresses
);
232 static int show_table(Table
*table
, const char *word
) {
238 if (table_get_rows(table
) > 1 || OUTPUT_MODE_IS_JSON(arg_output
)) {
239 r
= table_set_sort(table
, (size_t) 0);
241 return table_log_sort_error(r
);
243 table_set_header(table
, arg_legend
);
245 if (OUTPUT_MODE_IS_JSON(arg_output
))
246 r
= table_print_json(table
, NULL
, output_mode_to_json_format_flags(arg_output
) | JSON_FORMAT_COLOR_AUTO
);
248 r
= table_print(table
, NULL
);
250 return table_log_print_error(r
);
254 if (table_get_rows(table
) > 1)
255 printf("\n%zu %s listed.\n", table_get_rows(table
) - 1, word
);
257 printf("No %s.\n", word
);
263 static int list_machines(int argc
, char *argv
[], void *userdata
) {
264 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
265 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
266 _cleanup_(table_unrefp
) Table
*table
= NULL
;
267 sd_bus
*bus
= ASSERT_PTR(userdata
);
270 pager_open(arg_pager_flags
);
272 r
= bus_call_method(bus
, bus_machine_mgr
, "ListMachines", &error
, &reply
, NULL
);
274 return log_error_errno(r
, "Could not get machines: %s", bus_error_message(&error
, r
));
276 table
= table_new("machine", "class", "service", "os", "version",
277 arg_max_addresses
> 0 ? "addresses" : NULL
);
281 table_set_ersatz_string(table
, TABLE_ERSATZ_DASH
);
282 if (!arg_full
&& arg_max_addresses
> 0 && arg_max_addresses
< UINT_MAX
)
283 table_set_cell_height_max(table
, arg_max_addresses
);
286 table_set_width(table
, 0);
288 r
= sd_bus_message_enter_container(reply
, 'a', "(ssso)");
290 return bus_log_parse_error(r
);
293 _cleanup_free_
char *os
= NULL
, *version_id
= NULL
, *addresses
= NULL
;
294 const char *name
, *class, *service
;
296 r
= sd_bus_message_read(reply
, "(ssso)", &name
, &class, &service
, NULL
);
298 return bus_log_parse_error(r
);
302 if (name
[0] == '.' && !arg_all
)
305 (void) call_get_os_release(
307 "GetMachineOSRelease",
314 r
= table_add_many(table
,
315 TABLE_STRING
, empty_to_null(name
),
316 TABLE_STRING
, empty_to_null(class),
317 TABLE_STRING
, empty_to_null(service
),
318 TABLE_STRING
, empty_to_null(os
),
319 TABLE_STRING
, empty_to_null(version_id
));
321 return table_log_add_error(r
);
323 if (arg_max_addresses
> 0) {
324 (void) call_get_addresses(bus
, name
, 0, "", "\n", &addresses
);
326 r
= table_add_many(table
,
327 TABLE_STRING
, empty_to_null(addresses
));
329 return table_log_add_error(r
);
333 r
= sd_bus_message_exit_container(reply
);
335 return bus_log_parse_error(r
);
337 return show_table(table
, "machines");
340 static int list_images(int argc
, char *argv
[], void *userdata
) {
342 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
343 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
344 _cleanup_(table_unrefp
) Table
*table
= NULL
;
345 sd_bus
*bus
= ASSERT_PTR(userdata
);
348 pager_open(arg_pager_flags
);
350 r
= bus_call_method(bus
, bus_machine_mgr
, "ListImages", &error
, &reply
, NULL
);
352 return log_error_errno(r
, "Could not get images: %s", bus_error_message(&error
, r
));
354 table
= table_new("name", "type", "ro", "usage", "created", "modified");
359 table_set_width(table
, 0);
361 (void) table_set_align_percent(table
, TABLE_HEADER_CELL(3), 100);
363 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssbttto)");
365 return bus_log_parse_error(r
);
368 uint64_t crtime
, mtime
, size
;
369 const char *name
, *type
;
372 r
= sd_bus_message_read(reply
, "(ssbttto)", &name
, &type
, &ro_int
, &crtime
, &mtime
, &size
, NULL
);
374 return bus_log_parse_error(r
);
378 if (name
[0] == '.' && !arg_all
)
381 r
= table_add_many(table
,
384 TABLE_BOOLEAN
, ro_int
,
385 TABLE_SET_COLOR
, ro_int
? ansi_highlight_red() : NULL
,
387 TABLE_TIMESTAMP
, crtime
,
388 TABLE_TIMESTAMP
, mtime
);
390 return table_log_add_error(r
);
393 r
= sd_bus_message_exit_container(reply
);
395 return bus_log_parse_error(r
);
397 return show_table(table
, "images");
400 static int show_unit_cgroup(sd_bus
*bus
, const char *unit
, pid_t leader
) {
401 _cleanup_free_
char *cgroup
= NULL
;
402 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
409 r
= show_cgroup_get_unit_path_and_warn(bus
, unit
, &cgroup
);
422 r
= unit_show_processes(bus
, unit
, cgroup
, "\t\t ", c
, get_output_flags(), &error
);
425 if (arg_transport
== BUS_TRANSPORT_REMOTE
)
428 /* Fallback for older systemd versions where the GetUnitProcesses() call is not yet available */
430 if (cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, cgroup
) != 0 && leader
<= 0)
433 show_cgroup_and_extra(SYSTEMD_CGROUP_CONTROLLER
, cgroup
, "\t\t ", c
, &leader
, leader
> 0, get_output_flags());
435 return log_error_errno(r
, "Failed to dump process list: %s", bus_error_message(&error
, r
));
440 static int print_os_release(sd_bus
*bus
, const char *method
, const char *name
, const char *prefix
) {
441 _cleanup_free_
char *pretty
= NULL
;
448 r
= call_get_os_release(bus
, method
, name
, "PRETTY_NAME\0", &pretty
, NULL
);
453 printf("%s%s\n", prefix
, pretty
);
458 static int print_uid_shift(sd_bus
*bus
, const char *name
) {
459 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
460 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
467 r
= bus_call_method(bus
, bus_machine_mgr
, "GetMachineUIDShift", &error
, &reply
, "s", name
);
469 return log_debug_errno(r
, "Failed to query UID/GID shift: %s", bus_error_message(&error
, r
));
471 r
= sd_bus_message_read(reply
, "u", &shift
);
475 if (shift
== 0) /* Don't show trivial mappings */
478 printf(" UID Shift: %" PRIu32
"\n", shift
);
482 typedef struct MachineStatusInfo
{
488 const char *root_directory
;
490 struct dual_timestamp timestamp
;
495 static void machine_status_info_clear(MachineStatusInfo
*info
) {
502 static void print_machine_status_info(sd_bus
*bus
, MachineStatusInfo
*i
) {
503 _cleanup_free_
char *addresses
= NULL
, *s1
= NULL
, *s2
= NULL
;
509 fputs(strna(i
->name
), stdout
);
511 if (!sd_id128_is_null(i
->id
))
512 printf("(" SD_ID128_FORMAT_STR
")\n", SD_ID128_FORMAT_VAL(i
->id
));
516 s1
= strdup(strempty(FORMAT_TIMESTAMP_RELATIVE(i
->timestamp
.realtime
)));
517 s2
= strdup(strempty(FORMAT_TIMESTAMP(i
->timestamp
.realtime
)));
520 printf("\t Since: %s; %s\n", strna(s2
), s1
);
521 else if (!isempty(s2
))
522 printf("\t Since: %s\n", s2
);
525 _cleanup_free_
char *t
= NULL
;
527 printf("\t Leader: %u", (unsigned) i
->leader
);
529 (void) pid_get_comm(i
->leader
, &t
);
537 printf("\t Service: %s", i
->service
);
540 printf("; class %s", i
->class);
544 printf("\t Class: %s\n", i
->class);
546 if (i
->root_directory
)
547 printf("\t Root: %s\n", i
->root_directory
);
549 if (i
->n_netif
> 0) {
550 fputs("\t Iface:", stdout
);
552 for (size_t c
= 0; c
< i
->n_netif
; c
++) {
553 char name
[IF_NAMESIZE
];
555 if (format_ifname(i
->netif
[c
], name
) >= 0) {
564 printf(" %i", i
->netif
[c
]);
570 if (call_get_addresses(bus
, i
->name
, ifi
,
571 "\t Address: ", "\n\t ",
573 fputs(addresses
, stdout
);
577 print_os_release(bus
, "GetMachineOSRelease", i
->name
, "\t OS: ");
579 print_uid_shift(bus
, i
->name
);
582 printf("\t Unit: %s\n", i
->unit
);
583 show_unit_cgroup(bus
, i
->unit
, i
->leader
);
585 if (arg_transport
== BUS_TRANSPORT_LOCAL
)
587 show_journal_by_unit(
593 i
->timestamp
.monotonic
,
596 get_output_flags() | OUTPUT_BEGIN_NEWLINE
,
597 SD_JOURNAL_LOCAL_ONLY
,
603 static int map_netif(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
604 MachineStatusInfo
*i
= userdata
;
609 assert_cc(sizeof(int32_t) == sizeof(int));
610 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_INT32
, &v
, &l
);
616 i
->n_netif
= l
/ sizeof(int32_t);
617 i
->netif
= memdup(v
, l
);
624 static int show_machine_info(const char *verb
, sd_bus
*bus
, const char *path
, bool *new_line
) {
626 static const struct bus_properties_map map
[] = {
627 { "Name", "s", NULL
, offsetof(MachineStatusInfo
, name
) },
628 { "Class", "s", NULL
, offsetof(MachineStatusInfo
, class) },
629 { "Service", "s", NULL
, offsetof(MachineStatusInfo
, service
) },
630 { "Unit", "s", NULL
, offsetof(MachineStatusInfo
, unit
) },
631 { "RootDirectory", "s", NULL
, offsetof(MachineStatusInfo
, root_directory
) },
632 { "Leader", "u", NULL
, offsetof(MachineStatusInfo
, leader
) },
633 { "Timestamp", "t", NULL
, offsetof(MachineStatusInfo
, timestamp
.realtime
) },
634 { "TimestampMonotonic", "t", NULL
, offsetof(MachineStatusInfo
, timestamp
.monotonic
) },
635 { "Id", "ay", bus_map_id128
, offsetof(MachineStatusInfo
, id
) },
636 { "NetworkInterfaces", "ai", map_netif
, 0 },
640 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
641 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
642 _cleanup_(machine_status_info_clear
) MachineStatusInfo info
= {};
650 r
= bus_map_all_properties(bus
,
651 "org.freedesktop.machine1",
659 return log_error_errno(r
, "Could not get properties: %s", bus_error_message(&error
, r
));
665 print_machine_status_info(bus
, &info
);
670 static int show_machine_properties(sd_bus
*bus
, const char *path
, bool *new_line
) {
682 r
= bus_print_all_properties(bus
, "org.freedesktop.machine1", path
, NULL
, arg_property
, arg_print_flags
, NULL
);
684 log_error_errno(r
, "Could not get properties: %m");
689 static int show_machine(int argc
, char *argv
[], void *userdata
) {
690 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
691 bool properties
, new_line
= false;
692 sd_bus
*bus
= ASSERT_PTR(userdata
);
695 properties
= !strstr(argv
[0], "status");
697 pager_open(arg_pager_flags
);
699 if (properties
&& argc
<= 1) {
701 /* If no argument is specified, inspect the manager
703 r
= show_machine_properties(bus
, "/org/freedesktop/machine1", &new_line
);
708 for (int i
= 1; i
< argc
; i
++) {
709 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
710 const char *path
= NULL
;
712 r
= bus_call_method(bus
, bus_machine_mgr
, "GetMachine", &error
, &reply
, "s", argv
[i
]);
714 return log_error_errno(r
, "Could not get path to machine: %s", bus_error_message(&error
, r
));
716 r
= sd_bus_message_read(reply
, "o", &path
);
718 return bus_log_parse_error(r
);
721 r
= show_machine_properties(bus
, path
, &new_line
);
723 r
= show_machine_info(argv
[0], bus
, path
, &new_line
);
729 static int print_image_hostname(sd_bus
*bus
, const char *name
) {
730 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
734 r
= bus_call_method(bus
, bus_machine_mgr
, "GetImageHostname", NULL
, &reply
, "s", name
);
738 r
= sd_bus_message_read(reply
, "s", &hn
);
743 printf("\tHostname: %s\n", hn
);
748 static int print_image_machine_id(sd_bus
*bus
, const char *name
) {
749 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
750 sd_id128_t id
= SD_ID128_NULL
;
755 r
= bus_call_method(bus
, bus_machine_mgr
, "GetImageMachineID", NULL
, &reply
, "s", name
);
759 r
= sd_bus_message_read_array(reply
, 'y', &p
, &size
);
763 if (size
== sizeof(sd_id128_t
))
764 memcpy(&id
, p
, size
);
766 if (!sd_id128_is_null(id
))
767 printf(" Machine ID: " SD_ID128_FORMAT_STR
"\n", SD_ID128_FORMAT_VAL(id
));
772 static int print_image_machine_info(sd_bus
*bus
, const char *name
) {
773 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
776 r
= bus_call_method(bus
, bus_machine_mgr
, "GetImageMachineInfo", NULL
, &reply
, "s", name
);
780 r
= sd_bus_message_enter_container(reply
, 'a', "{ss}");
787 r
= sd_bus_message_read(reply
, "{ss}", &p
, &q
);
793 if (streq(p
, "DEPLOYMENT"))
794 printf(" Deployment: %s\n", q
);
797 r
= sd_bus_message_exit_container(reply
);
804 typedef struct ImageStatusInfo
{
813 uint64_t usage_exclusive
;
814 uint64_t limit_exclusive
;
817 static void print_image_status_info(sd_bus
*bus
, ImageStatusInfo
*i
) {
822 fputs(i
->name
, stdout
);
827 printf("\t Type: %s\n", i
->type
);
830 printf("\t Path: %s\n", i
->path
);
832 (void) print_image_hostname(bus
, i
->name
);
833 (void) print_image_machine_id(bus
, i
->name
);
834 (void) print_image_machine_info(bus
, i
->name
);
836 print_os_release(bus
, "GetImageOSRelease", i
->name
, "\t OS: ");
838 printf("\t RO: %s%s%s\n",
839 i
->read_only
? ansi_highlight_red() : "",
840 i
->read_only
? "read-only" : "writable",
841 i
->read_only
? ansi_normal() : "");
843 if (timestamp_is_set(i
->crtime
))
844 printf("\t Created: %s; %s\n",
845 FORMAT_TIMESTAMP(i
->crtime
), FORMAT_TIMESTAMP_RELATIVE(i
->crtime
));
847 if (timestamp_is_set(i
->mtime
))
848 printf("\tModified: %s; %s\n",
849 FORMAT_TIMESTAMP(i
->mtime
), FORMAT_TIMESTAMP_RELATIVE(i
->mtime
));
851 if (i
->usage
!= UINT64_MAX
) {
852 if (i
->usage_exclusive
!= i
->usage
&& i
->usage_exclusive
!= UINT64_MAX
)
853 printf("\t Usage: %s (exclusive: %s)\n",
854 FORMAT_BYTES(i
->usage
), FORMAT_BYTES(i
->usage_exclusive
));
856 printf("\t Usage: %s\n", FORMAT_BYTES(i
->usage
));
859 if (i
->limit
!= UINT64_MAX
) {
860 if (i
->limit_exclusive
!= i
->limit
&& i
->limit_exclusive
!= UINT64_MAX
)
861 printf("\t Limit: %s (exclusive: %s)\n",
862 FORMAT_BYTES(i
->limit
), FORMAT_BYTES(i
->limit_exclusive
));
864 printf("\t Limit: %s\n", FORMAT_BYTES(i
->limit
));
868 static int show_image_info(sd_bus
*bus
, const char *path
, bool *new_line
) {
870 static const struct bus_properties_map map
[] = {
871 { "Name", "s", NULL
, offsetof(ImageStatusInfo
, name
) },
872 { "Path", "s", NULL
, offsetof(ImageStatusInfo
, path
) },
873 { "Type", "s", NULL
, offsetof(ImageStatusInfo
, type
) },
874 { "ReadOnly", "b", NULL
, offsetof(ImageStatusInfo
, read_only
) },
875 { "CreationTimestamp", "t", NULL
, offsetof(ImageStatusInfo
, crtime
) },
876 { "ModificationTimestamp", "t", NULL
, offsetof(ImageStatusInfo
, mtime
) },
877 { "Usage", "t", NULL
, offsetof(ImageStatusInfo
, usage
) },
878 { "Limit", "t", NULL
, offsetof(ImageStatusInfo
, limit
) },
879 { "UsageExclusive", "t", NULL
, offsetof(ImageStatusInfo
, usage_exclusive
) },
880 { "LimitExclusive", "t", NULL
, offsetof(ImageStatusInfo
, limit_exclusive
) },
884 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
885 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
886 ImageStatusInfo info
= {};
893 r
= bus_map_all_properties(bus
,
894 "org.freedesktop.machine1",
897 BUS_MAP_BOOLEAN_AS_BOOL
,
902 return log_error_errno(r
, "Could not get properties: %s", bus_error_message(&error
, r
));
908 print_image_status_info(bus
, &info
);
913 typedef struct PoolStatusInfo
{
919 static void print_pool_status_info(sd_bus
*bus
, PoolStatusInfo
*i
) {
921 printf("\t Path: %s\n", i
->path
);
923 if (i
->usage
!= UINT64_MAX
)
924 printf("\t Usage: %s\n", FORMAT_BYTES(i
->usage
));
926 if (i
->limit
!= UINT64_MAX
)
927 printf("\t Limit: %s\n", FORMAT_BYTES(i
->limit
));
930 static int show_pool_info(sd_bus
*bus
) {
932 static const struct bus_properties_map map
[] = {
933 { "PoolPath", "s", NULL
, offsetof(PoolStatusInfo
, path
) },
934 { "PoolUsage", "t", NULL
, offsetof(PoolStatusInfo
, usage
) },
935 { "PoolLimit", "t", NULL
, offsetof(PoolStatusInfo
, limit
) },
939 PoolStatusInfo info
= {
944 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
945 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
950 r
= bus_map_all_properties(bus
,
951 "org.freedesktop.machine1",
952 "/org/freedesktop/machine1",
959 return log_error_errno(r
, "Could not get properties: %s", bus_error_message(&error
, r
));
961 print_pool_status_info(bus
, &info
);
966 static int show_image_properties(sd_bus
*bus
, const char *path
, bool *new_line
) {
978 r
= bus_print_all_properties(bus
, "org.freedesktop.machine1", path
, NULL
, arg_property
, arg_print_flags
, NULL
);
980 log_error_errno(r
, "Could not get properties: %m");
985 static int show_image(int argc
, char *argv
[], void *userdata
) {
986 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
987 bool properties
, new_line
= false;
988 sd_bus
*bus
= ASSERT_PTR(userdata
);
991 properties
= !strstr(argv
[0], "status");
993 pager_open(arg_pager_flags
);
997 /* If no argument is specified, inspect the manager
1001 r
= show_image_properties(bus
, "/org/freedesktop/machine1", &new_line
);
1003 r
= show_pool_info(bus
);
1008 for (int i
= 1; i
< argc
; i
++) {
1009 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1010 const char *path
= NULL
;
1012 r
= bus_call_method(bus
, bus_machine_mgr
, "GetImage", &error
, &reply
, "s", argv
[i
]);
1014 return log_error_errno(r
, "Could not get path to image: %s", bus_error_message(&error
, r
));
1016 r
= sd_bus_message_read(reply
, "o", &path
);
1018 return bus_log_parse_error(r
);
1021 r
= show_image_properties(bus
, path
, &new_line
);
1023 r
= show_image_info(bus
, path
, &new_line
);
1029 static int kill_machine(int argc
, char *argv
[], void *userdata
) {
1030 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1031 sd_bus
*bus
= ASSERT_PTR(userdata
);
1034 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1037 arg_kill_whom
= "all";
1039 for (int i
= 1; i
< argc
; i
++) {
1040 r
= bus_call_method(
1046 "ssi", argv
[i
], arg_kill_whom
, arg_signal
);
1048 return log_error_errno(r
, "Could not kill machine: %s", bus_error_message(&error
, r
));
1054 static int reboot_machine(int argc
, char *argv
[], void *userdata
) {
1055 arg_kill_whom
= "leader";
1056 arg_signal
= SIGINT
; /* sysvinit + systemd */
1058 return kill_machine(argc
, argv
, userdata
);
1061 static int poweroff_machine(int argc
, char *argv
[], void *userdata
) {
1062 arg_kill_whom
= "leader";
1063 arg_signal
= SIGRTMIN
+4; /* only systemd */
1065 return kill_machine(argc
, argv
, userdata
);
1068 static int terminate_machine(int argc
, char *argv
[], void *userdata
) {
1069 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1070 sd_bus
*bus
= ASSERT_PTR(userdata
);
1073 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1075 for (int i
= 1; i
< argc
; i
++) {
1076 r
= bus_call_method(bus
, bus_machine_mgr
, "TerminateMachine", &error
, NULL
, "s", argv
[i
]);
1078 return log_error_errno(r
, "Could not terminate machine: %s", bus_error_message(&error
, r
));
1084 static const char *select_copy_method(bool copy_from
, bool force
) {
1086 return copy_from
? "CopyFromMachineWithFlags" : "CopyToMachineWithFlags";
1088 return copy_from
? "CopyFromMachine" : "CopyToMachine";
1091 static int copy_files(int argc
, char *argv
[], void *userdata
) {
1092 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1093 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1094 _cleanup_free_
char *abs_host_path
= NULL
;
1095 char *dest
, *host_path
, *container_path
;
1096 sd_bus
*bus
= ASSERT_PTR(userdata
);
1100 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1102 copy_from
= streq(argv
[0], "copy-from");
1103 dest
= argv
[3] ?: argv
[2];
1104 host_path
= copy_from
? dest
: argv
[2];
1105 container_path
= copy_from
? argv
[2] : dest
;
1107 if (!path_is_absolute(host_path
)) {
1108 r
= path_make_absolute_cwd(host_path
, &abs_host_path
);
1110 return log_error_errno(r
, "Failed to make path absolute: %m");
1112 host_path
= abs_host_path
;
1115 r
= bus_message_new_method_call(
1119 select_copy_method(copy_from
, arg_force
));
1121 return bus_log_create_error(r
);
1123 r
= sd_bus_message_append(
1127 copy_from
? container_path
: host_path
,
1128 copy_from
? host_path
: container_path
);
1130 return bus_log_create_error(r
);
1133 r
= sd_bus_message_append(m
, "t", MACHINE_COPY_REPLACE
);
1135 return bus_log_create_error(r
);
1138 /* This is a slow operation, hence turn off any method call timeouts */
1139 r
= sd_bus_call(bus
, m
, USEC_INFINITY
, &error
, NULL
);
1141 return log_error_errno(r
, "Failed to copy: %s", bus_error_message(&error
, r
));
1146 static int bind_mount(int argc
, char *argv
[], void *userdata
) {
1147 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1148 sd_bus
*bus
= ASSERT_PTR(userdata
);
1151 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1153 r
= bus_call_method(
1166 return log_error_errno(r
, "Failed to bind mount: %s", bus_error_message(&error
, r
));
1171 static int on_machine_removed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
1172 PTYForward
** forward
= (PTYForward
**) userdata
;
1179 /* If the forwarder is already initialized, tell it to
1180 * exit on the next vhangup(), so that we still flush
1181 * out what might be queued and exit then. */
1183 r
= pty_forward_set_ignore_vhangup(*forward
, false);
1187 log_error_errno(r
, "Failed to set ignore_vhangup flag: %m");
1190 /* On error, or when the forwarder is not initialized yet, quit immediately */
1191 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), EXIT_FAILURE
);
1195 static int process_forward(sd_event
*event
, PTYForward
**forward
, int master
, PTYForwardFlags flags
, const char *name
) {
1201 assert(master
>= 0);
1204 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1207 if (streq(name
, ".host"))
1208 log_info("Connected to the local host. Press ^] three times within 1s to exit session.");
1210 log_info("Connected to machine %s. Press ^] three times within 1s to exit session.", name
);
1213 (void) sd_event_add_signal(event
, NULL
, SIGINT
, NULL
, NULL
);
1214 (void) sd_event_add_signal(event
, NULL
, SIGTERM
, NULL
, NULL
);
1216 r
= pty_forward_new(event
, master
, flags
, forward
);
1218 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1220 r
= sd_event_loop(event
);
1222 return log_error_errno(r
, "Failed to run event loop: %m");
1224 pty_forward_get_last_char(*forward
, &last_char
);
1227 (flags
& PTY_FORWARD_IGNORE_VHANGUP
) &&
1228 pty_forward_get_ignore_vhangup(*forward
) == 0;
1230 *forward
= pty_forward_free(*forward
);
1232 if (last_char
!= '\n')
1233 fputc('\n', stdout
);
1237 log_info("Machine %s terminated.", name
);
1238 else if (streq(name
, ".host"))
1239 log_info("Connection to the local host terminated.");
1241 log_info("Connection to machine %s terminated.", name
);
1247 static int parse_machine_uid(const char *spec
, const char **machine
, char **uid
) {
1249 * Whatever is specified in the spec takes priority over global arguments.
1252 const char *_machine
= NULL
;
1257 at
= strchr(spec
, '@');
1260 /* Do the same as ssh and refuse "@host". */
1264 _uid
= strndup(spec
, at
- spec
);
1271 if (arg_uid
&& !_uid
) {
1272 _uid
= strdup(arg_uid
);
1278 *machine
= isempty(_machine
) ? ".host" : _machine
;
1282 static int login_machine(int argc
, char *argv
[], void *userdata
) {
1283 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1284 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1285 _cleanup_(pty_forward_freep
) PTYForward
*forward
= NULL
;
1286 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot
= NULL
;
1287 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1289 sd_bus
*bus
= ASSERT_PTR(userdata
);
1290 const char *match
, *machine
;
1292 if (!strv_isempty(arg_setenv
) || arg_uid
)
1293 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1294 "--setenv= and --uid= are not supported for 'login'. Use 'shell' instead.");
1296 if (!IN_SET(arg_transport
, BUS_TRANSPORT_LOCAL
, BUS_TRANSPORT_MACHINE
))
1297 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1298 "Login only supported on local machines.");
1300 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1302 r
= sd_event_default(&event
);
1304 return log_error_errno(r
, "Failed to get event loop: %m");
1306 r
= sd_bus_attach_event(bus
, event
, 0);
1308 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1310 machine
= argc
< 2 || isempty(argv
[1]) ? ".host" : argv
[1];
1312 match
= strjoina("type='signal',"
1313 "sender='org.freedesktop.machine1',"
1314 "path='/org/freedesktop/machine1',",
1315 "interface='org.freedesktop.machine1.Manager',"
1316 "member='MachineRemoved',"
1317 "arg0='", machine
, "'");
1319 r
= sd_bus_add_match_async(bus
, &slot
, match
, on_machine_removed
, NULL
, &forward
);
1321 return log_error_errno(r
, "Failed to request machine removal match: %m");
1323 r
= bus_call_method(bus
, bus_machine_mgr
, "OpenMachineLogin", &error
, &reply
, "s", machine
);
1325 return log_error_errno(r
, "Failed to get login PTY: %s", bus_error_message(&error
, r
));
1327 r
= sd_bus_message_read(reply
, "hs", &master
, NULL
);
1329 return bus_log_parse_error(r
);
1331 return process_forward(event
, &forward
, master
, PTY_FORWARD_IGNORE_VHANGUP
, machine
);
1334 static int shell_machine(int argc
, char *argv
[], void *userdata
) {
1335 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
, *m
= NULL
;
1336 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1337 _cleanup_(pty_forward_freep
) PTYForward
*forward
= NULL
;
1338 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot
= NULL
;
1339 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1341 sd_bus
*bus
= ASSERT_PTR(userdata
);
1342 const char *match
, *machine
, *path
;
1343 _cleanup_free_
char *uid
= NULL
;
1345 if (!IN_SET(arg_transport
, BUS_TRANSPORT_LOCAL
, BUS_TRANSPORT_MACHINE
))
1346 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1347 "Shell only supported on local machines.");
1349 /* Pass $TERM to shell session, if not explicitly specified. */
1350 if (!strv_find_prefix(arg_setenv
, "TERM=")) {
1353 t
= strv_find_prefix(environ
, "TERM=");
1355 if (strv_extend(&arg_setenv
, t
) < 0)
1360 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1362 r
= sd_event_default(&event
);
1364 return log_error_errno(r
, "Failed to get event loop: %m");
1366 r
= sd_bus_attach_event(bus
, event
, 0);
1368 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1370 r
= parse_machine_uid(argc
>= 2 ? argv
[1] : NULL
, &machine
, &uid
);
1372 return log_error_errno(r
, "Failed to parse machine specification: %m");
1374 match
= strjoina("type='signal',"
1375 "sender='org.freedesktop.machine1',"
1376 "path='/org/freedesktop/machine1',",
1377 "interface='org.freedesktop.machine1.Manager',"
1378 "member='MachineRemoved',"
1379 "arg0='", machine
, "'");
1381 r
= sd_bus_add_match_async(bus
, &slot
, match
, on_machine_removed
, NULL
, &forward
);
1383 return log_error_errno(r
, "Failed to request machine removal match: %m");
1385 r
= bus_message_new_method_call(bus
, &m
, bus_machine_mgr
, "OpenMachineShell");
1387 return bus_log_create_error(r
);
1389 path
= argc
< 3 || isempty(argv
[2]) ? NULL
: argv
[2];
1391 r
= sd_bus_message_append(m
, "sss", machine
, uid
, path
);
1393 return bus_log_create_error(r
);
1395 r
= sd_bus_message_append_strv(m
, strv_length(argv
) <= 3 ? NULL
: argv
+ 2);
1397 return bus_log_create_error(r
);
1399 r
= sd_bus_message_append_strv(m
, arg_setenv
);
1401 return bus_log_create_error(r
);
1403 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1405 return log_error_errno(r
, "Failed to get shell PTY: %s", bus_error_message(&error
, r
));
1407 r
= sd_bus_message_read(reply
, "hs", &master
, NULL
);
1409 return bus_log_parse_error(r
);
1411 return process_forward(event
, &forward
, master
, 0, machine
);
1414 static int normalize_nspawn_filename(const char *name
, char **ret_file
) {
1415 _cleanup_free_
char *file
= NULL
;
1420 if (!endswith(name
, ".nspawn"))
1421 file
= strjoin(name
, ".nspawn");
1423 file
= strdup(name
);
1427 if (!filename_is_valid(file
))
1428 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid settings file name '%s'.", file
);
1430 *ret_file
= TAKE_PTR(file
);
1434 static int get_settings_path(const char *name
, char **ret_path
) {
1438 FOREACH_STRING(i
, "/etc/systemd/nspawn", "/run/systemd/nspawn", "/var/lib/machines") {
1439 _cleanup_free_
char *path
= NULL
;
1441 path
= path_join(i
, name
);
1445 if (access(path
, F_OK
) >= 0) {
1446 *ret_path
= TAKE_PTR(path
);
1454 static int edit_settings(int argc
, char *argv
[], void *userdata
) {
1455 _cleanup_(edit_file_context_done
) EditFileContext context
= {};
1459 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot edit machine settings if not on a tty.");
1461 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
1462 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1463 "Edit is only supported on the host machine.");
1469 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
1470 _cleanup_free_
char *file
= NULL
, *path
= NULL
;
1472 if (path_is_absolute(*name
)) {
1473 if (!path_is_safe(*name
))
1474 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1475 "Invalid settings file path '%s'.",
1478 r
= edit_files_add(&context
, *name
, NULL
, NULL
);
1484 r
= normalize_nspawn_filename(*name
, &file
);
1488 r
= get_settings_path(file
, &path
);
1490 log_debug("No existing settings file for machine '%s' found, creating a new file.", *name
);
1492 path
= path_join("/etc/systemd/nspawn", file
);
1496 r
= edit_files_add(&context
, path
, NULL
, NULL
);
1502 return log_error_errno(r
, "Failed to get the path of the settings file: %m");
1504 if (path_startswith(path
, "/var/lib/machines")) {
1505 _cleanup_free_
char *new_path
= NULL
;
1507 new_path
= path_join("/etc/systemd/nspawn", file
);
1511 r
= edit_files_add(&context
, new_path
, path
, NULL
);
1513 r
= edit_files_add(&context
, path
, NULL
, NULL
);
1518 return do_edit_files_and_install(&context
);
1521 static int cat_settings(int argc
, char *argv
[], void *userdata
) {
1524 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
1525 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1526 "Cat is only supported on the host machine.");
1528 pager_open(arg_pager_flags
);
1530 STRV_FOREACH(name
, strv_skip(argv
, 1)) {
1531 _cleanup_free_
char *file
= NULL
, *path
= NULL
;
1534 if (path_is_absolute(*name
)) {
1535 if (!path_is_safe(*name
))
1536 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1537 "Invalid settings file path '%s'.",
1540 q
= cat_files(*name
, /* dropins = */ NULL
, /* flags = */ CAT_FORMAT_HAS_SECTIONS
);
1542 return r
< 0 ? r
: q
;
1546 q
= normalize_nspawn_filename(*name
, &file
);
1548 return r
< 0 ? r
: q
;
1550 q
= get_settings_path(file
, &path
);
1552 log_error_errno(q
, "No settings file found for machine '%s'.", *name
);
1557 log_error_errno(q
, "Failed to get the path of the settings file: %m");
1558 return r
< 0 ? r
: q
;
1561 q
= cat_files(path
, /* dropins = */ NULL
, /* flags = */ CAT_FORMAT_HAS_SECTIONS
);
1563 return r
< 0 ? r
: q
;
1569 static int remove_image(int argc
, char *argv
[], void *userdata
) {
1570 sd_bus
*bus
= ASSERT_PTR(userdata
);
1573 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1575 for (int i
= 1; i
< argc
; i
++) {
1576 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1577 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1579 r
= bus_message_new_method_call(bus
, &m
, bus_machine_mgr
, "RemoveImage");
1581 return bus_log_create_error(r
);
1583 r
= sd_bus_message_append(m
, "s", argv
[i
]);
1585 return bus_log_create_error(r
);
1587 /* This is a slow operation, hence turn off any method call timeouts */
1588 r
= sd_bus_call(bus
, m
, USEC_INFINITY
, &error
, NULL
);
1590 return log_error_errno(r
, "Could not remove image: %s", bus_error_message(&error
, r
));
1596 static int rename_image(int argc
, char *argv
[], void *userdata
) {
1597 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1598 sd_bus
*bus
= ASSERT_PTR(userdata
);
1601 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1603 r
= bus_call_method(
1609 "ss", argv
[1], argv
[2]);
1611 return log_error_errno(r
, "Could not rename image: %s", bus_error_message(&error
, r
));
1616 static int clone_image(int argc
, char *argv
[], void *userdata
) {
1617 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1618 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1619 sd_bus
*bus
= ASSERT_PTR(userdata
);
1622 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1624 r
= bus_message_new_method_call(bus
, &m
, bus_machine_mgr
, "CloneImage");
1626 return bus_log_create_error(r
);
1628 r
= sd_bus_message_append(m
, "ssb", argv
[1], argv
[2], arg_read_only
);
1630 return bus_log_create_error(r
);
1632 /* This is a slow operation, hence turn off any method call timeouts */
1633 r
= sd_bus_call(bus
, m
, USEC_INFINITY
, &error
, NULL
);
1635 return log_error_errno(r
, "Could not clone image: %s", bus_error_message(&error
, r
));
1640 static int read_only_image(int argc
, char *argv
[], void *userdata
) {
1641 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1642 sd_bus
*bus
= ASSERT_PTR(userdata
);
1646 b
= parse_boolean(argv
[2]);
1648 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1649 "Failed to parse boolean argument: %s",
1653 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1655 r
= bus_call_method(bus
, bus_machine_mgr
, "MarkImageReadOnly", &error
, NULL
, "sb", argv
[1], b
);
1657 return log_error_errno(r
, "Could not mark image read-only: %s", bus_error_message(&error
, r
));
1662 static int image_exists(sd_bus
*bus
, const char *name
) {
1663 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1669 r
= bus_call_method(bus
, bus_machine_mgr
, "GetImage", &error
, NULL
, "s", name
);
1671 if (sd_bus_error_has_name(&error
, BUS_ERROR_NO_SUCH_IMAGE
))
1674 return log_error_errno(r
, "Failed to check whether image %s exists: %s", name
, bus_error_message(&error
, r
));
1680 static int make_service_name(const char *name
, char **ret
) {
1686 if (!hostname_is_valid(name
, 0))
1687 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1688 "Invalid machine name %s.", name
);
1690 r
= unit_name_build("systemd-nspawn", name
, ".service", ret
);
1692 return log_error_errno(r
, "Failed to build unit name: %m");
1697 static int start_machine(int argc
, char *argv
[], void *userdata
) {
1698 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1699 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1700 sd_bus
*bus
= ASSERT_PTR(userdata
);
1703 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1704 ask_password_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1706 r
= bus_wait_for_jobs_new(bus
, &w
);
1708 return log_error_errno(r
, "Could not watch jobs: %m");
1710 for (int i
= 1; i
< argc
; i
++) {
1711 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1712 _cleanup_free_
char *unit
= NULL
;
1715 r
= make_service_name(argv
[i
], &unit
);
1719 r
= image_exists(bus
, argv
[i
]);
1723 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
1724 "Machine image '%s' does not exist.",
1727 r
= bus_call_method(
1733 "ss", unit
, "fail");
1735 return log_error_errno(r
, "Failed to start unit: %s", bus_error_message(&error
, r
));
1737 r
= sd_bus_message_read(reply
, "o", &object
);
1739 return bus_log_parse_error(r
);
1741 r
= bus_wait_for_jobs_add(w
, object
);
1746 r
= bus_wait_for_jobs(w
, arg_quiet
, NULL
);
1753 static int enable_machine(int argc
, char *argv
[], void *userdata
) {
1754 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1755 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1757 sd_bus
*bus
= ASSERT_PTR(userdata
);
1761 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1763 enable
= streq(argv
[0], "enable");
1764 method
= enable
? "EnableUnitFiles" : "DisableUnitFiles";
1766 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, method
);
1768 return bus_log_create_error(r
);
1770 r
= sd_bus_message_open_container(m
, 'a', "s");
1772 return bus_log_create_error(r
);
1775 r
= sd_bus_message_append(m
, "s", "machines.target");
1777 return bus_log_create_error(r
);
1780 for (int i
= 1; i
< argc
; i
++) {
1781 _cleanup_free_
char *unit
= NULL
;
1783 r
= make_service_name(argv
[i
], &unit
);
1787 r
= image_exists(bus
, argv
[i
]);
1791 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
1792 "Machine image '%s' does not exist.",
1795 r
= sd_bus_message_append(m
, "s", unit
);
1797 return bus_log_create_error(r
);
1800 r
= sd_bus_message_close_container(m
);
1802 return bus_log_create_error(r
);
1805 r
= sd_bus_message_append(m
, "bb", false, false);
1807 r
= sd_bus_message_append(m
, "b", false);
1809 return bus_log_create_error(r
);
1811 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1813 return log_error_errno(r
, "Failed to enable or disable unit: %s", bus_error_message(&error
, r
));
1816 r
= sd_bus_message_read(reply
, "b", NULL
);
1818 return bus_log_parse_error(r
);
1821 r
= bus_deserialize_and_dump_unit_file_changes(reply
, arg_quiet
);
1825 r
= bus_service_manager_reload(bus
);
1830 _cleanup_strv_free_
char **new_args
= NULL
;
1832 new_args
= strv_new(enable
? "start" : "poweroff");
1836 r
= strv_extend_strv(&new_args
, argv
+ 1, /* filter_duplicates = */ false);
1841 return start_machine(strv_length(new_args
), new_args
, userdata
);
1843 return poweroff_machine(strv_length(new_args
), new_args
, userdata
);
1849 static int match_log_message(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
1850 const char **our_path
= userdata
, *line
;
1857 r
= sd_bus_message_read(m
, "us", &priority
, &line
);
1859 bus_log_parse_error(r
);
1863 if (!streq_ptr(*our_path
, sd_bus_message_get_path(m
)))
1866 if (arg_quiet
&& LOG_PRI(priority
) >= LOG_INFO
)
1869 log_full(priority
, "%s", line
);
1873 static int match_transfer_removed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
1874 const char **our_path
= userdata
, *path
, *result
;
1881 r
= sd_bus_message_read(m
, "uos", &id
, &path
, &result
);
1883 bus_log_parse_error(r
);
1887 if (!streq_ptr(*our_path
, path
))
1890 sd_event_exit(sd_bus_get_event(sd_bus_message_get_bus(m
)), !streq_ptr(result
, "done"));
1894 static int transfer_signal_handler(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
1899 log_info("Continuing download in the background. Use \"machinectl cancel-transfer %" PRIu32
"\" to abort transfer.", PTR_TO_UINT32(userdata
));
1901 sd_event_exit(sd_event_source_get_event(s
), EINTR
);
1905 static int transfer_image_common(sd_bus
*bus
, sd_bus_message
*m
) {
1906 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot_job_removed
= NULL
, *slot_log_message
= NULL
;
1907 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1908 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1909 _cleanup_(sd_event_unrefp
) sd_event
* event
= NULL
;
1910 const char *path
= NULL
;
1917 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1919 r
= sd_event_default(&event
);
1921 return log_error_errno(r
, "Failed to get event loop: %m");
1923 r
= sd_bus_attach_event(bus
, event
, 0);
1925 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1927 r
= bus_match_signal_async(
1932 match_transfer_removed
, NULL
, &path
);
1934 return log_error_errno(r
, "Failed to request match: %m");
1936 r
= sd_bus_match_signal_async(
1939 "org.freedesktop.import1",
1941 "org.freedesktop.import1.Transfer",
1943 match_log_message
, NULL
, &path
);
1945 return log_error_errno(r
, "Failed to request match: %m");
1947 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1949 return log_error_errno(r
, "Failed to transfer image: %s", bus_error_message(&error
, r
));
1951 r
= sd_bus_message_read(reply
, "uo", &id
, &path
);
1953 return bus_log_parse_error(r
);
1955 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGTERM
, SIGINT
, -1) >= 0);
1958 log_info("Enqueued transfer job %u. Press C-c to continue download in background.", id
);
1960 (void) sd_event_add_signal(event
, NULL
, SIGINT
, transfer_signal_handler
, UINT32_TO_PTR(id
));
1961 (void) sd_event_add_signal(event
, NULL
, SIGTERM
, transfer_signal_handler
, UINT32_TO_PTR(id
));
1963 r
= sd_event_loop(event
);
1965 return log_error_errno(r
, "Failed to run event loop: %m");
1970 static int import_tar(int argc
, char *argv
[], void *userdata
) {
1971 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1972 _cleanup_free_
char *ll
= NULL
, *fn
= NULL
;
1973 const char *local
= NULL
, *path
= NULL
;
1974 _cleanup_close_
int fd
= -EBADF
;
1975 sd_bus
*bus
= ASSERT_PTR(userdata
);
1979 path
= empty_or_dash_to_null(argv
[1]);
1982 local
= empty_or_dash_to_null(argv
[2]);
1984 r
= path_extract_filename(path
, &fn
);
1986 return log_error_errno(r
, "Cannot extract container name from filename: %m");
1987 if (r
== O_DIRECTORY
)
1988 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
1989 "Path '%s' refers to directory, but we need a regular file: %m", path
);
1994 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1995 "Need either path or local name.");
1997 r
= tar_strip_suffixes(local
, &ll
);
2003 if (!hostname_is_valid(local
, 0))
2004 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2005 "Local name %s is not a suitable machine name.",
2009 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2011 return log_error_errno(errno
, "Failed to open %s: %m", path
);
2014 r
= bus_message_new_method_call(bus
, &m
, bus_import_mgr
, "ImportTar");
2016 return bus_log_create_error(r
);
2018 r
= sd_bus_message_append(
2021 fd
>= 0 ? fd
: STDIN_FILENO
,
2026 return bus_log_create_error(r
);
2028 return transfer_image_common(bus
, m
);
2031 static int import_raw(int argc
, char *argv
[], void *userdata
) {
2032 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2033 _cleanup_free_
char *ll
= NULL
, *fn
= NULL
;
2034 const char *local
= NULL
, *path
= NULL
;
2035 _cleanup_close_
int fd
= -EBADF
;
2036 sd_bus
*bus
= ASSERT_PTR(userdata
);
2040 path
= empty_or_dash_to_null(argv
[1]);
2043 local
= empty_or_dash_to_null(argv
[2]);
2045 r
= path_extract_filename(path
, &fn
);
2047 return log_error_errno(r
, "Cannot extract container name from filename: %m");
2048 if (r
== O_DIRECTORY
)
2049 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
2050 "Path '%s' refers to directory, but we need a regular file: %m", path
);
2055 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2056 "Need either path or local name.");
2058 r
= raw_strip_suffixes(local
, &ll
);
2064 if (!hostname_is_valid(local
, 0))
2065 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2066 "Local name %s is not a suitable machine name.",
2070 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2072 return log_error_errno(errno
, "Failed to open %s: %m", path
);
2075 r
= bus_message_new_method_call(bus
, &m
, bus_import_mgr
, "ImportRaw");
2077 return bus_log_create_error(r
);
2079 r
= sd_bus_message_append(
2082 fd
>= 0 ? fd
: STDIN_FILENO
,
2087 return bus_log_create_error(r
);
2089 return transfer_image_common(bus
, m
);
2092 static int import_fs(int argc
, char *argv
[], void *userdata
) {
2093 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2094 const char *local
= NULL
, *path
= NULL
;
2095 _cleanup_free_
char *fn
= NULL
;
2096 _cleanup_close_
int fd
= -EBADF
;
2097 sd_bus
*bus
= ASSERT_PTR(userdata
);
2101 path
= empty_or_dash_to_null(argv
[1]);
2104 local
= empty_or_dash_to_null(argv
[2]);
2106 r
= path_extract_filename(path
, &fn
);
2108 return log_error_errno(r
, "Cannot extract container name from filename: %m");
2113 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2114 "Need either path or local name.");
2116 if (!hostname_is_valid(local
, 0))
2117 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2118 "Local name %s is not a suitable machine name.",
2122 fd
= open(path
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
);
2124 return log_error_errno(errno
, "Failed to open directory '%s': %m", path
);
2127 r
= bus_message_new_method_call(bus
, &m
, bus_import_mgr
, "ImportFileSystem");
2129 return bus_log_create_error(r
);
2131 r
= sd_bus_message_append(
2134 fd
>= 0 ? fd
: STDIN_FILENO
,
2139 return bus_log_create_error(r
);
2141 return transfer_image_common(bus
, m
);
2144 static void determine_compression_from_filename(const char *p
) {
2151 if (endswith(p
, ".xz"))
2153 else if (endswith(p
, ".gz"))
2154 arg_format
= "gzip";
2155 else if (endswith(p
, ".bz2"))
2156 arg_format
= "bzip2";
2159 static int export_tar(int argc
, char *argv
[], void *userdata
) {
2160 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2161 _cleanup_close_
int fd
= -EBADF
;
2162 const char *local
= NULL
, *path
= NULL
;
2163 sd_bus
*bus
= ASSERT_PTR(userdata
);
2167 if (!hostname_is_valid(local
, 0))
2168 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2169 "Machine name %s is not valid.", local
);
2173 path
= empty_or_dash_to_null(path
);
2176 determine_compression_from_filename(path
);
2178 fd
= open(path
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_CLOEXEC
|O_NOCTTY
, 0666);
2180 return log_error_errno(errno
, "Failed to open %s: %m", path
);
2183 r
= bus_message_new_method_call(bus
, &m
, bus_import_mgr
, "ExportTar");
2185 return bus_log_create_error(r
);
2187 r
= sd_bus_message_append(
2191 fd
>= 0 ? fd
: STDOUT_FILENO
,
2194 return bus_log_create_error(r
);
2196 return transfer_image_common(bus
, m
);
2199 static int export_raw(int argc
, char *argv
[], void *userdata
) {
2200 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2201 _cleanup_close_
int fd
= -EBADF
;
2202 const char *local
= NULL
, *path
= NULL
;
2203 sd_bus
*bus
= ASSERT_PTR(userdata
);
2207 if (!hostname_is_valid(local
, 0))
2208 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2209 "Machine name %s is not valid.", local
);
2213 path
= empty_or_dash_to_null(path
);
2216 determine_compression_from_filename(path
);
2218 fd
= open(path
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_CLOEXEC
|O_NOCTTY
, 0666);
2220 return log_error_errno(errno
, "Failed to open %s: %m", path
);
2223 r
= bus_message_new_method_call(bus
, &m
, bus_import_mgr
, "ExportRaw");
2225 return bus_log_create_error(r
);
2227 r
= sd_bus_message_append(
2231 fd
>= 0 ? fd
: STDOUT_FILENO
,
2234 return bus_log_create_error(r
);
2236 return transfer_image_common(bus
, m
);
2239 static int pull_tar(int argc
, char *argv
[], void *userdata
) {
2240 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2241 _cleanup_free_
char *l
= NULL
, *ll
= NULL
;
2242 const char *local
, *remote
;
2243 sd_bus
*bus
= ASSERT_PTR(userdata
);
2247 if (!http_url_is_valid(remote
) && !file_url_is_valid(remote
))
2248 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2249 "URL '%s' is not valid.", remote
);
2254 r
= import_url_last_component(remote
, &l
);
2256 return log_error_errno(r
, "Failed to get final component of URL: %m");
2261 local
= empty_or_dash_to_null(local
);
2264 r
= tar_strip_suffixes(local
, &ll
);
2270 if (!hostname_is_valid(local
, 0))
2271 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2272 "Local name %s is not a suitable machine name.",
2276 r
= bus_message_new_method_call(bus
, &m
, bus_import_mgr
, "PullTar");
2278 return bus_log_create_error(r
);
2280 r
= sd_bus_message_append(
2285 import_verify_to_string(arg_verify
),
2288 return bus_log_create_error(r
);
2290 return transfer_image_common(bus
, m
);
2293 static int pull_raw(int argc
, char *argv
[], void *userdata
) {
2294 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2295 _cleanup_free_
char *l
= NULL
, *ll
= NULL
;
2296 const char *local
, *remote
;
2297 sd_bus
*bus
= ASSERT_PTR(userdata
);
2301 if (!http_url_is_valid(remote
) && !file_url_is_valid(remote
))
2302 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2303 "URL '%s' is not valid.", remote
);
2308 r
= import_url_last_component(remote
, &l
);
2310 return log_error_errno(r
, "Failed to get final component of URL: %m");
2315 local
= empty_or_dash_to_null(local
);
2318 r
= raw_strip_suffixes(local
, &ll
);
2324 if (!hostname_is_valid(local
, 0))
2325 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2326 "Local name %s is not a suitable machine name.",
2330 r
= bus_message_new_method_call(bus
, &m
, bus_import_mgr
, "PullRaw");
2332 return bus_log_create_error(r
);
2334 r
= sd_bus_message_append(
2339 import_verify_to_string(arg_verify
),
2342 return bus_log_create_error(r
);
2344 return transfer_image_common(bus
, m
);
2347 typedef struct TransferInfo
{
2355 static int compare_transfer_info(const TransferInfo
*a
, const TransferInfo
*b
) {
2356 return strcmp(a
->local
, b
->local
);
2359 static int list_transfers(int argc
, char *argv
[], void *userdata
) {
2360 size_t max_type
= STRLEN("TYPE"), max_local
= STRLEN("LOCAL"), max_remote
= STRLEN("REMOTE");
2361 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2362 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2363 _cleanup_free_ TransferInfo
*transfers
= NULL
;
2364 const char *type
, *remote
, *local
;
2365 sd_bus
*bus
= userdata
;
2366 uint32_t id
, max_id
= 0;
2367 size_t n_transfers
= 0;
2371 pager_open(arg_pager_flags
);
2373 r
= bus_call_method(bus
, bus_import_mgr
, "ListTransfers", &error
, &reply
, NULL
);
2375 return log_error_errno(r
, "Could not get transfers: %s", bus_error_message(&error
, r
));
2377 r
= sd_bus_message_enter_container(reply
, 'a', "(usssdo)");
2379 return bus_log_parse_error(r
);
2381 while ((r
= sd_bus_message_read(reply
, "(usssdo)", &id
, &type
, &remote
, &local
, &progress
, NULL
)) > 0) {
2384 if (!GREEDY_REALLOC(transfers
, n_transfers
+ 1))
2387 transfers
[n_transfers
].id
= id
;
2388 transfers
[n_transfers
].type
= type
;
2389 transfers
[n_transfers
].remote
= remote
;
2390 transfers
[n_transfers
].local
= local
;
2391 transfers
[n_transfers
].progress
= progress
;
2411 return bus_log_parse_error(r
);
2413 r
= sd_bus_message_exit_container(reply
);
2415 return bus_log_parse_error(r
);
2417 typesafe_qsort(transfers
, n_transfers
, compare_transfer_info
);
2419 if (arg_legend
&& n_transfers
> 0)
2420 printf("%-*s %-*s %-*s %-*s %-*s\n",
2421 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id
)), "ID",
2423 (int) max_type
, "TYPE",
2424 (int) max_local
, "LOCAL",
2425 (int) max_remote
, "REMOTE");
2427 for (size_t j
= 0; j
< n_transfers
; j
++)
2429 if (transfers
[j
].progress
< 0)
2430 printf("%*" PRIu32
" %*s %-*s %-*s %-*s\n",
2431 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id
)), transfers
[j
].id
,
2433 (int) max_type
, transfers
[j
].type
,
2434 (int) max_local
, transfers
[j
].local
,
2435 (int) max_remote
, transfers
[j
].remote
);
2437 printf("%*" PRIu32
" %*u%% %-*s %-*s %-*s\n",
2438 (int) MAX(2U, DECIMAL_STR_WIDTH(max_id
)), transfers
[j
].id
,
2439 (int) 6, (unsigned) (transfers
[j
].progress
* 100),
2440 (int) max_type
, transfers
[j
].type
,
2441 (int) max_local
, transfers
[j
].local
,
2442 (int) max_remote
, transfers
[j
].remote
);
2445 if (n_transfers
> 0)
2446 printf("\n%zu transfers listed.\n", n_transfers
);
2448 printf("No transfers.\n");
2454 static int cancel_transfer(int argc
, char *argv
[], void *userdata
) {
2455 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2456 sd_bus
*bus
= ASSERT_PTR(userdata
);
2459 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
2461 for (int i
= 1; i
< argc
; i
++) {
2464 r
= safe_atou32(argv
[i
], &id
);
2466 return log_error_errno(r
, "Failed to parse transfer id: %s", argv
[i
]);
2468 r
= bus_call_method(bus
, bus_import_mgr
, "CancelTransfer", &error
, NULL
, "u", id
);
2470 return log_error_errno(r
, "Could not cancel transfer: %s", bus_error_message(&error
, r
));
2476 static int set_limit(int argc
, char *argv
[], void *userdata
) {
2477 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2478 sd_bus
*bus
= userdata
;
2482 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
2484 if (STR_IN_SET(argv
[argc
-1], "-", "none", "infinity"))
2487 r
= parse_size(argv
[argc
-1], 1024, &limit
);
2489 return log_error_errno(r
, "Failed to parse size: %s", argv
[argc
-1]);
2493 /* With two arguments changes the quota limit of the
2494 * specified image */
2495 r
= bus_call_method(bus
, bus_machine_mgr
, "SetImageLimit", &error
, NULL
, "st", argv
[1], limit
);
2497 /* With one argument changes the pool quota limit */
2498 r
= bus_call_method(bus
, bus_machine_mgr
, "SetPoolLimit", &error
, NULL
, "t", limit
);
2501 return log_error_errno(r
, "Could not set limit: %s", bus_error_message(&error
, r
));
2506 static int clean_images(int argc
, char *argv
[], void *userdata
) {
2507 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
2508 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2509 uint64_t usage
, total
= 0;
2510 sd_bus
*bus
= userdata
;
2515 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
2517 r
= bus_message_new_method_call(bus
, &m
, bus_machine_mgr
, "CleanPool");
2519 return bus_log_create_error(r
);
2521 r
= sd_bus_message_append(m
, "s", arg_all
? "all" : "hidden");
2523 return bus_log_create_error(r
);
2525 /* This is a slow operation, hence permit a longer time for completion. */
2526 r
= sd_bus_call(bus
, m
, USEC_INFINITY
, &error
, &reply
);
2528 return log_error_errno(r
, "Could not clean pool: %s", bus_error_message(&error
, r
));
2530 r
= sd_bus_message_enter_container(reply
, 'a', "(st)");
2532 return bus_log_parse_error(r
);
2534 while ((r
= sd_bus_message_read(reply
, "(st)", &name
, &usage
)) > 0) {
2535 if (usage
== UINT64_MAX
) {
2536 log_info("Removed image '%s'", name
);
2539 log_info("Removed image '%s'. Freed exclusive disk space: %s",
2540 name
, FORMAT_BYTES(usage
));
2541 if (total
!= UINT64_MAX
)
2547 r
= sd_bus_message_exit_container(reply
);
2549 return bus_log_parse_error(r
);
2551 if (total
== UINT64_MAX
)
2552 log_info("Removed %u images in total.", c
);
2554 log_info("Removed %u images in total. Total freed exclusive disk space: %s.",
2555 c
, FORMAT_BYTES(total
));
2560 static int help(int argc
, char *argv
[], void *userdata
) {
2561 _cleanup_free_
char *link
= NULL
;
2564 pager_open(arg_pager_flags
);
2566 r
= terminal_urlify_man("machinectl", "1", &link
);
2570 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
2571 "%5$sSend control commands to or query the virtual machine and container%6$s\n"
2572 "%5$sregistration manager.%6$s\n"
2573 "\n%3$sMachine Commands:%4$s\n"
2574 " list List running VMs and containers\n"
2575 " status NAME... Show VM/container details\n"
2576 " show [NAME...] Show properties of one or more VMs/containers\n"
2577 " start NAME... Start container as a service\n"
2578 " login [NAME] Get a login prompt in a container or on the\n"
2580 " shell [[USER@]NAME [COMMAND...]]\n"
2581 " Invoke a shell (or other command) in a container\n"
2582 " or on the local host\n"
2583 " enable NAME... Enable automatic container start at boot\n"
2584 " disable NAME... Disable automatic container start at boot\n"
2585 " poweroff NAME... Power off one or more containers\n"
2586 " reboot NAME... Reboot one or more containers\n"
2587 " terminate NAME... Terminate one or more VMs/containers\n"
2588 " kill NAME... Send signal to processes of a VM/container\n"
2589 " copy-to NAME PATH [PATH] Copy files from the host to a container\n"
2590 " copy-from NAME PATH [PATH] Copy files from a container to the host\n"
2591 " bind NAME PATH [PATH] Bind mount a path from the host into a container\n"
2592 "\n%3$sImage Commands:%4$s\n"
2593 " list-images Show available container and VM images\n"
2594 " image-status [NAME...] Show image details\n"
2595 " show-image [NAME...] Show properties of image\n"
2596 " edit NAME|FILE... Edit settings of one or more VMs/containers\n"
2597 " cat NAME|FILE... Show settings of one or more VMs/containers\n"
2598 " clone NAME NAME Clone an image\n"
2599 " rename NAME NAME Rename an image\n"
2600 " read-only NAME [BOOL] Mark or unmark image read-only\n"
2601 " remove NAME... Remove an image\n"
2602 " set-limit [NAME] BYTES Set image or pool size limit (disk quota)\n"
2603 " clean Remove hidden (or all) images\n"
2604 "\n%3$sImage Transfer Commands:%4$s\n"
2605 " pull-tar URL [NAME] Download a TAR container image\n"
2606 " pull-raw URL [NAME] Download a RAW container or VM image\n"
2607 " import-tar FILE [NAME] Import a local TAR container image\n"
2608 " import-raw FILE [NAME] Import a local RAW container or VM image\n"
2609 " import-fs DIRECTORY [NAME] Import a local directory container image\n"
2610 " export-tar NAME [FILE] Export a TAR container image locally\n"
2611 " export-raw NAME [FILE] Export a RAW container or VM image locally\n"
2612 " list-transfers Show list of downloads in progress\n"
2613 " cancel-transfer Cancel a download\n"
2614 "\n%3$sOptions:%4$s\n"
2615 " -h --help Show this help\n"
2616 " --version Show package version\n"
2617 " --no-pager Do not pipe output into a pager\n"
2618 " --no-legend Do not show the headers and footers\n"
2619 " --no-ask-password Do not ask for system passwords\n"
2620 " -H --host=[USER@]HOST Operate on remote host\n"
2621 " -M --machine=CONTAINER Operate on local container\n"
2622 " -p --property=NAME Show only properties by this name\n"
2623 " -q --quiet Suppress output\n"
2624 " -a --all Show all properties, including empty ones\n"
2625 " --value When showing properties, only print the value\n"
2626 " -l --full Do not ellipsize output\n"
2627 " --kill-whom=WHOM Whom to send signal to\n"
2628 " -s --signal=SIGNAL Which signal to send\n"
2629 " --uid=USER Specify user ID to invoke shell as\n"
2630 " -E --setenv=VAR[=VALUE] Add an environment variable for shell\n"
2631 " --read-only Create read-only bind mount\n"
2632 " --mkdir Create directory before bind mounting, if missing\n"
2633 " -n --lines=INTEGER Number of journal entries to show\n"
2634 " --max-addresses=INTEGER Number of internet addresses to show at most\n"
2635 " -o --output=STRING Change journal output mode (short, short-precise,\n"
2636 " short-iso, short-iso-precise, short-full,\n"
2637 " short-monotonic, short-unix, short-delta,\n"
2638 " json, json-pretty, json-sse, json-seq, cat,\n"
2639 " verbose, export, with-unit)\n"
2640 " --verify=MODE Verification mode for downloaded images (no,\n"
2641 " checksum, signature)\n"
2642 " --force Download image even if already exists\n"
2643 " --now Start or power off container after enabling or\n"
2645 "\nSee the %2$s for details.\n",
2646 program_invocation_short_name
,
2656 static int parse_argv(int argc
, char *argv
[]) {
2659 ARG_VERSION
= 0x100,
2666 ARG_NO_ASK_PASSWORD
,
2675 static const struct option options
[] = {
2676 { "help", no_argument
, NULL
, 'h' },
2677 { "version", no_argument
, NULL
, ARG_VERSION
},
2678 { "property", required_argument
, NULL
, 'p' },
2679 { "all", no_argument
, NULL
, 'a' },
2680 { "value", no_argument
, NULL
, ARG_VALUE
},
2681 { "full", no_argument
, NULL
, 'l' },
2682 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
2683 { "no-legend", no_argument
, NULL
, ARG_NO_LEGEND
},
2684 { "kill-whom", required_argument
, NULL
, ARG_KILL_WHOM
},
2685 { "signal", required_argument
, NULL
, 's' },
2686 { "host", required_argument
, NULL
, 'H' },
2687 { "machine", required_argument
, NULL
, 'M' },
2688 { "read-only", no_argument
, NULL
, ARG_READ_ONLY
},
2689 { "mkdir", no_argument
, NULL
, ARG_MKDIR
},
2690 { "quiet", no_argument
, NULL
, 'q' },
2691 { "lines", required_argument
, NULL
, 'n' },
2692 { "output", required_argument
, NULL
, 'o' },
2693 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
2694 { "verify", required_argument
, NULL
, ARG_VERIFY
},
2695 { "now", no_argument
, NULL
, ARG_NOW
},
2696 { "force", no_argument
, NULL
, ARG_FORCE
},
2697 { "format", required_argument
, NULL
, ARG_FORMAT
},
2698 { "uid", required_argument
, NULL
, ARG_UID
},
2699 { "setenv", required_argument
, NULL
, 'E' },
2700 { "max-addresses", required_argument
, NULL
, ARG_MAX_ADDRESSES
},
2704 bool reorder
= false;
2705 int c
, r
, shell
= -1;
2710 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
2711 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
2715 static const char option_string
[] = "-hp:als:H:M:qn:o:E:";
2717 c
= getopt_long(argc
, argv
, option_string
+ reorder
, options
, NULL
);
2723 case 1: /* getopt_long() returns 1 if "-" was the first character of the option string, and a
2724 * non-option argument was discovered. */
2728 /* We generally are fine with the fact that getopt_long() reorders the command line, and looks
2729 * for switches after the main verb. However, for "shell" we really don't want that, since we
2730 * want that switches specified after the machine name are passed to the program to execute,
2731 * and not processed by us. To make this possible, we'll first invoke getopt_long() with
2732 * reordering disabled (i.e. with the "-" prefix in the option string), looking for the first
2733 * non-option parameter. If it's the verb "shell" we remember its position and continue
2734 * processing options. In this case, as soon as we hit the next non-option argument we found
2735 * the machine name, and stop further processing. If the first non-option argument is any other
2736 * verb than "shell" we switch to normal reordering mode and continue processing arguments
2740 /* If we already found the "shell" verb on the command line, and now found the next
2741 * non-option argument, then this is the machine name and we should stop processing
2742 * further arguments. */
2743 optind
--; /* don't process this argument, go one step back */
2746 if (streq(optarg
, "shell"))
2747 /* Remember the position of the "shell" verb, and continue processing normally. */
2752 /* OK, this is some other verb. In this case, turn on reordering again, and continue
2753 * processing normally. */
2756 /* We changed the option string. getopt_long() only looks at it again if we invoke it
2757 * at least once with a reset option index. Hence, let's reset the option index here,
2758 * then invoke getopt_long() again (ignoring what it has to say, after all we most
2759 * likely already processed it), and the bump the option index so that we read the
2760 * intended argument again. */
2761 saved_optind
= optind
;
2763 (void) getopt_long(argc
, argv
, option_string
+ reorder
, options
, NULL
);
2764 optind
= saved_optind
- 1; /* go one step back, process this argument again */
2770 return help(0, NULL
, NULL
);
2776 r
= strv_extend(&arg_property
, optarg
);
2780 /* If the user asked for a particular
2781 * property, show it to them, even if it is
2783 SET_FLAG(arg_print_flags
, BUS_PRINT_PROPERTY_SHOW_EMPTY
, true);
2787 SET_FLAG(arg_print_flags
, BUS_PRINT_PROPERTY_SHOW_EMPTY
, true);
2792 SET_FLAG(arg_print_flags
, BUS_PRINT_PROPERTY_ONLY_VALUE
, true);
2800 if (safe_atou(optarg
, &arg_lines
) < 0)
2801 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2802 "Failed to parse lines '%s'", optarg
);
2806 if (streq(optarg
, "help")) {
2807 DUMP_STRING_TABLE(output_mode
, OutputMode
, _OUTPUT_MODE_MAX
);
2811 r
= output_mode_from_string(optarg
);
2813 return log_error_errno(r
, "Unknown output '%s'.", optarg
);
2816 if (OUTPUT_MODE_IS_JSON(arg_output
))
2821 arg_pager_flags
|= PAGER_DISABLE
;
2829 arg_kill_whom
= optarg
;
2833 r
= parse_signal_argument(optarg
, &arg_signal
);
2838 case ARG_NO_ASK_PASSWORD
:
2839 arg_ask_password
= false;
2843 arg_transport
= BUS_TRANSPORT_REMOTE
;
2848 arg_transport
= BUS_TRANSPORT_MACHINE
;
2853 arg_read_only
= true;
2865 if (streq(optarg
, "help")) {
2866 DUMP_STRING_TABLE(import_verify
, ImportVerify
, _IMPORT_VERIFY_MAX
);
2870 r
= import_verify_from_string(optarg
);
2872 return log_error_errno(r
, "Failed to parse --verify= setting: %s", optarg
);
2885 if (!STR_IN_SET(optarg
, "uncompressed", "xz", "gzip", "bzip2"))
2886 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2887 "Unknown format: %s", optarg
);
2889 arg_format
= optarg
;
2897 r
= strv_env_replace_strdup_passthrough(&arg_setenv
, optarg
);
2899 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
2902 case ARG_MAX_ADDRESSES
:
2903 if (streq(optarg
, "all"))
2904 arg_max_addresses
= UINT_MAX
;
2905 else if (safe_atou(optarg
, &arg_max_addresses
) < 0)
2906 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2907 "Invalid number of addresses: %s", optarg
);
2914 assert_not_reached();
2922 /* We found the "shell" verb while processing the argument list. Since we turned off reordering of the
2923 * argument list initially let's readjust it now, and move the "shell" verb to the back. */
2925 optind
-= 1; /* place the option index where the "shell" verb will be placed */
2928 for (int i
= shell
; i
< optind
; i
++)
2929 argv
[i
] = argv
[i
+1];
2936 static int machinectl_main(int argc
, char *argv
[], sd_bus
*bus
) {
2938 static const Verb verbs
[] = {
2939 { "help", VERB_ANY
, VERB_ANY
, 0, help
},
2940 { "list", VERB_ANY
, 1, VERB_DEFAULT
, list_machines
},
2941 { "list-images", VERB_ANY
, 1, 0, list_images
},
2942 { "status", 2, VERB_ANY
, 0, show_machine
},
2943 { "image-status", VERB_ANY
, VERB_ANY
, 0, show_image
},
2944 { "show", VERB_ANY
, VERB_ANY
, 0, show_machine
},
2945 { "show-image", VERB_ANY
, VERB_ANY
, 0, show_image
},
2946 { "terminate", 2, VERB_ANY
, 0, terminate_machine
},
2947 { "reboot", 2, VERB_ANY
, 0, reboot_machine
},
2948 { "poweroff", 2, VERB_ANY
, 0, poweroff_machine
},
2949 { "stop", 2, VERB_ANY
, 0, poweroff_machine
}, /* Convenience alias */
2950 { "kill", 2, VERB_ANY
, 0, kill_machine
},
2951 { "login", VERB_ANY
, 2, 0, login_machine
},
2952 { "shell", VERB_ANY
, VERB_ANY
, 0, shell_machine
},
2953 { "bind", 3, 4, 0, bind_mount
},
2954 { "edit", 2, VERB_ANY
, 0, edit_settings
},
2955 { "cat", 2, VERB_ANY
, 0, cat_settings
},
2956 { "copy-to", 3, 4, 0, copy_files
},
2957 { "copy-from", 3, 4, 0, copy_files
},
2958 { "remove", 2, VERB_ANY
, 0, remove_image
},
2959 { "rename", 3, 3, 0, rename_image
},
2960 { "clone", 3, 3, 0, clone_image
},
2961 { "read-only", 2, 3, 0, read_only_image
},
2962 { "start", 2, VERB_ANY
, 0, start_machine
},
2963 { "enable", 2, VERB_ANY
, 0, enable_machine
},
2964 { "disable", 2, VERB_ANY
, 0, enable_machine
},
2965 { "import-tar", 2, 3, 0, import_tar
},
2966 { "import-raw", 2, 3, 0, import_raw
},
2967 { "import-fs", 2, 3, 0, import_fs
},
2968 { "export-tar", 2, 3, 0, export_tar
},
2969 { "export-raw", 2, 3, 0, export_raw
},
2970 { "pull-tar", 2, 3, 0, pull_tar
},
2971 { "pull-raw", 2, 3, 0, pull_raw
},
2972 { "list-transfers", VERB_ANY
, 1, 0, list_transfers
},
2973 { "cancel-transfer", 2, VERB_ANY
, 0, cancel_transfer
},
2974 { "set-limit", 2, 3, 0, set_limit
},
2975 { "clean", VERB_ANY
, 1, 0, clean_images
},
2979 return dispatch_verb(argc
, argv
, verbs
, bus
);
2982 static int run(int argc
, char *argv
[]) {
2983 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
2986 setlocale(LC_ALL
, "");
2989 /* The journal merging logic potentially needs a lot of fds. */
2990 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
2994 r
= parse_argv(argc
, argv
);
2998 r
= bus_connect_transport(arg_transport
, arg_host
, RUNTIME_SCOPE_SYSTEM
, &bus
);
3000 return bus_log_connect_error(r
, arg_transport
);
3002 (void) sd_bus_set_allow_interactive_authorization(bus
, arg_ask_password
);
3004 return machinectl_main(argc
, argv
, bus
);
3007 DEFINE_MAIN_FUNCTION(run
);