Move 'run_child_proc' function into a separate source file.
[oweals/dinit.git] / src / service.cc
1 #include <cstring>
2 #include <cerrno>
3 #include <sstream>
4 #include <iterator>
5 #include <memory>
6 #include <cstddef>
7
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <sys/ioctl.h>
11 #include <sys/un.h>
12 #include <sys/socket.h>
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <termios.h>
16
17 #include "dinit.h"
18 #include "service.h"
19 #include "dinit-log.h"
20 #include "dinit-socket.h"
21 #include "dinit-util.h"
22
23 /*
24  * service.cc - Service management.
25  * See service.h for details.
26  */
27
28 // Find the requested service by name
29 static service_record * find_service(const std::list<service_record *> & records,
30                                     const char *name) noexcept
31 {
32     using std::list;
33     list<service_record *>::const_iterator i = records.begin();
34     for ( ; i != records.end(); i++ ) {
35         if (strcmp((*i)->get_name().c_str(), name) == 0) {
36             return *i;
37         }
38     }
39     return nullptr;
40 }
41
42 service_record * service_set::find_service(const std::string &name) noexcept
43 {
44     return ::find_service(records, name.c_str());
45 }
46
47 void service_set::stop_service(const std::string & name) noexcept
48 {
49     service_record *record = find_service(name);
50     if (record != nullptr) {
51         record->stop();
52         process_queues();
53     }
54 }
55
56 // Called when a service has actually stopped; dependents have stopped already, unless this stop
57 // is due to an unexpected process termination.
58 void service_record::stopped() noexcept
59 {
60     if (onstart_flags.runs_on_console) {
61         tcsetpgrp(0, getpgrp());
62         discard_console_log_buffer();
63         release_console();
64     }
65
66     force_stop = false;
67
68     // If we are a soft dependency of another target, break the acquisition from that target now:
69     for (auto & dependent : dependents) {
70         if (dependent->dep_type != dependency_type::REGULAR) {
71             if (dependent->holding_acq) {
72                 dependent->holding_acq = false;
73                 release();
74             }
75         }
76     }
77
78     bool will_restart = (desired_state == service_state_t::STARTED)
79             && services->get_auto_restart();
80
81     for (auto dependency : depends_on) {
82         // we signal dependencies in case they are waiting for us to stop:
83         dependency.get_to()->dependent_stopped();
84     }
85
86     service_state = service_state_t::STOPPED;
87
88     if (will_restart) {
89         // Desired state is "started".
90         restarting = true;
91         start(false);
92     }
93     else {
94         if (socket_fd != -1) {
95             close(socket_fd);
96             socket_fd = -1;
97         }
98         
99         if (start_explicit) {
100             start_explicit = false;
101             release();
102         }
103         else if (required_by == 0) {
104             services->service_inactive(this);
105         }
106     }
107
108     log_service_stopped(service_name);
109     notify_listeners(service_event_t::STOPPED);
110 }
111
112
113 bool service_record::do_auto_restart() noexcept
114 {
115     if (auto_restart) {
116         return services->get_auto_restart();
117     }
118     return false;
119 }
120
121 void service_record::emergency_stop() noexcept
122 {
123     if (! do_auto_restart() && start_explicit) {
124         start_explicit = false;
125         release();
126     }
127     forced_stop();
128     stop_dependents();
129     stopped();
130 }
131
132
133 void service_record::require() noexcept
134 {
135     if (required_by++ == 0) {
136         prop_require = !prop_release;
137         prop_release = false;
138         services->add_prop_queue(this);
139     }
140 }
141
142 void service_record::release() noexcept
143 {
144     if (--required_by == 0) {
145         desired_state = service_state_t::STOPPED;
146
147         // Can stop, and can release dependencies now. We don't need to issue a release if
148         // the require was pending though:
149         prop_release = !prop_require;
150         prop_require = false;
151         services->add_prop_queue(this);
152
153         if (service_state == service_state_t::STOPPED) {
154             services->service_inactive(this);
155         }
156         else {
157             do_stop();
158         }
159     }
160 }
161
162 void service_record::release_dependencies() noexcept
163 {
164     for (auto & dependency : depends_on) {
165         service_record * dep_to = dependency.get_to();
166         if (dependency.holding_acq) {
167             dep_to->release();
168             dependency.holding_acq = false;
169         }
170     }
171 }
172
173 void service_record::start(bool activate) noexcept
174 {
175     if (activate && ! start_explicit) {
176         require();
177         start_explicit = true;
178     }
179     
180     if (desired_state == service_state_t::STARTED && service_state != service_state_t::STOPPED) return;
181
182     bool was_active = service_state != service_state_t::STOPPED || desired_state != service_state_t::STOPPED;
183     desired_state = service_state_t::STARTED;
184     
185     if (service_state != service_state_t::STOPPED) {
186         // We're already starting/started, or we are stopping and need to wait for
187         // that the complete.
188         if (service_state != service_state_t::STOPPING || ! can_interrupt_stop()) {
189             return;
190         }
191         // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
192         // but if so they are waiting (for us), so they too can be instantly returned to
193         // STARTING state.
194         notify_listeners(service_event_t::STOPCANCELLED);
195     }
196     else if (! was_active) {
197         services->service_active(this);
198     }
199
200     service_state = service_state_t::STARTING;
201     waiting_for_deps = true;
202
203     if (start_check_dependencies()) {
204         services->add_transition_queue(this);
205     }
206 }
207
208 void service_record::do_propagation() noexcept
209 {
210     if (prop_require) {
211         // Need to require all our dependencies
212         for (auto & dep : depends_on) {
213             dep.get_to()->require();
214             dep.holding_acq = true;
215         }
216         prop_require = false;
217     }
218     
219     if (prop_release) {
220         release_dependencies();
221         prop_release = false;
222     }
223     
224     if (prop_failure) {
225         prop_failure = false;
226         failed_to_start(true);
227     }
228     
229     if (prop_start) {
230         prop_start = false;
231         start(false);
232     }
233
234     if (prop_stop) {
235         prop_stop = false;
236         do_stop();
237     }
238 }
239
240 void service_record::execute_transition() noexcept
241 {
242     // state is STARTED with restarting set true if we are running a smooth recovery.
243     if (service_state == service_state_t::STARTING || (service_state == service_state_t::STARTED
244             && restarting)) {
245         if (check_deps_started()) {
246             bool have_console = service_state == service_state_t::STARTED && onstart_flags.runs_on_console;
247             all_deps_started(have_console);
248         }
249     }
250     else if (service_state == service_state_t::STOPPING) {
251         if (stop_check_dependents()) {
252             bring_down();
253         }
254     }
255 }
256
257 void service_record::do_start() noexcept
258 {
259     if (pinned_stopped) return;
260     
261     if (service_state != service_state_t::STARTING) {
262         return;
263     }
264     
265     service_state = service_state_t::STARTING;
266
267     waiting_for_deps = true;
268
269     // Ask dependencies to start, mark them as being waited on.
270     if (check_deps_started()) {
271         // Once all dependencies are started, we start properly:
272         all_deps_started();
273     }
274 }
275
276 void service_record::dependency_started() noexcept
277 {
278     if ((service_state == service_state_t::STARTING || service_state == service_state_t::STARTED)
279             && waiting_for_deps) {
280         services->add_transition_queue(this);
281     }
282 }
283
284 bool service_record::start_check_dependencies() noexcept
285 {
286     bool all_deps_started = true;
287
288     for (auto & dep : depends_on) {
289         service_record * to = dep.get_to();
290         if (to->service_state != service_state_t::STARTED) {
291             if (to->service_state != service_state_t::STARTING) {
292                 to->prop_start = true;
293                 services->add_prop_queue(to);
294             }
295             dep.waiting_on = true;
296             all_deps_started = false;
297         }
298     }
299     
300     return all_deps_started;
301 }
302
303 bool service_record::check_deps_started() noexcept
304 {
305     for (auto & dep : depends_on) {
306         if (dep.waiting_on) {
307             return false;
308         }
309     }
310
311     return true;
312 }
313
314 bool service_record::open_socket() noexcept
315 {
316     if (socket_path.empty() || socket_fd != -1) {
317         // No socket, or already open
318         return true;
319     }
320     
321     const char * saddrname = socket_path.c_str();
322     
323     // Check the specified socket path
324     struct stat stat_buf;
325     if (stat(saddrname, &stat_buf) == 0) {
326         if ((stat_buf.st_mode & S_IFSOCK) == 0) {
327             // Not a socket
328             log(loglevel_t::ERROR, service_name, ": Activation socket file exists (and is not a socket)");
329             return false;
330         }
331     }
332     else if (errno != ENOENT) {
333         // Other error
334         log(loglevel_t::ERROR, service_name, ": Error checking activation socket: ", strerror(errno));
335         return false;
336     }
337
338     // Remove stale socket file (if it exists).
339     // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
340     // error when we try to create the socket anyway.
341     unlink(saddrname);
342
343     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
344     struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
345     if (name == nullptr) {
346         log(loglevel_t::ERROR, service_name, ": Opening activation socket: out of memory");
347         return false;
348     }
349
350     name->sun_family = AF_UNIX;
351     strcpy(name->sun_path, saddrname);
352
353     int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
354     if (sockfd == -1) {
355         log(loglevel_t::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
356         free(name);
357         return false;
358     }
359
360     if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
361         log(loglevel_t::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
362         close(sockfd);
363         free(name);
364         return false;
365     }
366     
367     free(name);
368     
369     // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
370     // use chown and chmod instead.
371     if (chown(saddrname, socket_uid, socket_gid)) {
372         log(loglevel_t::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
373         close(sockfd);
374         return false;
375     }
376     
377     if (chmod(saddrname, socket_perms) == -1) {
378         log(loglevel_t::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
379         close(sockfd);
380         return false;
381     }
382
383     if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
384         log(loglevel_t::ERROR, ": Error listening on activation socket: ", strerror(errno));
385         close(sockfd);
386         return false;
387     }
388     
389     socket_fd = sockfd;
390     return true;
391 }
392
393 void service_record::all_deps_started(bool has_console) noexcept
394 {
395     if (onstart_flags.starts_on_console && ! has_console) {
396         waiting_for_deps = true;
397         queue_for_console();
398         return;
399     }
400     
401     waiting_for_deps = false;
402
403     if (! can_proceed_to_start()) {
404         waiting_for_deps = true;
405         return;
406     }
407
408     if (! open_socket()) {
409         failed_to_start();
410     }
411
412     bool start_success = bring_up();
413     if (! start_success) {
414         failed_to_start();
415     }
416 }
417
418 void service_record::acquired_console() noexcept
419 {
420     if (service_state != service_state_t::STARTING) {
421         // We got the console but no longer want it.
422         release_console();
423     }
424     else if (check_deps_started()) {
425         all_deps_started(true);
426     }
427     else {
428         // We got the console but can't use it yet.
429         release_console();
430     }
431 }
432
433
434 void service_record::started() noexcept
435 {
436     if (onstart_flags.starts_on_console && ! onstart_flags.runs_on_console) {
437         tcsetpgrp(0, getpgrp());
438         release_console();
439     }
440
441     log_service_started(get_name());
442     service_state = service_state_t::STARTED;
443     notify_listeners(service_event_t::STARTED);
444
445     if (onstart_flags.rw_ready) {
446         open_control_socket();
447     }
448     if (onstart_flags.log_ready) {
449         setup_external_log();
450     }
451
452     if (force_stop || desired_state == service_state_t::STOPPED) {
453         // We must now stop.
454         do_stop();
455         return;
456     }
457
458     // Notify any dependents whose desired state is STARTED:
459     for (auto dept : dependents) {
460         dept->get_from()->dependency_started();
461         dept->waiting_on = false;
462     }
463 }
464
465 void service_record::failed_to_start(bool depfailed) noexcept
466 {
467     if (!depfailed && onstart_flags.starts_on_console) {
468         tcsetpgrp(0, getpgrp());
469         release_console();
470     }
471     
472     log_service_failed(get_name());
473     service_state = service_state_t::STOPPED;
474     if (start_explicit) {
475         start_explicit = false;
476         release();
477     }
478     notify_listeners(service_event_t::FAILEDSTART);
479     
480     // Cancel start of dependents:
481     for (auto & dept : dependents) {
482         switch (dept->dep_type) {
483         case dependency_type::REGULAR:
484         case dependency_type::MILESTONE:
485             if (dept->get_from()->service_state == service_state_t::STARTING) {
486                 dept->get_from()->prop_failure = true;
487                 services->add_prop_queue(dept->get_from());
488             }
489             break;
490         case dependency_type::WAITS_FOR:
491         case dependency_type::SOFT:
492             if (dept->waiting_on) {
493                 dept->waiting_on = false;
494                 dept->get_from()->dependency_started();
495             }
496             if (dept->holding_acq) {
497                 dept->holding_acq = false;
498                 release();
499             }
500         }
501     }
502 }
503
504 bool service_record::bring_up() noexcept
505 {
506     // default implementation: there is no process, so we are started.
507     started();
508     return true;
509 }
510
511 // Mark this and all dependent services as force-stopped.
512 void service_record::forced_stop() noexcept
513 {
514     if (service_state != service_state_t::STOPPED) {
515         force_stop = true;
516         services->add_transition_queue(this);
517     }
518 }
519
520 void service_record::dependent_stopped() noexcept
521 {
522     if (service_state == service_state_t::STOPPING && waiting_for_deps) {
523         services->add_transition_queue(this);
524     }
525 }
526
527 void service_record::stop(bool bring_down) noexcept
528 {
529     if (start_explicit) {
530         start_explicit = false;
531         release();
532     }
533
534     if (bring_down) {
535         do_stop();
536     }
537 }
538
539 void service_record::do_stop() noexcept
540 {
541     if (pinned_started) return;
542
543     if (start_explicit && ! do_auto_restart()) {
544         start_explicit = false;
545         release();
546         if (required_by == 0) return; // release will re-call us anyway
547     }
548
549     bool all_deps_stopped = stop_dependents();
550
551     if (service_state != service_state_t::STARTED) {
552         if (service_state == service_state_t::STARTING) {
553             if (! waiting_for_deps) {
554                 if (! can_interrupt_start()) {
555                     // Well this is awkward: we're going to have to continue starting. We can stop once we've
556                     // reached the started state.
557                     return;
558                 }
559
560                 if (! interrupt_start()) {
561                     // Now wait for service startup to actually end; we don't need to handle it here.
562                     return;
563                 }
564             }
565
566             // We must have had desired_state == STARTED.
567             notify_listeners(service_event_t::STARTCANCELLED);
568
569             // Reaching this point, we are starting interruptibly - so we
570             // stop now (by falling through to below).
571         }
572         else {
573             // If we're starting we need to wait for that to complete.
574             // If we're already stopping/stopped there's nothing to do.
575             return;
576         }
577     }
578
579     service_state = service_state_t::STOPPING;
580     waiting_for_deps = true;
581     if (all_deps_stopped) {
582         services->add_transition_queue(this);
583     }
584 }
585
586 bool service_record::stop_check_dependents() noexcept
587 {
588     bool all_deps_stopped = true;
589     for (auto dept : dependents) {
590         if (dept->dep_type == dependency_type::REGULAR && ! dept->get_from()->is_stopped()) {
591             all_deps_stopped = false;
592             break;
593         }
594     }
595     
596     return all_deps_stopped;
597 }
598
599 bool service_record::stop_dependents() noexcept
600 {
601     bool all_deps_stopped = true;
602     for (auto dept : dependents) {
603         if (dept->dep_type == dependency_type::REGULAR) {
604             if (! dept->get_from()->is_stopped()) {
605                 // Note we check *first* since if the dependent service is not stopped,
606                 // 1. We will issue a stop to it shortly and
607                 // 2. It will notify us when stopped, at which point the stop_check_dependents()
608                 //    check is run anyway.
609                 all_deps_stopped = false;
610             }
611
612             if (force_stop) {
613                 // If this service is to be forcefully stopped, dependents must also be.
614                 dept->get_from()->forced_stop();
615             }
616
617             dept->get_from()->prop_stop = true;
618             services->add_prop_queue(dept->get_from());
619         }
620     }
621
622     return all_deps_stopped;
623 }
624
625 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
626 void service_record::bring_down() noexcept
627 {
628     waiting_for_deps = false;
629     stopped();
630 }
631
632 void service_record::unpin() noexcept
633 {
634     if (pinned_started) {
635         pinned_started = false;
636         if (desired_state == service_state_t::STOPPED || force_stop) {
637             do_stop();
638             services->process_queues();
639         }
640     }
641     if (pinned_stopped) {
642         pinned_stopped = false;
643         if (desired_state == service_state_t::STARTED) {
644             do_start();
645             services->process_queues();
646         }
647     }
648 }
649
650 void service_record::queue_for_console() noexcept
651 {
652     services->append_console_queue(this);
653 }
654
655 void service_record::release_console() noexcept
656 {
657     services->pull_console_queue();
658 }
659
660 bool service_record::interrupt_start() noexcept
661 {
662     services->unqueue_console(this);
663     return true;
664 }
665
666 void service_set::service_active(service_record *sr) noexcept
667 {
668     active_services++;
669 }
670
671 void service_set::service_inactive(service_record *sr) noexcept
672 {
673     active_services--;
674 }