]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/transaction.c
tree-wide: define iterator inside of the macro
[thirdparty/systemd.git] / src / core / transaction.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
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
a4ac27c1
ZJS
651 r = hashmap_ensure_allocated(&m->jobs, NULL);
652 if (r < 0)
653 return r;
654
75778e21
MS
655 r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j);
656 if (r < 0)
657 goto rollback;
658 }
659
660 while ((j = hashmap_steal_first(tr->jobs))) {
656bbffc
MS
661 Job *installed_job;
662
75778e21
MS
663 /* Clean the job dependencies */
664 transaction_unlink_job(tr, j, false);
665
656bbffc
MS
666 installed_job = job_install(j);
667 if (installed_job != j) {
668 /* j has been merged into a previously installed job */
669 if (tr->anchor_job == j)
670 tr->anchor_job = installed_job;
671 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
672 job_free(j);
673 j = installed_job;
674 }
05d576f1 675
75778e21
MS
676 job_add_to_run_queue(j);
677 job_add_to_dbus_queue(j);
a2df3ea4 678 job_start_timer(j, false);
c65eb836 679 job_shutdown_magic(j);
50cbaba4
LP
680
681 /* When 'affected' is specified, let's track all in it all jobs that were touched because of
682 * this transaction. */
683 if (affected_jobs)
684 (void) set_put(affected_jobs, j);
75778e21
MS
685 }
686
75778e21
MS
687 return 0;
688
689rollback:
690
90e74a66 691 HASHMAP_FOREACH(j, tr->jobs)
75778e21 692 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
75778e21
MS
693
694 return r;
695}
696
50cbaba4
LP
697int transaction_activate(
698 Transaction *tr,
699 Manager *m,
700 JobMode mode,
701 Set *affected_jobs,
702 sd_bus_error *e) {
703
4e7bd268 704 Job *j;
75778e21
MS
705 int r;
706 unsigned generation = 1;
707
708 assert(tr);
709
710 /* This applies the changes recorded in tr->jobs to
711 * the actual list of jobs, if possible. */
712
4e7bd268
MS
713 /* Reset the generation counter of all installed jobs. The detection of cycles
714 * looks at installed jobs. If they had a non-zero generation from some previous
715 * walk of the graph, the algorithm would break. */
90e74a66 716 HASHMAP_FOREACH(j, m->jobs)
4e7bd268
MS
717 j->generation = 0;
718
75778e21 719 /* First step: figure out which jobs matter */
0d9989aa 720 transaction_find_jobs_that_matter_to_anchor(tr->anchor_job, generation++);
75778e21
MS
721
722 /* Second step: Try not to stop any running services if
723 * we don't have to. Don't try to reverse running
724 * jobs if we don't have to. */
725 if (mode == JOB_FAIL)
726 transaction_minimize_impact(tr);
727
728 /* Third step: Drop redundant jobs */
cc479760 729 transaction_drop_redundant(tr);
75778e21
MS
730
731 for (;;) {
732 /* Fourth step: Let's remove unneeded jobs that might
733 * be lurking. */
734 if (mode != JOB_ISOLATE)
735 transaction_collect_garbage(tr);
736
737 /* Fifth step: verify order makes sense and correct
738 * cycles if necessary and possible */
739 r = transaction_verify_order(tr, &generation, e);
740 if (r >= 0)
741 break;
742
4ae25393
YW
743 if (r != -EAGAIN)
744 return log_warning_errno(r, "Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error_message(e, r));
75778e21
MS
745
746 /* Let's see if the resulting transaction ordering
747 * graph is still cyclic... */
748 }
749
750 for (;;) {
751 /* Sixth step: let's drop unmergeable entries if
752 * necessary and possible, merge entries we can
753 * merge */
754 r = transaction_merge_jobs(tr, e);
755 if (r >= 0)
756 break;
757
4ae25393
YW
758 if (r != -EAGAIN)
759 return log_warning_errno(r, "Requested transaction contains unmergeable jobs: %s", bus_error_message(e, r));
75778e21
MS
760
761 /* Seventh step: an entry got dropped, let's garbage
762 * collect its dependencies. */
763 if (mode != JOB_ISOLATE)
764 transaction_collect_garbage(tr);
765
766 /* Let's see if the resulting transaction still has
767 * unmergeable entries ... */
768 }
769
770 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
cc479760 771 transaction_drop_redundant(tr);
75778e21
MS
772
773 /* Ninth step: check whether we can actually apply this */
23ade460 774 r = transaction_is_destructive(tr, mode, e);
4ae25393
YW
775 if (r < 0)
776 return log_notice_errno(r, "Requested transaction contradicts existing jobs: %s", bus_error_message(e, r));
75778e21
MS
777
778 /* Tenth step: apply changes */
50cbaba4 779 r = transaction_apply(tr, m, mode, affected_jobs);
23bbb0de
MS
780 if (r < 0)
781 return log_warning_errno(r, "Failed to apply transaction: %m");
75778e21
MS
782
783 assert(hashmap_isempty(tr->jobs));
75778e21 784
f2b68789
LP
785 if (!hashmap_isempty(m->jobs)) {
786 /* Are there any jobs now? Then make sure we have the
787 * idle pipe around. We don't really care too much
788 * whether this works or not, as the idle pipe is a
789 * feature for cosmetics, not actually useful for
790 * anything beyond that. */
791
31a7eb86
ZJS
792 if (m->idle_pipe[0] < 0 && m->idle_pipe[1] < 0 &&
793 m->idle_pipe[2] < 0 && m->idle_pipe[3] < 0) {
1afaa7e8
LP
794 (void) pipe2(m->idle_pipe, O_NONBLOCK|O_CLOEXEC);
795 (void) pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC);
31a7eb86 796 }
f2b68789
LP
797 }
798
75778e21
MS
799 return 0;
800}
801
4bd29fe5 802static Job* transaction_add_one_job(Transaction *tr, JobType type, Unit *unit, bool *is_new) {
75778e21
MS
803 Job *j, *f;
804
805 assert(tr);
806 assert(unit);
807
808 /* Looks for an existing prospective job and returns that. If
809 * it doesn't exist it is created and added to the prospective
810 * jobs list. */
811
812 f = hashmap_get(tr->jobs, unit);
813
814 LIST_FOREACH(transaction, j, f) {
815 assert(j->unit == unit);
816
817 if (j->type == type) {
818 if (is_new)
819 *is_new = false;
820 return j;
821 }
822 }
823
3c956cfe
MS
824 j = job_new(unit, type);
825 if (!j)
826 return NULL;
75778e21
MS
827
828 j->generation = 0;
829 j->marker = NULL;
830 j->matters_to_anchor = false;
23ade460 831 j->irreversible = tr->irreversible;
75778e21 832
71fda00f 833 LIST_PREPEND(transaction, f, j);
75778e21
MS
834
835 if (hashmap_replace(tr->jobs, unit, f) < 0) {
71fda00f 836 LIST_REMOVE(transaction, f, j);
75778e21
MS
837 job_free(j);
838 return NULL;
839 }
840
841 if (is_new)
842 *is_new = true;
843
78218e62 844 log_trace("Added job %s/%s to transaction.", unit->id, job_type_to_string(type));
75778e21
MS
845
846 return j;
847}
848
849static void transaction_unlink_job(Transaction *tr, Job *j, bool delete_dependencies) {
850 assert(tr);
851 assert(j);
852
853 if (j->transaction_prev)
854 j->transaction_prev->transaction_next = j->transaction_next;
855 else if (j->transaction_next)
856 hashmap_replace(tr->jobs, j->unit, j->transaction_next);
857 else
858 hashmap_remove_value(tr->jobs, j->unit, j);
859
860 if (j->transaction_next)
861 j->transaction_next->transaction_prev = j->transaction_prev;
862
863 j->transaction_prev = j->transaction_next = NULL;
864
865 while (j->subject_list)
e6eda1f2 866 job_dependency_free(j->subject_list);
75778e21
MS
867
868 while (j->object_list) {
869 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
870
e6eda1f2 871 job_dependency_free(j->object_list);
75778e21
MS
872
873 if (other && delete_dependencies) {
f2341e0a 874 log_unit_debug(other->unit,
66870f90
ZJS
875 "Deleting job %s/%s as dependency of job %s/%s",
876 other->unit->id, job_type_to_string(other->type),
877 j->unit->id, job_type_to_string(j->type));
75778e21
MS
878 transaction_delete_job(tr, other, delete_dependencies);
879 }
880 }
881}
882
15d167f8 883void transaction_add_propagate_reload_jobs(Transaction *tr, Unit *unit, Job *by, bool ignore_order, sd_bus_error *e) {
15d167f8 884 JobType nt;
eef85c4a
LP
885 Unit *dep;
886 void *v;
15d167f8
JW
887 int r;
888
889 assert(tr);
890 assert(unit);
891
90e74a66 892 HASHMAP_FOREACH_KEY(v, dep, unit->dependencies[UNIT_PROPAGATES_RELOAD_TO]) {
15d167f8
JW
893 nt = job_type_collapse(JOB_TRY_RELOAD, dep);
894 if (nt == JOB_NOP)
895 continue;
896
897 r = transaction_add_job_and_dependencies(tr, nt, dep, by, false, false, false, ignore_order, e);
898 if (r < 0) {
899 log_unit_warning(dep,
900 "Cannot add dependency reload job, ignoring: %s",
901 bus_error_message(e, r));
902 sd_bus_error_free(e);
903 }
904 }
905}
906
75778e21
MS
907int transaction_add_job_and_dependencies(
908 Transaction *tr,
909 JobType type,
910 Unit *unit,
911 Job *by,
912 bool matters,
75778e21
MS
913 bool conflicts,
914 bool ignore_requirements,
915 bool ignore_order,
718db961 916 sd_bus_error *e) {
eef85c4a
LP
917
918 bool is_new;
75778e21 919 Unit *dep;
eef85c4a
LP
920 Job *ret;
921 void *v;
75778e21 922 int r;
75778e21
MS
923
924 assert(tr);
925 assert(type < _JOB_TYPE_MAX);
e0209d83 926 assert(type < _JOB_TYPE_MAX_IN_TRANSACTION);
75778e21
MS
927 assert(unit);
928
43706330
IS
929 /* Before adding jobs for this unit, let's ensure that its state has been loaded
930 * This matters when jobs are spawned as part of coldplugging itself (see e. g. path_coldplug()).
931 * This way, we "recursively" coldplug units, ensuring that we do not look at state of
932 * not-yet-coldplugged units. */
2c289ea8 933 if (MANAGER_IS_RELOADING(unit->manager))
43706330
IS
934 unit_coldplug(unit);
935
78218e62
JK
936 if (by)
937 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 938
c4555ad8
LP
939 /* Safety check that the unit is a valid state, i.e. not in UNIT_STUB or UNIT_MERGED which should only be set
940 * temporarily. */
941 if (!IN_SET(unit->load_state, UNIT_LOADED, UNIT_ERROR, UNIT_NOT_FOUND, UNIT_BAD_SETTING, UNIT_MASKED))
c6497ccb 942 return sd_bus_error_setf(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->id);
75778e21 943
ee87525c 944 if (type != JOB_STOP) {
e49da001 945 r = bus_unit_validate_load_state(unit, e);
cda66772
LB
946 /* The time-based cache allows to start new units without daemon-reload,
947 * but if they are already referenced (because of dependencies or ordering)
948 * then we have to force a load of the fragment. As an optimization, check
949 * first if anything in the usual paths was modified since the last time
950 * the cache was loaded. Also check if the last time an attempt to load the
951 * unit was made was before the most recent cache refresh, so that we know
81be2388 952 * we need to try again — even if the cache is current, it might have been
cda66772
LB
953 * updated in a different context before we had a chance to retry loading
954 * this particular unit.
81be2388 955 *
cda66772
LB
956 * Given building up the transaction is a synchronous operation, attempt
957 * to load the unit immediately. */
81be2388 958 if (r < 0 && manager_unit_cache_should_retry_load(unit)) {
94efaa31 959 sd_bus_error_free(e);
cda66772
LB
960 unit->load_state = UNIT_STUB;
961 r = unit_load(unit);
962 if (r < 0 || unit->load_state == UNIT_STUB)
963 unit->load_state = UNIT_NOT_FOUND;
964 r = bus_unit_validate_load_state(unit, e);
965 }
ee87525c
FB
966 if (r < 0)
967 return r;
75778e21
MS
968 }
969
7358dc02
ZJS
970 if (!unit_job_is_applicable(unit, type))
971 return sd_bus_error_setf(e, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE,
972 "Job type %s is not applicable for unit %s.",
973 job_type_to_string(type), unit->id);
75778e21 974
75778e21 975 /* First add the job. */
4bd29fe5 976 ret = transaction_add_one_job(tr, type, unit, &is_new);
75778e21
MS
977 if (!ret)
978 return -ENOMEM;
979
980 ret->ignore_order = ret->ignore_order || ignore_order;
981
982 /* Then, add a link to the job. */
e6eda1f2
MS
983 if (by) {
984 if (!job_dependency_new(by, ret, matters, conflicts))
985 return -ENOMEM;
986 } else {
987 /* If the job has no parent job, it is the anchor job. */
4483f694
MS
988 assert(!tr->anchor_job);
989 tr->anchor_job = ret;
b94fbd30 990 }
e0209d83
MS
991
992 if (is_new && !ignore_requirements && type != JOB_NOP) {
75778e21
MS
993 Set *following;
994
995 /* If we are following some other unit, make sure we
996 * add all dependencies of everybody following. */
997 if (unit_following_set(ret->unit, &following) > 0) {
90e74a66 998 SET_FOREACH(dep, following) {
4bd29fe5 999 r = transaction_add_job_and_dependencies(tr, type, dep, ret, false, false, false, ignore_order, e);
75778e21 1000 if (r < 0) {
e0f65994
ZJS
1001 log_unit_full(dep,
1002 r == -ERFKILL ? LOG_INFO : LOG_WARNING,
1003 r, "Cannot add dependency job, ignoring: %s",
1004 bus_error_message(e, r));
69301c17 1005 sd_bus_error_free(e);
75778e21
MS
1006 }
1007 }
1008
1009 set_free(following);
1010 }
1011
1012 /* Finally, recursively add in all dependencies. */
3742095b 1013 if (IN_SET(type, JOB_START, JOB_RESTART)) {
90e74a66 1014 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_REQUIRES]) {
4bd29fe5 1015 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
75778e21 1016 if (r < 0) {
114400df 1017 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1018 goto fail;
1019
69301c17 1020 sd_bus_error_free(e);
75778e21
MS
1021 }
1022 }
1023
90e74a66 1024 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_BINDS_TO]) {
4bd29fe5 1025 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
75778e21 1026 if (r < 0) {
114400df 1027 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1028 goto fail;
1029
69301c17 1030 sd_bus_error_free(e);
75778e21
MS
1031 }
1032 }
1033
90e74a66 1034 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_WANTS]) {
4bd29fe5 1035 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, false, false, false, ignore_order, e);
75778e21 1036 if (r < 0) {
114400df 1037 /* unit masked, job type not applicable and unit not found are not considered as errors. */
f2341e0a 1038 log_unit_full(dep,
76ec966f 1039 IN_SET(r, -ERFKILL, -EBADR, -ENOENT) ? LOG_DEBUG : LOG_WARNING,
f14637fc 1040 r, "Cannot add dependency job, ignoring: %s",
f2341e0a 1041 bus_error_message(e, r));
69301c17 1042 sd_bus_error_free(e);
75778e21
MS
1043 }
1044 }
1045
90e74a66 1046 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_REQUISITE]) {
4bd29fe5 1047 r = transaction_add_job_and_dependencies(tr, JOB_VERIFY_ACTIVE, dep, ret, true, false, false, ignore_order, e);
75778e21 1048 if (r < 0) {
114400df 1049 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1050 goto fail;
1051
69301c17 1052 sd_bus_error_free(e);
75778e21
MS
1053 }
1054 }
1055
90e74a66 1056 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_CONFLICTS]) {
4bd29fe5 1057 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, true, true, false, ignore_order, e);
75778e21 1058 if (r < 0) {
114400df 1059 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1060 goto fail;
1061
69301c17 1062 sd_bus_error_free(e);
75778e21
MS
1063 }
1064 }
1065
90e74a66 1066 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[UNIT_CONFLICTED_BY]) {
4bd29fe5 1067 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, false, false, false, ignore_order, e);
75778e21 1068 if (r < 0) {
f2341e0a
LP
1069 log_unit_warning(dep,
1070 "Cannot add dependency job, ignoring: %s",
1071 bus_error_message(e, r));
69301c17 1072 sd_bus_error_free(e);
75778e21
MS
1073 }
1074 }
1075
1076 }
1077
3742095b 1078 if (IN_SET(type, JOB_STOP, JOB_RESTART)) {
ce74e769
LP
1079 static const UnitDependency propagate_deps[] = {
1080 UNIT_REQUIRED_BY,
1081 UNIT_REQUISITE_OF,
1082 UNIT_BOUND_BY,
1083 UNIT_CONSISTS_OF,
1084 };
75778e21 1085
c6497ccb 1086 JobType ptype;
ce74e769 1087 unsigned j;
75778e21 1088
c6497ccb
LP
1089 /* We propagate STOP as STOP, but RESTART only
1090 * as TRY_RESTART, in order not to start
1091 * dependencies that are not around. */
1092 ptype = type == JOB_RESTART ? JOB_TRY_RESTART : type;
1093
ce74e769 1094 for (j = 0; j < ELEMENTSOF(propagate_deps); j++)
90e74a66 1095 HASHMAP_FOREACH_KEY(v, dep, ret->unit->dependencies[propagate_deps[j]]) {
48894cd0 1096 JobType nt;
85e9a101 1097
48894cd0
LP
1098 nt = job_type_collapse(ptype, dep);
1099 if (nt == JOB_NOP)
1100 continue;
1101
4bd29fe5 1102 r = transaction_add_job_and_dependencies(tr, nt, dep, ret, true, false, false, ignore_order, e);
ce74e769 1103 if (r < 0) {
114400df 1104 if (r != -EBADR) /* job type not applicable */
ce74e769 1105 goto fail;
85e9a101 1106
718db961 1107 sd_bus_error_free(e);
ce74e769 1108 }
85e9a101 1109 }
75778e21
MS
1110 }
1111
15d167f8
JW
1112 if (type == JOB_RELOAD)
1113 transaction_add_propagate_reload_jobs(tr, ret->unit, ret, ignore_order, e);
75778e21 1114
78218e62 1115 /* JOB_VERIFY_ACTIVE requires no dependency handling */
75778e21
MS
1116 }
1117
75778e21
MS
1118 return 0;
1119
1120fail:
1121 return r;
1122}
1123
1124int transaction_add_isolate_jobs(Transaction *tr, Manager *m) {
75778e21
MS
1125 Unit *u;
1126 char *k;
1127 int r;
1128
1129 assert(tr);
1130 assert(m);
1131
90e74a66 1132 HASHMAP_FOREACH_KEY(u, k, m->units) {
75778e21
MS
1133
1134 /* ignore aliases */
1135 if (u->id != k)
1136 continue;
1137
1138 if (u->ignore_on_isolate)
1139 continue;
1140
1141 /* No need to stop inactive jobs */
1142 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->job)
1143 continue;
1144
1145 /* Is there already something listed for this? */
1146 if (hashmap_get(tr->jobs, u))
1147 continue;
1148
4bd29fe5 1149 r = transaction_add_job_and_dependencies(tr, JOB_STOP, u, tr->anchor_job, true, false, false, false, NULL);
75778e21 1150 if (r < 0)
f2341e0a 1151 log_unit_warning_errno(u, r, "Cannot add isolate job, ignoring: %m");
75778e21
MS
1152 }
1153
1154 return 0;
1155}
1156
1f0f9f21 1157int transaction_add_triggering_jobs(Transaction *tr, Unit *u) {
1f0f9f21
KK
1158 void *v;
1159 Unit *trigger;
1160 int r;
1161
1162 assert(tr);
132e0b53 1163 assert(u);
1f0f9f21 1164
90e74a66 1165 HASHMAP_FOREACH_KEY(v, trigger, u->dependencies[UNIT_TRIGGERED_BY]) {
1f0f9f21
KK
1166 /* No need to stop inactive jobs */
1167 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(trigger)) && !trigger->job)
1168 continue;
1169
1170 /* Is there already something listed for this? */
1171 if (hashmap_get(tr->jobs, trigger))
1172 continue;
1173
1174 r = transaction_add_job_and_dependencies(tr, JOB_STOP, trigger, tr->anchor_job, true, false, false, false, NULL);
1175 if (r < 0)
1176 log_unit_warning_errno(u, r, "Cannot add triggered by job, ignoring: %m");
1177 }
1178
1179 return 0;
1180}
1181
23ade460 1182Transaction *transaction_new(bool irreversible) {
75778e21
MS
1183 Transaction *tr;
1184
1185 tr = new0(Transaction, 1);
1186 if (!tr)
1187 return NULL;
1188
d5099efc 1189 tr->jobs = hashmap_new(NULL);
6b430fdb
ZJS
1190 if (!tr->jobs)
1191 return mfree(tr);
75778e21 1192
23ade460
MS
1193 tr->irreversible = irreversible;
1194
75778e21
MS
1195 return tr;
1196}
1197
1198void transaction_free(Transaction *tr) {
1199 assert(hashmap_isempty(tr->jobs));
1200 hashmap_free(tr->jobs);
1201 free(tr);
1202}