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 restart_interval_count = 0;
45 if (start_ps_process(exec_arg_parts,
46 onstart_flags.starts_on_console || onstart_flags.shares_console)) {
47 // start_ps_process updates last_start_time, use it also for restart_interval_time:
48 restart_interval_time = last_start_time;
49 // Note: we don't set a start timeout for PROCESS services.
50 if (start_timeout != time_val(0,0) && get_type() != service_type_t::PROCESS) {
51 restart_timer.arm_timer_rel(event_loop, start_timeout);
52 stop_timer_armed = true;
54 else if (stop_timer_armed) {
55 restart_timer.stop_timer(event_loop);
56 stop_timer_armed = false;
60 restart_interval_time = last_start_time;
65 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
67 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
68 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
69 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
70 // is written to the pipe, and the parent can read it.
72 event_loop.get_time(last_start_time, clock_type::MONOTONIC);
75 if (bp_sys::pipe2(pipefd, O_CLOEXEC)) {
76 log(loglevel_t::ERROR, get_name(), ": can't create status check pipe: ", strerror(errno));
80 const char * logfile = this->logfile.c_str();
82 logfile = "/dev/null";
85 bool child_status_registered = false;
86 control_conn_t *control_conn = nullptr;
88 int control_socket[2] = {-1, -1};
89 int notify_pipe[2] = {-1, -1};
90 bool have_notify = !notification_var.empty() || force_notification_fd != -1;
91 ready_notify_watcher * rwatcher = have_notify ? get_ready_watcher() : nullptr;
92 bool ready_watcher_registered = false;
94 if (onstart_flags.pass_cs_fd) {
95 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
96 log(loglevel_t::ERROR, get_name(), ": can't create control socket: ", strerror(errno));
100 // Make the server side socket close-on-exec:
101 int fdflags = bp_sys::fcntl(control_socket[0], F_GETFD);
102 bp_sys::fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
105 control_conn = new control_conn_t(event_loop, services, control_socket[0]);
107 catch (std::exception &exc) {
108 log(loglevel_t::ERROR, get_name(), ": can't launch process; out of memory");
114 // Create a notification pipe:
115 if (bp_sys::pipe2(notify_pipe, 0) != 0) {
116 log(loglevel_t::ERROR, get_name(), ": can't create notification pipe: ", strerror(errno));
120 // Set the read side as close-on-exec:
121 int fdflags = bp_sys::fcntl(notify_pipe[0], F_GETFD);
122 bp_sys::fcntl(notify_pipe[0], F_SETFD, fdflags | FD_CLOEXEC);
124 // add, but don't yet enable, readiness watcher:
126 rwatcher->add_watch(event_loop, notify_pipe[0], dasynq::IN_EVENTS, false);
127 ready_watcher_registered = true;
129 catch (std::exception &exc) {
130 log(loglevel_t::ERROR, get_name(), ": can't add notification watch: ", exc.what());
134 // Set up complete, now fork and exec:
139 child_status_listener.add_watch(event_loop, pipefd[0], dasynq::IN_EVENTS);
140 child_status_registered = true;
142 // We specify a high priority (i.e. low priority value) so that process termination is
143 // handled early. This means we have always recorded that the process is terminated by the
144 // time that we handle events that might otherwise cause us to signal the process, so we
145 // avoid sending a signal to an invalid (and possibly recycled) process ID.
146 forkpid = child_listener.fork(event_loop, reserved_child_watch, dasynq::DEFAULT_PRIORITY - 10);
147 reserved_child_watch = true;
149 catch (std::exception &e) {
150 log(loglevel_t::ERROR, get_name(), ": Could not fork: ", e.what());
155 const char * working_dir_c = nullptr;
156 if (! working_dir.empty()) working_dir_c = working_dir.c_str();
157 after_fork(getpid());
158 run_proc_params run_params{cmd.data(), working_dir_c, logfile, pipefd[1], run_as_uid, run_as_gid, rlimits};
159 run_params.on_console = on_console;
160 run_params.in_foreground = !onstart_flags.shares_console;
161 run_params.csfd = control_socket[1];
162 run_params.socket_fd = socket_fd;
163 run_params.notify_fd = notify_pipe[1];
164 run_params.force_notify_fd = force_notification_fd;
165 run_params.notify_var = notification_var.c_str();
166 run_params.env_file = env_file.c_str();
167 run_child_proc(run_params);
173 bp_sys::close(pipefd[1]); // close the 'other end' fd
174 if (control_socket[1] != -1) bp_sys::close(control_socket[1]);
175 if (notify_pipe[1] != -1) bp_sys::close(notify_pipe[1]);
176 notification_fd = notify_pipe[0];
177 waiting_for_execstat = true;
184 if (child_status_registered) {
185 child_status_listener.deregister(event_loop);
188 if (notify_pipe[0] != -1) bp_sys::close(notify_pipe[0]);
189 if (notify_pipe[1] != -1) bp_sys::close(notify_pipe[1]);
190 if (ready_watcher_registered) {
191 rwatcher->deregister(event_loop);
194 if (onstart_flags.pass_cs_fd) {
198 bp_sys::close(control_socket[0]);
199 bp_sys::close(control_socket[1]);
203 bp_sys::close(pipefd[0]);
204 bp_sys::close(pipefd[1]);
209 base_process_service::base_process_service(service_set *sset, string name,
210 service_type_t service_type_p, string &&command,
211 const std::list<std::pair<unsigned,unsigned>> &command_offsets,
212 const std::list<prelim_dep> &deplist_p)
213 : service_record(sset, name, service_type_p, deplist_p), child_listener(this),
214 child_status_listener(this), restart_timer(this)
216 program_name = std::move(command);
217 exec_arg_parts = separate_args(program_name, command_offsets);
219 restart_interval_count = 0;
220 restart_interval_time = {0, 0};
221 restart_timer.service = this;
222 restart_timer.add_timer(event_loop);
224 // By default, allow a maximum of 3 restarts within 10.0 seconds:
225 restart_interval.seconds() = 10;
226 restart_interval.nseconds() = 0;
227 max_restart_interval_count = 3;
229 waiting_restart_timer = false;
230 reserved_child_watch = false;
231 tracking_child = false;
232 stop_timer_armed = false;
235 void base_process_service::do_restart() noexcept
237 waiting_restart_timer = false;
238 restart_interval_count++;
239 auto service_state = get_state();
241 if (service_state == service_state_t::STARTING) {
242 // for a smooth recovery, we want to check dependencies are available before actually
244 if (! check_deps_started()) {
245 waiting_for_deps = true;
250 if (! start_ps_process(exec_arg_parts, have_console || onstart_flags.shares_console)) {
252 if (service_state == service_state_t::STARTING) {
256 // desired_state = service_state_t::STOPPED;
259 services->process_queues();
263 bool base_process_service::restart_ps_process() noexcept
265 using time_val = dasynq::time_val;
267 time_val current_time;
268 event_loop.get_time(current_time, clock_type::MONOTONIC);
270 if (max_restart_interval_count != 0) {
271 // Check whether we're still in the most recent restart check interval:
272 time_val int_diff = current_time - restart_interval_time;
273 if (int_diff < restart_interval) {
274 if (restart_interval_count >= max_restart_interval_count) {
275 log(loglevel_t::ERROR, "Service ", get_name(), " restarting too quickly; stopping.");
280 restart_interval_time = current_time;
281 restart_interval_count = 0;
285 // Check if enough time has lapsed since the previous restart. If not, start a timer:
286 time_val tdiff = current_time - last_start_time;
287 if (restart_delay <= tdiff) {
288 // > restart delay (normally 200ms)
292 time_val timeout = restart_delay - tdiff;
293 restart_timer.arm_timer_rel(event_loop, timeout);
294 waiting_restart_timer = true;
299 bool base_process_service::interrupt_start() noexcept
301 if (waiting_restart_timer) {
302 restart_timer.stop_timer(event_loop);
303 waiting_restart_timer = false;
304 return service_record::interrupt_start();
307 log(loglevel_t::WARN, "Interrupting start of service ", get_name(), " with pid ", pid,
311 if (stop_timeout != time_val(0,0)) {
312 restart_timer.arm_timer_rel(event_loop, stop_timeout);
313 stop_timer_armed = true;
315 else if (stop_timer_armed) {
316 restart_timer.stop_timer(event_loop);
317 stop_timer_armed = false;
320 set_state(service_state_t::STOPPING);
325 void base_process_service::kill_with_fire() noexcept
328 log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid,
329 " exceeded allowed stop time; killing.");
334 void base_process_service::kill_pg(int signo) noexcept
336 if (onstart_flags.signal_process_only) {
337 bp_sys::kill(pid, signo);
340 pid_t pgid = bp_sys::getpgid(pid);
342 // On some OSes (eg OpenBSD) we aren't allowed to get the pgid of a process in a different
343 // session. If the process is in a different session, however, it must be a process group
344 // leader and the pgid must equal the process id.
347 bp_sys::kill(-pgid, signo);
351 void base_process_service::timer_expired() noexcept
353 stop_timer_armed = false;
356 // We are stopping, including after having startup cancelled (stop timeout, state is STOPPING); We are
357 // starting (start timeout, state is STARTING); We are waiting for restart timer before restarting,
358 // including smooth recovery (restart timeout, state is STARTING or STARTED).
359 if (get_state() == service_state_t::STOPPING) {
362 else if (pid != -1) {
363 // Starting, start timed out.
364 log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid,
365 " exceeded allowed start time; cancelling.");
367 stop_reason = stopped_reason_t::TIMEDOUT;
368 failed_to_start(false, false);
371 // STARTING / STARTED, and we have a pid: must be restarting (smooth recovery if STARTED)
376 void base_process_service::emergency_stop() noexcept
382 void base_process_service::becoming_inactive() noexcept
384 if (socket_fd != -1) {
390 bool base_process_service::open_socket() noexcept
392 if (socket_path.empty() || socket_fd != -1) {
393 // No socket, or already open
397 const char * saddrname = socket_path.c_str();
399 // Check the specified socket path
400 struct stat stat_buf;
401 if (stat(saddrname, &stat_buf) == 0) {
402 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
404 log(loglevel_t::ERROR, get_name(), ": Activation socket file exists (and is not a socket)");
408 else if (errno != ENOENT) {
410 log(loglevel_t::ERROR, get_name(), ": Error checking activation socket: ", strerror(errno));
414 // Remove stale socket file (if it exists).
415 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
416 // error when we try to create the socket anyway.
419 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
420 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
421 if (name == nullptr) {
422 log(loglevel_t::ERROR, get_name(), ": Opening activation socket: out of memory");
426 name->sun_family = AF_UNIX;
427 strcpy(name->sun_path, saddrname);
429 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
431 log(loglevel_t::ERROR, get_name(), ": Error creating activation socket: ", strerror(errno));
436 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
437 log(loglevel_t::ERROR, get_name(), ": Error binding activation socket: ", strerror(errno));
445 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
446 // use chown and chmod instead.
447 if (chown(saddrname, socket_uid, socket_gid)) {
448 log(loglevel_t::ERROR, get_name(), ": Error setting activation socket owner/group: ",
454 if (chmod(saddrname, socket_perms) == -1) {
455 log(loglevel_t::ERROR, get_name(), ": Error setting activation socket permissions: ",
461 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
462 log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));