]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC/Config.pm
net: Add `link_down` config to allow setting interfaces as disconnected
[pve-container.git] / src / PVE / LXC / Config.pm
1 package PVE::LXC::Config;
2
3 use strict;
4 use warnings;
5
6 use Fcntl qw(O_RDONLY);
7
8 use PVE::AbstractConfig;
9 use PVE::Cluster qw(cfs_register_file);
10 use PVE::DataCenterConfig;
11 use PVE::GuestHelpers;
12 use PVE::INotify;
13 use PVE::JSONSchema qw(get_standard_option);
14 use PVE::Tools;
15
16 use PVE::LXC;
17
18 use base qw(PVE::AbstractConfig);
19
20 use constant {
21 FIFREEZE => 0xc0045877,
22 FITHAW => 0xc0045878,
23 };
24
25 my $nodename = PVE::INotify::nodename();
26 my $lock_handles = {};
27 my $lockdir = "/run/lock/lxc";
28 mkdir $lockdir;
29 mkdir "/etc/pve/nodes/$nodename/lxc";
30 my $MAX_MOUNT_POINTS = 256;
31 my $MAX_UNUSED_DISKS = $MAX_MOUNT_POINTS;
32
33 # BEGIN implemented abstract methods from PVE::AbstractConfig
34
35 sub guest_type {
36 return "CT";
37 }
38
39 sub __config_max_unused_disks {
40 my ($class) = @_;
41
42 return $MAX_UNUSED_DISKS;
43 }
44
45 sub config_file_lock {
46 my ($class, $vmid) = @_;
47
48 return "$lockdir/pve-config-${vmid}.lock";
49 }
50
51 sub cfs_config_path {
52 my ($class, $vmid, $node) = @_;
53
54 $node = $nodename if !$node;
55 return "nodes/$node/lxc/$vmid.conf";
56 }
57
58 sub mountpoint_backup_enabled {
59 my ($class, $mp_key, $mountpoint) = @_;
60
61 my $enabled;
62 my $reason;
63
64 if ($mp_key eq 'rootfs') {
65 $enabled = 1;
66 $reason = 'rootfs';
67 } elsif ($mountpoint->{type} ne 'volume') {
68 $enabled = 0;
69 $reason = 'not a volume';
70 } elsif ($mountpoint->{backup}) {
71 $enabled = 1;
72 $reason = 'enabled';
73 } else {
74 $enabled = 0;
75 $reason = 'disabled';
76 }
77 return wantarray ? ($enabled, $reason) : $enabled;
78 }
79
80 sub has_feature {
81 my ($class, $feature, $conf, $storecfg, $snapname, $running, $backup_only) = @_;
82 my $err;
83
84 my $opts;
85 if ($feature eq 'copy' || $feature eq 'clone') {
86 $opts = {'valid_target_formats' => ['raw', 'subvol']};
87 }
88
89 $class->foreach_volume($conf, sub {
90 my ($ms, $mountpoint) = @_;
91
92 return if $err; # skip further test
93 return if $backup_only && !$class->mountpoint_backup_enabled($ms, $mountpoint);
94
95 $err = 1 if !PVE::Storage::volume_has_feature(
96 $storecfg, $feature, $mountpoint->{volume}, $snapname, $running, $opts);
97 });
98
99 return $err ? 0 : 1;
100 }
101
102 sub __snapshot_save_vmstate {
103 my ($class, $vmid, $conf, $snapname, $storecfg) = @_;
104 die "implement me - snapshot_save_vmstate\n";
105 }
106
107 sub __snapshot_activate_storages {
108 my ($class, $conf, $include_vmstate) = @_;
109
110 my $storecfg = PVE::Storage::config();
111 my $opts = $include_vmstate ? { 'extra_keys' => ['vmstate'] } : {};
112 my $storage_hash = {};
113
114 $class->foreach_volume_full($conf, $opts, sub {
115 my ($vs, $mountpoint) = @_;
116
117 return if $mountpoint->{type} ne 'volume';
118
119 my ($storeid) = PVE::Storage::parse_volume_id($mountpoint->{volume});
120 $storage_hash->{$storeid} = 1;
121 });
122
123 PVE::Storage::activate_storage_list($storecfg, [ sort keys $storage_hash->%* ]);
124 }
125
126 sub __snapshot_check_running {
127 my ($class, $vmid) = @_;
128 return PVE::LXC::check_running($vmid);
129 }
130
131 sub __snapshot_check_freeze_needed {
132 my ($class, $vmid, $config, $save_vmstate) = @_;
133
134 my $ret = $class->__snapshot_check_running($vmid);
135 return ($ret, $ret);
136 }
137
138 # implements similar functionality to fsfreeze(8)
139 sub fsfreeze_mountpoint {
140 my ($path, $thaw) = @_;
141
142 my $op = $thaw ? 'thaw' : 'freeze';
143 my $ioctl = $thaw ? FITHAW : FIFREEZE;
144
145 sysopen my $fd, $path, O_RDONLY or die "failed to open $path: $!\n";
146 my $ioctl_err;
147 if (!ioctl($fd, $ioctl, 0)) {
148 $ioctl_err = "$!";
149 }
150 close($fd);
151 die "fs$op '$path' failed - $ioctl_err\n" if defined $ioctl_err;
152 }
153
154 sub __snapshot_freeze {
155 my ($class, $vmid, $unfreeze) = @_;
156
157 my $conf = $class->load_config($vmid);
158 my $storagecfg = PVE::Storage::config();
159
160 my $freeze_mps = [];
161 $class->foreach_volume($conf, sub {
162 my ($ms, $mountpoint) = @_;
163
164 return if $mountpoint->{type} ne 'volume';
165
166 if (PVE::Storage::volume_snapshot_needs_fsfreeze($storagecfg, $mountpoint->{volume})) {
167 push @$freeze_mps, $mountpoint->{mp};
168 }
169 });
170
171 my $freeze_mountpoints = sub {
172 my ($thaw) = @_;
173
174 return if scalar(@$freeze_mps) == 0;
175
176 my $pid = PVE::LXC::find_lxc_pid($vmid);
177
178 for my $mp (@$freeze_mps) {
179 eval{ fsfreeze_mountpoint("/proc/${pid}/root/${mp}", $thaw); };
180 warn $@ if $@;
181 }
182 };
183
184 if ($unfreeze) {
185 eval { PVE::LXC::thaw($vmid); };
186 warn $@ if $@;
187 $freeze_mountpoints->(1);
188 } else {
189 PVE::LXC::freeze($vmid);
190 PVE::LXC::sync_container_namespace($vmid);
191 $freeze_mountpoints->(0);
192 }
193 }
194
195 sub __snapshot_create_vol_snapshot {
196 my ($class, $vmid, $ms, $mountpoint, $snapname) = @_;
197
198 my $storecfg = PVE::Storage::config();
199
200 return if $snapname eq 'vzdump' &&
201 !$class->mountpoint_backup_enabled($ms, $mountpoint);
202
203 PVE::Storage::volume_snapshot($storecfg, $mountpoint->{volume}, $snapname);
204 }
205
206 sub __snapshot_delete_remove_drive {
207 my ($class, $snap, $remove_drive) = @_;
208
209 if ($remove_drive eq 'vmstate') {
210 die "implement me - saving vmstate\n";
211 } else {
212 my $value = $snap->{$remove_drive};
213 my $mountpoint = $class->parse_volume($remove_drive, $value, 1);
214 delete $snap->{$remove_drive};
215
216 $class->add_unused_volume($snap, $mountpoint->{volume})
217 if $mountpoint && ($mountpoint->{type} eq 'volume');
218 }
219 }
220
221 sub __snapshot_delete_vmstate_file {
222 my ($class, $snap, $force) = @_;
223
224 die "implement me - saving vmstate\n";
225 }
226
227 sub __snapshot_delete_vol_snapshot {
228 my ($class, $vmid, $ms, $mountpoint, $snapname, $unused) = @_;
229
230 return if $snapname eq 'vzdump' &&
231 !$class->mountpoint_backup_enabled($ms, $mountpoint);
232
233 my $storecfg = PVE::Storage::config();
234 PVE::Storage::volume_snapshot_delete($storecfg, $mountpoint->{volume}, $snapname);
235 push @$unused, $mountpoint->{volume};
236 }
237
238 sub __snapshot_rollback_vol_possible {
239 my ($class, $mountpoint, $snapname, $blockers) = @_;
240
241 my $storecfg = PVE::Storage::config();
242 PVE::Storage::volume_rollback_is_possible(
243 $storecfg,
244 $mountpoint->{volume},
245 $snapname,
246 $blockers,
247 );
248 }
249
250 sub __snapshot_rollback_vol_rollback {
251 my ($class, $mountpoint, $snapname) = @_;
252
253 my $storecfg = PVE::Storage::config();
254 PVE::Storage::volume_snapshot_rollback($storecfg, $mountpoint->{volume}, $snapname);
255 }
256
257 sub __snapshot_rollback_vm_stop {
258 my ($class, $vmid) = @_;
259
260 PVE::LXC::vm_stop($vmid, 1)
261 if $class->__snapshot_check_running($vmid);
262 }
263
264 sub __snapshot_rollback_vm_start {
265 my ($class, $vmid, $vmstate, $data);
266
267 die "implement me - save vmstate\n";
268 }
269
270 sub __snapshot_rollback_get_unused {
271 my ($class, $conf, $snap) = @_;
272
273 my $unused = [];
274
275 $class->foreach_volume($conf, sub {
276 my ($vs, $volume) = @_;
277
278 return if $volume->{type} ne 'volume';
279
280 my $found = 0;
281 my $volid = $volume->{volume};
282
283 $class->foreach_volume($snap, sub {
284 my ($ms, $mountpoint) = @_;
285
286 return if $found;
287 return if ($mountpoint->{type} ne 'volume');
288
289 $found = 1
290 if ($mountpoint->{volume} && $mountpoint->{volume} eq $volid);
291 });
292
293 push @$unused, $volid if !$found;
294 });
295
296 return $unused;
297 }
298
299 # END implemented abstract methods from PVE::AbstractConfig
300
301 # BEGIN JSON config code
302
303 cfs_register_file('/lxc/', \&parse_pct_config, \&write_pct_config);
304
305
306 my $valid_mount_option_re = qr/(noatime|lazytime|nodev|nosuid|noexec)/;
307
308 sub is_valid_mount_option {
309 my ($option) = @_;
310 return $option =~ $valid_mount_option_re;
311 }
312
313 my $rootfs_desc = {
314 volume => {
315 type => 'string',
316 default_key => 1,
317 format => 'pve-lxc-mp-string',
318 format_description => 'volume',
319 description => 'Volume, device or directory to mount into the container.',
320 },
321 size => {
322 type => 'string',
323 format => 'disk-size',
324 format_description => 'DiskSize',
325 description => 'Volume size (read only value).',
326 optional => 1,
327 },
328 acl => {
329 type => 'boolean',
330 description => 'Explicitly enable or disable ACL support.',
331 optional => 1,
332 },
333 mountoptions => {
334 optional => 1,
335 type => 'string',
336 description => 'Extra mount options for rootfs/mps.',
337 format_description => 'opt[;opt...]',
338 pattern => qr/$valid_mount_option_re(;$valid_mount_option_re)*/,
339 },
340 ro => {
341 type => 'boolean',
342 description => 'Read-only mount point',
343 optional => 1,
344 },
345 quota => {
346 type => 'boolean',
347 description => 'Enable user quotas inside the container (not supported with zfs subvolumes)',
348 optional => 1,
349 },
350 replicate => {
351 type => 'boolean',
352 description => 'Will include this volume to a storage replica job.',
353 optional => 1,
354 default => 1,
355 },
356 shared => {
357 type => 'boolean',
358 description => 'Mark this non-volume mount point as available on multiple nodes (see \'nodes\')',
359 verbose_description => "Mark this non-volume mount point as available on all nodes.\n\nWARNING: This option does not share the mount point automatically, it assumes it is shared already!",
360 optional => 1,
361 default => 0,
362 },
363 };
364
365 PVE::JSONSchema::register_standard_option('pve-ct-rootfs', {
366 type => 'string', format => $rootfs_desc,
367 description => "Use volume as container root.",
368 optional => 1,
369 });
370
371 # IP address with optional interface suffix for link local ipv6 addresses
372 PVE::JSONSchema::register_format('lxc-ip-with-ll-iface', \&verify_ip_with_ll_iface);
373 sub verify_ip_with_ll_iface {
374 my ($addr, $noerr) = @_;
375
376 if (my ($addr, $iface) = ($addr =~ /^(fe80:[^%]+)%(.*)$/)) {
377 if (PVE::JSONSchema::pve_verify_ip($addr, 1)
378 && PVE::JSONSchema::pve_verify_iface($iface, 1))
379 {
380 return $addr;
381 }
382 }
383
384 return PVE::JSONSchema::pve_verify_ip($addr, $noerr);
385 }
386
387
388 my $features_desc = {
389 mount => {
390 optional => 1,
391 type => 'string',
392 description => "Allow mounting file systems of specific types."
393 ." This should be a list of file system types as used with the mount command."
394 ." Note that this can have negative effects on the container's security."
395 ." With access to a loop device, mounting a file can circumvent the mknod"
396 ." permission of the devices cgroup, mounting an NFS file system can"
397 ." block the host's I/O completely and prevent it from rebooting, etc.",
398 format_description => 'fstype;fstype;...',
399 pattern => qr/[a-zA-Z0-9_; ]+/,
400 },
401 nesting => {
402 optional => 1,
403 type => 'boolean',
404 default => 0,
405 description => "Allow nesting."
406 ." Best used with unprivileged containers with additional id mapping."
407 ." Note that this will expose procfs and sysfs contents of the host"
408 ." to the guest.",
409 },
410 keyctl => {
411 optional => 1,
412 type => 'boolean',
413 default => 0,
414 description => "For unprivileged containers only: Allow the use of the keyctl() system call."
415 ." This is required to use docker inside a container."
416 ." By default unprivileged containers will see this system call as non-existent."
417 ." This is mostly a workaround for systemd-networkd, as it will treat it as a fatal"
418 ." error when some keyctl() operations are denied by the kernel due to lacking permissions."
419 ." Essentially, you can choose between running systemd-networkd or docker.",
420 },
421 fuse => {
422 optional => 1,
423 type => 'boolean',
424 default => 0,
425 description => "Allow using 'fuse' file systems in a container."
426 ." Note that interactions between fuse and the freezer cgroup can potentially cause I/O deadlocks.",
427 },
428 mknod => {
429 optional => 1,
430 type => 'boolean',
431 default => 0,
432 description => "Allow unprivileged containers to use mknod() to add certain device nodes."
433 ." This requires a kernel with seccomp trap to user space support (5.3 or newer)."
434 ." This is experimental.",
435 },
436 force_rw_sys => {
437 optional => 1,
438 type => 'boolean',
439 default => 0,
440 description => "Mount /sys in unprivileged containers as `rw` instead of `mixed`."
441 ." This can break networking under newer (>= v245) systemd-network use."
442 },
443 };
444
445 my $confdesc = {
446 lock => {
447 optional => 1,
448 type => 'string',
449 description => "Lock/unlock the container.",
450 enum => [qw(backup create destroyed disk fstrim migrate mounted rollback snapshot snapshot-delete)],
451 },
452 onboot => {
453 optional => 1,
454 type => 'boolean',
455 description => "Specifies whether a container will be started during system bootup.",
456 default => 0,
457 },
458 startup => get_standard_option('pve-startup-order'),
459 template => {
460 optional => 1,
461 type => 'boolean',
462 description => "Enable/disable Template.",
463 default => 0,
464 },
465 arch => {
466 optional => 1,
467 type => 'string',
468 enum => ['amd64', 'i386', 'arm64', 'armhf', 'riscv32', 'riscv64'],
469 description => "OS architecture type.",
470 default => 'amd64',
471 },
472 ostype => {
473 optional => 1,
474 type => 'string',
475 enum => [qw(debian devuan ubuntu centos fedora opensuse archlinux alpine gentoo nixos unmanaged)],
476 description => "OS type. This is used to setup configuration inside the container, and corresponds to lxc setup scripts in /usr/share/lxc/config/<ostype>.common.conf. Value 'unmanaged' can be used to skip and OS specific setup.",
477 },
478 console => {
479 optional => 1,
480 type => 'boolean',
481 description => "Attach a console device (/dev/console) to the container.",
482 default => 1,
483 },
484 tty => {
485 optional => 1,
486 type => 'integer',
487 description => "Specify the number of tty available to the container",
488 minimum => 0,
489 maximum => 6,
490 default => 2,
491 },
492 cores => {
493 optional => 1,
494 type => 'integer',
495 description => "The number of cores assigned to the container. A container can use all available cores by default.",
496 minimum => 1,
497 maximum => 8192,
498 },
499 cpulimit => {
500 optional => 1,
501 type => 'number',
502 description => "Limit of CPU usage.\n\nNOTE: If the computer has 2 CPUs, it has a total of '2' CPU time. Value '0' indicates no CPU limit.",
503 minimum => 0,
504 maximum => 8192,
505 default => 0,
506 },
507 cpuunits => {
508 optional => 1,
509 type => 'integer',
510 description => "CPU weight for a container, will be clamped to [1, 10000] in cgroup v2.",
511 verbose_description => "CPU weight for a container. Argument is used in the kernel fair "
512 ."scheduler. The larger the number is, the more CPU time this container gets. Number "
513 ."is relative to the weights of all the other running guests.",
514 minimum => 0,
515 maximum => 500000,
516 default => 'cgroup v1: 1024, cgroup v2: 100',
517 },
518 memory => {
519 optional => 1,
520 type => 'integer',
521 description => "Amount of RAM for the container in MB.",
522 minimum => 16,
523 default => 512,
524 },
525 swap => {
526 optional => 1,
527 type => 'integer',
528 description => "Amount of SWAP for the container in MB.",
529 minimum => 0,
530 default => 512,
531 },
532 hostname => {
533 optional => 1,
534 description => "Set a host name for the container.",
535 type => 'string', format => 'dns-name',
536 maxLength => 255,
537 },
538 description => {
539 optional => 1,
540 type => 'string',
541 description => "Description for the Container. Shown in the web-interface CT's summary."
542 ." This is saved as comment inside the configuration file.",
543 maxLength => 1024 * 8,
544 },
545 searchdomain => {
546 optional => 1,
547 type => 'string', format => 'dns-name-list',
548 description => "Sets DNS search domains for a container. Create will automatically use the setting from the host if you neither set searchdomain nor nameserver.",
549 },
550 nameserver => {
551 optional => 1,
552 type => 'string', format => 'lxc-ip-with-ll-iface-list',
553 description => "Sets DNS server IP address for a container. Create will automatically use the setting from the host if you neither set searchdomain nor nameserver.",
554 },
555 timezone => {
556 optional => 1,
557 type => 'string', format => 'pve-ct-timezone',
558 description => "Time zone to use in the container. If option isn't set, then nothing will be done. Can be set to 'host' to match the host time zone, or an arbitrary time zone option from /usr/share/zoneinfo/zone.tab",
559 },
560 rootfs => get_standard_option('pve-ct-rootfs'),
561 parent => {
562 optional => 1,
563 type => 'string', format => 'pve-configid',
564 maxLength => 40,
565 description => "Parent snapshot name. This is used internally, and should not be modified.",
566 },
567 snaptime => {
568 optional => 1,
569 description => "Timestamp for snapshots.",
570 type => 'integer',
571 minimum => 0,
572 },
573 cmode => {
574 optional => 1,
575 description => "Console mode. By default, the console command tries to open a connection to one of the available tty devices. By setting cmode to 'console' it tries to attach to /dev/console instead. If you set cmode to 'shell', it simply invokes a shell inside the container (no login).",
576 type => 'string',
577 enum => ['shell', 'console', 'tty'],
578 default => 'tty',
579 },
580 protection => {
581 optional => 1,
582 type => 'boolean',
583 description => "Sets the protection flag of the container. This will prevent the CT or CT's disk remove/update operation.",
584 default => 0,
585 },
586 unprivileged => {
587 optional => 1,
588 type => 'boolean',
589 description => "Makes the container run as unprivileged user. (Should not be modified manually.)",
590 default => 0,
591 },
592 features => {
593 optional => 1,
594 type => 'string',
595 format => $features_desc,
596 description => "Allow containers access to advanced features.",
597 },
598 hookscript => {
599 optional => 1,
600 type => 'string',
601 format => 'pve-volume-id',
602 description => 'Script that will be exectued during various steps in the containers lifetime.',
603 },
604 tags => {
605 type => 'string', format => 'pve-tag-list',
606 description => 'Tags of the Container. This is only meta information.',
607 optional => 1,
608 },
609 debug => {
610 optional => 1,
611 type => 'boolean',
612 description => "Try to be more verbose. For now this only enables debug log-level on start.",
613 default => 0,
614 },
615 };
616
617 my $valid_lxc_conf_keys = {
618 'lxc.apparmor.profile' => 1,
619 'lxc.apparmor.allow_incomplete' => 1,
620 'lxc.apparmor.allow_nesting' => 1,
621 'lxc.apparmor.raw' => 1,
622 'lxc.selinux.context' => 1,
623 'lxc.include' => 1,
624 'lxc.arch' => 1,
625 'lxc.uts.name' => 1,
626 'lxc.signal.halt' => 1,
627 'lxc.signal.reboot' => 1,
628 'lxc.signal.stop' => 1,
629 'lxc.init.cmd' => 1,
630 'lxc.pty.max' => 1,
631 'lxc.console.logfile' => 1,
632 'lxc.console.path' => 1,
633 'lxc.tty.max' => 1,
634 'lxc.devtty.dir' => 1,
635 'lxc.hook.autodev' => 1,
636 'lxc.autodev' => 1,
637 'lxc.kmsg' => 1,
638 'lxc.mount.fstab' => 1,
639 'lxc.mount.entry' => 1,
640 'lxc.mount.auto' => 1,
641 'lxc.rootfs.path' => 'lxc.rootfs.path is auto generated from rootfs',
642 'lxc.rootfs.mount' => 1,
643 'lxc.rootfs.options' => 'lxc.rootfs.options is not supported' .
644 ', please use mount point options in the "rootfs" key',
645 # lxc.cgroup.*
646 # lxc.prlimit.*
647 # lxc.net.*
648 'lxc.cap.drop' => 1,
649 'lxc.cap.keep' => 1,
650 'lxc.seccomp.profile' => 1,
651 'lxc.seccomp.notify.proxy' => 1,
652 'lxc.seccomp.notify.cookie' => 1,
653 'lxc.idmap' => 1,
654 'lxc.hook.pre-start' => 1,
655 'lxc.hook.pre-mount' => 1,
656 'lxc.hook.mount' => 1,
657 'lxc.hook.start' => 1,
658 'lxc.hook.stop' => 1,
659 'lxc.hook.post-stop' => 1,
660 'lxc.hook.clone' => 1,
661 'lxc.hook.destroy' => 1,
662 'lxc.hook.version' => 1,
663 'lxc.log.level' => 1,
664 'lxc.log.file' => 1,
665 'lxc.start.auto' => 1,
666 'lxc.start.delay' => 1,
667 'lxc.start.order' => 1,
668 'lxc.group' => 1,
669 'lxc.environment' => 1,
670
671 # All these are namespaced via CLONE_NEWIPC (see namespaces(7)).
672 'lxc.sysctl.fs.mqueue' => 1,
673 'lxc.sysctl.kernel.msgmax' => 1,
674 'lxc.sysctl.kernel.msgmnb' => 1,
675 'lxc.sysctl.kernel.msgmni' => 1,
676 'lxc.sysctl.kernel.sem' => 1,
677 'lxc.sysctl.kernel.shmall' => 1,
678 'lxc.sysctl.kernel.shmmax' => 1,
679 'lxc.sysctl.kernel.shmmni' => 1,
680 'lxc.sysctl.kernel.shm_rmid_forced' => 1,
681 };
682
683 my $deprecated_lxc_conf_keys = {
684 # Deprecated (removed with lxc 3.0):
685 'lxc.aa_profile' => 'lxc.apparmor.profile',
686 'lxc.aa_allow_incomplete' => 'lxc.apparmor.allow_incomplete',
687 'lxc.console' => 'lxc.console.path',
688 'lxc.devttydir' => 'lxc.tty.dir',
689 'lxc.haltsignal' => 'lxc.signal.halt',
690 'lxc.rebootsignal' => 'lxc.signal.reboot',
691 'lxc.stopsignal' => 'lxc.signal.stop',
692 'lxc.id_map' => 'lxc.idmap',
693 'lxc.init_cmd' => 'lxc.init.cmd',
694 'lxc.loglevel' => 'lxc.log.level',
695 'lxc.logfile' => 'lxc.log.file',
696 'lxc.mount' => 'lxc.mount.fstab',
697 'lxc.network.type' => 'lxc.net.INDEX.type',
698 'lxc.network.flags' => 'lxc.net.INDEX.flags',
699 'lxc.network.link' => 'lxc.net.INDEX.link',
700 'lxc.network.mtu' => 'lxc.net.INDEX.mtu',
701 'lxc.network.name' => 'lxc.net.INDEX.name',
702 'lxc.network.hwaddr' => 'lxc.net.INDEX.hwaddr',
703 'lxc.network.ipv4' => 'lxc.net.INDEX.ipv4.address',
704 'lxc.network.ipv4.gateway' => 'lxc.net.INDEX.ipv4.gateway',
705 'lxc.network.ipv6' => 'lxc.net.INDEX.ipv6.address',
706 'lxc.network.ipv6.gateway' => 'lxc.net.INDEX.ipv6.gateway',
707 'lxc.network.script.up' => 'lxc.net.INDEX.script.up',
708 'lxc.network.script.down' => 'lxc.net.INDEX.script.down',
709 'lxc.pts' => 'lxc.pty.max',
710 'lxc.se_context' => 'lxc.selinux.context',
711 'lxc.seccomp' => 'lxc.seccomp.profile',
712 'lxc.tty' => 'lxc.tty.max',
713 'lxc.utsname' => 'lxc.uts.name',
714 };
715
716 sub is_valid_lxc_conf_key {
717 my ($vmid, $key) = @_;
718 if ($key =~ /^lxc\.limit\./) {
719 warn "vm $vmid - $key: lxc.limit.* was renamed to lxc.prlimit.*\n";
720 return 1;
721 }
722 if (defined(my $new_name = $deprecated_lxc_conf_keys->{$key})) {
723 warn "vm $vmid - $key is deprecated and was renamed to $new_name\n";
724 return 1;
725 }
726 my $validity = $valid_lxc_conf_keys->{$key};
727 return $validity if defined($validity);
728 return 1 if $key =~ /^lxc\.cgroup2?\./ # allow all cgroup values
729 || $key =~ /^lxc\.prlimit\./ # allow all prlimits
730 || $key =~ /^lxc\.net\./; # allow custom network definitions
731 return 0;
732 }
733
734 our $netconf_desc = {
735 type => {
736 type => 'string',
737 optional => 1,
738 description => "Network interface type.",
739 enum => [qw(veth)],
740 },
741 name => {
742 type => 'string',
743 format_description => 'string',
744 description => 'Name of the network device as seen from inside the container. (lxc.network.name)',
745 pattern => '[-_.\w\d]+',
746 },
747 bridge => {
748 type => 'string',
749 format_description => 'bridge',
750 description => 'Bridge to attach the network device to.',
751 pattern => '[-_.\w\d]+',
752 optional => 1,
753 },
754 hwaddr => get_standard_option('mac-addr', {
755 description => 'The interface MAC address. This is dynamically allocated by default, but you can set that statically if needed, for example to always have the same link-local IPv6 address. (lxc.network.hwaddr)',
756 }),
757 mtu => {
758 type => 'integer',
759 description => 'Maximum transfer unit of the interface. (lxc.network.mtu)',
760 minimum => 64, # minimum ethernet frame is 64 bytes
761 maximum => 65535,
762 optional => 1,
763 },
764 ip => {
765 type => 'string',
766 format => 'pve-ipv4-config',
767 format_description => '(IPv4/CIDR|dhcp|manual)',
768 description => 'IPv4 address in CIDR format.',
769 optional => 1,
770 },
771 gw => {
772 type => 'string',
773 format => 'ipv4',
774 format_description => 'GatewayIPv4',
775 description => 'Default gateway for IPv4 traffic.',
776 optional => 1,
777 },
778 ip6 => {
779 type => 'string',
780 format => 'pve-ipv6-config',
781 format_description => '(IPv6/CIDR|auto|dhcp|manual)',
782 description => 'IPv6 address in CIDR format.',
783 optional => 1,
784 },
785 gw6 => {
786 type => 'string',
787 format => 'ipv6',
788 format_description => 'GatewayIPv6',
789 description => 'Default gateway for IPv6 traffic.',
790 optional => 1,
791 },
792 firewall => {
793 type => 'boolean',
794 description => "Controls whether this interface's firewall rules should be used.",
795 optional => 1,
796 },
797 tag => {
798 type => 'integer',
799 minimum => 1,
800 maximum => 4094,
801 description => "VLAN tag for this interface.",
802 optional => 1,
803 },
804 trunks => {
805 type => 'string',
806 pattern => qr/\d+(?:;\d+)*/,
807 format_description => 'vlanid[;vlanid...]',
808 description => "VLAN ids to pass through the interface",
809 optional => 1,
810 },
811 rate => {
812 type => 'number',
813 format_description => 'mbps',
814 description => "Apply rate limiting to the interface",
815 optional => 1,
816 },
817 # TODO: Rename this option and the qemu-server one to `link-down` for PVE 8.0
818 link_down => {
819 type => 'boolean',
820 description => 'Whether this interface should be disconnected (like pulling the plug).',
821 optional => 1,
822 },
823 };
824 PVE::JSONSchema::register_format('pve-lxc-network', $netconf_desc);
825
826 my $MAX_LXC_NETWORKS = 32;
827 for (my $i = 0; $i < $MAX_LXC_NETWORKS; $i++) {
828 $confdesc->{"net$i"} = {
829 optional => 1,
830 type => 'string', format => $netconf_desc,
831 description => "Specifies network interfaces for the container.",
832 };
833 }
834
835 PVE::JSONSchema::register_format('pve-ct-timezone', \&verify_ct_timezone);
836 sub verify_ct_timezone {
837 my ($timezone, $noerr) = @_;
838
839 return if $timezone eq 'host'; # using host settings
840
841 PVE::JSONSchema::pve_verify_timezone($timezone);
842 }
843
844 PVE::JSONSchema::register_format('pve-lxc-mp-string', \&verify_lxc_mp_string);
845 sub verify_lxc_mp_string {
846 my ($mp, $noerr) = @_;
847
848 # do not allow:
849 # /./ or /../
850 # /. or /.. at the end
851 # ../ at the beginning
852
853 if($mp =~ m@/\.\.?/@ ||
854 $mp =~ m@/\.\.?$@ ||
855 $mp =~ m@^\.\./@) {
856 return undef if $noerr;
857 die "$mp contains illegal character sequences\n";
858 }
859 return $mp;
860 }
861
862 my $mp_desc = {
863 %$rootfs_desc,
864 backup => {
865 type => 'boolean',
866 description => 'Whether to include the mount point in backups.',
867 verbose_description => 'Whether to include the mount point in backups '.
868 '(only used for volume mount points).',
869 optional => 1,
870 },
871 mp => {
872 type => 'string',
873 format => 'pve-lxc-mp-string',
874 format_description => 'Path',
875 description => 'Path to the mount point as seen from inside the container '.
876 '(must not contain symlinks).',
877 verbose_description => "Path to the mount point as seen from inside the container.\n\n".
878 "NOTE: Must not contain any symlinks for security reasons."
879 },
880 };
881 PVE::JSONSchema::register_format('pve-ct-mountpoint', $mp_desc);
882
883 my $unused_desc = {
884 volume => {
885 type => 'string',
886 default_key => 1,
887 format => 'pve-volume-id',
888 format_description => 'volume',
889 description => 'The volume that is not used currently.',
890 }
891 };
892
893 for (my $i = 0; $i < $MAX_MOUNT_POINTS; $i++) {
894 $confdesc->{"mp$i"} = {
895 optional => 1,
896 type => 'string', format => $mp_desc,
897 description => "Use volume as container mount point. Use the special " .
898 "syntax STORAGE_ID:SIZE_IN_GiB to allocate a new volume.",
899 optional => 1,
900 };
901 }
902
903 for (my $i = 0; $i < $MAX_UNUSED_DISKS; $i++) {
904 $confdesc->{"unused$i"} = {
905 optional => 1,
906 type => 'string', format => $unused_desc,
907 description => "Reference to unused volumes. This is used internally, and should not be modified manually.",
908 }
909 }
910
911 sub parse_pct_config {
912 my ($filename, $raw, $strict) = @_;
913
914 return undef if !defined($raw);
915
916 my $res = {
917 digest => Digest::SHA::sha1_hex($raw),
918 snapshots => {},
919 pending => {},
920 };
921
922 my $handle_error = sub {
923 my ($msg) = @_;
924
925 if ($strict) {
926 die $msg;
927 } else {
928 warn $msg;
929 }
930 };
931
932 $filename =~ m|/lxc/(\d+).conf$|
933 || die "got strange filename '$filename'";
934
935 my $vmid = $1;
936
937 my $conf = $res;
938 my $descr = '';
939 my $section = '';
940
941 my @lines = split(/\n/, $raw);
942 foreach my $line (@lines) {
943 next if $line =~ m/^\s*$/;
944
945 if ($line =~ m/^\[pve:pending\]\s*$/i) {
946 $section = 'pending';
947 $conf->{description} = $descr if $descr;
948 $descr = '';
949 $conf = $res->{$section} = {};
950 next;
951 } elsif ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) {
952 $section = $1;
953 $conf->{description} = $descr if $descr;
954 $descr = '';
955 $conf = $res->{snapshots}->{$section} = {};
956 next;
957 }
958
959 if ($line =~ m/^\#(.*)$/) {
960 $descr .= PVE::Tools::decode_text($1) . "\n";
961 next;
962 }
963
964 if ($line =~ m/^(lxc\.[a-z0-9_\-\.]+)(:|\s*=)\s*(.*?)\s*$/) {
965 my $key = $1;
966 my $value = $3;
967 my $validity = is_valid_lxc_conf_key($vmid, $key);
968 if ($validity eq 1) {
969 push @{$conf->{lxc}}, [$key, $value];
970 } elsif (my $errmsg = $validity) {
971 $handle_error->("vm $vmid - $key: $errmsg\n");
972 } else {
973 $handle_error->("vm $vmid - unable to parse config: $line\n");
974 }
975 } elsif ($line =~ m/^(description):\s*(.*\S)\s*$/) {
976 $descr .= PVE::Tools::decode_text($2);
977 } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) {
978 $conf->{snapstate} = $1;
979 } elsif ($line =~ m/^delete:\s*(.*\S)\s*$/) {
980 my $value = $1;
981 if ($section eq 'pending') {
982 $conf->{delete} = $value;
983 } else {
984 $handle_error->("vm $vmid - property 'delete' is only allowed in [pve:pending]\n");
985 }
986 } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(.+?)\s*$/) {
987 my $key = $1;
988 my $value = $2;
989 eval { $value = PVE::LXC::Config->check_type($key, $value); };
990 $handle_error->("vm $vmid - unable to parse value of '$key' - $@") if $@;
991 $conf->{$key} = $value;
992 } else {
993 $handle_error->("vm $vmid - unable to parse config: $line\n");
994 }
995 }
996
997 $conf->{description} = $descr if $descr;
998
999 delete $res->{snapstate}; # just to be sure
1000
1001 return $res;
1002 }
1003
1004 sub write_pct_config {
1005 my ($filename, $conf) = @_;
1006
1007 delete $conf->{snapstate}; # just to be sure
1008
1009 my $volidlist = PVE::LXC::Config->get_vm_volumes($conf);
1010 my $used_volids = {};
1011 foreach my $vid (@$volidlist) {
1012 $used_volids->{$vid} = 1;
1013 }
1014
1015 # remove 'unusedX' settings if the volume is still used
1016 foreach my $key (keys %$conf) {
1017 my $value = $conf->{$key};
1018 if ($key =~ m/^unused/ && $used_volids->{$value}) {
1019 delete $conf->{$key};
1020 }
1021 }
1022
1023 my $generate_raw_config = sub {
1024 my ($conf) = @_;
1025
1026 my $raw = '';
1027
1028 # add description as comment to top of file
1029 my $descr = $conf->{description} || '';
1030 foreach my $cl (split(/\n/, $descr)) {
1031 $raw .= '#' . PVE::Tools::encode_text($cl) . "\n";
1032 }
1033
1034 foreach my $key (sort keys %$conf) {
1035 next if $key eq 'digest' || $key eq 'description' ||
1036 $key eq 'pending' || $key eq 'snapshots' ||
1037 $key eq 'snapname' || $key eq 'lxc';
1038 my $value = $conf->{$key};
1039 die "detected invalid newline inside property '$key'\n"
1040 if $value =~ m/\n/;
1041 $raw .= "$key: $value\n";
1042 }
1043
1044 if (my $lxcconf = $conf->{lxc}) {
1045 foreach my $entry (@$lxcconf) {
1046 my ($k, $v) = @$entry;
1047 $raw .= "$k: $v\n";
1048 }
1049 }
1050
1051 return $raw;
1052 };
1053
1054 my $raw = &$generate_raw_config($conf);
1055
1056 if (scalar(keys %{$conf->{pending}})){
1057 $raw .= "\n[pve:pending]\n";
1058 $raw .= &$generate_raw_config($conf->{pending});
1059 }
1060
1061 foreach my $snapname (sort keys %{$conf->{snapshots}}) {
1062 $raw .= "\n[$snapname]\n";
1063 $raw .= &$generate_raw_config($conf->{snapshots}->{$snapname});
1064 }
1065
1066 return $raw;
1067 }
1068
1069 sub update_pct_config {
1070 my ($class, $vmid, $conf, $running, $param, $delete, $revert) = @_;
1071
1072 my $storage_cfg = PVE::Storage::config();
1073
1074 foreach my $opt (@$revert) {
1075 delete $conf->{pending}->{$opt};
1076 $class->remove_from_pending_delete($conf, $opt); # also remove from deletion queue
1077 }
1078
1079 # write updates to pending section
1080 my $modified = {}; # record modified options
1081
1082 foreach my $opt (@$delete) {
1083 if (!defined($conf->{$opt}) && !defined($conf->{pending}->{$opt})) {
1084 warn "cannot delete '$opt' - not set in current configuration!\n";
1085 next;
1086 }
1087 $modified->{$opt} = 1;
1088 if ($opt eq 'memory' || $opt eq 'rootfs' || $opt eq 'ostype') {
1089 die "unable to delete required option '$opt'\n";
1090 } elsif ($opt =~ m/^unused(\d+)$/) {
1091 $class->check_protection($conf, "can't remove CT $vmid drive '$opt'");
1092 } elsif ($opt =~ m/^mp(\d+)$/) {
1093 $class->check_protection($conf, "can't remove CT $vmid drive '$opt'");
1094 } elsif ($opt eq 'unprivileged') {
1095 die "unable to delete read-only option: '$opt'\n";
1096 }
1097 $class->add_to_pending_delete($conf, $opt);
1098 }
1099
1100 my $check_content_type = sub {
1101 my ($mp) = @_;
1102 my $sid = PVE::Storage::parse_volume_id($mp->{volume});
1103 my $storage_config = PVE::Storage::storage_config($storage_cfg, $sid);
1104 die "storage '$sid' does not allow content type 'rootdir' (Container)\n"
1105 if !$storage_config->{content}->{rootdir};
1106 };
1107
1108 foreach my $opt (sort keys %$param) { # add/change
1109 $modified->{$opt} = 1;
1110 my $value = $param->{$opt};
1111 if ($opt =~ m/^mp(\d+)$/ || $opt eq 'rootfs') {
1112 $class->check_protection($conf, "can't update CT $vmid drive '$opt'");
1113 my $mp = $class->parse_volume($opt, $value);
1114 $check_content_type->($mp) if ($mp->{type} eq 'volume');
1115 } elsif ($opt eq 'hookscript') {
1116 PVE::GuestHelpers::check_hookscript($value);
1117 } elsif ($opt eq 'nameserver') {
1118 $value = PVE::LXC::verify_nameserver_list($value);
1119 } elsif ($opt eq 'searchdomain') {
1120 $value = PVE::LXC::verify_searchdomain_list($value);
1121 } elsif ($opt eq 'unprivileged') {
1122 die "unable to modify read-only option: '$opt'\n";
1123 } elsif ($opt eq 'tags') {
1124 $value = PVE::GuestHelpers::get_unique_tags($value);
1125 } elsif ($opt =~ m/^net(\d+)$/) {
1126 my $res = PVE::JSONSchema::parse_property_string($netconf_desc, $value);
1127
1128 if (my $mtu = $res->{mtu}) {
1129 my $bridge_mtu = PVE::Network::read_bridge_mtu($res->{bridge});
1130 die "$opt: MTU size '$mtu' is bigger than bridge MTU '$bridge_mtu'\n"
1131 if ($mtu > $bridge_mtu);
1132 }
1133 }
1134 $conf->{pending}->{$opt} = $value;
1135 $class->remove_from_pending_delete($conf, $opt);
1136 }
1137
1138 my $changes = $class->cleanup_pending($conf);
1139
1140 my $errors = {};
1141 if ($running) {
1142 $class->vmconfig_hotplug_pending($vmid, $conf, $storage_cfg, $modified, $errors);
1143 } else {
1144 $class->vmconfig_apply_pending($vmid, $conf, $storage_cfg, $modified, $errors);
1145 }
1146
1147 return $errors;
1148 }
1149
1150 sub check_type {
1151 my ($class, $key, $value) = @_;
1152
1153 die "unknown setting '$key'\n" if !$confdesc->{$key};
1154
1155 my $type = $confdesc->{$key}->{type};
1156
1157 if (!defined($value)) {
1158 die "got undefined value\n";
1159 }
1160
1161 if ($value =~ m/[\n\r]/) {
1162 die "property contains a line feed\n";
1163 }
1164
1165 if ($type eq 'boolean') {
1166 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
1167 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
1168 die "type check ('boolean') failed - got '$value'\n";
1169 } elsif ($type eq 'integer') {
1170 return int($1) if $value =~ m/^(\d+)$/;
1171 die "type check ('integer') failed - got '$value'\n";
1172 } elsif ($type eq 'number') {
1173 return $value if $value =~ m/^(\d+)(\.\d+)?$/;
1174 die "type check ('number') failed - got '$value'\n";
1175 } elsif ($type eq 'string') {
1176 if (my $fmt = $confdesc->{$key}->{format}) {
1177 PVE::JSONSchema::check_format($fmt, $value);
1178 return $value;
1179 }
1180 return $value;
1181 } else {
1182 die "internal error"
1183 }
1184 }
1185
1186
1187 # add JSON properties for create and set function
1188 sub json_config_properties {
1189 my ($class, $prop) = @_;
1190
1191 foreach my $opt (keys %$confdesc) {
1192 next if $opt eq 'parent' || $opt eq 'snaptime';
1193 next if $prop->{$opt};
1194 $prop->{$opt} = $confdesc->{$opt};
1195 }
1196
1197 return $prop;
1198 }
1199
1200 my $parse_ct_mountpoint_full = sub {
1201 my ($class, $desc, $data, $noerr) = @_;
1202
1203 $data //= '';
1204
1205 my $res;
1206 eval { $res = PVE::JSONSchema::parse_property_string($desc, $data) };
1207 if ($@) {
1208 return undef if $noerr;
1209 die $@;
1210 }
1211
1212 if (defined(my $size = $res->{size})) {
1213 $size = PVE::JSONSchema::parse_size($size);
1214 if (!defined($size)) {
1215 return undef if $noerr;
1216 die "invalid size: $size\n";
1217 }
1218 $res->{size} = $size;
1219 }
1220
1221 $res->{type} = $class->classify_mountpoint($res->{volume});
1222
1223 return $res;
1224 };
1225
1226 sub print_ct_mountpoint {
1227 my ($class, $info, $nomp) = @_;
1228 my $skip = [ 'type' ];
1229 push @$skip, 'mp' if $nomp;
1230 return PVE::JSONSchema::print_property_string($info, $mp_desc, $skip);
1231 }
1232
1233 sub print_ct_unused {
1234 my ($class, $info) = @_;
1235
1236 my $skip = [ 'type' ];
1237 return PVE::JSONSchema::print_property_string($info, $unused_desc, $skip);
1238 }
1239
1240 sub parse_volume {
1241 my ($class, $key, $volume_string, $noerr) = @_;
1242
1243 if ($key eq 'rootfs') {
1244 my $res = $parse_ct_mountpoint_full->($class, $rootfs_desc, $volume_string, $noerr);
1245 $res->{mp} = '/' if defined($res);
1246 return $res;
1247 } elsif ($key =~ m/^mp\d+$/) {
1248 return $parse_ct_mountpoint_full->($class, $mp_desc, $volume_string, $noerr);
1249 } elsif ($key =~ m/^unused\d+$/) {
1250 return $parse_ct_mountpoint_full->($class, $unused_desc, $volume_string, $noerr);
1251 }
1252
1253 die "parse_volume - unknown type: $key\n" if !$noerr;
1254
1255 return;
1256 }
1257
1258 sub print_volume {
1259 my ($class, $key, $volume) = @_;
1260
1261 return $class->print_ct_unused($volume) if $key =~ m/^unused(\d+)$/;
1262
1263 return $class->print_ct_mountpoint($volume, $key eq 'rootfs');
1264 }
1265
1266 sub volid_key {
1267 my ($class) = @_;
1268
1269 return 'volume';
1270 }
1271
1272 sub print_lxc_network {
1273 my ($class, $net) = @_;
1274 return PVE::JSONSchema::print_property_string($net, $netconf_desc);
1275 }
1276
1277 sub parse_lxc_network {
1278 my ($class, $data) = @_;
1279
1280 return {} if !$data;
1281
1282 my $res = PVE::JSONSchema::parse_property_string($netconf_desc, $data);
1283
1284 $res->{type} = 'veth';
1285 if (!$res->{hwaddr}) {
1286 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
1287 $res->{hwaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
1288 }
1289
1290 return $res;
1291 }
1292
1293 sub parse_features {
1294 my ($class, $data) = @_;
1295 return {} if !$data;
1296 return PVE::JSONSchema::parse_property_string($features_desc, $data);
1297 }
1298
1299 sub option_exists {
1300 my ($class, $name) = @_;
1301
1302 return defined($confdesc->{$name});
1303 }
1304 # END JSON config code
1305
1306 my $LXC_FASTPLUG_OPTIONS= {
1307 'description' => 1,
1308 'onboot' => 1,
1309 'startup' => 1,
1310 'protection' => 1,
1311 'hostname' => 1,
1312 'hookscript' => 1,
1313 'cores' => 1,
1314 'tags' => 1,
1315 'lock' => 1,
1316 };
1317
1318 sub vmconfig_hotplug_pending {
1319 my ($class, $vmid, $conf, $storecfg, $selection, $errors) = @_;
1320
1321 my $pid = PVE::LXC::find_lxc_pid($vmid);
1322 my $rootdir = "/proc/$pid/root";
1323
1324 my $add_hotplug_error = sub {
1325 my ($opt, $msg) = @_;
1326 $errors->{$opt} = "unable to hotplug $opt: $msg";
1327 };
1328
1329 foreach my $opt (sort keys %{$conf->{pending}}) { # add/change
1330 next if $selection && !$selection->{$opt};
1331 if ($LXC_FASTPLUG_OPTIONS->{$opt}) {
1332 $conf->{$opt} = delete $conf->{pending}->{$opt};
1333 }
1334 }
1335
1336 my $cgroup = PVE::LXC::CGroup->new($vmid);
1337
1338 # There's no separate swap size to configure, there's memory and "total"
1339 # memory (iow. memory+swap). This means we have to change them together.
1340 my $hotplug_memory_done;
1341 my $hotplug_memory = sub {
1342 my ($wanted_memory, $wanted_swap) = @_;
1343
1344 $wanted_memory = int($wanted_memory * 1024 * 1024) if defined($wanted_memory);
1345 $wanted_swap = int($wanted_swap * 1024 * 1024) if defined($wanted_swap);
1346 $cgroup->change_memory_limit($wanted_memory, $wanted_swap);
1347
1348 $hotplug_memory_done = 1;
1349 };
1350
1351 my $pending_delete_hash = $class->parse_pending_delete($conf->{pending}->{delete});
1352 # FIXME: $force deletion is not implemented for CTs
1353 foreach my $opt (sort keys %$pending_delete_hash) {
1354 next if $selection && !$selection->{$opt};
1355 eval {
1356 if ($LXC_FASTPLUG_OPTIONS->{$opt}) {
1357 # pass
1358 } elsif ($opt =~ m/^unused(\d+)$/) {
1359 PVE::LXC::delete_mountpoint_volume($storecfg, $vmid, $conf->{$opt})
1360 if !$class->is_volume_in_use($conf, $conf->{$opt}, 1, 1);
1361 } elsif ($opt eq 'swap') {
1362 $hotplug_memory->(undef, 0);
1363 } elsif ($opt eq 'cpulimit') {
1364 $cgroup->change_cpu_quota(undef, undef); # reset, cgroup module can better decide values
1365 } elsif ($opt eq 'cpuunits') {
1366 $cgroup->change_cpu_shares(undef);
1367 } elsif ($opt =~ m/^net(\d)$/) {
1368 my $netid = $1;
1369 PVE::Network::veth_delete("veth${vmid}i$netid");
1370 } else {
1371 die "skip\n"; # skip non-hotpluggable opts
1372 }
1373 };
1374 if (my $err = $@) {
1375 $add_hotplug_error->($opt, $err) if $err ne "skip\n";
1376 } else {
1377 delete $conf->{$opt};
1378 $class->remove_from_pending_delete($conf, $opt);
1379 }
1380 }
1381
1382 foreach my $opt (sort keys %{$conf->{pending}}) {
1383 next if $opt eq 'delete'; # just to be sure
1384 next if $selection && !$selection->{$opt};
1385 my $value = $conf->{pending}->{$opt};
1386 eval {
1387 if ($opt eq 'cpulimit') {
1388 my $quota = 100000 * $value;
1389 $cgroup->change_cpu_quota(int(100000 * $value), 100000);
1390 } elsif ($opt eq 'cpuunits') {
1391 $cgroup->change_cpu_shares($value);
1392 } elsif ($opt =~ m/^net(\d+)$/) {
1393 my $netid = $1;
1394 my $net = $class->parse_lxc_network($value);
1395 $value = $class->print_lxc_network($net);
1396 PVE::LXC::update_net($vmid, $conf, $opt, $net, $netid, $rootdir);
1397 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1398 if (!$hotplug_memory_done) { # don't call twice if both opts are passed
1399 $hotplug_memory->($conf->{pending}->{memory}, $conf->{pending}->{swap});
1400 }
1401 } elsif ($opt =~ m/^mp(\d+)$/) {
1402 if (!PVE::LXC::Tools::can_use_new_mount_api()) {
1403 die "skip\n";
1404 }
1405
1406 if (exists($conf->{$opt})) {
1407 die "skip\n"; # don't try to hotplug over existing mp
1408 }
1409
1410 $class->apply_pending_mountpoint($vmid, $conf, $opt, $storecfg, 1);
1411 # apply_pending_mountpoint modifies the value if it creates a new disk
1412 $value = $conf->{pending}->{$opt};
1413 } else {
1414 die "skip\n"; # skip non-hotpluggable
1415 }
1416 };
1417 if (my $err = $@) {
1418 $add_hotplug_error->($opt, $err) if $err ne "skip\n";
1419 } else {
1420 $conf->{$opt} = $value;
1421 delete $conf->{pending}->{$opt};
1422 }
1423 }
1424 }
1425
1426 sub vmconfig_apply_pending {
1427 my ($class, $vmid, $conf, $storecfg, $selection, $errors) = @_;
1428
1429 my $add_apply_error = sub {
1430 my ($opt, $msg) = @_;
1431 my $err_msg = "unable to apply pending change $opt : $msg";
1432 $errors->{$opt} = $err_msg;
1433 warn $err_msg;
1434 };
1435
1436 my $pending_delete_hash = $class->parse_pending_delete($conf->{pending}->{delete});
1437 # FIXME: $force deletion is not implemented for CTs
1438 foreach my $opt (sort keys %$pending_delete_hash) {
1439 next if $selection && !$selection->{$opt};
1440 eval {
1441 if ($opt =~ m/^mp(\d+)$/) {
1442 my $mp = $class->parse_volume($opt, $conf->{$opt});
1443 if ($mp->{type} eq 'volume') {
1444 $class->add_unused_volume($conf, $mp->{volume})
1445 if !$class->is_volume_in_use($conf, $conf->{$opt}, 1, 1);
1446 }
1447 } elsif ($opt =~ m/^unused(\d+)$/) {
1448 PVE::LXC::delete_mountpoint_volume($storecfg, $vmid, $conf->{$opt})
1449 if !$class->is_volume_in_use($conf, $conf->{$opt}, 1, 1);
1450 }
1451 };
1452 if (my $err = $@) {
1453 $add_apply_error->($opt, $err);
1454 } else {
1455 delete $conf->{$opt};
1456 $class->remove_from_pending_delete($conf, $opt);
1457 }
1458 }
1459
1460 $class->cleanup_pending($conf);
1461
1462 foreach my $opt (sort keys %{$conf->{pending}}) { # add/change
1463 next if $opt eq 'delete'; # just to be sure
1464 next if $selection && !$selection->{$opt};
1465 eval {
1466 if ($opt =~ m/^mp(\d+)$/) {
1467 $class->apply_pending_mountpoint($vmid, $conf, $opt, $storecfg, 0);
1468 } elsif ($opt =~ m/^net(\d+)$/) {
1469 my $netid = $1;
1470 my $net = $class->parse_lxc_network($conf->{pending}->{$opt});
1471 $conf->{pending}->{$opt} = $class->print_lxc_network($net);
1472 }
1473 };
1474 if (my $err = $@) {
1475 $add_apply_error->($opt, $err);
1476 } else {
1477 $conf->{$opt} = delete $conf->{pending}->{$opt};
1478 }
1479 }
1480 }
1481
1482 my $rescan_volume = sub {
1483 my ($storecfg, $mp) = @_;
1484 eval {
1485 $mp->{size} = PVE::Storage::volume_size_info($storecfg, $mp->{volume}, 5);
1486 };
1487 warn "Could not rescan volume size - $@\n" if $@;
1488 };
1489
1490 sub apply_pending_mountpoint {
1491 my ($class, $vmid, $conf, $opt, $storecfg, $running) = @_;
1492
1493 my $mp = $class->parse_volume($opt, $conf->{pending}->{$opt});
1494 my $old = $conf->{$opt};
1495 if ($mp->{type} eq 'volume' && $mp->{volume} =~ $PVE::LXC::NEW_DISK_RE) {
1496 my $original_value = $conf->{pending}->{$opt};
1497 my $vollist = PVE::LXC::create_disks(
1498 $storecfg,
1499 $vmid,
1500 { $opt => $original_value },
1501 $conf,
1502 1,
1503 );
1504 if ($running) {
1505 # Re-parse mount point:
1506 my $mp = $class->parse_volume($opt, $conf->{pending}->{$opt});
1507 eval {
1508 PVE::LXC::mountpoint_hotplug($vmid, $conf, $opt, $mp, $storecfg);
1509 };
1510 my $err = $@;
1511 if ($err) {
1512 PVE::LXC::destroy_disks($storecfg, $vollist);
1513 # The pending-changes code collects errors but keeps on looping through further
1514 # pending changes, so unroll the change in $conf as well if destroy_disks()
1515 # didn't die().
1516 $conf->{pending}->{$opt} = $original_value;
1517 die $err;
1518 }
1519 }
1520 } else {
1521 die "skip\n" if $running && defined($old); # TODO: "changing" mount points?
1522 $rescan_volume->($storecfg, $mp) if $mp->{type} eq 'volume';
1523 if ($running) {
1524 PVE::LXC::mountpoint_hotplug($vmid, $conf, $opt, $mp, $storecfg);
1525 }
1526 $conf->{pending}->{$opt} = $class->print_ct_mountpoint($mp);
1527 }
1528
1529 if (defined($old)) {
1530 my $mp = $class->parse_volume($opt, $old);
1531 if ($mp->{type} eq 'volume') {
1532 $class->add_unused_volume($conf, $mp->{volume})
1533 if !$class->is_volume_in_use($conf, $conf->{$opt}, 1, 1);
1534 }
1535 }
1536 }
1537
1538 sub classify_mountpoint {
1539 my ($class, $vol) = @_;
1540 if ($vol =~ m!^/!) {
1541 return 'device' if $vol =~ m!^/dev/!;
1542 return 'bind';
1543 }
1544 return 'volume';
1545 }
1546
1547 my $__is_volume_in_use = sub {
1548 my ($class, $config, $volid) = @_;
1549 my $used = 0;
1550
1551 $class->foreach_volume($config, sub {
1552 my ($ms, $mountpoint) = @_;
1553 return if $used;
1554 $used = $mountpoint->{type} eq 'volume' && $mountpoint->{volume} eq $volid;
1555 });
1556
1557 return $used;
1558 };
1559
1560 sub is_volume_in_use_by_snapshots {
1561 my ($class, $config, $volid) = @_;
1562
1563 if (my $snapshots = $config->{snapshots}) {
1564 foreach my $snap (keys %$snapshots) {
1565 return 1 if $__is_volume_in_use->($class, $snapshots->{$snap}, $volid);
1566 }
1567 }
1568
1569 return 0;
1570 }
1571
1572 sub is_volume_in_use {
1573 my ($class, $config, $volid, $include_snapshots, $include_pending) = @_;
1574 return 1 if $__is_volume_in_use->($class, $config, $volid);
1575 return 1 if $include_snapshots && $class->is_volume_in_use_by_snapshots($config, $volid);
1576 return 1 if $include_pending && $__is_volume_in_use->($class, $config->{pending}, $volid);
1577 return 0;
1578 }
1579
1580 sub has_dev_console {
1581 my ($class, $conf) = @_;
1582
1583 return !(defined($conf->{console}) && !$conf->{console});
1584 }
1585
1586 sub has_lxc_entry {
1587 my ($class, $conf, $keyname) = @_;
1588
1589 if (my $lxcconf = $conf->{lxc}) {
1590 foreach my $entry (@$lxcconf) {
1591 my ($key, undef) = @$entry;
1592 return 1 if $key eq $keyname;
1593 }
1594 }
1595
1596 return 0;
1597 }
1598
1599 sub get_tty_count {
1600 my ($class, $conf) = @_;
1601
1602 return $conf->{tty} // $confdesc->{tty}->{default};
1603 }
1604
1605 sub get_cmode {
1606 my ($class, $conf) = @_;
1607
1608 return $conf->{cmode} // $confdesc->{cmode}->{default};
1609 }
1610
1611 sub valid_volume_keys {
1612 my ($class, $reverse) = @_;
1613
1614 my @names = ('rootfs');
1615
1616 for (my $i = 0; $i < $MAX_MOUNT_POINTS; $i++) {
1617 push @names, "mp$i";
1618 }
1619
1620 return $reverse ? reverse @names : @names;
1621 }
1622
1623 sub valid_volume_keys_with_unused {
1624 my ($class, $reverse) = @_;
1625 my @names = $class->valid_volume_keys();
1626 for (my $i = 0; $i < $MAX_UNUSED_DISKS; $i++) {
1627 push @names, "unused$i";
1628 }
1629 return $reverse ? reverse @names : @names;
1630 }
1631
1632 sub get_vm_volumes {
1633 my ($class, $conf, $excludes) = @_;
1634
1635 my $vollist = [];
1636
1637 $class->foreach_volume($conf, sub {
1638 my ($ms, $mountpoint) = @_;
1639
1640 return if $excludes && $ms eq $excludes;
1641
1642 my $volid = $mountpoint->{volume};
1643 return if !$volid || $mountpoint->{type} ne 'volume';
1644
1645 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1646 return if !$sid;
1647
1648 push @$vollist, $volid;
1649 });
1650
1651 return $vollist;
1652 }
1653
1654 sub get_replicatable_volumes {
1655 my ($class, $storecfg, $vmid, $conf, $cleanup, $noerr) = @_;
1656
1657 my $volhash = {};
1658
1659 my $test_volid = sub {
1660 my ($volid, $mountpoint) = @_;
1661
1662 return if !$volid;
1663
1664 my $mptype = $mountpoint->{type};
1665 my $replicate = $mountpoint->{replicate} // 1;
1666
1667 if ($mptype ne 'volume') {
1668 # skip bindmounts if replicate = 0 even for cleanup,
1669 # since bind mounts could not have been replicated ever
1670 return if !$replicate;
1671 die "unable to replicate mountpoint type '$mptype'\n";
1672 }
1673
1674 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, $noerr);
1675 return if !$storeid;
1676
1677 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
1678 return if $scfg->{shared};
1679
1680 my ($path, $owner, $vtype) = PVE::Storage::path($storecfg, $volid);
1681 return if !$owner || ($owner != $vmid);
1682
1683 die "unable to replicate volume '$volid', type '$vtype'\n" if $vtype ne 'images';
1684
1685 return if !$cleanup && !$replicate;
1686
1687 if (!PVE::Storage::volume_has_feature($storecfg, 'replicate', $volid)) {
1688 return if $cleanup || $noerr;
1689 die "missing replicate feature on volume '$volid'\n";
1690 }
1691
1692 $volhash->{$volid} = 1;
1693 };
1694
1695 $class->foreach_volume($conf, sub {
1696 my ($ms, $mountpoint) = @_;
1697 $test_volid->($mountpoint->{volume}, $mountpoint);
1698 });
1699
1700 foreach my $snapname (keys %{$conf->{snapshots}}) {
1701 my $snap = $conf->{snapshots}->{$snapname};
1702 $class->foreach_volume($snap, sub {
1703 my ($ms, $mountpoint) = @_;
1704 $test_volid->($mountpoint->{volume}, $mountpoint);
1705 });
1706 }
1707
1708 # add 'unusedX' volumes to volhash
1709 foreach my $key (keys %$conf) {
1710 if ($key =~ m/^unused/) {
1711 $test_volid->($conf->{$key}, { type => 'volume', replicate => 1 });
1712 }
1713 }
1714
1715 return $volhash;
1716 }
1717
1718 sub get_backup_volumes {
1719 my ($class, $conf) = @_;
1720
1721 my $return_volumes = [];
1722
1723 my $test_mountpoint = sub {
1724 my ($key, $volume) = @_;
1725
1726 my ($included, $reason) = $class->mountpoint_backup_enabled($key, $volume);
1727
1728 push @$return_volumes, {
1729 key => $key,
1730 included => $included,
1731 reason => $reason,
1732 volume_config => $volume,
1733 };
1734 };
1735
1736 PVE::LXC::Config->foreach_volume($conf, $test_mountpoint);
1737
1738 return $return_volumes;
1739 }
1740
1741 1;