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