Re-work console acquisition/release.
[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(false);
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(bool issue_stop) 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 if (issue_stop) {
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             all_deps_started();
247         }
248     }
249     else if (service_state == service_state_t::STOPPING) {
250         if (stop_check_dependents()) {
251             waiting_for_deps = false;
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() noexcept
394 {
395     if (onstart_flags.starts_on_console && ! have_console) {
396         queue_for_console();
397         return;
398     }
399     
400     waiting_for_deps = false;
401
402     if (! can_proceed_to_start()) {
403         waiting_for_deps = true;
404         return;
405     }
406
407     if (! open_socket()) {
408         failed_to_start();
409     }
410
411     bool start_success = bring_up();
412     if (! start_success) {
413         failed_to_start();
414     }
415 }
416
417 void service_record::acquired_console() noexcept
418 {
419     waiting_for_console = false;
420     have_console = true;
421
422     if (service_state != service_state_t::STARTING) {
423         // We got the console but no longer want it.
424         release_console();
425     }
426     else if (check_deps_started()) {
427         all_deps_started();
428     }
429     else {
430         // We got the console but can't use it yet.
431         release_console();
432     }
433 }
434
435
436 void service_record::started() noexcept
437 {
438     // If we start on console but don't keep it, release it now:
439     if (have_console && ! onstart_flags.runs_on_console) {
440         tcsetpgrp(0, getpgrp());
441         release_console();
442     }
443
444     log_service_started(get_name());
445     service_state = service_state_t::STARTED;
446     notify_listeners(service_event_t::STARTED);
447
448     if (onstart_flags.rw_ready) {
449         open_control_socket();
450     }
451     if (onstart_flags.log_ready) {
452         setup_external_log();
453     }
454
455     if (force_stop || desired_state == service_state_t::STOPPED) {
456         // We must now stop.
457         do_stop();
458         return;
459     }
460
461     // Notify any dependents whose desired state is STARTED:
462     for (auto dept : dependents) {
463         dept->get_from()->dependency_started();
464         dept->waiting_on = false;
465     }
466 }
467
468 void service_record::failed_to_start(bool depfailed) noexcept
469 {
470     if (have_console) {
471         tcsetpgrp(0, getpgrp());
472         release_console();
473     }
474     if (waiting_for_console) {
475         services->unqueue_console(this);
476         waiting_for_console = false;
477     }
478     
479     log_service_failed(get_name());
480     service_state = service_state_t::STOPPED;
481     if (start_explicit) {
482         start_explicit = false;
483         release(false);
484     }
485     notify_listeners(service_event_t::FAILEDSTART);
486     
487     // Cancel start of dependents:
488     for (auto & dept : dependents) {
489         switch (dept->dep_type) {
490         case dependency_type::REGULAR:
491         case dependency_type::MILESTONE:
492             if (dept->get_from()->service_state == service_state_t::STARTING) {
493                 dept->get_from()->prop_failure = true;
494                 services->add_prop_queue(dept->get_from());
495             }
496             break;
497         case dependency_type::WAITS_FOR:
498         case dependency_type::SOFT:
499             if (dept->waiting_on) {
500                 dept->waiting_on = false;
501                 dept->get_from()->dependency_started();
502             }
503             if (dept->holding_acq) {
504                 dept->holding_acq = false;
505                 release();
506             }
507         }
508     }
509 }
510
511 bool service_record::bring_up() noexcept
512 {
513     // default implementation: there is no process, so we are started.
514     started();
515     return true;
516 }
517
518 // Mark this and all dependent services as force-stopped.
519 void service_record::forced_stop() noexcept
520 {
521     if (service_state != service_state_t::STOPPED) {
522         force_stop = true;
523         services->add_transition_queue(this);
524     }
525 }
526
527 void service_record::dependent_stopped() noexcept
528 {
529     if (service_state == service_state_t::STOPPING && waiting_for_deps) {
530         services->add_transition_queue(this);
531     }
532 }
533
534 void service_record::stop(bool bring_down) noexcept
535 {
536     if (start_explicit) {
537         start_explicit = false;
538         release();
539     }
540
541     if (bring_down) {
542         do_stop();
543     }
544 }
545
546 void service_record::do_stop() noexcept
547 {
548     if (pinned_started) return;
549
550     if (start_explicit && ! do_auto_restart()) {
551         start_explicit = false;
552         release(false);
553     }
554
555     bool all_deps_stopped = stop_dependents();
556
557     if (service_state != service_state_t::STARTED) {
558         if (service_state == service_state_t::STARTING) {
559             // If waiting for a dependency, or waiting for the console, we can interrupt start. Otherwise,
560             // we need to delegate to can_interrupt_start() (which can be overridden).
561             if (! waiting_for_deps && ! waiting_for_console) {
562                 if (! can_interrupt_start()) {
563                     // Well this is awkward: we're going to have to continue starting. We can stop once we've
564                     // reached the started state.
565                     return;
566                 }
567
568                 if (! interrupt_start()) {
569                     // Now wait for service startup to actually end; we don't need to handle it here.
570                     return;
571                 }
572             }
573             else if (waiting_for_console) {
574                 services->unqueue_console(this);
575                 waiting_for_console = false;
576             }
577
578             // We must have had desired_state == STARTED.
579             notify_listeners(service_event_t::STARTCANCELLED);
580
581             // Reaching this point, we are starting interruptibly - so we
582             // stop now (by falling through to below).
583         }
584         else {
585             // If we're starting we need to wait for that to complete.
586             // If we're already stopping/stopped there's nothing to do.
587             return;
588         }
589     }
590
591     service_state = service_state_t::STOPPING;
592     waiting_for_deps = true;
593     if (all_deps_stopped) {
594         services->add_transition_queue(this);
595     }
596 }
597
598 bool service_record::stop_check_dependents() noexcept
599 {
600     bool all_deps_stopped = true;
601     for (auto dept : dependents) {
602         if (dept->dep_type == dependency_type::REGULAR && ! dept->get_from()->is_stopped()) {
603             all_deps_stopped = false;
604             break;
605         }
606     }
607     
608     return all_deps_stopped;
609 }
610
611 bool service_record::stop_dependents() noexcept
612 {
613     bool all_deps_stopped = true;
614     for (auto dept : dependents) {
615         if (dept->dep_type == dependency_type::REGULAR) {
616             if (! dept->get_from()->is_stopped()) {
617                 // Note we check *first* since if the dependent service is not stopped,
618                 // 1. We will issue a stop to it shortly and
619                 // 2. It will notify us when stopped, at which point the stop_check_dependents()
620                 //    check is run anyway.
621                 all_deps_stopped = false;
622             }
623
624             if (force_stop) {
625                 // If this service is to be forcefully stopped, dependents must also be.
626                 dept->get_from()->forced_stop();
627             }
628
629             dept->get_from()->prop_stop = true;
630             services->add_prop_queue(dept->get_from());
631         }
632     }
633
634     return all_deps_stopped;
635 }
636
637 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
638 void service_record::bring_down() noexcept
639 {
640     waiting_for_deps = false;
641     stopped();
642 }
643
644 void service_record::unpin() noexcept
645 {
646     if (pinned_started) {
647         pinned_started = false;
648         if (desired_state == service_state_t::STOPPED || force_stop) {
649             do_stop();
650             services->process_queues();
651         }
652     }
653     if (pinned_stopped) {
654         pinned_stopped = false;
655         if (desired_state == service_state_t::STARTED) {
656             do_start();
657             services->process_queues();
658         }
659     }
660 }
661
662 void service_record::queue_for_console() noexcept
663 {
664     waiting_for_console = true;
665     services->append_console_queue(this);
666 }
667
668 void service_record::release_console() noexcept
669 {
670     have_console = false;
671     services->pull_console_queue();
672 }
673
674 bool service_record::interrupt_start() noexcept
675 {
676     services->unqueue_console(this);
677     return true;
678 }
679
680 void service_set::service_active(service_record *sr) noexcept
681 {
682     active_services++;
683 }
684
685 void service_set::service_inactive(service_record *sr) noexcept
686 {
687     active_services--;
688 }