5 #include <sys/socket.h>
11 #include "dinit-log.h"
12 #include "dinit-socket.h"
13 #include "proc-service.h"
15 #include "baseproc-sys.h"
18 * Base process implementation (base_process_service).
20 * See proc-service.h for interface documentation.
23 void base_process_service::do_smooth_recovery() noexcept
25 if (! restart_ps_process()) {
27 services->process_queues();
31 bool base_process_service::bring_up() noexcept
35 return restart_ps_process();
40 if (! open_socket()) {
44 event_loop.get_time(restart_interval_time, clock_type::MONOTONIC);
45 restart_interval_count = 0;
46 if (start_ps_process(exec_arg_parts, onstart_flags.starts_on_console)) {
47 // Note: we don't set a start timeout for PROCESS services.
48 if (start_timeout != time_val(0,0) && get_type() != service_type_t::PROCESS) {
49 restart_timer.arm_timer_rel(event_loop, start_timeout);
50 stop_timer_armed = true;
52 else if (stop_timer_armed) {
53 restart_timer.stop_timer(event_loop);
54 stop_timer_armed = false;
62 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
64 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
65 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
66 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
67 // is written to the pipe, and the parent can read it.
69 event_loop.get_time(last_start_time, clock_type::MONOTONIC);
72 if (bp_sys::pipe2(pipefd, O_CLOEXEC)) {
73 log(loglevel_t::ERROR, get_name(), ": can't create status check pipe: ", strerror(errno));
77 const char * logfile = this->logfile.c_str();
79 logfile = "/dev/null";
82 bool child_status_registered = false;
83 control_conn_t *control_conn = nullptr;
85 int control_socket[2] = {-1, -1};
86 if (onstart_flags.pass_cs_fd) {
87 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
88 log(loglevel_t::ERROR, get_name(), ": can't create control socket: ", strerror(errno));
92 // Make the server side socket close-on-exec:
93 int fdflags = bp_sys::fcntl(control_socket[0], F_GETFD);
94 bp_sys::fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
97 control_conn = new control_conn_t(event_loop, services, control_socket[0]);
99 catch (std::exception &exc) {
100 log(loglevel_t::ERROR, get_name(), ": can't launch process; out of memory");
105 // Set up complete, now fork and exec:
110 child_status_listener.add_watch(event_loop, pipefd[0], dasynq::IN_EVENTS);
111 child_status_registered = true;
113 // We specify a high priority (i.e. low priority value) so that process termination is
114 // handled early. This means we have always recorded that the process is terminated by the
115 // time that we handle events that might otherwise cause us to signal the process, so we
116 // avoid sending a signal to an invalid (and possibly recycled) process ID.
117 forkpid = child_listener.fork(event_loop, reserved_child_watch, dasynq::DEFAULT_PRIORITY - 10);
118 reserved_child_watch = true;
120 catch (std::exception &e) {
121 log(loglevel_t::ERROR, get_name(), ": Could not fork: ", e.what());
126 const char * working_dir_c = nullptr;
127 if (! working_dir.empty()) working_dir_c = working_dir.c_str();
128 run_child_proc(cmd.data(), working_dir_c, logfile, on_console, pipefd[1], control_socket[1],
129 socket_fd, run_as_uid, run_as_gid);
133 bp_sys::close(pipefd[1]); // close the 'other end' fd
134 if (control_socket[1] != -1) {
135 bp_sys::close(control_socket[1]);
139 waiting_for_execstat = true;
146 if (child_status_registered) {
147 child_status_listener.deregister(event_loop);
150 if (onstart_flags.pass_cs_fd) {
154 bp_sys::close(control_socket[0]);
155 bp_sys::close(control_socket[1]);
159 bp_sys::close(pipefd[0]);
160 bp_sys::close(pipefd[1]);
165 base_process_service::base_process_service(service_set *sset, string name,
166 service_type_t service_type_p, string &&command,
167 std::list<std::pair<unsigned,unsigned>> &command_offsets,
168 const std::list<prelim_dep> &deplist_p)
169 : service_record(sset, name, service_type_p, deplist_p), child_listener(this),
170 child_status_listener(this), restart_timer(this)
172 program_name = std::move(command);
173 exec_arg_parts = separate_args(program_name, command_offsets);
175 restart_interval_count = 0;
176 restart_interval_time = {0, 0};
177 restart_timer.service = this;
178 restart_timer.add_timer(event_loop);
180 // By default, allow a maximum of 3 restarts within 10.0 seconds:
181 restart_interval.seconds() = 10;
182 restart_interval.nseconds() = 0;
183 max_restart_interval_count = 3;
185 waiting_restart_timer = false;
186 reserved_child_watch = false;
187 tracking_child = false;
188 stop_timer_armed = false;
191 void base_process_service::do_restart() noexcept
193 waiting_restart_timer = false;
194 restart_interval_count++;
195 auto service_state = get_state();
197 if (service_state == service_state_t::STARTING) {
198 // for a smooth recovery, we want to check dependencies are available before actually
200 if (! check_deps_started()) {
201 waiting_for_deps = true;
206 if (! start_ps_process(exec_arg_parts, have_console)) {
208 if (service_state == service_state_t::STARTING) {
212 // desired_state = service_state_t::STOPPED;
215 services->process_queues();
219 bool base_process_service::restart_ps_process() noexcept
221 using time_val = dasynq::time_val;
223 time_val current_time;
224 event_loop.get_time(current_time, clock_type::MONOTONIC);
226 if (max_restart_interval_count != 0) {
227 // Check whether we're still in the most recent restart check interval:
228 time_val int_diff = current_time - restart_interval_time;
229 if (int_diff < restart_interval) {
230 if (restart_interval_count >= max_restart_interval_count) {
231 log(loglevel_t::ERROR, "Service ", get_name(), " restarting too quickly; stopping.");
236 restart_interval_time = current_time;
237 restart_interval_count = 0;
241 // Check if enough time has lapsed since the previous restart. If not, start a timer:
242 time_val tdiff = current_time - last_start_time;
243 if (restart_delay <= tdiff) {
244 // > restart delay (normally 200ms)
248 time_val timeout = restart_delay - tdiff;
249 restart_timer.arm_timer_rel(event_loop, timeout);
250 waiting_restart_timer = true;
255 bool base_process_service::interrupt_start() noexcept
257 if (waiting_restart_timer) {
258 restart_timer.stop_timer(event_loop);
259 waiting_restart_timer = false;
260 return service_record::interrupt_start();
263 log(loglevel_t::WARN, "Interrupting start of service ", get_name(), " with pid ", pid, " (with SIGINT).");
266 if (stop_timeout != time_val(0,0)) {
267 restart_timer.arm_timer_rel(event_loop, stop_timeout);
268 stop_timer_armed = true;
270 else if (stop_timer_armed) {
271 restart_timer.stop_timer(event_loop);
272 stop_timer_armed = false;
275 set_state(service_state_t::STOPPING);
280 void base_process_service::kill_with_fire() noexcept
283 log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid, " exceeded allowed stop time; killing.");
288 void base_process_service::kill_pg(int signo) noexcept
290 if (onstart_flags.signal_process_only) {
291 bp_sys::kill(pid, signo);
294 pid_t pgid = bp_sys::getpgid(pid);
296 // only should happen if pid is invalid, which should never happen...
297 log(loglevel_t::ERROR, get_name(), ": can't signal process: ", strerror(errno));
300 bp_sys::kill(-pgid, signo);
304 void base_process_service::timer_expired() noexcept
306 stop_timer_armed = false;
309 // We are stopping, including after having startup cancelled (stop timeout, state is STOPPING); We are
310 // starting (start timeout, state is STARTING); We are waiting for restart timer before restarting,
311 // including smooth recovery (restart timeout, state is STARTING or STARTED).
312 if (get_state() == service_state_t::STOPPING) {
315 else if (pid != -1) {
316 // Starting, start timed out.
317 log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid, " exceeded allowed start time; cancelling.");
319 stop_reason = stopped_reason_t::TIMEDOUT;
320 failed_to_start(false, false);
323 // STARTING / STARTED, and we have a pid: must be restarting (smooth recovery if STARTED)
328 void base_process_service::emergency_stop() noexcept
330 if (! do_auto_restart() && start_explicit) {
331 start_explicit = false;
338 void base_process_service::becoming_inactive() noexcept
340 if (socket_fd != -1) {
346 bool base_process_service::open_socket() noexcept
348 if (socket_path.empty() || socket_fd != -1) {
349 // No socket, or already open
353 const char * saddrname = socket_path.c_str();
355 // Check the specified socket path
356 struct stat stat_buf;
357 if (stat(saddrname, &stat_buf) == 0) {
358 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
360 log(loglevel_t::ERROR, get_name(), ": Activation socket file exists (and is not a socket)");
364 else if (errno != ENOENT) {
366 log(loglevel_t::ERROR, get_name(), ": Error checking activation socket: ", strerror(errno));
370 // Remove stale socket file (if it exists).
371 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
372 // error when we try to create the socket anyway.
375 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
376 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
377 if (name == nullptr) {
378 log(loglevel_t::ERROR, get_name(), ": Opening activation socket: out of memory");
382 name->sun_family = AF_UNIX;
383 strcpy(name->sun_path, saddrname);
385 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
387 log(loglevel_t::ERROR, get_name(), ": Error creating activation socket: ", strerror(errno));
392 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
393 log(loglevel_t::ERROR, get_name(), ": Error binding activation socket: ", strerror(errno));
401 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
402 // use chown and chmod instead.
403 if (chown(saddrname, socket_uid, socket_gid)) {
404 log(loglevel_t::ERROR, get_name(), ": Error setting activation socket owner/group: ", strerror(errno));
409 if (chmod(saddrname, socket_perms) == -1) {
410 log(loglevel_t::ERROR, get_name(), ": Error setting activation socket permissions: ", strerror(errno));
415 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
416 log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));