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