chiark / gitweb /
job: timeout every job independently of the unit
[elogind.git] / src / 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 #include <sys/stat.h>
31
32 #include "set.h"
33 #include "unit.h"
34 #include "macro.h"
35 #include "strv.h"
36 #include "load-fragment.h"
37 #include "load-dropin.h"
38 #include "log.h"
39 #include "unit-name.h"
40 #include "specifier.h"
41 #include "dbus-unit.h"
42 #include "special.h"
43 #include "cgroup-util.h"
44
45 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
46         [UNIT_SERVICE] = &service_vtable,
47         [UNIT_TIMER] = &timer_vtable,
48         [UNIT_SOCKET] = &socket_vtable,
49         [UNIT_TARGET] = &target_vtable,
50         [UNIT_DEVICE] = &device_vtable,
51         [UNIT_MOUNT] = &mount_vtable,
52         [UNIT_AUTOMOUNT] = &automount_vtable,
53         [UNIT_SNAPSHOT] = &snapshot_vtable,
54         [UNIT_SWAP] = &swap_vtable,
55         [UNIT_PATH] = &path_vtable
56 };
57
58 Unit *unit_new(Manager *m) {
59         Unit *u;
60
61         assert(m);
62
63         if (!(u = new0(Unit, 1)))
64                 return NULL;
65
66         if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
67                 free(u);
68                 return NULL;
69         }
70
71         u->meta.manager = m;
72         u->meta.type = _UNIT_TYPE_INVALID;
73         u->meta.deserialized_job = _JOB_TYPE_INVALID;
74         u->meta.default_dependencies = true;
75
76         return u;
77 }
78
79 bool unit_has_name(Unit *u, const char *name) {
80         assert(u);
81         assert(name);
82
83         return !!set_get(u->meta.names, (char*) name);
84 }
85
86 int unit_add_name(Unit *u, const char *text) {
87         UnitType t;
88         char *s, *i = NULL;
89         int r;
90
91         assert(u);
92         assert(text);
93
94         if (unit_name_is_template(text)) {
95                 if (!u->meta.instance)
96                         return -EINVAL;
97
98                 s = unit_name_replace_instance(text, u->meta.instance);
99         } else
100                 s = strdup(text);
101
102         if (!s)
103                 return -ENOMEM;
104
105         if (!unit_name_is_valid(s)) {
106                 r = -EINVAL;
107                 goto fail;
108         }
109
110         assert_se((t = unit_name_to_type(s)) >= 0);
111
112         if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type) {
113                 r = -EINVAL;
114                 goto fail;
115         }
116
117         if ((r = unit_name_to_instance(s, &i)) < 0)
118                 goto fail;
119
120         if (i && unit_vtable[t]->no_instances)
121                 goto fail;
122
123         /* Ensure that this unit is either instanced or not instanced,
124          * but not both. */
125         if (u->meta.type != _UNIT_TYPE_INVALID && !u->meta.instance != !i) {
126                 r = -EINVAL;
127                 goto fail;
128         }
129
130         if (unit_vtable[t]->no_alias &&
131             !set_isempty(u->meta.names) &&
132             !set_get(u->meta.names, s)) {
133                 r = -EEXIST;
134                 goto fail;
135         }
136
137         if (hashmap_size(u->meta.manager->units) >= MANAGER_MAX_NAMES) {
138                 r = -E2BIG;
139                 goto fail;
140         }
141
142         if ((r = set_put(u->meta.names, s)) < 0) {
143                 if (r == -EEXIST)
144                         r = 0;
145                 goto fail;
146         }
147
148         if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
149                 set_remove(u->meta.names, s);
150                 goto fail;
151         }
152
153         if (u->meta.type == _UNIT_TYPE_INVALID) {
154
155                 u->meta.type = t;
156                 u->meta.id = s;
157                 u->meta.instance = i;
158
159                 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
160
161                 if (UNIT_VTABLE(u)->init)
162                         UNIT_VTABLE(u)->init(u);
163         } else
164                 free(i);
165
166         unit_add_to_dbus_queue(u);
167         return 0;
168
169 fail:
170         free(s);
171         free(i);
172
173         return r;
174 }
175
176 int unit_choose_id(Unit *u, const char *name) {
177         char *s, *t = NULL, *i;
178         int r;
179
180         assert(u);
181         assert(name);
182
183         if (unit_name_is_template(name)) {
184
185                 if (!u->meta.instance)
186                         return -EINVAL;
187
188                 if (!(t = unit_name_replace_instance(name, u->meta.instance)))
189                         return -ENOMEM;
190
191                 name = t;
192         }
193
194         /* Selects one of the names of this unit as the id */
195         s = set_get(u->meta.names, (char*) name);
196         free(t);
197
198         if (!s)
199                 return -ENOENT;
200
201         if ((r = unit_name_to_instance(s, &i)) < 0)
202                 return r;
203
204         u->meta.id = s;
205
206         free(u->meta.instance);
207         u->meta.instance = i;
208
209         unit_add_to_dbus_queue(u);
210
211         return 0;
212 }
213
214 int unit_set_description(Unit *u, const char *description) {
215         char *s;
216
217         assert(u);
218
219         if (!(s = strdup(description)))
220                 return -ENOMEM;
221
222         free(u->meta.description);
223         u->meta.description = s;
224
225         unit_add_to_dbus_queue(u);
226         return 0;
227 }
228
229 bool unit_check_gc(Unit *u) {
230         assert(u);
231
232         if (u->meta.load_state == UNIT_STUB)
233                 return true;
234
235         if (UNIT_VTABLE(u)->no_gc)
236                 return true;
237
238         if (u->meta.job)
239                 return true;
240
241         if (unit_active_state(u) != UNIT_INACTIVE)
242                 return true;
243
244         if (UNIT_VTABLE(u)->check_gc)
245                 if (UNIT_VTABLE(u)->check_gc(u))
246                         return true;
247
248         return false;
249 }
250
251 void unit_add_to_load_queue(Unit *u) {
252         assert(u);
253         assert(u->meta.type != _UNIT_TYPE_INVALID);
254
255         if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
256                 return;
257
258         LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
259         u->meta.in_load_queue = true;
260 }
261
262 void unit_add_to_cleanup_queue(Unit *u) {
263         assert(u);
264
265         if (u->meta.in_cleanup_queue)
266                 return;
267
268         LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
269         u->meta.in_cleanup_queue = true;
270 }
271
272 void unit_add_to_gc_queue(Unit *u) {
273         assert(u);
274
275         if (u->meta.in_gc_queue || u->meta.in_cleanup_queue)
276                 return;
277
278         if (unit_check_gc(u))
279                 return;
280
281         LIST_PREPEND(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
282         u->meta.in_gc_queue = true;
283
284         u->meta.manager->n_in_gc_queue ++;
285
286         if (u->meta.manager->gc_queue_timestamp <= 0)
287                 u->meta.manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
288 }
289
290 void unit_add_to_dbus_queue(Unit *u) {
291         assert(u);
292         assert(u->meta.type != _UNIT_TYPE_INVALID);
293
294         if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue)
295                 return;
296
297         /* Shortcut things if nobody cares */
298         if (!bus_has_subscriber(u->meta.manager)) {
299                 u->meta.sent_dbus_new_signal = true;
300                 return;
301         }
302
303         LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
304         u->meta.in_dbus_queue = true;
305 }
306
307 static void bidi_set_free(Unit *u, Set *s) {
308         Iterator i;
309         Unit *other;
310
311         assert(u);
312
313         /* Frees the set and makes sure we are dropped from the
314          * inverse pointers */
315
316         SET_FOREACH(other, s, i) {
317                 UnitDependency d;
318
319                 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
320                         set_remove(other->meta.dependencies[d], u);
321
322                 unit_add_to_gc_queue(other);
323         }
324
325         set_free(s);
326 }
327
328 void unit_free(Unit *u) {
329         UnitDependency d;
330         Iterator i;
331         char *t;
332
333         assert(u);
334
335         bus_unit_send_removed_signal(u);
336
337         if (u->meta.load_state != UNIT_STUB)
338                 if (UNIT_VTABLE(u)->done)
339                         UNIT_VTABLE(u)->done(u);
340
341         SET_FOREACH(t, u->meta.names, i)
342                 hashmap_remove_value(u->meta.manager->units, t, u);
343
344         if (u->meta.job)
345                 job_free(u->meta.job);
346
347         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
348                 bidi_set_free(u, u->meta.dependencies[d]);
349
350         if (u->meta.type != _UNIT_TYPE_INVALID)
351                 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
352
353         if (u->meta.in_load_queue)
354                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
355
356         if (u->meta.in_dbus_queue)
357                 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
358
359         if (u->meta.in_cleanup_queue)
360                 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
361
362         if (u->meta.in_gc_queue) {
363                 LIST_REMOVE(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
364                 u->meta.manager->n_in_gc_queue--;
365         }
366
367         cgroup_bonding_free_list(u->meta.cgroup_bondings);
368
369         free(u->meta.description);
370         free(u->meta.fragment_path);
371
372         set_free_free(u->meta.names);
373
374         free(u->meta.instance);
375
376         free(u);
377 }
378
379 UnitActiveState unit_active_state(Unit *u) {
380         assert(u);
381
382         if (u->meta.load_state == UNIT_MERGED)
383                 return unit_active_state(unit_follow_merge(u));
384
385         /* After a reload it might happen that a unit is not correctly
386          * loaded but still has a process around. That's why we won't
387          * shortcut failed loading to UNIT_INACTIVE_MAINTENANCE. */
388
389         return UNIT_VTABLE(u)->active_state(u);
390 }
391
392 const char* unit_sub_state_to_string(Unit *u) {
393         assert(u);
394
395         return UNIT_VTABLE(u)->sub_state_to_string(u);
396 }
397
398 static void complete_move(Set **s, Set **other) {
399         assert(s);
400         assert(other);
401
402         if (!*other)
403                 return;
404
405         if (*s)
406                 set_move(*s, *other);
407         else {
408                 *s = *other;
409                 *other = NULL;
410         }
411 }
412
413 static void merge_names(Unit *u, Unit *other) {
414         char *t;
415         Iterator i;
416
417         assert(u);
418         assert(other);
419
420         complete_move(&u->meta.names, &other->meta.names);
421
422         set_free_free(other->meta.names);
423         other->meta.names = NULL;
424         other->meta.id = NULL;
425
426         SET_FOREACH(t, u->meta.names, i)
427                 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
428 }
429
430 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
431         Iterator i;
432         Unit *back;
433         int r;
434
435         assert(u);
436         assert(other);
437         assert(d < _UNIT_DEPENDENCY_MAX);
438
439         SET_FOREACH(back, other->meta.dependencies[d], i) {
440                 UnitDependency k;
441
442                 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
443                         if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
444
445                                 if (r == -EEXIST)
446                                         set_remove(back->meta.dependencies[k], other);
447                                 else
448                                         assert(r == -ENOENT);
449                         }
450         }
451
452         complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
453
454         set_free(other->meta.dependencies[d]);
455         other->meta.dependencies[d] = NULL;
456 }
457
458 int unit_merge(Unit *u, Unit *other) {
459         UnitDependency d;
460
461         assert(u);
462         assert(other);
463         assert(u->meta.manager == other->meta.manager);
464         assert(u->meta.type != _UNIT_TYPE_INVALID);
465
466         other = unit_follow_merge(other);
467
468         if (other == u)
469                 return 0;
470
471         if (u->meta.type != other->meta.type)
472                 return -EINVAL;
473
474         if (!u->meta.instance != !other->meta.instance)
475                 return -EINVAL;
476
477         if (other->meta.load_state != UNIT_STUB &&
478             other->meta.load_state != UNIT_FAILED)
479                 return -EEXIST;
480
481         if (other->meta.job)
482                 return -EEXIST;
483
484         if (!UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(other)))
485                 return -EEXIST;
486
487         /* Merge names */
488         merge_names(u, other);
489
490         /* Merge dependencies */
491         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
492                 merge_dependencies(u, other, d);
493
494         other->meta.load_state = UNIT_MERGED;
495         other->meta.merged_into = u;
496
497         /* If there is still some data attached to the other node, we
498          * don't need it anymore, and can free it. */
499         if (other->meta.load_state != UNIT_STUB)
500                 if (UNIT_VTABLE(other)->done)
501                         UNIT_VTABLE(other)->done(other);
502
503         unit_add_to_dbus_queue(u);
504         unit_add_to_cleanup_queue(other);
505
506         return 0;
507 }
508
509 int unit_merge_by_name(Unit *u, const char *name) {
510         Unit *other;
511         int r;
512         char *s = NULL;
513
514         assert(u);
515         assert(name);
516
517         if (unit_name_is_template(name)) {
518                 if (!u->meta.instance)
519                         return -EINVAL;
520
521                 if (!(s = unit_name_replace_instance(name, u->meta.instance)))
522                         return -ENOMEM;
523
524                 name = s;
525         }
526
527         if (!(other = manager_get_unit(u->meta.manager, name)))
528                 r = unit_add_name(u, name);
529         else
530                 r = unit_merge(u, other);
531
532         free(s);
533         return r;
534 }
535
536 Unit* unit_follow_merge(Unit *u) {
537         assert(u);
538
539         while (u->meta.load_state == UNIT_MERGED)
540                 assert_se(u = u->meta.merged_into);
541
542         return u;
543 }
544
545 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
546         int r;
547
548         assert(u);
549         assert(c);
550
551         if (c->std_output != EXEC_OUTPUT_KMSG &&
552             c->std_output != EXEC_OUTPUT_SYSLOG &&
553             c->std_error != EXEC_OUTPUT_KMSG &&
554             c->std_error != EXEC_OUTPUT_SYSLOG)
555                 return 0;
556
557         /* If syslog or kernel logging is requested, make sure our own
558          * logging daemon is run first. */
559
560         if ((r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
561                 return r;
562
563         if (u->meta.manager->running_as == MANAGER_SYSTEM)
564                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
565                         return r;
566
567         return 0;
568 }
569
570 const char *unit_description(Unit *u) {
571         assert(u);
572
573         if (u->meta.description)
574                 return u->meta.description;
575
576         return u->meta.id;
577 }
578
579 void unit_dump(Unit *u, FILE *f, const char *prefix) {
580         char *t;
581         UnitDependency d;
582         Iterator i;
583         char *p2;
584         const char *prefix2;
585         CGroupBonding *b;
586         char
587                 timestamp1[FORMAT_TIMESTAMP_MAX],
588                 timestamp2[FORMAT_TIMESTAMP_MAX],
589                 timestamp3[FORMAT_TIMESTAMP_MAX],
590                 timestamp4[FORMAT_TIMESTAMP_MAX],
591                 timespan[FORMAT_TIMESPAN_MAX];
592
593         assert(u);
594         assert(u->meta.type >= 0);
595
596         if (!prefix)
597                 prefix = "";
598         p2 = strappend(prefix, "\t");
599         prefix2 = p2 ? p2 : prefix;
600
601         fprintf(f,
602                 "%s-> Unit %s:\n"
603                 "%s\tDescription: %s\n"
604                 "%s\tInstance: %s\n"
605                 "%s\tUnit Load State: %s\n"
606                 "%s\tUnit Active State: %s\n"
607                 "%s\tInactive Exit Timestamp: %s\n"
608                 "%s\tActive Enter Timestamp: %s\n"
609                 "%s\tActive Exit Timestamp: %s\n"
610                 "%s\tInactive Enter Timestamp: %s\n"
611                 "%s\tGC Check Good: %s\n"
612                 "%s\tNeed Daemon Reload: %s\n",
613                 prefix, u->meta.id,
614                 prefix, unit_description(u),
615                 prefix, strna(u->meta.instance),
616                 prefix, unit_load_state_to_string(u->meta.load_state),
617                 prefix, unit_active_state_to_string(unit_active_state(u)),
618                 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp.realtime)),
619                 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp.realtime)),
620                 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp.realtime)),
621                 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp.realtime)),
622                 prefix, yes_no(unit_check_gc(u)),
623                 prefix, yes_no(unit_need_daemon_reload(u)));
624
625         SET_FOREACH(t, u->meta.names, i)
626                 fprintf(f, "%s\tName: %s\n", prefix, t);
627
628         if (u->meta.fragment_path)
629                 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
630
631         if (u->meta.job_timeout > 0)
632                 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->meta.job_timeout));
633
634         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
635                 Unit *other;
636
637                 SET_FOREACH(other, u->meta.dependencies[d], i)
638                         fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
639         }
640
641         if (u->meta.load_state == UNIT_LOADED) {
642                 fprintf(f,
643                         "%s\tRecursive Stop: %s\n"
644                         "%s\tStopWhenUnneeded: %s\n"
645                         "%s\tOnlyByDependency: %s\n"
646                         "%s\tDefaultDependencies: %s\n"
647                         "%s\tIgnoreDependencyFailure: %s\n",
648                         prefix, yes_no(u->meta.recursive_stop),
649                         prefix, yes_no(u->meta.stop_when_unneeded),
650                         prefix, yes_no(u->meta.only_by_dependency),
651                         prefix, yes_no(u->meta.default_dependencies),
652                         prefix, yes_no(u->meta.ignore_dependency_failure));
653
654                 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
655                         fprintf(f, "%s\tControlGroup: %s:%s\n",
656                                 prefix, b->controller, b->path);
657
658                 if (UNIT_VTABLE(u)->dump)
659                         UNIT_VTABLE(u)->dump(u, f, prefix2);
660
661         } else if (u->meta.load_state == UNIT_MERGED)
662                 fprintf(f,
663                         "%s\tMerged into: %s\n",
664                         prefix, u->meta.merged_into->meta.id);
665
666         if (u->meta.job)
667                 job_dump(u->meta.job, f, prefix2);
668
669         free(p2);
670 }
671
672 /* Common implementation for multiple backends */
673 int unit_load_fragment_and_dropin(Unit *u) {
674         int r;
675
676         assert(u);
677
678         /* Load a .service file */
679         if ((r = unit_load_fragment(u)) < 0)
680                 return r;
681
682         if (u->meta.load_state == UNIT_STUB)
683                 return -ENOENT;
684
685         /* Load drop-in directory data */
686         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
687                 return r;
688
689         return 0;
690 }
691
692 /* Common implementation for multiple backends */
693 int unit_load_fragment_and_dropin_optional(Unit *u) {
694         int r;
695
696         assert(u);
697
698         /* Same as unit_load_fragment_and_dropin(), but whether
699          * something can be loaded or not doesn't matter. */
700
701         /* Load a .service file */
702         if ((r = unit_load_fragment(u)) < 0)
703                 return r;
704
705         if (u->meta.load_state == UNIT_STUB)
706                 u->meta.load_state = UNIT_LOADED;
707
708         /* Load drop-in directory data */
709         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
710                 return r;
711
712         return 0;
713 }
714
715 /* Common implementation for multiple backends */
716 int unit_load_nop(Unit *u) {
717         assert(u);
718
719         if (u->meta.load_state == UNIT_STUB)
720                 u->meta.load_state = UNIT_LOADED;
721
722         return 0;
723 }
724
725 int unit_load(Unit *u) {
726         int r;
727
728         assert(u);
729
730         if (u->meta.in_load_queue) {
731                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
732                 u->meta.in_load_queue = false;
733         }
734
735         if (u->meta.type == _UNIT_TYPE_INVALID)
736                 return -EINVAL;
737
738         if (u->meta.load_state != UNIT_STUB)
739                 return 0;
740
741         if (UNIT_VTABLE(u)->load)
742                 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
743                         goto fail;
744
745         if (u->meta.load_state == UNIT_STUB) {
746                 r = -ENOENT;
747                 goto fail;
748         }
749
750         assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
751
752         unit_add_to_dbus_queue(unit_follow_merge(u));
753         unit_add_to_gc_queue(u);
754
755         return 0;
756
757 fail:
758         u->meta.load_state = UNIT_FAILED;
759         unit_add_to_dbus_queue(u);
760
761         log_notice("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
762
763         return r;
764 }
765
766 /* Errors:
767  *         -EBADR:     This unit type does not support starting.
768  *         -EALREADY:  Unit is already started.
769  *         -EAGAIN:    An operation is already in progress. Retry later.
770  *         -ECANCELED: Too many requests for now.
771  */
772 int unit_start(Unit *u) {
773         UnitActiveState state;
774
775         assert(u);
776
777         if (u->meta.load_state != UNIT_LOADED)
778                 return -EINVAL;
779
780         /* If this is already (being) started, then this will
781          * succeed. Note that this will even succeed if this unit is
782          * not startable by the user. This is relied on to detect when
783          * we need to wait for units and when waiting is finished. */
784         state = unit_active_state(u);
785         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
786                 return -EALREADY;
787
788         /* If it is stopped, but we cannot start it, then fail */
789         if (!UNIT_VTABLE(u)->start)
790                 return -EBADR;
791
792         /* We don't suppress calls to ->start() here when we are
793          * already starting, to allow this request to be used as a
794          * "hurry up" call, for example when the unit is in some "auto
795          * restart" state where it waits for a holdoff timer to elapse
796          * before it will start again. */
797
798         unit_add_to_dbus_queue(u);
799
800         unit_status_printf(u, "Starting %s...\n", unit_description(u));
801
802         return UNIT_VTABLE(u)->start(u);
803 }
804
805 bool unit_can_start(Unit *u) {
806         assert(u);
807
808         return !!UNIT_VTABLE(u)->start;
809 }
810
811 /* Errors:
812  *         -EBADR:    This unit type does not support stopping.
813  *         -EALREADY: Unit is already stopped.
814  *         -EAGAIN:   An operation is already in progress. Retry later.
815  */
816 int unit_stop(Unit *u) {
817         UnitActiveState state;
818
819         assert(u);
820
821         state = unit_active_state(u);
822         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(state))
823                 return -EALREADY;
824
825         if (!UNIT_VTABLE(u)->stop)
826                 return -EBADR;
827
828         unit_add_to_dbus_queue(u);
829
830         unit_status_printf(u, "Stopping %s...\n", unit_description(u));
831
832         return UNIT_VTABLE(u)->stop(u);
833 }
834
835 /* Errors:
836  *         -EBADR:    This unit type does not support reloading.
837  *         -ENOEXEC:  Unit is not started.
838  *         -EAGAIN:   An operation is already in progress. Retry later.
839  */
840 int unit_reload(Unit *u) {
841         UnitActiveState state;
842
843         assert(u);
844
845         if (u->meta.load_state != UNIT_LOADED)
846                 return -EINVAL;
847
848         if (!unit_can_reload(u))
849                 return -EBADR;
850
851         state = unit_active_state(u);
852         if (unit_active_state(u) == UNIT_RELOADING)
853                 return -EALREADY;
854
855         if (unit_active_state(u) != UNIT_ACTIVE)
856                 return -ENOEXEC;
857
858         unit_add_to_dbus_queue(u);
859         return UNIT_VTABLE(u)->reload(u);
860 }
861
862 bool unit_can_reload(Unit *u) {
863         assert(u);
864
865         if (!UNIT_VTABLE(u)->reload)
866                 return false;
867
868         if (!UNIT_VTABLE(u)->can_reload)
869                 return true;
870
871         return UNIT_VTABLE(u)->can_reload(u);
872 }
873
874 static void unit_check_uneeded(Unit *u) {
875         Iterator i;
876         Unit *other;
877
878         assert(u);
879
880         /* If this service shall be shut down when unneeded then do
881          * so. */
882
883         if (!u->meta.stop_when_unneeded)
884                 return;
885
886         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
887                 return;
888
889         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
890                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
891                         return;
892
893         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
894                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
895                         return;
896
897         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
898                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
899                         return;
900
901         log_info("Service %s is not needed anymore. Stopping.", u->meta.id);
902
903         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
904         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
905 }
906
907 static void retroactively_start_dependencies(Unit *u) {
908         Iterator i;
909         Unit *other;
910
911         assert(u);
912         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
913
914         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
915                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
916                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
917
918         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
919                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
920                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
921
922         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
923                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
924                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
925
926         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
927                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
928                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
929
930         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
931                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
932                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
933 }
934
935 static void retroactively_stop_dependencies(Unit *u) {
936         Iterator i;
937         Unit *other;
938
939         assert(u);
940         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
941
942         if (u->meta.recursive_stop) {
943                 /* Pull down units need us recursively if enabled */
944                 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
945                         if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
946                                 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
947         }
948
949         /* Garbage collect services that might not be needed anymore, if enabled */
950         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
951                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
952                         unit_check_uneeded(other);
953         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
954                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
955                         unit_check_uneeded(other);
956         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
957                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
958                         unit_check_uneeded(other);
959         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
960                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
961                         unit_check_uneeded(other);
962         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
963                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
964                         unit_check_uneeded(other);
965 }
966
967 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
968         dual_timestamp ts;
969         bool unexpected;
970
971         assert(u);
972         assert(os < _UNIT_ACTIVE_STATE_MAX);
973         assert(ns < _UNIT_ACTIVE_STATE_MAX);
974
975         /* Note that this is called for all low-level state changes,
976          * even if they might map to the same high-level
977          * UnitActiveState! That means that ns == os is OK an expected
978          * behaviour here. For example: if a mount point is remounted
979          * this function will be called too and the utmp code below
980          * relies on that! */
981
982         dual_timestamp_get(&ts);
983
984         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(os) && !UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
985                 u->meta.inactive_exit_timestamp = ts;
986         else if (!UNIT_IS_INACTIVE_OR_MAINTENANCE(os) && UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
987                 u->meta.inactive_enter_timestamp = ts;
988
989         if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
990                 u->meta.active_enter_timestamp = ts;
991         else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
992                 u->meta.active_exit_timestamp = ts;
993
994         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
995                 cgroup_bonding_trim_list(u->meta.cgroup_bondings, true);
996
997         timer_unit_notify(u, ns);
998         path_unit_notify(u, ns);
999
1000         if (u->meta.job) {
1001                 unexpected = false;
1002
1003                 if (u->meta.job->state == JOB_WAITING)
1004
1005                         /* So we reached a different state for this
1006                          * job. Let's see if we can run it now if it
1007                          * failed previously due to EAGAIN. */
1008                         job_add_to_run_queue(u->meta.job);
1009
1010                 /* Let's check whether this state change constitutes a
1011                  * finished job, or maybe cotradicts a running job and
1012                  * hence needs to invalidate jobs. */
1013
1014                 switch (u->meta.job->type) {
1015
1016                 case JOB_START:
1017                 case JOB_VERIFY_ACTIVE:
1018
1019                         if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1020                                 job_finish_and_invalidate(u->meta.job, true);
1021                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1022                                 unexpected = true;
1023                                 job_finish_and_invalidate(u->meta.job, false);
1024                         }
1025
1026                         break;
1027
1028                 case JOB_RELOAD:
1029                 case JOB_RELOAD_OR_START:
1030
1031                         if (u->meta.job->state == JOB_RUNNING) {
1032                                 if (ns == UNIT_ACTIVE)
1033                                         job_finish_and_invalidate(u->meta.job, true);
1034                                 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1035                                         unexpected = true;
1036                                         job_finish_and_invalidate(u->meta.job, false);
1037                                 }
1038                         }
1039
1040                         break;
1041
1042                 case JOB_STOP:
1043                 case JOB_RESTART:
1044                 case JOB_TRY_RESTART:
1045
1046                         if (ns == UNIT_INACTIVE || ns == UNIT_MAINTENANCE)
1047                                 job_finish_and_invalidate(u->meta.job, true);
1048                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1049                                 unexpected = true;
1050                                 job_finish_and_invalidate(u->meta.job, false);
1051                         }
1052
1053                         break;
1054
1055                 default:
1056                         assert_not_reached("Job type unknown");
1057                 }
1058
1059         } else
1060                 unexpected = true;
1061
1062         /* If this state change happened without being requested by a
1063          * job, then let's retroactively start or stop
1064          * dependencies. We skip that step when deserializing, since
1065          * we don't want to create any additional jobs just because
1066          * something is already activated. */
1067
1068         if (unexpected && u->meta.manager->n_deserializing <= 0) {
1069                 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1070                         retroactively_start_dependencies(u);
1071                 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1072                         retroactively_stop_dependencies(u);
1073         }
1074
1075         if (ns != os && ns == UNIT_MAINTENANCE) {
1076                 Iterator i;
1077                 Unit *other;
1078
1079                 SET_FOREACH(other, u->meta.dependencies[UNIT_ON_FAILURE], i)
1080                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1081
1082                 log_notice("Unit %s entered maintenance state.", u->meta.id);
1083         }
1084
1085         /* Some names are special */
1086         if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1087                 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
1088                         /* The bus just might have become available,
1089                          * hence try to connect to it, if we aren't
1090                          * yet connected. */
1091                         bus_init(u->meta.manager);
1092                 }
1093
1094                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1095                         /* The syslog daemon just might have become
1096                          * available, hence try to connect to it, if
1097                          * we aren't yet connected. */
1098                         log_open();
1099
1100                 if (u->meta.type == UNIT_MOUNT)
1101                         /* Another directory became available, let's
1102                          * check if that is enough to write our utmp
1103                          * entry. */
1104                         manager_write_utmp_reboot(u->meta.manager);
1105
1106                 if (u->meta.type == UNIT_TARGET)
1107                         /* A target got activated, maybe this is a runlevel? */
1108                         manager_write_utmp_runlevel(u->meta.manager, u);
1109
1110         } else if (!UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1111
1112                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1113                         /* The syslog daemon might just have
1114                          * terminated, hence try to disconnect from
1115                          * it. */
1116                         log_close_syslog();
1117
1118                 /* We don't care about D-Bus here, since we'll get an
1119                  * asynchronous notification for it anyway. */
1120         }
1121
1122         /* Maybe we finished startup and are now ready for being
1123          * stopped because unneeded? */
1124         unit_check_uneeded(u);
1125
1126         unit_add_to_dbus_queue(u);
1127         unit_add_to_gc_queue(u);
1128 }
1129
1130 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1131         struct epoll_event ev;
1132
1133         assert(u);
1134         assert(fd >= 0);
1135         assert(w);
1136         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1137
1138         zero(ev);
1139         ev.data.ptr = w;
1140         ev.events = events;
1141
1142         if (epoll_ctl(u->meta.manager->epoll_fd,
1143                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1144                       fd,
1145                       &ev) < 0)
1146                 return -errno;
1147
1148         w->fd = fd;
1149         w->type = WATCH_FD;
1150         w->data.unit = u;
1151
1152         return 0;
1153 }
1154
1155 void unit_unwatch_fd(Unit *u, Watch *w) {
1156         assert(u);
1157         assert(w);
1158
1159         if (w->type == WATCH_INVALID)
1160                 return;
1161
1162         assert(w->type == WATCH_FD);
1163         assert(w->data.unit == u);
1164         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1165
1166         w->fd = -1;
1167         w->type = WATCH_INVALID;
1168         w->data.unit = NULL;
1169 }
1170
1171 int unit_watch_pid(Unit *u, pid_t pid) {
1172         assert(u);
1173         assert(pid >= 1);
1174
1175         /* Watch a specific PID. We only support one unit watching
1176          * each PID for now. */
1177
1178         return hashmap_put(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1179 }
1180
1181 void unit_unwatch_pid(Unit *u, pid_t pid) {
1182         assert(u);
1183         assert(pid >= 1);
1184
1185         hashmap_remove_value(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1186 }
1187
1188 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1189         struct itimerspec its;
1190         int flags, fd;
1191         bool ours;
1192
1193         assert(u);
1194         assert(w);
1195         assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1196
1197         /* This will try to reuse the old timer if there is one */
1198
1199         if (w->type == WATCH_UNIT_TIMER) {
1200                 assert(w->data.unit == u);
1201                 assert(w->fd >= 0);
1202
1203                 ours = false;
1204                 fd = w->fd;
1205         } else if (w->type == WATCH_INVALID) {
1206
1207                 ours = true;
1208                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1209                         return -errno;
1210         } else
1211                 assert_not_reached("Invalid watch type");
1212
1213         zero(its);
1214
1215         if (delay <= 0) {
1216                 /* Set absolute time in the past, but not 0, since we
1217                  * don't want to disarm the timer */
1218                 its.it_value.tv_sec = 0;
1219                 its.it_value.tv_nsec = 1;
1220
1221                 flags = TFD_TIMER_ABSTIME;
1222         } else {
1223                 timespec_store(&its.it_value, delay);
1224                 flags = 0;
1225         }
1226
1227         /* This will also flush the elapse counter */
1228         if (timerfd_settime(fd, flags, &its, NULL) < 0)
1229                 goto fail;
1230
1231         if (w->type == WATCH_INVALID) {
1232                 struct epoll_event ev;
1233
1234                 zero(ev);
1235                 ev.data.ptr = w;
1236                 ev.events = EPOLLIN;
1237
1238                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1239                         goto fail;
1240         }
1241
1242         w->type = WATCH_UNIT_TIMER;
1243         w->fd = fd;
1244         w->data.unit = u;
1245
1246         return 0;
1247
1248 fail:
1249         if (ours)
1250                 close_nointr_nofail(fd);
1251
1252         return -errno;
1253 }
1254
1255 void unit_unwatch_timer(Unit *u, Watch *w) {
1256         assert(u);
1257         assert(w);
1258
1259         if (w->type == WATCH_INVALID)
1260                 return;
1261
1262         assert(w->type == WATCH_UNIT_TIMER);
1263         assert(w->data.unit == u);
1264         assert(w->fd >= 0);
1265
1266         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1267         close_nointr_nofail(w->fd);
1268
1269         w->fd = -1;
1270         w->type = WATCH_INVALID;
1271         w->data.unit = NULL;
1272 }
1273
1274 bool unit_job_is_applicable(Unit *u, JobType j) {
1275         assert(u);
1276         assert(j >= 0 && j < _JOB_TYPE_MAX);
1277
1278         switch (j) {
1279
1280         case JOB_VERIFY_ACTIVE:
1281         case JOB_START:
1282                 return true;
1283
1284         case JOB_STOP:
1285         case JOB_RESTART:
1286         case JOB_TRY_RESTART:
1287                 return unit_can_start(u);
1288
1289         case JOB_RELOAD:
1290                 return unit_can_reload(u);
1291
1292         case JOB_RELOAD_OR_START:
1293                 return unit_can_reload(u) && unit_can_start(u);
1294
1295         default:
1296                 assert_not_reached("Invalid job type");
1297         }
1298 }
1299
1300 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1301
1302         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1303                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1304                 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1305                 [UNIT_WANTS] = UNIT_WANTED_BY,
1306                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1307                 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1308                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1309                 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1310                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1311                 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
1312                 [UNIT_BEFORE] = UNIT_AFTER,
1313                 [UNIT_AFTER] = UNIT_BEFORE,
1314                 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1315                 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1316                 [UNIT_REFERENCED_BY] = UNIT_REFERENCES
1317         };
1318         int r, q = 0, v = 0, w = 0;
1319
1320         assert(u);
1321         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1322         assert(other);
1323
1324         /* We won't allow dependencies on ourselves. We will not
1325          * consider them an error however. */
1326         if (u == other)
1327                 return 0;
1328
1329         if (UNIT_VTABLE(u)->no_requires &&
1330             (d == UNIT_REQUIRES ||
1331              d == UNIT_REQUIRES_OVERRIDABLE ||
1332              d == UNIT_REQUISITE ||
1333              d == UNIT_REQUISITE_OVERRIDABLE)) {
1334                     return -EINVAL;
1335         }
1336
1337         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1338                 return r;
1339
1340         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1341                 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1342                         return r;
1343
1344         if (add_reference)
1345                 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1346                     (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1347                         return r;
1348
1349         if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1350                 return q;
1351
1352         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1353                 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1354                         r = v;
1355                         goto fail;
1356                 }
1357
1358         if (add_reference) {
1359                 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1360                         r = w;
1361                         goto fail;
1362                 }
1363
1364                 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1365                         goto fail;
1366         }
1367
1368         unit_add_to_dbus_queue(u);
1369         return 0;
1370
1371 fail:
1372         if (q > 0)
1373                 set_remove(u->meta.dependencies[d], other);
1374
1375         if (v > 0)
1376                 set_remove(other->meta.dependencies[inverse_table[d]], u);
1377
1378         if (w > 0)
1379                 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1380
1381         return r;
1382 }
1383
1384 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1385         int r;
1386
1387         assert(u);
1388
1389         if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1390                 return r;
1391
1392         if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1393                 return r;
1394
1395         return 0;
1396 }
1397
1398 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1399         char *s;
1400
1401         assert(u);
1402         assert(name || path);
1403
1404         if (!name)
1405                 name = file_name_from_path(path);
1406
1407         if (!unit_name_is_template(name)) {
1408                 *p = NULL;
1409                 return name;
1410         }
1411
1412         if (u->meta.instance)
1413                 s = unit_name_replace_instance(name, u->meta.instance);
1414         else {
1415                 char *i;
1416
1417                 if (!(i = unit_name_to_prefix(u->meta.id)))
1418                         return NULL;
1419
1420                 s = unit_name_replace_instance(name, i);
1421                 free(i);
1422         }
1423
1424         if (!s)
1425                 return NULL;
1426
1427         *p = s;
1428         return s;
1429 }
1430
1431 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1432         Unit *other;
1433         int r;
1434         char *s;
1435
1436         assert(u);
1437         assert(name || path);
1438
1439         if (!(name = resolve_template(u, name, path, &s)))
1440                 return -ENOMEM;
1441
1442         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1443                 goto finish;
1444
1445         r = unit_add_dependency(u, d, other, add_reference);
1446
1447 finish:
1448         free(s);
1449         return r;
1450 }
1451
1452 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1453         Unit *other;
1454         int r;
1455         char *s;
1456
1457         assert(u);
1458         assert(name || path);
1459
1460         if (!(name = resolve_template(u, name, path, &s)))
1461                 return -ENOMEM;
1462
1463         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1464                 goto finish;
1465
1466         r = unit_add_two_dependencies(u, d, e, other, add_reference);
1467
1468 finish:
1469         free(s);
1470         return r;
1471 }
1472
1473 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1474         Unit *other;
1475         int r;
1476         char *s;
1477
1478         assert(u);
1479         assert(name || path);
1480
1481         if (!(name = resolve_template(u, name, path, &s)))
1482                 return -ENOMEM;
1483
1484         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1485                 goto finish;
1486
1487         r = unit_add_dependency(other, d, u, add_reference);
1488
1489 finish:
1490         free(s);
1491         return r;
1492 }
1493
1494 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1495         Unit *other;
1496         int r;
1497         char *s;
1498
1499         assert(u);
1500         assert(name || path);
1501
1502         if (!(name = resolve_template(u, name, path, &s)))
1503                 return -ENOMEM;
1504
1505         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1506                 goto finish;
1507
1508         if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1509                 goto finish;
1510
1511 finish:
1512         free(s);
1513         return r;
1514 }
1515
1516 int set_unit_path(const char *p) {
1517         char *cwd, *c;
1518         int r;
1519
1520         /* This is mostly for debug purposes */
1521
1522         if (path_is_absolute(p)) {
1523                 if (!(c = strdup(p)))
1524                         return -ENOMEM;
1525         } else {
1526                 if (!(cwd = get_current_dir_name()))
1527                         return -errno;
1528
1529                 r = asprintf(&c, "%s/%s", cwd, p);
1530                 free(cwd);
1531
1532                 if (r < 0)
1533                         return -ENOMEM;
1534         }
1535
1536         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1537                 r = -errno;
1538                 free(c);
1539                 return r;
1540         }
1541
1542         return 0;
1543 }
1544
1545 char *unit_dbus_path(Unit *u) {
1546         char *p, *e;
1547
1548         assert(u);
1549
1550         if (!(e = bus_path_escape(u->meta.id)))
1551                 return NULL;
1552
1553         p = strappend("/org/freedesktop/systemd1/unit/", e);
1554         free(e);
1555
1556         return p;
1557 }
1558
1559 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1560         CGroupBonding *l;
1561         int r;
1562
1563         assert(u);
1564         assert(b);
1565
1566         assert(b->path);
1567
1568         if (!b->controller)
1569                 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1570                         return -ENOMEM;
1571
1572         /* Ensure this hasn't been added yet */
1573         assert(!b->unit);
1574
1575         l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1576         LIST_PREPEND(CGroupBonding, by_path, l, b);
1577
1578         if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1579                 LIST_REMOVE(CGroupBonding, by_path, l, b);
1580                 return r;
1581         }
1582
1583         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1584         b->unit = u;
1585
1586         return 0;
1587 }
1588
1589 static char *default_cgroup_path(Unit *u) {
1590         char *p;
1591         int r;
1592
1593         assert(u);
1594
1595         if (u->meta.instance) {
1596                 char *t;
1597
1598                 if (!(t = unit_name_template(u->meta.id)))
1599                         return NULL;
1600
1601                 r = asprintf(&p, "%s/%s/%s", u->meta.manager->cgroup_hierarchy, t, u->meta.instance);
1602                 free(t);
1603         } else
1604                 r = asprintf(&p, "%s/%s", u->meta.manager->cgroup_hierarchy, u->meta.id);
1605
1606         return r < 0 ? NULL : p;
1607 }
1608
1609 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1610         char *controller = NULL, *path = NULL;
1611         CGroupBonding *b = NULL;
1612         int r;
1613
1614         assert(u);
1615         assert(name);
1616
1617         if ((r = cg_split_spec(name, &controller, &path)) < 0)
1618                 return r;
1619
1620         if (!path)
1621                 path = default_cgroup_path(u);
1622
1623         if (!controller)
1624                 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1625
1626         if (!path || !controller) {
1627                 free(path);
1628                 free(controller);
1629
1630                 return -ENOMEM;
1631         }
1632
1633         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1634                 r = -EEXIST;
1635                 goto fail;
1636         }
1637
1638         if (!(b = new0(CGroupBonding, 1))) {
1639                 r = -ENOMEM;
1640                 goto fail;
1641         }
1642
1643         b->controller = controller;
1644         b->path = path;
1645         b->only_us = false;
1646         b->clean_up = false;
1647
1648         if ((r = unit_add_cgroup(u, b)) < 0)
1649                 goto fail;
1650
1651         return 0;
1652
1653 fail:
1654         free(path);
1655         free(controller);
1656         free(b);
1657
1658         return r;
1659 }
1660
1661 int unit_add_default_cgroup(Unit *u) {
1662         CGroupBonding *b;
1663         int r = -ENOMEM;
1664
1665         assert(u);
1666
1667         /* Adds in the default cgroup data, if it wasn't specified yet */
1668
1669         if (unit_get_default_cgroup(u))
1670                 return 0;
1671
1672         if (!(b = new0(CGroupBonding, 1)))
1673                 return -ENOMEM;
1674
1675         if (!(b->path = default_cgroup_path(u)))
1676                 goto fail;
1677
1678         b->clean_up = true;
1679         b->only_us = true;
1680
1681         if ((r = unit_add_cgroup(u, b)) < 0)
1682                 goto fail;
1683
1684         return 0;
1685
1686 fail:
1687         free(b->path);
1688         free(b->controller);
1689         free(b);
1690
1691         return r;
1692 }
1693
1694 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1695         assert(u);
1696
1697         return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1698 }
1699
1700 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
1701         char *t;
1702         int r;
1703
1704         assert(u);
1705         assert(type);
1706         assert(_found);
1707
1708         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1709                 return -ENOMEM;
1710
1711         assert(!unit_has_name(u, t));
1712
1713         r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
1714         free(t);
1715
1716         assert(r < 0 || *_found != u);
1717
1718         return r;
1719 }
1720
1721 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
1722         Unit *found;
1723         char *t;
1724
1725         assert(u);
1726         assert(type);
1727         assert(_found);
1728
1729         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1730                 return -ENOMEM;
1731
1732         assert(!unit_has_name(u, t));
1733
1734         found = manager_get_unit(u->meta.manager, t);
1735         free(t);
1736
1737         if (!found)
1738                 return -ENOENT;
1739
1740         *_found = found;
1741         return 0;
1742 }
1743
1744 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
1745         Unit *u = userdata;
1746         assert(u);
1747
1748         return unit_name_to_prefix_and_instance(u->meta.id);
1749 }
1750
1751 static char *specifier_prefix(char specifier, void *data, void *userdata) {
1752         Unit *u = userdata;
1753         assert(u);
1754
1755         return unit_name_to_prefix(u->meta.id);
1756 }
1757
1758 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
1759         Unit *u = userdata;
1760         char *p, *r;
1761
1762         assert(u);
1763
1764         if (!(p = unit_name_to_prefix(u->meta.id)))
1765                 return NULL;
1766
1767         r = unit_name_unescape(p);
1768         free(p);
1769
1770         return r;
1771 }
1772
1773 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
1774         Unit *u = userdata;
1775         assert(u);
1776
1777         if (u->meta.instance)
1778                 return unit_name_unescape(u->meta.instance);
1779
1780         return strdup("");
1781 }
1782
1783 char *unit_name_printf(Unit *u, const char* format) {
1784
1785         /*
1786          * This will use the passed string as format string and
1787          * replace the following specifiers:
1788          *
1789          * %n: the full id of the unit                 (foo@bar.waldo)
1790          * %N: the id of the unit without the suffix   (foo@bar)
1791          * %p: the prefix                              (foo)
1792          * %i: the instance                            (bar)
1793          */
1794
1795         const Specifier table[] = {
1796                 { 'n', specifier_string,              u->meta.id },
1797                 { 'N', specifier_prefix_and_instance, NULL },
1798                 { 'p', specifier_prefix,              NULL },
1799                 { 'i', specifier_string,              u->meta.instance },
1800                 { 0, NULL, NULL }
1801         };
1802
1803         assert(u);
1804         assert(format);
1805
1806         return specifier_printf(format, table, u);
1807 }
1808
1809 char *unit_full_printf(Unit *u, const char *format) {
1810
1811         /* This is similar to unit_name_printf() but also supports
1812          * unescaping */
1813
1814         const Specifier table[] = {
1815                 { 'n', specifier_string,              u->meta.id },
1816                 { 'N', specifier_prefix_and_instance, NULL },
1817                 { 'p', specifier_prefix,              NULL },
1818                 { 'P', specifier_prefix_unescaped,    NULL },
1819                 { 'i', specifier_string,              u->meta.instance },
1820                 { 'I', specifier_instance_unescaped,  NULL },
1821                 { 0, NULL, NULL }
1822         };
1823
1824         assert(u);
1825         assert(format);
1826
1827         return specifier_printf(format, table, u);
1828 }
1829
1830 char **unit_full_printf_strv(Unit *u, char **l) {
1831         size_t n;
1832         char **r, **i, **j;
1833
1834         /* Applies unit_full_printf to every entry in l */
1835
1836         assert(u);
1837
1838         n = strv_length(l);
1839         if (!(r = new(char*, n+1)))
1840                 return NULL;
1841
1842         for (i = l, j = r; *i; i++, j++)
1843                 if (!(*j = unit_full_printf(u, *i)))
1844                         goto fail;
1845
1846         *j = NULL;
1847         return r;
1848
1849 fail:
1850         j--;
1851         while (j >= r)
1852                 free(*j);
1853
1854         free(r);
1855
1856         return NULL;
1857 }
1858
1859 int unit_watch_bus_name(Unit *u, const char *name) {
1860         assert(u);
1861         assert(name);
1862
1863         /* Watch a specific name on the bus. We only support one unit
1864          * watching each name for now. */
1865
1866         return hashmap_put(u->meta.manager->watch_bus, name, u);
1867 }
1868
1869 void unit_unwatch_bus_name(Unit *u, const char *name) {
1870         assert(u);
1871         assert(name);
1872
1873         hashmap_remove_value(u->meta.manager->watch_bus, name, u);
1874 }
1875
1876 bool unit_can_serialize(Unit *u) {
1877         assert(u);
1878
1879         return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
1880 }
1881
1882 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
1883         int r;
1884
1885         assert(u);
1886         assert(f);
1887         assert(fds);
1888
1889         if (!unit_can_serialize(u))
1890                 return 0;
1891
1892         if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
1893                 return r;
1894
1895         if (u->meta.job)
1896                 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
1897
1898         /* End marker */
1899         fputc('\n', f);
1900         return 0;
1901 }
1902
1903 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
1904         va_list ap;
1905
1906         assert(u);
1907         assert(f);
1908         assert(key);
1909         assert(format);
1910
1911         fputs(key, f);
1912         fputc('=', f);
1913
1914         va_start(ap, format);
1915         vfprintf(f, format, ap);
1916         va_end(ap);
1917
1918         fputc('\n', f);
1919 }
1920
1921 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
1922         assert(u);
1923         assert(f);
1924         assert(key);
1925         assert(value);
1926
1927         fprintf(f, "%s=%s\n", key, value);
1928 }
1929
1930 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
1931         int r;
1932
1933         assert(u);
1934         assert(f);
1935         assert(fds);
1936
1937         if (!unit_can_serialize(u))
1938                 return 0;
1939
1940         for (;;) {
1941                 char line[1024], *l, *v;
1942                 size_t k;
1943
1944                 if (!fgets(line, sizeof(line), f)) {
1945                         if (feof(f))
1946                                 return 0;
1947                         return -errno;
1948                 }
1949
1950                 l = strstrip(line);
1951
1952                 /* End marker */
1953                 if (l[0] == 0)
1954                         return 0;
1955
1956                 k = strcspn(l, "=");
1957
1958                 if (l[k] == '=') {
1959                         l[k] = 0;
1960                         v = l+k+1;
1961                 } else
1962                         v = l+k;
1963
1964                 if (streq(l, "job")) {
1965                         JobType type;
1966
1967                         if ((type = job_type_from_string(v)) < 0)
1968                                 log_debug("Failed to parse job type value %s", v);
1969                         else
1970                                 u->meta.deserialized_job = type;
1971
1972                         continue;
1973                 }
1974
1975                 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
1976                         return r;
1977         }
1978 }
1979
1980 int unit_add_node_link(Unit *u, const char *what, bool wants) {
1981         Unit *device;
1982         char *e;
1983         int r;
1984
1985         assert(u);
1986
1987         if (!what)
1988                 return 0;
1989
1990         /* Adds in links to the device node that this unit is based on */
1991
1992         if (!is_device_path(what))
1993                 return 0;
1994
1995         if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
1996                 return -ENOMEM;
1997
1998         r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
1999         free(e);
2000
2001         if (r < 0)
2002                 return r;
2003
2004         if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, device, true)) < 0)
2005                 return r;
2006
2007         if (wants)
2008                 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2009                         return r;
2010
2011         return 0;
2012 }
2013
2014 int unit_coldplug(Unit *u) {
2015         int r;
2016
2017         assert(u);
2018
2019         if (UNIT_VTABLE(u)->coldplug)
2020                 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2021                         return r;
2022
2023         if (u->meta.deserialized_job >= 0) {
2024                 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_FAIL, false, NULL, NULL)) < 0)
2025                         return r;
2026
2027                 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2028         }
2029
2030         return 0;
2031 }
2032
2033 void unit_status_printf(Unit *u, const char *format, ...) {
2034         va_list ap;
2035
2036         assert(u);
2037         assert(format);
2038
2039         if (!UNIT_VTABLE(u)->show_status)
2040                 return;
2041
2042         if (u->meta.manager->running_as != MANAGER_SYSTEM)
2043                 return;
2044
2045         if (!u->meta.manager->show_status)
2046                 return;
2047
2048         if (!manager_is_booting_or_shutting_down(u->meta.manager))
2049                 return;
2050
2051         va_start(ap, format);
2052         status_vprintf(format, ap);
2053         va_end(ap);
2054 }
2055
2056 bool unit_need_daemon_reload(Unit *u) {
2057         struct stat st;
2058
2059         assert(u);
2060
2061         if (!u->meta.fragment_path)
2062                 return false;
2063
2064         zero(st);
2065         if (stat(u->meta.fragment_path, &st) < 0)
2066                 /* What, cannot access this anymore? */
2067                 return true;
2068
2069         return
2070                 u->meta.fragment_mtime &&
2071                 timespec_load(&st.st_mtim) != u->meta.fragment_mtime;
2072 }
2073
2074 static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
2075         [UNIT_SERVICE] = "service",
2076         [UNIT_TIMER] = "timer",
2077         [UNIT_SOCKET] = "socket",
2078         [UNIT_TARGET] = "target",
2079         [UNIT_DEVICE] = "device",
2080         [UNIT_MOUNT] = "mount",
2081         [UNIT_AUTOMOUNT] = "automount",
2082         [UNIT_SNAPSHOT] = "snapshot",
2083         [UNIT_SWAP] = "swap"
2084 };
2085
2086 DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
2087
2088 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2089         [UNIT_STUB] = "stub",
2090         [UNIT_LOADED] = "loaded",
2091         [UNIT_FAILED] = "failed",
2092         [UNIT_MERGED] = "merged"
2093 };
2094
2095 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2096
2097 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2098         [UNIT_ACTIVE] = "active",
2099         [UNIT_RELOADING] = "reloading",
2100         [UNIT_INACTIVE] = "inactive",
2101         [UNIT_MAINTENANCE] = "maintenance",
2102         [UNIT_ACTIVATING] = "activating",
2103         [UNIT_DEACTIVATING] = "deactivating"
2104 };
2105
2106 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2107
2108 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2109         [UNIT_REQUIRES] = "Requires",
2110         [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2111         [UNIT_WANTS] = "Wants",
2112         [UNIT_REQUISITE] = "Requisite",
2113         [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2114         [UNIT_REQUIRED_BY] = "RequiredBy",
2115         [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2116         [UNIT_WANTED_BY] = "WantedBy",
2117         [UNIT_CONFLICTS] = "Conflicts",
2118         [UNIT_BEFORE] = "Before",
2119         [UNIT_AFTER] = "After",
2120         [UNIT_REFERENCES] = "References",
2121         [UNIT_REFERENCED_BY] = "ReferencedBy",
2122         [UNIT_ON_FAILURE] = "OnFailure"
2123 };
2124
2125 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);
2126
2127 static const char* const kill_mode_table[_KILL_MODE_MAX] = {
2128         [KILL_CONTROL_GROUP] = "control-group",
2129         [KILL_PROCESS_GROUP] = "process-group",
2130         [KILL_PROCESS] = "process",
2131         [KILL_NONE] = "none"
2132 };
2133
2134 DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);