]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/transaction.c
network: fix ipv6 tunnel encapsulation limit (#19087)
[thirdparty/systemd.git] / src / core / transaction.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
7c0436b9 2
f2b68789 3#include <fcntl.h>
cf0fbc49 4#include <unistd.h>
f2b68789 5
b5efdb8a 6#include "alloc-util.h"
96aad8d1 7#include "bus-common-errors.h"
718db961 8#include "bus-error.h"
5cfa33e0
ZJS
9#include "dbus-unit.h"
10#include "strv.h"
288a74cc 11#include "terminal-util.h"
b5efdb8a 12#include "transaction.h"
75778e21
MS
13
14static void transaction_unlink_job(Transaction *tr, Job *j, bool delete_dependencies);
15
16static 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
d6a093d0 24 job_free(j);
75778e21
MS
25}
26
27static 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
37void transaction_abort(Transaction *tr) {
38 Job *j;
39
40 assert(tr);
41
42 while ((j = hashmap_first(tr->jobs)))
1b9cea0c 43 transaction_delete_job(tr, j, false);
75778e21
MS
44
45 assert(hashmap_isempty(tr->jobs));
75778e21
MS
46}
47
0d9989aa 48static void transaction_find_jobs_that_matter_to_anchor(Job *j, unsigned generation) {
75778e21
MS
49 JobDependency *l;
50
75778e21
MS
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
0d9989aa
MS
56 j->matters_to_anchor = true;
57 j->generation = generation;
75778e21 58
0d9989aa 59 LIST_FOREACH(subject, l, j->subject_list) {
75778e21
MS
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
0d9989aa 69 transaction_find_jobs_that_matter_to_anchor(l->object, generation);
75778e21
MS
70 }
71}
72
73static 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;
23ade460 85 j->irreversible = j->irreversible || other->irreversible;
75778e21
MS
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
44a6b1b6 126_pure_ static bool job_is_conflicted_by(Job *j) {
75778e21
MS
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
141static 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
f2341e0a 174 log_unit_debug(j->unit,
66870f90
ZJS
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)));
f2341e0a 178 log_unit_debug(k->unit,
66870f90
ZJS
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)));
75778e21
MS
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. */
f2341e0a 207 log_unit_debug(d->unit,
75cb8502
ZJS
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),
66870f90 211 d->unit->id, job_type_to_string(d->type));
75778e21
MS
212 transaction_delete_job(tr, d, true);
213 return 0;
214 }
215
216 return -EINVAL;
217}
218
718db961 219static int transaction_merge_jobs(Transaction *tr, sd_bus_error *e) {
75778e21 220 Job *j;
75778e21
MS
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. */
90e74a66 227 HASHMAP_FOREACH(j, tr->jobs) {
75778e21
MS
228 JobType t;
229 Job *k;
230
231 t = j->type;
232 LIST_FOREACH(transaction, k, j->transaction_next) {
e0209d83 233 if (job_type_merge_and_collapse(&t, k->type, j->unit) >= 0)
75778e21
MS
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 */
7358dc02
ZJS
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);
75778e21
MS
254 }
255 }
256
257 /* Second step, merge the jobs. */
90e74a66 258 HASHMAP_FOREACH(j, tr->jobs) {
75778e21
MS
259 JobType t = j->type;
260 Job *k;
261
e0209d83 262 /* Merge all transaction jobs for j->unit */
75778e21 263 LIST_FOREACH(transaction, k, j->transaction_next)
e0209d83 264 assert_se(job_type_merge_and_collapse(&t, k->type, j->unit) == 0);
75778e21 265
75778e21 266 while ((k = j->transaction_next)) {
656bbffc 267 if (tr->anchor_job == k) {
75778e21
MS
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
75778e21
MS
274 assert(!j->transaction_next);
275 assert(!j->transaction_prev);
276 }
277
278 return 0;
279}
280
cc479760 281static void transaction_drop_redundant(Transaction *tr) {
ca006fc6 282 bool again;
75778e21 283
ca006fc6
LP
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. */
75778e21 286
055163ad 287 assert(tr);
75778e21 288
ca006fc6 289 do {
ca006fc6
LP
290 Job *j;
291
292 again = false;
293
90e74a66 294 HASHMAP_FOREACH(j, tr->jobs) {
ca006fc6
LP
295 bool keep = false;
296 Job *k;
297
298 LIST_FOREACH(transaction, k, j)
299 if (tr->anchor_job == k ||
cc479760 300 !job_type_is_redundant(k->type, unit_active_state(k->unit)) ||
ca006fc6
LP
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 }
75778e21 313 }
ca006fc6 314 } while (again);
75778e21
MS
315}
316
44a6b1b6 317_pure_ static bool unit_matters_to_anchor(Unit *u, Job *j) {
75778e21
MS
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
924775e8
ZJS
331static 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);
38cd55b0 337 if (!GREEDY_REALLOC(ans, alloc, size + next + 1))
5fecf46d 338 return mfree(ans);
924775e8
ZJS
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
718db961 349static int transaction_verify_order_one(Transaction *tr, Job *j, Job *from, unsigned generation, sd_bus_error *e) {
75778e21 350 Unit *u;
eef85c4a 351 void *v;
75778e21 352 int r;
dfd79eca
MK
353 static const UnitDependency directions[] = {
354 UNIT_BEFORE,
355 UNIT_AFTER,
356 };
357 size_t d;
75778e21
MS
358
359 assert(tr);
360 assert(j);
361 assert(!j->transaction_prev);
362
363 /* Does a recursive sweep through the ordering graph, looking
1244d8d6 364 * for a cycle. If we find a cycle we try to break it. */
75778e21
MS
365
366 /* Have we seen this before? */
367 if (j->generation == generation) {
924775e8
ZJS
368 Job *k, *delete = NULL;
369 _cleanup_free_ char **array = NULL, *unit_ids = NULL;
370 char **unit_id, **job_type;
75778e21
MS
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
924775e8
ZJS
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
75778e21
MS
384 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
385
924775e8
ZJS
386 /* For logging below */
387 if (strv_push_pair(&array, k->unit->id, (char*) job_type_to_string(k->type)) < 0)
388 log_oom();
75778e21 389
ece174c5 390 if (!delete && hashmap_get(tr->jobs, k->unit) && !unit_matters_to_anchor(k->unit, k))
924775e8 391 /* Ok, we can drop this one, so let's do so. */
75778e21 392 delete = k;
75778e21 393
924775e8 394 /* Check if this in fact was the beginning of the cycle */
75778e21
MS
395 if (k == j)
396 break;
397 }
398
924775e8
ZJS
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,
a1230ff9 408 unit_ids);
75778e21
MS
409
410 if (delete) {
dc9b5816 411 const char *status;
924775e8
ZJS
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),
a1230ff9 417 unit_ids);
dc9b5816
ZJS
418
419 if (log_get_show_color())
420 status = ANSI_HIGHLIGHT_RED " SKIP " ANSI_NORMAL;
421 else
422 status = " SKIP ";
423
5bcf34eb
ZJS
424 unit_status_printf(delete->unit,
425 STATUS_TYPE_NOTICE,
426 status,
297d0749 427 "Ordering cycle found, skipping %s");
75778e21
MS
428 transaction_delete_unit(tr, delete->unit);
429 return -EAGAIN;
430 }
431
924775e8
ZJS
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),
a1230ff9 435 unit_ids);
75778e21 436
7358dc02
ZJS
437 return sd_bus_error_setf(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC,
438 "Transaction order is cyclic. See system logs for details.");
75778e21
MS
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
dfd79eca
MK
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++) {
90e74a66 453 HASHMAP_FOREACH_KEY(v, u, j->unit->dependencies[directions[d]]) {
dfd79eca
MK
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)
75778e21 469 continue;
75778e21 470
dfd79eca
MK
471 r = transaction_verify_order_one(tr, o, j, generation, e);
472 if (r < 0)
473 return r;
474 }
75778e21
MS
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
718db961 484static int transaction_verify_order(Transaction *tr, unsigned *generation, sd_bus_error *e) {
75778e21
MS
485 Job *j;
486 int r;
75778e21
MS
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
90e74a66 497 HASHMAP_FOREACH(j, tr->jobs) {
3cc2aff1
LP
498 r = transaction_verify_order_one(tr, j, NULL, g, e);
499 if (r < 0)
75778e21 500 return r;
3cc2aff1 501 }
75778e21
MS
502
503 return 0;
504}
505
506static void transaction_collect_garbage(Transaction *tr) {
ca006fc6 507 bool again;
75778e21
MS
508
509 assert(tr);
510
511 /* Drop jobs that are not required by any other job */
512
ca006fc6 513 do {
ca006fc6
LP
514 Job *j;
515
516 again = false;
517
90e74a66 518 HASHMAP_FOREACH(j, tr->jobs) {
ca006fc6
LP
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
78218e62
JK
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");
75778e21
MS
533 }
534
ca006fc6 535 } while (again);
75778e21
MS
536}
537
718db961 538static int transaction_is_destructive(Transaction *tr, JobMode mode, sd_bus_error *e) {
75778e21
MS
539 Job *j;
540
541 assert(tr);
542
543 /* Checks whether applying this transaction means that
544 * existing jobs would be replaced */
545
90e74a66 546 HASHMAP_FOREACH(j, tr->jobs) {
75778e21
MS
547
548 /* Assume merged */
549 assert(!j->transaction_prev);
550 assert(!j->transaction_next);
551
23ade460 552 if (j->unit->job && (mode == JOB_FAIL || j->unit->job->irreversible) &&
c21b92ff 553 job_type_is_conflicting(j->unit->job->type, j->type))
7358dc02 554 return sd_bus_error_setf(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE,
cf99f8ea
LP
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));
75778e21
MS
558 }
559
560 return 0;
561}
562
563static void transaction_minimize_impact(Transaction *tr) {
055163ad 564 Job *j;
055163ad 565
75778e21
MS
566 assert(tr);
567
568 /* Drops all unnecessary jobs that reverse already active jobs
569 * or that stop a running service. */
570
055163ad 571rescan:
90e74a66 572 HASHMAP_FOREACH(j, tr->jobs) {
055163ad
MS
573 LIST_FOREACH(transaction, j, j) {
574 bool stops_running_service, changes_existing_job;
75778e21 575
055163ad
MS
576 /* If it matters, we shouldn't drop it */
577 if (j->matters_to_anchor)
578 continue;
75778e21 579
055163ad
MS
580 /* Would this stop a running service?
581 * Would this change an existing job?
582 * If so, let's drop this entry */
75778e21 583
055163ad
MS
584 stops_running_service =
585 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
75778e21 586
055163ad
MS
587 changes_existing_job =
588 j->unit->job &&
589 job_type_is_conflicting(j->type, j->unit->job->type);
75778e21 590
055163ad
MS
591 if (!stops_running_service && !changes_existing_job)
592 continue;
75778e21 593
055163ad 594 if (stops_running_service)
f2341e0a 595 log_unit_debug(j->unit,
66870f90
ZJS
596 "%s/%s would stop a running service.",
597 j->unit->id, job_type_to_string(j->type));
75778e21 598
055163ad 599 if (changes_existing_job)
f2341e0a 600 log_unit_debug(j->unit,
66870f90
ZJS
601 "%s/%s would change existing job.",
602 j->unit->id, job_type_to_string(j->type));
75778e21 603
055163ad 604 /* Ok, let's get rid of this */
f2341e0a 605 log_unit_debug(j->unit,
66870f90
ZJS
606 "Deleting %s/%s to minimize impact.",
607 j->unit->id, job_type_to_string(j->type));
75778e21 608
055163ad
MS
609 transaction_delete_job(tr, j, true);
610 goto rescan;
75778e21 611 }
055163ad 612 }
75778e21
MS
613}
614
50cbaba4
LP
615static int transaction_apply(
616 Transaction *tr,
617 Manager *m,
618 JobMode mode,
619 Set *affected_jobs) {
620
75778e21
MS
621 Job *j;
622 int r;
623
624 /* Moves the transaction jobs to the set of active jobs */
625
3742095b 626 if (IN_SET(mode, JOB_ISOLATE, JOB_FLUSH)) {
75778e21
MS
627
628 /* When isolating first kill all installed jobs which
629 * aren't part of the new transaction */
90e74a66 630 HASHMAP_FOREACH(j, m->jobs) {
75778e21
MS
631 assert(j->installed);
632
2de0b9e9
MO
633 if (j->unit->ignore_on_isolate)
634 continue;
635
75778e21
MS
636 if (hashmap_get(tr->jobs, j->unit))
637 continue;
638
5273510e
MS
639 /* Not invalidating recursively. Avoids triggering
640 * OnFailure= actions of dependent jobs. Also avoids
641 * invalidating our iterator. */
833f92ad 642 job_finish_and_invalidate(j, JOB_CANCELED, false, false);
75778e21
MS
643 }
644 }
645
90e74a66 646 HASHMAP_FOREACH(j, tr->jobs) {
75778e21
MS
647 /* Assume merged */
648 assert(!j->transaction_prev);
649 assert(!j->transaction_next);
650
acf56b72 651 r = hashmap_ensure_put(&m->jobs, NULL, UINT32_TO_PTR(j->id), j);
75778e21
MS
652 if (r < 0)
653 goto rollback;
654 }
655
656 while ((j = hashmap_steal_first(tr->jobs))) {
656bbffc
MS
657 Job *installed_job;
658
75778e21
MS
659 /* Clean the job dependencies */
660 transaction_unlink_job(tr, j, false);
661
656bbffc
MS
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 }
05d576f1 671
75778e21
MS
672 job_add_to_run_queue(j);
673 job_add_to_dbus_queue(j);
a2df3ea4 674 job_start_timer(j, false);
c65eb836 675 job_shutdown_magic(j);
50cbaba4
LP
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);
75778e21
MS
681 }
682
75778e21
MS
683 return 0;
684
685rollback:
686
90e74a66 687 HASHMAP_FOREACH(j, tr->jobs)
75778e21 688 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
75778e21
MS
689
690 return r;
691}
692
50cbaba4
LP
693int transaction_activate(
694 Transaction *tr,
695 Manager *m,
696 JobMode mode,
697 Set *affected_jobs,
698 sd_bus_error *e) {
699
4e7bd268 700 Job *j;
75778e21
MS
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
4e7bd268
MS
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. */
90e74a66 712 HASHMAP_FOREACH(j, m->jobs)
4e7bd268
MS
713 j->generation = 0;
714
75778e21 715 /* First step: figure out which jobs matter */
0d9989aa 716 transaction_find_jobs_that_matter_to_anchor(tr->anchor_job, generation++);
75778e21
MS
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 */
cc479760 725 transaction_drop_redundant(tr);
75778e21
MS
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
4ae25393
YW
739 if (r != -EAGAIN)
740 return log_warning_errno(r, "Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error_message(e, r));
75778e21
MS
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
4ae25393
YW
754 if (r != -EAGAIN)
755 return log_warning_errno(r, "Requested transaction contains unmergeable jobs: %s", bus_error_message(e, r));
75778e21
MS
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. */
cc479760 767 transaction_drop_redundant(tr);
75778e21
MS
768
769 /* Ninth step: check whether we can actually apply this */
23ade460 770 r = transaction_is_destructive(tr, mode, e);
4ae25393
YW
771 if (r < 0)
772 return log_notice_errno(r, "Requested transaction contradicts existing jobs: %s", bus_error_message(e, r));
75778e21
MS
773
774 /* Tenth step: apply changes */
50cbaba4 775 r = transaction_apply(tr, m, mode, affected_jobs);
23bbb0de
MS
776 if (r < 0)
777 return log_warning_errno(r, "Failed to apply transaction: %m");
75778e21
MS
778
779 assert(hashmap_isempty(tr->jobs));
75778e21 780
f2b68789
LP
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
31a7eb86
ZJS
788 if (m->idle_pipe[0] < 0 && m->idle_pipe[1] < 0 &&
789 m->idle_pipe[2] < 0 && m->idle_pipe[3] < 0) {
1afaa7e8
LP
790 (void) pipe2(m->idle_pipe, O_NONBLOCK|O_CLOEXEC);
791 (void) pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC);
31a7eb86 792 }
f2b68789
LP
793 }
794
75778e21
MS
795 return 0;
796}
797
4bd29fe5 798static Job* transaction_add_one_job(Transaction *tr, JobType type, Unit *unit, bool *is_new) {
75778e21
MS
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
3c956cfe
MS
820 j = job_new(unit, type);
821 if (!j)
822 return NULL;
75778e21
MS
823
824 j->generation = 0;
825 j->marker = NULL;
826 j->matters_to_anchor = false;
23ade460 827 j->irreversible = tr->irreversible;
75778e21 828
71fda00f 829 LIST_PREPEND(transaction, f, j);
75778e21
MS
830
831 if (hashmap_replace(tr->jobs, unit, f) < 0) {
71fda00f 832 LIST_REMOVE(transaction, f, j);
75778e21
MS
833 job_free(j);
834 return NULL;
835 }
836
837 if (is_new)
838 *is_new = true;
839
78218e62 840 log_trace("Added job %s/%s to transaction.", unit->id, job_type_to_string(type));
75778e21
MS
841
842 return j;
843}
844
845static 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)
e6eda1f2 862 job_dependency_free(j->subject_list);
75778e21
MS
863
864 while (j->object_list) {
865 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
866
e6eda1f2 867 job_dependency_free(j->object_list);
75778e21
MS
868
869 if (other && delete_dependencies) {
f2341e0a 870 log_unit_debug(other->unit,
66870f90
ZJS
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));
75778e21
MS
874 transaction_delete_job(tr, other, delete_dependencies);
875 }
876 }
877}
878
15d167f8 879void transaction_add_propagate_reload_jobs(Transaction *tr, Unit *unit, Job *by, bool ignore_order, sd_bus_error *e) {
15d167f8 880 JobType nt;
eef85c4a
LP
881 Unit *dep;
882 void *v;
15d167f8
JW
883 int r;
884
885 assert(tr);
886 assert(unit);
887
90e74a66 888 HASHMAP_FOREACH_KEY(v, dep, unit->dependencies[UNIT_PROPAGATES_RELOAD_TO]) {
15d167f8
JW
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
75778e21
MS
903int transaction_add_job_and_dependencies(
904 Transaction *tr,
905 JobType type,
906 Unit *unit,
907 Job *by,
908 bool matters,
75778e21
MS
909 bool conflicts,
910 bool ignore_requirements,
911 bool ignore_order,
718db961 912 sd_bus_error *e) {
eef85c4a
LP
913
914 bool is_new;
75778e21 915 Unit *dep;
eef85c4a
LP
916 Job *ret;
917 void *v;
75778e21 918 int r;
75778e21
MS
919
920 assert(tr);
921 assert(type < _JOB_TYPE_MAX);
e0209d83 922 assert(type < _JOB_TYPE_MAX_IN_TRANSACTION);
75778e21
MS
923 assert(unit);
924
43706330
IS
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. */
2c289ea8 929 if (MANAGER_IS_RELOADING(unit->manager))
43706330
IS
930 unit_coldplug(unit);
931
78218e62
JK
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));
75778e21 934
c4555ad8
LP
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. */
0377cd29 937 if (!UNIT_IS_LOAD_COMPLETE(unit->load_state))
c6497ccb 938 return sd_bus_error_setf(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->id);
75778e21 939
ee87525c 940 if (type != JOB_STOP) {
e49da001 941 r = bus_unit_validate_load_state(unit, e);
cda66772
LB
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
81be2388 948 * we need to try again — even if the cache is current, it might have been
cda66772
LB
949 * updated in a different context before we had a chance to retry loading
950 * this particular unit.
81be2388 951 *
cda66772
LB
952 * Given building up the transaction is a synchronous operation, attempt
953 * to load the unit immediately. */
81be2388 954 if (r < 0 && manager_unit_cache_should_retry_load(unit)) {
94efaa31 955 sd_bus_error_free(e);
cda66772
LB
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 }
ee87525c
FB
962 if (r < 0)
963 return r;
75778e21
MS
964 }
965
7358dc02
ZJS
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);
75778e21 970
75778e21 971 /* First add the job. */
4bd29fe5 972 ret = transaction_add_one_job(tr, type, unit, &is_new);
75778e21
MS
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. */
e6eda1f2
MS
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. */
4483f694
MS
984 assert(!tr->anchor_job);
985 tr->anchor_job = ret;
b94fbd30 986 }
e0209d83
MS
987
988 if (is_new && !ignore_requirements && type != JOB_NOP) {
75778e21
MS
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) {
90e74a66 994 SET_FOREACH(dep, following) {
4bd29fe5 995 r = transaction_add_job_and_dependencies(tr, type, dep, ret, false, false, false, ignore_order, e);
75778e21 996 if (r < 0) {
8ed6f81b
YW
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));
69301c17 1000 sd_bus_error_free(e);
75778e21
MS
1001 }
1002 }
1003
1004 set_free(following);
1005 }
1006
1007 /* Finally, recursively add in all dependencies. */
3742095b 1008 if (IN_SET(type, JOB_START, JOB_RESTART)) {
90e74a66 1009 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_REQUIRES]) {
4bd29fe5 1010 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
75778e21 1011 if (r < 0) {
114400df 1012 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1013 goto fail;
1014
69301c17 1015 sd_bus_error_free(e);
75778e21
MS
1016 }
1017 }
1018
90e74a66 1019 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_BINDS_TO]) {
4bd29fe5 1020 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
75778e21 1021 if (r < 0) {
114400df 1022 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1023 goto fail;
1024
69301c17 1025 sd_bus_error_free(e);
75778e21
MS
1026 }
1027 }
1028
90e74a66 1029 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_WANTS]) {
4bd29fe5 1030 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, false, false, false, ignore_order, e);
75778e21 1031 if (r < 0) {
114400df 1032 /* unit masked, job type not applicable and unit not found are not considered as errors. */
8ed6f81b
YW
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));
69301c17 1037 sd_bus_error_free(e);
75778e21
MS
1038 }
1039 }
1040
90e74a66 1041 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_REQUISITE]) {
4bd29fe5 1042 r = transaction_add_job_and_dependencies(tr, JOB_VERIFY_ACTIVE, dep, ret, true, false, false, ignore_order, e);
75778e21 1043 if (r < 0) {
114400df 1044 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1045 goto fail;
1046
69301c17 1047 sd_bus_error_free(e);
75778e21
MS
1048 }
1049 }
1050
90e74a66 1051 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_CONFLICTS]) {
4bd29fe5 1052 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, true, true, false, ignore_order, e);
75778e21 1053 if (r < 0) {
114400df 1054 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1055 goto fail;
1056
69301c17 1057 sd_bus_error_free(e);
75778e21
MS
1058 }
1059 }
1060
90e74a66 1061 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_CONFLICTED_BY]) {
4bd29fe5 1062 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, false, false, false, ignore_order, e);
75778e21 1063 if (r < 0) {
f2341e0a
LP
1064 log_unit_warning(dep,
1065 "Cannot add dependency job, ignoring: %s",
1066 bus_error_message(e, r));
69301c17 1067 sd_bus_error_free(e);
75778e21
MS
1068 }
1069 }
1070
1071 }
1072
3742095b 1073 if (IN_SET(type, JOB_STOP, JOB_RESTART)) {
ce74e769
LP
1074 static const UnitDependency propagate_deps[] = {
1075 UNIT_REQUIRED_BY,
1076 UNIT_REQUISITE_OF,
1077 UNIT_BOUND_BY,
1078 UNIT_CONSISTS_OF,
1079 };
75778e21 1080
c6497ccb 1081 JobType ptype;
ce74e769 1082 unsigned j;
75778e21 1083
c6497ccb
LP
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
ce74e769 1089 for (j = 0; j < ELEMENTSOF(propagate_deps); j++)
90e74a66 1090 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[propagate_deps[j]]) {
48894cd0 1091 JobType nt;
85e9a101 1092
48894cd0
LP
1093 nt = job_type_collapse(ptype, dep);
1094 if (nt == JOB_NOP)
1095 continue;
1096
4bd29fe5 1097 r = transaction_add_job_and_dependencies(tr, nt, dep, ret, true, false, false, ignore_order, e);
ce74e769 1098 if (r < 0) {
114400df 1099 if (r != -EBADR) /* job type not applicable */
ce74e769 1100 goto fail;
85e9a101 1101
718db961 1102 sd_bus_error_free(e);
ce74e769 1103 }
85e9a101 1104 }
75778e21
MS
1105 }
1106
15d167f8
JW
1107 if (type == JOB_RELOAD)
1108 transaction_add_propagate_reload_jobs(tr, ret->unit, ret, ignore_order, e);
75778e21 1109
78218e62 1110 /* JOB_VERIFY_ACTIVE requires no dependency handling */
75778e21
MS
1111 }
1112
75778e21
MS
1113 return 0;
1114
1115fail:
1116 return r;
1117}
1118
1119int transaction_add_isolate_jobs(Transaction *tr, Manager *m) {
75778e21
MS
1120 Unit *u;
1121 char *k;
1122 int r;
1123
1124 assert(tr);
1125 assert(m);
1126
90e74a66 1127 HASHMAP_FOREACH_KEY(u, k, m->units) {
75778e21
MS
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
4bd29fe5 1144 r = transaction_add_job_and_dependencies(tr, JOB_STOP, u, tr->anchor_job, true, false, false, false, NULL);
75778e21 1145 if (r < 0)
f2341e0a 1146 log_unit_warning_errno(u, r, "Cannot add isolate job, ignoring: %m");
75778e21
MS
1147 }
1148
1149 return 0;
1150}
1151
1f0f9f21 1152int transaction_add_triggering_jobs(Transaction *tr, Unit *u) {
1f0f9f21
KK
1153 void *v;
1154 Unit *trigger;
1155 int r;
1156
1157 assert(tr);
132e0b53 1158 assert(u);
1f0f9f21 1159
90e74a66 1160 HASHMAP_FOREACH_KEY(v, trigger, u->dependencies[UNIT_TRIGGERED_BY]) {
1f0f9f21
KK
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
23ade460 1177Transaction *transaction_new(bool irreversible) {
75778e21
MS
1178 Transaction *tr;
1179
1180 tr = new0(Transaction, 1);
1181 if (!tr)
1182 return NULL;
1183
d5099efc 1184 tr->jobs = hashmap_new(NULL);
6b430fdb
ZJS
1185 if (!tr->jobs)
1186 return mfree(tr);
75778e21 1187
23ade460
MS
1188 tr->irreversible = irreversible;
1189
75778e21
MS
1190 return tr;
1191}
1192
1193void transaction_free(Transaction *tr) {
1194 assert(hashmap_isempty(tr->jobs));
1195 hashmap_free(tr->jobs);
1196 free(tr);
1197}