]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/transaction.c
various: make parse_env_file error handling the same in various places
[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,
04d232d8
ZJS
422 "Ordering cycle found, skipping %s",
423 unit_status_string(delete->unit, NULL));
75778e21
MS
424 transaction_delete_unit(tr, delete->unit);
425 return -EAGAIN;
426 }
427
924775e8
ZJS
428 log_struct(LOG_ERR,
429 "MESSAGE=%s: Unable to break cycle starting with %s/%s",
430 j->unit->id, j->unit->id, job_type_to_string(j->type),
7325a2b2 431 "%s", unit_ids);
75778e21 432
7358dc02
ZJS
433 return sd_bus_error_setf(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC,
434 "Transaction order is cyclic. See system logs for details.");
75778e21
MS
435 }
436
437 /* Make the marker point to where we come from, so that we can
438 * find our way backwards if we want to break a cycle. We use
439 * a special marker for the beginning: we point to
440 * ourselves. */
441 j->marker = from ? from : j;
442 j->generation = generation;
443
dfd79eca
MK
444 /* Actual ordering of jobs depends on the unit ordering dependency and job types. We need to traverse
445 * the graph over 'before' edges in the actual job execution order. We traverse over both unit
446 * ordering dependencies and we test with job_compare() whether it is the 'before' edge in the job
447 * execution ordering. */
15ed3c3a
LP
448 for (size_t d = 0; d < ELEMENTSOF(directions); d++) {
449 Unit *u;
450
451 UNIT_FOREACH_DEPENDENCY(u, j->unit, directions[d]) {
dfd79eca
MK
452 Job *o;
453
454 /* Is there a job for this unit? */
455 o = hashmap_get(tr->jobs, u);
456 if (!o) {
defe63b0
LP
457 /* Ok, there is no job for this in the transaction, but maybe there is
458 * already one running? */
dfd79eca
MK
459 o = u->job;
460 if (!o)
461 continue;
462 }
463
464 /* Cut traversing if the job j is not really *before* o. */
465 if (job_compare(j, o, directions[d]) >= 0)
75778e21 466 continue;
75778e21 467
dfd79eca
MK
468 r = transaction_verify_order_one(tr, o, j, generation, e);
469 if (r < 0)
470 return r;
471 }
75778e21
MS
472 }
473
474 /* Ok, let's backtrack, and remember that this entry is not on
475 * our path anymore. */
476 j->marker = NULL;
477
478 return 0;
479}
480
718db961 481static int transaction_verify_order(Transaction *tr, unsigned *generation, sd_bus_error *e) {
75778e21
MS
482 Job *j;
483 int r;
75778e21
MS
484 unsigned g;
485
486 assert(tr);
487 assert(generation);
488
489 /* Check if the ordering graph is cyclic. If it is, try to fix
490 * that up by dropping one of the jobs. */
491
492 g = (*generation)++;
493
90e74a66 494 HASHMAP_FOREACH(j, tr->jobs) {
3cc2aff1
LP
495 r = transaction_verify_order_one(tr, j, NULL, g, e);
496 if (r < 0)
75778e21 497 return r;
3cc2aff1 498 }
75778e21
MS
499
500 return 0;
501}
502
503static void transaction_collect_garbage(Transaction *tr) {
ca006fc6 504 bool again;
75778e21
MS
505
506 assert(tr);
507
508 /* Drop jobs that are not required by any other job */
509
ca006fc6 510 do {
ca006fc6
LP
511 Job *j;
512
513 again = false;
514
90e74a66 515 HASHMAP_FOREACH(j, tr->jobs) {
ca006fc6
LP
516 if (tr->anchor_job == j)
517 continue;
518
519 if (!j->object_list) {
520 log_trace("Garbage collecting job %s/%s", j->unit->id, job_type_to_string(j->type));
521 transaction_delete_job(tr, j, true);
522 again = true;
523 break;
524 }
525
78218e62
JK
526 log_trace("Keeping job %s/%s because of %s/%s",
527 j->unit->id, job_type_to_string(j->type),
528 j->object_list->subject ? j->object_list->subject->unit->id : "root",
529 j->object_list->subject ? job_type_to_string(j->object_list->subject->type) : "root");
75778e21
MS
530 }
531
ca006fc6 532 } while (again);
75778e21
MS
533}
534
718db961 535static int transaction_is_destructive(Transaction *tr, JobMode mode, sd_bus_error *e) {
75778e21
MS
536 Job *j;
537
538 assert(tr);
539
540 /* Checks whether applying this transaction means that
541 * existing jobs would be replaced */
542
90e74a66 543 HASHMAP_FOREACH(j, tr->jobs) {
75778e21
MS
544
545 /* Assume merged */
546 assert(!j->transaction_prev);
547 assert(!j->transaction_next);
548
23ade460 549 if (j->unit->job && (mode == JOB_FAIL || j->unit->job->irreversible) &&
c21b92ff 550 job_type_is_conflicting(j->unit->job->type, j->type))
7358dc02 551 return sd_bus_error_setf(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE,
cf99f8ea
LP
552 "Transaction for %s/%s is destructive (%s has '%s' job queued, but '%s' is included in transaction).",
553 tr->anchor_job->unit->id, job_type_to_string(tr->anchor_job->type),
554 j->unit->id, job_type_to_string(j->unit->job->type), job_type_to_string(j->type));
75778e21
MS
555 }
556
557 return 0;
558}
559
560static void transaction_minimize_impact(Transaction *tr) {
055163ad 561 Job *j;
055163ad 562
75778e21
MS
563 assert(tr);
564
565 /* Drops all unnecessary jobs that reverse already active jobs
566 * or that stop a running service. */
567
055163ad 568rescan:
90e74a66 569 HASHMAP_FOREACH(j, tr->jobs) {
055163ad
MS
570 LIST_FOREACH(transaction, j, j) {
571 bool stops_running_service, changes_existing_job;
75778e21 572
055163ad
MS
573 /* If it matters, we shouldn't drop it */
574 if (j->matters_to_anchor)
575 continue;
75778e21 576
055163ad
MS
577 /* Would this stop a running service?
578 * Would this change an existing job?
579 * If so, let's drop this entry */
75778e21 580
055163ad
MS
581 stops_running_service =
582 j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
75778e21 583
055163ad
MS
584 changes_existing_job =
585 j->unit->job &&
586 job_type_is_conflicting(j->type, j->unit->job->type);
75778e21 587
055163ad
MS
588 if (!stops_running_service && !changes_existing_job)
589 continue;
75778e21 590
055163ad 591 if (stops_running_service)
f2341e0a 592 log_unit_debug(j->unit,
66870f90
ZJS
593 "%s/%s would stop a running service.",
594 j->unit->id, job_type_to_string(j->type));
75778e21 595
055163ad 596 if (changes_existing_job)
f2341e0a 597 log_unit_debug(j->unit,
66870f90
ZJS
598 "%s/%s would change existing job.",
599 j->unit->id, job_type_to_string(j->type));
75778e21 600
055163ad 601 /* Ok, let's get rid of this */
f2341e0a 602 log_unit_debug(j->unit,
66870f90
ZJS
603 "Deleting %s/%s to minimize impact.",
604 j->unit->id, job_type_to_string(j->type));
75778e21 605
055163ad
MS
606 transaction_delete_job(tr, j, true);
607 goto rescan;
75778e21 608 }
055163ad 609 }
75778e21
MS
610}
611
50cbaba4
LP
612static int transaction_apply(
613 Transaction *tr,
614 Manager *m,
615 JobMode mode,
616 Set *affected_jobs) {
617
75778e21
MS
618 Job *j;
619 int r;
620
621 /* Moves the transaction jobs to the set of active jobs */
622
3742095b 623 if (IN_SET(mode, JOB_ISOLATE, JOB_FLUSH)) {
75778e21
MS
624
625 /* When isolating first kill all installed jobs which
626 * aren't part of the new transaction */
90e74a66 627 HASHMAP_FOREACH(j, m->jobs) {
75778e21
MS
628 assert(j->installed);
629
2de0b9e9
MO
630 if (j->unit->ignore_on_isolate)
631 continue;
632
75778e21
MS
633 if (hashmap_get(tr->jobs, j->unit))
634 continue;
635
5273510e
MS
636 /* Not invalidating recursively. Avoids triggering
637 * OnFailure= actions of dependent jobs. Also avoids
638 * invalidating our iterator. */
833f92ad 639 job_finish_and_invalidate(j, JOB_CANCELED, false, false);
75778e21
MS
640 }
641 }
642
90e74a66 643 HASHMAP_FOREACH(j, tr->jobs) {
75778e21
MS
644 /* Assume merged */
645 assert(!j->transaction_prev);
646 assert(!j->transaction_next);
647
acf56b72 648 r = hashmap_ensure_put(&m->jobs, NULL, UINT32_TO_PTR(j->id), j);
75778e21
MS
649 if (r < 0)
650 goto rollback;
651 }
652
653 while ((j = hashmap_steal_first(tr->jobs))) {
656bbffc
MS
654 Job *installed_job;
655
75778e21
MS
656 /* Clean the job dependencies */
657 transaction_unlink_job(tr, j, false);
658
656bbffc
MS
659 installed_job = job_install(j);
660 if (installed_job != j) {
661 /* j has been merged into a previously installed job */
662 if (tr->anchor_job == j)
663 tr->anchor_job = installed_job;
664 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
665 job_free(j);
666 j = installed_job;
667 }
05d576f1 668
75778e21
MS
669 job_add_to_run_queue(j);
670 job_add_to_dbus_queue(j);
a2df3ea4 671 job_start_timer(j, false);
c65eb836 672 job_shutdown_magic(j);
50cbaba4
LP
673
674 /* When 'affected' is specified, let's track all in it all jobs that were touched because of
675 * this transaction. */
676 if (affected_jobs)
677 (void) set_put(affected_jobs, j);
75778e21
MS
678 }
679
75778e21
MS
680 return 0;
681
682rollback:
683
90e74a66 684 HASHMAP_FOREACH(j, tr->jobs)
75778e21 685 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
75778e21
MS
686
687 return r;
688}
689
50cbaba4
LP
690int transaction_activate(
691 Transaction *tr,
692 Manager *m,
693 JobMode mode,
694 Set *affected_jobs,
695 sd_bus_error *e) {
696
4e7bd268 697 Job *j;
75778e21
MS
698 int r;
699 unsigned generation = 1;
700
701 assert(tr);
702
703 /* This applies the changes recorded in tr->jobs to
704 * the actual list of jobs, if possible. */
705
4e7bd268
MS
706 /* Reset the generation counter of all installed jobs. The detection of cycles
707 * looks at installed jobs. If they had a non-zero generation from some previous
708 * walk of the graph, the algorithm would break. */
90e74a66 709 HASHMAP_FOREACH(j, m->jobs)
4e7bd268
MS
710 j->generation = 0;
711
75778e21 712 /* First step: figure out which jobs matter */
0d9989aa 713 transaction_find_jobs_that_matter_to_anchor(tr->anchor_job, generation++);
75778e21
MS
714
715 /* Second step: Try not to stop any running services if
716 * we don't have to. Don't try to reverse running
717 * jobs if we don't have to. */
718 if (mode == JOB_FAIL)
719 transaction_minimize_impact(tr);
720
721 /* Third step: Drop redundant jobs */
cc479760 722 transaction_drop_redundant(tr);
75778e21
MS
723
724 for (;;) {
725 /* Fourth step: Let's remove unneeded jobs that might
726 * be lurking. */
727 if (mode != JOB_ISOLATE)
728 transaction_collect_garbage(tr);
729
730 /* Fifth step: verify order makes sense and correct
731 * cycles if necessary and possible */
732 r = transaction_verify_order(tr, &generation, e);
733 if (r >= 0)
734 break;
735
4ae25393
YW
736 if (r != -EAGAIN)
737 return log_warning_errno(r, "Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error_message(e, r));
75778e21
MS
738
739 /* Let's see if the resulting transaction ordering
740 * graph is still cyclic... */
741 }
742
743 for (;;) {
744 /* Sixth step: let's drop unmergeable entries if
745 * necessary and possible, merge entries we can
746 * merge */
747 r = transaction_merge_jobs(tr, e);
748 if (r >= 0)
749 break;
750
4ae25393
YW
751 if (r != -EAGAIN)
752 return log_warning_errno(r, "Requested transaction contains unmergeable jobs: %s", bus_error_message(e, r));
75778e21
MS
753
754 /* Seventh step: an entry got dropped, let's garbage
755 * collect its dependencies. */
756 if (mode != JOB_ISOLATE)
757 transaction_collect_garbage(tr);
758
759 /* Let's see if the resulting transaction still has
760 * unmergeable entries ... */
761 }
762
763 /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
cc479760 764 transaction_drop_redundant(tr);
75778e21
MS
765
766 /* Ninth step: check whether we can actually apply this */
23ade460 767 r = transaction_is_destructive(tr, mode, e);
4ae25393
YW
768 if (r < 0)
769 return log_notice_errno(r, "Requested transaction contradicts existing jobs: %s", bus_error_message(e, r));
75778e21
MS
770
771 /* Tenth step: apply changes */
50cbaba4 772 r = transaction_apply(tr, m, mode, affected_jobs);
23bbb0de
MS
773 if (r < 0)
774 return log_warning_errno(r, "Failed to apply transaction: %m");
75778e21
MS
775
776 assert(hashmap_isempty(tr->jobs));
75778e21 777
f2b68789
LP
778 if (!hashmap_isempty(m->jobs)) {
779 /* Are there any jobs now? Then make sure we have the
780 * idle pipe around. We don't really care too much
781 * whether this works or not, as the idle pipe is a
782 * feature for cosmetics, not actually useful for
783 * anything beyond that. */
784
31a7eb86
ZJS
785 if (m->idle_pipe[0] < 0 && m->idle_pipe[1] < 0 &&
786 m->idle_pipe[2] < 0 && m->idle_pipe[3] < 0) {
1afaa7e8
LP
787 (void) pipe2(m->idle_pipe, O_NONBLOCK|O_CLOEXEC);
788 (void) pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC);
31a7eb86 789 }
f2b68789
LP
790 }
791
75778e21
MS
792 return 0;
793}
794
4bd29fe5 795static Job* transaction_add_one_job(Transaction *tr, JobType type, Unit *unit, bool *is_new) {
75778e21
MS
796 Job *j, *f;
797
798 assert(tr);
799 assert(unit);
800
801 /* Looks for an existing prospective job and returns that. If
802 * it doesn't exist it is created and added to the prospective
803 * jobs list. */
804
805 f = hashmap_get(tr->jobs, unit);
806
807 LIST_FOREACH(transaction, j, f) {
808 assert(j->unit == unit);
809
810 if (j->type == type) {
811 if (is_new)
812 *is_new = false;
813 return j;
814 }
815 }
816
3c956cfe
MS
817 j = job_new(unit, type);
818 if (!j)
819 return NULL;
75778e21
MS
820
821 j->generation = 0;
822 j->marker = NULL;
823 j->matters_to_anchor = false;
23ade460 824 j->irreversible = tr->irreversible;
75778e21 825
71fda00f 826 LIST_PREPEND(transaction, f, j);
75778e21
MS
827
828 if (hashmap_replace(tr->jobs, unit, f) < 0) {
71fda00f 829 LIST_REMOVE(transaction, f, j);
75778e21
MS
830 job_free(j);
831 return NULL;
832 }
833
834 if (is_new)
835 *is_new = true;
836
78218e62 837 log_trace("Added job %s/%s to transaction.", unit->id, job_type_to_string(type));
75778e21
MS
838
839 return j;
840}
841
842static void transaction_unlink_job(Transaction *tr, Job *j, bool delete_dependencies) {
843 assert(tr);
844 assert(j);
845
846 if (j->transaction_prev)
847 j->transaction_prev->transaction_next = j->transaction_next;
848 else if (j->transaction_next)
849 hashmap_replace(tr->jobs, j->unit, j->transaction_next);
850 else
851 hashmap_remove_value(tr->jobs, j->unit, j);
852
853 if (j->transaction_next)
854 j->transaction_next->transaction_prev = j->transaction_prev;
855
856 j->transaction_prev = j->transaction_next = NULL;
857
858 while (j->subject_list)
e6eda1f2 859 job_dependency_free(j->subject_list);
75778e21
MS
860
861 while (j->object_list) {
862 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
863
e6eda1f2 864 job_dependency_free(j->object_list);
75778e21
MS
865
866 if (other && delete_dependencies) {
f2341e0a 867 log_unit_debug(other->unit,
66870f90
ZJS
868 "Deleting job %s/%s as dependency of job %s/%s",
869 other->unit->id, job_type_to_string(other->type),
870 j->unit->id, job_type_to_string(j->type));
75778e21
MS
871 transaction_delete_job(tr, other, delete_dependencies);
872 }
873 }
874}
875
15d167f8 876void transaction_add_propagate_reload_jobs(Transaction *tr, Unit *unit, Job *by, bool ignore_order, sd_bus_error *e) {
15d167f8 877 JobType nt;
eef85c4a 878 Unit *dep;
15d167f8
JW
879 int r;
880
881 assert(tr);
882 assert(unit);
883
15ed3c3a 884 UNIT_FOREACH_DEPENDENCY(dep, unit, UNIT_ATOM_PROPAGATES_RELOAD_TO) {
15d167f8
JW
885 nt = job_type_collapse(JOB_TRY_RELOAD, dep);
886 if (nt == JOB_NOP)
887 continue;
888
889 r = transaction_add_job_and_dependencies(tr, nt, dep, by, false, false, false, ignore_order, e);
890 if (r < 0) {
891 log_unit_warning(dep,
892 "Cannot add dependency reload job, ignoring: %s",
893 bus_error_message(e, r));
894 sd_bus_error_free(e);
895 }
896 }
897}
898
75778e21
MS
899int transaction_add_job_and_dependencies(
900 Transaction *tr,
901 JobType type,
902 Unit *unit,
903 Job *by,
904 bool matters,
75778e21
MS
905 bool conflicts,
906 bool ignore_requirements,
907 bool ignore_order,
718db961 908 sd_bus_error *e) {
eef85c4a
LP
909
910 bool is_new;
75778e21 911 Unit *dep;
eef85c4a 912 Job *ret;
75778e21 913 int r;
75778e21
MS
914
915 assert(tr);
916 assert(type < _JOB_TYPE_MAX);
e0209d83 917 assert(type < _JOB_TYPE_MAX_IN_TRANSACTION);
75778e21
MS
918 assert(unit);
919
43706330
IS
920 /* Before adding jobs for this unit, let's ensure that its state has been loaded
921 * This matters when jobs are spawned as part of coldplugging itself (see e. g. path_coldplug()).
922 * This way, we "recursively" coldplug units, ensuring that we do not look at state of
923 * not-yet-coldplugged units. */
2c289ea8 924 if (MANAGER_IS_RELOADING(unit->manager))
43706330
IS
925 unit_coldplug(unit);
926
78218e62
JK
927 if (by)
928 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 929
c4555ad8
LP
930 /* Safety check that the unit is a valid state, i.e. not in UNIT_STUB or UNIT_MERGED which should only be set
931 * temporarily. */
0377cd29 932 if (!UNIT_IS_LOAD_COMPLETE(unit->load_state))
c6497ccb 933 return sd_bus_error_setf(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->id);
75778e21 934
ee87525c 935 if (type != JOB_STOP) {
e49da001 936 r = bus_unit_validate_load_state(unit, e);
cda66772
LB
937 /* The time-based cache allows to start new units without daemon-reload,
938 * but if they are already referenced (because of dependencies or ordering)
939 * then we have to force a load of the fragment. As an optimization, check
940 * first if anything in the usual paths was modified since the last time
941 * the cache was loaded. Also check if the last time an attempt to load the
942 * unit was made was before the most recent cache refresh, so that we know
81be2388 943 * we need to try again — even if the cache is current, it might have been
cda66772
LB
944 * updated in a different context before we had a chance to retry loading
945 * this particular unit.
81be2388 946 *
cda66772
LB
947 * Given building up the transaction is a synchronous operation, attempt
948 * to load the unit immediately. */
81be2388 949 if (r < 0 && manager_unit_cache_should_retry_load(unit)) {
94efaa31 950 sd_bus_error_free(e);
cda66772
LB
951 unit->load_state = UNIT_STUB;
952 r = unit_load(unit);
953 if (r < 0 || unit->load_state == UNIT_STUB)
954 unit->load_state = UNIT_NOT_FOUND;
955 r = bus_unit_validate_load_state(unit, e);
956 }
ee87525c
FB
957 if (r < 0)
958 return r;
75778e21
MS
959 }
960
7358dc02
ZJS
961 if (!unit_job_is_applicable(unit, type))
962 return sd_bus_error_setf(e, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE,
963 "Job type %s is not applicable for unit %s.",
964 job_type_to_string(type), unit->id);
75778e21 965
75778e21 966 /* First add the job. */
4bd29fe5 967 ret = transaction_add_one_job(tr, type, unit, &is_new);
75778e21
MS
968 if (!ret)
969 return -ENOMEM;
970
971 ret->ignore_order = ret->ignore_order || ignore_order;
972
973 /* Then, add a link to the job. */
e6eda1f2
MS
974 if (by) {
975 if (!job_dependency_new(by, ret, matters, conflicts))
976 return -ENOMEM;
977 } else {
978 /* If the job has no parent job, it is the anchor job. */
4483f694
MS
979 assert(!tr->anchor_job);
980 tr->anchor_job = ret;
b94fbd30 981 }
e0209d83
MS
982
983 if (is_new && !ignore_requirements && type != JOB_NOP) {
75778e21
MS
984 Set *following;
985
986 /* If we are following some other unit, make sure we
987 * add all dependencies of everybody following. */
988 if (unit_following_set(ret->unit, &following) > 0) {
90e74a66 989 SET_FOREACH(dep, following) {
4bd29fe5 990 r = transaction_add_job_and_dependencies(tr, type, dep, ret, false, false, false, ignore_order, e);
75778e21 991 if (r < 0) {
8ed6f81b
YW
992 log_unit_full_errno(dep, r == -ERFKILL ? LOG_INFO : LOG_WARNING, r,
993 "Cannot add dependency job, ignoring: %s",
994 bus_error_message(e, r));
69301c17 995 sd_bus_error_free(e);
75778e21
MS
996 }
997 }
998
999 set_free(following);
1000 }
1001
1002 /* Finally, recursively add in all dependencies. */
3742095b 1003 if (IN_SET(type, JOB_START, JOB_RESTART)) {
15ed3c3a 1004 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_START) {
4bd29fe5 1005 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, true, false, false, ignore_order, e);
75778e21 1006 if (r < 0) {
114400df 1007 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1008 goto fail;
1009
69301c17 1010 sd_bus_error_free(e);
75778e21
MS
1011 }
1012 }
1013
15ed3c3a 1014 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_START_IGNORED) {
4bd29fe5 1015 r = transaction_add_job_and_dependencies(tr, JOB_START, dep, ret, false, false, false, ignore_order, e);
75778e21 1016 if (r < 0) {
114400df 1017 /* unit masked, job type not applicable and unit not found are not considered as errors. */
8ed6f81b
YW
1018 log_unit_full_errno(dep,
1019 IN_SET(r, -ERFKILL, -EBADR, -ENOENT) ? LOG_DEBUG : LOG_WARNING,
1020 r, "Cannot add dependency job, ignoring: %s",
1021 bus_error_message(e, r));
69301c17 1022 sd_bus_error_free(e);
75778e21
MS
1023 }
1024 }
1025
15ed3c3a 1026 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_VERIFY) {
4bd29fe5 1027 r = transaction_add_job_and_dependencies(tr, JOB_VERIFY_ACTIVE, dep, ret, true, false, false, ignore_order, e);
75778e21 1028 if (r < 0) {
114400df 1029 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1030 goto fail;
1031
69301c17 1032 sd_bus_error_free(e);
75778e21
MS
1033 }
1034 }
1035
15ed3c3a 1036 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_STOP) {
4bd29fe5 1037 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, true, true, false, ignore_order, e);
75778e21 1038 if (r < 0) {
114400df 1039 if (r != -EBADR) /* job type not applicable */
75778e21
MS
1040 goto fail;
1041
69301c17 1042 sd_bus_error_free(e);
75778e21
MS
1043 }
1044 }
1045
15ed3c3a 1046 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, UNIT_ATOM_PULL_IN_STOP_IGNORED) {
4bd29fe5 1047 r = transaction_add_job_and_dependencies(tr, JOB_STOP, dep, ret, false, false, false, ignore_order, e);
75778e21 1048 if (r < 0) {
f2341e0a
LP
1049 log_unit_warning(dep,
1050 "Cannot add dependency job, ignoring: %s",
1051 bus_error_message(e, r));
69301c17 1052 sd_bus_error_free(e);
75778e21
MS
1053 }
1054 }
75778e21
MS
1055 }
1056
3742095b 1057 if (IN_SET(type, JOB_STOP, JOB_RESTART)) {
15ed3c3a 1058 UnitDependencyAtom atom;
c6497ccb 1059 JobType ptype;
75778e21 1060
15ed3c3a 1061 /* We propagate STOP as STOP, but RESTART only as TRY_RESTART, in order not to start
c6497ccb 1062 * dependencies that are not around. */
15ed3c3a
LP
1063 if (type == JOB_RESTART) {
1064 atom = UNIT_ATOM_PROPAGATE_RESTART;
1065 ptype = JOB_TRY_RESTART;
1066 } else {
1067 ptype = JOB_STOP;
1068 atom = UNIT_ATOM_PROPAGATE_STOP;
1069 }
c6497ccb 1070
15ed3c3a
LP
1071 UNIT_FOREACH_DEPENDENCY(dep, ret->unit, atom) {
1072 JobType nt;
85e9a101 1073
15ed3c3a
LP
1074 nt = job_type_collapse(ptype, dep);
1075 if (nt == JOB_NOP)
1076 continue;
48894cd0 1077
15ed3c3a
LP
1078 r = transaction_add_job_and_dependencies(tr, nt, dep, ret, true, false, false, ignore_order, e);
1079 if (r < 0) {
1080 if (r != -EBADR) /* job type not applicable */
1081 goto fail;
85e9a101 1082
15ed3c3a 1083 sd_bus_error_free(e);
85e9a101 1084 }
15ed3c3a 1085 }
75778e21
MS
1086 }
1087
15d167f8
JW
1088 if (type == JOB_RELOAD)
1089 transaction_add_propagate_reload_jobs(tr, ret->unit, ret, ignore_order, e);
75778e21 1090
78218e62 1091 /* JOB_VERIFY_ACTIVE requires no dependency handling */
75778e21
MS
1092 }
1093
75778e21
MS
1094 return 0;
1095
1096fail:
1097 return r;
1098}
1099
1100int transaction_add_isolate_jobs(Transaction *tr, Manager *m) {
75778e21
MS
1101 Unit *u;
1102 char *k;
1103 int r;
1104
1105 assert(tr);
1106 assert(m);
1107
90e74a66 1108 HASHMAP_FOREACH_KEY(u, k, m->units) {
75778e21
MS
1109
1110 /* ignore aliases */
1111 if (u->id != k)
1112 continue;
1113
1114 if (u->ignore_on_isolate)
1115 continue;
1116
1117 /* No need to stop inactive jobs */
1118 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->job)
1119 continue;
1120
1121 /* Is there already something listed for this? */
1122 if (hashmap_get(tr->jobs, u))
1123 continue;
1124
4bd29fe5 1125 r = transaction_add_job_and_dependencies(tr, JOB_STOP, u, tr->anchor_job, true, false, false, false, NULL);
75778e21 1126 if (r < 0)
f2341e0a 1127 log_unit_warning_errno(u, r, "Cannot add isolate job, ignoring: %m");
75778e21
MS
1128 }
1129
1130 return 0;
1131}
1132
1f0f9f21 1133int transaction_add_triggering_jobs(Transaction *tr, Unit *u) {
1f0f9f21
KK
1134 Unit *trigger;
1135 int r;
1136
1137 assert(tr);
132e0b53 1138 assert(u);
1f0f9f21 1139
15ed3c3a
LP
1140 UNIT_FOREACH_DEPENDENCY(trigger, u, UNIT_ATOM_TRIGGERED_BY) {
1141
1f0f9f21
KK
1142 /* No need to stop inactive jobs */
1143 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(trigger)) && !trigger->job)
1144 continue;
1145
1146 /* Is there already something listed for this? */
1147 if (hashmap_get(tr->jobs, trigger))
1148 continue;
1149
1150 r = transaction_add_job_and_dependencies(tr, JOB_STOP, trigger, tr->anchor_job, true, false, false, false, NULL);
1151 if (r < 0)
1152 log_unit_warning_errno(u, r, "Cannot add triggered by job, ignoring: %m");
1153 }
1154
1155 return 0;
1156}
1157
23ade460 1158Transaction *transaction_new(bool irreversible) {
75778e21
MS
1159 Transaction *tr;
1160
1161 tr = new0(Transaction, 1);
1162 if (!tr)
1163 return NULL;
1164
d5099efc 1165 tr->jobs = hashmap_new(NULL);
6b430fdb
ZJS
1166 if (!tr->jobs)
1167 return mfree(tr);
75778e21 1168
23ade460
MS
1169 tr->irreversible = irreversible;
1170
75778e21
MS
1171 return tr;
1172}
1173
1174void transaction_free(Transaction *tr) {
1175 assert(hashmap_isempty(tr->jobs));
1176 hashmap_free(tr->jobs);
1177 free(tr);
1178}