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