4 #include <sys/socket.h>
8 #include "dinit-socket.h"
9 #include "proc-service.h"
11 #include "baseproc-sys.h"
14 * Base process implementation (base_process_service).
16 * See proc-service.h for interface documentation.
19 void base_process_service::do_smooth_recovery() noexcept
21 if (! restart_ps_process()) {
23 services->process_queues();
27 bool base_process_service::bring_up() noexcept
31 return restart_ps_process();
36 if (! open_socket()) {
40 event_loop.get_time(restart_interval_time, clock_type::MONOTONIC);
41 restart_interval_count = 0;
42 if (start_ps_process(exec_arg_parts, onstart_flags.starts_on_console)) {
43 if (start_timeout != time_val(0,0)) {
44 restart_timer.arm_timer_rel(event_loop, start_timeout);
45 stop_timer_armed = true;
47 else if (stop_timer_armed) {
48 restart_timer.stop_timer(event_loop);
49 stop_timer_armed = false;
57 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
59 // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
60 // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
61 // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
62 // is written to the pipe, and the parent can read it.
64 event_loop.get_time(last_start_time, clock_type::MONOTONIC);
67 if (bp_sys::pipe2(pipefd, O_CLOEXEC)) {
68 log(loglevel_t::ERROR, get_name(), ": can't create status check pipe: ", strerror(errno));
72 const char * logfile = this->logfile.c_str();
74 logfile = "/dev/null";
77 bool child_status_registered = false;
78 control_conn_t *control_conn = nullptr;
80 int control_socket[2] = {-1, -1};
81 if (onstart_flags.pass_cs_fd) {
82 if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
83 log(loglevel_t::ERROR, get_name(), ": can't create control socket: ", strerror(errno));
87 // Make the server side socket close-on-exec:
88 int fdflags = bp_sys::fcntl(control_socket[0], F_GETFD);
89 bp_sys::fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
92 control_conn = new control_conn_t(event_loop, services, control_socket[0]);
94 catch (std::exception &exc) {
95 log(loglevel_t::ERROR, get_name(), ": can't launch process; out of memory");
100 // Set up complete, now fork and exec:
105 child_status_listener.add_watch(event_loop, pipefd[0], dasynq::IN_EVENTS);
106 child_status_registered = true;
108 // We specify a high priority (i.e. low priority value) so that process termination is
109 // handled early. This means we have always recorded that the process is terminated by the
110 // time that we handle events that might otherwise cause us to signal the process, so we
111 // avoid sending a signal to an invalid (and possibly recycled) process ID.
112 forkpid = child_listener.fork(event_loop, reserved_child_watch, dasynq::DEFAULT_PRIORITY - 10);
113 reserved_child_watch = true;
115 catch (std::exception &e) {
116 log(loglevel_t::ERROR, get_name(), ": Could not fork: ", e.what());
121 run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1], socket_fd);
125 bp_sys::close(pipefd[1]); // close the 'other end' fd
126 if (control_socket[1] != -1) {
127 bp_sys::close(control_socket[1]);
131 waiting_for_execstat = true;
138 if (child_status_registered) {
139 child_status_listener.deregister(event_loop);
142 if (onstart_flags.pass_cs_fd) {
146 bp_sys::close(control_socket[0]);
147 bp_sys::close(control_socket[1]);
151 bp_sys::close(pipefd[0]);
152 bp_sys::close(pipefd[1]);
157 void base_process_service::bring_down() noexcept
160 // The process is still kicking on - must actually kill it. We signal the process
161 // group (-pid) rather than just the process as there's less risk then of creating
162 // an orphaned process group:
163 if (! onstart_flags.no_sigterm) {
166 if (term_signal != -1) {
167 kill_pg(term_signal);
170 // In most cases, the rest is done in handle_exit_status.
171 // If we are a BGPROCESS and the process is not our immediate child, however, that
172 // won't work - check for this now:
173 if (get_type() == service_type_t::BGPROCESS && ! tracking_child) {
176 else if (stop_timeout != time_val(0,0)) {
177 restart_timer.arm_timer_rel(event_loop, stop_timeout);
178 stop_timer_armed = true;
182 // The process is already dead.
187 base_process_service::base_process_service(service_set *sset, string name,
188 service_type_t service_type_p, string &&command,
189 std::list<std::pair<unsigned,unsigned>> &command_offsets,
190 const std::list<prelim_dep> &deplist_p)
191 : service_record(sset, name, service_type_p, deplist_p), child_listener(this),
192 child_status_listener(this), restart_timer(this)
194 program_name = std::move(command);
195 exec_arg_parts = separate_args(program_name, command_offsets);
197 restart_interval_count = 0;
198 restart_interval_time = {0, 0};
199 restart_timer.service = this;
200 restart_timer.add_timer(event_loop);
202 // By default, allow a maximum of 3 restarts within 10.0 seconds:
203 restart_interval.seconds() = 10;
204 restart_interval.nseconds() = 0;
205 max_restart_interval_count = 3;
207 waiting_restart_timer = false;
208 reserved_child_watch = false;
209 tracking_child = false;
210 stop_timer_armed = false;
211 start_is_interruptible = false;
214 void base_process_service::do_restart() noexcept
216 waiting_restart_timer = false;
217 restart_interval_count++;
218 auto service_state = get_state();
220 if (service_state == service_state_t::STARTING) {
221 // for a smooth recovery, we want to check dependencies are available before actually
223 if (! check_deps_started()) {
224 waiting_for_deps = true;
229 if (! start_ps_process(exec_arg_parts, have_console)) {
231 if (service_state == service_state_t::STARTING) {
235 // desired_state = service_state_t::STOPPED;
238 services->process_queues();
242 bool base_process_service::restart_ps_process() noexcept
244 using time_val = dasynq::time_val;
246 time_val current_time;
247 event_loop.get_time(current_time, clock_type::MONOTONIC);
249 if (max_restart_interval_count != 0) {
250 // Check whether we're still in the most recent restart check interval:
251 time_val int_diff = current_time - restart_interval_time;
252 if (int_diff < restart_interval) {
253 if (restart_interval_count >= max_restart_interval_count) {
254 log(loglevel_t::ERROR, "Service ", get_name(), " restarting too quickly; stopping.");
259 restart_interval_time = current_time;
260 restart_interval_count = 0;
264 // Check if enough time has lapsed since the previous restart. If not, start a timer:
265 time_val tdiff = current_time - last_start_time;
266 if (restart_delay <= tdiff) {
267 // > restart delay (normally 200ms)
271 time_val timeout = restart_delay - tdiff;
272 restart_timer.arm_timer_rel(event_loop, timeout);
273 waiting_restart_timer = true;
278 bool base_process_service::interrupt_start() noexcept
280 if (waiting_restart_timer) {
281 restart_timer.stop_timer(event_loop);
282 waiting_restart_timer = false;
283 return service_record::interrupt_start();
286 log(loglevel_t::WARN, "Interrupting start of service ", get_name(), " with pid ", pid, " (with SIGINT).");
288 if (stop_timeout != time_val(0,0)) {
289 restart_timer.arm_timer_rel(event_loop, stop_timeout);
290 stop_timer_armed = true;
292 else if (stop_timer_armed) {
293 restart_timer.stop_timer(event_loop);
294 stop_timer_armed = false;
296 set_state(service_state_t::STOPPING);
297 notify_listeners(service_event_t::STARTCANCELLED);
302 void base_process_service::kill_with_fire() noexcept
305 log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid, " exceeded allowed stop time; killing.");
310 void base_process_service::kill_pg(int signo) noexcept
312 pid_t pgid = bp_sys::getpgid(pid);
314 // only should happen if pid is invalid, which should never happen...
315 log(loglevel_t::ERROR, get_name(), ": can't signal process: ", strerror(errno));
318 bp_sys::kill(-pgid, signo);
321 void base_process_service::timer_expired() noexcept
323 stop_timer_armed = false;
326 // We are stopping, including after having startup cancelled (stop timeout, state is STOPPING); We are
327 // starting (start timeout, state is STARTING); We are waiting for restart timer before restarting,
328 // including smooth recovery (restart timeout, state is STARTING or STARTED).
329 if (get_state() == service_state_t::STOPPING) {
332 else if (pid != -1) {
333 // Starting, start timed out.
335 if (start_explicit) {
336 start_explicit = false;
342 // STARTING / STARTED, and we have a pid: must be restarting (smooth recovery if STARTED)
347 void base_process_service::emergency_stop() noexcept
349 if (! do_auto_restart() && start_explicit) {
350 start_explicit = false;
358 void base_process_service::becoming_inactive() noexcept
360 if (socket_fd != -1) {
366 bool base_process_service::open_socket() noexcept
368 if (socket_path.empty() || socket_fd != -1) {
369 // No socket, or already open
373 const char * saddrname = socket_path.c_str();
375 // Check the specified socket path
376 struct stat stat_buf;
377 if (stat(saddrname, &stat_buf) == 0) {
378 if ((stat_buf.st_mode & S_IFSOCK) == 0) {
380 log(loglevel_t::ERROR, get_name(), ": Activation socket file exists (and is not a socket)");
384 else if (errno != ENOENT) {
386 log(loglevel_t::ERROR, get_name(), ": Error checking activation socket: ", strerror(errno));
390 // Remove stale socket file (if it exists).
391 // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
392 // error when we try to create the socket anyway.
395 uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
396 struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
397 if (name == nullptr) {
398 log(loglevel_t::ERROR, get_name(), ": Opening activation socket: out of memory");
402 name->sun_family = AF_UNIX;
403 strcpy(name->sun_path, saddrname);
405 int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
407 log(loglevel_t::ERROR, get_name(), ": Error creating activation socket: ", strerror(errno));
412 if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
413 log(loglevel_t::ERROR, get_name(), ": Error binding activation socket: ", strerror(errno));
421 // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
422 // use chown and chmod instead.
423 if (chown(saddrname, socket_uid, socket_gid)) {
424 log(loglevel_t::ERROR, get_name(), ": Error setting activation socket owner/group: ", strerror(errno));
429 if (chmod(saddrname, socket_perms) == -1) {
430 log(loglevel_t::ERROR, get_name(), ": Error setting activation socket permissions: ", strerror(errno));
435 if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
436 log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));