]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/transaction.c
network: also introduce UseDomains= for [DHCPv6] section
[thirdparty/systemd.git] / src / core / transaction.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "bus-common-errors.h"
8 #include "bus-error.h"
9 #include "dbus-unit.h"
10 #include "strv.h"
11 #include "terminal-util.h"
12 #include "transaction.h"
13
14 static void transaction_unlink_job(Transaction *tr, Job *j, bool delete_dependencies);
15
16 static void transaction_delete_job(Transaction *tr, Job *j, bool delete_dependencies) {
17 assert(tr);
18 assert(j);
19
20 /* Deletes one job from the transaction */
21
22 transaction_unlink_job(tr, j, delete_dependencies);
23
24 job_free(j);
25 }
26
27 static void transaction_delete_unit(Transaction *tr, Unit *u) {
28 Job *j;
29
30 /* Deletes all jobs associated with a certain unit from the
31 * transaction */
32
33 while ((j = hashmap_get(tr->jobs, u)))
34 transaction_delete_job(tr, j, true);
35 }
36
37 void transaction_abort(Transaction *tr) {
38 Job *j;
39
40 assert(tr);
41
42 while ((j = hashmap_first(tr->jobs)))
43 transaction_delete_job(tr, j, false);
44
45 assert(hashmap_isempty(tr->jobs));
46 }
47
48 static void transaction_find_jobs_that_matter_to_anchor(Job *j, unsigned generation) {
49 JobDependency *l;
50
51 /* A recursive sweep through the graph that marks all units
52 * that matter to the anchor job, i.e. are directly or
53 * indirectly a dependency of the anchor job via paths that
54 * are fully marked as mattering. */
55
56 j->matters_to_anchor = true;
57 j->generation = generation;
58
59 LIST_FOREACH(subject, l, j->subject_list) {
60
61 /* This link does not matter */
62 if (!l->matters)
63 continue;
64
65 /* This unit has already been marked */
66 if (l->object->generation == generation)
67 continue;
68
69 transaction_find_jobs_that_matter_to_anchor(l->object, generation);
70 }
71 }
72
73 static void transaction_merge_and_delete_job(Transaction *tr, Job *j, Job *other, JobType t) {
74 JobDependency *l, *last;
75
76 assert(j);
77 assert(other);
78 assert(j->unit == other->unit);
79 assert(!j->installed);
80
81 /* Merges 'other' into 'j' and then deletes 'other'. */
82
83 j->type = t;
84 j->state = JOB_WAITING;
85 j->irreversible = j->irreversible || other->irreversible;
86 j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
87
88 /* Patch us in as new owner of the JobDependency objects */
89 last = NULL;
90 LIST_FOREACH(subject, l, other->subject_list) {
91 assert(l->subject == other);
92 l->subject = j;
93 last = l;
94 }
95
96 /* Merge both lists */
97 if (last) {
98 last->subject_next = j->subject_list;
99 if (j->subject_list)
100 j->subject_list->subject_prev = last;
101 j->subject_list = other->subject_list;
102 }
103
104 /* Patch us in as new owner of the JobDependency objects */
105 last = NULL;
106 LIST_FOREACH(object, l, other->object_list) {
107 assert(l->object == other);
108 l->object = j;
109 last = l;
110 }
111
112 /* Merge both lists */
113 if (last) {
114 last->object_next = j->object_list;
115 if (j->object_list)
116 j->object_list->object_prev = last;
117 j->object_list = other->object_list;
118 }
119
120 /* Kill the other job */
121 other->subject_list = NULL;
122 other->object_list = NULL;
123 transaction_delete_job(tr, other, true);
124 }
125
126 _pure_ static bool job_is_conflicted_by(Job *j) {
127 JobDependency *l;
128
129 assert(j);
130
131 /* Returns true if this job is pulled in by a least one
132 * ConflictedBy dependency. */
133
134 LIST_FOREACH(object, l, j->object_list)
135 if (l->conflicts)
136 return true;
137
138 return false;
139 }
140
141 static int delete_one_unmergeable_job(Transaction *tr, Job *j) {
142 Job *k;
143
144 assert(j);
145
146 /* Tries to delete one item in the linked list
147 * j->transaction_next->transaction_next->... that conflicts
148 * with another one, in an attempt to make an inconsistent
149 * transaction work. */
150
151 /* We rely here on the fact that if a merged with b does not
152 * merge with c, either a or b merge with c neither */
153 LIST_FOREACH(transaction, j, j)
154 LIST_FOREACH(transaction, k, j->transaction_next) {
155 Job *d;
156
157 /* Is this one mergeable? Then skip it */
158 if (job_type_is_mergeable(j->type, k->type))
159 continue;
160
161 /* Ok, we found two that conflict, let's see if we can
162 * drop one of them */
163 if (!j->matters_to_anchor && !k->matters_to_anchor) {
164
165 /* Both jobs don't matter, so let's
166 * find the one that is smarter to
167 * remove. Let's think positive and
168 * rather remove stops then starts --
169 * except if something is being
170 * stopped because it is conflicted by
171 * another unit in which case we
172 * rather remove the start. */
173
174 log_unit_debug(j->unit,
175 "Looking at job %s/%s conflicted_by=%s",
176 j->unit->id, job_type_to_string(j->type),
177 yes_no(j->type == JOB_STOP && job_is_conflicted_by(j)));
178 log_unit_debug(k->unit,
179 "Looking at job %s/%s conflicted_by=%s",
180 k->unit->id, job_type_to_string(k->type),
181 yes_no(k->type == JOB_STOP && job_is_conflicted_by(k)));
182
183 if (j->type == JOB_STOP) {
184
185 if (job_is_conflicted_by(j))
186 d = k;
187 else
188 d = j;
189
190 } else if (k->type == JOB_STOP) {
191
192 if (job_is_conflicted_by(k))
193 d = j;
194 else
195 d = k;
196 } else
197 d = j;
198
199 } else if (!j->matters_to_anchor)
200 d = j;
201 else if (!k->matters_to_anchor)
202 d = k;
203 else
204 return -ENOEXEC;
205
206 /* Ok, we can drop one, so let's do so. */
207 log_unit_debug(d->unit,
208 "Fixing conflicting jobs %s/%s,%s/%s by deleting job %s/%s",
209 j->unit->id, job_type_to_string(j->type),
210 k->unit->id, job_type_to_string(k->type),
211 d->unit->id, job_type_to_string(d->type));
212 transaction_delete_job(tr, d, true);
213 return 0;
214 }
215
216 return -EINVAL;
217 }
218
219 static int transaction_merge_jobs(Transaction *tr, sd_bus_error *e) {
220 Job *j;
221 int r;
222
223 assert(tr);
224
225 /* First step, check whether any of the jobs for one specific
226 * task conflict. If so, try to drop one of them. */
227 HASHMAP_FOREACH(j, tr->jobs) {
228 JobType t;
229 Job *k;
230
231 t = j->type;
232 LIST_FOREACH(transaction, k, j->transaction_next) {
233 if (job_type_merge_and_collapse(&t, k->type, j->unit) >= 0)
234 continue;
235
236 /* OK, we could not merge all jobs for this
237 * action. Let's see if we can get rid of one
238 * of them */
239
240 r = delete_one_unmergeable_job(tr, j);
241 if (r >= 0)
242 /* Ok, we managed to drop one, now
243 * let's ask our callers to call us
244 * again after garbage collecting */
245 return -EAGAIN;
246
247 /* We couldn't merge anything. Failure */
248 return sd_bus_error_setf(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING,
249 "Transaction contains conflicting jobs '%s' and '%s' for %s. "
250 "Probably contradicting requirement dependencies configured.",
251 job_type_to_string(t),
252 job_type_to_string(k->type),
253 k->unit->id);
254 }
255 }
256
257 /* Second step, merge the jobs. */
258 HASHMAP_FOREACH(j, tr->jobs) {
259 JobType t = j->type;
260 Job *k;
261
262 /* Merge all transaction jobs for j->unit */
263 LIST_FOREACH(transaction, k, j->transaction_next)
264 assert_se(job_type_merge_and_collapse(&t, k->type, j->unit) == 0);
265
266 while ((k = j->transaction_next)) {
267 if (tr->anchor_job == k) {
268 transaction_merge_and_delete_job(tr, k, j, t);
269 j = k;
270 } else
271 transaction_merge_and_delete_job(tr, j, k, t);
272 }
273
274 assert(!j->transaction_next);
275 assert(!j->transaction_prev);
276 }
277
278 return 0;
279 }
280
281 static void transaction_drop_redundant(Transaction *tr) {
282 bool again;
283
284 /* Goes through the transaction and removes all jobs of the units whose jobs are all noops. If not
285 * all of a unit's jobs are redundant, they are kept. */
286
287 assert(tr);
288
289 do {
290 Job *j;
291
292 again = false;
293
294 HASHMAP_FOREACH(j, tr->jobs) {
295 bool keep = false;
296 Job *k;
297
298 LIST_FOREACH(transaction, k, j)
299 if (tr->anchor_job == k ||
300 !job_type_is_redundant(k->type, unit_active_state(k->unit)) ||
301 (k->unit->job && job_type_is_conflicting(k->type, k->unit->job->type))) {
302 keep = true;
303 break;
304 }
305
306 if (!keep) {
307 log_trace("Found redundant job %s/%s, dropping from transaction.",
308 j->unit->id, job_type_to_string(j->type));
309 transaction_delete_job(tr, j, false);
310 again = true;
311 break;
312 }
313 }
314 } while (again);
315 }
316
317 _pure_ static bool unit_matters_to_anchor(Unit *u, Job *j) {
318 assert(u);
319 assert(!j->transaction_prev);
320
321 /* Checks whether at least one of the jobs for this unit
322 * matters to the anchor. */
323
324 LIST_FOREACH(transaction, j, j)
325 if (j->matters_to_anchor)
326 return true;
327
328 return false;
329 }
330
331 static char* merge_unit_ids(const char* unit_log_field, char **pairs) {
332 char **unit_id, **job_type, *ans = NULL;
333 size_t alloc = 0, size = 0, next;
334
335 STRV_FOREACH_PAIR(unit_id, job_type, pairs) {
336 next = strlen(unit_log_field) + strlen(*unit_id);
337 if (!GREEDY_REALLOC(ans, alloc, size + next + 1))
338 return mfree(ans);
339
340 sprintf(ans + size, "%s%s", unit_log_field, *unit_id);
341 if (*(unit_id+1))
342 ans[size + next] = '\n';
343 size += next + 1;
344 }
345
346 return ans;
347 }
348
349 static int transaction_verify_order_one(Transaction *tr, Job *j, Job *from, unsigned generation, sd_bus_error *e) {
350 Unit *u;
351 void *v;
352 int r;
353 static const UnitDependency directions[] = {
354 UNIT_BEFORE,
355 UNIT_AFTER,
356 };
357 size_t d;
358
359 assert(tr);
360 assert(j);
361 assert(!j->transaction_prev);
362
363 /* Does a recursive sweep through the ordering graph, looking
364 * for a cycle. If we find a cycle we try to break it. */
365
366 /* Have we seen this before? */
367 if (j->generation == generation) {
368 Job *k, *delete = NULL;
369 _cleanup_free_ char **array = NULL, *unit_ids = NULL;
370 char **unit_id, **job_type;
371
372 /* If the marker is NULL we have been here already and
373 * decided the job was loop-free from here. Hence
374 * shortcut things and return right-away. */
375 if (!j->marker)
376 return 0;
377
378 /* So, the marker is not NULL and we already have been here. We have
379 * a cycle. Let's try to break it. We go backwards in our path and
380 * try to find a suitable job to remove. We use the marker to find
381 * our way back, since smart how we are we stored our way back in
382 * there. */
383
384 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
385
386 /* For logging below */
387 if (strv_push_pair(&array, k->unit->id, (char*) job_type_to_string(k->type)) < 0)
388 log_oom();
389
390 if (!delete && hashmap_get(tr->jobs, k->unit) && !unit_matters_to_anchor(k->unit, k))
391 /* Ok, we can drop this one, so let's do so. */
392 delete = k;
393
394 /* Check if this in fact was the beginning of the cycle */
395 if (k == j)
396 break;
397 }
398
399 unit_ids = merge_unit_ids(j->manager->unit_log_field, array); /* ignore error */
400
401 STRV_FOREACH_PAIR(unit_id, job_type, array)
402 /* logging for j not k here to provide a consistent narrative */
403 log_struct(LOG_WARNING,
404 "MESSAGE=%s: Found %s on %s/%s",
405 j->unit->id,
406 unit_id == array ? "ordering cycle" : "dependency",
407 *unit_id, *job_type,
408 unit_ids);
409
410 if (delete) {
411 const char *status;
412 /* logging for j not k here to provide a consistent narrative */
413 log_struct(LOG_ERR,
414 "MESSAGE=%s: Job %s/%s deleted to break ordering cycle starting with %s/%s",
415 j->unit->id, delete->unit->id, job_type_to_string(delete->type),
416 j->unit->id, job_type_to_string(j->type),
417 unit_ids);
418
419 if (log_get_show_color())
420 status = ANSI_HIGHLIGHT_RED " SKIP " ANSI_NORMAL;
421 else
422 status = " SKIP ";
423
424 unit_status_printf(delete->unit,
425 STATUS_TYPE_NOTICE,
426 status,
427 "Ordering cycle found, skipping %s");
428 transaction_delete_unit(tr, delete->unit);
429 return -EAGAIN;
430 }
431
432 log_struct(LOG_ERR,
433 "MESSAGE=%s: Unable to break cycle starting with %s/%s",
434 j->unit->id, j->unit->id, job_type_to_string(j->type),
435 unit_ids);
436
437 return sd_bus_error_setf(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC,
438 "Transaction order is cyclic. See system logs for details.");
439 }
440
441 /* Make the marker point to where we come from, so that we can
442 * find our way backwards if we want to break a cycle. We use
443 * a special marker for the beginning: we point to
444 * ourselves. */
445 j->marker = from ? from : j;
446 j->generation = generation;
447
448 /* Actual ordering of jobs depends on the unit ordering dependency and job types. We need to traverse
449 * the graph over 'before' edges in the actual job execution order. We traverse over both unit
450 * ordering dependencies and we test with job_compare() whether it is the 'before' edge in the job
451 * execution ordering. */
452 for (d = 0; d < ELEMENTSOF(directions); d++) {
453 HASHMAP_FOREACH_KEY(v, u, j->unit->dependencies[directions[d]]) {
454 Job *o;
455
456 /* Is there a job for this unit? */
457 o = hashmap_get(tr->jobs, u);
458 if (!o) {
459 /* Ok, there is no job for this in the
460 * transaction, but maybe there is already one
461 * running? */
462 o = u->job;
463 if (!o)
464 continue;
465 }
466
467 /* Cut traversing if the job j is not really *before* o. */
468 if (job_compare(j, o, directions[d]) >= 0)
469 continue;
470
471 r = transaction_verify_order_one(tr, o, j, generation, e);
472 if (r < 0)
473 return r;
474 }
475 }
476
477 /* Ok, let's backtrack, and remember that this entry is not on
478 * our path anymore. */
479 j->marker = NULL;
480
481 return 0;
482 }
483
484 static int transaction_verify_order(Transaction *tr, unsigned *generation, sd_bus_error *e) {
485 Job *j;
486 int r;
487 unsigned g;
488
489 assert(tr);
490 assert(generation);
491
492 /* Check if the ordering graph is cyclic. If it is, try to fix
493 * that up by dropping one of the jobs. */
494
495 g = (*generation)++;
496
497 HASHMAP_FOREACH(j, tr->jobs) {
498 r = transaction_verify_order_one(tr, j, NULL, g, e);
499 if (r < 0)
500 return r;
501 }
502
503 return 0;
504 }
505
506 static void transaction_collect_garbage(Transaction *tr) {
507 bool again;
508
509 assert(tr);
510
511 /* Drop jobs that are not required by any other job */
512
513 do {
514 Job *j;
515
516 again = false;
517
518 HASHMAP_FOREACH(j, tr->jobs) {
519 if (tr->anchor_job == j)
520 continue;
521
522 if (!j->object_list) {
523 log_trace("Garbage collecting job %s/%s", j->unit->id, job_type_to_string(j->type));
524 transaction_delete_job(tr, j, true);
525 again = true;
526 break;
527 }
528
529 log_trace("Keeping job %s/%s because of %s/%s",
530 j->unit->id, job_type_to_string(j->type),
531 j->object_list->subject ? j->object_list->subject->unit->id : "root",
532 j->object_list->subject ? job_type_to_string(j->object_list->subject->type) : "root");
533 }
534
535 } while (again);
536 }
537
538 static int transaction_is_destructive(Transaction *tr, JobMode mode, sd_bus_error *e) {
539 Job *j;
540
541 assert(tr);
542
543 /* Checks whether applying this transaction means that
544 * existing jobs would be replaced */
545
546 HASHMAP_FOREACH(j, tr->jobs) {
547
548 /* Assume merged */
549 assert(!j->transaction_prev);
550 assert(!j->transaction_next);
551
552 if (j->unit->job && (mode == JOB_FAIL || j->unit->job->irreversible) &&
553 job_type_is_conflicting(j->unit->job->type, j->type))
554 return sd_bus_error_setf(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE,
555 "Transaction for %s/%s is destructive (%s has '%s' job queued, but '%s' is included in transaction).",
556 tr->anchor_job->unit->id, job_type_to_string(tr->anchor_job->type),
557 j->unit->id, job_type_to_string(j->unit->job->type), job_type_to_string(j->type));
558 }
559
560 return 0;
561 }
562
563 static void transaction_minimize_impact(Transaction *tr) {
564 Job *j;
565
566 assert(tr);
567
568 /* Drops all unnecessary jobs that reverse already active jobs
569 * or that stop a running service. */
570
571 rescan:
572 HASHMAP_FOREACH(j, tr->jobs) {
573 LIST_FOREACH(transaction, j, j) {
574 bool stops_running_service, changes_existing_job;
575
576 /* If it matters, we shouldn't drop it */
577 if (j->matters_to_anchor)
578 continue;
579
580 /* Would this stop a running service?
581 * Would this change an existing job?
582 * If so, let's drop this entry */
583
584 stops_running_service =
585 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
586
587 changes_existing_job =
588 j->unit->job &&
589 job_type_is_conflicting(j->type, j->unit->job->type);
590
591 if (!stops_running_service && !changes_existing_job)
592 continue;
593
594 if (stops_running_service)
595 log_unit_debug(j->unit,
596 "%s/%s would stop a running service.",
597 j->unit->id, job_type_to_string(j->type));
598
599 if (changes_existing_job)
600 log_unit_debug(j->unit,
601 "%s/%s would change existing job.",
602 j->unit->id, job_type_to_string(j->type));
603
604 /* Ok, let's get rid of this */
605 log_unit_debug(j->unit,
606 "Deleting %s/%s to minimize impact.",
607 j->unit->id, job_type_to_string(j->type));
608
609 transaction_delete_job(tr, j, true);
610 goto rescan;
611 }
612 }
613 }
614
615 static int transaction_apply(
616 Transaction *tr,
617 Manager *m,
618 JobMode mode,
619 Set *affected_jobs) {
620
621 Job *j;
622 int r;
623
624 /* Moves the transaction jobs to the set of active jobs */
625
626 if (IN_SET(mode, JOB_ISOLATE, JOB_FLUSH)) {
627
628 /* When isolating first kill all installed jobs which
629 * aren't part of the new transaction */
630 HASHMAP_FOREACH(j, m->jobs) {
631 assert(j->installed);
632
633 if (j->unit->ignore_on_isolate)
634 continue;
635
636 if (hashmap_get(tr->jobs, j->unit))
637 continue;
638
639 /* Not invalidating recursively. Avoids triggering
640 * OnFailure= actions of dependent jobs. Also avoids
641 * invalidating our iterator. */
642 job_finish_and_invalidate(j, JOB_CANCELED, false, false);
643 }
644 }
645
646 HASHMAP_FOREACH(j, tr->jobs) {
647 /* Assume merged */
648 assert(!j->transaction_prev);
649 assert(!j->transaction_next);
650
651 r = hashmap_ensure_put(&m->jobs, NULL, UINT32_TO_PTR(j->id), j);
652 if (r < 0)
653 goto rollback;
654 }
655
656 while ((j = hashmap_steal_first(tr->jobs))) {
657 Job *installed_job;
658
659 /* Clean the job dependencies */
660 transaction_unlink_job(tr, j, false);
661
662 installed_job = job_install(j);
663 if (installed_job != j) {
664 /* j has been merged into a previously installed job */
665 if (tr->anchor_job == j)
666 tr->anchor_job = installed_job;
667 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
668 job_free(j);
669 j = installed_job;
670 }
671
672 job_add_to_run_queue(j);
673 job_add_to_dbus_queue(j);
674 job_start_timer(j, false);
675 job_shutdown_magic(j);
676
677 /* When 'affected' is specified, let's track all in it all jobs that were touched because of
678 * this transaction. */
679 if (affected_jobs)
680 (void) set_put(affected_jobs, j);
681 }
682
683 return 0;
684
685 rollback:
686
687 HASHMAP_FOREACH(j, tr->jobs)
688 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
689
690 return r;
691 }
692
693 int transaction_activate(
694 Transaction *tr,
695 Manager *m,
696 JobMode mode,
697 Set *affected_jobs,
698 sd_bus_error *e) {
699
700 Job *j;
701 int r;
702 unsigned generation = 1;
703
704 assert(tr);
705
706 /* This applies the changes recorded in tr->jobs to
707 * the actual list of jobs, if possible. */
708
709 /* Reset the generation counter of all installed jobs. The detection of cycles
710 * looks at installed jobs. If they had a non-zero generation from some previous
711 * walk of the graph, the algorithm would break. */
712 HASHMAP_FOREACH(j, m->jobs)
713 j->generation = 0;
714
715 /* First step: figure out which jobs matter */
716 transaction_find_jobs_that_matter_to_anchor(tr->anchor_job, generation++);
717
718 /* Second step: Try not to stop any running services if
719 * we don't have to. Don't try to reverse running
720 * jobs if we don't have to. */
721 if (mode == JOB_FAIL)
722 transaction_minimize_impact(tr);
723
724 /* Third step: Drop redundant jobs */
725 transaction_drop_redundant(tr);
726
727 for (;;) {
728 /* Fourth step: Let's remove unneeded jobs that might
729 * be lurking. */
730 if (mode != JOB_ISOLATE)
731 transaction_collect_garbage(tr);
732
733 /* Fifth step: verify order makes sense and correct
734 * cycles if necessary and possible */
735 r = transaction_verify_order(tr, &generation, e);
736 if (r >= 0)
737 break;
738
739 if (r != -EAGAIN)
740 return log_warning_errno(r, "Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error_message(e, r));
741
742 /* Let's see if the resulting transaction ordering
743 * graph is still cyclic... */
744 }
745
746 for (;;) {
747 /* Sixth step: let's drop unmergeable entries if
748 * necessary and possible, merge entries we can
749 * merge */
750 r = transaction_merge_jobs(tr, e);
751 if (r >= 0)
752 break;
753
754 if (r != -EAGAIN)
755 return log_warning_errno(r, "Requested transaction contains unmergeable jobs: %s", bus_error_message(e, r));
756
757 /* Seventh step: an entry got dropped, let's garbage
758 * collect its dependencies. */
759 if (mode != JOB_ISOLATE)
760 transaction_collect_garbage(tr);
761
762 /* Let's see if the resulting transaction still has
763 * unmergeable entries ... */
764 }
765
766 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
767 transaction_drop_redundant(tr);
768
769 /* Ninth step: check whether we can actually apply this */
770 r = transaction_is_destructive(tr, mode, e);
771 if (r < 0)
772 return log_notice_errno(r, "Requested transaction contradicts existing jobs: %s", bus_error_message(e, r));
773
774 /* Tenth step: apply changes */
775 r = transaction_apply(tr, m, mode, affected_jobs);
776 if (r < 0)
777 return log_warning_errno(r, "Failed to apply transaction: %m");
778
779 assert(hashmap_isempty(tr->jobs));
780
781 if (!hashmap_isempty(m->jobs)) {
782 /* Are there any jobs now? Then make sure we have the
783 * idle pipe around. We don't really care too much
784 * whether this works or not, as the idle pipe is a
785 * feature for cosmetics, not actually useful for
786 * anything beyond that. */
787
788 if (m->idle_pipe[0] < 0 && m->idle_pipe[1] < 0 &&
789 m->idle_pipe[2] < 0 && m->idle_pipe[3] < 0) {
790 (void) pipe2(m->idle_pipe, O_NONBLOCK|O_CLOEXEC);
791 (void) pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC);
792 }
793 }
794
795 return 0;
796 }
797
798 static Job* transaction_add_one_job(Transaction *tr, JobType type, Unit *unit, bool *is_new) {
799 Job *j, *f;
800
801 assert(tr);
802 assert(unit);
803
804 /* Looks for an existing prospective job and returns that. If
805 * it doesn't exist it is created and added to the prospective
806 * jobs list. */
807
808 f = hashmap_get(tr->jobs, unit);
809
810 LIST_FOREACH(transaction, j, f) {
811 assert(j->unit == unit);
812
813 if (j->type == type) {
814 if (is_new)
815 *is_new = false;
816 return j;
817 }
818 }
819
820 j = job_new(unit, type);
821 if (!j)
822 return NULL;
823
824 j->generation = 0;
825 j->marker = NULL;
826 j->matters_to_anchor = false;
827 j->irreversible = tr->irreversible;
828
829 LIST_PREPEND(transaction, f, j);
830
831 if (hashmap_replace(tr->jobs, unit, f) < 0) {
832 LIST_REMOVE(transaction, f, j);
833 job_free(j);
834 return NULL;
835 }
836
837 if (is_new)
838 *is_new = true;
839
840 log_trace("Added job %s/%s to transaction.", unit->id, job_type_to_string(type));
841
842 return j;
843 }
844
845 static void transaction_unlink_job(Transaction *tr, Job *j, bool delete_dependencies) {
846 assert(tr);
847 assert(j);
848
849 if (j->transaction_prev)
850 j->transaction_prev->transaction_next = j->transaction_next;
851 else if (j->transaction_next)
852 hashmap_replace(tr->jobs, j->unit, j->transaction_next);
853 else
854 hashmap_remove_value(tr->jobs, j->unit, j);
855
856 if (j->transaction_next)
857 j->transaction_next->transaction_prev = j->transaction_prev;
858
859 j->transaction_prev = j->transaction_next = NULL;
860
861 while (j->subject_list)
862 job_dependency_free(j->subject_list);
863
864 while (j->object_list) {
865 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
866
867 job_dependency_free(j->object_list);
868
869 if (other && delete_dependencies) {
870 log_unit_debug(other->unit,
871 "Deleting job %s/%s as dependency of job %s/%s",
872 other->unit->id, job_type_to_string(other->type),
873 j->unit->id, job_type_to_string(j->type));
874 transaction_delete_job(tr, other, delete_dependencies);
875 }
876 }
877 }
878
879 void transaction_add_propagate_reload_jobs(Transaction *tr, Unit *unit, Job *by, bool ignore_order, sd_bus_error *e) {
880 JobType nt;
881 Unit *dep;
882 void *v;
883 int r;
884
885 assert(tr);
886 assert(unit);
887
888 HASHMAP_FOREACH_KEY(v, dep, unit->dependencies[UNIT_PROPAGATES_RELOAD_TO]) {
889 nt = job_type_collapse(JOB_TRY_RELOAD, dep);
890 if (nt == JOB_NOP)
891 continue;
892
893 r = transaction_add_job_and_dependencies(tr, nt, dep, by, false, false, false, ignore_order, e);
894 if (r < 0) {
895 log_unit_warning(dep,
896 "Cannot add dependency reload job, ignoring: %s",
897 bus_error_message(e, r));
898 sd_bus_error_free(e);
899 }
900 }
901 }
902
903 int transaction_add_job_and_dependencies(
904 Transaction *tr,
905 JobType type,
906 Unit *unit,
907 Job *by,
908 bool matters,
909 bool conflicts,
910 bool ignore_requirements,
911 bool ignore_order,
912 sd_bus_error *e) {
913
914 bool is_new;
915 Unit *dep;
916 Job *ret;
917 void *v;
918 int r;
919
920 assert(tr);
921 assert(type < _JOB_TYPE_MAX);
922 assert(type < _JOB_TYPE_MAX_IN_TRANSACTION);
923 assert(unit);
924
925 /* Before adding jobs for this unit, let's ensure that its state has been loaded
926 * This matters when jobs are spawned as part of coldplugging itself (see e. g. path_coldplug()).
927 * This way, we "recursively" coldplug units, ensuring that we do not look at state of
928 * not-yet-coldplugged units. */
929 if (MANAGER_IS_RELOADING(unit->manager))
930 unit_coldplug(unit);
931
932 if (by)
933 log_trace("Pulling in %s/%s from %s/%s", unit->id, job_type_to_string(type), by->unit->id, job_type_to_string(by->type));
934
935 /* Safety check that the unit is a valid state, i.e. not in UNIT_STUB or UNIT_MERGED which should only be set
936 * temporarily. */
937 if (!UNIT_IS_LOAD_COMPLETE(unit->load_state))
938 return sd_bus_error_setf(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->id);
939
940 if (type != JOB_STOP) {
941 r = bus_unit_validate_load_state(unit, e);
942 /* The time-based cache allows to start new units without daemon-reload,
943 * but if they are already referenced (because of dependencies or ordering)
944 * then we have to force a load of the fragment. As an optimization, check
945 * first if anything in the usual paths was modified since the last time
946 * the cache was loaded. Also check if the last time an attempt to load the
947 * unit was made was before the most recent cache refresh, so that we know
948 * we need to try again — even if the cache is current, it might have been
949 * updated in a different context before we had a chance to retry loading
950 * this particular unit.
951 *
952 * Given building up the transaction is a synchronous operation, attempt
953 * to load the unit immediately. */
954 if (r < 0 && manager_unit_cache_should_retry_load(unit)) {
955 sd_bus_error_free(e);
956 unit->load_state = UNIT_STUB;
957 r = unit_load(unit);
958 if (r < 0 || unit->load_state == UNIT_STUB)
959 unit->load_state = UNIT_NOT_FOUND;
960 r = bus_unit_validate_load_state(unit, e);
961 }
962 if (r < 0)
963 return r;
964 }
965
966 if (!unit_job_is_applicable(unit, type))
967 return sd_bus_error_setf(e, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE,
968 "Job type %s is not applicable for unit %s.",
969 job_type_to_string(type), unit->id);
970
971 /* First add the job. */
972 ret = transaction_add_one_job(tr, type, unit, &is_new);
973 if (!ret)
974 return -ENOMEM;
975
976 ret->ignore_order = ret->ignore_order || ignore_order;
977
978 /* Then, add a link to the job. */
979 if (by) {
980 if (!job_dependency_new(by, ret, matters, conflicts))
981 return -ENOMEM;
982 } else {
983 /* If the job has no parent job, it is the anchor job. */
984 assert(!tr->anchor_job);
985 tr->anchor_job = ret;
986 }
987
988 if (is_new && !ignore_requirements && type != JOB_NOP) {
989 Set *following;
990
991 /* If we are following some other unit, make sure we
992 * add all dependencies of everybody following. */
993 if (unit_following_set(ret->unit, &following) > 0) {
994 SET_FOREACH(dep, following) {
995 r = transaction_add_job_and_dependencies(tr, type, dep, ret, false, false, false, ignore_order, e);
996 if (r < 0) {
997 log_unit_full_errno(dep, r == -ERFKILL ? LOG_INFO : LOG_WARNING, r,
998 "Cannot add dependency job, ignoring: %s",
999 bus_error_message(e, r));
1000 sd_bus_error_free(e);
1001 }
1002 }
1003
1004 set_free(following);
1005 }
1006
1007 /* Finally, recursively add in all dependencies. */
1008 if (IN_SET(type, JOB_START, JOB_RESTART)) {
1009 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_REQUIRES]) {
1010 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
1011 if (r < 0) {
1012 if (r != -EBADR) /* job type not applicable */
1013 goto fail;
1014
1015 sd_bus_error_free(e);
1016 }
1017 }
1018
1019 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_BINDS_TO]) {
1020 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
1021 if (r < 0) {
1022 if (r != -EBADR) /* job type not applicable */
1023 goto fail;
1024
1025 sd_bus_error_free(e);
1026 }
1027 }
1028
1029 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_WANTS]) {
1030 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, false, false, false, ignore_order, e);
1031 if (r < 0) {
1032 /* unit masked, job type not applicable and unit not found are not considered as errors. */
1033 log_unit_full_errno(dep,
1034 IN_SET(r, -ERFKILL, -EBADR, -ENOENT) ? LOG_DEBUG : LOG_WARNING,
1035 r, "Cannot add dependency job, ignoring: %s",
1036 bus_error_message(e, r));
1037 sd_bus_error_free(e);
1038 }
1039 }
1040
1041 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_REQUISITE]) {
1042 r = transaction_add_job_and_dependencies(tr, JOB_VERIFY_ACTIVE, dep, ret, true, false, false, ignore_order, e);
1043 if (r < 0) {
1044 if (r != -EBADR) /* job type not applicable */
1045 goto fail;
1046
1047 sd_bus_error_free(e);
1048 }
1049 }
1050
1051 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_CONFLICTS]) {
1052 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, true, true, false, ignore_order, e);
1053 if (r < 0) {
1054 if (r != -EBADR) /* job type not applicable */
1055 goto fail;
1056
1057 sd_bus_error_free(e);
1058 }
1059 }
1060
1061 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_CONFLICTED_BY]) {
1062 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, false, false, false, ignore_order, e);
1063 if (r < 0) {
1064 log_unit_warning(dep,
1065 "Cannot add dependency job, ignoring: %s",
1066 bus_error_message(e, r));
1067 sd_bus_error_free(e);
1068 }
1069 }
1070
1071 }
1072
1073 if (IN_SET(type, JOB_STOP, JOB_RESTART)) {
1074 static const UnitDependency propagate_deps[] = {
1075 UNIT_REQUIRED_BY,
1076 UNIT_REQUISITE_OF,
1077 UNIT_BOUND_BY,
1078 UNIT_CONSISTS_OF,
1079 };
1080
1081 JobType ptype;
1082 unsigned j;
1083
1084 /* We propagate STOP as STOP, but RESTART only
1085 * as TRY_RESTART, in order not to start
1086 * dependencies that are not around. */
1087 ptype = type == JOB_RESTART ? JOB_TRY_RESTART : type;
1088
1089 for (j = 0; j < ELEMENTSOF(propagate_deps); j++)
1090 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[propagate_deps[j]]) {
1091 JobType nt;
1092
1093 nt = job_type_collapse(ptype, dep);
1094 if (nt == JOB_NOP)
1095 continue;
1096
1097 r = transaction_add_job_and_dependencies(tr, nt, dep, ret, true, false, false, ignore_order, e);
1098 if (r < 0) {
1099 if (r != -EBADR) /* job type not applicable */
1100 goto fail;
1101
1102 sd_bus_error_free(e);
1103 }
1104 }
1105 }
1106
1107 if (type == JOB_RELOAD)
1108 transaction_add_propagate_reload_jobs(tr, ret->unit, ret, ignore_order, e);
1109
1110 /* JOB_VERIFY_ACTIVE requires no dependency handling */
1111 }
1112
1113 return 0;
1114
1115 fail:
1116 return r;
1117 }
1118
1119 int transaction_add_isolate_jobs(Transaction *tr, Manager *m) {
1120 Unit *u;
1121 char *k;
1122 int r;
1123
1124 assert(tr);
1125 assert(m);
1126
1127 HASHMAP_FOREACH_KEY(u, k, m->units) {
1128
1129 /* ignore aliases */
1130 if (u->id != k)
1131 continue;
1132
1133 if (u->ignore_on_isolate)
1134 continue;
1135
1136 /* No need to stop inactive jobs */
1137 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->job)
1138 continue;
1139
1140 /* Is there already something listed for this? */
1141 if (hashmap_get(tr->jobs, u))
1142 continue;
1143
1144 r = transaction_add_job_and_dependencies(tr, JOB_STOP, u, tr->anchor_job, true, false, false, false, NULL);
1145 if (r < 0)
1146 log_unit_warning_errno(u, r, "Cannot add isolate job, ignoring: %m");
1147 }
1148
1149 return 0;
1150 }
1151
1152 int transaction_add_triggering_jobs(Transaction *tr, Unit *u) {
1153 void *v;
1154 Unit *trigger;
1155 int r;
1156
1157 assert(tr);
1158 assert(u);
1159
1160 HASHMAP_FOREACH_KEY(v, trigger, u->dependencies[UNIT_TRIGGERED_BY]) {
1161 /* No need to stop inactive jobs */
1162 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(trigger)) && !trigger->job)
1163 continue;
1164
1165 /* Is there already something listed for this? */
1166 if (hashmap_get(tr->jobs, trigger))
1167 continue;
1168
1169 r = transaction_add_job_and_dependencies(tr, JOB_STOP, trigger, tr->anchor_job, true, false, false, false, NULL);
1170 if (r < 0)
1171 log_unit_warning_errno(u, r, "Cannot add triggered by job, ignoring: %m");
1172 }
1173
1174 return 0;
1175 }
1176
1177 Transaction *transaction_new(bool irreversible) {
1178 Transaction *tr;
1179
1180 tr = new0(Transaction, 1);
1181 if (!tr)
1182 return NULL;
1183
1184 tr->jobs = hashmap_new(NULL);
1185 if (!tr->jobs)
1186 return mfree(tr);
1187
1188 tr->irreversible = irreversible;
1189
1190 return tr;
1191 }
1192
1193 void transaction_free(Transaction *tr) {
1194 assert(hashmap_isempty(tr->jobs));
1195 hashmap_free(tr->jobs);
1196 free(tr);
1197 }