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