]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/service.c
core: unified cgroup hierarchy support
[thirdparty/systemd.git] / src / core / service.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <errno.h>
23 #include <signal.h>
24 #include <unistd.h>
25
26 #include "async.h"
27 #include "manager.h"
28 #include "unit.h"
29 #include "service.h"
30 #include "load-fragment.h"
31 #include "load-dropin.h"
32 #include "log.h"
33 #include "strv.h"
34 #include "unit-name.h"
35 #include "unit-printf.h"
36 #include "dbus-service.h"
37 #include "special.h"
38 #include "exit-status.h"
39 #include "def.h"
40 #include "path-util.h"
41 #include "util.h"
42 #include "utf8.h"
43 #include "env-util.h"
44 #include "fileio.h"
45 #include "bus-error.h"
46 #include "bus-util.h"
47 #include "bus-kernel.h"
48 #include "formats-util.h"
49 #include "process-util.h"
50 #include "signal-util.h"
51
52 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
53 [SERVICE_DEAD] = UNIT_INACTIVE,
54 [SERVICE_START_PRE] = UNIT_ACTIVATING,
55 [SERVICE_START] = UNIT_ACTIVATING,
56 [SERVICE_START_POST] = UNIT_ACTIVATING,
57 [SERVICE_RUNNING] = UNIT_ACTIVE,
58 [SERVICE_EXITED] = UNIT_ACTIVE,
59 [SERVICE_RELOAD] = UNIT_RELOADING,
60 [SERVICE_STOP] = UNIT_DEACTIVATING,
61 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
62 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
63 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
64 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
65 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
66 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
67 [SERVICE_FAILED] = UNIT_FAILED,
68 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
69 };
70
71 /* For Type=idle we never want to delay any other jobs, hence we
72 * consider idle jobs active as soon as we start working on them */
73 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
74 [SERVICE_DEAD] = UNIT_INACTIVE,
75 [SERVICE_START_PRE] = UNIT_ACTIVE,
76 [SERVICE_START] = UNIT_ACTIVE,
77 [SERVICE_START_POST] = UNIT_ACTIVE,
78 [SERVICE_RUNNING] = UNIT_ACTIVE,
79 [SERVICE_EXITED] = UNIT_ACTIVE,
80 [SERVICE_RELOAD] = UNIT_RELOADING,
81 [SERVICE_STOP] = UNIT_DEACTIVATING,
82 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
83 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
84 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
85 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
86 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
87 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
88 [SERVICE_FAILED] = UNIT_FAILED,
89 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
90 };
91
92 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
93 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
94 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
95
96 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
97 static void service_enter_reload_by_notify(Service *s);
98
99 static void service_init(Unit *u) {
100 Service *s = SERVICE(u);
101
102 assert(u);
103 assert(u->load_state == UNIT_STUB);
104
105 s->timeout_start_usec = u->manager->default_timeout_start_usec;
106 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
107 s->restart_usec = u->manager->default_restart_usec;
108 s->type = _SERVICE_TYPE_INVALID;
109 s->socket_fd = -1;
110 s->bus_endpoint_fd = -1;
111 s->guess_main_pid = true;
112
113 RATELIMIT_INIT(s->start_limit, u->manager->default_start_limit_interval, u->manager->default_start_limit_burst);
114
115 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
116 }
117
118 static void service_unwatch_control_pid(Service *s) {
119 assert(s);
120
121 if (s->control_pid <= 0)
122 return;
123
124 unit_unwatch_pid(UNIT(s), s->control_pid);
125 s->control_pid = 0;
126 }
127
128 static void service_unwatch_main_pid(Service *s) {
129 assert(s);
130
131 if (s->main_pid <= 0)
132 return;
133
134 unit_unwatch_pid(UNIT(s), s->main_pid);
135 s->main_pid = 0;
136 }
137
138 static void service_unwatch_pid_file(Service *s) {
139 if (!s->pid_file_pathspec)
140 return;
141
142 log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
143 path_spec_unwatch(s->pid_file_pathspec);
144 path_spec_done(s->pid_file_pathspec);
145 free(s->pid_file_pathspec);
146 s->pid_file_pathspec = NULL;
147 }
148
149 static int service_set_main_pid(Service *s, pid_t pid) {
150 pid_t ppid;
151
152 assert(s);
153
154 if (pid <= 1)
155 return -EINVAL;
156
157 if (pid == getpid())
158 return -EINVAL;
159
160 if (s->main_pid == pid && s->main_pid_known)
161 return 0;
162
163 if (s->main_pid != pid) {
164 service_unwatch_main_pid(s);
165 exec_status_start(&s->main_exec_status, pid);
166 }
167
168 s->main_pid = pid;
169 s->main_pid_known = true;
170
171 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
172 log_unit_warning(UNIT(s), "Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.", pid);
173 s->main_pid_alien = true;
174 } else
175 s->main_pid_alien = false;
176
177 return 0;
178 }
179
180 static void service_close_socket_fd(Service *s) {
181 assert(s);
182
183 s->socket_fd = asynchronous_close(s->socket_fd);
184 }
185
186 static void service_connection_unref(Service *s) {
187 assert(s);
188
189 if (!UNIT_ISSET(s->accept_socket))
190 return;
191
192 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
193 unit_ref_unset(&s->accept_socket);
194 }
195
196 static void service_stop_watchdog(Service *s) {
197 assert(s);
198
199 s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
200 s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
201 }
202
203 static void service_start_watchdog(Service *s) {
204 int r;
205
206 assert(s);
207
208 if (s->watchdog_usec <= 0)
209 return;
210
211 if (s->watchdog_event_source) {
212 r = sd_event_source_set_time(s->watchdog_event_source, s->watchdog_timestamp.monotonic + s->watchdog_usec);
213 if (r < 0) {
214 log_unit_warning_errno(UNIT(s), r, "Failed to reset watchdog timer: %m");
215 return;
216 }
217
218 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
219 } else {
220 r = sd_event_add_time(
221 UNIT(s)->manager->event,
222 &s->watchdog_event_source,
223 CLOCK_MONOTONIC,
224 s->watchdog_timestamp.monotonic + s->watchdog_usec, 0,
225 service_dispatch_watchdog, s);
226 if (r < 0) {
227 log_unit_warning_errno(UNIT(s), r, "Failed to add watchdog timer: %m");
228 return;
229 }
230
231 (void) sd_event_source_set_description(s->watchdog_event_source, "service-watchdog");
232
233 /* Let's process everything else which might be a sign
234 * of living before we consider a service died. */
235 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
236 }
237
238 if (r < 0)
239 log_unit_warning_errno(UNIT(s), r, "Failed to install watchdog timer: %m");
240 }
241
242 static void service_reset_watchdog(Service *s) {
243 assert(s);
244
245 dual_timestamp_get(&s->watchdog_timestamp);
246 service_start_watchdog(s);
247 }
248
249 static void service_fd_store_unlink(ServiceFDStore *fs) {
250
251 if (!fs)
252 return;
253
254 if (fs->service) {
255 assert(fs->service->n_fd_store > 0);
256 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
257 fs->service->n_fd_store--;
258 }
259
260 if (fs->event_source) {
261 sd_event_source_set_enabled(fs->event_source, SD_EVENT_OFF);
262 sd_event_source_unref(fs->event_source);
263 }
264
265 safe_close(fs->fd);
266 free(fs);
267 }
268
269 static void service_release_resources(Unit *u) {
270 Service *s = SERVICE(u);
271
272 assert(s);
273
274 if (!s->fd_store)
275 return;
276
277 log_unit_debug(u, "Releasing all resources.");
278
279 while (s->fd_store)
280 service_fd_store_unlink(s->fd_store);
281
282 assert(s->n_fd_store == 0);
283 }
284
285 static void service_done(Unit *u) {
286 Service *s = SERVICE(u);
287
288 assert(s);
289
290 free(s->pid_file);
291 s->pid_file = NULL;
292
293 free(s->status_text);
294 s->status_text = NULL;
295
296 free(s->reboot_arg);
297 s->reboot_arg = NULL;
298
299 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
300 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
301 s->control_command = NULL;
302 s->main_command = NULL;
303
304 exit_status_set_free(&s->restart_prevent_status);
305 exit_status_set_free(&s->restart_force_status);
306 exit_status_set_free(&s->success_status);
307
308 /* This will leak a process, but at least no memory or any of
309 * our resources */
310 service_unwatch_main_pid(s);
311 service_unwatch_control_pid(s);
312 service_unwatch_pid_file(s);
313
314 if (s->bus_name) {
315 unit_unwatch_bus_name(u, s->bus_name);
316 free(s->bus_name);
317 s->bus_name = NULL;
318 }
319
320 s->bus_endpoint_fd = safe_close(s->bus_endpoint_fd);
321 service_close_socket_fd(s);
322 service_connection_unref(s);
323
324 unit_ref_unset(&s->accept_socket);
325
326 service_stop_watchdog(s);
327
328 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
329
330 service_release_resources(u);
331 }
332
333 static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
334 ServiceFDStore *fs = userdata;
335
336 assert(e);
337 assert(fs);
338
339 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
340 service_fd_store_unlink(fs);
341 return 0;
342 }
343
344 static int service_add_fd_store(Service *s, int fd) {
345 ServiceFDStore *fs;
346 int r;
347
348 assert(s);
349 assert(fd >= 0);
350
351 if (s->n_fd_store >= s->n_fd_store_max)
352 return 0;
353
354 LIST_FOREACH(fd_store, fs, s->fd_store) {
355 r = same_fd(fs->fd, fd);
356 if (r < 0)
357 return r;
358 if (r > 0) {
359 /* Already included */
360 safe_close(fd);
361 return 1;
362 }
363 }
364
365 fs = new0(ServiceFDStore, 1);
366 if (!fs)
367 return -ENOMEM;
368
369 fs->fd = fd;
370 fs->service = s;
371
372 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fd, 0, on_fd_store_io, fs);
373 if (r < 0) {
374 free(fs);
375 return r;
376 }
377
378 (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
379
380 LIST_PREPEND(fd_store, s->fd_store, fs);
381 s->n_fd_store++;
382
383 return 1;
384 }
385
386 static int service_add_fd_store_set(Service *s, FDSet *fds) {
387 int r;
388
389 assert(s);
390
391 if (fdset_size(fds) <= 0)
392 return 0;
393
394 while (s->n_fd_store < s->n_fd_store_max) {
395 _cleanup_close_ int fd = -1;
396
397 fd = fdset_steal_first(fds);
398 if (fd < 0)
399 break;
400
401 r = service_add_fd_store(s, fd);
402 if (r < 0)
403 return log_unit_error_errno(UNIT(s), r, "Couldn't add fd to fd store: %m");
404 if (r > 0) {
405 log_unit_debug(UNIT(s), "Added fd to fd store.");
406 fd = -1;
407 }
408 }
409
410 if (fdset_size(fds) > 0)
411 log_unit_warning(UNIT(s), "Tried to store more fds than FDStoreMax=%u allows, closing remaining.", s->n_fd_store_max);
412
413 return 0;
414 }
415
416 static int service_arm_timer(Service *s, usec_t usec) {
417 int r;
418
419 assert(s);
420
421 if (s->timer_event_source) {
422 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
423 if (r < 0)
424 return r;
425
426 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
427 }
428
429 r = sd_event_add_time(
430 UNIT(s)->manager->event,
431 &s->timer_event_source,
432 CLOCK_MONOTONIC,
433 now(CLOCK_MONOTONIC) + usec, 0,
434 service_dispatch_timer, s);
435 if (r < 0)
436 return r;
437
438 (void) sd_event_source_set_description(s->timer_event_source, "service-timer");
439
440 return 0;
441 }
442
443 static int service_verify(Service *s) {
444 assert(s);
445
446 if (UNIT(s)->load_state != UNIT_LOADED)
447 return 0;
448
449 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP]) {
450 log_unit_error(UNIT(s), "Service lacks both ExecStart= and ExecStop= setting. Refusing.");
451 return -EINVAL;
452 }
453
454 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START]) {
455 log_unit_error(UNIT(s), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
456 return -EINVAL;
457 }
458
459 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START]) {
460 log_unit_error(UNIT(s), "Service has no ExecStart= setting, which is only allowed for RemainAfterExit=yes services. Refusing.");
461 return -EINVAL;
462 }
463
464 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next) {
465 log_unit_error(UNIT(s), "Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
466 return -EINVAL;
467 }
468
469 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
470 log_unit_error(UNIT(s), "Service has Restart= setting other than no, which isn't allowed for Type=oneshot services. Refusing.");
471 return -EINVAL;
472 }
473
474 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
475 log_unit_error(UNIT(s), "Service has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
476 return -EINVAL;
477 }
478
479 if (s->type == SERVICE_DBUS && !s->bus_name) {
480 log_unit_error(UNIT(s), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
481 return -EINVAL;
482 }
483
484 if (s->bus_name && s->type != SERVICE_DBUS)
485 log_unit_warning(UNIT(s), "Service has a D-Bus service name specified, but is not of type dbus. Ignoring.");
486
487 if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
488 log_unit_error(UNIT(s), "Service has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.");
489 return -EINVAL;
490 }
491
492 return 0;
493 }
494
495 static int service_add_default_dependencies(Service *s) {
496 int r;
497
498 assert(s);
499
500 /* Add a number of automatic dependencies useful for the
501 * majority of services. */
502
503 /* First, pull in base system */
504 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true);
505 if (r < 0)
506 return r;
507
508 /* Second, activate normal shutdown */
509 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
510 }
511
512 static void service_fix_output(Service *s) {
513 assert(s);
514
515 /* If nothing has been explicitly configured, patch default
516 * output in. If input is socket/tty we avoid this however,
517 * since in that case we want output to default to the same
518 * place as we read input from. */
519
520 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
521 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
522 s->exec_context.std_input == EXEC_INPUT_NULL)
523 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
524
525 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
526 s->exec_context.std_input == EXEC_INPUT_NULL)
527 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
528 }
529
530 static int service_add_extras(Service *s) {
531 int r;
532
533 assert(s);
534
535 if (s->type == _SERVICE_TYPE_INVALID) {
536 /* Figure out a type automatically */
537 if (s->bus_name)
538 s->type = SERVICE_DBUS;
539 else if (s->exec_command[SERVICE_EXEC_START])
540 s->type = SERVICE_SIMPLE;
541 else
542 s->type = SERVICE_ONESHOT;
543 }
544
545 /* Oneshot services have disabled start timeout by default */
546 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
547 s->timeout_start_usec = 0;
548
549 service_fix_output(s);
550
551 r = unit_patch_contexts(UNIT(s));
552 if (r < 0)
553 return r;
554
555 r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
556 if (r < 0)
557 return r;
558
559 r = unit_set_default_slice(UNIT(s));
560 if (r < 0)
561 return r;
562
563 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
564 s->notify_access = NOTIFY_MAIN;
565
566 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
567 s->notify_access = NOTIFY_MAIN;
568
569 if (s->bus_name) {
570 const char *n;
571
572 n = strjoina(s->bus_name, ".busname");
573 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, n, NULL, true);
574 if (r < 0)
575 return r;
576
577 r = unit_watch_bus_name(UNIT(s), s->bus_name);
578 if (r == -EEXIST)
579 return log_unit_error_errno(UNIT(s), r, "Two services allocated for the same bus name %s, refusing operation.", s->bus_name);
580 if (r < 0)
581 return log_unit_error_errno(UNIT(s), r, "Cannot watch bus name %s: %m", s->bus_name);
582 }
583
584 if (UNIT(s)->default_dependencies) {
585 r = service_add_default_dependencies(s);
586 if (r < 0)
587 return r;
588 }
589
590 return 0;
591 }
592
593 static int service_load(Unit *u) {
594 Service *s = SERVICE(u);
595 int r;
596
597 assert(s);
598
599 /* Load a .service file */
600 r = unit_load_fragment(u);
601 if (r < 0)
602 return r;
603
604 /* Still nothing found? Then let's give up */
605 if (u->load_state == UNIT_STUB)
606 return -ENOENT;
607
608 /* This is a new unit? Then let's add in some extras */
609 if (u->load_state == UNIT_LOADED) {
610
611 /* We were able to load something, then let's add in
612 * the dropin directories. */
613 r = unit_load_dropin(u);
614 if (r < 0)
615 return r;
616
617 /* This is a new unit? Then let's add in some
618 * extras */
619 r = service_add_extras(s);
620 if (r < 0)
621 return r;
622 }
623
624 return service_verify(s);
625 }
626
627 static void service_dump(Unit *u, FILE *f, const char *prefix) {
628 ServiceExecCommand c;
629 Service *s = SERVICE(u);
630 const char *prefix2;
631
632 assert(s);
633
634 prefix = strempty(prefix);
635 prefix2 = strjoina(prefix, "\t");
636
637 fprintf(f,
638 "%sService State: %s\n"
639 "%sResult: %s\n"
640 "%sReload Result: %s\n"
641 "%sPermissionsStartOnly: %s\n"
642 "%sRootDirectoryStartOnly: %s\n"
643 "%sRemainAfterExit: %s\n"
644 "%sGuessMainPID: %s\n"
645 "%sType: %s\n"
646 "%sRestart: %s\n"
647 "%sNotifyAccess: %s\n"
648 "%sNotifyState: %s\n",
649 prefix, service_state_to_string(s->state),
650 prefix, service_result_to_string(s->result),
651 prefix, service_result_to_string(s->reload_result),
652 prefix, yes_no(s->permissions_start_only),
653 prefix, yes_no(s->root_directory_start_only),
654 prefix, yes_no(s->remain_after_exit),
655 prefix, yes_no(s->guess_main_pid),
656 prefix, service_type_to_string(s->type),
657 prefix, service_restart_to_string(s->restart),
658 prefix, notify_access_to_string(s->notify_access),
659 prefix, notify_state_to_string(s->notify_state));
660
661 if (s->control_pid > 0)
662 fprintf(f,
663 "%sControl PID: "PID_FMT"\n",
664 prefix, s->control_pid);
665
666 if (s->main_pid > 0)
667 fprintf(f,
668 "%sMain PID: "PID_FMT"\n"
669 "%sMain PID Known: %s\n"
670 "%sMain PID Alien: %s\n",
671 prefix, s->main_pid,
672 prefix, yes_no(s->main_pid_known),
673 prefix, yes_no(s->main_pid_alien));
674
675 if (s->pid_file)
676 fprintf(f,
677 "%sPIDFile: %s\n",
678 prefix, s->pid_file);
679
680 if (s->bus_name)
681 fprintf(f,
682 "%sBusName: %s\n"
683 "%sBus Name Good: %s\n",
684 prefix, s->bus_name,
685 prefix, yes_no(s->bus_name_good));
686
687 kill_context_dump(&s->kill_context, f, prefix);
688 exec_context_dump(&s->exec_context, f, prefix);
689
690 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
691
692 if (!s->exec_command[c])
693 continue;
694
695 fprintf(f, "%s-> %s:\n",
696 prefix, service_exec_command_to_string(c));
697
698 exec_command_dump_list(s->exec_command[c], f, prefix2);
699 }
700
701 if (s->status_text)
702 fprintf(f, "%sStatus Text: %s\n",
703 prefix, s->status_text);
704
705 if (s->n_fd_store_max > 0) {
706 fprintf(f,
707 "%sFile Descriptor Store Max: %u\n"
708 "%sFile Descriptor Store Current: %u\n",
709 prefix, s->n_fd_store_max,
710 prefix, s->n_fd_store);
711 }
712 }
713
714 static int service_load_pid_file(Service *s, bool may_warn) {
715 _cleanup_free_ char *k = NULL;
716 int r;
717 pid_t pid;
718
719 assert(s);
720
721 if (!s->pid_file)
722 return -ENOENT;
723
724 r = read_one_line_file(s->pid_file, &k);
725 if (r < 0) {
726 if (may_warn)
727 log_unit_info_errno(UNIT(s), r, "PID file %s not readable (yet?) after %s: %m", s->pid_file, service_state_to_string(s->state));
728 return r;
729 }
730
731 r = parse_pid(k, &pid);
732 if (r < 0) {
733 if (may_warn)
734 log_unit_info_errno(UNIT(s), r, "Failed to read PID from file %s: %m", s->pid_file);
735 return r;
736 }
737
738 if (!pid_is_alive(pid)) {
739 if (may_warn)
740 log_unit_info(UNIT(s), "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
741 return -ESRCH;
742 }
743
744 if (s->main_pid_known) {
745 if (pid == s->main_pid)
746 return 0;
747
748 log_unit_debug(UNIT(s), "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
749
750 service_unwatch_main_pid(s);
751 s->main_pid_known = false;
752 } else
753 log_unit_debug(UNIT(s), "Main PID loaded: "PID_FMT, pid);
754
755 r = service_set_main_pid(s, pid);
756 if (r < 0)
757 return r;
758
759 r = unit_watch_pid(UNIT(s), pid);
760 if (r < 0) {
761 /* FIXME: we need to do something here */
762 log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" for service: %m", pid);
763 return r;
764 }
765
766 return 0;
767 }
768
769 static int service_search_main_pid(Service *s) {
770 pid_t pid = 0;
771 int r;
772
773 assert(s);
774
775 /* If we know it anyway, don't ever fallback to unreliable
776 * heuristics */
777 if (s->main_pid_known)
778 return 0;
779
780 if (!s->guess_main_pid)
781 return 0;
782
783 assert(s->main_pid <= 0);
784
785 r = unit_search_main_pid(UNIT(s), &pid);
786 if (r < 0)
787 return r;
788
789 log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid);
790 r = service_set_main_pid(s, pid);
791 if (r < 0)
792 return r;
793
794 r = unit_watch_pid(UNIT(s), pid);
795 if (r < 0) {
796 /* FIXME: we need to do something here */
797 log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" from: %m", pid);
798 return r;
799 }
800
801 return 0;
802 }
803
804 static void service_set_state(Service *s, ServiceState state) {
805 ServiceState old_state;
806 const UnitActiveState *table;
807
808 assert(s);
809
810 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
811
812 old_state = s->state;
813 s->state = state;
814
815 service_unwatch_pid_file(s);
816
817 if (!IN_SET(state,
818 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
819 SERVICE_RELOAD,
820 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
821 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
822 SERVICE_AUTO_RESTART))
823 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
824
825 if (!IN_SET(state,
826 SERVICE_START, SERVICE_START_POST,
827 SERVICE_RUNNING, SERVICE_RELOAD,
828 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
829 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
830 service_unwatch_main_pid(s);
831 s->main_command = NULL;
832 }
833
834 if (!IN_SET(state,
835 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
836 SERVICE_RELOAD,
837 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
838 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
839 service_unwatch_control_pid(s);
840 s->control_command = NULL;
841 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
842 }
843
844 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
845 unit_unwatch_all_pids(UNIT(s));
846
847 if (!IN_SET(state,
848 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
849 SERVICE_RUNNING, SERVICE_RELOAD,
850 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
851 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
852 !(state == SERVICE_DEAD && UNIT(s)->job)) {
853 service_close_socket_fd(s);
854 service_connection_unref(s);
855 }
856
857 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
858 service_stop_watchdog(s);
859
860 /* For the inactive states unit_notify() will trim the cgroup,
861 * but for exit we have to do that ourselves... */
862 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
863 unit_prune_cgroup(UNIT(s));
864
865 /* For remain_after_exit services, let's see if we can "release" the
866 * hold on the console, since unit_notify() only does that in case of
867 * change of state */
868 if (state == SERVICE_EXITED &&
869 s->remain_after_exit &&
870 UNIT(s)->manager->n_on_console > 0) {
871
872 ExecContext *ec;
873
874 ec = unit_get_exec_context(UNIT(s));
875 if (ec && exec_context_may_touch_console(ec)) {
876 Manager *m = UNIT(s)->manager;
877
878 m->n_on_console --;
879 if (m->n_on_console == 0)
880 /* unset no_console_output flag, since the console is free */
881 m->no_console_output = false;
882 }
883 }
884
885 if (old_state != state)
886 log_unit_debug(UNIT(s), "Changed %s -> %s", service_state_to_string(old_state), service_state_to_string(state));
887
888 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
889 s->reload_result = SERVICE_SUCCESS;
890 }
891
892 static int service_coldplug(Unit *u) {
893 Service *s = SERVICE(u);
894 int r;
895
896 assert(s);
897 assert(s->state == SERVICE_DEAD);
898
899 if (s->deserialized_state != s->state) {
900
901 if (IN_SET(s->deserialized_state,
902 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
903 SERVICE_RELOAD,
904 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
905 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
906
907 usec_t k;
908
909 k = IN_SET(s->deserialized_state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec;
910
911 /* For the start/stop timeouts 0 means off */
912 if (k > 0) {
913 r = service_arm_timer(s, k);
914 if (r < 0)
915 return r;
916 }
917 }
918
919 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
920
921 /* The restart timeouts 0 means immediately */
922 r = service_arm_timer(s, s->restart_usec);
923 if (r < 0)
924 return r;
925 }
926
927 if (pid_is_unwaited(s->main_pid) &&
928 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
929 IN_SET(s->deserialized_state,
930 SERVICE_START, SERVICE_START_POST,
931 SERVICE_RUNNING, SERVICE_RELOAD,
932 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
933 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
934 r = unit_watch_pid(UNIT(s), s->main_pid);
935 if (r < 0)
936 return r;
937 }
938
939 if (pid_is_unwaited(s->control_pid) &&
940 IN_SET(s->deserialized_state,
941 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
942 SERVICE_RELOAD,
943 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
944 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
945 r = unit_watch_pid(UNIT(s), s->control_pid);
946 if (r < 0)
947 return r;
948 }
949
950 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
951 unit_watch_all_pids(UNIT(s));
952
953 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
954 service_start_watchdog(s);
955
956 service_set_state(s, s->deserialized_state);
957 }
958
959 return 0;
960 }
961
962 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
963 _cleanup_free_ int *rfds = NULL;
964 unsigned rn_fds = 0;
965 Iterator i;
966 int r;
967 Unit *u;
968
969 assert(s);
970 assert(fds);
971 assert(n_fds);
972
973 if (s->socket_fd >= 0)
974 return 0;
975
976 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
977 int *cfds;
978 unsigned cn_fds;
979 Socket *sock;
980
981 if (u->type != UNIT_SOCKET)
982 continue;
983
984 sock = SOCKET(u);
985
986 r = socket_collect_fds(sock, &cfds, &cn_fds);
987 if (r < 0)
988 return r;
989
990 if (cn_fds <= 0) {
991 free(cfds);
992 continue;
993 }
994
995 if (!rfds) {
996 rfds = cfds;
997 rn_fds = cn_fds;
998 } else {
999 int *t;
1000
1001 t = realloc(rfds, (rn_fds + cn_fds) * sizeof(int));
1002 if (!t) {
1003 free(cfds);
1004 return -ENOMEM;
1005 }
1006
1007 memcpy(t + rn_fds, cfds, cn_fds * sizeof(int));
1008 rfds = t;
1009 rn_fds += cn_fds;
1010
1011 free(cfds);
1012
1013 }
1014 }
1015
1016 if (s->n_fd_store > 0) {
1017 ServiceFDStore *fs;
1018 int *t;
1019
1020 t = realloc(rfds, (rn_fds + s->n_fd_store) * sizeof(int));
1021 if (!t)
1022 return -ENOMEM;
1023
1024 rfds = t;
1025 LIST_FOREACH(fd_store, fs, s->fd_store)
1026 rfds[rn_fds++] = fs->fd;
1027 }
1028
1029 *fds = rfds;
1030 *n_fds = rn_fds;
1031
1032 rfds = NULL;
1033 return 0;
1034 }
1035
1036 static int service_spawn(
1037 Service *s,
1038 ExecCommand *c,
1039 usec_t timeout,
1040 bool pass_fds,
1041 bool apply_permissions,
1042 bool apply_chroot,
1043 bool apply_tty_stdin,
1044 bool is_control,
1045 pid_t *_pid) {
1046
1047 pid_t pid;
1048 int r;
1049 int *fds = NULL;
1050 _cleanup_free_ int *fdsbuf = NULL;
1051 unsigned n_fds = 0, n_env = 0;
1052 _cleanup_free_ char *bus_endpoint_path = NULL;
1053 _cleanup_strv_free_ char
1054 **argv = NULL, **final_env = NULL, **our_env = NULL;
1055 const char *path;
1056 ExecParameters exec_params = {
1057 .apply_permissions = apply_permissions,
1058 .apply_chroot = apply_chroot,
1059 .apply_tty_stdin = apply_tty_stdin,
1060 .bus_endpoint_fd = -1,
1061 .selinux_context_net = s->socket_fd_selinux_context_net
1062 };
1063
1064 assert(s);
1065 assert(c);
1066 assert(_pid);
1067
1068 (void) unit_realize_cgroup(UNIT(s));
1069 if (s->reset_cpu_usage) {
1070 (void) unit_reset_cpu_usage(UNIT(s));
1071 s->reset_cpu_usage = false;
1072 }
1073
1074 r = unit_setup_exec_runtime(UNIT(s));
1075 if (r < 0)
1076 goto fail;
1077
1078 if (pass_fds ||
1079 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1080 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1081 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1082
1083 if (s->socket_fd >= 0) {
1084 fds = &s->socket_fd;
1085 n_fds = 1;
1086 } else {
1087 r = service_collect_fds(s, &fdsbuf, &n_fds);
1088 if (r < 0)
1089 goto fail;
1090
1091 fds = fdsbuf;
1092 }
1093 }
1094
1095 if (timeout > 0) {
1096 r = service_arm_timer(s, timeout);
1097 if (r < 0)
1098 goto fail;
1099 } else
1100 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1101
1102 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1103 if (r < 0)
1104 goto fail;
1105
1106 our_env = new0(char*, 6);
1107 if (!our_env) {
1108 r = -ENOMEM;
1109 goto fail;
1110 }
1111
1112 if (is_control ? s->notify_access == NOTIFY_ALL : s->notify_access != NOTIFY_NONE)
1113 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
1114 r = -ENOMEM;
1115 goto fail;
1116 }
1117
1118 if (s->main_pid > 0)
1119 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0) {
1120 r = -ENOMEM;
1121 goto fail;
1122 }
1123
1124 if (UNIT(s)->manager->running_as != MANAGER_SYSTEM)
1125 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0) {
1126 r = -ENOMEM;
1127 goto fail;
1128 }
1129
1130 if (UNIT_DEREF(s->accept_socket)) {
1131 union sockaddr_union sa;
1132 socklen_t salen = sizeof(sa);
1133
1134 r = getpeername(s->socket_fd, &sa.sa, &salen);
1135 if (r < 0) {
1136 r = -errno;
1137 goto fail;
1138 }
1139
1140 if (IN_SET(sa.sa.sa_family, AF_INET, AF_INET6)) {
1141 _cleanup_free_ char *addr = NULL;
1142 char *t;
1143 int port;
1144
1145 r = sockaddr_pretty(&sa.sa, salen, true, false, &addr);
1146 if (r < 0)
1147 goto fail;
1148
1149 t = strappend("REMOTE_ADDR=", addr);
1150 if (!t) {
1151 r = -ENOMEM;
1152 goto fail;
1153 }
1154 our_env[n_env++] = t;
1155
1156 port = sockaddr_port(&sa.sa);
1157 if (port < 0) {
1158 r = port;
1159 goto fail;
1160 }
1161
1162 if (asprintf(&t, "REMOTE_PORT=%u", port) < 0) {
1163 r = -ENOMEM;
1164 goto fail;
1165 }
1166 our_env[n_env++] = t;
1167 }
1168 }
1169
1170 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1171 if (!final_env) {
1172 r = -ENOMEM;
1173 goto fail;
1174 }
1175
1176 if (is_control && UNIT(s)->cgroup_path) {
1177 path = strjoina(UNIT(s)->cgroup_path, "/control");
1178 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1179 } else
1180 path = UNIT(s)->cgroup_path;
1181
1182 if (s->exec_context.bus_endpoint) {
1183 r = bus_kernel_create_endpoint(UNIT(s)->manager->running_as == MANAGER_SYSTEM ? "system" : "user",
1184 UNIT(s)->id, &bus_endpoint_path);
1185 if (r < 0)
1186 goto fail;
1187
1188 /* Pass the fd to the exec_params so that the child process can upload the policy.
1189 * Keep a reference to the fd in the service, so the endpoint is kept alive as long
1190 * as the service is running. */
1191 exec_params.bus_endpoint_fd = s->bus_endpoint_fd = r;
1192 }
1193
1194 exec_params.argv = argv;
1195 exec_params.fds = fds;
1196 exec_params.n_fds = n_fds;
1197 exec_params.environment = final_env;
1198 exec_params.confirm_spawn = UNIT(s)->manager->confirm_spawn;
1199 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1200 exec_params.cgroup_path = path;
1201 exec_params.cgroup_delegate = s->cgroup_context.delegate;
1202 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1203 exec_params.watchdog_usec = s->watchdog_usec;
1204 exec_params.bus_endpoint_path = bus_endpoint_path;
1205 if (s->type == SERVICE_IDLE)
1206 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1207
1208 r = exec_spawn(UNIT(s),
1209 c,
1210 &s->exec_context,
1211 &exec_params,
1212 s->exec_runtime,
1213 &pid);
1214 if (r < 0)
1215 goto fail;
1216
1217 r = unit_watch_pid(UNIT(s), pid);
1218 if (r < 0)
1219 /* FIXME: we need to do something here */
1220 goto fail;
1221
1222 *_pid = pid;
1223
1224 return 0;
1225
1226 fail:
1227 if (timeout)
1228 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1229
1230 return r;
1231 }
1232
1233 static int main_pid_good(Service *s) {
1234 assert(s);
1235
1236 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1237 * don't know */
1238
1239 /* If we know the pid file, then let's just check if it is
1240 * still valid */
1241 if (s->main_pid_known) {
1242
1243 /* If it's an alien child let's check if it is still
1244 * alive ... */
1245 if (s->main_pid_alien && s->main_pid > 0)
1246 return pid_is_alive(s->main_pid);
1247
1248 /* .. otherwise assume we'll get a SIGCHLD for it,
1249 * which we really should wait for to collect exit
1250 * status and code */
1251 return s->main_pid > 0;
1252 }
1253
1254 /* We don't know the pid */
1255 return -EAGAIN;
1256 }
1257
1258 _pure_ static int control_pid_good(Service *s) {
1259 assert(s);
1260
1261 return s->control_pid > 0;
1262 }
1263
1264 static int cgroup_good(Service *s) {
1265 int r;
1266
1267 assert(s);
1268
1269 if (!UNIT(s)->cgroup_path)
1270 return 0;
1271
1272 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path);
1273 if (r < 0)
1274 return r;
1275
1276 return !r;
1277 }
1278
1279 static bool service_shall_restart(Service *s) {
1280 assert(s);
1281
1282 /* Don't restart after manual stops */
1283 if (s->forbid_restart)
1284 return false;
1285
1286 /* Never restart if this is configured as special exception */
1287 if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status))
1288 return false;
1289
1290 /* Restart if the exit code/status are configured as restart triggers */
1291 if (exit_status_set_test(&s->restart_force_status, s->main_exec_status.code, s->main_exec_status.status))
1292 return true;
1293
1294 switch (s->restart) {
1295
1296 case SERVICE_RESTART_NO:
1297 return false;
1298
1299 case SERVICE_RESTART_ALWAYS:
1300 return true;
1301
1302 case SERVICE_RESTART_ON_SUCCESS:
1303 return s->result == SERVICE_SUCCESS;
1304
1305 case SERVICE_RESTART_ON_FAILURE:
1306 return s->result != SERVICE_SUCCESS;
1307
1308 case SERVICE_RESTART_ON_ABNORMAL:
1309 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE);
1310
1311 case SERVICE_RESTART_ON_WATCHDOG:
1312 return s->result == SERVICE_FAILURE_WATCHDOG;
1313
1314 case SERVICE_RESTART_ON_ABORT:
1315 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
1316
1317 default:
1318 assert_not_reached("unknown restart setting");
1319 }
1320 }
1321
1322 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1323 int r;
1324 assert(s);
1325
1326 if (f != SERVICE_SUCCESS)
1327 s->result = f;
1328
1329 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1330
1331 if (s->result != SERVICE_SUCCESS) {
1332 log_unit_warning(UNIT(s), "Failed with result '%s'.", service_result_to_string(s->result));
1333 failure_action(UNIT(s)->manager, s->failure_action, s->reboot_arg);
1334 }
1335
1336 if (allow_restart && service_shall_restart(s)) {
1337
1338 r = service_arm_timer(s, s->restart_usec);
1339 if (r < 0)
1340 goto fail;
1341
1342 service_set_state(s, SERVICE_AUTO_RESTART);
1343 }
1344
1345 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1346 s->forbid_restart = false;
1347
1348 /* We want fresh tmpdirs in case service is started again immediately */
1349 exec_runtime_destroy(s->exec_runtime);
1350 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1351
1352 /* Also, remove the runtime directory in */
1353 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1354
1355 /* Try to delete the pid file. At this point it will be
1356 * out-of-date, and some software might be confused by it, so
1357 * let's remove it. */
1358 if (s->pid_file)
1359 unlink_noerrno(s->pid_file);
1360
1361 return;
1362
1363 fail:
1364 log_unit_warning_errno(UNIT(s), r, "Failed to run install restart timer: %m");
1365 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1366 }
1367
1368 static void service_enter_stop_post(Service *s, ServiceResult f) {
1369 int r;
1370 assert(s);
1371
1372 if (f != SERVICE_SUCCESS)
1373 s->result = f;
1374
1375 service_unwatch_control_pid(s);
1376 unit_watch_all_pids(UNIT(s));
1377
1378 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1379 if (s->control_command) {
1380 s->control_command_id = SERVICE_EXEC_STOP_POST;
1381
1382 r = service_spawn(s,
1383 s->control_command,
1384 s->timeout_stop_usec,
1385 false,
1386 !s->permissions_start_only,
1387 !s->root_directory_start_only,
1388 true,
1389 true,
1390 &s->control_pid);
1391 if (r < 0)
1392 goto fail;
1393
1394 service_set_state(s, SERVICE_STOP_POST);
1395 } else
1396 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1397
1398 return;
1399
1400 fail:
1401 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
1402 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1403 }
1404
1405 static int state_to_kill_operation(ServiceState state) {
1406 switch (state) {
1407
1408 case SERVICE_STOP_SIGABRT:
1409 return KILL_ABORT;
1410
1411 case SERVICE_STOP_SIGTERM:
1412 case SERVICE_FINAL_SIGTERM:
1413 return KILL_TERMINATE;
1414
1415 case SERVICE_STOP_SIGKILL:
1416 case SERVICE_FINAL_SIGKILL:
1417 return KILL_KILL;
1418
1419 default:
1420 return _KILL_OPERATION_INVALID;
1421 }
1422 }
1423
1424 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1425 int r;
1426
1427 assert(s);
1428
1429 if (f != SERVICE_SUCCESS)
1430 s->result = f;
1431
1432 unit_watch_all_pids(UNIT(s));
1433
1434 r = unit_kill_context(
1435 UNIT(s),
1436 &s->kill_context,
1437 state_to_kill_operation(state),
1438 s->main_pid,
1439 s->control_pid,
1440 s->main_pid_alien);
1441
1442 if (r < 0)
1443 goto fail;
1444
1445 if (r > 0) {
1446 if (s->timeout_stop_usec > 0) {
1447 r = service_arm_timer(s, s->timeout_stop_usec);
1448 if (r < 0)
1449 goto fail;
1450 }
1451
1452 service_set_state(s, state);
1453 } else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
1454 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1455 else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1456 service_enter_stop_post(s, SERVICE_SUCCESS);
1457 else if (state == SERVICE_FINAL_SIGTERM && s->kill_context.send_sigkill)
1458 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1459 else
1460 service_enter_dead(s, SERVICE_SUCCESS, true);
1461
1462 return;
1463
1464 fail:
1465 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
1466
1467 if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1468 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1469 else
1470 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1471 }
1472
1473 static void service_enter_stop_by_notify(Service *s) {
1474 assert(s);
1475
1476 unit_watch_all_pids(UNIT(s));
1477
1478 if (s->timeout_stop_usec > 0)
1479 service_arm_timer(s, s->timeout_stop_usec);
1480
1481 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1482 service_set_state(s, SERVICE_STOP_SIGTERM);
1483 }
1484
1485 static void service_enter_stop(Service *s, ServiceResult f) {
1486 int r;
1487
1488 assert(s);
1489
1490 if (f != SERVICE_SUCCESS)
1491 s->result = f;
1492
1493 service_unwatch_control_pid(s);
1494 unit_watch_all_pids(UNIT(s));
1495
1496 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1497 if (s->control_command) {
1498 s->control_command_id = SERVICE_EXEC_STOP;
1499
1500 r = service_spawn(s,
1501 s->control_command,
1502 s->timeout_stop_usec,
1503 false,
1504 !s->permissions_start_only,
1505 !s->root_directory_start_only,
1506 false,
1507 true,
1508 &s->control_pid);
1509 if (r < 0)
1510 goto fail;
1511
1512 service_set_state(s, SERVICE_STOP);
1513 } else
1514 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1515
1516 return;
1517
1518 fail:
1519 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop' task: %m");
1520 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1521 }
1522
1523 static bool service_good(Service *s) {
1524 int main_pid_ok;
1525 assert(s);
1526
1527 if (s->type == SERVICE_DBUS && !s->bus_name_good)
1528 return false;
1529
1530 main_pid_ok = main_pid_good(s);
1531 if (main_pid_ok > 0) /* It's alive */
1532 return true;
1533 if (main_pid_ok == 0) /* It's dead */
1534 return false;
1535
1536 /* OK, we don't know anything about the main PID, maybe
1537 * because there is none. Let's check the control group
1538 * instead. */
1539
1540 return cgroup_good(s) != 0;
1541 }
1542
1543 static void service_enter_running(Service *s, ServiceResult f) {
1544 assert(s);
1545
1546 if (f != SERVICE_SUCCESS)
1547 s->result = f;
1548
1549 if (service_good(s)) {
1550
1551 /* If there are any queued up sd_notify()
1552 * notifications, process them now */
1553 if (s->notify_state == NOTIFY_RELOADING)
1554 service_enter_reload_by_notify(s);
1555 else if (s->notify_state == NOTIFY_STOPPING)
1556 service_enter_stop_by_notify(s);
1557 else
1558 service_set_state(s, SERVICE_RUNNING);
1559
1560 } else if (s->remain_after_exit)
1561 service_set_state(s, SERVICE_EXITED);
1562 else
1563 service_enter_stop(s, SERVICE_SUCCESS);
1564 }
1565
1566 static void service_enter_start_post(Service *s) {
1567 int r;
1568 assert(s);
1569
1570 service_unwatch_control_pid(s);
1571 service_reset_watchdog(s);
1572
1573 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1574 if (s->control_command) {
1575 s->control_command_id = SERVICE_EXEC_START_POST;
1576
1577 r = service_spawn(s,
1578 s->control_command,
1579 s->timeout_start_usec,
1580 false,
1581 !s->permissions_start_only,
1582 !s->root_directory_start_only,
1583 false,
1584 true,
1585 &s->control_pid);
1586 if (r < 0)
1587 goto fail;
1588
1589 service_set_state(s, SERVICE_START_POST);
1590 } else
1591 service_enter_running(s, SERVICE_SUCCESS);
1592
1593 return;
1594
1595 fail:
1596 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
1597 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1598 }
1599
1600 static void service_kill_control_processes(Service *s) {
1601 char *p;
1602
1603 if (!UNIT(s)->cgroup_path)
1604 return;
1605
1606 p = strjoina(UNIT(s)->cgroup_path, "/control");
1607 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1608 }
1609
1610 static void service_enter_start(Service *s) {
1611 ExecCommand *c;
1612 pid_t pid;
1613 int r;
1614
1615 assert(s);
1616
1617 service_unwatch_control_pid(s);
1618 service_unwatch_main_pid(s);
1619
1620 /* We want to ensure that nobody leaks processes from
1621 * START_PRE here, so let's go on a killing spree, People
1622 * should not spawn long running processes from START_PRE. */
1623 service_kill_control_processes(s);
1624
1625 if (s->type == SERVICE_FORKING) {
1626 s->control_command_id = SERVICE_EXEC_START;
1627 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1628
1629 s->main_command = NULL;
1630 } else {
1631 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1632 s->control_command = NULL;
1633
1634 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1635 }
1636
1637 if (!c) {
1638 assert(s->type == SERVICE_ONESHOT);
1639 service_enter_start_post(s);
1640 return;
1641 }
1642
1643 r = service_spawn(s,
1644 c,
1645 IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_ONESHOT) ? s->timeout_start_usec : 0,
1646 true,
1647 true,
1648 true,
1649 true,
1650 false,
1651 &pid);
1652 if (r < 0)
1653 goto fail;
1654
1655 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
1656 /* For simple services we immediately start
1657 * the START_POST binaries. */
1658
1659 service_set_main_pid(s, pid);
1660 service_enter_start_post(s);
1661
1662 } else if (s->type == SERVICE_FORKING) {
1663
1664 /* For forking services we wait until the start
1665 * process exited. */
1666
1667 s->control_pid = pid;
1668 service_set_state(s, SERVICE_START);
1669
1670 } else if (s->type == SERVICE_ONESHOT ||
1671 s->type == SERVICE_DBUS ||
1672 s->type == SERVICE_NOTIFY) {
1673
1674 /* For oneshot services we wait until the start
1675 * process exited, too, but it is our main process. */
1676
1677 /* For D-Bus services we know the main pid right away,
1678 * but wait for the bus name to appear on the
1679 * bus. Notify services are similar. */
1680
1681 service_set_main_pid(s, pid);
1682 service_set_state(s, SERVICE_START);
1683 } else
1684 assert_not_reached("Unknown service type");
1685
1686 return;
1687
1688 fail:
1689 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start' task: %m");
1690 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1691 }
1692
1693 static void service_enter_start_pre(Service *s) {
1694 int r;
1695
1696 assert(s);
1697
1698 service_unwatch_control_pid(s);
1699
1700 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1701 if (s->control_command) {
1702 /* Before we start anything, let's clear up what might
1703 * be left from previous runs. */
1704 service_kill_control_processes(s);
1705
1706 s->control_command_id = SERVICE_EXEC_START_PRE;
1707
1708 r = service_spawn(s,
1709 s->control_command,
1710 s->timeout_start_usec,
1711 false,
1712 !s->permissions_start_only,
1713 !s->root_directory_start_only,
1714 true,
1715 true,
1716 &s->control_pid);
1717 if (r < 0)
1718 goto fail;
1719
1720 service_set_state(s, SERVICE_START_PRE);
1721 } else
1722 service_enter_start(s);
1723
1724 return;
1725
1726 fail:
1727 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
1728 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1729 }
1730
1731 static void service_enter_restart(Service *s) {
1732 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1733 int r;
1734
1735 assert(s);
1736
1737 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1738 /* Don't restart things if we are going down anyway */
1739 log_unit_info(UNIT(s), "Stop job pending for unit, delaying automatic restart.");
1740
1741 r = service_arm_timer(s, s->restart_usec);
1742 if (r < 0)
1743 goto fail;
1744
1745 return;
1746 }
1747
1748 /* Any units that are bound to this service must also be
1749 * restarted. We use JOB_RESTART (instead of the more obvious
1750 * JOB_START) here so that those dependency jobs will be added
1751 * as well. */
1752 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
1753 if (r < 0)
1754 goto fail;
1755
1756 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1757 * it will be canceled as part of the service_stop() call that
1758 * is executed as part of JOB_RESTART. */
1759
1760 log_unit_debug(UNIT(s), "Scheduled restart job.");
1761 return;
1762
1763 fail:
1764 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, -r));
1765 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1766 }
1767
1768 static void service_enter_reload_by_notify(Service *s) {
1769 assert(s);
1770
1771 if (s->timeout_start_usec > 0)
1772 service_arm_timer(s, s->timeout_start_usec);
1773
1774 service_set_state(s, SERVICE_RELOAD);
1775 }
1776
1777 static void service_enter_reload(Service *s) {
1778 int r;
1779
1780 assert(s);
1781
1782 service_unwatch_control_pid(s);
1783
1784 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1785 if (s->control_command) {
1786 s->control_command_id = SERVICE_EXEC_RELOAD;
1787
1788 r = service_spawn(s,
1789 s->control_command,
1790 s->timeout_start_usec,
1791 false,
1792 !s->permissions_start_only,
1793 !s->root_directory_start_only,
1794 false,
1795 true,
1796 &s->control_pid);
1797 if (r < 0)
1798 goto fail;
1799
1800 service_set_state(s, SERVICE_RELOAD);
1801 } else
1802 service_enter_running(s, SERVICE_SUCCESS);
1803
1804 return;
1805
1806 fail:
1807 log_unit_warning_errno(UNIT(s), r, "Failed to run 'reload' task: %m");
1808 s->reload_result = SERVICE_FAILURE_RESOURCES;
1809 service_enter_running(s, SERVICE_SUCCESS);
1810 }
1811
1812 static void service_run_next_control(Service *s) {
1813 int r;
1814
1815 assert(s);
1816 assert(s->control_command);
1817 assert(s->control_command->command_next);
1818
1819 assert(s->control_command_id != SERVICE_EXEC_START);
1820
1821 s->control_command = s->control_command->command_next;
1822 service_unwatch_control_pid(s);
1823
1824 r = service_spawn(s,
1825 s->control_command,
1826 IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD) ? s->timeout_start_usec : s->timeout_stop_usec,
1827 false,
1828 !s->permissions_start_only,
1829 !s->root_directory_start_only,
1830 s->control_command_id == SERVICE_EXEC_START_PRE ||
1831 s->control_command_id == SERVICE_EXEC_STOP_POST,
1832 true,
1833 &s->control_pid);
1834 if (r < 0)
1835 goto fail;
1836
1837 return;
1838
1839 fail:
1840 log_unit_warning_errno(UNIT(s), r, "Failed to run next control task: %m");
1841
1842 if (s->state == SERVICE_START_PRE)
1843 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1844 else if (s->state == SERVICE_STOP)
1845 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1846 else if (s->state == SERVICE_STOP_POST)
1847 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1848 else if (s->state == SERVICE_RELOAD) {
1849 s->reload_result = SERVICE_FAILURE_RESOURCES;
1850 service_enter_running(s, SERVICE_SUCCESS);
1851 } else
1852 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1853 }
1854
1855 static void service_run_next_main(Service *s) {
1856 pid_t pid;
1857 int r;
1858
1859 assert(s);
1860 assert(s->main_command);
1861 assert(s->main_command->command_next);
1862 assert(s->type == SERVICE_ONESHOT);
1863
1864 s->main_command = s->main_command->command_next;
1865 service_unwatch_main_pid(s);
1866
1867 r = service_spawn(s,
1868 s->main_command,
1869 s->timeout_start_usec,
1870 true,
1871 true,
1872 true,
1873 true,
1874 false,
1875 &pid);
1876 if (r < 0)
1877 goto fail;
1878
1879 service_set_main_pid(s, pid);
1880
1881 return;
1882
1883 fail:
1884 log_unit_warning_errno(UNIT(s), r, "Failed to run next main task: %m");
1885 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1886 }
1887
1888 static int service_start_limit_test(Service *s) {
1889 assert(s);
1890
1891 if (ratelimit_test(&s->start_limit))
1892 return 0;
1893
1894 log_unit_warning(UNIT(s), "Start request repeated too quickly.");
1895
1896 return failure_action(UNIT(s)->manager, s->start_limit_action, s->reboot_arg);
1897 }
1898
1899 static int service_start(Unit *u) {
1900 Service *s = SERVICE(u);
1901 int r;
1902
1903 assert(s);
1904
1905 /* We cannot fulfill this request right now, try again later
1906 * please! */
1907 if (IN_SET(s->state,
1908 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1909 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
1910 return -EAGAIN;
1911
1912 /* Already on it! */
1913 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
1914 return 0;
1915
1916 /* A service that will be restarted must be stopped first to
1917 * trigger BindsTo and/or OnFailure dependencies. If a user
1918 * does not want to wait for the holdoff time to elapse, the
1919 * service should be manually restarted, not started. We
1920 * simply return EAGAIN here, so that any start jobs stay
1921 * queued, and assume that the auto restart timer will
1922 * eventually trigger the restart. */
1923 if (s->state == SERVICE_AUTO_RESTART)
1924 return -EAGAIN;
1925
1926 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED));
1927
1928 /* Make sure we don't enter a busy loop of some kind. */
1929 r = service_start_limit_test(s);
1930 if (r < 0) {
1931 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
1932 return r;
1933 }
1934
1935 s->result = SERVICE_SUCCESS;
1936 s->reload_result = SERVICE_SUCCESS;
1937 s->main_pid_known = false;
1938 s->main_pid_alien = false;
1939 s->forbid_restart = false;
1940 s->reset_cpu_usage = true;
1941
1942 free(s->status_text);
1943 s->status_text = NULL;
1944 s->status_errno = 0;
1945
1946 s->notify_state = NOTIFY_UNKNOWN;
1947
1948 service_enter_start_pre(s);
1949 return 1;
1950 }
1951
1952 static int service_stop(Unit *u) {
1953 Service *s = SERVICE(u);
1954
1955 assert(s);
1956
1957 /* Don't create restart jobs from manual stops. */
1958 s->forbid_restart = true;
1959
1960 /* Already on it */
1961 if (IN_SET(s->state,
1962 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1963 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
1964 return 0;
1965
1966 /* A restart will be scheduled or is in progress. */
1967 if (s->state == SERVICE_AUTO_RESTART) {
1968 service_set_state(s, SERVICE_DEAD);
1969 return 0;
1970 }
1971
1972 /* If there's already something running we go directly into
1973 * kill mode. */
1974 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD)) {
1975 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1976 return 0;
1977 }
1978
1979 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
1980
1981 service_enter_stop(s, SERVICE_SUCCESS);
1982 return 1;
1983 }
1984
1985 static int service_reload(Unit *u) {
1986 Service *s = SERVICE(u);
1987
1988 assert(s);
1989
1990 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
1991
1992 service_enter_reload(s);
1993 return 1;
1994 }
1995
1996 _pure_ static bool service_can_reload(Unit *u) {
1997 Service *s = SERVICE(u);
1998
1999 assert(s);
2000
2001 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2002 }
2003
2004 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2005 Service *s = SERVICE(u);
2006 ServiceFDStore *fs;
2007
2008 assert(u);
2009 assert(f);
2010 assert(fds);
2011
2012 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2013 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2014 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2015
2016 if (s->control_pid > 0)
2017 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
2018
2019 if (s->main_pid_known && s->main_pid > 0)
2020 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
2021
2022 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2023 unit_serialize_item(u, f, "bus-name-good", yes_no(s->bus_name_good));
2024
2025 if (s->status_text) {
2026 _cleanup_free_ char *c = NULL;
2027
2028 c = cescape(s->status_text);
2029 unit_serialize_item(u, f, "status-text", strempty(c));
2030 }
2031
2032 /* FIXME: There's a minor uncleanliness here: if there are
2033 * multiple commands attached here, we will start from the
2034 * first one again */
2035 if (s->control_command_id >= 0)
2036 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2037
2038 if (s->socket_fd >= 0) {
2039 int copy;
2040
2041 copy = fdset_put_dup(fds, s->socket_fd);
2042 if (copy < 0)
2043 return copy;
2044
2045 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2046 }
2047
2048 if (s->bus_endpoint_fd >= 0) {
2049 int copy;
2050
2051 copy = fdset_put_dup(fds, s->bus_endpoint_fd);
2052 if (copy < 0)
2053 return copy;
2054
2055 unit_serialize_item_format(u, f, "endpoint-fd", "%i", copy);
2056 }
2057
2058 LIST_FOREACH(fd_store, fs, s->fd_store) {
2059 int copy;
2060
2061 copy = fdset_put_dup(fds, fs->fd);
2062 if (copy < 0)
2063 return copy;
2064
2065 unit_serialize_item_format(u, f, "fd-store-fd", "%i", copy);
2066 }
2067
2068 if (s->main_exec_status.pid > 0) {
2069 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
2070 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2071 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2072
2073 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2074 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2075 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2076 }
2077 }
2078
2079 if (dual_timestamp_is_set(&s->watchdog_timestamp))
2080 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2081
2082 if (s->forbid_restart)
2083 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
2084
2085 return 0;
2086 }
2087
2088 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2089 Service *s = SERVICE(u);
2090 int r;
2091
2092 assert(u);
2093 assert(key);
2094 assert(value);
2095 assert(fds);
2096
2097 if (streq(key, "state")) {
2098 ServiceState state;
2099
2100 state = service_state_from_string(value);
2101 if (state < 0)
2102 log_unit_debug(u, "Failed to parse state value: %s", value);
2103 else
2104 s->deserialized_state = state;
2105 } else if (streq(key, "result")) {
2106 ServiceResult f;
2107
2108 f = service_result_from_string(value);
2109 if (f < 0)
2110 log_unit_debug(u, "Failed to parse result value: %s", value);
2111 else if (f != SERVICE_SUCCESS)
2112 s->result = f;
2113
2114 } else if (streq(key, "reload-result")) {
2115 ServiceResult f;
2116
2117 f = service_result_from_string(value);
2118 if (f < 0)
2119 log_unit_debug(u, "Failed to parse reload result value: %s", value);
2120 else if (f != SERVICE_SUCCESS)
2121 s->reload_result = f;
2122
2123 } else if (streq(key, "control-pid")) {
2124 pid_t pid;
2125
2126 if (parse_pid(value, &pid) < 0)
2127 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
2128 else
2129 s->control_pid = pid;
2130 } else if (streq(key, "main-pid")) {
2131 pid_t pid;
2132
2133 if (parse_pid(value, &pid) < 0)
2134 log_unit_debug(u, "Failed to parse main-pid value: %s", value);
2135 else {
2136 service_set_main_pid(s, pid);
2137 unit_watch_pid(UNIT(s), pid);
2138 }
2139 } else if (streq(key, "main-pid-known")) {
2140 int b;
2141
2142 b = parse_boolean(value);
2143 if (b < 0)
2144 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
2145 else
2146 s->main_pid_known = b;
2147 } else if (streq(key, "bus-name-good")) {
2148 int b;
2149
2150 b = parse_boolean(value);
2151 if (b < 0)
2152 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
2153 else
2154 s->bus_name_good = b;
2155 } else if (streq(key, "status-text")) {
2156 char *t;
2157
2158 r = cunescape(value, 0, &t);
2159 if (r < 0)
2160 log_unit_debug_errno(u, r, "Failed to unescape status text: %s", value);
2161 else {
2162 free(s->status_text);
2163 s->status_text = t;
2164 }
2165
2166 } else if (streq(key, "control-command")) {
2167 ServiceExecCommand id;
2168
2169 id = service_exec_command_from_string(value);
2170 if (id < 0)
2171 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
2172 else {
2173 s->control_command_id = id;
2174 s->control_command = s->exec_command[id];
2175 }
2176 } else if (streq(key, "socket-fd")) {
2177 int fd;
2178
2179 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2180 log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
2181 else {
2182 asynchronous_close(s->socket_fd);
2183 s->socket_fd = fdset_remove(fds, fd);
2184 }
2185 } else if (streq(key, "endpoint-fd")) {
2186 int fd;
2187
2188 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2189 log_unit_debug(u, "Failed to parse endpoint-fd value: %s", value);
2190 else {
2191 safe_close(s->bus_endpoint_fd);
2192 s->bus_endpoint_fd = fdset_remove(fds, fd);
2193 }
2194 } else if (streq(key, "fd-store-fd")) {
2195 int fd;
2196
2197 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2198 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
2199 else {
2200 r = service_add_fd_store(s, fd);
2201 if (r < 0)
2202 log_unit_error_errno(u, r, "Failed to add fd to store: %m");
2203 else if (r > 0)
2204 fdset_remove(fds, fd);
2205 }
2206
2207 } else if (streq(key, "main-exec-status-pid")) {
2208 pid_t pid;
2209
2210 if (parse_pid(value, &pid) < 0)
2211 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
2212 else
2213 s->main_exec_status.pid = pid;
2214 } else if (streq(key, "main-exec-status-code")) {
2215 int i;
2216
2217 if (safe_atoi(value, &i) < 0)
2218 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
2219 else
2220 s->main_exec_status.code = i;
2221 } else if (streq(key, "main-exec-status-status")) {
2222 int i;
2223
2224 if (safe_atoi(value, &i) < 0)
2225 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
2226 else
2227 s->main_exec_status.status = i;
2228 } else if (streq(key, "main-exec-status-start"))
2229 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2230 else if (streq(key, "main-exec-status-exit"))
2231 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2232 else if (streq(key, "watchdog-timestamp"))
2233 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2234 else if (streq(key, "forbid-restart")) {
2235 int b;
2236
2237 b = parse_boolean(value);
2238 if (b < 0)
2239 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
2240 else
2241 s->forbid_restart = b;
2242 } else
2243 log_unit_debug(u, "Unknown serialization key: %s", key);
2244
2245 return 0;
2246 }
2247
2248 _pure_ static UnitActiveState service_active_state(Unit *u) {
2249 const UnitActiveState *table;
2250
2251 assert(u);
2252
2253 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2254
2255 return table[SERVICE(u)->state];
2256 }
2257
2258 static const char *service_sub_state_to_string(Unit *u) {
2259 assert(u);
2260
2261 return service_state_to_string(SERVICE(u)->state);
2262 }
2263
2264 static bool service_check_gc(Unit *u) {
2265 Service *s = SERVICE(u);
2266
2267 assert(s);
2268
2269 /* Never clean up services that still have a process around,
2270 * even if the service is formally dead. */
2271 if (cgroup_good(s) > 0 ||
2272 main_pid_good(s) > 0 ||
2273 control_pid_good(s) > 0)
2274 return true;
2275
2276 return false;
2277 }
2278
2279 _pure_ static bool service_check_snapshot(Unit *u) {
2280 Service *s = SERVICE(u);
2281
2282 assert(s);
2283
2284 return s->socket_fd < 0;
2285 }
2286
2287 static int service_retry_pid_file(Service *s) {
2288 int r;
2289
2290 assert(s->pid_file);
2291 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2292
2293 r = service_load_pid_file(s, false);
2294 if (r < 0)
2295 return r;
2296
2297 service_unwatch_pid_file(s);
2298
2299 service_enter_running(s, SERVICE_SUCCESS);
2300 return 0;
2301 }
2302
2303 static int service_watch_pid_file(Service *s) {
2304 int r;
2305
2306 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
2307
2308 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2309 if (r < 0)
2310 goto fail;
2311
2312 /* the pidfile might have appeared just before we set the watch */
2313 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
2314 service_retry_pid_file(s);
2315
2316 return 0;
2317 fail:
2318 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
2319 service_unwatch_pid_file(s);
2320 return r;
2321 }
2322
2323 static int service_demand_pid_file(Service *s) {
2324 PathSpec *ps;
2325
2326 assert(s->pid_file);
2327 assert(!s->pid_file_pathspec);
2328
2329 ps = new0(PathSpec, 1);
2330 if (!ps)
2331 return -ENOMEM;
2332
2333 ps->unit = UNIT(s);
2334 ps->path = strdup(s->pid_file);
2335 if (!ps->path) {
2336 free(ps);
2337 return -ENOMEM;
2338 }
2339
2340 path_kill_slashes(ps->path);
2341
2342 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2343 * keep their PID file open all the time. */
2344 ps->type = PATH_MODIFIED;
2345 ps->inotify_fd = -1;
2346
2347 s->pid_file_pathspec = ps;
2348
2349 return service_watch_pid_file(s);
2350 }
2351
2352 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2353 PathSpec *p = userdata;
2354 Service *s;
2355
2356 assert(p);
2357
2358 s = SERVICE(p->unit);
2359
2360 assert(s);
2361 assert(fd >= 0);
2362 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2363 assert(s->pid_file_pathspec);
2364 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2365
2366 log_unit_debug(UNIT(s), "inotify event");
2367
2368 if (path_spec_fd_event(p, events) < 0)
2369 goto fail;
2370
2371 if (service_retry_pid_file(s) == 0)
2372 return 0;
2373
2374 if (service_watch_pid_file(s) < 0)
2375 goto fail;
2376
2377 return 0;
2378
2379 fail:
2380 service_unwatch_pid_file(s);
2381 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2382 return 0;
2383 }
2384
2385 static void service_notify_cgroup_empty_event(Unit *u) {
2386 Service *s = SERVICE(u);
2387
2388 assert(u);
2389
2390 log_unit_debug(u, "cgroup is empty");
2391
2392 switch (s->state) {
2393
2394 /* Waiting for SIGCHLD is usually more interesting,
2395 * because it includes return codes/signals. Which is
2396 * why we ignore the cgroup events for most cases,
2397 * except when we don't know pid which to expect the
2398 * SIGCHLD for. */
2399
2400 case SERVICE_START:
2401 case SERVICE_START_POST:
2402 /* If we were hoping for the daemon to write its PID file,
2403 * we can give up now. */
2404 if (s->pid_file_pathspec) {
2405 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
2406
2407 service_unwatch_pid_file(s);
2408 if (s->state == SERVICE_START)
2409 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2410 else
2411 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2412 }
2413 break;
2414
2415 case SERVICE_RUNNING:
2416 /* service_enter_running() will figure out what to do */
2417 service_enter_running(s, SERVICE_SUCCESS);
2418 break;
2419
2420 case SERVICE_STOP_SIGABRT:
2421 case SERVICE_STOP_SIGTERM:
2422 case SERVICE_STOP_SIGKILL:
2423
2424 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2425 service_enter_stop_post(s, SERVICE_SUCCESS);
2426
2427 break;
2428
2429 case SERVICE_STOP_POST:
2430 case SERVICE_FINAL_SIGTERM:
2431 case SERVICE_FINAL_SIGKILL:
2432 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2433 service_enter_dead(s, SERVICE_SUCCESS, true);
2434
2435 break;
2436
2437 default:
2438 ;
2439 }
2440 }
2441
2442 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2443 Service *s = SERVICE(u);
2444 ServiceResult f;
2445
2446 assert(s);
2447 assert(pid >= 0);
2448
2449 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2450 is_clean_exit_lsb(code, status, &s->success_status))
2451 f = SERVICE_SUCCESS;
2452 else if (code == CLD_EXITED)
2453 f = SERVICE_FAILURE_EXIT_CODE;
2454 else if (code == CLD_KILLED)
2455 f = SERVICE_FAILURE_SIGNAL;
2456 else if (code == CLD_DUMPED)
2457 f = SERVICE_FAILURE_CORE_DUMP;
2458 else
2459 assert_not_reached("Unknown code");
2460
2461 if (s->main_pid == pid) {
2462 /* Forking services may occasionally move to a new PID.
2463 * As long as they update the PID file before exiting the old
2464 * PID, they're fine. */
2465 if (service_load_pid_file(s, false) == 0)
2466 return;
2467
2468 s->main_pid = 0;
2469 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2470
2471 if (s->main_command) {
2472 /* If this is not a forking service than the
2473 * main process got started and hence we copy
2474 * the exit status so that it is recorded both
2475 * as main and as control process exit
2476 * status */
2477
2478 s->main_command->exec_status = s->main_exec_status;
2479
2480 if (s->main_command->ignore)
2481 f = SERVICE_SUCCESS;
2482 } else if (s->exec_command[SERVICE_EXEC_START]) {
2483
2484 /* If this is a forked process, then we should
2485 * ignore the return value if this was
2486 * configured for the starter process */
2487
2488 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2489 f = SERVICE_SUCCESS;
2490 }
2491
2492 log_struct(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2493 LOG_UNIT_ID(u),
2494 LOG_UNIT_MESSAGE(u, "Main process exited, code=%s, status=%i/%s",
2495 sigchld_code_to_string(code), status,
2496 strna(code == CLD_EXITED
2497 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2498 : signal_to_string(status))),
2499 "EXIT_CODE=%s", sigchld_code_to_string(code),
2500 "EXIT_STATUS=%i", status,
2501 NULL);
2502
2503 if (f != SERVICE_SUCCESS)
2504 s->result = f;
2505
2506 if (s->main_command &&
2507 s->main_command->command_next &&
2508 f == SERVICE_SUCCESS) {
2509
2510 /* There is another command to *
2511 * execute, so let's do that. */
2512
2513 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
2514 service_run_next_main(s);
2515
2516 } else {
2517
2518 /* The service exited, so the service is officially
2519 * gone. */
2520 s->main_command = NULL;
2521
2522 switch (s->state) {
2523
2524 case SERVICE_START_POST:
2525 case SERVICE_RELOAD:
2526 case SERVICE_STOP:
2527 /* Need to wait until the operation is
2528 * done */
2529 break;
2530
2531 case SERVICE_START:
2532 if (s->type == SERVICE_ONESHOT) {
2533 /* This was our main goal, so let's go on */
2534 if (f == SERVICE_SUCCESS)
2535 service_enter_start_post(s);
2536 else
2537 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2538 break;
2539 }
2540
2541 /* Fall through */
2542
2543 case SERVICE_RUNNING:
2544 service_enter_running(s, f);
2545 break;
2546
2547 case SERVICE_STOP_SIGABRT:
2548 case SERVICE_STOP_SIGTERM:
2549 case SERVICE_STOP_SIGKILL:
2550
2551 if (!control_pid_good(s))
2552 service_enter_stop_post(s, f);
2553
2554 /* If there is still a control process, wait for that first */
2555 break;
2556
2557 case SERVICE_STOP_POST:
2558 case SERVICE_FINAL_SIGTERM:
2559 case SERVICE_FINAL_SIGKILL:
2560
2561 if (!control_pid_good(s))
2562 service_enter_dead(s, f, true);
2563 break;
2564
2565 default:
2566 assert_not_reached("Uh, main process died at wrong time.");
2567 }
2568 }
2569
2570 } else if (s->control_pid == pid) {
2571 s->control_pid = 0;
2572
2573 if (s->control_command) {
2574 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2575
2576 if (s->control_command->ignore)
2577 f = SERVICE_SUCCESS;
2578 }
2579
2580 log_unit_full(u, f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0,
2581 "Control process exited, code=%s status=%i",
2582 sigchld_code_to_string(code), status);
2583
2584 if (f != SERVICE_SUCCESS)
2585 s->result = f;
2586
2587 /* Immediately get rid of the cgroup, so that the
2588 * kernel doesn't delay the cgroup empty messages for
2589 * the service cgroup any longer than necessary */
2590 service_kill_control_processes(s);
2591
2592 if (s->control_command &&
2593 s->control_command->command_next &&
2594 f == SERVICE_SUCCESS) {
2595
2596 /* There is another command to *
2597 * execute, so let's do that. */
2598
2599 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
2600 service_run_next_control(s);
2601
2602 } else {
2603 /* No further commands for this step, so let's
2604 * figure out what to do next */
2605
2606 s->control_command = NULL;
2607 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2608
2609 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
2610
2611 switch (s->state) {
2612
2613 case SERVICE_START_PRE:
2614 if (f == SERVICE_SUCCESS)
2615 service_enter_start(s);
2616 else
2617 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2618 break;
2619
2620 case SERVICE_START:
2621 if (s->type != SERVICE_FORKING)
2622 /* Maybe spurious event due to a reload that changed the type? */
2623 break;
2624
2625 if (f != SERVICE_SUCCESS) {
2626 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2627 break;
2628 }
2629
2630 if (s->pid_file) {
2631 bool has_start_post;
2632 int r;
2633
2634 /* Let's try to load the pid file here if we can.
2635 * The PID file might actually be created by a START_POST
2636 * script. In that case don't worry if the loading fails. */
2637
2638 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2639 r = service_load_pid_file(s, !has_start_post);
2640 if (!has_start_post && r < 0) {
2641 r = service_demand_pid_file(s);
2642 if (r < 0 || !cgroup_good(s))
2643 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2644 break;
2645 }
2646 } else
2647 (void) service_search_main_pid(s);
2648
2649 service_enter_start_post(s);
2650 break;
2651
2652 case SERVICE_START_POST:
2653 if (f != SERVICE_SUCCESS) {
2654 service_enter_stop(s, f);
2655 break;
2656 }
2657
2658 if (s->pid_file) {
2659 int r;
2660
2661 r = service_load_pid_file(s, true);
2662 if (r < 0) {
2663 r = service_demand_pid_file(s);
2664 if (r < 0 || !cgroup_good(s))
2665 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2666 break;
2667 }
2668 } else
2669 (void) service_search_main_pid(s);
2670
2671 service_enter_running(s, SERVICE_SUCCESS);
2672 break;
2673
2674 case SERVICE_RELOAD:
2675 if (f == SERVICE_SUCCESS) {
2676 service_load_pid_file(s, true);
2677 (void) service_search_main_pid(s);
2678 }
2679
2680 s->reload_result = f;
2681 service_enter_running(s, SERVICE_SUCCESS);
2682 break;
2683
2684 case SERVICE_STOP:
2685 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2686 break;
2687
2688 case SERVICE_STOP_SIGABRT:
2689 case SERVICE_STOP_SIGTERM:
2690 case SERVICE_STOP_SIGKILL:
2691 if (main_pid_good(s) <= 0)
2692 service_enter_stop_post(s, f);
2693
2694 /* If there is still a service
2695 * process around, wait until
2696 * that one quit, too */
2697 break;
2698
2699 case SERVICE_STOP_POST:
2700 case SERVICE_FINAL_SIGTERM:
2701 case SERVICE_FINAL_SIGKILL:
2702 if (main_pid_good(s) <= 0)
2703 service_enter_dead(s, f, true);
2704 break;
2705
2706 default:
2707 assert_not_reached("Uh, control process died at wrong time.");
2708 }
2709 }
2710 }
2711
2712 /* Notify clients about changed exit status */
2713 unit_add_to_dbus_queue(u);
2714
2715 /* We got one SIGCHLD for the service, let's watch all
2716 * processes that are now running of the service, and watch
2717 * that. Among the PIDs we then watch will be children
2718 * reassigned to us, which hopefully allows us to identify
2719 * when all children are gone */
2720 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2721 unit_watch_all_pids(u);
2722
2723 /* If the PID set is empty now, then let's finish this off */
2724 if (set_isempty(u->pids))
2725 service_notify_cgroup_empty_event(u);
2726 }
2727
2728 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2729 Service *s = SERVICE(userdata);
2730
2731 assert(s);
2732 assert(source == s->timer_event_source);
2733
2734 switch (s->state) {
2735
2736 case SERVICE_START_PRE:
2737 case SERVICE_START:
2738 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", s->state == SERVICE_START ? "Start" : "Start-pre");
2739 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2740 break;
2741
2742 case SERVICE_START_POST:
2743 log_unit_warning(UNIT(s), "Start-post operation timed out. Stopping.");
2744 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2745 break;
2746
2747 case SERVICE_RELOAD:
2748 log_unit_warning(UNIT(s), "Reload operation timed out. Stopping.");
2749 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2750 service_enter_running(s, SERVICE_SUCCESS);
2751 break;
2752
2753 case SERVICE_STOP:
2754 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
2755 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2756 break;
2757
2758 case SERVICE_STOP_SIGABRT:
2759 log_unit_warning(UNIT(s), "State 'stop-sigabrt' timed out. Terminating.");
2760 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2761 break;
2762
2763 case SERVICE_STOP_SIGTERM:
2764 if (s->kill_context.send_sigkill) {
2765 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
2766 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2767 } else {
2768 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
2769 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2770 }
2771
2772 break;
2773
2774 case SERVICE_STOP_SIGKILL:
2775 /* Uh, we sent a SIGKILL and it is still not gone?
2776 * Must be something we cannot kill, so let's just be
2777 * weirded out and continue */
2778
2779 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
2780 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2781 break;
2782
2783 case SERVICE_STOP_POST:
2784 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
2785 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2786 break;
2787
2788 case SERVICE_FINAL_SIGTERM:
2789 if (s->kill_context.send_sigkill) {
2790 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Killing.");
2791 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2792 } else {
2793 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
2794 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2795 }
2796
2797 break;
2798
2799 case SERVICE_FINAL_SIGKILL:
2800 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
2801 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2802 break;
2803
2804 case SERVICE_AUTO_RESTART:
2805 log_unit_info(UNIT(s),
2806 s->restart_usec > 0 ?
2807 "Service hold-off time over, scheduling restart." :
2808 "Service has no hold-off time, scheduling restart.");
2809 service_enter_restart(s);
2810 break;
2811
2812 default:
2813 assert_not_reached("Timeout at wrong time.");
2814 }
2815
2816 return 0;
2817 }
2818
2819 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2820 Service *s = SERVICE(userdata);
2821 char t[FORMAT_TIMESPAN_MAX];
2822
2823 assert(s);
2824 assert(source == s->watchdog_event_source);
2825
2826 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
2827 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2828
2829 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
2830
2831 return 0;
2832 }
2833
2834 static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
2835 Service *s = SERVICE(u);
2836 _cleanup_free_ char *cc = NULL;
2837 bool notify_dbus = false;
2838 const char *e;
2839
2840 assert(u);
2841
2842 cc = strv_join(tags, ", ");
2843
2844 if (s->notify_access == NOTIFY_NONE) {
2845 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
2846 return;
2847 } else if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2848 if (s->main_pid != 0)
2849 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
2850 else
2851 log_unit_debug(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid);
2852 return;
2853 } else
2854 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", pid, isempty(cc) ? "n/a" : cc);
2855
2856 /* Interpret MAINPID= */
2857 e = strv_find_startswith(tags, "MAINPID=");
2858 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2859 if (parse_pid(e, &pid) < 0)
2860 log_unit_warning(u, "Failed to parse MAINPID= field in notification message: %s", e);
2861 else {
2862 service_set_main_pid(s, pid);
2863 unit_watch_pid(UNIT(s), pid);
2864 notify_dbus = true;
2865 }
2866 }
2867
2868 /* Interpret RELOADING= */
2869 if (strv_find(tags, "RELOADING=1")) {
2870
2871 s->notify_state = NOTIFY_RELOADING;
2872
2873 if (s->state == SERVICE_RUNNING)
2874 service_enter_reload_by_notify(s);
2875
2876 notify_dbus = true;
2877 }
2878
2879 /* Interpret READY= */
2880 if (strv_find(tags, "READY=1")) {
2881
2882 s->notify_state = NOTIFY_READY;
2883
2884 /* Type=notify services inform us about completed
2885 * initialization with READY=1 */
2886 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2887 service_enter_start_post(s);
2888
2889 /* Sending READY=1 while we are reloading informs us
2890 * that the reloading is complete */
2891 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2892 service_enter_running(s, SERVICE_SUCCESS);
2893
2894 notify_dbus = true;
2895 }
2896
2897 /* Interpret STOPPING= */
2898 if (strv_find(tags, "STOPPING=1")) {
2899
2900 s->notify_state = NOTIFY_STOPPING;
2901
2902 if (s->state == SERVICE_RUNNING)
2903 service_enter_stop_by_notify(s);
2904
2905 notify_dbus = true;
2906 }
2907
2908 /* Interpret STATUS= */
2909 e = strv_find_startswith(tags, "STATUS=");
2910 if (e) {
2911 _cleanup_free_ char *t = NULL;
2912
2913 if (!isempty(e)) {
2914 if (!utf8_is_valid(e))
2915 log_unit_warning(u, "Status message in notification message is not UTF-8 clean.");
2916 else {
2917 t = strdup(e);
2918 if (!t)
2919 log_oom();
2920 }
2921 }
2922
2923 if (!streq_ptr(s->status_text, t)) {
2924
2925 free(s->status_text);
2926 s->status_text = t;
2927 t = NULL;
2928
2929 notify_dbus = true;
2930 }
2931 }
2932
2933 /* Interpret ERRNO= */
2934 e = strv_find_startswith(tags, "ERRNO=");
2935 if (e) {
2936 int status_errno;
2937
2938 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
2939 log_unit_warning(u, "Failed to parse ERRNO= field in notification message: %s", e);
2940 else {
2941 if (s->status_errno != status_errno) {
2942 s->status_errno = status_errno;
2943 notify_dbus = true;
2944 }
2945 }
2946 }
2947
2948 /* Interpret WATCHDOG= */
2949 if (strv_find(tags, "WATCHDOG=1")) {
2950 service_reset_watchdog(s);
2951 }
2952
2953 /* Add the passed fds to the fd store */
2954 if (strv_find(tags, "FDSTORE=1")) {
2955 service_add_fd_store_set(s, fds);
2956 }
2957
2958 /* Notify clients about changed status or main pid */
2959 if (notify_dbus)
2960 unit_add_to_dbus_queue(u);
2961 }
2962
2963 static int service_get_timeout(Unit *u, uint64_t *timeout) {
2964 Service *s = SERVICE(u);
2965 int r;
2966
2967 if (!s->timer_event_source)
2968 return 0;
2969
2970 r = sd_event_source_get_time(s->timer_event_source, timeout);
2971 if (r < 0)
2972 return r;
2973
2974 return 1;
2975 }
2976
2977 static void service_bus_name_owner_change(
2978 Unit *u,
2979 const char *name,
2980 const char *old_owner,
2981 const char *new_owner) {
2982
2983 Service *s = SERVICE(u);
2984 int r;
2985
2986 assert(s);
2987 assert(name);
2988
2989 assert(streq(s->bus_name, name));
2990 assert(old_owner || new_owner);
2991
2992 if (old_owner && new_owner)
2993 log_unit_debug(u, "D-Bus name %s changed owner from %s to %s", name, old_owner, new_owner);
2994 else if (old_owner)
2995 log_unit_debug(u, "D-Bus name %s no longer registered by %s", name, old_owner);
2996 else
2997 log_unit_debug(u, "D-Bus name %s now registered by %s", name, new_owner);
2998
2999 s->bus_name_good = !!new_owner;
3000
3001 if (s->type == SERVICE_DBUS) {
3002
3003 /* service_enter_running() will figure out what to
3004 * do */
3005 if (s->state == SERVICE_RUNNING)
3006 service_enter_running(s, SERVICE_SUCCESS);
3007 else if (s->state == SERVICE_START && new_owner)
3008 service_enter_start_post(s);
3009
3010 } else if (new_owner &&
3011 s->main_pid <= 0 &&
3012 (s->state == SERVICE_START ||
3013 s->state == SERVICE_START_POST ||
3014 s->state == SERVICE_RUNNING ||
3015 s->state == SERVICE_RELOAD)) {
3016
3017 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
3018 pid_t pid;
3019
3020 /* Try to acquire PID from bus service */
3021
3022 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
3023 if (r >= 0)
3024 r = sd_bus_creds_get_pid(creds, &pid);
3025 if (r >= 0) {
3026 log_unit_debug(u, "D-Bus name %s is now owned by process %u", name, (unsigned) pid);
3027
3028 service_set_main_pid(s, pid);
3029 unit_watch_pid(UNIT(s), pid);
3030 }
3031 }
3032 }
3033
3034 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
3035 _cleanup_free_ char *peer = NULL;
3036 int r;
3037
3038 assert(s);
3039 assert(fd >= 0);
3040
3041 /* This is called by the socket code when instantiating a new
3042 * service for a stream socket and the socket needs to be
3043 * configured. */
3044
3045 if (UNIT(s)->load_state != UNIT_LOADED)
3046 return -EINVAL;
3047
3048 if (s->socket_fd >= 0)
3049 return -EBUSY;
3050
3051 if (s->state != SERVICE_DEAD)
3052 return -EAGAIN;
3053
3054 if (getpeername_pretty(fd, &peer) >= 0) {
3055
3056 if (UNIT(s)->description) {
3057 _cleanup_free_ char *a;
3058
3059 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
3060 if (!a)
3061 return -ENOMEM;
3062
3063 r = unit_set_description(UNIT(s), a);
3064 } else
3065 r = unit_set_description(UNIT(s), peer);
3066
3067 if (r < 0)
3068 return r;
3069 }
3070
3071 s->socket_fd = fd;
3072 s->socket_fd_selinux_context_net = selinux_context_net;
3073
3074 unit_ref_set(&s->accept_socket, UNIT(sock));
3075
3076 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3077 }
3078
3079 static void service_reset_failed(Unit *u) {
3080 Service *s = SERVICE(u);
3081
3082 assert(s);
3083
3084 if (s->state == SERVICE_FAILED)
3085 service_set_state(s, SERVICE_DEAD);
3086
3087 s->result = SERVICE_SUCCESS;
3088 s->reload_result = SERVICE_SUCCESS;
3089
3090 RATELIMIT_RESET(s->start_limit);
3091 }
3092
3093 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
3094 Service *s = SERVICE(u);
3095
3096 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3097 }
3098
3099 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3100 [SERVICE_DEAD] = "dead",
3101 [SERVICE_START_PRE] = "start-pre",
3102 [SERVICE_START] = "start",
3103 [SERVICE_START_POST] = "start-post",
3104 [SERVICE_RUNNING] = "running",
3105 [SERVICE_EXITED] = "exited",
3106 [SERVICE_RELOAD] = "reload",
3107 [SERVICE_STOP] = "stop",
3108 [SERVICE_STOP_SIGABRT] = "stop-sigabrt",
3109 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3110 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3111 [SERVICE_STOP_POST] = "stop-post",
3112 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3113 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
3114 [SERVICE_FAILED] = "failed",
3115 [SERVICE_AUTO_RESTART] = "auto-restart",
3116 };
3117
3118 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3119
3120 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3121 [SERVICE_RESTART_NO] = "no",
3122 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3123 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3124 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
3125 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3126 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3127 [SERVICE_RESTART_ALWAYS] = "always",
3128 };
3129
3130 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3131
3132 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3133 [SERVICE_SIMPLE] = "simple",
3134 [SERVICE_FORKING] = "forking",
3135 [SERVICE_ONESHOT] = "oneshot",
3136 [SERVICE_DBUS] = "dbus",
3137 [SERVICE_NOTIFY] = "notify",
3138 [SERVICE_IDLE] = "idle"
3139 };
3140
3141 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3142
3143 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3144 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3145 [SERVICE_EXEC_START] = "ExecStart",
3146 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3147 [SERVICE_EXEC_RELOAD] = "ExecReload",
3148 [SERVICE_EXEC_STOP] = "ExecStop",
3149 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3150 };
3151
3152 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3153
3154 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3155 [NOTIFY_NONE] = "none",
3156 [NOTIFY_MAIN] = "main",
3157 [NOTIFY_ALL] = "all"
3158 };
3159
3160 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3161
3162 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3163 [NOTIFY_UNKNOWN] = "unknown",
3164 [NOTIFY_READY] = "ready",
3165 [NOTIFY_RELOADING] = "reloading",
3166 [NOTIFY_STOPPING] = "stopping",
3167 };
3168
3169 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3170
3171 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3172 [SERVICE_SUCCESS] = "success",
3173 [SERVICE_FAILURE_RESOURCES] = "resources",
3174 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3175 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3176 [SERVICE_FAILURE_SIGNAL] = "signal",
3177 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3178 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3179 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
3180 };
3181
3182 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3183
3184 const UnitVTable service_vtable = {
3185 .object_size = sizeof(Service),
3186 .exec_context_offset = offsetof(Service, exec_context),
3187 .cgroup_context_offset = offsetof(Service, cgroup_context),
3188 .kill_context_offset = offsetof(Service, kill_context),
3189 .exec_runtime_offset = offsetof(Service, exec_runtime),
3190
3191 .sections =
3192 "Unit\0"
3193 "Service\0"
3194 "Install\0",
3195 .private_section = "Service",
3196
3197 .init = service_init,
3198 .done = service_done,
3199 .load = service_load,
3200 .release_resources = service_release_resources,
3201
3202 .coldplug = service_coldplug,
3203
3204 .dump = service_dump,
3205
3206 .start = service_start,
3207 .stop = service_stop,
3208 .reload = service_reload,
3209
3210 .can_reload = service_can_reload,
3211
3212 .kill = service_kill,
3213
3214 .serialize = service_serialize,
3215 .deserialize_item = service_deserialize_item,
3216
3217 .active_state = service_active_state,
3218 .sub_state_to_string = service_sub_state_to_string,
3219
3220 .check_gc = service_check_gc,
3221 .check_snapshot = service_check_snapshot,
3222
3223 .sigchld_event = service_sigchld_event,
3224
3225 .reset_failed = service_reset_failed,
3226
3227 .notify_cgroup_empty = service_notify_cgroup_empty_event,
3228 .notify_message = service_notify_message,
3229
3230 .bus_name_owner_change = service_bus_name_owner_change,
3231
3232 .bus_vtable = bus_service_vtable,
3233 .bus_set_property = bus_service_set_property,
3234 .bus_commit_properties = bus_service_commit_properties,
3235
3236 .get_timeout = service_get_timeout,
3237 .can_transient = true,
3238
3239 .status_message_formats = {
3240 .starting_stopping = {
3241 [0] = "Starting %s...",
3242 [1] = "Stopping %s...",
3243 },
3244 .finished_start_job = {
3245 [JOB_DONE] = "Started %s.",
3246 [JOB_FAILED] = "Failed to start %s.",
3247 },
3248 .finished_stop_job = {
3249 [JOB_DONE] = "Stopped %s.",
3250 [JOB_FAILED] = "Stopped (with error) %s.",
3251 },
3252 },
3253 };