]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine/machine.c
machine: simplify machine_start_scope()
[thirdparty/systemd.git] / src / machine / machine.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <unistd.h>
5 #include <sys/stat.h>
6
7 #include "sd-messages.h"
8
9 #include "alloc-util.h"
10 #include "bus-error.h"
11 #include "bus-util.h"
12 #include "env-file.h"
13 #include "errno-util.h"
14 #include "escape.h"
15 #include "extract-word.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "format-util.h"
19 #include "hashmap.h"
20 #include "machine-dbus.h"
21 #include "machine.h"
22 #include "mkdir.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "process-util.h"
26 #include "serialize.h"
27 #include "special.h"
28 #include "stdio-util.h"
29 #include "string-table.h"
30 #include "terminal-util.h"
31 #include "tmpfile-util.h"
32 #include "unit-name.h"
33 #include "user-util.h"
34 #include "util.h"
35
36 Machine* machine_new(Manager *manager, MachineClass class, const char *name) {
37 Machine *m;
38
39 assert(manager);
40 assert(class < _MACHINE_CLASS_MAX);
41 assert(name);
42
43 /* Passing class == _MACHINE_CLASS_INVALID here is fine. It
44 * means as much as "we don't know yet", and that we'll figure
45 * it out later when loading the state file. */
46
47 m = new0(Machine, 1);
48 if (!m)
49 return NULL;
50
51 m->name = strdup(name);
52 if (!m->name)
53 goto fail;
54
55 if (class != MACHINE_HOST) {
56 m->state_file = path_join("/run/systemd/machines", m->name);
57 if (!m->state_file)
58 goto fail;
59 }
60
61 m->class = class;
62
63 if (hashmap_put(manager->machines, m->name, m) < 0)
64 goto fail;
65
66 m->manager = manager;
67
68 return m;
69
70 fail:
71 free(m->state_file);
72 free(m->name);
73 return mfree(m);
74 }
75
76 Machine* machine_free(Machine *m) {
77 if (!m)
78 return NULL;
79
80 while (m->operations)
81 operation_free(m->operations);
82
83 if (m->in_gc_queue)
84 LIST_REMOVE(gc_queue, m->manager->machine_gc_queue, m);
85
86 machine_release_unit(m);
87
88 free(m->scope_job);
89
90 (void) hashmap_remove(m->manager->machines, m->name);
91
92 if (m->manager->host_machine == m)
93 m->manager->host_machine = NULL;
94
95 if (m->leader > 0)
96 (void) hashmap_remove_value(m->manager->machine_leaders, PID_TO_PTR(m->leader), m);
97
98 sd_bus_message_unref(m->create_message);
99
100 free(m->name);
101 free(m->state_file);
102 free(m->service);
103 free(m->root_directory);
104 free(m->netif);
105 return mfree(m);
106 }
107
108 int machine_save(Machine *m) {
109 _cleanup_free_ char *temp_path = NULL;
110 _cleanup_fclose_ FILE *f = NULL;
111 int r;
112
113 assert(m);
114
115 if (!m->state_file)
116 return 0;
117
118 if (!m->started)
119 return 0;
120
121 r = mkdir_safe_label("/run/systemd/machines", 0755, 0, 0, MKDIR_WARN_MODE);
122 if (r < 0)
123 goto fail;
124
125 r = fopen_temporary(m->state_file, &f, &temp_path);
126 if (r < 0)
127 goto fail;
128
129 (void) fchmod(fileno(f), 0644);
130
131 fprintf(f,
132 "# This is private data. Do not parse.\n"
133 "NAME=%s\n",
134 m->name);
135
136 if (m->unit) {
137 _cleanup_free_ char *escaped;
138
139 escaped = cescape(m->unit);
140 if (!escaped) {
141 r = -ENOMEM;
142 goto fail;
143 }
144
145 fprintf(f, "SCOPE=%s\n", escaped); /* We continue to call this "SCOPE=" because it is internal only, and we want to stay compatible with old files */
146 }
147
148 if (m->scope_job)
149 fprintf(f, "SCOPE_JOB=%s\n", m->scope_job);
150
151 if (m->service) {
152 _cleanup_free_ char *escaped;
153
154 escaped = cescape(m->service);
155 if (!escaped) {
156 r = -ENOMEM;
157 goto fail;
158 }
159 fprintf(f, "SERVICE=%s\n", escaped);
160 }
161
162 if (m->root_directory) {
163 _cleanup_free_ char *escaped;
164
165 escaped = cescape(m->root_directory);
166 if (!escaped) {
167 r = -ENOMEM;
168 goto fail;
169 }
170 fprintf(f, "ROOT=%s\n", escaped);
171 }
172
173 if (!sd_id128_is_null(m->id))
174 fprintf(f, "ID=" SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(m->id));
175
176 if (m->leader != 0)
177 fprintf(f, "LEADER="PID_FMT"\n", m->leader);
178
179 if (m->class != _MACHINE_CLASS_INVALID)
180 fprintf(f, "CLASS=%s\n", machine_class_to_string(m->class));
181
182 if (dual_timestamp_is_set(&m->timestamp))
183 fprintf(f,
184 "REALTIME="USEC_FMT"\n"
185 "MONOTONIC="USEC_FMT"\n",
186 m->timestamp.realtime,
187 m->timestamp.monotonic);
188
189 if (m->n_netif > 0) {
190 size_t i;
191
192 fputs("NETIF=", f);
193
194 for (i = 0; i < m->n_netif; i++) {
195 if (i != 0)
196 fputc(' ', f);
197
198 fprintf(f, "%i", m->netif[i]);
199 }
200
201 fputc('\n', f);
202 }
203
204 r = fflush_and_check(f);
205 if (r < 0)
206 goto fail;
207
208 if (rename(temp_path, m->state_file) < 0) {
209 r = -errno;
210 goto fail;
211 }
212
213 if (m->unit) {
214 char *sl;
215
216 /* Create a symlink from the unit name to the machine
217 * name, so that we can quickly find the machine for
218 * each given unit. Ignore error. */
219 sl = strjoina("/run/systemd/machines/unit:", m->unit);
220 (void) symlink(m->name, sl);
221 }
222
223 return 0;
224
225 fail:
226 (void) unlink(m->state_file);
227
228 if (temp_path)
229 (void) unlink(temp_path);
230
231 return log_error_errno(r, "Failed to save machine data %s: %m", m->state_file);
232 }
233
234 static void machine_unlink(Machine *m) {
235 assert(m);
236
237 if (m->unit) {
238 char *sl;
239
240 sl = strjoina("/run/systemd/machines/unit:", m->unit);
241 (void) unlink(sl);
242 }
243
244 if (m->state_file)
245 (void) unlink(m->state_file);
246 }
247
248 int machine_load(Machine *m) {
249 _cleanup_free_ char *realtime = NULL, *monotonic = NULL, *id = NULL, *leader = NULL, *class = NULL, *netif = NULL;
250 int r;
251
252 assert(m);
253
254 if (!m->state_file)
255 return 0;
256
257 r = parse_env_file(NULL, m->state_file,
258 "SCOPE", &m->unit,
259 "SCOPE_JOB", &m->scope_job,
260 "SERVICE", &m->service,
261 "ROOT", &m->root_directory,
262 "ID", &id,
263 "LEADER", &leader,
264 "CLASS", &class,
265 "REALTIME", &realtime,
266 "MONOTONIC", &monotonic,
267 "NETIF", &netif);
268 if (r < 0) {
269 if (r == -ENOENT)
270 return 0;
271
272 return log_error_errno(r, "Failed to read %s: %m", m->state_file);
273 }
274
275 if (id)
276 sd_id128_from_string(id, &m->id);
277
278 if (leader)
279 parse_pid(leader, &m->leader);
280
281 if (class) {
282 MachineClass c;
283
284 c = machine_class_from_string(class);
285 if (c >= 0)
286 m->class = c;
287 }
288
289 if (realtime)
290 (void) deserialize_usec(realtime, &m->timestamp.realtime);
291 if (monotonic)
292 (void) deserialize_usec(monotonic, &m->timestamp.monotonic);
293
294 if (netif) {
295 size_t allocated = 0, nr = 0;
296 const char *p;
297 int *ni = NULL;
298
299 p = netif;
300 for (;;) {
301 _cleanup_free_ char *word = NULL;
302 int ifi;
303
304 r = extract_first_word(&p, &word, NULL, 0);
305 if (r == 0)
306 break;
307 if (r == -ENOMEM)
308 return log_oom();
309 if (r < 0) {
310 log_warning_errno(r, "Failed to parse NETIF: %s", netif);
311 break;
312 }
313
314 if (parse_ifindex(word, &ifi) < 0)
315 continue;
316
317 if (!GREEDY_REALLOC(ni, allocated, nr+1)) {
318 free(ni);
319 return log_oom();
320 }
321
322 ni[nr++] = ifi;
323 }
324
325 free(m->netif);
326 m->netif = ni;
327 m->n_netif = nr;
328 }
329
330 return r;
331 }
332
333 static int machine_start_scope(
334 Machine *machine,
335 sd_bus_message *more_properties,
336 sd_bus_error *error) {
337
338 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
339 _cleanup_free_ char *escaped = NULL, *unit = NULL;
340 const char *description;
341 int r;
342
343 assert(machine);
344 assert(machine->leader > 0);
345 assert(!machine->unit);
346
347 escaped = unit_name_escape(machine->name);
348 if (!escaped)
349 return log_oom();
350
351 unit = strjoin("machine-", escaped, ".scope");
352 if (!unit)
353 return log_oom();
354
355 r = sd_bus_message_new_method_call(
356 machine->manager->bus,
357 &m,
358 "org.freedesktop.systemd1",
359 "/org/freedesktop/systemd1",
360 "org.freedesktop.systemd1.Manager",
361 "StartTransientUnit");
362 if (r < 0)
363 return r;
364
365 r = sd_bus_message_append(m, "ss", unit, "fail");
366 if (r < 0)
367 return r;
368
369 r = sd_bus_message_open_container(m, 'a', "(sv)");
370 if (r < 0)
371 return r;
372
373 r = sd_bus_message_append(m, "(sv)", "Slice", "s", SPECIAL_MACHINE_SLICE);
374 if (r < 0)
375 return r;
376
377 description = strjoina(machine->class == MACHINE_VM ? "Virtual Machine " : "Container ", machine->name);
378 r = sd_bus_message_append(m, "(sv)", "Description", "s", description);
379 if (r < 0)
380 return r;
381
382 r = sd_bus_message_append(m, "(sv)(sv)(sv)(sv)(sv)",
383 "PIDs", "au", 1, machine->leader,
384 "Delegate", "b", 1,
385 "CollectMode", "s", "inactive-or-failed",
386 "AddRef", "b", 1,
387 "TasksMax", "t", UINT64_C(16384));
388 if (r < 0)
389 return r;
390
391 if (more_properties) {
392 r = sd_bus_message_copy(m, more_properties, true);
393 if (r < 0)
394 return r;
395 }
396
397 r = sd_bus_message_close_container(m);
398 if (r < 0)
399 return r;
400
401 r = sd_bus_message_append(m, "a(sa(sv))", 0);
402 if (r < 0)
403 return r;
404
405 r = sd_bus_call(NULL, m, 0, error, &reply);
406 if (r < 0)
407 return r;
408
409 machine->unit = TAKE_PTR(unit);
410 machine->referenced = true;
411
412 const char *job;
413 r = sd_bus_message_read(reply, "o", &job);
414 if (r < 0)
415 return r;
416
417 return free_and_strdup(&machine->scope_job, job);
418 }
419
420 static int machine_ensure_scope(Machine *m, sd_bus_message *properties, sd_bus_error *error) {
421 int r;
422
423 assert(m);
424 assert(m->class != MACHINE_HOST);
425
426 if (!m->unit) {
427 r = machine_start_scope(m, properties, error);
428 if (r < 0)
429 return log_error_errno(r, "Failed to start machine scope: %s", bus_error_message(error, r));
430 }
431
432 assert(m->unit);
433 hashmap_put(m->manager->machine_units, m->unit, m);
434
435 return 0;
436 }
437
438 int machine_start(Machine *m, sd_bus_message *properties, sd_bus_error *error) {
439 int r;
440
441 assert(m);
442
443 if (!IN_SET(m->class, MACHINE_CONTAINER, MACHINE_VM))
444 return -EOPNOTSUPP;
445
446 if (m->started)
447 return 0;
448
449 r = hashmap_put(m->manager->machine_leaders, PID_TO_PTR(m->leader), m);
450 if (r < 0)
451 return r;
452
453 /* Create cgroup */
454 r = machine_ensure_scope(m, properties, error);
455 if (r < 0)
456 return r;
457
458 log_struct(LOG_INFO,
459 "MESSAGE_ID=" SD_MESSAGE_MACHINE_START_STR,
460 "NAME=%s", m->name,
461 "LEADER="PID_FMT, m->leader,
462 LOG_MESSAGE("New machine %s.", m->name));
463
464 if (!dual_timestamp_is_set(&m->timestamp))
465 dual_timestamp_get(&m->timestamp);
466
467 m->started = true;
468
469 /* Save new machine data */
470 machine_save(m);
471
472 machine_send_signal(m, true);
473 (void) manager_enqueue_nscd_cache_flush(m->manager);
474
475 return 0;
476 }
477
478 static int machine_stop_scope(Machine *m) {
479 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
480 char *job = NULL;
481 int r, q;
482
483 assert(m);
484 assert(m->class != MACHINE_HOST);
485
486 if (!m->unit)
487 return 0;
488
489 r = manager_stop_unit(m->manager, m->unit, &error, &job);
490 if (r < 0) {
491 log_error_errno(r, "Failed to stop machine scope: %s", bus_error_message(&error, r));
492 sd_bus_error_free(&error);
493 } else
494 free_and_replace(m->scope_job, job);
495
496 if (m->referenced) {
497 q = manager_unref_unit(m->manager, m->unit, &error);
498 if (q < 0)
499 log_warning_errno(q, "Failed to drop reference to machine scope, ignoring: %s", bus_error_message(&error, r));
500 m->referenced = false;
501 }
502
503 return r;
504 }
505
506 int machine_stop(Machine *m) {
507 int r;
508 assert(m);
509
510 if (!IN_SET(m->class, MACHINE_CONTAINER, MACHINE_VM))
511 return -EOPNOTSUPP;
512
513 r = machine_stop_scope(m);
514
515 m->stopping = true;
516
517 machine_save(m);
518 (void) manager_enqueue_nscd_cache_flush(m->manager);
519
520 return r;
521 }
522
523 int machine_finalize(Machine *m) {
524 assert(m);
525
526 if (m->started) {
527 log_struct(LOG_INFO,
528 "MESSAGE_ID=" SD_MESSAGE_MACHINE_STOP_STR,
529 "NAME=%s", m->name,
530 "LEADER="PID_FMT, m->leader,
531 LOG_MESSAGE("Machine %s terminated.", m->name));
532
533 m->stopping = true; /* The machine is supposed to be going away. Don't try to kill it. */
534 }
535
536 machine_unlink(m);
537 machine_add_to_gc_queue(m);
538
539 if (m->started) {
540 machine_send_signal(m, false);
541 m->started = false;
542 }
543
544 return 0;
545 }
546
547 bool machine_may_gc(Machine *m, bool drop_not_started) {
548 assert(m);
549
550 if (m->class == MACHINE_HOST)
551 return false;
552
553 if (drop_not_started && !m->started)
554 return true;
555
556 if (m->scope_job && manager_job_is_active(m->manager, m->scope_job))
557 return false;
558
559 if (m->unit && manager_unit_is_active(m->manager, m->unit))
560 return false;
561
562 return true;
563 }
564
565 void machine_add_to_gc_queue(Machine *m) {
566 assert(m);
567
568 if (m->in_gc_queue)
569 return;
570
571 LIST_PREPEND(gc_queue, m->manager->machine_gc_queue, m);
572 m->in_gc_queue = true;
573 }
574
575 MachineState machine_get_state(Machine *s) {
576 assert(s);
577
578 if (s->class == MACHINE_HOST)
579 return MACHINE_RUNNING;
580
581 if (s->stopping)
582 return MACHINE_CLOSING;
583
584 if (s->scope_job)
585 return MACHINE_OPENING;
586
587 return MACHINE_RUNNING;
588 }
589
590 int machine_kill(Machine *m, KillWho who, int signo) {
591 assert(m);
592
593 if (!IN_SET(m->class, MACHINE_VM, MACHINE_CONTAINER))
594 return -EOPNOTSUPP;
595
596 if (!m->unit)
597 return -ESRCH;
598
599 if (who == KILL_LEADER) {
600 /* If we shall simply kill the leader, do so directly */
601
602 if (kill(m->leader, signo) < 0)
603 return -errno;
604
605 return 0;
606 }
607
608 /* Otherwise, make PID 1 do it for us, for the entire cgroup */
609 return manager_kill_unit(m->manager, m->unit, signo, NULL);
610 }
611
612 int machine_openpt(Machine *m, int flags, char **ret_slave) {
613 assert(m);
614
615 switch (m->class) {
616
617 case MACHINE_HOST:
618
619 return openpt_allocate(flags, ret_slave);
620
621 case MACHINE_CONTAINER:
622 if (m->leader <= 0)
623 return -EINVAL;
624
625 return openpt_allocate_in_namespace(m->leader, flags, ret_slave);
626
627 default:
628 return -EOPNOTSUPP;
629 }
630 }
631
632 int machine_open_terminal(Machine *m, const char *path, int mode) {
633 assert(m);
634
635 switch (m->class) {
636
637 case MACHINE_HOST:
638 return open_terminal(path, mode);
639
640 case MACHINE_CONTAINER:
641 if (m->leader <= 0)
642 return -EINVAL;
643
644 return open_terminal_in_namespace(m->leader, path, mode);
645
646 default:
647 return -EOPNOTSUPP;
648 }
649 }
650
651 void machine_release_unit(Machine *m) {
652 assert(m);
653
654 if (!m->unit)
655 return;
656
657 (void) hashmap_remove(m->manager->machine_units, m->unit);
658 m->unit = mfree(m->unit);
659 }
660
661 int machine_get_uid_shift(Machine *m, uid_t *ret) {
662 char p[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t) + 1];
663 uid_t uid_base, uid_shift, uid_range;
664 gid_t gid_base, gid_shift, gid_range;
665 _cleanup_fclose_ FILE *f = NULL;
666 int k, r;
667
668 assert(m);
669 assert(ret);
670
671 /* Return the base UID/GID of the specified machine. Note that this only works for containers with simple
672 * mappings. In most cases setups should be simple like this, and administrators should only care about the
673 * basic offset a container has relative to the host. This is what this function exposes.
674 *
675 * If we encounter any more complex mappings we politely refuse this with ENXIO. */
676
677 if (m->class == MACHINE_HOST) {
678 *ret = 0;
679 return 0;
680 }
681
682 if (m->class != MACHINE_CONTAINER)
683 return -EOPNOTSUPP;
684
685 xsprintf(p, "/proc/" PID_FMT "/uid_map", m->leader);
686 f = fopen(p, "re");
687 if (!f) {
688 if (errno == ENOENT) {
689 /* If the file doesn't exist, user namespacing is off in the kernel, return a zero mapping hence. */
690 *ret = 0;
691 return 0;
692 }
693
694 return -errno;
695 }
696
697 /* Read the first line. There's at least one. */
698 errno = 0;
699 k = fscanf(f, UID_FMT " " UID_FMT " " UID_FMT "\n", &uid_base, &uid_shift, &uid_range);
700 if (k != 3) {
701 if (ferror(f))
702 return errno_or_else(EIO);
703
704 return -EBADMSG;
705 }
706
707 /* Not a mapping starting at 0? Then it's a complex mapping we can't expose here. */
708 if (uid_base != 0)
709 return -ENXIO;
710 /* Insist that at least the nobody user is mapped, everything else is weird, and hence complex, and we don't support it */
711 if (uid_range < UID_NOBODY)
712 return -ENXIO;
713
714 /* If there's more than one line, then we don't support this mapping. */
715 r = safe_fgetc(f, NULL);
716 if (r < 0)
717 return r;
718 if (r != 0) /* Insist on EOF */
719 return -ENXIO;
720
721 fclose(f);
722
723 xsprintf(p, "/proc/" PID_FMT "/gid_map", m->leader);
724 f = fopen(p, "re");
725 if (!f)
726 return -errno;
727
728 /* Read the first line. There's at least one. */
729 errno = 0;
730 k = fscanf(f, GID_FMT " " GID_FMT " " GID_FMT "\n", &gid_base, &gid_shift, &gid_range);
731 if (k != 3) {
732 if (ferror(f))
733 return errno_or_else(EIO);
734
735 return -EBADMSG;
736 }
737
738 /* If there's more than one line, then we don't support this file. */
739 r = safe_fgetc(f, NULL);
740 if (r < 0)
741 return r;
742 if (r != 0) /* Insist on EOF */
743 return -ENXIO;
744
745 /* If the UID and GID mapping doesn't match, we don't support this mapping. */
746 if (uid_base != (uid_t) gid_base)
747 return -ENXIO;
748 if (uid_shift != (uid_t) gid_shift)
749 return -ENXIO;
750 if (uid_range != (uid_t) gid_range)
751 return -ENXIO;
752
753 *ret = uid_shift;
754 return 0;
755 }
756
757 static const char* const machine_class_table[_MACHINE_CLASS_MAX] = {
758 [MACHINE_CONTAINER] = "container",
759 [MACHINE_VM] = "vm",
760 [MACHINE_HOST] = "host",
761 };
762
763 DEFINE_STRING_TABLE_LOOKUP(machine_class, MachineClass);
764
765 static const char* const machine_state_table[_MACHINE_STATE_MAX] = {
766 [MACHINE_OPENING] = "opening",
767 [MACHINE_RUNNING] = "running",
768 [MACHINE_CLOSING] = "closing"
769 };
770
771 DEFINE_STRING_TABLE_LOOKUP(machine_state, MachineState);
772
773 static const char* const kill_who_table[_KILL_WHO_MAX] = {
774 [KILL_LEADER] = "leader",
775 [KILL_ALL] = "all"
776 };
777
778 DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);