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