chiark / gitweb /
service: stop the service if ExecStartPost ends with a failure
[elogind.git] / src / path.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 General Public License as published by
10   the Free Software Foundation; either version 2 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   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/inotify.h>
23 #include <sys/epoll.h>
24 #include <sys/ioctl.h>
25 #include <errno.h>
26 #include <unistd.h>
27
28 #include "unit.h"
29 #include "unit-name.h"
30 #include "path.h"
31 #include "dbus-path.h"
32 #include "special.h"
33 #include "bus-errors.h"
34
35 static const UnitActiveState state_translation_table[_PATH_STATE_MAX] = {
36         [PATH_DEAD] = UNIT_INACTIVE,
37         [PATH_WAITING] = UNIT_ACTIVE,
38         [PATH_RUNNING] = UNIT_ACTIVE,
39         [PATH_FAILED] = UNIT_FAILED
40 };
41
42 int pathspec_watch(PathSpec *s, Unit *u) {
43         static const int flags_table[_PATH_TYPE_MAX] = {
44                 [PATH_EXISTS] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
45                 [PATH_EXISTS_GLOB] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
46                 [PATH_CHANGED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO,
47                 [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,
48                 [PATH_DIRECTORY_NOT_EMPTY] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO
49         };
50
51         bool exists = false;
52         char *k, *slash;
53         int r;
54
55         assert(u);
56         assert(s);
57
58         pathspec_unwatch(s, u);
59
60         if (!(k = strdup(s->path)))
61                 return -ENOMEM;
62
63         if ((s->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC)) < 0) {
64                 r = -errno;
65                 goto fail;
66         }
67
68         if (unit_watch_fd(u, s->inotify_fd, EPOLLIN, &s->watch) < 0) {
69                 r = -errno;
70                 goto fail;
71         }
72
73         if ((s->primary_wd = inotify_add_watch(s->inotify_fd, k, flags_table[s->type])) >= 0)
74                 exists = true;
75
76         do {
77                 int flags;
78
79                 /* This assumes the path was passed through path_kill_slashes()! */
80                 if (!(slash = strrchr(k, '/')))
81                         break;
82
83                 /* Trim the path at the last slash. Keep the slash if it's the root dir. */
84                 slash[slash == k] = 0;
85
86                 flags = IN_MOVE_SELF;
87                 if (!exists)
88                         flags |= IN_DELETE_SELF | IN_ATTRIB | IN_CREATE | IN_MOVED_TO;
89
90                 if (inotify_add_watch(s->inotify_fd, k, flags) >= 0)
91                         exists = true;
92         } while (slash != k);
93
94         return 0;
95
96 fail:
97         free(k);
98
99         pathspec_unwatch(s, u);
100         return r;
101 }
102
103 void pathspec_unwatch(PathSpec *s, Unit *u) {
104
105         if (s->inotify_fd < 0)
106                 return;
107
108         unit_unwatch_fd(u, &s->watch);
109
110         close_nointr_nofail(s->inotify_fd);
111         s->inotify_fd = -1;
112 }
113
114 int pathspec_fd_event(PathSpec *s, uint32_t events) {
115         uint8_t *buf = NULL;
116         struct inotify_event *e;
117         ssize_t k;
118         int l;
119         int r = 0;
120
121         if (events != EPOLLIN) {
122                 log_error("Got Invalid poll event on inotify.");
123                 r = -EINVAL;
124                 goto out;
125         }
126
127         if (ioctl(s->inotify_fd, FIONREAD, &l) < 0) {
128                 log_error("FIONREAD failed: %m");
129                 r = -errno;
130                 goto out;
131         }
132
133         assert(l > 0);
134
135         if (!(buf = malloc(l))) {
136                 log_error("Failed to allocate buffer: %m");
137                 r = -errno;
138                 goto out;
139         }
140
141         if ((k = read(s->inotify_fd, buf, l)) < 0) {
142                 log_error("Failed to read inotify event: %m");
143                 r = -errno;
144                 goto out;
145         }
146
147         e = (struct inotify_event*) buf;
148
149         while (k > 0) {
150                 size_t step;
151
152                 if (s->type == PATH_CHANGED && s->primary_wd == e->wd)
153                         r = 1;
154
155                 step = sizeof(struct inotify_event) + e->len;
156                 assert(step <= (size_t) k);
157
158                 e = (struct inotify_event*) ((uint8_t*) e + step);
159                 k -= step;
160         }
161 out:
162         free(buf);
163         return r;
164 }
165
166 static bool pathspec_check_good(PathSpec *s, bool initial) {
167         bool good = false;
168
169         switch (s->type) {
170
171         case PATH_EXISTS:
172                 good = access(s->path, F_OK) >= 0;
173                 break;
174
175         case PATH_EXISTS_GLOB:
176                 good = glob_exists(s->path) > 0;
177                 break;
178
179         case PATH_DIRECTORY_NOT_EMPTY: {
180                 int k;
181
182                 k = dir_is_empty(s->path);
183                 good = !(k == -ENOENT || k > 0);
184                 break;
185         }
186
187         case PATH_CHANGED: {
188                 bool b;
189
190                 b = access(s->path, F_OK) >= 0;
191                 good = !initial && b != s->previous_exists;
192                 s->previous_exists = b;
193                 break;
194         }
195
196         default:
197                 ;
198         }
199
200         return good;
201 }
202
203 static bool pathspec_startswith(PathSpec *s, const char *what) {
204         return path_startswith(s->path, what);
205 }
206
207 static void pathspec_mkdir(PathSpec *s, mode_t mode) {
208         int r;
209
210         if (s->type == PATH_EXISTS || s->type == PATH_EXISTS_GLOB)
211                 return;
212
213         if ((r = mkdir_p(s->path, mode)) < 0)
214                 log_warning("mkdir(%s) failed: %s", s->path, strerror(-r));
215 }
216
217 static void pathspec_dump(PathSpec *s, FILE *f, const char *prefix) {
218         fprintf(f,
219                 "%s%s: %s\n",
220                 prefix,
221                 path_type_to_string(s->type),
222                 s->path);
223 }
224
225 void pathspec_done(PathSpec *s) {
226         assert(s->inotify_fd == -1);
227         free(s->path);
228 }
229
230 static void path_init(Unit *u) {
231         Path *p = PATH(u);
232
233         assert(u);
234         assert(u->meta.load_state == UNIT_STUB);
235
236         p->directory_mode = 0755;
237 }
238
239 static void path_done(Unit *u) {
240         Path *p = PATH(u);
241         PathSpec *s;
242
243         assert(p);
244
245         while ((s = p->specs)) {
246                 pathspec_unwatch(s, u);
247                 LIST_REMOVE(PathSpec, spec, p->specs, s);
248                 pathspec_done(s);
249                 free(s);
250         }
251 }
252
253 int path_add_one_mount_link(Path *p, Mount *m) {
254         PathSpec *s;
255         int r;
256
257         assert(p);
258         assert(m);
259
260         if (p->meta.load_state != UNIT_LOADED ||
261             m->meta.load_state != UNIT_LOADED)
262                 return 0;
263
264         LIST_FOREACH(spec, s, p->specs) {
265
266                 if (!pathspec_startswith(s, m->where))
267                         continue;
268
269                 if ((r = unit_add_two_dependencies(UNIT(p), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
270                         return r;
271         }
272
273         return 0;
274 }
275
276 static int path_add_mount_links(Path *p) {
277         Meta *other;
278         int r;
279
280         assert(p);
281
282         LIST_FOREACH(units_by_type, other, p->meta.manager->units_by_type[UNIT_MOUNT])
283                 if ((r = path_add_one_mount_link(p, (Mount*) other)) < 0)
284                         return r;
285
286         return 0;
287 }
288
289 static int path_verify(Path *p) {
290         assert(p);
291
292         if (p->meta.load_state != UNIT_LOADED)
293                 return 0;
294
295         if (!p->specs) {
296                 log_error("%s lacks path setting. Refusing.", p->meta.id);
297                 return -EINVAL;
298         }
299
300         return 0;
301 }
302
303 static int path_add_default_dependencies(Path *p) {
304         int r;
305
306         assert(p);
307
308         if (p->meta.manager->running_as == MANAGER_SYSTEM) {
309                 if ((r = unit_add_dependency_by_name(UNIT(p), UNIT_BEFORE, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
310                         return r;
311
312                 if ((r = unit_add_two_dependencies_by_name(UNIT(p), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 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);
317 }
318
319 static int path_load(Unit *u) {
320         Path *p = PATH(u);
321         int r;
322
323         assert(u);
324         assert(u->meta.load_state == UNIT_STUB);
325
326         if ((r = unit_load_fragment_and_dropin(u)) < 0)
327                 return r;
328
329         if (u->meta.load_state == UNIT_LOADED) {
330
331                 if (!p->unit)
332                         if ((r = unit_load_related_unit(u, ".service", &p->unit)))
333                                 return r;
334
335                 if ((r = unit_add_dependency(u, UNIT_BEFORE, p->unit, true)) < 0)
336                         return r;
337
338                 if ((r = path_add_mount_links(p)) < 0)
339                         return r;
340
341                 if (p->meta.default_dependencies)
342                         if ((r = path_add_default_dependencies(p)) < 0)
343                                 return r;
344         }
345
346         return path_verify(p);
347 }
348
349 static void path_dump(Unit *u, FILE *f, const char *prefix) {
350         Path *p = PATH(u);
351         PathSpec *s;
352
353         assert(p);
354         assert(f);
355
356         fprintf(f,
357                 "%sPath State: %s\n"
358                 "%sUnit: %s\n"
359                 "%sMakeDirectory: %s\n"
360                 "%sDirectoryMode: %04o\n",
361                 prefix, path_state_to_string(p->state),
362                 prefix, p->unit->meta.id,
363                 prefix, yes_no(p->make_directory),
364                 prefix, p->directory_mode);
365
366         LIST_FOREACH(spec, s, p->specs)
367                 pathspec_dump(s, f, prefix);
368 }
369
370 static void path_unwatch(Path *p) {
371         PathSpec *s;
372
373         assert(p);
374
375         LIST_FOREACH(spec, s, p->specs)
376                 pathspec_unwatch(s, UNIT(p));
377 }
378
379 static int path_watch(Path *p) {
380         int r;
381         PathSpec *s;
382
383         assert(p);
384
385         LIST_FOREACH(spec, s, p->specs)
386                 if ((r = pathspec_watch(s, UNIT(p))) < 0)
387                         return r;
388
389         return 0;
390 }
391
392 static void path_set_state(Path *p, PathState state) {
393         PathState old_state;
394         assert(p);
395
396         old_state = p->state;
397         p->state = state;
398
399         if (state != PATH_WAITING &&
400             (state != PATH_RUNNING || p->inotify_triggered))
401                 path_unwatch(p);
402
403         if (state != old_state)
404                 log_debug("%s changed %s -> %s",
405                           p->meta.id,
406                           path_state_to_string(old_state),
407                           path_state_to_string(state));
408
409         unit_notify(UNIT(p), state_translation_table[old_state], state_translation_table[state], true);
410 }
411
412 static void path_enter_waiting(Path *p, bool initial, bool recheck);
413
414 static int path_coldplug(Unit *u) {
415         Path *p = PATH(u);
416
417         assert(p);
418         assert(p->state == PATH_DEAD);
419
420         if (p->deserialized_state != p->state) {
421
422                 if (p->deserialized_state == PATH_WAITING ||
423                     p->deserialized_state == PATH_RUNNING)
424                         path_enter_waiting(p, true, true);
425                 else
426                         path_set_state(p, p->deserialized_state);
427         }
428
429         return 0;
430 }
431
432 static void path_enter_dead(Path *p, bool success) {
433         assert(p);
434
435         if (!success)
436                 p->failure = true;
437
438         path_set_state(p, p->failure ? PATH_FAILED : PATH_DEAD);
439 }
440
441 static void path_enter_running(Path *p) {
442         int r;
443         DBusError error;
444
445         assert(p);
446         dbus_error_init(&error);
447
448         /* Don't start job if we are supposed to go down */
449         if (p->meta.job && p->meta.job->type == JOB_STOP)
450                 return;
451
452         if ((r = manager_add_job(p->meta.manager, JOB_START, p->unit, JOB_REPLACE, true, &error, NULL)) < 0)
453                 goto fail;
454
455         p->inotify_triggered = false;
456
457         if ((r = path_watch(p)) < 0)
458                 goto fail;
459
460         path_set_state(p, PATH_RUNNING);
461         return;
462
463 fail:
464         log_warning("%s failed to queue unit startup job: %s", p->meta.id, bus_error(&error, r));
465         path_enter_dead(p, false);
466
467         dbus_error_free(&error);
468 }
469
470 static bool path_check_good(Path *p, bool initial) {
471         PathSpec *s;
472         bool good = false;
473
474         assert(p);
475
476         LIST_FOREACH(spec, s, p->specs) {
477                 good = pathspec_check_good(s, initial);
478
479                 if (good)
480                         break;
481         }
482
483         return good;
484 }
485
486 static void path_enter_waiting(Path *p, bool initial, bool recheck) {
487         int r;
488
489         if (recheck)
490                 if (path_check_good(p, initial)) {
491                         log_debug("%s got triggered.", p->meta.id);
492                         path_enter_running(p);
493                         return;
494                 }
495
496         if ((r = path_watch(p)) < 0)
497                 goto fail;
498
499         /* Hmm, so now we have created inotify watches, but the file
500          * might have appeared/been removed by now, so we must
501          * recheck */
502
503         if (recheck)
504                 if (path_check_good(p, false)) {
505                         log_debug("%s got triggered.", p->meta.id);
506                         path_enter_running(p);
507                         return;
508                 }
509
510         path_set_state(p, PATH_WAITING);
511         return;
512
513 fail:
514         log_warning("%s failed to enter waiting state: %s", p->meta.id, strerror(-r));
515         path_enter_dead(p, false);
516 }
517
518 static void path_mkdir(Path *p) {
519         PathSpec *s;
520
521         assert(p);
522
523         if (!p->make_directory)
524                 return;
525
526         LIST_FOREACH(spec, s, p->specs)
527                 pathspec_mkdir(s, p->directory_mode);
528 }
529
530 static int path_start(Unit *u) {
531         Path *p = PATH(u);
532
533         assert(p);
534         assert(p->state == PATH_DEAD || p->state == PATH_FAILED);
535
536         if (p->unit->meta.load_state != UNIT_LOADED)
537                 return -ENOENT;
538
539         path_mkdir(p);
540
541         p->failure = false;
542         path_enter_waiting(p, true, true);
543
544         return 0;
545 }
546
547 static int path_stop(Unit *u) {
548         Path *p = PATH(u);
549
550         assert(p);
551         assert(p->state == PATH_WAITING || p->state == PATH_RUNNING);
552
553         path_enter_dead(p, true);
554         return 0;
555 }
556
557 static int path_serialize(Unit *u, FILE *f, FDSet *fds) {
558         Path *p = PATH(u);
559
560         assert(u);
561         assert(f);
562         assert(fds);
563
564         unit_serialize_item(u, f, "state", path_state_to_string(p->state));
565
566         return 0;
567 }
568
569 static int path_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
570         Path *p = PATH(u);
571
572         assert(u);
573         assert(key);
574         assert(value);
575         assert(fds);
576
577         if (streq(key, "state")) {
578                 PathState state;
579
580                 if ((state = path_state_from_string(value)) < 0)
581                         log_debug("Failed to parse state value %s", value);
582                 else
583                         p->deserialized_state = state;
584         } else
585                 log_debug("Unknown serialization key '%s'", key);
586
587         return 0;
588 }
589
590 static UnitActiveState path_active_state(Unit *u) {
591         assert(u);
592
593         return state_translation_table[PATH(u)->state];
594 }
595
596 static const char *path_sub_state_to_string(Unit *u) {
597         assert(u);
598
599         return path_state_to_string(PATH(u)->state);
600 }
601
602 static void path_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
603         Path *p = PATH(u);
604         PathSpec *s;
605         int changed;
606
607         assert(p);
608         assert(fd >= 0);
609
610         if (p->state != PATH_WAITING &&
611             p->state != PATH_RUNNING)
612                 return;
613
614         /* log_debug("inotify wakeup on %s.", u->meta.id); */
615
616         LIST_FOREACH(spec, s, p->specs)
617                 if (pathspec_owns_inotify_fd(s, fd))
618                         break;
619
620         if (!s) {
621                 log_error("Got event on unknown fd.");
622                 goto fail;
623         }
624
625         changed = pathspec_fd_event(s, events);
626         if (changed < 0)
627                 goto fail;
628
629         /* If we are already running, then remember that one event was
630          * dispatched so that we restart the service only if something
631          * actually changed on disk */
632         p->inotify_triggered = true;
633
634         if (changed)
635                 path_enter_running(p);
636         else
637                 path_enter_waiting(p, false, true);
638
639         return;
640
641 fail:
642         path_enter_dead(p, false);
643 }
644
645 void path_unit_notify(Unit *u, UnitActiveState new_state) {
646         char *n;
647         int r;
648         Iterator i;
649
650         if (u->meta.type == UNIT_PATH)
651                 return;
652
653         SET_FOREACH(n, u->meta.names, i) {
654                 char *k;
655                 Unit *t;
656                 Path *p;
657
658                 if (!(k = unit_name_change_suffix(n, ".path"))) {
659                         r = -ENOMEM;
660                         goto fail;
661                 }
662
663                 t = manager_get_unit(u->meta.manager, k);
664                 free(k);
665
666                 if (!t)
667                         continue;
668
669                 if (t->meta.load_state != UNIT_LOADED)
670                         continue;
671
672                 p = PATH(t);
673
674                 if (p->unit != u)
675                         continue;
676
677                 if (p->state == PATH_RUNNING && new_state == UNIT_INACTIVE) {
678                         log_debug("%s got notified about unit deactivation.", p->meta.id);
679
680                         /* Hmm, so inotify was triggered since the
681                          * last activation, so I guess we need to
682                          * recheck what is going on. */
683                         path_enter_waiting(p, false, p->inotify_triggered);
684                 }
685         }
686
687         return;
688
689 fail:
690         log_error("Failed find path unit: %s", strerror(-r));
691 }
692
693 static void path_reset_failed(Unit *u) {
694         Path *p = PATH(u);
695
696         assert(p);
697
698         if (p->state == PATH_FAILED)
699                 path_set_state(p, PATH_DEAD);
700
701         p->failure = false;
702 }
703
704 static const char* const path_state_table[_PATH_STATE_MAX] = {
705         [PATH_DEAD] = "dead",
706         [PATH_WAITING] = "waiting",
707         [PATH_RUNNING] = "running",
708         [PATH_FAILED] = "failed"
709 };
710
711 DEFINE_STRING_TABLE_LOOKUP(path_state, PathState);
712
713 static const char* const path_type_table[_PATH_TYPE_MAX] = {
714         [PATH_EXISTS] = "PathExists",
715         [PATH_EXISTS_GLOB] = "PathExistsGlob",
716         [PATH_CHANGED] = "PathChanged",
717         [PATH_MODIFIED] = "PathModified",
718         [PATH_DIRECTORY_NOT_EMPTY] = "DirectoryNotEmpty"
719 };
720
721 DEFINE_STRING_TABLE_LOOKUP(path_type, PathType);
722
723 const UnitVTable path_vtable = {
724         .suffix = ".path",
725         .sections =
726                 "Unit\0"
727                 "Path\0"
728                 "Install\0",
729
730         .init = path_init,
731         .done = path_done,
732         .load = path_load,
733
734         .coldplug = path_coldplug,
735
736         .dump = path_dump,
737
738         .start = path_start,
739         .stop = path_stop,
740
741         .serialize = path_serialize,
742         .deserialize_item = path_deserialize_item,
743
744         .active_state = path_active_state,
745         .sub_state_to_string = path_sub_state_to_string,
746
747         .fd_event = path_fd_event,
748
749         .reset_failed = path_reset_failed,
750
751         .bus_interface = "org.freedesktop.systemd1.Path",
752         .bus_message_handler = bus_path_message_handler
753 };