HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/run/run.c
Git blob: b4b5df1634fa3cb574305a65a1bfab1e48a1c5dd
Lines 1001–2000 of 3,060
if (custom_slice && arg_lightweight >= 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--lightweight= may not be combined with a custom slice");
if (custom_slice && !isempty(arg_area))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--area= may not be combined with a custom slice");
if (!strv_isempty(args)) {
if (arg_validate)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Option '--validate' cannot be used with a command");
l = strv_copy(args);
if (!l)
return log_oom();
} else if (!arg_via_shell) {
const char *e;
arg_default_command = true;
e = strv_env_get(arg_environment, "SHELL");
if (e) {
arg_exec_path = strdup(e);
if (!arg_exec_path)
return log_oom();
} else {
if (arg_transport == BUS_TRANSPORT_LOCAL) {
r = get_shell(&arg_exec_path);
if (r < 0)
return log_error_errno(r, "Failed to determine shell: %m");
} else {
arg_exec_path = strdup("/bin/sh");
if (!arg_exec_path)
return log_oom();
}
r = strv_env_assign(&arg_environment, "SHELL", arg_exec_path);
if (r < 0)
return log_error_errno(r, "Failed to set $SHELL environment variable: %m");
}
l = make_login_shell_cmdline(arg_exec_path);
if (!l)
return log_oom();
}
if (arg_via_shell) {
arg_exec_path = strdup(_PATH_BSHELL);
if (!arg_exec_path)
return log_oom();
r = strv_prepend(&l, "-sh");
if (r < 0)
return log_oom();
}
strv_free_and_replace(arg_cmdline, l);
if (!custom_slice) {
arg_slice = strdup(SPECIAL_USER_SLICE);
if (!arg_slice)
return log_oom();
}
_cleanup_free_ char *un = NULL;
un = getusername_malloc();
if (!un)
return log_oom();
/* Set a bunch of environment variables in a roughly sudo-compatible way */
r = strv_env_assign(&arg_environment, "SUDO_USER", un);
if (r < 0)
return log_error_errno(r, "Failed to set $SUDO_USER environment variable: %m");
r = strv_env_assignf(&arg_environment, "SUDO_UID", UID_FMT, getuid());
if (r < 0)
return log_error_errno(r, "Failed to set $SUDO_UID environment variable: %m");
r = strv_env_assignf(&arg_environment, "SUDO_GID", GID_FMT, getgid());
if (r < 0)
return log_error_errno(r, "Failed to set $SUDO_GID environment variable: %m");
if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_UID=" UID_FMT, getuid()) < 0)
return log_oom();
if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_GID=" GID_FMT, getgid()) < 0)
return log_oom();
if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_USER=%s", un) < 0)
return log_oom();
if (strv_extend(&arg_property, "PAMName=systemd-run0") < 0)
return log_oom();
/* The service manager ignores SIGPIPE for all spawned processes by default. Let's explicitly override
* that here, since we're primarily invoked in interactive environments where this does matter. */
if (strv_extend(&arg_property, "IgnoreSIGPIPE=no") < 0)
return log_oom();
if (!arg_background && arg_stdio == ARG_STDIO_PTY) {
r = terminal_tint_color(shell_prompt_hue(), &arg_background);
if (r < 0)
log_debug_errno(r, "Unable to get terminal background color, not tinting background: %m");
}
if (!arg_shell_prompt_prefix) {
const char *e = secure_getenv("SYSTEMD_RUN_SHELL_PROMPT_PREFIX");
if (e) {
arg_shell_prompt_prefix = strdup(e);
if (!arg_shell_prompt_prefix)
return log_oom();
} else if (emoji_enabled()) {
arg_shell_prompt_prefix = strjoin(glyph(shell_prompt_glyph()), " ");
if (!arg_shell_prompt_prefix)
return log_oom();
}
}
if (!isempty(arg_shell_prompt_prefix)) {
r = strv_env_assign(&arg_environment, "SHELL_PROMPT_PREFIX", arg_shell_prompt_prefix);
if (r < 0)
return log_error_errno(r, "Failed to set $SHELL_PROMPT_PREFIX environment variable: %m");
}
if (!strv_env_get(arg_environment, "XDG_SESSION_CLASS")) {
const char *class = NULL;
if (custom_slice)
class = "none";
/* If logging into an area, imply lightweight mode */
else if (arg_lightweight < 0 && !isempty(arg_area))
arg_lightweight = true;
/* When using run0 to acquire privileges temporarily, let's not pull in session manager by
* default. Note that pam_logind/systemd-logind doesn't distinguish between run0-style privilege
* escalation on a TTY and first class (getty-style) TTY logins (and thus gives root a per-session
* manager for interactive TTY sessions), hence let's override the logic explicitly here. We only do
* this for root or --empower though, under the assumption that if a regular user temporarily
* transitions into another regular user it's a better default that the full user environment is
* uniformly available. */
else if (arg_lightweight < 0 && (become_root() || arg_empower))
arg_lightweight = true;
if (arg_lightweight >= 0)
class = arg_lightweight ? (arg_stdio == ARG_STDIO_PTY ? (become_root() ? "user-early-light" : "user-light") : "background-light") :
(arg_stdio == ARG_STDIO_PTY ? (become_root() ? "user-early" : "user") : "background");
if (class) {
log_debug("Setting XDG_SESSION_CLASS to '%s'.", class);
r = strv_env_assign(&arg_environment, "XDG_SESSION_CLASS", class);
if (r < 0)
return log_error_errno(r, "Failed to set $XDG_SESSION_CLASS environment variable: %m");
}
}
if (arg_area) {
r = strv_env_assign(&arg_environment, "XDG_AREA", arg_area);
if (r < 0)
return log_error_errno(r, "Failed to set $XDG_AREA environment variable: %m");
}
return 1;
}
static int transient_unit_set_properties(sd_bus_message *m, UnitType t, char **properties) {
int r;
assert(m);
r = sd_bus_message_append(m, "(sv)", "Description", "s", arg_description);
if (r < 0)
return bus_log_create_error(r);
if (arg_aggressive_gc) {
r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed");
if (r < 0)
return bus_log_create_error(r);
}
r = sd_bus_is_bus_client(sd_bus_message_get_bus(m));
if (r < 0)
return log_error_errno(r, "Can't determine if bus connection is direct or to broker: %m");
if (r > 0) {
/* Pin the object as least as long as we are around. Note that AddRef (currently) only works
* if we talk via the bus though. */
r = sd_bus_message_append(m, "(sv)", "AddRef", "b", 1);
if (r < 0)
return bus_log_create_error(r);
}
return bus_append_unit_property_assignment_many(m, t, properties);
}
static int transient_cgroup_set_properties(sd_bus_message *m) {
_cleanup_free_ char *name = NULL;
_cleanup_free_ char *slice = NULL;
int r;
assert(m);
if (arg_slice_inherit) {
char *end;
switch (arg_runtime_scope) {
case RUNTIME_SCOPE_USER:
r = cg_pid_get_user_slice(0, &name);
break;
case RUNTIME_SCOPE_SYSTEM:
r = cg_pid_get_slice(0, &name);
break;
default:
assert_not_reached();
}
if (r < 0)
return log_error_errno(r, "Failed to get PID slice: %m");
end = endswith(name, ".slice");
if (!end)
return -ENXIO;
*end = 0;
}
if (!isempty(arg_slice) && !strextend_with_separator(&name, "-", arg_slice))
return log_oom();
if (!name)
return 0;
r = unit_name_mangle_with_suffix(name, "as slice",
arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
".slice", &slice);
if (r < 0)
return log_error_errno(r, "Failed to mangle name '%s': %m", arg_slice);
r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
if (r < 0)
return bus_log_create_error(r);
return 0;
}
static int transient_kill_set_properties(sd_bus_message *m) {
int r;
assert(m);
if (arg_send_sighup) {
r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", arg_send_sighup);
if (r < 0)
return bus_log_create_error(r);
}
return 0;
}
static int transient_service_set_properties(sd_bus_message *m, const char *pty_path, int pty_fd) {
int r, send_term; /* tri-state */
/* Use ExecStartEx if new exec flags are required. */
bool use_ex_prop = !arg_expand_environment || arg_via_shell;
assert(m);
assert((!!pty_path) == (pty_fd >= 0));
r = transient_unit_set_properties(m, UNIT_SERVICE, arg_property);
if (r < 0)
return r;
r = transient_kill_set_properties(m);
if (r < 0)
return r;
r = transient_cgroup_set_properties(m);
if (r < 0)
return r;
if (arg_remain_after_exit) {
r = sd_bus_message_append(m, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit);
if (r < 0)
return bus_log_create_error(r);
}
if (arg_service_type) {
r = sd_bus_message_append(m, "(sv)", "Type", "s", arg_service_type);
if (r < 0)
return bus_log_create_error(r);
}
if (arg_exec_user) {
r = sd_bus_message_append(m, "(sv)", "User", "s", arg_exec_user);
if (r < 0)
return bus_log_create_error(r);
}
if (arg_exec_group) {
r = sd_bus_message_append(m, "(sv)", "Group", "s", arg_exec_group);
if (r < 0)
return bus_log_create_error(r);
}
if (arg_empower) {
r = sd_bus_message_append(m, "(sv)", "AmbientCapabilities", "t", CAP_MASK_ALL);
if (r < 0)
return bus_log_create_error(r);
r = getgrnam_malloc("empower", /* ret= */ NULL);
if (r < 0 && r != -ESRCH)
return log_error_errno(r, "Failed to look up group 'empower' via NSS: %m");
if (r >= 0) {
r = sd_bus_message_append(m, "(sv)", "SupplementaryGroups", "as", 1, "empower");
if (r < 0)
return bus_log_create_error(r);
}
}
if (arg_nice_set) {
r = sd_bus_message_append(m, "(sv)", "Nice", "i", arg_nice);
if (r < 0)
return bus_log_create_error(r);
}
if (arg_working_directory) {
r = sd_bus_message_append(m, "(sv)", "WorkingDirectory", "s", arg_working_directory);
if (r < 0)
return bus_log_create_error(r);
}
if (arg_root_directory) {
_cleanup_close_ int fd = open_tree(AT_FDCWD, arg_root_directory, OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_RECURSIVE);
if (fd < 0)
return log_error_errno(errno, "Failed to clone mount tree at '%s': %m", arg_root_directory);
r = sd_bus_message_append(m, "(sv)", "RootDirectoryFileDescriptor", "h", fd);
if (r < 0)
return bus_log_create_error(r);
}
if (pty_path) {
r = sd_bus_message_append(m, "(sv)(sv)(sv)(sv)",
"TTYPath", "s", pty_path,
"StandardInputFileDescriptor", "h", pty_fd,
"StandardOutputFileDescriptor", "h", pty_fd,
"StandardErrorFileDescriptor", "h", pty_fd);
if (r < 0)
return bus_log_create_error(r);
send_term = true;
} else if (arg_stdio == ARG_STDIO_DIRECT) {
r = sd_bus_message_append(m,
"(sv)(sv)(sv)",
"StandardInputFileDescriptor", "h", STDIN_FILENO,
"StandardOutputFileDescriptor", "h", STDOUT_FILENO,
"StandardErrorFileDescriptor", "h", STDERR_FILENO);
if (r < 0)
return bus_log_create_error(r);
send_term = -1;
} else
send_term = false;
if (send_term != 0) {
const char *e, *colorterm = NULL, *no_color = NULL;
/* Propagate $TERM + $COLORTERM + $NO_COLOR if we are actually connected to a TTY */
if (isatty_safe(STDIN_FILENO) || isatty_safe(STDOUT_FILENO) || isatty_safe(STDERR_FILENO)) {
e = strv_find_prefix(environ, "TERM=");
send_term = !!e;
if (send_term) {
/* If we send $TERM along, then also propagate $COLORTERM + $NO_COLOR right with it */
colorterm = strv_find_prefix(environ, "COLORTERM=");
no_color = strv_find_prefix(environ, "NO_COLOR=");
}
} else
/* If we are not connected to any TTY ourselves, then send TERM=dumb, but only if we
* really need to (because we actually allocated a TTY for the service) */
e = "TERM=dumb";
if (send_term > 0) {
r = sd_bus_message_append(
m,
"(sv)",
"Environment", "as", 1, e);
if (r < 0)
return bus_log_create_error(r);
if (colorterm) {
r = sd_bus_message_append(
m,
"(sv)",
"Environment", "as", 1, colorterm);
if (r < 0)
return bus_log_create_error(r);
}
if (no_color) {
r = sd_bus_message_append(
m,
"(sv)",
"Environment", "as", 1, no_color);
if (r < 0)
return bus_log_create_error(r);
}
}
}
if (!strv_isempty(arg_environment)) {
r = sd_bus_message_open_container(m, 'r', "sv");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append(m, "s", "Environment");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'v', "as");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_strv(m, arg_environment);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
}
/* Exec container */
if (!strv_isempty(arg_cmdline)) {
r = sd_bus_message_open_container(m, 'r', "sv");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append(m, "s",
use_ex_prop ? "ExecStartEx" : "ExecStart");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'v',
use_ex_prop ? "a(sasas)" : "a(sasb)");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'a',
use_ex_prop ? "(sasas)" : "(sasb)");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, 'r',
use_ex_prop ? "sasas" : "sasb");
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append(m, "s", arg_exec_path ?: arg_cmdline[0]);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_append_strv(m, arg_cmdline);
if (r < 0)
return bus_log_create_error(r);
if (use_ex_prop) {
_cleanup_strv_free_ char **opts = NULL;
r = exec_command_flags_to_strv(
(arg_expand_environment ? 0 : EXEC_COMMAND_NO_ENV_EXPAND)|
(arg_ignore_failure ? EXEC_COMMAND_IGNORE_FAILURE : 0)|
(arg_via_shell ? EXEC_COMMAND_VIA_SHELL : 0),
&opts);
if (r < 0)
return log_error_errno(r, "Failed to format execute flags: %m");
r = sd_bus_message_append_strv(m, opts);
} else
r = sd_bus_message_append(m, "b", arg_ignore_failure);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
}
return 0;
}
static int transient_scope_set_properties(sd_bus_message *m, bool allow_pidfd) {
int r;
assert(m);
r = transient_unit_set_properties(m, UNIT_SCOPE, arg_property);
if (r < 0)
return r;
r = transient_kill_set_properties(m);
if (r < 0)
return r;
r = transient_cgroup_set_properties(m);
if (r < 0)
return r;
_cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
r = pidref_set_self(&pidref);
if (r < 0)
return r;
r = bus_append_scope_pidref(m, &pidref, allow_pidfd);
if (r < 0)
return bus_log_create_error(r);
return 0;
}
static int transient_timer_set_properties(sd_bus_message *m) {
int r;
assert(m);
r = transient_unit_set_properties(m, UNIT_TIMER, arg_timer_property);
if (r < 0)
return r;
/* Automatically clean up our transient timers */
r = sd_bus_message_append(m, "(sv)", "RemainAfterElapse", "b", false);
if (r < 0)
return bus_log_create_error(r);
return 0;
}
static int make_unit_name(UnitType t, char **ret) {
int r;
assert(t >= 0);
assert(t < _UNIT_TYPE_MAX);
assert(ret);
/* Preferably use our PID + pidfd ID as identifier, if available. It's a boot time unique identifier
* managed by the kernel. Unfortunately only new kernels support this, hence we keep some fallback
* logic in place. */
_cleanup_(pidref_done) PidRef self = PIDREF_NULL;
r = pidref_set_self(&self);
if (r < 0)
return log_error_errno(r, "Failed to get reference to my own process: %m");
r = pidref_acquire_pidfd_id(&self);
if (r < 0) {
log_debug_errno(r, "Failed to acquire pidfd ID of myself, defaulting to randomized unit name: %m");
/* We couldn't get the pidfd id. In that case, just pick a random uuid as name */
sd_id128_t rnd;
r = sd_id128_randomize(&rnd);
if (r < 0)
return log_error_errno(r, "Failed to generate random run unit name: %m");
r = asprintf(ret, "run-r" SD_ID128_FORMAT_STR ".%s", SD_ID128_FORMAT_VAL(rnd), unit_type_to_string(t));
} else
r = asprintf(ret, "run-p" PID_FMT "-i%" PRIu64 ".%s", self.pid, self.fd_id, unit_type_to_string(t));
if (r < 0)
return log_oom();
return 0;
}
static int connect_bus(sd_bus **ret) {
_cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
int r;
assert(ret);
/* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the
* limited direct connection */
if (arg_wait ||
arg_stdio != ARG_STDIO_NONE ||
(arg_runtime_scope == RUNTIME_SCOPE_USER && !IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_CAPSULE)))
r = bus_connect_transport(arg_transport, arg_host, arg_runtime_scope, &bus);
else
r = bus_connect_transport_systemd(arg_transport, arg_host, arg_runtime_scope, &bus);
if (r < 0)
return bus_log_connect_error(r, arg_transport, arg_runtime_scope);
(void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
*ret = TAKE_PTR(bus);
return 0;
}
typedef struct RunContext {
sd_event *event;
PTYForward *forward;
char *unit;
char *bus_path;
char *start_job;
int pty_fd;
/* Bus objects */
sd_bus *bus;
sd_bus_slot *match_properties_changed;
sd_bus_slot *match_disconnected;
sd_event_source *retry_timer;
/* Current state of the unit */
char *active_state;
char *job;
/* The exit data of the unit */
uint64_t inactive_exit_usec;
uint64_t inactive_enter_usec;
char *result;
uint64_t cpu_usage_nsec;
uint64_t memory_peak;
uint64_t memory_swap_peak;
uint64_t ip_ingress_bytes;
uint64_t ip_egress_bytes;
uint64_t io_read_bytes;
uint64_t io_write_bytes;
uint32_t exit_code;
uint32_t exit_status;
} RunContext;
static int run_context_update(RunContext *c);
static int run_context_attach_bus(RunContext *c, sd_bus *bus);
static void run_context_detach_bus(RunContext *c);
static int run_context_reconnect(RunContext *c);
static int run_context_setup_ptyfwd(RunContext *c);
static void run_context_done(RunContext *c) {
assert(c);
run_context_detach_bus(c);
c->retry_timer = sd_event_source_disable_unref(c->retry_timer);
c->forward = pty_forward_free(c->forward);
c->event = sd_event_unref(c->event);
free(c->active_state);
free(c->job);
free(c->result);
free(c->unit);
free(c->bus_path);
free(c->start_job);
safe_close(c->pty_fd);
}
static int on_retry_timer(sd_event_source *s, uint64_t usec, void *userdata) {
RunContext *c = ASSERT_PTR(userdata);
c->retry_timer = sd_event_source_disable_unref(c->retry_timer);
return run_context_reconnect(c);
}
static int run_context_reconnect(RunContext *c) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
int r;
assert(c);
run_context_detach_bus(c);
r = connect_bus(&bus);
if (r < 0)
goto retry_timer;
r = sd_bus_call_method(bus,
"org.freedesktop.systemd1",
c->bus_path,
"org.freedesktop.systemd1.Unit",
"Ref",
&error,
/* ret_reply= */ NULL,
/* types= */ NULL);
if (r < 0) {
/* Hmm, the service manager probably hasn't finished reexecution just yet? Try again later. */
if (bus_error_is_connection(&error) || bus_error_is_unknown_service(&error))
goto retry_timer;
if (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_OBJECT))
log_warning_errno(r, "Unit deactivated during reconnection to the bus, exiting.");
else
log_error_errno(r, "Failed to re-add reference to unit: %s", bus_error_message(&error, r));
(void) sd_event_exit(c->event, EXIT_FAILURE);
return r;
}
r = run_context_attach_bus(c, bus);
if (r < 0) {
(void) sd_event_exit(c->event, EXIT_FAILURE);
return r;
}
log_info("Reconnected to bus.");
return run_context_update(c);
retry_timer:
log_warning_errno(r, "Failed to reconnect, retrying in 2s: %m");
r = event_reset_time_relative(
c->event,
&c->retry_timer,
CLOCK_MONOTONIC,
2 * USEC_PER_SEC, /* accuracy= */ 0,
on_retry_timer, c,
SD_EVENT_PRIORITY_NORMAL,
"retry-timeout",
/* force_reset= */ false);
if (r < 0) {
(void) sd_event_exit(c->event, EXIT_FAILURE);
return log_error_errno(r, "Failed to install retry timer: %m");
}
return 0;
}
static int run_context_check_started(RunContext *c) {
int r;
assert(c);
if (!c->start_job)
return 0; /* Already started? */
if (streq_ptr(c->start_job, c->job))
return 0; /* The start job is still active. */
/* The start job is finished. */
c->start_job = mfree(c->start_job);
/* Setup ptyfwd now if --pty-late is specified. */
r = run_context_setup_ptyfwd(c);
if (r < 0) {
(void) sd_event_exit(c->event, EXIT_FAILURE);
return r;
}
if (STRPTR_IN_SET(c->active_state, "inactive", "failed"))
return 0; /* Already finished or failed? */
/* Notify our caller that the service is now running, just in case. */
(void) sd_notifyf(/* unset_environment= */ false,
"READY=1\n"
"RUN_UNIT=%s",
c->unit);
return 0;
}
static void run_context_check_done(RunContext *c) {
int r;
assert(c);
if (!STRPTR_IN_SET(c->active_state, "inactive", "failed") ||
c->start_job || /* our start job */
c->job) /* any other job */
return;
if (!c->forward)
return (void) sd_event_exit(c->event, EXIT_SUCCESS);
/* If the service is gone, it's time to drain the output */
r = pty_forward_drain(c->forward);
if (r < 0) {
log_error_errno(r, "Failed to drain PTY forwarder: %m");
return (void) sd_event_exit(c->event, EXIT_FAILURE);
}
/* Tell the forwarder to exit on the next vhangup(), so that we still flush out what might be queued
* and exit then. */
r = pty_forward_honor_vhangup(c->forward);
if (r < 0) {
log_error_errno(r, "Failed to make PTY forwarder honor vhangup(): %m");
return (void) sd_event_exit(c->event, EXIT_FAILURE);
}
}
static int map_job(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
char **p = ASSERT_PTR(userdata);
const char *job;
uint32_t id;
int r;
assert(m);
r = sd_bus_message_read(m, "(uo)", &id, &job);
if (r < 0)
return r;
return free_and_strdup(p, id == 0 ? NULL : job);
}
static int run_context_update(RunContext *c) {
static const struct bus_properties_map map[] = {
{ "ActiveState", "s", NULL, offsetof(RunContext, active_state) },
{ "InactiveExitTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_exit_usec) },
{ "InactiveEnterTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_enter_usec) },
{ "Result", "s", NULL, offsetof(RunContext, result) },
{ "ExecMainCode", "i", NULL, offsetof(RunContext, exit_code) },
{ "ExecMainStatus", "i", NULL, offsetof(RunContext, exit_status) },
{ "CPUUsageNSec", "t", NULL, offsetof(RunContext, cpu_usage_nsec) },
{ "MemoryPeak", "t", NULL, offsetof(RunContext, memory_peak) },
{ "MemorySwapPeak", "t", NULL, offsetof(RunContext, memory_swap_peak) },
{ "IPIngressBytes", "t", NULL, offsetof(RunContext, ip_ingress_bytes) },
{ "IPEgressBytes", "t", NULL, offsetof(RunContext, ip_egress_bytes) },
{ "IOReadBytes", "t", NULL, offsetof(RunContext, io_read_bytes) },
{ "IOWriteBytes", "t", NULL, offsetof(RunContext, io_write_bytes) },
{ "Job", "(uo)", map_job, offsetof(RunContext, job) },
{}
};
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
int r;
assert(c);
assert(c->bus);
r = bus_map_all_properties(
c->bus,
"org.freedesktop.systemd1",
c->bus_path,
map,
BUS_MAP_STRDUP,
&error,
NULL,
c);
if (r < 0) {
/* If this is a connection error, then try to reconnect. This might be because the service
* manager is being restarted. Handle this gracefully. */
if (bus_error_is_connection(&error) || bus_error_is_unknown_service(&error)) {
log_info_errno(r, "Bus call failed due to connection problems. Trying to reconnect...");
/* Not propagating error, because we handled it already, by reconnecting. */
return run_context_reconnect(c);
}
(void) sd_event_exit(c->event, EXIT_FAILURE);
return log_error_errno(r, "Failed to query unit state: %s", bus_error_message(&error, r));
}
r = run_context_check_started(c);
if (r < 0)
return r;
run_context_check_done(c);
return 0;
}
static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
return run_context_update(ASSERT_PTR(userdata));
}
static int on_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
/* If our connection gets terminated, then try to reconnect. This might be because the service
* manager is being restarted. Handle this gracefully. */
log_info("Got disconnected from bus connection. Trying to reconnect...");
return run_context_reconnect(ASSERT_PTR(userdata));
}
static int run_context_attach_bus(RunContext *c, sd_bus *bus) {
int r;
assert(c);
assert(bus);
assert(!c->bus);
assert(!c->match_properties_changed);
assert(!c->match_disconnected);
c->bus = sd_bus_ref(bus);
r = sd_bus_match_signal_async(
c->bus,
&c->match_properties_changed,
"org.freedesktop.systemd1",
c->bus_path,
"org.freedesktop.DBus.Properties",
"PropertiesChanged",
on_properties_changed, NULL, c);
if (r < 0)
return log_error_errno(r, "Failed to request PropertiesChanged signal match: %m");
r = sd_bus_match_signal_async(
bus,
&c->match_disconnected,
"org.freedesktop.DBus.Local",
/* path= */ NULL,
"org.freedesktop.DBus.Local",
"Disconnected",
on_disconnected, NULL, c);
if (r < 0)
return log_error_errno(r, "Failed to request Disconnected signal match: %m");
r = sd_bus_attach_event(c->bus, c->event, SD_EVENT_PRIORITY_NORMAL);
if (r < 0)
return log_error_errno(r, "Failed to attach bus to event loop: %m");
return 0;
}
static void run_context_detach_bus(RunContext *c) {
assert(c);
if (c->bus) {
(void) sd_bus_detach_event(c->bus);
c->bus = sd_bus_unref(c->bus);
}
c->match_properties_changed = sd_bus_slot_unref(c->match_properties_changed);
c->match_disconnected = sd_bus_slot_unref(c->match_disconnected);
}
static int pty_forward_handler(PTYForward *f, int rcode, void *userdata) {
RunContext *c = ASSERT_PTR(userdata);
assert(f);
if (rcode == -ECANCELED) {
log_debug_errno(rcode, "PTY forwarder disconnected.");
if (!arg_wait)
return sd_event_exit(c->event, EXIT_SUCCESS);
/* If --wait is specified, we'll only exit the pty forwarding, but will continue to wait
* for the service to end. If the user hits ^C we'll exit too. */
} else if (rcode < 0) {
(void) sd_event_exit(c->event, EXIT_FAILURE);
return log_error_errno(rcode, "Error on PTY forwarding logic: %m");
}
c->forward = pty_forward_free(c->forward);
run_context_check_done(c);
return 0;
}
static int make_transient_service_unit(
sd_bus *bus,
sd_bus_message **message,
const char *service,
const char *pty_path,
int pty_fd) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
int r;
assert(bus);
assert(message);
assert(service);
r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
if (r < 0)
return bus_log_create_error(r);
/* Name and mode */
r = sd_bus_message_append(m, "ss", service, job_mode_to_string(arg_job_mode));
if (r < 0)
return bus_log_create_error(r);
/* Properties */
r = sd_bus_message_open_container(m, 'a', "(sv)");
if (r < 0)
return bus_log_create_error(r);
r = transient_service_set_properties(m, pty_path, pty_fd);
if (r < 0)
return r;
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
/* Auxiliary units */
r = sd_bus_message_append(m, "a(sa(sv))", 0);