]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/path.c
Merge pull request #9158 from poettering/notify-auto-reload
[thirdparty/systemd.git] / src / core / path.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <errno.h>
9 #include <sys/epoll.h>
10 #include <sys/inotify.h>
11 #include <unistd.h>
12
13 #include "bus-error.h"
14 #include "bus-util.h"
15 #include "dbus-path.h"
16 #include "fd-util.h"
17 #include "fs-util.h"
18 #include "glob-util.h"
19 #include "macro.h"
20 #include "mkdir.h"
21 #include "path.h"
22 #include "special.h"
23 #include "stat-util.h"
24 #include "string-table.h"
25 #include "string-util.h"
26 #include "unit-name.h"
27 #include "unit.h"
28
29 static const UnitActiveState state_translation_table[_PATH_STATE_MAX] = {
30 [PATH_DEAD] = UNIT_INACTIVE,
31 [PATH_WAITING] = UNIT_ACTIVE,
32 [PATH_RUNNING] = UNIT_ACTIVE,
33 [PATH_FAILED] = UNIT_FAILED
34 };
35
36 static int path_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
37
38 int path_spec_watch(PathSpec *s, sd_event_io_handler_t handler) {
39
40 static const int flags_table[_PATH_TYPE_MAX] = {
41 [PATH_EXISTS] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
42 [PATH_EXISTS_GLOB] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
43 [PATH_CHANGED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO,
44 [PATH_MODIFIED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO|IN_MODIFY,
45 [PATH_DIRECTORY_NOT_EMPTY] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO
46 };
47
48 bool exists = false;
49 char *slash, *oldslash = NULL;
50 int r;
51
52 assert(s);
53 assert(s->unit);
54 assert(handler);
55
56 path_spec_unwatch(s);
57
58 s->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
59 if (s->inotify_fd < 0) {
60 r = -errno;
61 goto fail;
62 }
63
64 r = sd_event_add_io(s->unit->manager->event, &s->event_source, s->inotify_fd, EPOLLIN, handler, s);
65 if (r < 0)
66 goto fail;
67
68 (void) sd_event_source_set_description(s->event_source, "path");
69
70 /* This function assumes the path was passed through path_simplify()! */
71 assert(!strstr(s->path, "//"));
72
73 for (slash = strchr(s->path, '/'); ; slash = strchr(slash+1, '/')) {
74 char *cut = NULL;
75 int flags;
76 char tmp;
77
78 if (slash) {
79 cut = slash + (slash == s->path);
80 tmp = *cut;
81 *cut = '\0';
82
83 flags = IN_MOVE_SELF | IN_DELETE_SELF | IN_ATTRIB | IN_CREATE | IN_MOVED_TO;
84 } else
85 flags = flags_table[s->type];
86
87 r = inotify_add_watch(s->inotify_fd, s->path, flags);
88 if (r < 0) {
89 if (IN_SET(errno, EACCES, ENOENT)) {
90 if (cut)
91 *cut = tmp;
92 break;
93 }
94
95 r = log_warning_errno(errno, "Failed to add watch on %s: %s", s->path, errno == ENOSPC ? "too many watches" : strerror(-r));
96 if (cut)
97 *cut = tmp;
98 goto fail;
99 } else {
100 exists = true;
101
102 /* Path exists, we don't need to watch parent too closely. */
103 if (oldslash) {
104 char *cut2 = oldslash + (oldslash == s->path);
105 char tmp2 = *cut2;
106 *cut2 = '\0';
107
108 (void) inotify_add_watch(s->inotify_fd, s->path, IN_MOVE_SELF);
109 /* Error is ignored, the worst can happen is we get spurious events. */
110
111 *cut2 = tmp2;
112 }
113 }
114
115 if (cut)
116 *cut = tmp;
117
118 if (slash)
119 oldslash = slash;
120 else {
121 /* whole path has been iterated over */
122 s->primary_wd = r;
123 break;
124 }
125 }
126
127 if (!exists) {
128 r = log_error_errno(errno, "Failed to add watch on any of the components of %s: %m", s->path);
129 /* either EACCESS or ENOENT */
130 goto fail;
131 }
132
133 return 0;
134
135 fail:
136 path_spec_unwatch(s);
137 return r;
138 }
139
140 void path_spec_unwatch(PathSpec *s) {
141 assert(s);
142
143 s->event_source = sd_event_source_unref(s->event_source);
144 s->inotify_fd = safe_close(s->inotify_fd);
145 }
146
147 int path_spec_fd_event(PathSpec *s, uint32_t revents) {
148 union inotify_event_buffer buffer;
149 struct inotify_event *e;
150 ssize_t l;
151 int r = 0;
152
153 if (revents != EPOLLIN) {
154 log_error("Got invalid poll event on inotify.");
155 return -EINVAL;
156 }
157
158 l = read(s->inotify_fd, &buffer, sizeof(buffer));
159 if (l < 0) {
160 if (IN_SET(errno, EAGAIN, EINTR))
161 return 0;
162
163 return log_error_errno(errno, "Failed to read inotify event: %m");
164 }
165
166 FOREACH_INOTIFY_EVENT(e, buffer, l) {
167 if (IN_SET(s->type, PATH_CHANGED, PATH_MODIFIED) &&
168 s->primary_wd == e->wd)
169 r = 1;
170 }
171
172 return r;
173 }
174
175 static bool path_spec_check_good(PathSpec *s, bool initial) {
176 bool good = false;
177
178 switch (s->type) {
179
180 case PATH_EXISTS:
181 good = access(s->path, F_OK) >= 0;
182 break;
183
184 case PATH_EXISTS_GLOB:
185 good = glob_exists(s->path) > 0;
186 break;
187
188 case PATH_DIRECTORY_NOT_EMPTY: {
189 int k;
190
191 k = dir_is_empty(s->path);
192 good = !(k == -ENOENT || k > 0);
193 break;
194 }
195
196 case PATH_CHANGED:
197 case PATH_MODIFIED: {
198 bool b;
199
200 b = access(s->path, F_OK) >= 0;
201 good = !initial && b != s->previous_exists;
202 s->previous_exists = b;
203 break;
204 }
205
206 default:
207 ;
208 }
209
210 return good;
211 }
212
213 static void path_spec_mkdir(PathSpec *s, mode_t mode) {
214 int r;
215
216 if (IN_SET(s->type, PATH_EXISTS, PATH_EXISTS_GLOB))
217 return;
218
219 r = mkdir_p_label(s->path, mode);
220 if (r < 0)
221 log_warning_errno(r, "mkdir(%s) failed: %m", s->path);
222 }
223
224 static void path_spec_dump(PathSpec *s, FILE *f, const char *prefix) {
225 fprintf(f,
226 "%s%s: %s\n",
227 prefix,
228 path_type_to_string(s->type),
229 s->path);
230 }
231
232 void path_spec_done(PathSpec *s) {
233 assert(s);
234 assert(s->inotify_fd == -1);
235
236 free(s->path);
237 }
238
239 static void path_init(Unit *u) {
240 Path *p = PATH(u);
241
242 assert(u);
243 assert(u->load_state == UNIT_STUB);
244
245 p->directory_mode = 0755;
246 }
247
248 void path_free_specs(Path *p) {
249 PathSpec *s;
250
251 assert(p);
252
253 while ((s = p->specs)) {
254 path_spec_unwatch(s);
255 LIST_REMOVE(spec, p->specs, s);
256 path_spec_done(s);
257 free(s);
258 }
259 }
260
261 static void path_done(Unit *u) {
262 Path *p = PATH(u);
263
264 assert(p);
265
266 path_free_specs(p);
267 }
268
269 static int path_add_mount_dependencies(Path *p) {
270 PathSpec *s;
271 int r;
272
273 assert(p);
274
275 LIST_FOREACH(spec, s, p->specs) {
276 r = unit_require_mounts_for(UNIT(p), s->path, UNIT_DEPENDENCY_FILE);
277 if (r < 0)
278 return r;
279 }
280
281 return 0;
282 }
283
284 static int path_verify(Path *p) {
285 assert(p);
286
287 if (UNIT(p)->load_state != UNIT_LOADED)
288 return 0;
289
290 if (!p->specs) {
291 log_unit_error(UNIT(p), "Path unit lacks path setting. Refusing.");
292 return -EINVAL;
293 }
294
295 return 0;
296 }
297
298 static int path_add_default_dependencies(Path *p) {
299 int r;
300
301 assert(p);
302
303 if (!UNIT(p)->default_dependencies)
304 return 0;
305
306 r = unit_add_dependency_by_name(UNIT(p), UNIT_BEFORE, SPECIAL_PATHS_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT);
307 if (r < 0)
308 return r;
309
310 if (MANAGER_IS_SYSTEM(UNIT(p)->manager)) {
311 r = unit_add_two_dependencies_by_name(UNIT(p), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT);
312 if (r < 0)
313 return r;
314 }
315
316 return unit_add_two_dependencies_by_name(UNIT(p), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT);
317 }
318
319 static int path_add_trigger_dependencies(Path *p) {
320 Unit *x;
321 int r;
322
323 assert(p);
324
325 if (!hashmap_isempty(UNIT(p)->dependencies[UNIT_TRIGGERS]))
326 return 0;
327
328 r = unit_load_related_unit(UNIT(p), ".service", &x);
329 if (r < 0)
330 return r;
331
332 return unit_add_two_dependencies(UNIT(p), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
333 }
334
335 static int path_load(Unit *u) {
336 Path *p = PATH(u);
337 int r;
338
339 assert(u);
340 assert(u->load_state == UNIT_STUB);
341
342 r = unit_load_fragment_and_dropin(u);
343 if (r < 0)
344 return r;
345
346 if (u->load_state == UNIT_LOADED) {
347
348 r = path_add_trigger_dependencies(p);
349 if (r < 0)
350 return r;
351
352 r = path_add_mount_dependencies(p);
353 if (r < 0)
354 return r;
355
356 r = path_add_default_dependencies(p);
357 if (r < 0)
358 return r;
359 }
360
361 return path_verify(p);
362 }
363
364 static void path_dump(Unit *u, FILE *f, const char *prefix) {
365 Path *p = PATH(u);
366 Unit *trigger;
367 PathSpec *s;
368
369 assert(p);
370 assert(f);
371
372 trigger = UNIT_TRIGGER(u);
373
374 fprintf(f,
375 "%sPath State: %s\n"
376 "%sResult: %s\n"
377 "%sUnit: %s\n"
378 "%sMakeDirectory: %s\n"
379 "%sDirectoryMode: %04o\n",
380 prefix, path_state_to_string(p->state),
381 prefix, path_result_to_string(p->result),
382 prefix, trigger ? trigger->id : "n/a",
383 prefix, yes_no(p->make_directory),
384 prefix, p->directory_mode);
385
386 LIST_FOREACH(spec, s, p->specs)
387 path_spec_dump(s, f, prefix);
388 }
389
390 static void path_unwatch(Path *p) {
391 PathSpec *s;
392
393 assert(p);
394
395 LIST_FOREACH(spec, s, p->specs)
396 path_spec_unwatch(s);
397 }
398
399 static int path_watch(Path *p) {
400 int r;
401 PathSpec *s;
402
403 assert(p);
404
405 LIST_FOREACH(spec, s, p->specs) {
406 r = path_spec_watch(s, path_dispatch_io);
407 if (r < 0)
408 return r;
409 }
410
411 return 0;
412 }
413
414 static void path_set_state(Path *p, PathState state) {
415 PathState old_state;
416 assert(p);
417
418 old_state = p->state;
419 p->state = state;
420
421 if (state != PATH_WAITING &&
422 (state != PATH_RUNNING || p->inotify_triggered))
423 path_unwatch(p);
424
425 if (state != old_state)
426 log_unit_debug(UNIT(p), "Changed %s -> %s", path_state_to_string(old_state), path_state_to_string(state));
427
428 unit_notify(UNIT(p), state_translation_table[old_state], state_translation_table[state], 0);
429 }
430
431 static void path_enter_waiting(Path *p, bool initial, bool recheck);
432
433 static int path_coldplug(Unit *u) {
434 Path *p = PATH(u);
435
436 assert(p);
437 assert(p->state == PATH_DEAD);
438
439 if (p->deserialized_state != p->state) {
440
441 if (IN_SET(p->deserialized_state, PATH_WAITING, PATH_RUNNING))
442 path_enter_waiting(p, true, true);
443 else
444 path_set_state(p, p->deserialized_state);
445 }
446
447 return 0;
448 }
449
450 static void path_enter_dead(Path *p, PathResult f) {
451 assert(p);
452
453 if (p->result == PATH_SUCCESS)
454 p->result = f;
455
456 if (p->result != PATH_SUCCESS)
457 log_unit_warning(UNIT(p), "Failed with result '%s'.", path_result_to_string(p->result));
458
459 path_set_state(p, p->result != PATH_SUCCESS ? PATH_FAILED : PATH_DEAD);
460 }
461
462 static void path_enter_running(Path *p) {
463 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
464 Unit *trigger;
465 int r;
466
467 assert(p);
468
469 /* Don't start job if we are supposed to go down */
470 if (unit_stop_pending(UNIT(p)))
471 return;
472
473 trigger = UNIT_TRIGGER(UNIT(p));
474 if (!trigger) {
475 log_unit_error(UNIT(p), "Unit to trigger vanished.");
476 path_enter_dead(p, PATH_FAILURE_RESOURCES);
477 return;
478 }
479
480 r = manager_add_job(UNIT(p)->manager, JOB_START, trigger, JOB_REPLACE, &error, NULL);
481 if (r < 0)
482 goto fail;
483
484 p->inotify_triggered = false;
485
486 r = path_watch(p);
487 if (r < 0)
488 goto fail;
489
490 path_set_state(p, PATH_RUNNING);
491 return;
492
493 fail:
494 log_unit_warning(UNIT(p), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
495 path_enter_dead(p, PATH_FAILURE_RESOURCES);
496 }
497
498 static bool path_check_good(Path *p, bool initial) {
499 PathSpec *s;
500 bool good = false;
501
502 assert(p);
503
504 LIST_FOREACH(spec, s, p->specs) {
505 good = path_spec_check_good(s, initial);
506
507 if (good)
508 break;
509 }
510
511 return good;
512 }
513
514 static void path_enter_waiting(Path *p, bool initial, bool recheck) {
515 int r;
516
517 if (recheck)
518 if (path_check_good(p, initial)) {
519 log_unit_debug(UNIT(p), "Got triggered.");
520 path_enter_running(p);
521 return;
522 }
523
524 r = path_watch(p);
525 if (r < 0)
526 goto fail;
527
528 /* Hmm, so now we have created inotify watches, but the file
529 * might have appeared/been removed by now, so we must
530 * recheck */
531
532 if (recheck)
533 if (path_check_good(p, false)) {
534 log_unit_debug(UNIT(p), "Got triggered.");
535 path_enter_running(p);
536 return;
537 }
538
539 path_set_state(p, PATH_WAITING);
540 return;
541
542 fail:
543 log_unit_warning_errno(UNIT(p), r, "Failed to enter waiting state: %m");
544 path_enter_dead(p, PATH_FAILURE_RESOURCES);
545 }
546
547 static void path_mkdir(Path *p) {
548 PathSpec *s;
549
550 assert(p);
551
552 if (!p->make_directory)
553 return;
554
555 LIST_FOREACH(spec, s, p->specs)
556 path_spec_mkdir(s, p->directory_mode);
557 }
558
559 static int path_start(Unit *u) {
560 Path *p = PATH(u);
561 Unit *trigger;
562 int r;
563
564 assert(p);
565 assert(IN_SET(p->state, PATH_DEAD, PATH_FAILED));
566
567 trigger = UNIT_TRIGGER(u);
568 if (!trigger || trigger->load_state != UNIT_LOADED) {
569 log_unit_error(u, "Refusing to start, unit to trigger not loaded.");
570 return -ENOENT;
571 }
572
573 r = unit_start_limit_test(u);
574 if (r < 0) {
575 path_enter_dead(p, PATH_FAILURE_START_LIMIT_HIT);
576 return r;
577 }
578
579 r = unit_acquire_invocation_id(u);
580 if (r < 0)
581 return r;
582
583 path_mkdir(p);
584
585 p->result = PATH_SUCCESS;
586 path_enter_waiting(p, true, true);
587
588 return 1;
589 }
590
591 static int path_stop(Unit *u) {
592 Path *p = PATH(u);
593
594 assert(p);
595 assert(IN_SET(p->state, PATH_WAITING, PATH_RUNNING));
596
597 path_enter_dead(p, PATH_SUCCESS);
598 return 1;
599 }
600
601 static int path_serialize(Unit *u, FILE *f, FDSet *fds) {
602 Path *p = PATH(u);
603
604 assert(u);
605 assert(f);
606 assert(fds);
607
608 unit_serialize_item(u, f, "state", path_state_to_string(p->state));
609 unit_serialize_item(u, f, "result", path_result_to_string(p->result));
610
611 return 0;
612 }
613
614 static int path_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
615 Path *p = PATH(u);
616
617 assert(u);
618 assert(key);
619 assert(value);
620 assert(fds);
621
622 if (streq(key, "state")) {
623 PathState state;
624
625 state = path_state_from_string(value);
626 if (state < 0)
627 log_unit_debug(u, "Failed to parse state value: %s", value);
628 else
629 p->deserialized_state = state;
630
631 } else if (streq(key, "result")) {
632 PathResult f;
633
634 f = path_result_from_string(value);
635 if (f < 0)
636 log_unit_debug(u, "Failed to parse result value: %s", value);
637 else if (f != PATH_SUCCESS)
638 p->result = f;
639
640 } else
641 log_unit_debug(u, "Unknown serialization key: %s", key);
642
643 return 0;
644 }
645
646 _pure_ static UnitActiveState path_active_state(Unit *u) {
647 assert(u);
648
649 return state_translation_table[PATH(u)->state];
650 }
651
652 _pure_ static const char *path_sub_state_to_string(Unit *u) {
653 assert(u);
654
655 return path_state_to_string(PATH(u)->state);
656 }
657
658 static int path_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
659 PathSpec *s = userdata;
660 Path *p;
661 int changed;
662
663 assert(s);
664 assert(s->unit);
665 assert(fd >= 0);
666
667 p = PATH(s->unit);
668
669 if (!IN_SET(p->state, PATH_WAITING, PATH_RUNNING))
670 return 0;
671
672 /* log_debug("inotify wakeup on %s.", u->id); */
673
674 LIST_FOREACH(spec, s, p->specs)
675 if (path_spec_owns_inotify_fd(s, fd))
676 break;
677
678 if (!s) {
679 log_error("Got event on unknown fd.");
680 goto fail;
681 }
682
683 changed = path_spec_fd_event(s, revents);
684 if (changed < 0)
685 goto fail;
686
687 /* If we are already running, then remember that one event was
688 * dispatched so that we restart the service only if something
689 * actually changed on disk */
690 p->inotify_triggered = true;
691
692 if (changed)
693 path_enter_running(p);
694 else
695 path_enter_waiting(p, false, true);
696
697 return 0;
698
699 fail:
700 path_enter_dead(p, PATH_FAILURE_RESOURCES);
701 return 0;
702 }
703
704 static void path_trigger_notify(Unit *u, Unit *other) {
705 Path *p = PATH(u);
706
707 assert(u);
708 assert(other);
709
710 /* Invoked whenever the unit we trigger changes state or gains
711 * or loses a job */
712
713 if (other->load_state != UNIT_LOADED)
714 return;
715
716 if (p->state == PATH_RUNNING &&
717 UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
718 log_unit_debug(UNIT(p), "Got notified about unit deactivation.");
719
720 /* Hmm, so inotify was triggered since the
721 * last activation, so I guess we need to
722 * recheck what is going on. */
723 path_enter_waiting(p, false, p->inotify_triggered);
724 }
725 }
726
727 static void path_reset_failed(Unit *u) {
728 Path *p = PATH(u);
729
730 assert(p);
731
732 if (p->state == PATH_FAILED)
733 path_set_state(p, PATH_DEAD);
734
735 p->result = PATH_SUCCESS;
736 }
737
738 static const char* const path_type_table[_PATH_TYPE_MAX] = {
739 [PATH_EXISTS] = "PathExists",
740 [PATH_EXISTS_GLOB] = "PathExistsGlob",
741 [PATH_DIRECTORY_NOT_EMPTY] = "DirectoryNotEmpty",
742 [PATH_CHANGED] = "PathChanged",
743 [PATH_MODIFIED] = "PathModified",
744 };
745
746 DEFINE_STRING_TABLE_LOOKUP(path_type, PathType);
747
748 static const char* const path_result_table[_PATH_RESULT_MAX] = {
749 [PATH_SUCCESS] = "success",
750 [PATH_FAILURE_RESOURCES] = "resources",
751 [PATH_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
752 };
753
754 DEFINE_STRING_TABLE_LOOKUP(path_result, PathResult);
755
756 const UnitVTable path_vtable = {
757 .object_size = sizeof(Path),
758
759 .sections =
760 "Unit\0"
761 "Path\0"
762 "Install\0",
763 .private_section = "Path",
764
765 .can_transient = true,
766
767 .init = path_init,
768 .done = path_done,
769 .load = path_load,
770
771 .coldplug = path_coldplug,
772
773 .dump = path_dump,
774
775 .start = path_start,
776 .stop = path_stop,
777
778 .serialize = path_serialize,
779 .deserialize_item = path_deserialize_item,
780
781 .active_state = path_active_state,
782 .sub_state_to_string = path_sub_state_to_string,
783
784 .trigger_notify = path_trigger_notify,
785
786 .reset_failed = path_reset_failed,
787
788 .bus_vtable = bus_path_vtable,
789 .bus_set_property = bus_path_set_property,
790 };