Move some data/functions from service_record to base_process_service.
[oweals/dinit.git] / src / baseproc-service.cc
1 #include <cstring>
2
3 #include <sys/un.h>
4 #include <sys/socket.h>
5
6 #include "dinit.h"
7 #include "dinit-log.h"
8 #include "dinit-socket.h"
9 #include "proc-service.h"
10
11 #include "baseproc-sys.h"
12
13 /*
14  * Base process implementation (base_process_service).
15  *
16  * See proc-service.h for interface documentation.
17  */
18
19 void base_process_service::do_smooth_recovery() noexcept
20 {
21     if (! restart_ps_process()) {
22         emergency_stop();
23         services->process_queues();
24     }
25 }
26
27 bool base_process_service::bring_up() noexcept
28 {
29     if (restarting) {
30         if (pid == -1) {
31             return restart_ps_process();
32         }
33         return true;
34     }
35     else {
36         if (! open_socket()) {
37             return false;
38         }
39
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;
46             }
47             else if (stop_timer_armed) {
48                 restart_timer.stop_timer(event_loop);
49                 stop_timer_armed = false;
50             }
51             return true;
52         }
53         return false;
54     }
55 }
56
57 bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
58 {
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.
63
64     event_loop.get_time(last_start_time, clock_type::MONOTONIC);
65
66     int pipefd[2];
67     if (bp_sys::pipe2(pipefd, O_CLOEXEC)) {
68         log(loglevel_t::ERROR, get_name(), ": can't create status check pipe: ", strerror(errno));
69         return false;
70     }
71
72     const char * logfile = this->logfile.c_str();
73     if (*logfile == 0) {
74         logfile = "/dev/null";
75     }
76
77     bool child_status_registered = false;
78     control_conn_t *control_conn = nullptr;
79
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));
84             goto out_p;
85         }
86
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);
90
91         try {
92             control_conn = new control_conn_t(event_loop, services, control_socket[0]);
93         }
94         catch (std::exception &exc) {
95             log(loglevel_t::ERROR, get_name(), ": can't launch process; out of memory");
96             goto out_cs;
97         }
98     }
99
100     // Set up complete, now fork and exec:
101
102     pid_t forkpid;
103
104     try {
105         child_status_listener.add_watch(event_loop, pipefd[0], dasynq::IN_EVENTS);
106         child_status_registered = true;
107
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;
114     }
115     catch (std::exception &e) {
116         log(loglevel_t::ERROR, get_name(), ": Could not fork: ", e.what());
117         goto out_cs_h;
118     }
119
120     if (forkpid == 0) {
121         run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1], socket_fd);
122     }
123     else {
124         // Parent process
125         bp_sys::close(pipefd[1]); // close the 'other end' fd
126         if (control_socket[1] != -1) {
127             bp_sys::close(control_socket[1]);
128         }
129         pid = forkpid;
130
131         waiting_for_execstat = true;
132         return true;
133     }
134
135     // Failure exit:
136
137     out_cs_h:
138     if (child_status_registered) {
139         child_status_listener.deregister(event_loop);
140     }
141
142     if (onstart_flags.pass_cs_fd) {
143         delete control_conn;
144
145         out_cs:
146         bp_sys::close(control_socket[0]);
147         bp_sys::close(control_socket[1]);
148     }
149
150     out_p:
151     bp_sys::close(pipefd[0]);
152     bp_sys::close(pipefd[1]);
153
154     return false;
155 }
156
157 void base_process_service::bring_down() noexcept
158 {
159     if (pid != -1) {
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) {
164             kill_pg(SIGTERM);
165         }
166         if (term_signal != -1) {
167             kill_pg(term_signal);
168         }
169
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) {
174             stopped();
175         }
176         else if (stop_timeout != time_val(0,0)) {
177             restart_timer.arm_timer_rel(event_loop, stop_timeout);
178             stop_timer_armed = true;
179         }
180     }
181     else {
182         // The process is already dead.
183         stopped();
184     }
185 }
186
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)
193 {
194     program_name = std::move(command);
195     exec_arg_parts = separate_args(program_name, command_offsets);
196
197     restart_interval_count = 0;
198     restart_interval_time = {0, 0};
199     restart_timer.service = this;
200     restart_timer.add_timer(event_loop);
201
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;
206
207     waiting_restart_timer = false;
208     reserved_child_watch = false;
209     tracking_child = false;
210     stop_timer_armed = false;
211     start_is_interruptible = false;
212 }
213
214 void base_process_service::do_restart() noexcept
215 {
216     waiting_restart_timer = false;
217     restart_interval_count++;
218     auto service_state = get_state();
219
220     if (service_state == service_state_t::STARTING) {
221         // for a smooth recovery, we want to check dependencies are available before actually
222         // starting:
223         if (! check_deps_started()) {
224             waiting_for_deps = true;
225             return;
226         }
227     }
228
229     if (! start_ps_process(exec_arg_parts, have_console)) {
230         restarting = false;
231         if (service_state == service_state_t::STARTING) {
232             failed_to_start();
233         }
234         else {
235             // desired_state = service_state_t::STOPPED;
236             forced_stop();
237         }
238         services->process_queues();
239     }
240 }
241
242 bool base_process_service::restart_ps_process() noexcept
243 {
244     using time_val = dasynq::time_val;
245
246     time_val current_time;
247     event_loop.get_time(current_time, clock_type::MONOTONIC);
248
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.");
255                 return false;
256             }
257         }
258         else {
259             restart_interval_time = current_time;
260             restart_interval_count = 0;
261         }
262     }
263
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)
268         do_restart();
269     }
270     else {
271         time_val timeout = restart_delay - tdiff;
272         restart_timer.arm_timer_rel(event_loop, timeout);
273         waiting_restart_timer = true;
274     }
275     return true;
276 }
277
278 bool base_process_service::interrupt_start() noexcept
279 {
280     if (waiting_restart_timer) {
281         restart_timer.stop_timer(event_loop);
282         waiting_restart_timer = false;
283         return service_record::interrupt_start();
284     }
285     else {
286         log(loglevel_t::WARN, "Interrupting start of service ", get_name(), " with pid ", pid, " (with SIGINT).");
287         kill_pg(SIGINT);
288         if (stop_timeout != time_val(0,0)) {
289             restart_timer.arm_timer_rel(event_loop, stop_timeout);
290             stop_timer_armed = true;
291         }
292         else if (stop_timer_armed) {
293             restart_timer.stop_timer(event_loop);
294             stop_timer_armed = false;
295         }
296         set_state(service_state_t::STOPPING);
297         notify_listeners(service_event_t::STARTCANCELLED);
298         return false;
299     }
300 }
301
302 void base_process_service::kill_with_fire() noexcept
303 {
304     if (pid != -1) {
305         log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid, " exceeded allowed stop time; killing.");
306         kill_pg(SIGKILL);
307     }
308 }
309
310 void base_process_service::kill_pg(int signo) noexcept
311 {
312     pid_t pgid = bp_sys::getpgid(pid);
313     if (pgid == -1) {
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));
316         return;
317     }
318     bp_sys::kill(-pgid, signo);
319 }
320
321 void base_process_service::timer_expired() noexcept
322 {
323     stop_timer_armed = false;
324
325     // Timer expires if:
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) {
330         kill_with_fire();
331     }
332     else if (pid != -1) {
333         // Starting, start timed out.
334         stop_dependents();
335         if (start_explicit) {
336             start_explicit = false;
337             release();
338         }
339         interrupt_start();
340     }
341     else {
342         // STARTING / STARTED, and we have a pid: must be restarting (smooth recovery if STARTED)
343         do_restart();
344     }
345 }
346
347 void base_process_service::emergency_stop() noexcept
348 {
349     if (! do_auto_restart() && start_explicit) {
350         start_explicit = false;
351         release(false);
352     }
353     forced_stop();
354     stop_dependents();
355     stopped();
356 }
357
358 void base_process_service::becoming_inactive() noexcept
359 {
360     if (socket_fd != -1) {
361         close(socket_fd);
362         socket_fd = -1;
363     }
364 }
365
366 bool base_process_service::open_socket() noexcept
367 {
368     if (socket_path.empty() || socket_fd != -1) {
369         // No socket, or already open
370         return true;
371     }
372
373     const char * saddrname = socket_path.c_str();
374
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) {
379             // Not a socket
380             log(loglevel_t::ERROR, get_name(), ": Activation socket file exists (and is not a socket)");
381             return false;
382         }
383     }
384     else if (errno != ENOENT) {
385         // Other error
386         log(loglevel_t::ERROR, get_name(), ": Error checking activation socket: ", strerror(errno));
387         return false;
388     }
389
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.
393     unlink(saddrname);
394
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");
399         return false;
400     }
401
402     name->sun_family = AF_UNIX;
403     strcpy(name->sun_path, saddrname);
404
405     int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
406     if (sockfd == -1) {
407         log(loglevel_t::ERROR, get_name(), ": Error creating activation socket: ", strerror(errno));
408         free(name);
409         return false;
410     }
411
412     if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
413         log(loglevel_t::ERROR, get_name(), ": Error binding activation socket: ", strerror(errno));
414         close(sockfd);
415         free(name);
416         return false;
417     }
418
419     free(name);
420
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));
425         close(sockfd);
426         return false;
427     }
428
429     if (chmod(saddrname, socket_perms) == -1) {
430         log(loglevel_t::ERROR, get_name(), ": Error setting activation socket permissions: ", strerror(errno));
431         close(sockfd);
432         return false;
433     }
434
435     if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
436         log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));
437         close(sockfd);
438         return false;
439     }
440
441     socket_fd = sockfd;
442     return true;
443 }