]> git.ipfire.org Git - people/ms/systemd.git/blob - unit.c
unit: when merging a device, follow the merge first
[people/ms/systemd.git] / unit.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 <assert.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <sys/epoll.h>
26 #include <sys/timerfd.h>
27 #include <sys/poll.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30
31 #include "set.h"
32 #include "unit.h"
33 #include "macro.h"
34 #include "strv.h"
35 #include "load-fragment.h"
36 #include "load-dropin.h"
37 #include "log.h"
38
39 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
40 [UNIT_SERVICE] = &service_vtable,
41 [UNIT_TIMER] = &timer_vtable,
42 [UNIT_SOCKET] = &socket_vtable,
43 [UNIT_TARGET] = &target_vtable,
44 [UNIT_DEVICE] = &device_vtable,
45 [UNIT_MOUNT] = &mount_vtable,
46 [UNIT_AUTOMOUNT] = &automount_vtable,
47 [UNIT_SNAPSHOT] = &snapshot_vtable
48 };
49
50 UnitType unit_name_to_type(const char *n) {
51 UnitType t;
52
53 assert(n);
54
55 for (t = 0; t < _UNIT_TYPE_MAX; t++)
56 if (endswith(n, unit_vtable[t]->suffix))
57 return t;
58
59 return _UNIT_TYPE_INVALID;
60 }
61
62 #define VALID_CHARS \
63 "0123456789" \
64 "abcdefghijklmnopqrstuvwxyz" \
65 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
66 "-_.\\"
67
68 bool unit_name_is_valid(const char *n) {
69 UnitType t;
70 const char *e, *i;
71
72 assert(n);
73
74 if (strlen(n) >= UNIT_NAME_MAX)
75 return false;
76
77 t = unit_name_to_type(n);
78 if (t < 0 || t >= _UNIT_TYPE_MAX)
79 return false;
80
81 if (!(e = strrchr(n, '.')))
82 return false;
83
84 if (e == n)
85 return false;
86
87 for (i = n; i < e; i++)
88 if (!strchr(VALID_CHARS, *i))
89 return false;
90
91 return true;
92 }
93
94 char *unit_name_change_suffix(const char *n, const char *suffix) {
95 char *e, *r;
96 size_t a, b;
97
98 assert(n);
99 assert(unit_name_is_valid(n));
100 assert(suffix);
101
102 assert_se(e = strrchr(n, '.'));
103 a = e - n;
104 b = strlen(suffix);
105
106 if (!(r = new(char, a + b + 1)))
107 return NULL;
108
109 memcpy(r, n, a);
110 memcpy(r+a, suffix, b+1);
111
112 return r;
113 }
114
115 Unit *unit_new(Manager *m) {
116 Unit *u;
117
118 assert(m);
119
120 if (!(u = new0(Unit, 1)))
121 return NULL;
122
123 if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
124 free(u);
125 return NULL;
126 }
127
128 u->meta.manager = m;
129 u->meta.type = _UNIT_TYPE_INVALID;
130
131 return u;
132 }
133
134 bool unit_has_name(Unit *u, const char *name) {
135 assert(u);
136 assert(name);
137
138 return !!set_get(u->meta.names, (char*) name);
139 }
140
141 int unit_add_name(Unit *u, const char *text) {
142 UnitType t;
143 char *s;
144 int r;
145
146 assert(u);
147 assert(text);
148
149 if (!unit_name_is_valid(text))
150 return -EINVAL;
151
152 if ((t = unit_name_to_type(text)) == _UNIT_TYPE_INVALID)
153 return -EINVAL;
154
155 if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type)
156 return -EINVAL;
157
158 if (!(s = strdup(text)))
159 return -ENOMEM;
160
161 if ((r = set_put(u->meta.names, s)) < 0) {
162 free(s);
163
164 if (r == -EEXIST)
165 return 0;
166
167 return r;
168 }
169
170 if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
171 set_remove(u->meta.names, s);
172 free(s);
173 return r;
174 }
175
176 if (u->meta.type == _UNIT_TYPE_INVALID)
177 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
178
179 u->meta.type = t;
180
181 if (!u->meta.id)
182 u->meta.id = s;
183
184 unit_add_to_dbus_queue(u);
185 return 0;
186 }
187
188 int unit_choose_id(Unit *u, const char *name) {
189 char *s;
190
191 assert(u);
192 assert(name);
193
194 /* Selects one of the names of this unit as the id */
195
196 if (!(s = set_get(u->meta.names, (char*) name)))
197 return -ENOENT;
198
199 u->meta.id = s;
200
201 unit_add_to_dbus_queue(u);
202 return 0;
203 }
204
205 int unit_set_description(Unit *u, const char *description) {
206 char *s;
207
208 assert(u);
209
210 if (!(s = strdup(description)))
211 return -ENOMEM;
212
213 free(u->meta.description);
214 u->meta.description = s;
215
216 unit_add_to_dbus_queue(u);
217 return 0;
218 }
219
220 void unit_add_to_load_queue(Unit *u) {
221 assert(u);
222
223 if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
224 return;
225
226 LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
227 u->meta.in_load_queue = true;
228 }
229
230 void unit_add_to_cleanup_queue(Unit *u) {
231 assert(u);
232
233 if (u->meta.in_cleanup_queue)
234 return;
235
236 LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
237 u->meta.in_cleanup_queue = true;
238 }
239
240 void unit_add_to_dbus_queue(Unit *u) {
241 assert(u);
242
243 if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue || set_isempty(u->meta.manager->subscribed))
244 return;
245
246 LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
247 u->meta.in_dbus_queue = true;
248 }
249
250 static void bidi_set_free(Unit *u, Set *s) {
251 Iterator i;
252 Unit *other;
253
254 assert(u);
255
256 /* Frees the set and makes sure we are dropped from the
257 * inverse pointers */
258
259 SET_FOREACH(other, s, i) {
260 UnitDependency d;
261
262 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
263 set_remove(other->meta.dependencies[d], u);
264 }
265
266 set_free(s);
267 }
268
269 void unit_free(Unit *u) {
270 UnitDependency d;
271 Iterator i;
272 char *t;
273
274 assert(u);
275
276 bus_unit_send_removed_signal(u);
277
278 /* Detach from next 'bigger' objects */
279
280 cgroup_bonding_free_list(u->meta.cgroup_bondings);
281
282 SET_FOREACH(t, u->meta.names, i)
283 hashmap_remove_value(u->meta.manager->units, t, u);
284
285 if (u->meta.type != _UNIT_TYPE_INVALID)
286 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
287
288 if (u->meta.in_load_queue)
289 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
290
291 if (u->meta.in_dbus_queue)
292 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
293
294 if (u->meta.in_cleanup_queue)
295 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
296
297 if (u->meta.load_state != UNIT_STUB)
298 if (UNIT_VTABLE(u)->done)
299 UNIT_VTABLE(u)->done(u);
300
301 /* Free data and next 'smaller' objects */
302 if (u->meta.job)
303 job_free(u->meta.job);
304
305 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
306 bidi_set_free(u, u->meta.dependencies[d]);
307
308 free(u->meta.description);
309 free(u->meta.fragment_path);
310
311 while ((t = set_steal_first(u->meta.names)))
312 free(t);
313 set_free(u->meta.names);
314
315 free(u);
316 }
317
318 UnitActiveState unit_active_state(Unit *u) {
319 assert(u);
320
321 if (u->meta.load_state != UNIT_LOADED)
322 return UNIT_INACTIVE;
323
324 return UNIT_VTABLE(u)->active_state(u);
325 }
326
327 static void complete_move(Set **s, Set **other) {
328 assert(s);
329 assert(other);
330
331 if (!*other)
332 return;
333
334 if (*s)
335 set_move(*s, *other);
336 else {
337 *s = *other;
338 *other = NULL;
339 }
340 }
341
342 static void merge_names(Unit *u, Unit *other) {
343 char *t;
344 Iterator i;
345
346 assert(u);
347 assert(other);
348
349 complete_move(&u->meta.names, &other->meta.names);
350
351 while ((t = set_steal_first(other->meta.names)))
352 free(t);
353
354 set_free(other->meta.names);
355 other->meta.names = NULL;
356 other->meta.id = NULL;
357
358 SET_FOREACH(t, u->meta.names, i)
359 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
360 }
361
362 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
363 Iterator i;
364 Unit *back;
365 int r;
366
367 assert(u);
368 assert(other);
369 assert(d < _UNIT_DEPENDENCY_MAX);
370
371 SET_FOREACH(back, other->meta.dependencies[d], i) {
372 UnitDependency k;
373
374 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
375 if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
376
377 if (r == -EEXIST)
378 set_remove(back->meta.dependencies[k], other);
379 else
380 assert(r == -ENOENT);
381 }
382 }
383
384 complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
385
386 set_free(other->meta.dependencies[d]);
387 other->meta.dependencies[d] = NULL;
388 }
389
390 int unit_merge(Unit *u, Unit *other) {
391 UnitDependency d;
392
393 assert(u);
394 assert(other);
395 assert(u->meta.manager == other->meta.manager);
396
397 other = unit_follow_merge(other);
398
399 if (other == u)
400 return 0;
401
402 /* This merges 'other' into 'unit'. FIXME: This does not
403 * rollback on failure. */
404
405 if (u->meta.type != u->meta.type)
406 return -EINVAL;
407
408 if (other->meta.load_state != UNIT_STUB &&
409 other->meta.load_state != UNIT_FAILED)
410 return -EEXIST;
411
412 /* Merge names */
413 merge_names(u, other);
414
415 /* Merge dependencies */
416 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
417 merge_dependencies(u, other, d);
418
419 unit_add_to_dbus_queue(u);
420
421 other->meta.load_state = UNIT_MERGED;
422 other->meta.merged_into = u;
423
424 unit_add_to_cleanup_queue(other);
425
426 return 0;
427 }
428
429 int unit_merge_by_name(Unit *u, const char *name) {
430 Unit *other;
431
432 assert(u);
433 assert(name);
434
435 if (!(other = manager_get_unit(u->meta.manager, name)))
436 return unit_add_name(u, name);
437
438 return unit_merge(u, other);
439 }
440
441 Unit* unit_follow_merge(Unit *u) {
442 assert(u);
443
444 while (u->meta.load_state == UNIT_MERGED)
445 assert_se(u = u->meta.merged_into);
446
447 return u;
448 }
449
450 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
451 int r;
452
453 assert(u);
454 assert(c);
455
456 if (c->output != EXEC_OUTPUT_KERNEL && c->output != EXEC_OUTPUT_SYSLOG)
457 return 0;
458
459 /* If syslog or kernel logging is requested, make sure our own
460 * logging daemon is run first. */
461
462 if ((r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_LOGGER_SOCKET)) < 0)
463 return r;
464
465 if (u->meta.manager->running_as != MANAGER_SESSION)
466 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_LOGGER_SOCKET)) < 0)
467 return r;
468
469 return 0;
470 }
471
472 const char* unit_id(Unit *u) {
473 assert(u);
474
475 if (u->meta.id)
476 return u->meta.id;
477
478 return set_first(u->meta.names);
479 }
480
481 const char *unit_description(Unit *u) {
482 assert(u);
483
484 if (u->meta.description)
485 return u->meta.description;
486
487 return unit_id(u);
488 }
489
490 void unit_dump(Unit *u, FILE *f, const char *prefix) {
491 char *t;
492 UnitDependency d;
493 Iterator i;
494 char *p2;
495 const char *prefix2;
496 CGroupBonding *b;
497
498 assert(u);
499
500 if (!prefix)
501 prefix = "";
502 p2 = strappend(prefix, "\t");
503 prefix2 = p2 ? p2 : prefix;
504
505 fprintf(f,
506 "%s→ Unit %s:\n"
507 "%s\tDescription: %s\n"
508 "%s\tUnit Load State: %s\n"
509 "%s\tUnit Active State: %s\n",
510 prefix, unit_id(u),
511 prefix, unit_description(u),
512 prefix, unit_load_state_to_string(u->meta.load_state),
513 prefix, unit_active_state_to_string(unit_active_state(u)));
514
515 SET_FOREACH(t, u->meta.names, i)
516 fprintf(f, "%s\tName: %s\n", prefix, t);
517
518 if (u->meta.fragment_path)
519 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
520
521 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
522 Unit *other;
523
524 if (set_isempty(u->meta.dependencies[d]))
525 continue;
526
527 SET_FOREACH(other, u->meta.dependencies[d], i)
528 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), unit_id(other));
529 }
530
531 fprintf(f,
532 "%s\tRecursive Stop: %s\n"
533 "%s\tStop When Unneeded: %s\n",
534 prefix, yes_no(u->meta.recursive_stop),
535 prefix, yes_no(u->meta.stop_when_unneeded));
536
537 if (u->meta.load_state == UNIT_LOADED) {
538 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
539 fprintf(f, "%s\tControlGroup: %s:%s\n",
540 prefix, b->controller, b->path);
541
542 if (UNIT_VTABLE(u)->dump)
543 UNIT_VTABLE(u)->dump(u, f, prefix2);
544 }
545
546 if (u->meta.job)
547 job_dump(u->meta.job, f, prefix2);
548
549 free(p2);
550 }
551
552 /* Common implementation for multiple backends */
553 int unit_load_fragment_and_dropin(Unit *u, UnitLoadState *new_state) {
554 int r;
555
556 assert(u);
557 assert(new_state);
558 assert(*new_state == UNIT_STUB || *new_state == UNIT_LOADED);
559
560 /* Load a .service file */
561 if ((r = unit_load_fragment(u, new_state)) < 0)
562 return r;
563
564 if (*new_state == UNIT_STUB)
565 return -ENOENT;
566
567 /* Load drop-in directory data */
568 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
569 return r;
570
571 return 0;
572 }
573
574 /* Common implementation for multiple backends */
575 int unit_load_fragment_and_dropin_optional(Unit *u, UnitLoadState *new_state) {
576 int r;
577
578 assert(u);
579 assert(new_state);
580 assert(*new_state == UNIT_STUB || *new_state == UNIT_LOADED);
581
582 /* Same as unit_load_fragment_and_dropin(), but whether
583 * something can be loaded or not doesn't matter. */
584
585 /* Load a .service file */
586 if ((r = unit_load_fragment(u, new_state)) < 0)
587 return r;
588
589 if (*new_state == UNIT_STUB)
590 *new_state = UNIT_LOADED;
591
592 /* Load drop-in directory data */
593 if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
594 return r;
595
596 return 0;
597 }
598
599 int unit_load(Unit *u) {
600 int r;
601 UnitLoadState res;
602
603 assert(u);
604
605 if (u->meta.in_load_queue) {
606 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
607 u->meta.in_load_queue = false;
608 }
609
610 if (u->meta.load_state != UNIT_STUB)
611 return 0;
612
613 if (UNIT_VTABLE(u)->init) {
614 res = UNIT_STUB;
615 if ((r = UNIT_VTABLE(u)->init(u, &res)) < 0)
616 goto fail;
617 }
618
619 if (res == UNIT_STUB) {
620 r = -ENOENT;
621 goto fail;
622 }
623
624 u->meta.load_state = res;
625 assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
626
627 unit_add_to_dbus_queue(unit_follow_merge(u));
628
629 return 0;
630
631 fail:
632 u->meta.load_state = UNIT_FAILED;
633 unit_add_to_dbus_queue(u);
634
635 log_error("Failed to load configuration for %s: %s", unit_id(u), strerror(-r));
636
637 return r;
638 }
639
640 /* Errors:
641 * -EBADR: This unit type does not support starting.
642 * -EALREADY: Unit is already started.
643 * -EAGAIN: An operation is already in progress. Retry later.
644 */
645 int unit_start(Unit *u) {
646 UnitActiveState state;
647
648 assert(u);
649
650 /* If this is already (being) started, then this will
651 * succeed. Note that this will even succeed if this unit is
652 * not startable by the user. This is relied on to detect when
653 * we need to wait for units and when waiting is finished. */
654 state = unit_active_state(u);
655 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
656 return -EALREADY;
657
658 /* If it is stopped, but we cannot start it, then fail */
659 if (!UNIT_VTABLE(u)->start)
660 return -EBADR;
661
662 /* We don't suppress calls to ->start() here when we are
663 * already starting, to allow this request to be used as a
664 * "hurry up" call, for example when the unit is in some "auto
665 * restart" state where it waits for a holdoff timer to elapse
666 * before it will start again. */
667
668 unit_add_to_dbus_queue(u);
669 return UNIT_VTABLE(u)->start(u);
670 }
671
672 bool unit_can_start(Unit *u) {
673 assert(u);
674
675 return !!UNIT_VTABLE(u)->start;
676 }
677
678 /* Errors:
679 * -EBADR: This unit type does not support stopping.
680 * -EALREADY: Unit is already stopped.
681 * -EAGAIN: An operation is already in progress. Retry later.
682 */
683 int unit_stop(Unit *u) {
684 UnitActiveState state;
685
686 assert(u);
687
688 state = unit_active_state(u);
689 if (state == UNIT_INACTIVE)
690 return -EALREADY;
691
692 if (!UNIT_VTABLE(u)->stop)
693 return -EBADR;
694
695 if (state == UNIT_DEACTIVATING)
696 return 0;
697
698 unit_add_to_dbus_queue(u);
699 return UNIT_VTABLE(u)->stop(u);
700 }
701
702 /* Errors:
703 * -EBADR: This unit type does not support reloading.
704 * -ENOEXEC: Unit is not started.
705 * -EAGAIN: An operation is already in progress. Retry later.
706 */
707 int unit_reload(Unit *u) {
708 UnitActiveState state;
709
710 assert(u);
711
712 if (!unit_can_reload(u))
713 return -EBADR;
714
715 state = unit_active_state(u);
716 if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
717 return -EALREADY;
718
719 if (unit_active_state(u) != UNIT_ACTIVE)
720 return -ENOEXEC;
721
722 unit_add_to_dbus_queue(u);
723 return UNIT_VTABLE(u)->reload(u);
724 }
725
726 bool unit_can_reload(Unit *u) {
727 assert(u);
728
729 if (!UNIT_VTABLE(u)->reload)
730 return false;
731
732 if (!UNIT_VTABLE(u)->can_reload)
733 return true;
734
735 return UNIT_VTABLE(u)->can_reload(u);
736 }
737
738 static void unit_check_uneeded(Unit *u) {
739 Iterator i;
740 Unit *other;
741
742 assert(u);
743
744 /* If this service shall be shut down when unneeded then do
745 * so. */
746
747 if (!u->meta.stop_when_unneeded)
748 return;
749
750 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
751 return;
752
753 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
754 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
755 return;
756
757 SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRED_BY], i)
758 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
759 return;
760
761 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
762 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
763 return;
764
765 log_debug("Service %s is not needed anymore. Stopping.", unit_id(u));
766
767 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
768 manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL);
769 }
770
771 static void retroactively_start_dependencies(Unit *u) {
772 Iterator i;
773 Unit *other;
774
775 assert(u);
776 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
777
778 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
779 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
780 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
781
782 SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
783 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
784 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
785
786 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
787 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
788 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
789
790 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
791 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
792 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
793
794 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
795 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
796 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
797 }
798
799 static void retroactively_stop_dependencies(Unit *u) {
800 Iterator i;
801 Unit *other;
802
803 assert(u);
804 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
805
806 if (u->meta.recursive_stop) {
807 /* Pull down units need us recursively if enabled */
808 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
809 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
810 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
811 }
812
813 /* Garbage collect services that might not be needed anymore, if enabled */
814 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
815 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
816 unit_check_uneeded(other);
817 SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
818 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
819 unit_check_uneeded(other);
820 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
821 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
822 unit_check_uneeded(other);
823 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
824 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
825 unit_check_uneeded(other);
826 SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUISITE], i)
827 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
828 unit_check_uneeded(other);
829 }
830
831 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
832 bool unexpected = false;
833
834 assert(u);
835 assert(os < _UNIT_ACTIVE_STATE_MAX);
836 assert(ns < _UNIT_ACTIVE_STATE_MAX);
837 assert(!(os == UNIT_ACTIVE && ns == UNIT_ACTIVATING));
838 assert(!(os == UNIT_INACTIVE && ns == UNIT_DEACTIVATING));
839
840 if (os == ns)
841 return;
842
843 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
844 u->meta.active_enter_timestamp = now(CLOCK_REALTIME);
845 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
846 u->meta.active_exit_timestamp = now(CLOCK_REALTIME);
847
848 if (u->meta.job) {
849
850 if (u->meta.job->state == JOB_WAITING)
851
852 /* So we reached a different state for this
853 * job. Let's see if we can run it now if it
854 * failed previously due to EAGAIN. */
855 job_add_to_run_queue(u->meta.job);
856
857 else {
858 assert(u->meta.job->state == JOB_RUNNING);
859
860 /* Let's check whether this state change
861 * constitutes a finished job, or maybe
862 * cotradicts a running job and hence needs to
863 * invalidate jobs. */
864
865 switch (u->meta.job->type) {
866
867 case JOB_START:
868 case JOB_VERIFY_ACTIVE:
869
870 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
871 job_finish_and_invalidate(u->meta.job, true);
872 else if (ns != UNIT_ACTIVATING) {
873 unexpected = true;
874 job_finish_and_invalidate(u->meta.job, false);
875 }
876
877 break;
878
879 case JOB_RELOAD:
880 case JOB_RELOAD_OR_START:
881
882 if (ns == UNIT_ACTIVE)
883 job_finish_and_invalidate(u->meta.job, true);
884 else if (ns != UNIT_ACTIVATING && ns != UNIT_ACTIVE_RELOADING) {
885 unexpected = true;
886 job_finish_and_invalidate(u->meta.job, false);
887 }
888
889 break;
890
891 case JOB_STOP:
892 case JOB_RESTART:
893 case JOB_TRY_RESTART:
894
895 if (ns == UNIT_INACTIVE)
896 job_finish_and_invalidate(u->meta.job, true);
897 else if (ns != UNIT_DEACTIVATING) {
898 unexpected = true;
899 job_finish_and_invalidate(u->meta.job, false);
900 }
901
902 break;
903
904 default:
905 assert_not_reached("Job type unknown");
906 }
907 }
908 }
909
910 /* If this state change happened without being requested by a
911 * job, then let's retroactively start or stop dependencies */
912
913 if (unexpected) {
914 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
915 retroactively_start_dependencies(u);
916 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
917 retroactively_stop_dependencies(u);
918 }
919
920 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
921
922 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
923 log_info("D-Bus became available, trying to reconnect.");
924 /* The bus just got started, hence try to connect to it. */
925 bus_init_system(u->meta.manager);
926 bus_init_api(u->meta.manager);
927 }
928
929 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE)) {
930 /* The syslog daemon just got started, hence try to connect to it. */
931 log_info("Syslog became available, trying to reconnect.");
932 log_open_syslog();
933 }
934
935 } else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
936
937 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
938 /* The syslog daemon just got terminated, hence try to disconnect from it. */
939 log_close_syslog();
940
941 /* We don't care about D-Bus here, since we'll get an
942 * asynchronous notification for it anyway. */
943 }
944
945 /* Maybe we finished startup and are now ready for being
946 * stopped because unneeded? */
947 unit_check_uneeded(u);
948
949 unit_add_to_dbus_queue(u);
950 }
951
952 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
953 struct epoll_event ev;
954
955 assert(u);
956 assert(fd >= 0);
957 assert(w);
958 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
959
960 zero(ev);
961 ev.data.ptr = w;
962 ev.events = events;
963
964 if (epoll_ctl(u->meta.manager->epoll_fd,
965 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
966 fd,
967 &ev) < 0)
968 return -errno;
969
970 w->fd = fd;
971 w->type = WATCH_FD;
972 w->data.unit = u;
973
974 return 0;
975 }
976
977 void unit_unwatch_fd(Unit *u, Watch *w) {
978 assert(u);
979 assert(w);
980
981 if (w->type == WATCH_INVALID)
982 return;
983
984 assert(w->type == WATCH_FD);
985 assert(w->data.unit == u);
986 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
987
988 w->fd = -1;
989 w->type = WATCH_INVALID;
990 w->data.unit = NULL;
991 }
992
993 int unit_watch_pid(Unit *u, pid_t pid) {
994 assert(u);
995 assert(pid >= 1);
996
997 return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
998 }
999
1000 void unit_unwatch_pid(Unit *u, pid_t pid) {
1001 assert(u);
1002 assert(pid >= 1);
1003
1004 hashmap_remove(u->meta.manager->watch_pids, UINT32_TO_PTR(pid));
1005 }
1006
1007 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1008 struct itimerspec its;
1009 int flags, fd;
1010 bool ours;
1011
1012 assert(u);
1013 assert(w);
1014 assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->data.unit == u));
1015
1016 /* This will try to reuse the old timer if there is one */
1017
1018 if (w->type == WATCH_TIMER) {
1019 ours = false;
1020 fd = w->fd;
1021 } else {
1022 ours = true;
1023 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1024 return -errno;
1025 }
1026
1027 zero(its);
1028
1029 if (delay <= 0) {
1030 /* Set absolute time in the past, but not 0, since we
1031 * don't want to disarm the timer */
1032 its.it_value.tv_sec = 0;
1033 its.it_value.tv_nsec = 1;
1034
1035 flags = TFD_TIMER_ABSTIME;
1036 } else {
1037 timespec_store(&its.it_value, delay);
1038 flags = 0;
1039 }
1040
1041 /* This will also flush the elapse counter */
1042 if (timerfd_settime(fd, flags, &its, NULL) < 0)
1043 goto fail;
1044
1045 if (w->type == WATCH_INVALID) {
1046 struct epoll_event ev;
1047
1048 zero(ev);
1049 ev.data.ptr = w;
1050 ev.events = EPOLLIN;
1051
1052 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1053 goto fail;
1054 }
1055
1056 w->fd = fd;
1057 w->type = WATCH_TIMER;
1058 w->data.unit = u;
1059
1060 return 0;
1061
1062 fail:
1063 if (ours)
1064 close_nointr_nofail(fd);
1065
1066 return -errno;
1067 }
1068
1069 void unit_unwatch_timer(Unit *u, Watch *w) {
1070 assert(u);
1071 assert(w);
1072
1073 if (w->type == WATCH_INVALID)
1074 return;
1075
1076 assert(w->type == WATCH_TIMER && w->data.unit == u);
1077
1078 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1079 assert_se(close_nointr(w->fd) == 0);
1080
1081 w->fd = -1;
1082 w->type = WATCH_INVALID;
1083 w->data.unit = NULL;
1084 }
1085
1086 bool unit_job_is_applicable(Unit *u, JobType j) {
1087 assert(u);
1088 assert(j >= 0 && j < _JOB_TYPE_MAX);
1089
1090 switch (j) {
1091
1092 case JOB_VERIFY_ACTIVE:
1093 case JOB_START:
1094 return true;
1095
1096 case JOB_STOP:
1097 case JOB_RESTART:
1098 case JOB_TRY_RESTART:
1099 return unit_can_start(u);
1100
1101 case JOB_RELOAD:
1102 return unit_can_reload(u);
1103
1104 case JOB_RELOAD_OR_START:
1105 return unit_can_reload(u) && unit_can_start(u);
1106
1107 default:
1108 assert_not_reached("Invalid job type");
1109 }
1110 }
1111
1112 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other) {
1113
1114 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1115 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1116 [UNIT_SOFT_REQUIRES] = UNIT_SOFT_REQUIRED_BY,
1117 [UNIT_WANTS] = UNIT_WANTED_BY,
1118 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1119 [UNIT_SOFT_REQUISITE] = UNIT_SOFT_REQUIRED_BY,
1120 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1121 [UNIT_SOFT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1122 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1123 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
1124 [UNIT_BEFORE] = UNIT_AFTER,
1125 [UNIT_AFTER] = UNIT_BEFORE
1126 };
1127 int r;
1128
1129 assert(u);
1130 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1131 assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
1132 assert(other);
1133
1134 /* We won't allow dependencies on ourselves. We will not
1135 * consider them an error however. */
1136 if (u == other)
1137 return 0;
1138
1139 if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1140 return r;
1141
1142 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1143 return r;
1144
1145 if ((r = set_put(u->meta.dependencies[d], other)) < 0)
1146 return r;
1147
1148 if ((r = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1149 set_remove(u->meta.dependencies[d], other);
1150 return r;
1151 }
1152
1153 unit_add_to_dbus_queue(u);
1154 return 0;
1155 }
1156
1157 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name) {
1158 Unit *other;
1159 int r;
1160
1161 if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
1162 return r;
1163
1164 if ((r = unit_add_dependency(u, d, other)) < 0)
1165 return r;
1166
1167 return 0;
1168 }
1169
1170 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name) {
1171 Unit *other;
1172 int r;
1173
1174 if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
1175 return r;
1176
1177 if ((r = unit_add_dependency(other, d, u)) < 0)
1178 return r;
1179
1180 return 0;
1181 }
1182
1183 int set_unit_path(const char *p) {
1184 char *cwd, *c;
1185 int r;
1186
1187 /* This is mostly for debug purposes */
1188
1189 if (path_is_absolute(p)) {
1190 if (!(c = strdup(p)))
1191 return -ENOMEM;
1192 } else {
1193 if (!(cwd = get_current_dir_name()))
1194 return -errno;
1195
1196 r = asprintf(&c, "%s/%s", cwd, p);
1197 free(cwd);
1198
1199 if (r < 0)
1200 return -ENOMEM;
1201 }
1202
1203 if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1204 r = -errno;
1205 free(c);
1206 return r;
1207 }
1208
1209 return 0;
1210 }
1211
1212 char *unit_name_escape_path(const char *path, const char *suffix) {
1213 char *r, *t;
1214 const char *f;
1215 size_t a, b;
1216
1217 assert(path);
1218
1219 /* Takes a path and a suffix and prefix and makes a nice
1220 * string suitable as unit name of it, escaping all weird
1221 * chars on the way.
1222 *
1223 * / becomes ., and all chars not alloweed in a unit name get
1224 * escaped as \xFF, including \ and ., of course. This
1225 * escaping is hence reversible.
1226 */
1227
1228 if (!suffix)
1229 suffix = "";
1230
1231 a = strlen(path);
1232 b = strlen(suffix);
1233
1234 if (!(r = new(char, a*4+b+1)))
1235 return NULL;
1236
1237 for (f = path, t = r; *f; f++) {
1238 if (*f == '/')
1239 *(t++) = '.';
1240 else if (*f == '.' || *f == '\\' || !strchr(VALID_CHARS, *f)) {
1241 *(t++) = '\\';
1242 *(t++) = 'x';
1243 *(t++) = hexchar(*f > 4);
1244 *(t++) = hexchar(*f);
1245 } else
1246 *(t++) = *f;
1247 }
1248
1249 memcpy(t, suffix, b+1);
1250
1251 return r;
1252 }
1253
1254 char *unit_dbus_path(Unit *u) {
1255 char *p, *e;
1256
1257 assert(u);
1258
1259 if (!(e = bus_path_escape(unit_id(u))))
1260 return NULL;
1261
1262 if (asprintf(&p, "/org/freedesktop/systemd1/unit/%s", e) < 0) {
1263 free(e);
1264 return NULL;
1265 }
1266
1267 free(e);
1268 return p;
1269 }
1270
1271 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1272 CGroupBonding *l;
1273 int r;
1274
1275 assert(u);
1276 assert(b);
1277 assert(b->path);
1278
1279 /* Ensure this hasn't been added yet */
1280 assert(!b->unit);
1281
1282 l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1283 LIST_PREPEND(CGroupBonding, by_path, l, b);
1284
1285 if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1286 LIST_REMOVE(CGroupBonding, by_path, l, b);
1287 return r;
1288 }
1289
1290 LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1291 b->unit = u;
1292
1293 return 0;
1294 }
1295
1296 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1297 size_t n;
1298 const char *p;
1299 char *controller;
1300 CGroupBonding *b;
1301 int r;
1302
1303 assert(u);
1304 assert(name);
1305
1306 /* Detect controller name */
1307 n = strcspn(name, ":/");
1308
1309 /* Only controller name, no path? No path? */
1310 if (name[n] == 0)
1311 return -EINVAL;
1312
1313 if (n > 0) {
1314 if (name[n] != ':')
1315 return -EINVAL;
1316
1317 p = name+n+1;
1318 } else
1319 p = name;
1320
1321 /* Insist in absolute paths */
1322 if (p[0] != '/')
1323 return -EINVAL;
1324
1325 if (!(controller = strndup(name, n)))
1326 return -ENOMEM;
1327
1328 if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1329 free(controller);
1330 return -EEXIST;
1331 }
1332
1333 if (!(b = new0(CGroupBonding, 1))) {
1334 free(controller);
1335 return -ENOMEM;
1336 }
1337
1338 b->controller = controller;
1339
1340 if (!(b->path = strdup(p))) {
1341 r = -ENOMEM;
1342 goto fail;
1343 }
1344
1345 b->only_us = false;
1346 b->clean_up = false;
1347
1348 if ((r = unit_add_cgroup(u, b)) < 0)
1349 goto fail;
1350
1351 return 0;
1352
1353 fail:
1354 free(b->path);
1355 free(b->controller);
1356 free(b);
1357
1358 return r;
1359 }
1360
1361 int unit_add_default_cgroup(Unit *u) {
1362 CGroupBonding *b;
1363 int r = -ENOMEM;
1364
1365 assert(u);
1366
1367 /* Adds in the default cgroup data, if it wasn't specified yet */
1368
1369 if (unit_get_default_cgroup(u))
1370 return 0;
1371
1372 if (!(b = new0(CGroupBonding, 1)))
1373 return -ENOMEM;
1374
1375 if (!(b->controller = strdup(u->meta.manager->cgroup_controller)))
1376 goto fail;
1377
1378 if (asprintf(&b->path, "%s/%s", u->meta.manager->cgroup_hierarchy, unit_id(u)) < 0)
1379 goto fail;
1380
1381 b->clean_up = true;
1382 b->only_us = true;
1383
1384 if ((r = unit_add_cgroup(u, b)) < 0)
1385 goto fail;
1386
1387 return 0;
1388
1389 fail:
1390 free(b->path);
1391 free(b->controller);
1392 free(b);
1393
1394 return r;
1395 }
1396
1397 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1398 assert(u);
1399
1400 return cgroup_bonding_find_list(u->meta.cgroup_bondings, u->meta.manager->cgroup_controller);
1401 }
1402
1403 static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
1404 [UNIT_SERVICE] = "service",
1405 [UNIT_TIMER] = "timer",
1406 [UNIT_SOCKET] = "socket",
1407 [UNIT_TARGET] = "target",
1408 [UNIT_DEVICE] = "device",
1409 [UNIT_MOUNT] = "mount",
1410 [UNIT_AUTOMOUNT] = "automount",
1411 [UNIT_SNAPSHOT] = "snapshot"
1412 };
1413
1414 DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
1415
1416 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
1417 [UNIT_STUB] = "stub",
1418 [UNIT_LOADED] = "loaded",
1419 [UNIT_FAILED] = "failed",
1420 [UNIT_MERGED] = "merged"
1421 };
1422
1423 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
1424
1425 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
1426 [UNIT_ACTIVE] = "active",
1427 [UNIT_INACTIVE] = "inactive",
1428 [UNIT_ACTIVATING] = "activating",
1429 [UNIT_DEACTIVATING] = "deactivating"
1430 };
1431
1432 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
1433
1434 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
1435 [UNIT_REQUIRES] = "Requires",
1436 [UNIT_SOFT_REQUIRES] = "SoftRequires",
1437 [UNIT_WANTS] = "Wants",
1438 [UNIT_REQUISITE] = "Requisite",
1439 [UNIT_SOFT_REQUISITE] = "SoftRequisite",
1440 [UNIT_REQUIRED_BY] = "RequiredBy",
1441 [UNIT_SOFT_REQUIRED_BY] = "SoftRequiredBy",
1442 [UNIT_WANTED_BY] = "WantedBy",
1443 [UNIT_CONFLICTS] = "Conflicts",
1444 [UNIT_BEFORE] = "Before",
1445 [UNIT_AFTER] = "After",
1446 };
1447
1448 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);
1449
1450 static const char* const kill_mode_table[_KILL_MODE_MAX] = {
1451 [KILL_PROCESS] = "process",
1452 [KILL_PROCESS_GROUP] = "process-group",
1453 [KILL_CONTROL_GROUP] = "control-group"
1454 };
1455
1456 DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);