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