]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/transaction.c
core: add combined status unit format
[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;
319a4f4b 333 size_t size = 0, next;
924775e8
ZJS
334
335 STRV_FOREACH_PAIR(unit_id, job_type, pairs) {
336 next = strlen(unit_log_field) + strlen(*unit_id);
319a4f4b 337 if (!GREEDY_REALLOC(ans, 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) {
15ed3c3a
LP
350
351 static const UnitDependencyAtom directions[] = {
352 UNIT_ATOM_BEFORE,
353 UNIT_ATOM_AFTER,
dfd79eca 354 };
15ed3c3a
LP
355
356 int r;
75778e21
MS
357
358 assert(tr);
359 assert(j);
360 assert(!j->transaction_prev);
361
defe63b0
LP
362 /* Does a recursive sweep through the ordering graph, looking for a cycle. If we find a cycle we try
363 * to break it. */
75778e21
MS
364
365 /* Have we seen this before? */
366 if (j->generation == generation) {
924775e8
ZJS
367 Job *k, *delete = NULL;
368 _cleanup_free_ char **array = NULL, *unit_ids = NULL;
369 char **unit_id, **job_type;
75778e21 370
defe63b0
LP
371 /* If the marker is NULL we have been here already and decided the job was loop-free from
372 * here. Hence shortcut things and return right-away. */
75778e21
MS
373 if (!j->marker)
374 return 0;
375
defe63b0
LP
376 /* So, the marker is not NULL and we already have been here. We have a cycle. Let's try to
377 * break it. We go backwards in our path and try to find a suitable job to remove. We use the
378 * marker to find our way back, since smart how we are we stored our way back in there. */
75778e21
MS
379 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
380
924775e8
ZJS
381 /* For logging below */
382 if (strv_push_pair(&array, k->unit->id, (char*) job_type_to_string(k->type)) < 0)
383 log_oom();
75778e21 384
ece174c5 385 if (!delete && hashmap_get(tr->jobs, k->unit) && !unit_matters_to_anchor(k->unit, k))
924775e8 386 /* Ok, we can drop this one, so let's do so. */
75778e21 387 delete = k;
75778e21 388
924775e8 389 /* Check if this in fact was the beginning of the cycle */
75778e21
MS
390 if (k == j)
391 break;
392 }
393
924775e8
ZJS
394 unit_ids = merge_unit_ids(j->manager->unit_log_field, array); /* ignore error */
395
396 STRV_FOREACH_PAIR(unit_id, job_type, array)
397 /* logging for j not k here to provide a consistent narrative */
398 log_struct(LOG_WARNING,
399 "MESSAGE=%s: Found %s on %s/%s",
400 j->unit->id,
401 unit_id == array ? "ordering cycle" : "dependency",
402 *unit_id, *job_type,
7325a2b2 403 "%s", unit_ids);
75778e21
MS
404
405 if (delete) {
dc9b5816 406 const char *status;
924775e8
ZJS
407 /* logging for j not k here to provide a consistent narrative */
408 log_struct(LOG_ERR,
409 "MESSAGE=%s: Job %s/%s deleted to break ordering cycle starting with %s/%s",
410 j->unit->id, delete->unit->id, job_type_to_string(delete->type),
411 j->unit->id, job_type_to_string(j->type),
7325a2b2 412 "%s", unit_ids);
dc9b5816
ZJS
413
414 if (log_get_show_color())
415 status = ANSI_HIGHLIGHT_RED " SKIP " ANSI_NORMAL;
416 else
417 status = " SKIP ";
418
5bcf34eb
ZJS
419 unit_status_printf(delete->unit,
420 STATUS_TYPE_NOTICE,
421 status,
297d0749 422 "Ordering cycle found, skipping %s");
75778e21
MS
423 transaction_delete_unit(tr, delete->unit);
424 return -EAGAIN;
425 }
426
924775e8
ZJS
427 log_struct(LOG_ERR,
428 "MESSAGE=%s: Unable to break cycle starting with %s/%s",
429 j->unit->id, j->unit->id, job_type_to_string(j->type),
7325a2b2 430 "%s", 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. */
440 j->marker = from ? from : j;
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) {
055163ad 560 Job *j;
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:
90e74a66 568 HASHMAP_FOREACH(j, tr->jobs) {
055163ad
MS
569 LIST_FOREACH(transaction, j, j) {
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
75778e21
MS
632 if (hashmap_get(tr->jobs, j->unit))
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;
663 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
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)
75778e21 684 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
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
806 LIST_FOREACH(transaction, j, f) {
807 assert(j->unit == unit);
808
809 if (j->type == type) {
810 if (is_new)
811 *is_new = false;
812 return j;
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) {
75778e21
MS
983 Set *following;
984
985 /* If we are following some other unit, make sure we
986 * add all dependencies of everybody following. */
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
998 set_free(following);
999 }
1000
1001 /* Finally, recursively add in all dependencies. */
3742095b 1002 if (IN_SET(type, JOB_START, JOB_RESTART)) {
15ed3c3a 1003 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_START) {
4bd29fe5 1004 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
75778e21 1005 if (r < 0) {
114400df 1006 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1007 goto fail;
1008
69301c17 1009 sd_bus_error_free(e);
75778e21
MS
1010 }
1011 }
1012
15ed3c3a 1013 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_START_IGNORED) {
4bd29fe5 1014 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, false, false, false, ignore_order, e);
75778e21 1015 if (r < 0) {
114400df 1016 /* unit masked, job type not applicable and unit not found are not considered as errors. */
8ed6f81b
YW
1017 log_unit_full_errno(dep,
1018 IN_SET(r, -ERFKILL, -EBADR, -ENOENT) ? LOG_DEBUG : LOG_WARNING,
1019 r, "Cannot add dependency job, ignoring: %s",
1020 bus_error_message(e, r));
69301c17 1021 sd_bus_error_free(e);
75778e21
MS
1022 }
1023 }
1024
15ed3c3a 1025 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_VERIFY) {
4bd29fe5 1026 r = transaction_add_job_and_dependencies(tr, JOB_VERIFY_ACTIVE, dep, ret, true, false, false, ignore_order, e);
75778e21 1027 if (r < 0) {
114400df 1028 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1029 goto fail;
1030
69301c17 1031 sd_bus_error_free(e);
75778e21
MS
1032 }
1033 }
1034
15ed3c3a 1035 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_STOP) {
4bd29fe5 1036 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, true, true, false, ignore_order, e);
75778e21 1037 if (r < 0) {
114400df 1038 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1039 goto fail;
1040
69301c17 1041 sd_bus_error_free(e);
75778e21
MS
1042 }
1043 }
1044
15ed3c3a 1045 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_STOP_IGNORED) {
4bd29fe5 1046 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, false, false, false, ignore_order, e);
75778e21 1047 if (r < 0) {
f2341e0a
LP
1048 log_unit_warning(dep,
1049 "Cannot add dependency job, ignoring: %s",
1050 bus_error_message(e, r));
69301c17 1051 sd_bus_error_free(e);
75778e21
MS
1052 }
1053 }
75778e21
MS
1054 }
1055
3742095b 1056 if (IN_SET(type, JOB_STOP, JOB_RESTART)) {
15ed3c3a 1057 UnitDependencyAtom atom;
c6497ccb 1058 JobType ptype;
75778e21 1059
15ed3c3a 1060 /* We propagate STOP as STOP, but RESTART only as TRY_RESTART, in order not to start
c6497ccb 1061 * dependencies that are not around. */
15ed3c3a
LP
1062 if (type == JOB_RESTART) {
1063 atom = UNIT_ATOM_PROPAGATE_RESTART;
1064 ptype = JOB_TRY_RESTART;
1065 } else {
1066 ptype = JOB_STOP;
1067 atom = UNIT_ATOM_PROPAGATE_STOP;
1068 }
c6497ccb 1069
15ed3c3a
LP
1070 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, atom) {
1071 JobType nt;
85e9a101 1072
15ed3c3a
LP
1073 nt = job_type_collapse(ptype, dep);
1074 if (nt == JOB_NOP)
1075 continue;
48894cd0 1076
15ed3c3a
LP
1077 r = transaction_add_job_and_dependencies(tr, nt, dep, ret, true, false, false, ignore_order, e);
1078 if (r < 0) {
1079 if (r != -EBADR) /* job type not applicable */
1080 goto fail;
85e9a101 1081
15ed3c3a 1082 sd_bus_error_free(e);
85e9a101 1083 }
15ed3c3a 1084 }
75778e21
MS
1085 }
1086
15d167f8
JW
1087 if (type == JOB_RELOAD)
1088 transaction_add_propagate_reload_jobs(tr, ret->unit, ret, ignore_order, e);
75778e21 1089
78218e62 1090 /* JOB_VERIFY_ACTIVE requires no dependency handling */
75778e21
MS
1091 }
1092
75778e21
MS
1093 return 0;
1094
1095fail:
1096 return r;
1097}
1098
1099int transaction_add_isolate_jobs(Transaction *tr, Manager *m) {
75778e21
MS
1100 Unit *u;
1101 char *k;
1102 int r;
1103
1104 assert(tr);
1105 assert(m);
1106
90e74a66 1107 HASHMAP_FOREACH_KEY(u, k, m->units) {
75778e21
MS
1108
1109 /* ignore aliases */
1110 if (u->id != k)
1111 continue;
1112
1113 if (u->ignore_on_isolate)
1114 continue;
1115
1116 /* No need to stop inactive jobs */
1117 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->job)
1118 continue;
1119
1120 /* Is there already something listed for this? */
1121 if (hashmap_get(tr->jobs, u))
1122 continue;
1123
4bd29fe5 1124 r = transaction_add_job_and_dependencies(tr, JOB_STOP, u, tr->anchor_job, true, false, false, false, NULL);
75778e21 1125 if (r < 0)
f2341e0a 1126 log_unit_warning_errno(u, r, "Cannot add isolate job, ignoring: %m");
75778e21
MS
1127 }
1128
1129 return 0;
1130}
1131
1f0f9f21 1132int transaction_add_triggering_jobs(Transaction *tr, Unit *u) {
1f0f9f21
KK
1133 Unit *trigger;
1134 int r;
1135
1136 assert(tr);
132e0b53 1137 assert(u);
1f0f9f21 1138
15ed3c3a
LP
1139 UNIT_FOREACH_DEPENDENCY(trigger, u, UNIT_ATOM_TRIGGERED_BY) {
1140
1f0f9f21
KK
1141 /* No need to stop inactive jobs */
1142 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(trigger)) && !trigger->job)
1143 continue;
1144
1145 /* Is there already something listed for this? */
1146 if (hashmap_get(tr->jobs, trigger))
1147 continue;
1148
1149 r = transaction_add_job_and_dependencies(tr, JOB_STOP, trigger, tr->anchor_job, true, false, false, false, NULL);
1150 if (r < 0)
1151 log_unit_warning_errno(u, r, "Cannot add triggered by job, ignoring: %m");
1152 }
1153
1154 return 0;
1155}
1156
23ade460 1157Transaction *transaction_new(bool irreversible) {
75778e21
MS
1158 Transaction *tr;
1159
1160 tr = new0(Transaction, 1);
1161 if (!tr)
1162 return NULL;
1163
d5099efc 1164 tr->jobs = hashmap_new(NULL);
6b430fdb
ZJS
1165 if (!tr->jobs)
1166 return mfree(tr);
75778e21 1167
23ade460
MS
1168 tr->irreversible = irreversible;
1169
75778e21
MS
1170 return tr;
1171}
1172
1173void transaction_free(Transaction *tr) {
1174 assert(hashmap_isempty(tr->jobs));
1175 hashmap_free(tr->jobs);
1176 free(tr);
1177}