HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/manager.c

215,074 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: e0aa34f4c11534f81d2a7e0a2a8c2aa218451eb3

Lines 3001–4000 of 5,689

        return n + manager_send_pending_reload_replies(m);
}
 
static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
 
        /* nothing else must be sent when using BARRIER=1 */
        if (strv_contains(tags, "BARRIER=1")) {
                if (strv_length(tags) != 1)
                        log_warning("Extra notification messages sent with BARRIER=1, ignoring everything.");
                else if (fdset_size(fds) != 1)
                        log_warning("Got incorrect number of fds with BARRIER=1, closing them.");
 
                /* Drop the message if BARRIER=1 was found */
                return true;
        }
 
        return false;
}
 
static void manager_invoke_notify_message(
                Manager *m,
                Unit *u,
                PidRef *pidref,
                const struct ucred *ucred,
                char * const *tags,
                FDSet *fds) {
 
        assert(m);
        assert(u);
        assert(pidref_is_set(pidref));
        assert(ucred);
        assert(pidref->pid == ucred->pid);
        assert(tags);
 
        if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
                return;
        u->notifygen = m->notifygen;
 
        if (UNIT_VTABLE(u)->notify_message)
                UNIT_VTABLE(u)->notify_message(u, pidref, ucred, tags, fds);
 
        else if (DEBUG_LOGGING) {
                _cleanup_free_ char *joined = strv_join(tags, ", ");
                char buf[CELLESCAPE_DEFAULT_LENGTH];
 
                log_unit_debug(u, "Got notification message from unexpected unit type, ignoring: %s",
                               joined ? cellescape(buf, sizeof(buf), joined) : "(null)");
        }
}
 
static int manager_get_units_for_pidref(Manager *m, const PidRef *pidref, Unit ***ret_units) {
        /* Determine array of every unit that is interested in the specified process */
 
        assert(m);
        assert(pidref_is_set(pidref));
 
        Unit *u1, *u2, **array;
        u1 = manager_get_unit_by_pidref_cgroup(m, pidref);
        u2 = hashmap_get(m->watch_pids, pidref);
        array = hashmap_get(m->watch_pids_more, pidref);
 
        size_t n = 0;
        if (u1)
                n++;
        if (u2)
                n++;
        if (array)
                for (size_t j = 0; array[j]; j++)
                        n++;
 
        assert(n <= INT_MAX); /* Make sure we can reasonably return the counter as "int" */
 
        if (ret_units) {
                _cleanup_free_ Unit **units = NULL;
 
                if (n > 0) {
                        units = new(Unit*, n + 1);
                        if (!units)
                                return -ENOMEM;
 
                        /* We return a dense array, and put the "main" unit first, i.e. unit in whose cgroup
                         * the process currently is. Note that we do not bother with filtering duplicates
                         * here. */
 
                        size_t i = 0;
                        if (u1)
                                units[i++] = u1;
                        if (u2)
                                units[i++] = u2;
                        if (array)
                                for (size_t j = 0; array[j]; j++)
                                        units[i++] = array[j];
                        assert(i == n);
 
                        units[i] = NULL; /* end array in an extra NULL */
                }
 
                *ret_units = TAKE_PTR(units);
        }
 
        return (int) n;
}
 
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        struct ucred ucred;
        _cleanup_(fdset_free_asyncp) FDSet *fds = NULL;
        int r;
 
        assert(m->notify_fd == fd);
 
        if (revents != EPOLLIN) {
                log_warning("Got unexpected poll event for notify fd.");
                return 0;
        }
 
        _cleanup_strv_free_ char **tags = NULL;
        r = notify_recv_with_fds_strv(m->notify_fd, &tags, &ucred, &pidref, &fds);
        if (r == -EAGAIN)
                return 0;
        if (r < 0)
                /* If this is any other, real error, then stop processing this socket. This of course means
                 * we won't take notification messages anymore, but that's still better than busy looping:
                 * being woken up over and over again, but being unable to actually read the message from the
                 * socket. */
                return r;
 
        /* Possibly a barrier fd, let's see. */
        if (manager_process_barrier_fd(tags, fds)) {
                log_debug("Received barrier notification message from PID " PID_FMT ".", pidref.pid);
                return 0;
        }
 
        /* Increase the generation counter used for filtering out duplicate unit invocations. */
        m->notifygen++;
 
        /* Notify every unit that might be interested, which might be multiple. */
        _cleanup_free_ Unit **array = NULL;
 
        int n_array = manager_get_units_for_pidref(m, &pidref, &array);
        if (n_array < 0) {
                log_warning_errno(n_array, "Failed to determine units for PID " PID_FMT ", ignoring: %m", pidref.pid);
                return 0;
        }
        if (n_array == 0)
                log_debug("Cannot find unit for notify message of PID "PID_FMT", ignoring.", pidref.pid);
        else
                /* And now invoke the per-unit callbacks. Note that manager_invoke_notify_message() will handle
                 * duplicate units – making sure we only invoke each unit's handler once. */
                FOREACH_ARRAY(u, array, n_array)
                        manager_invoke_notify_message(m, *u, &pidref, &ucred, tags, fds);
 
        if (!fdset_isempty(fds))
                log_warning("Got extra auxiliary fds with notification message, closing them.");
 
        return 0;
}
 
static void manager_invoke_sigchld_event(
                Manager *m,
                Unit *u,
                const siginfo_t *si) {
 
        assert(m);
        assert(u);
        assert(si);
 
        /* Already invoked the handler of this unit in this iteration? Then don't process this again */
        if (u->sigchldgen == m->sigchldgen)
                return;
        u->sigchldgen = m->sigchldgen;
 
        log_unit_debug(u, "Child "PID_FMT" belongs to %s.", si->si_pid, u->id);
        unit_unwatch_pidref(u, &PIDREF_MAKE_FROM_PID(si->si_pid));
 
        if (UNIT_VTABLE(u)->sigchld_event)
                UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
}
 
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        siginfo_t si = {};
        int r;
 
        assert(source);
 
        /* First we call waitid() for a PID and do not reap the zombie. That way we can still access
         * /proc/$PID for it while it is a zombie. */
 
        if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
 
                if (errno != ECHILD)
                        log_error_errno(errno, "Failed to peek for child with waitid(), ignoring: %m");
 
                goto turn_off;
        }
 
        if (si.si_pid <= 0)
                goto turn_off;
 
        if (SIGINFO_CODE_IS_DEAD(si.si_code)) {
                _cleanup_free_ char *name = NULL;
                (void) pid_get_comm(si.si_pid, &name);
 
                log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
                          si.si_pid, strna(name),
                          sigchld_code_to_string(si.si_code),
                          si.si_status,
                          strna(si.si_code == CLD_EXITED
                                ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
                                : signal_to_string(si.si_status)));
 
                /* Increase the generation counter used for filtering out duplicate unit invocations */
                m->sigchldgen++;
 
                /* We look this up by a PidRef that only consists of the PID. After all we couldn't create a
                 * pidfd here any more even if we wanted (since the process just exited). */
                PidRef pidref = PIDREF_MAKE_FROM_PID(si.si_pid);
 
                /* And now figure out the units this belongs to, there might be multiple... */
                _cleanup_free_ Unit **array = NULL;
                int n_array = manager_get_units_for_pidref(m, &pidref, &array);
                if (n_array < 0)
                        log_warning_errno(n_array, "Failed to get units for process " PID_FMT ", ignoring: %m", si.si_pid);
                else if (n_array == 0)
                        log_debug("Got SIGCHLD for process " PID_FMT " we weren't interested in, ignoring.", si.si_pid);
                else {
                        /* We check for an OOM condition, in case we got SIGCHLD before the OOM notification.
                         * We only do this for the cgroup the PID belonged to, which is the f */
                        (void) unit_check_oom(array[0]);
 
                        /* We check if systemd-oomd performed a kill so that we log and notify appropriately */
                        (void) unit_check_oomd_kill(array[0]);
 
                        /* Finally, execute them all. Note that the array might contain duplicates, but that's fine,
                         * manager_invoke_sigchld_event() will ensure we only invoke the handlers once for each
                         * iteration. */
                        FOREACH_ARRAY(u, array, n_array)
                                manager_invoke_sigchld_event(m, *u, &si);
                }
        }
 
        /* And now, we actually reap the zombie. */
        if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
                log_error_errno(errno, "Failed to dequeue child, ignoring: %m");
                return 0;
        }
 
        return 0;
 
turn_off:
        /* All children processed for now, turn off event source */
 
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
        if (r < 0)
                return log_error_errno(r, "Failed to disable SIGCHLD event source: %m");
 
        return 0;
}
 
static void manager_start_special_with_fallback(Manager *m, const char *name, const char *fallback, JobMode mode) {
        Job *job;
 
        if (manager_add_job_by_name_or_warn_with_fallback(m, JOB_START, name, fallback, mode, /* affected_jobs= */ NULL, &job) < 0)
                return;
 
        const char *s = unit_status_string(job->unit, NULL);
 
        log_info("Activating special unit %s...", s);
 
        (void) sd_notifyf(/* unset_environment= */ false,
                          "STATUS=Activating special unit %s...", s);
        m->status_ready = false;
}
 
static void manager_start_special(Manager *m, const char *name, JobMode mode) {
        manager_start_special_with_fallback(m, name, /* fallback= */ NULL, mode);
}
 
static void manager_handle_ctrl_alt_del(Manager *m) {
        assert(m);
 
        /* If the user presses C-A-D more than 7 times within 2s, we reboot/shutdown immediately,
         * unless it was disabled in system.conf. */
 
        if (ratelimit_below(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
                manager_start_special_with_fallback(
                                m,
                                SPECIAL_CTRL_ALT_DEL_TARGET,
                                FALLBACK_CTRL_ALT_DEL_TARGET,
                                JOB_REPLACE_IRREVERSIBLY);
        else
                emergency_action(
                                m,
                                m->cad_burst_action,
                                EMERGENCY_ACTION_WARN,
                                /* reboot_arg= */ NULL,
                                /* exit_status= */ -1,
                                "Ctrl-Alt-Del was pressed more than 7 times within 2s");
}
 
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        ssize_t n;
        struct signalfd_siginfo sfsi;
        int r;
 
        assert(m->signal_fd == fd);
 
        if (revents != EPOLLIN) {
                log_warning("Got unexpected events from signal file descriptor.");
                return 0;
        }
 
        n = read(m->signal_fd, &sfsi, sizeof(sfsi));
        if (n < 0) {
                if (ERRNO_IS_TRANSIENT(errno))
                        return 0;
 
                /* We return an error here, which will kill this handler,
                 * to avoid a busy loop on read error. */
                return log_error_errno(errno, "Reading from signal fd failed: %m");
        }
        if (n != sizeof(sfsi)) {
                log_warning("Truncated read from signal fd (%zi bytes), ignoring!", n);
                return 0;
        }
 
        log_received_signal(sfsi.ssi_signo == SIGCHLD ||
                            (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
                            ? LOG_DEBUG : LOG_INFO,
                            &sfsi);
 
        switch (sfsi.ssi_signo) {
 
        case SIGCHLD:
                r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
                if (r < 0)
                        log_warning_errno(r, "Failed to enable SIGCHLD event source, ignoring: %m");
 
                break;
 
        case SIGTERM:
                if (MANAGER_IS_SYSTEM(m)) {
                        /* This is for compatibility with the original sysvinit */
                        m->objective = MANAGER_REEXECUTE;
                        break;
                }
 
                _fallthrough_;
        case SIGINT:
                if (MANAGER_IS_SYSTEM(m))
                        manager_handle_ctrl_alt_del(m);
                else
                        manager_start_special(m, SPECIAL_EXIT_TARGET, JOB_REPLACE_IRREVERSIBLY);
                break;
 
        case SIGWINCH:
                /* This is a nop on non-init */
                if (MANAGER_IS_SYSTEM(m))
                        manager_start_special(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
 
                break;
 
        case SIGPWR:
                /* This is a nop on non-init */
                if (MANAGER_IS_SYSTEM(m))
                        manager_start_special(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
 
                break;
 
        case SIGUSR1:
                if (manager_dbus_is_running(m, false)) {
                        log_info("Trying to reconnect to bus...");
 
                        (void) bus_init_api(m);
 
                        if (MANAGER_IS_SYSTEM(m))
                                (void) bus_init_system(m);
                } else
                        manager_start_special(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
 
                break;
 
        case SIGUSR2: {
                _cleanup_free_ char *dump = NULL;
 
                r = manager_get_dump_string(m, /* patterns= */ NULL, &dump);
                if (r < 0) {
                        log_warning_errno(r, "Failed to acquire manager dump: %m");
                        break;
                }
 
                log_dump(LOG_INFO, dump);
                break;
        }
 
        case SIGHUP:
                m->objective = MANAGER_RELOAD;
                break;
 
        default: {
 
                if (MANAGER_IS_SYSTEM(m)) {
                        /* Starting SIGRTMIN+0 */
                        static const struct {
                                const char *target;
                                JobMode mode;
                        } target_table[] = {
                                [0] = { SPECIAL_DEFAULT_TARGET,     JOB_ISOLATE              },
                                [1] = { SPECIAL_RESCUE_TARGET,      JOB_ISOLATE              },
                                [2] = { SPECIAL_EMERGENCY_TARGET,   JOB_ISOLATE              },
                                [3] = { SPECIAL_HALT_TARGET,        JOB_REPLACE_IRREVERSIBLY },
                                [4] = { SPECIAL_POWEROFF_TARGET,    JOB_REPLACE_IRREVERSIBLY },
                                [5] = { SPECIAL_REBOOT_TARGET,      JOB_REPLACE_IRREVERSIBLY },
                                [6] = { SPECIAL_KEXEC_TARGET,       JOB_REPLACE_IRREVERSIBLY },
                                [7] = { SPECIAL_SOFT_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
                        };
 
                        /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
                        static const ManagerObjective objective_table[] = {
                                [0] = MANAGER_HALT,
                                [1] = MANAGER_POWEROFF,
                                [2] = MANAGER_REBOOT,
                                [3] = MANAGER_KEXEC,
                                [4] = MANAGER_SOFT_REBOOT,
                        };
 
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
                            (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
                                int idx = (int) sfsi.ssi_signo - SIGRTMIN;
                                manager_start_special(m, target_table[idx].target, target_table[idx].mode);
                                break;
                        }
 
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
                            (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(objective_table)) {
                                m->objective = objective_table[sfsi.ssi_signo - SIGRTMIN - 13];
                                break;
                        }
                }
 
                switch (sfsi.ssi_signo - SIGRTMIN) {
 
                case 18: {
                        bool generic = false;
 
                        if (sfsi.ssi_code != SI_QUEUE)
                                generic = true;
                        else {
                                /* Override a few select commands by our own PID1-specific logic */
 
                                switch (sfsi.ssi_int) {
 
                                case _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE..._COMMON_SIGNAL_COMMAND_LOG_LEVEL_END:
                                        manager_override_log_level(m, sfsi.ssi_int - _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE);
                                        break;
 
                                case COMMON_SIGNAL_COMMAND_CONSOLE:
                                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
                                        break;
 
                                case COMMON_SIGNAL_COMMAND_JOURNAL:
                                        manager_override_log_target(m, LOG_TARGET_JOURNAL);
                                        break;
 
                                case COMMON_SIGNAL_COMMAND_KMSG:
                                        manager_override_log_target(m, LOG_TARGET_KMSG);
                                        break;
 
                                case COMMON_SIGNAL_COMMAND_NULL:
                                        manager_override_log_target(m, LOG_TARGET_NULL);
                                        break;
 
                                case MANAGER_SIGNAL_COMMAND_DUMP_JOBS: {
                                        _cleanup_free_ char *dump_jobs = NULL;
 
                                        r = manager_get_dump_jobs_string(m, /* patterns= */ NULL, "  ", &dump_jobs);
                                        if (r < 0) {
                                                log_warning_errno(r, "Failed to acquire manager jobs dump: %m");
                                                break;
                                        }
 
                                        log_dump(LOG_INFO, dump_jobs);
                                        break;
                                }
 
                                default:
                                        generic = true;
                                }
                        }
 
                        if (generic)
                                return sigrtmin18_handler(source, &sfsi, NULL);
 
                        break;
                }
 
                case 20:
                        manager_override_show_status(m, SHOW_STATUS_YES, "signal");
                        break;
 
                case 21:
                        manager_override_show_status(m, SHOW_STATUS_NO, "signal");
                        break;
 
                case 22:
                        manager_override_log_level(m, LOG_DEBUG);
                        break;
 
                case 23:
                        manager_restore_original_log_level(m);
                        break;
 
                case 24:
                        if (MANAGER_IS_USER(m)) {
                                m->objective = MANAGER_EXIT;
                                return 0;
                        }
 
                        /* This is a nop on init */
                        break;
 
                case 25:
                        m->objective = MANAGER_REEXECUTE;
                        break;
 
                case 26:
                case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
                        manager_restore_original_log_target(m);
                        break;
 
                case 27:
                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
                        break;
 
                case 28:
                        manager_override_log_target(m, LOG_TARGET_KMSG);
                        break;
 
                default:
                        log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
                }
        }}
 
        return 0;
}
 
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        Unit *u;
 
        log_struct(LOG_DEBUG,
                   LOG_MESSAGE_ID(SD_MESSAGE_TIME_CHANGE_STR),
                   LOG_MESSAGE("Time has been changed"));
 
        /* Restart the watch */
        (void) manager_setup_time_change(m);
 
        HASHMAP_FOREACH(u, m->units)
                if (UNIT_VTABLE(u)->time_change)
                        UNIT_VTABLE(u)->time_change(u);
 
        return 0;
}
 
static int manager_dispatch_timezone_change(
                sd_event_source *source,
                const struct inotify_event *e,
                void *userdata) {
 
        Manager *m = ASSERT_PTR(userdata);
        int changed;
        Unit *u;
 
        log_debug("inotify event for /etc/localtime");
 
        changed = manager_read_timezone_stat(m);
        if (changed <= 0)
                return changed;
 
        /* Something changed, restart the watch, to ensure we watch the new /etc/localtime if it changed */
        (void) manager_setup_timezone_change(m);
 
        /* Read the new timezone */
        tzset();
 
        log_debug("Timezone has been changed (now: %s).", get_tzname(daylight));
 
        HASHMAP_FOREACH(u, m->units)
                if (UNIT_VTABLE(u)->timezone_change)
                        UNIT_VTABLE(u)->timezone_change(u);
 
        return 0;
}
 
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
 
        assert(m->idle_pipe[2] == fd);
 
        /* There's at least one Type=idle child that just gave up on us waiting for the boot process to
         * complete. Let's now turn off any further console output if there's at least one service that needs
         * console access, so that from now on our own output should not spill into that service's output
         * anymore. After all, we support Type=idle only to beautify console output and it generally is set
         * on services that want to own the console exclusively without our interference. */
        m->no_console_output = m->n_on_console > 0;
 
        /* Acknowledge the child's request, and let all other children know too that they shouldn't wait
         * any longer by closing the pipes towards them, which is what they are waiting for. */
        manager_close_idle_pipe(m);
 
        return 0;
}
 
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        int r;
 
        assert(source);
 
        manager_print_jobs_in_progress(m);
 
        r = sd_event_source_set_time_relative(source, JOBS_IN_PROGRESS_PERIOD_USEC);
        if (r < 0)
                return r;
 
        return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
}
 
int manager_loop(Manager *m) {
        int r;
 
        assert(m);
        assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
 
        manager_check_finished(m);
 
        /* There might still be some zombies hanging around from before we were exec()'ed. Let's reap them. */
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
        if (r < 0)
                return log_error_errno(r, "Failed to enable SIGCHLD event source: %m");
 
        while (m->objective == MANAGER_OK) {
 
                if (!ratelimit_below(&m->event_loop_ratelimit)) {
                        /* Yay, something is going seriously wrong, pause a little */
                        log_warning("Looping too fast. Throttling execution a little.");
                        sleep(1);
                }
 
                (void) watchdog_ping();
 
                if (manager_dispatch_load_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_gc_job_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_gc_unit_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_cleanup_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_cgroup_realize_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_start_when_upheld_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_stop_when_bound_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_release_resources_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_stop_notify_queue(m) > 0)
                        continue;
 
                if (manager_dispatch_dbus_queue(m) > 0)
                        continue;
 
                /* Sleep for watchdog runtime wait time */
                r = sd_event_run(m->event, watchdog_runtime_wait(/* divisor= */ 2));
                if (r < 0)
                        return log_error_errno(r, "Failed to run event loop: %m");
        }
 
        return m->objective;
}
 
int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
        _cleanup_free_ char *n = NULL;
        sd_id128_t invocation_id;
        Unit *u;
        int r;
 
        assert(m);
        assert(s);
        assert(_u);
 
        r = unit_name_from_dbus_path(s, &n);
        if (r < 0)
                return r;
 
        /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128-bit ID then
         * we use it as invocation ID. */
        r = sd_id128_from_string(n, &invocation_id);
        if (r >= 0) {
                u = hashmap_get(m->units_by_invocation_id, &invocation_id);
                if (u) {
                        *_u = u;
                        return 0;
                }
 
                return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID,
                                         "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.",
                                         SD_ID128_FORMAT_VAL(invocation_id));
        }
 
        /* If this didn't work, we check if this is a unit name */
        if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
                _cleanup_free_ char *nn = NULL;
 
                nn = cescape(n);
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS,
                                         "Unit name %s is neither a valid invocation ID nor unit name.", strnull(nn));
        }
 
        r = manager_load_unit(m, n, NULL, e, &u);
        if (r < 0)
                return r;
 
        *_u = u;
        return 0;
}
 
int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
        const char *p;
        unsigned id;
        Job *j;
        int r;
 
        assert(m);
        assert(s);
        assert(_j);
 
        p = startswith(s, "/org/freedesktop/systemd1/job/");
        if (!p)
                return -EINVAL;
 
        r = safe_atou(p, &id);
        if (r < 0)
                return r;
 
        j = manager_get_job(m, id);
        if (!j)
                return -ENOENT;
 
        *_j = j;
 
        return 0;
}
 
void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
 
#if HAVE_AUDIT
        _cleanup_free_ char *p = NULL;
        const char *msg;
        int audit_fd, r;
 
        assert(m);
        assert(u);
 
        if (!MANAGER_IS_SYSTEM(m))
                return;
 
        /* Don't generate audit events if the service was already started and we're just deserializing */
        if (MANAGER_IS_RELOADING(m))
                return;
 
        audit_fd = get_core_audit_fd();
        if (audit_fd < 0)
                return;
 
        r = unit_name_to_prefix_and_instance(u->id, &p);
        if (r < 0) {
                log_warning_errno(r, "Failed to extract prefix and instance of unit name, ignoring: %m");
                return;
        }
 
        msg = strjoina("unit=", p);
        if (sym_audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
                if (ERRNO_IS_PRIVILEGE(errno)) {
                        /* We aren't allowed to send audit messages?  Then let's not retry again. */
                        log_debug_errno(errno, "Failed to send audit message, closing audit socket: %m");
                        close_core_audit_fd();
                } else
                        log_warning_errno(errno, "Failed to send audit message, ignoring: %m");
        }
#endif
}
 
void manager_send_unit_plymouth(Manager *m, Unit *u) {
        _cleanup_free_ char *message = NULL;
        int c, r;
 
        assert(m);
        assert(u);
 
        if (!MANAGER_IS_SYSTEM(m))
                return;
 
        /* Don't generate plymouth events if the service was already started and we're just deserializing */
        if (MANAGER_IS_RELOADING(m))
                return;
 
        if (detect_container() > 0)
                return;
 
        if (!UNIT_VTABLE(u)->notify_plymouth)
                return;
 
        c = asprintf(&message, "U\x02%c%s%c", (int) (strlen(u->id) + 1), u->id, '\x00');
        if (c < 0)
                return (void) log_oom();
 
        /* We set SOCK_NONBLOCK here so that we rather drop the message then wait for plymouth */
        r = plymouth_send_raw(message, c, SOCK_NONBLOCK);
        if (r < 0)
                log_full_errno(ERRNO_IS_NO_PLYMOUTH(r) ? LOG_DEBUG : LOG_WARNING, r,
                               "Failed to communicate with plymouth: %m");
}
 
void manager_send_unit_supervisor(Manager *m, Unit *u, bool active) {
        assert(m);
        assert(u);
 
        /* Notify a "supervisor" process about our progress, i.e. a container manager, hypervisor, or
         * surrounding service manager. */
 
        if (MANAGER_IS_RELOADING(m))
                return;
 
        if (!UNIT_VTABLE(u)->notify_supervisor)
                return;
 
        if (in_initrd()) /* Only send these once we left the initrd */
                return;
 
        (void) sd_notifyf(/* unset_environment= */ false,
                          active ? "X_SYSTEMD_UNIT_ACTIVE=%s" : "X_SYSTEMD_UNIT_INACTIVE=%s",
                          u->id);
}
 
usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
        assert(m);
 
        if (MANAGER_IS_USER(m))
                return USEC_INFINITY;
 
        if (m->watchdog_overridden[t] != USEC_INFINITY)
                return m->watchdog_overridden[t];
 
        return m->watchdog[t];
}
 
void manager_set_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
 
        assert(m);
 
        if (MANAGER_IS_USER(m))
                return;
 
        if (m->watchdog_overridden[t] == USEC_INFINITY) {
                if (t == WATCHDOG_RUNTIME)
                        (void) watchdog_setup(timeout);
                else if (t == WATCHDOG_PRETIMEOUT)
                        (void) watchdog_setup_pretimeout(timeout);
        }
 
        m->watchdog[t] = timeout;
}
 
void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
        usec_t usec;
 
        assert(m);
 
        if (MANAGER_IS_USER(m))
                return;
 
        usec = timeout == USEC_INFINITY ? m->watchdog[t] : timeout;
        if (t == WATCHDOG_RUNTIME)
                (void) watchdog_setup(usec);
        else if (t == WATCHDOG_PRETIMEOUT)
                (void) watchdog_setup_pretimeout(usec);
 
        m->watchdog_overridden[t] = timeout;
}
 
int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
        _cleanup_free_ char *p = NULL;
        int r;
 
        assert(m);
 
        if (MANAGER_IS_USER(m))
                return 0;
 
        governor = empty_to_null(governor);
 
        if (streq_ptr(m->watchdog_pretimeout_governor, governor))
                return 0;
 
        r = strdup_to(&p, governor);
        if (r < 0)
                return r;
 
        r = watchdog_setup_pretimeout_governor(governor);
        if (r < 0)
                return r;
 
        return free_and_replace(m->watchdog_pretimeout_governor, p);
}
 
int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor) {
        _cleanup_free_ char *p = NULL;
        int r;
 
        assert(m);
 
        if (MANAGER_IS_USER(m))
                return 0;
 
        governor = empty_to_null(governor);
 
        if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
                return 0;
 
        r = strdup_to(&p, governor);
        if (r < 0)
                return r;
 
        r = watchdog_setup_pretimeout_governor(governor);
        if (r < 0)
                return r;
 
        return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
}
 
int manager_reload(Manager *m) {
        _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
        _cleanup_strv_free_ char **saved_subscribed_as_strv = NULL;
        _cleanup_fdset_free_ FDSet *fds = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        sd_id128_t saved_deserialized_bus_id;
        int r;
 
        assert(m);
 
        r = manager_open_serialization(m, &f);
        if (r < 0)
                return log_error_errno(r, "Failed to create serialization file: %m");
 
        fds = fdset_new();
        if (!fds)
                return log_oom();
 
        /* We are officially in reload mode from here on. */
        reloading = manager_reloading_start(m);
 
        r = manager_serialize(m, f, fds, false);
        if (r < 0)
                return r;
 
        r = finish_serialization_file(f);
        if (r < 0)
                return log_error_errno(r, "Failed to finish serialization: %m");
 
        /* 💀 This is the point of no return, from here on there is no way back. 💀 */
        reloading = NULL;
 
        /* Bump before sending the Reloading signal, so any client that reads
         * ReloadCount in response to that signal observes the new value. */
        m->reload_count = saturate_add(m->reload_count, 1, UINT64_MAX);
 
        bus_manager_send_reloading(m, true);
 
        /* Start by flushing out all jobs and units, all generated units, all runtime environments, all dynamic users
         * and everything else that is worth flushing out. We'll get it all back from the serialization — if we need
         * it. */
 
        manager_clear_jobs_and_units(m);
        lookup_paths_flush_generator(&m->lookup_paths);