7 use Errno
qw(ELOOP ENOENT ENOTDIR EROFS ECONNREFUSED EEXIST);
8 use Fcntl
qw(O_RDONLY O_WRONLY O_NOFOLLOW O_DIRECTORY :mode);
11 use IO
::Poll
qw(POLLIN POLLHUP);
15 use Time
::HiRes qw
(gettimeofday
);
17 use PVE
::AccessControl
;
20 use PVE
::Exception
qw(raise_perm_exc);
21 use PVE
::GuestHelpers
qw(check_vnet_access safe_string_ne safe_num_ne safe_boolean_ne);
23 use PVE
::JSONSchema
qw(get_standard_option);
26 use PVE
::RESTEnvironment
;
39 use PVE
::Syscall
qw(:fsmount);
43 use PVE
::LXC
::Monitor
;
48 require PVE
::Network
::SDN
::Zones
;
49 require PVE
::Network
::SDN
::Vnets
;
53 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
55 my $nodename = PVE
::INotify
::nodename
();
57 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
59 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
62 my $vmlist = PVE
::Cluster
::get_vmlist
();
64 return $res if !$vmlist || !$vmlist->{ids
};
65 my $ids = $vmlist->{ids
};
67 foreach my $vmid (keys %$ids) {
68 next if !$vmid; # skip CT0
69 my $d = $ids->{$vmid};
70 next if !$d->{node
} || $d->{node
} ne $nodename;
71 next if !$d->{type
} || $d->{type
} ne 'lxc';
72 $res->{$vmid} = { type
=> 'lxc', vmid
=> $vmid };
77 # container status helpers
79 sub list_active_containers
{
81 my $filename = "/proc/net/unix";
83 # similar test is used by lcxcontainers.c: list_active_containers
86 my $fh = IO
::File-
>new ($filename, "r");
89 while (defined(my $line = <$fh>)) {
90 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
92 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
103 # warning: this is slow
107 my $active_hash = list_active_containers
();
109 return 1 if defined($active_hash->{$vmid});
114 sub get_container_disk_usage
{
115 my ($vmid, $pid) = @_;
117 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
120 my $last_proc_vmid_stat;
122 our $vmstatus_return_properties = {
123 vmid
=> get_standard_option
('pve-vmid'),
125 description
=> "LXC Container status.",
127 enum
=> ['stopped', 'running'],
130 description
=> "Maximum memory in bytes.",
136 description
=> "Maximum SWAP memory in bytes.",
142 description
=> "Root disk size in bytes.",
148 description
=> "Container name.",
153 description
=> "Uptime.",
156 renderer
=> 'duration',
159 description
=> "Maximum usable CPUs.",
164 description
=> "The current config lock, if any.",
169 description
=> "The current configured tags, if any.",
178 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc', vmid
=> int($opt_vmid) }} : config_list
();
180 my $active_hash = list_active_containers
();
182 my $cpucount = $cpuinfo->{cpus
} || 1;
184 my $cdtime = gettimeofday
;
186 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
187 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
189 my $unprivileged = {};
191 foreach my $vmid (keys %$list) {
192 my $d = $list->{$vmid};
194 eval { $d->{pid
} = int(find_lxc_pid
($vmid)) if defined($active_hash->{$vmid}); };
195 warn $@ if $@; # ignore errors (consider them stopped)
197 $d->{status
} = $active_hash->{$vmid} ?
'running' : 'stopped';
199 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
200 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
202 $unprivileged->{$vmid} = $conf->{unprivileged
};
204 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
205 $d->{name
} =~ s/[\s]//g;
207 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
208 $d->{cpus
} = $cpucount if !$d->{cpus
};
210 $d->{tags
} = $conf->{tags
} if defined($conf->{tags
});
213 my $res = get_container_disk_usage
($vmid, $d->{pid
});
214 $d->{disk
} = int($res->{used
});
215 $d->{maxdisk
} = int($res->{total
});
218 # use 4GB by default ??
219 if (my $rootfs = $conf->{rootfs
}) {
220 my $rootinfo = PVE
::LXC
::Config-
>parse_volume('rootfs', $rootfs);
221 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
223 $d->{maxdisk
} = 4*1024*1024*1024;
229 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
230 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
241 $d->{template
} = 1 if PVE
::LXC
::Config-
>is_template($conf);
242 $d->{lock} = $conf->{lock} if $conf->{lock};
245 foreach my $vmid (keys %$list) {
246 my $d = $list->{$vmid};
249 next if !$pid; # skip stopped CTs
251 my $proc_pid_stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
252 $d->{uptime
} = int(($uptime - $proc_pid_stat->{starttime
}) / $clock_ticks); # the method lxcfs uses
254 my $unpriv = $unprivileged->{$vmid};
256 my $cgroups = PVE
::LXC
::CGroup-
>new($vmid);
258 if (defined(my $mem = $cgroups->get_memory_stat())) {
259 $d->{mem
} = int($mem->{mem
});
260 $d->{swap
} = int($mem->{swap
});
266 if (defined(my $blkio = $cgroups->get_io_stats())) {
267 $d->{diskread
} = int($blkio->{diskread
});
268 $d->{diskwrite
} = int($blkio->{diskwrite
});
274 if (defined(my $cpu = $cgroups->get_cpu_stat())) {
275 # Total time (in milliseconds) used up by the cpu.
276 my $used_ms = $cpu->{utime} + $cpu->{stime
};
278 my $old = $last_proc_vmid_stat->{$vmid};
280 $last_proc_vmid_stat->{$vmid} = {
288 my $delta_ms = ($cdtime - $old->{time}) * $cpucount * 1000.0;
289 if ($delta_ms > 1000.0) {
290 my $delta_used_ms = $used_ms - $old->{used
};
291 $d->{cpu
} = (($delta_used_ms / $delta_ms) * $cpucount) / $d->{cpus
};
292 $last_proc_vmid_stat->{$vmid} = {
298 $d->{cpu
} = $old->{cpu
};
305 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
307 foreach my $dev (keys %$netdev) {
308 next if $dev !~ m/^veth([1-9]\d*)i/;
310 my $d = $list->{$vmid};
314 $d->{netout
} += $netdev->{$dev}->{receive
};
315 $d->{netin
} += $netdev->{$dev}->{transmit
};
322 sub find_lxc_console_pids
{
326 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
329 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
332 my @args = split(/\0/, $cmdline);
334 # search for lxc-console -n <vmid>
335 return if scalar(@args) != 3;
336 return if $args[1] ne '-n';
337 return if $args[2] !~ m/^\d+$/;
338 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
342 push @{$res->{$vmid}}, $pid;
354 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
356 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
358 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
365 sysopen(my $fd, "/proc/$pid", O_RDONLY
| O_DIRECTORY
)
366 or die "failed to open /proc/$pid pid fd\n";
373 # Find the pid and open:
374 my $pid = find_lxc_pid
($vmid);
375 my $fd = open_pid_fd
($pid);
378 my $pid2 = find_lxc_pid
($vmid);
380 return () if $pid != $pid2;
387 # Find the parent pid via proc and open it:
388 my $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
389 my $ppid = $stat->{ppid
} // die "failed to get parent pid\n";
391 my $fd = open_pid_fd
($ppid);
394 $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
395 my $ppid2 = $stat->{ppid
} // die "failed to get parent pid for verification\n";
397 return () if $ppid != $ppid2;
401 # Note: we cannot use Net:IP, because that only allows strict
403 sub parse_ipv4_cidr
{
404 my ($cidr, $noerr) = @_;
406 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
407 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
410 return undef if $noerr;
412 die "unable to parse ipv4 address/mask\n";
415 # With seccomp trap to userspace we now have the ability to optionally forward
416 # certain syscalls to the "host" to handle (via our pve-lxc-syscalld daemon).
418 # This means that there are cases where we need to create an extra seccomp
419 # profile for the container to load.
421 # This returns a configuration snippet added to the raw lxc config.
422 sub make_seccomp_config
{
423 my ($conf, $vmid, $conf_dir, $unprivileged, $features) = @_;
424 # User-configured profile has precedence, note that the user's entry would
425 # be written 'after' this line anyway...
426 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.seccomp.profile')) {
427 # Warn the user if this conflicts with a feature:
428 my $warn = join(', ', grep { $features->{$_} } qw(keyctl mknod));
429 warn "explicitly configured lxc.seccomp.profile overrides the following settings: $warn\n"
430 if length($warn) > 0;
434 # Privileged containers keep using the default (which is already part of
435 # the files included via lxc.include, so we don't need to write it out,
436 # that way it stays admin-configurable via /usr/share/lxc/config/... as
438 return '' if !$unprivileged;
441 keyctl
=> ['errno 38'],
443 # Disable btrfs ioctrls since they don't work particularly well in user namespaces.
444 # Particularly, without the mount option to enable rmdir removing snapshots, user
445 # namespaces can create snapshots but neither `show` or `delete` them, which is quite
446 # horrible, so for now, just disable this entirely:
448 # BTRFS_IOCTL_MAGIC 0x94, _IOC type shift is 8,
449 # so `(req & 0xFF00) == 0x9400` is a btrfs ioctl and gets an EPERM
450 ioctl => ['errno 1 [1,0x9400,SCMP_CMP_MASKED_EQ,0xff00]'],
455 # Unprivileged containers will get keyctl() disabled by default as a
456 # workaround for systemd-networkd behavior. But we have an option to
457 # explicitly enable it:
458 if ($features->{keyctl
}) {
459 delete $rules->{keyctl
};
462 # By default, unprivileged containers cannot use `mknod` at all.
463 # Since lxc 3.2, we can use seccomp's trap to userspace feature for this,
464 # but for now this is experimental, so it has to be enabled via a feature
466 # Note that we only handle block and char devices (like lxd), the rest we
467 # leave up to the kernel. We may in the future remove this if seccomp gets
468 # a way to tell the kernel to "continue" a syscall.
469 if ($features->{mknod
}) {
470 my ($ok, $kernel) = PVE
::ProcFSTools
::check_kernel_release
(5, 3);
472 die "'mknod' feature requested, but kernel too old (found $kernel, required >= 5.3)\n";
475 $raw_conf .= "lxc.seccomp.notify.proxy = unix:/run/pve/lxc-syscalld.sock\n";
476 $raw_conf .= "lxc.seccomp.notify.cookie = $vmid\n";
479 # condition: (mode & S_IFMT) == S_IFCHR
480 'notify [1,8192,SCMP_CMP_MASKED_EQ,61440]',
481 # condition: (mode & S_IFMT) == S_IFBLK
482 'notify [1,24576,SCMP_CMP_MASKED_EQ,61440]',
484 $rules->{mknodat
} = [
485 # condition: (mode & S_IFMT) == S_IFCHR
486 'notify [2,8192,SCMP_CMP_MASKED_EQ,61440]',
487 # condition: (mode & S_IFMT) == S_IFBLK
488 'notify [2,24576,SCMP_CMP_MASKED_EQ,61440]',
492 # Now build the custom seccomp rule text...
493 my $extra_rules = join("\n", map {
495 map { "$syscall $_" } $rules->{$syscall}->@*
496 } sort keys %$rules) . "\n";
498 return $raw_conf if $extra_rules eq "\n";
500 # We still have the "most common" config readily available, so don't write
502 if ($raw_conf eq '' && $extra_rules eq "keyctl errno 38\n") {
503 # we have no extra $raw_conf and use the same we had in pve 6.1:
504 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
507 # Write the rule file to the container's config path:
508 my $rule_file = "$conf_dir/rules.seccomp";
509 my $rule_data = file_get_contents
("$LXC_CONFIG_PATH/common.seccomp")
511 file_set_contents
($rule_file, $rule_data);
512 $raw_conf .= "lxc.seccomp.profile = $rule_file\n";
517 # Since lxc-3.0.2 we can have lxc generate a profile for the container
518 # automatically. The default should be equivalent to the old
519 # `lxc-container-default-cgns` profile.
521 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
522 # additional lines into the profile. We can use that to allow mounting specific
524 sub make_apparmor_config
{
525 my ($conf, $unprivileged, $features) = @_;
527 # user-configured profile has precedence, but first we go through our own
528 # code to figure out whether we should warn the user:
530 my $raw = "lxc.apparmor.profile = generated\n";
533 if ($features->{fuse
}) {
534 # For the informational warning:
535 push @profile_uses, 'features:fuse';
538 # There's lxc.apparmor.allow_nesting now, which will add the necessary
539 # apparmor lines, create an apparmor namespace for the container, but also
540 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
541 # lxcfs mounted over them, because that would prevent the container from
542 # mounting new instances of them for nested containers.
543 if ($features->{nesting
}) {
544 push @profile_uses, 'features:nesting';
545 $raw .= "lxc.apparmor.allow_nesting = 1\n"
547 # In the default profile in /etc/apparmor.d we patch this in because
548 # otherwise a container can for example run `chown` on /sys, breaking
549 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
550 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
551 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
552 # Preferably we could use the 'remount' flag but this does not sit well
553 # with apparmor_parser currently:
554 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
557 if (my $mount = $features->{mount
}) {
558 push @profile_uses, 'features:mount';
559 foreach my $fs (PVE
::Tools
::split_list
($mount)) {
560 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
566 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.apparmor.profile')) {
567 if (length(my $used = join(', ', @profile_uses))) {
568 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
576 sub update_lxc_config
{
577 my ($vmid, $conf) = @_;
579 my $dir = "/var/lib/lxc/$vmid";
581 if ($conf->{template
}) {
583 unlink "$dir/config";
588 my ($lxc_major, $lxc_minor) = get_lxc_version
();
592 if ($lxc_major >= 4) {
593 # Explicitly don't use relative directories, which is the default, but
594 # note that we do this mostly because they are only applied for *some*
595 # cgroups. Our pve-container@.service now starts lxc-start with `-F`,
596 # so we also don't need to worry about the new monitor cgroup to
598 $raw .= "lxc.cgroup.relative = 0\n";
600 # To make things easier, let's keep our previous cgroup layout and
601 # simply move the monitor outside:
602 $raw .= "lxc.cgroup.dir.monitor = lxc.monitor/$vmid\n";
603 # cgroup namespace separation for stronger limits:
604 $raw .= "lxc.cgroup.dir.container = lxc/$vmid\n";
605 $raw .= "lxc.cgroup.dir.container.inner = ns\n";
608 die "missing 'arch' - internal error" if !$conf->{arch
};
609 $raw .= "lxc.arch = $conf->{arch}\n";
611 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
612 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
614 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
616 File
::Path
::mkpath
($dir);
618 my $cfgpath = '/usr/share/lxc/config';
619 my $inc = "$cfgpath/$ostype.common.conf";
620 $inc ="$cfgpath/common.conf" if !-f
$inc;
621 $raw .= "lxc.include = $inc\n";
623 $inc = "$cfgpath/$ostype.userns.conf";
624 $inc = "$cfgpath/userns.conf" if !-f
$inc;
625 $raw .= "lxc.include = $inc\n";
628 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
630 $raw .= make_seccomp_config
($conf, $vmid, $dir, $unprivileged, $features);
631 $raw .= make_apparmor_config
($conf, $unprivileged, $features);
632 if ($features->{fuse
}) {
633 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
634 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
637 if ($unprivileged && !$features->{force_rw_sys
}) {
638 # unpriv. CT default to sys:rw, but that doesn't always plays well with
639 # systemd, e.g., systemd-networkd https://systemd.io/CONTAINER_INTERFACE/
640 $raw .= "lxc.mount.auto = sys:mixed\n";
643 PVE
::LXC
::Config-
>foreach_passthrough_device($conf, sub {
644 my ($key, $device) = @_;
646 die "Path is not defined for passthrough device $key"
647 unless (defined($device->{path
}));
649 my $absolute_path = $device->{path
};
650 my ($mode, $rdev) = (stat($absolute_path))[2, 6];
652 die "Device $absolute_path does not exist\n" if $! == ENOENT
;
654 die "Error accessing device $absolute_path\n"
655 if (!defined($mode) || !defined($rdev));
657 die "$absolute_path is not a device\n"
658 if (!S_ISBLK
($mode) && !S_ISCHR
($mode));
660 my $major = PVE
::Tools
::dev_t_major
($rdev);
661 my $minor = PVE
::Tools
::dev_t_minor
($rdev);
662 my $device_type_char = S_ISBLK
($mode) ?
'b' : 'c';
663 $raw .= "lxc.cgroup2.devices.allow = $device_type_char $major:$minor rw\n";
666 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
667 # cannot be exposed to the container with r/w access (cgroup perms).
668 # When this is enabled mounts will still remain in the monitor's namespace
669 # after the container unmounted them and thus will not detach from their
670 # files while the container is running!
671 $raw .= "lxc.monitor.unshare = 1\n";
673 my ($cgv1, $cgv2) = PVE
::CGroup
::get_cgroup_controllers
();
675 # Should we read them from /etc/subuid?
676 if ($unprivileged && !$custom_idmap) {
677 $raw .= "lxc.idmap = u 0 100000 65536\n";
678 $raw .= "lxc.idmap = g 0 100000 65536\n";
681 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
682 $raw .= "lxc.console.path = none\n";
683 if ($cgv1->{devices
}) {
684 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
685 } elsif (defined($cgv2)) {
686 $raw .= "lxc.cgroup2.devices.deny = c 5:1 rwm\n";
690 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
691 $raw .= "lxc.tty.max = $ttycount\n";
693 # some init scripts expect a linux terminal (turnkey).
694 $raw .= "lxc.environment = TERM=linux\n";
696 my $utsname = $conf->{hostname
} || "CT$vmid";
697 $raw .= "lxc.uts.name = $utsname\n";
699 if ($cgv1->{memory
}) {
700 my $memory = $conf->{memory
} || 512;
701 my $swap = $conf->{swap
} // 0;
703 my $lxcmem = int($memory*1024*1024);
704 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
706 my $lxcswap = int(($memory + $swap)*1024*1024);
707 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
708 } elsif ($cgv2->{memory
}) {
709 my $memory = $conf->{memory
} || 512;
710 my $swap = $conf->{swap
} // 0;
712 # cgroup memory usage is limited by the hard 'max' limit (OOM-killer enforced) and the soft
713 # 'high' limit (cgroup processes get throttled and put under heavy reclaim pressure).
714 my ($lxc_mem_max, $lxc_mem_high) = PVE
::LXC
::Config
::calculate_memory_constraints
($memory);
715 $raw .= "lxc.cgroup2.memory.max = $lxc_mem_max\n";
716 $raw .= "lxc.cgroup2.memory.high = $lxc_mem_high\n";
718 my $lxcswap = int($swap*1024*1024);
719 $raw .= "lxc.cgroup2.memory.swap.max = $lxcswap\n";
723 if (my $cpulimit = $conf->{cpulimit
}) {
724 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
725 my $value = int(100000*$cpulimit);
726 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
729 my $shares = PVE
::CGroup
::clamp_cpu_shares
($conf->{cpuunits
});
730 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
731 } elsif ($cgv2->{cpu
}) {
733 if (my $cpulimit = $conf->{cpulimit
}) {
734 my $value = int(100000*$cpulimit);
735 $raw .= "lxc.cgroup2.cpu.max = $value 100000\n";
738 if (defined(my $shares = $conf->{cpuunits
})) {
739 $shares = PVE
::CGroup
::clamp_cpu_shares
($shares);
740 $raw .= "lxc.cgroup2.cpu.weight = $shares\n";
744 die "missing 'rootfs' configuration\n"
745 if !defined($conf->{rootfs
});
747 my $mountpoint = PVE
::LXC
::Config-
>parse_volume('rootfs', $conf->{rootfs
});
749 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
751 foreach my $k (sort keys %$conf) {
752 next if $k !~ m/^net(\d+)$/;
754 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
755 $raw .= "lxc.net.$ind.type = veth\n";
756 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
757 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
758 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
760 my $bridge_mtu = PVE
::Network
::read_bridge_mtu
($d->{bridge
});
761 my $mtu = $d->{mtu
} || $bridge_mtu;
763 # Keep container from starting with invalid mtu configuration
764 die "$k: MTU size '$mtu' is bigger than bridge MTU '$bridge_mtu'\n"
765 if ($mtu > $bridge_mtu);
767 $raw .= "lxc.net.$ind.mtu = $mtu\n";
769 # Starting with lxc 4.0, we do not patch lxc to execute our up-scripts.
770 if ($lxc_major >= 4) {
771 $raw .= "lxc.net.$ind.script.up = /usr/share/lxc/lxcnetaddbr\n";
776 if (my $lxcconf = $conf->{lxc
}) {
777 foreach my $entry (@$lxcconf) {
778 my ($k, $v) = @$entry;
779 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus' || $k eq 'lxc.cgroup2.cpuset.cpus';
785 my ($cpuset_cgroup, $cpuset_version) = eval { PVE
::CGroup
::cpuset_controller_path
() };
786 if (defined($cpuset_cgroup)) {
787 $cpuset = eval { PVE
::CpuSet-
>new_from_path("$cpuset_cgroup/lxc", 1) }
788 || PVE
::CpuSet-
>new_from_path($cpuset_cgroup, 1);
790 my $cores = $conf->{cores
};
791 if (!$had_cpuset && $cores && $cpuset) {
792 my @members = $cpuset->members();
793 while (scalar(@members) > $cores) {
794 my $randidx = int(rand(scalar(@members)));
795 $cpuset->delete($members[$randidx]);
796 splice(@members, $randidx, 1); # keep track of the changes
798 my $ver = $cpuset_version == 1 ?
'' : '2';
799 $raw .= "lxc.cgroup$ver.cpuset.cpus = ".$cpuset->short_string()."\n";
802 File
::Path
::mkpath
("$dir/rootfs");
804 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
807 # verify and cleanup nameserver list (replace \0 with ' ')
808 sub verify_nameserver_list
{
809 my ($nameserver_list) = @_;
812 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
813 PVE
::LXC
::Config
::verify_ip_with_ll_iface
($server);
817 return join(' ', @list);
820 sub verify_searchdomain_list
{
821 my ($searchdomain_list) = @_;
824 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
825 # todo: should we add checks for valid dns domains?
829 return join(' ', @list);
832 sub get_console_command
{
833 my ($vmid, $conf, $escapechar) = @_;
835 # '-1' as $escapechar disables keyboard escape sequence
836 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
838 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
841 if ($cmode eq 'console') {
842 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
843 push @$cmd, '-e', $escapechar if $escapechar;
844 } elsif ($cmode eq 'tty') {
845 push @$cmd, 'lxc-console', '-n', $vmid;
846 push @$cmd, '-e', $escapechar if $escapechar;
847 } elsif ($cmode eq 'shell') {
848 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
850 die "internal error";
856 sub get_primary_ips
{
859 # return data from net0
861 return undef if !defined($conf->{net0
});
862 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
864 my $ipv4 = $net->{ip
};
866 if ($ipv4 =~ /^(dhcp|manual)$/) {
872 my $ipv6 = $net->{ip6
};
874 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
881 return ($ipv4, $ipv6);
884 sub delete_mountpoint_volume
{
885 my ($storage_cfg, $vmid, $volume) = @_;
887 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
889 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
891 if ($vmid == $owner) {
892 PVE
::Storage
::vdisk_free
($storage_cfg, $volume);
894 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
898 sub destroy_lxc_container
{
899 my ($storage_cfg, $vmid, $conf, $replacement_conf, $purge_unreferenced) = @_;
902 my $remove_volume = sub {
903 my ($ms, $mountpoint) = @_;
905 my $volume = $mountpoint->{volume
};
907 return if $volids->{$volume};
908 $volids->{$volume} = 1;
910 delete_mountpoint_volume
($storage_cfg, $vmid, $volume);
912 PVE
::LXC
::Config-
>foreach_volume_full($conf, {include_unused
=> 1}, $remove_volume);
914 PVE
::LXC
::Config-
>foreach_volume_full($conf->{pending
}, {include_unused
=> 1}, $remove_volume);
916 if ($purge_unreferenced) { # also remove unreferenced disk
917 my $vmdisks = PVE
::Storage
::vdisk_list
($storage_cfg, undef, $vmid, undef, 'rootdir');
918 PVE
::Storage
::foreach_volid
($vmdisks, sub {
919 my ($volid, $sid, $volname, $d) = @_;
920 eval { PVE
::Storage
::vdisk_free
($storage_cfg, $volid) };
925 delete_ifaces_ipams_ips
($conf, $vmid);
927 rmdir "/var/lib/lxc/$vmid/rootfs";
928 unlink "/var/lib/lxc/$vmid/config";
929 rmdir "/var/lib/lxc/$vmid";
930 if (defined $replacement_conf) {
931 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
933 PVE
::LXC
::Config-
>destroy_config($vmid);
937 sub vm_stop_cleanup
{
938 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
940 return if $keepActive;
943 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
944 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
946 warn $@ if $@; # avoid errors - just warn
949 sub net_tap_plug
: prototype($$) {
950 my ($iface, $net) = @_;
952 if (defined($net->{link_down
})) {
953 PVE
::Tools
::run_command
(['/sbin/ip', 'link', 'set', 'dev', $iface, 'down']);
954 # Don't add disconnected interfaces to the bridge, otherwise e.g. applying any network
955 # change (e.g. `ifreload -a`) could (re-)activate it unintentionally.
959 my ($bridge, $tag, $firewall, $trunks, $rate, $hwaddr) =
960 $net->@{'bridge', 'tag', 'firewall', 'trunks', 'rate', 'hwaddr'};
963 PVE
::Network
::SDN
::Zones
::tap_plug
($iface, $bridge, $tag, $firewall, $trunks, $rate);
964 PVE
::Network
::SDN
::Zones
::add_bridge_fdb
($iface, $hwaddr, $bridge);
966 PVE
::Network
::tap_plug
($iface, $bridge, $tag, $firewall, $trunks, $rate, { mac
=> $hwaddr });
969 PVE
::Tools
::run_command
(['/sbin/ip', 'link', 'set', 'dev', $iface, 'up']);
973 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
975 if ($newnet->{type
} ne 'veth') {
976 # for when there are physical interfaces
977 die "cannot update interface of type $newnet->{type}";
980 my $veth = "veth${vmid}i${netid}";
981 my $eth = $newnet->{name
};
983 if (my $oldnetcfg = $conf->{$opt}) {
984 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
986 if (safe_string_ne
($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
987 safe_string_ne
($oldnet->{name
}, $newnet->{name
})) {
989 PVE
::Network
::veth_delete
($veth);
991 if ($have_sdn && safe_string_ne
($oldnet->{hwaddr
}, $newnet->{hwaddr
})) {
992 eval { PVE
::Network
::SDN
::Vnets
::del_ips_from_mac
($oldnet->{bridge
}, $oldnet->{hwaddr
}, $conf->{hostname
}) };
995 PVE
::Network
::SDN
::Vnets
::add_next_free_cidr
($newnet->{bridge
}, $conf->{hostname
}, $newnet->{hwaddr
}, $vmid, undef, 1);
996 PVE
::Network
::SDN
::Vnets
::add_dhcp_mapping
($newnet->{bridge
}, $newnet->{hwaddr
});
999 delete $conf->{$opt};
1000 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1002 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
1005 my $bridge_changed = safe_string_ne
($oldnet->{bridge
}, $newnet->{bridge
});
1007 if ($bridge_changed ||
1008 safe_num_ne
($oldnet->{tag
}, $newnet->{tag
}) ||
1009 safe_num_ne
($oldnet->{firewall
}, $newnet->{firewall
}) ||
1010 safe_boolean_ne
($oldnet->{link_down
}, $newnet->{link_down
})
1012 if ($oldnet->{bridge
}) {
1013 my $oldbridge = $oldnet->{bridge
};
1015 PVE
::Network
::tap_unplug
($veth);
1016 foreach (qw(bridge tag firewall)) {
1017 delete $oldnet->{$_};
1019 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
1020 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1022 if ($have_sdn && $bridge_changed) {
1023 eval { PVE
::Network
::SDN
::Vnets
::del_ips_from_mac
($oldbridge, $oldnet->{hwaddr
}, $conf->{hostname
}) };
1028 if ($have_sdn && $bridge_changed) {
1029 PVE
::Network
::SDN
::Vnets
::add_next_free_cidr
($newnet->{bridge
}, $conf->{hostname
}, $newnet->{hwaddr
}, $vmid, undef, 1);
1031 PVE
::LXC
::net_tap_plug
($veth, $newnet);
1033 # This includes the rate:
1034 foreach (qw(bridge tag firewall rate link_down)) {
1035 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
1037 } elsif (safe_string_ne
($oldnet->{rate
}, $newnet->{rate
})) {
1038 # Rate can be applied on its own but any change above needs to
1039 # include the rate in tap_plug since OVS resets everything.
1040 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
1041 $oldnet->{rate
} = $newnet->{rate
}
1043 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
1044 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1047 PVE
::Network
::SDN
::Vnets
::add_next_free_cidr
($newnet->{bridge
}, $conf->{hostname
}, $newnet->{hwaddr
}, $vmid, undef, 1);
1048 PVE
::Network
::SDN
::Vnets
::add_dhcp_mapping
($newnet->{bridge
}, $newnet->{hwaddr
});
1050 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
1053 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
1057 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
1059 my $veth = "veth${vmid}i${netid}";
1060 my $vethpeer = $veth . "p";
1061 my $eth = $newnet->{name
};
1064 PVE
::Network
::SDN
::Zones
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
1066 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
1069 PVE
::LXC
::net_tap_plug
($veth, $newnet);
1071 # attach peer in container
1072 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
1073 PVE
::Tools
::run_command
($cmd);
1075 # link up peer in container
1076 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
1077 PVE
::Tools
::run_command
($cmd);
1079 my $done = { type
=> 'veth' };
1080 foreach (qw(bridge tag firewall hwaddr name link_down)) {
1081 $done->{$_} = $newnet->{$_} if $newnet->{$_};
1083 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
1085 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1088 sub get_interfaces
{
1091 my $pid = eval { find_lxc_pid
($vmid); };
1095 # enters the network namespace of the container and executes 'ip a'
1096 run_command
(['nsenter', '-t', $pid, '--net', '--', 'ip', '--json', 'a'],
1097 outfunc
=> sub { $output .= shift; });
1099 my $config = JSON
::decode_json
($output);
1102 for my $interface ($config->@*) {
1103 my $obj = { name
=> $interface->{ifname
} };
1104 for my $ip ($interface->{addr_info
}->@*) {
1105 $obj->{$ip->{family
}} = $ip->{local} . "/" . $ip->{prefixlen
};
1107 $obj->{hwaddr
} = $interface->{address
};
1114 sub update_ipconfig
{
1115 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
1117 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
1119 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
1123 my $cmdargs = shift;
1124 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
1126 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
1128 my $change_ip_config = sub {
1129 my ($ipversion) = @_;
1131 my $family_opt = "-$ipversion";
1132 my $suffix = $ipversion == 4 ?
'' : $ipversion;
1133 my $gw= "gw$suffix";
1134 my $ip= "ip$suffix";
1136 my $newip = $newnet->{$ip};
1137 my $newgw = $newnet->{$gw};
1138 my $oldip = $optdata->{$ip};
1139 my $oldgw = $optdata->{$gw};
1141 my $change_ip = safe_string_ne
($oldip, $newip);
1142 my $change_gw = safe_string_ne
($oldgw, $newgw);
1144 return if !$change_ip && !$change_gw;
1146 # step 1: add new IP, if this fails we cancel
1147 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
1148 if ($change_ip && $is_real_ip) {
1149 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
1156 # step 2: replace gateway
1157 # If this fails we delete the added IP and cancel.
1158 # If it succeeds we save the config and delete the old IP, ignoring
1159 # errors. The config is then saved.
1160 # Note: 'ip route replace' can add
1164 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
1165 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1167 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1171 # the route was not replaced, the old IP is still available
1172 # rollback (delete new IP) and cancel
1174 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
1175 warn $@ if $@; # no need to die here
1180 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
1181 # if the route was not deleted, the guest might have deleted it manually
1185 if ($oldgw && $oldip && !PVE
::Network
::is_ip_in_cidr
($oldgw, $oldip)) {
1186 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
1187 # warn if the route was deleted manually
1192 # from this point on we save the configuration
1193 # step 3: delete old IP ignoring errors
1194 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
1195 # We need to enable promote_secondaries, otherwise our newly added
1196 # address will be removed along with the old one.
1199 if ($ipversion == 4) {
1200 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
1201 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1202 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1204 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1206 warn $@ if $@; # no need to die here
1208 if ($ipversion == 4) {
1209 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1213 foreach my $property ($ip, $gw) {
1214 if ($newnet->{$property}) {
1215 $optdata->{$property} = $newnet->{$property};
1217 delete $optdata->{$property};
1220 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
1221 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1222 $lxc_setup->setup_network($conf);
1225 &$change_ip_config(4);
1226 &$change_ip_config(6);
1230 my $open_namespace = sub {
1231 my ($vmid, $pid, $kind) = @_;
1232 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1233 or die "failed to open $kind namespace of container $vmid: $!\n";
1237 my $enter_namespace = sub {
1238 my ($vmid, $pid, $kind, $type) = @_;
1239 my $fd = $open_namespace->($vmid, $pid, $kind);
1240 PVE
::Tools
::setns
(fileno($fd), $type)
1241 or die "failed to enter $kind namespace of container $vmid: $!\n";
1245 my $get_container_namespace = sub {
1246 my ($vmid, $pid, $kind) = @_;
1249 if (!defined($pid)) {
1250 # Pin the pid while we're grabbing its stuff from /proc
1251 ($pid, $pidfd) = open_lxc_pid
($vmid)
1252 or die "failed to open pidfd of container $vmid\'s init process\n";
1255 return $open_namespace->($vmid, $pid, $kind);
1258 my $do_syncfs = sub {
1259 my ($vmid, $pid, $socket) = @_;
1261 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
1263 # Tell the parent process to start reading our /proc/mounts
1264 print {$socket} "go\n";
1267 # Receive /proc/self/mounts
1268 my $mountdata = do { local $/ = undef; <$socket> };
1284 # Now sync all mountpoints...
1285 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
1286 foreach my $mp (@$mounts) {
1287 my ($what, $dir, $fs) = @$mp;
1288 next if $nosyncfs{$fs};
1289 eval { PVE
::Tools
::sync_mountpoint
($dir); };
1294 sub sync_container_namespace
{
1296 my $pid = find_lxc_pid
($vmid);
1298 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1299 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
1300 or die "failed to create socketpair: $!\n";
1303 die "fork failed: $!\n" if !defined($child);
1308 &$do_syncfs($vmid, $pid, $cfd);
1318 die "failed to enter container namespace\n" if $go ne "go\n";
1320 open my $mounts, '<', "/proc/$child/mounts"
1321 or die "failed to open container's /proc/mounts: $!\n";
1322 my $mountdata = do { local $/ = undef; <$mounts> };
1324 print {$pfd} $mountdata;
1327 while (waitpid($child, 0) != $child) {}
1328 die "failed to sync container namespace\n" if $? != 0;
1331 sub template_create
{
1332 my ($vmid, $conf) = @_;
1334 my $storecfg = PVE
::Storage
::config
();
1336 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1337 my ($ms, $mountpoint) = @_;
1339 my $volid = $mountpoint->{volume
};
1341 die "Template feature is not available for '$volid'\n"
1342 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1345 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1346 my ($ms, $mountpoint) = @_;
1348 my $volid = $mountpoint->{volume
};
1350 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
1352 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
1353 $mountpoint->{volume
} = $template_volid;
1354 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1357 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1360 sub check_ct_modify_config_perm
{
1361 my ($rpcenv, $authuser, $vmid, $pool, $oldconf, $newconf, $delete, $unprivileged) = @_;
1363 return 1 if $authuser eq 'root@pam';
1364 my $storage_cfg = PVE
::Storage
::config
();
1367 my ($opt, $delete) = @_;
1368 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1369 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1370 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1371 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1373 my $data = PVE
::LXC
::Config-
>parse_volume($opt, $newconf->{$opt});
1374 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
1375 if $data->{type
} ne 'volume';
1376 my $volid = $data->{volume
};
1377 if ($volid =~ $NEW_DISK_RE) {
1379 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
1381 PVE
::Storage
::check_volume_access
(
1390 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1391 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1392 } elsif ($opt =~ m/^net\d+$/) {
1393 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1394 check_bridge_access
($rpcenv, $authuser, $oldconf->{$opt}) if $oldconf->{$opt};
1395 check_bridge_access
($rpcenv, $authuser, $newconf->{$opt}) if $newconf->{$opt};
1396 } elsif ($opt =~ m/^dev\d+$/) {
1397 raise_perm_exc
("configuring device passthrough is only allowed for root\@pam");
1398 } elsif ($opt eq 'nameserver' || $opt eq 'searchdomain' || $opt eq 'hostname') {
1399 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1400 } elsif ($opt eq 'features') {
1401 raise_perm_exc
("changing feature flags for privileged container is only allowed for root\@pam")
1404 my $nesting_changed = 0;
1405 my $other_changed = 0;
1407 my $features = PVE
::LXC
::Config-
>parse_features($newconf->{$opt});
1408 if (defined($oldconf) && $oldconf->{$opt}) {
1409 # existing container with features
1410 my $old_features = PVE
::LXC
::Config-
>parse_features($oldconf->{$opt});
1411 for my $feature ((keys %$old_features, keys %$features)) {
1412 my $old = $old_features->{$feature} // '';
1413 my $new = $features->{$feature} // '';
1415 if ($feature eq 'nesting') {
1416 $nesting_changed = 1;
1425 # new container or no features defined
1426 if (scalar(keys %$features) == 1 && $features->{nesting
}) {
1427 $nesting_changed = 1;
1428 } elsif (scalar(keys %$features) > 0) {
1433 my $features = PVE
::LXC
::Config-
>parse_features($oldconf->{$opt});
1434 if (scalar(keys %$features) == 1 && $features->{nesting
}) {
1435 $nesting_changed = 1;
1436 } elsif (scalar(keys %$features) > 0) {
1440 raise_perm_exc
("changing feature flags (except nesting) is only allowed for root\@pam")
1442 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Allocate'])
1443 if $nesting_changed;
1444 } elsif ($opt eq 'hookscript') {
1445 # For now this is restricted to root@pam
1446 raise_perm_exc
("changing the hookscript is only allowed for root\@pam");
1447 } elsif ($opt eq 'tags') {
1448 my $old = $oldconf->{$opt};
1449 my $new = $delete ?
'' : $newconf->{$opt};
1450 PVE
::GuestHelpers
::assert_tag_permissions
($vmid, $old, $new, $rpcenv, $authuser);
1452 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1456 foreach my $opt (keys %$newconf) {
1459 foreach my $opt (@$delete) {
1466 sub check_bridge_access
{
1467 my ($rpcenv, $authuser, $raw) = @_;
1469 return 1 if $authuser eq 'root@pam';
1471 my $net = PVE
::LXC
::Config-
>parse_lxc_network($raw);
1472 my ($bridge, $tag, $trunks) = $net->@{'bridge', 'tag', 'trunks'};
1473 check_vnet_access
($rpcenv, $authuser, $bridge, $tag, $trunks);
1479 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1481 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1482 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1486 PVE
::LXC
::Config-
>foreach_volume_full($conf, {'reverse' => 1}, sub {
1487 my ($ms, $mountpoint) = @_;
1489 my $volid = $mountpoint->{volume
};
1490 my $mount = $mountpoint->{mp
};
1492 return if !$volid || !$mount;
1494 my $mount_path = "$rootdir/$mount";
1495 $mount_path =~ s!/+!/!g;
1497 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1500 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
1512 return $res; # tell caller if (some) umounts failed for the noerr case
1516 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1518 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1519 File
::Path
::make_path
($rootdir);
1521 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1522 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
1524 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1527 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1528 my ($ms, $mountpoint) = @_;
1530 $mountpoint->{ro
} = 0 if $ignore_ro;
1532 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1536 warn "mounting container failed\n";
1537 umount_all
($vmid, $storage_cfg, $conf, 1);
1545 sub mountpoint_mount_path
{
1546 my ($mountpoint, $storage_cfg, $snapname) = @_;
1548 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1556 if ($line =~ m
@^(/dev/loop\d
+):@) {
1560 my $cmd = ['losetup', '--associated', $path];
1561 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1565 # Run a function with a file attached to a loop device.
1566 # The loop device is always detached afterwards (or set to autoclear).
1567 # Returns the loop device.
1568 sub run_with_loopdev
{
1569 my ($func, $file, $readonly) = @_;
1570 my $device = query_loopdev
($file);
1571 # Try to reuse an existing device
1573 # We assume that whoever setup the loop device is responsible for
1581 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1591 push @$losetup_cmd, '-r' if $readonly;
1592 PVE
::Tools
::run_command
($losetup_cmd, outfunc
=> $parser);
1593 die "failed to setup loop device for $file\n" if !$device;
1594 eval { &$func($device); };
1596 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1601 # In scalar mode: returns a file handle to the deepest directory node.
1602 # In list context: returns a list of:
1603 # * the deepest directory node
1604 # * the 2nd deepest directory (parent of the above)
1605 # * directory name of the last directory
1606 # So that the path $2/$3 should lead to $1 afterwards.
1607 sub walk_tree_nofollow
($$$;$$) {
1608 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1610 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1611 or die "failed to open start directory $start: $!\n";
1613 return walk_tree_nofollow_fd
($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1617 sub walk_tree_nofollow_fd
($$$$;$$) {
1618 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1620 # splitdir() returns '' for empty components including the leading /
1621 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1624 my $dir = $start_dirname;
1625 my $last_component = undef;
1627 foreach my $component (@comps) {
1628 $dir .= "/$component";
1629 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1632 # failed, check for symlinks and try to create the path
1633 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1634 die "cannot open directory $dir: $!\n" if !$mkdir;
1636 # We don't check for errors on mkdirat() here and just try to
1637 # openat() again, since at least one error (EEXIST) is an
1638 # expected possibility if multiple containers start
1639 # simultaneously. If someone else injects a symlink now then
1640 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1641 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1643 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1644 die "failed to create path: $dir: $!\n" if !$next;
1646 PVE
::Tools
::fchownat
(fileno($next), '', $rootuid, $rootgid, PVE
::Tools
::AT_EMPTY_PATH
)
1647 if defined($rootuid) && defined($rootgid);
1650 close $second if defined($last_component) && $second != $start_fd;
1651 $last_component = $component;
1656 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1657 close $second if defined($last_component) && $second != $start_fd;
1661 # To guard against symlink attack races against other currently running
1662 # containers with shared recursive bind mount hierarchies we prepare a
1663 # directory handle for the directory we're mounting over to verify the
1664 # mountpoint afterwards.
1665 sub __bindmount_prepare
{
1666 my ($hostroot, $dir) = @_;
1667 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1671 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1672 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1673 # we intended to bind mount.
1674 sub __bindmount_verify
{
1675 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1678 # Open the mount point path coming from the parent directory since the
1679 # filehandle we would have gotten as first result of walk_tree_nofollow
1680 # earlier is still a handle to the underlying directory instead of the
1682 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1683 die "failed to open mount point: $!\n" if !$destdh;
1686 # no separate function because 99% of the time it's the wrong thing to use.
1687 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1688 die "failed to mark bind mount read only\n";
1690 die "read-only check failed: $!\n" if $! != EROFS
;
1693 # For the rootfs we don't have a parentfd so we open the path directly.
1694 # Note that this means bindmounting any prefix of the host's
1695 # /var/lib/lxc/$vmid path into another container is considered a grave
1697 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1698 die "failed to open mount point: $!\n" if !$destdh;
1701 my ($srcdev, $srcinode) = stat($srcdh);
1702 my ($dstdev, $dstinode) = stat($destdh);
1706 return ($srcdev == $dstdev && $srcinode == $dstinode);
1709 # Perform the actual bind mounting:
1710 sub __bindmount_do
{
1711 my ($dir, $dest, $ro, @extra_opts) = @_;
1712 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1714 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1716 warn "bindmount error\n";
1717 # don't leave writable bind-mounts behind...
1718 PVE
::Tools
::run_command
(['umount', $dest]);
1725 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1727 my $srcdh = __bindmount_prepare
('/', $dir);
1729 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1731 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1732 PVE
::Tools
::run_command
(['umount', $dest]);
1733 die "detected mount path change at: $dir\n";
1737 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1738 # from $rootdir and $mount and walk the path from $rootdir to the final
1739 # directory to check for symlinks.
1740 sub __mount_prepare_rootdir
{
1741 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1742 $rootdir =~ s!/+!/!g;
1743 $rootdir =~ s!/+$!!;
1744 my $mount_path = "$rootdir/$mount";
1745 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1, $rootuid, $rootgid);
1746 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1749 # use $rootdir = undef to just return the corresponding mount path
1750 sub mountpoint_mount
{
1751 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1752 return __mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1755 sub mountpoint_stage
{
1756 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1757 my ($path, $loop, $dev) =
1758 __mountpoint_mount
($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1760 if (!defined($path)) {
1761 die "failed to mount subvolume: $!\n";
1764 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1765 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1768 my $fd = PVE
::Tools
::open_tree
(&AT_FDCWD
, $stage_dir, &OPEN_TREE_CLOEXEC
| &OPEN_TREE_CLONE
)
1769 or die "open_tree() on mount point failed: $!\n";
1771 return wantarray ?
($path, $loop, $dev, $fd) : $fd;
1774 sub mountpoint_insert_staged
{
1775 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1777 if (!defined($rootdir_fd)) {
1778 sysopen($rootdir_fd, '.', O_PATH
| O_DIRECTORY
)
1779 or die "failed to open '.': $!\n";
1782 my $dest_fd = walk_tree_nofollow_fd
('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1784 PVE
::Tools
::move_mount
(
1789 &MOVE_MOUNT_F_EMPTY_PATH
| &MOVE_MOUNT_T_EMPTY_PATH
,
1790 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1793 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1794 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1795 sub __mountpoint_mount
{
1796 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1798 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1799 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1800 # which we use in __bindmount_verify()!
1801 my $mount = $stage_mount ?
'/': $mountpoint->{mp
};
1803 my $volid = $mountpoint->{volume
};
1804 my $type = $mountpoint->{type
};
1805 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1808 return if !$volid || !$mount;
1813 my ($mpfd, $parentfd, $last_dir);
1815 if (defined($rootdir)) {
1816 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1817 __mount_prepare_rootdir
($rootdir, $mount, $rootuid, $rootgid);
1820 if (defined($stage_mount)) {
1821 $mount_path = $rootdir;
1824 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1826 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1830 if (my $mountopts = $mountpoint->{mountoptions
}) {
1831 my @opts = split(/;/, $mountpoint->{mountoptions
});
1832 push @$optlist, grep { PVE
::LXC
::Config
::is_valid_mount_option
($_) } @opts;
1835 my $acl = $mountpoint->{acl
};
1836 if (defined($acl)) {
1837 push @$optlist, ($acl ?
'acl' : 'noacl');
1840 my $optstring = join(',', @$optlist);
1841 my $readonly = $mountpoint->{ro
};
1844 @extra_opts = ('-o', $optstring) if $optstring;
1848 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1850 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid, $snapname);
1852 $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname) if !defined($path);
1854 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1855 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1857 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1859 if ($format eq 'subvol') {
1861 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1862 if (defined($snapname)) {
1863 $name .= "\@$snapname";
1864 if ($scfg->{type
} eq 'zfspool') {
1865 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', "$scfg->{pool}/$name", $mount_path]);
1867 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1870 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1871 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1872 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1874 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1875 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1878 return wantarray ?
($path, 0, undef) : $path;
1879 } elsif ($format eq 'raw' || $format eq 'iso') {
1880 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1881 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1882 # Our autodev hook expects the /dev/dm-* device currently
1883 # and will create the /dev/mapper symlink accordingly
1884 $path = Cwd
::realpath
($path);
1885 die "failed to get device path\n" if !$path;
1886 ($path) = ($path =~ /^(.*)$/s); #untaint
1890 if ($format eq 'iso') {
1891 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1892 } elsif ($isBase || defined($snapname)) {
1893 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1896 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1898 push @extra_opts, '-o', 'ro' if $readonly;
1899 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1903 my $use_loopdev = 0;
1904 if ($scfg->{content
}->{rootdir
}) {
1905 if ($scfg->{path
}) {
1906 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1909 $mounted_dev = $path;
1913 die "storage '$storage' does not support containers\n";
1915 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1917 die "unsupported image format '$format'\n";
1919 } elsif ($type eq 'device') {
1920 push @extra_opts, '-o', 'ro' if $readonly;
1921 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1922 # See the NOTE above about devicemapper canonicalization
1923 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1924 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1925 return wantarray ?
($volid, 0, $devpath) : $volid;
1926 } elsif ($type eq 'bind') {
1927 die "directory '$volid' does not exist\n" if ! -d
$volid;
1928 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1929 warn "cannot enable quota control for bind mounts\n" if $quota;
1930 return wantarray ?
($volid, 0, undef) : $volid;
1933 die "unsupported storage";
1936 sub mountpoint_hotplug
:prototype($$$$$) {
1937 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1939 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1941 # We do the rest in a fork with an unshared mount namespace, because:
1942 # -) change our papparmor profile to that of /usr/bin/lxc-start
1943 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1944 # container's namespace, then mount it.
1946 PVE
::Tools
::run_fork
(sub {
1947 # Pin the container pid longer, we also need to get its monitor/parent:
1948 my ($ct_pid, $ct_pidfd) = open_lxc_pid
($vmid)
1949 or die "failed to open pidfd of container $vmid\'s init process\n";
1951 my ($monitor_pid, $monitor_pidfd) = open_ppid
($ct_pid)
1952 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1954 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1955 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1957 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1958 # profile to lower our privileges to the same level we have in the start hook:
1959 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY
)
1960 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1961 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1964 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1965 # namespace for it to remain active there since the container will be able to unmount
1966 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1968 PVE
::Tools
::setns
(fileno($monitor_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1970 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1972 my $dir = get_staging_mount_path
($opt);
1974 # Now switch our apparmor profile before mounting:
1975 my $data = 'changeprofile /usr/bin/lxc-start';
1976 if (syswrite($aa_fd, $data, length($data)) != length($data)) {
1977 die "failed to change apparmor profile: $!\n";
1979 # Check errors on close as well:
1981 or die "failed to change apparmor profile (close() failed): $!\n";
1983 my $mount_fd = mountpoint_stage
($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1985 PVE
::Tools
::setns
(fileno($ct_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1987 or die "failed to change root directory within the container's mount namespace: $!\n";
1989 mountpoint_insert_staged
($mount_fd, undef, $mp->{mp
}, $opt, $rootuid, $rootgid);
1993 # Create a directory in the mountpoint staging tempfs.
1994 sub get_staging_mount_path
($) {
1997 my $target = get_staging_tempfs
() . "/$opt";
1998 if (!mkdir($target) && $! != EEXIST
) {
1999 die "failed to create directory $target: $!\n";
2005 # Mount tmpfs for mount point staging and return the path.
2006 sub get_staging_tempfs
() {
2007 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
2009 my $target = '/var/lib/lxc/.pve-staged-mounts';
2010 if (!mkdir($target)) {
2011 return $target if $! == EEXIST
;
2012 die "failed to create directory $target: $!\n";
2015 PVE
::Tools
::mount
("none", $target, 'tmpfs', 0, "size=8k,mode=755")
2016 or die "failed to mount $target as tmpfs: $!\n";
2022 my ($dev, $rootuid, $rootgid) = @_;
2030 "root_owner=$rootuid:$rootgid",
2035 # a hack to print only the relevant stuff, i.e., the one which could help on repair
2036 if ($line =~ /^(Creating filesystem|Filesystem UUID|Superblock backups|\s+\d+, \d)/) {
2042 print STDERR
"$line\n" if $line && $line !~ /^mke2fs \d\.\d/;
2048 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
2050 if ($volid =~ m!^/dev/.+!) {
2055 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2057 die "cannot format volume '$volid' with no storage\n" if !$storage;
2059 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
2061 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid);
2063 $path = PVE
::Storage
::path
($storage_cfg, $volid) if !defined($path);
2065 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
2066 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
2068 die "cannot format volume '$volid' (format == $format)\n"
2069 if $format ne 'raw';
2071 mkfs
($path, $rootuid, $rootgid);
2075 my ($storecfg, $vollist) = @_;
2077 foreach my $volid (@$vollist) {
2078 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
2084 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
2086 my $needs_chown = 0;
2089 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
2090 # fixme: use better naming ct-$vmid-disk-X.raw?
2094 if ($scfg->{content
}->{rootdir
} && $scfg->{path
}) {
2095 if ($size_kb > 0 && !($scfg->{type
} eq 'btrfs' && $scfg->{quotas
})) {
2096 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2099 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2102 } elsif ($scfg->{type
} eq 'zfspool') {
2103 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2105 } elsif ($scfg->{content
}->{rootdir
}) {
2106 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2109 die "content type 'rootdir' is not available or configured on storage '$storage'\n";
2111 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
2114 # in case formatting got interrupted:
2115 if (defined($volid)) {
2116 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
2122 return ($volid, $needs_chown);
2126 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
2131 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
2132 my $chown_vollist = [];
2134 PVE
::LXC
::Config-
>foreach_volume($settings, sub {
2135 my ($ms, $mountpoint) = @_;
2137 my $volid = $mountpoint->{volume
};
2138 my $mp = $mountpoint->{mp
};
2140 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2142 if ($storage && ($volid =~ $NEW_DISK_RE)) {
2143 my ($storeid, $size_gb) = ($1, $2);
2145 my $size_kb = int(${size_gb
}*1024) * 1024;
2147 my $needs_chown = 0;
2148 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
2149 push @$chown_vollist, $volid if $needs_chown;
2150 push @$vollist, $volid;
2151 $mountpoint->{volume
} = $volid;
2152 $mountpoint->{size
} = $size_kb * 1024;
2154 $conf->{pending
}->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2156 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2159 # use specified/existing volid/dir/device
2160 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2164 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
2165 foreach my $volid (@$chown_vollist) {
2166 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
2167 chown($rootuid, $rootgid, $path);
2169 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
2171 # free allocated images on error
2173 destroy_disks
($storecfg, $vollist);
2179 sub update_disksize
{
2180 my ($vmid, $conf, $all_volumes) = @_;
2183 my $prefix = "CT $vmid:";
2185 my $update_mp = sub {
2186 my ($key, $mp, @param) = @_;
2187 my $size = $all_volumes->{$mp->{volume
}}->{size
} // 0;
2189 if (!defined($mp->{size
}) || $size != $mp->{size
}) {
2191 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
2192 $mp->{size
} = $size;
2193 my $no_mp = $key eq 'rootfs'; # rootfs is handled different from other mount points
2194 $conf->{$key} = PVE
::LXC
::Config-
>print_ct_mountpoint($mp, $no_mp);
2198 PVE
::LXC
::Config-
>foreach_volume($conf, $update_mp);
2204 my ($vmid, $conf, $all_volumes) = @_;
2207 my $prefix = "CT $vmid:";
2209 # Note: it is allowed to define multiple storage entries with the same path
2210 # (alias), so we need to check both 'volid' and real 'path' (two different
2211 # volid can point to the same path).
2213 # used and unused disks
2217 foreach my $opt (keys %$conf) {
2218 next if ($opt !~ m/^unused\d+$/);
2219 my $vol = $all_volumes->{$conf->{$opt}};
2220 $refpath->{$vol->{path
}} = $vol->{volid
};
2223 foreach my $key (keys %$all_volumes) {
2224 my $vol = $all_volumes->{$key};
2225 my $in_use = PVE
::LXC
::Config-
>is_volume_in_use($conf, $vol->{volid
});
2226 my $path = $vol->{path
};
2229 $refpath->{$path} = $key;
2230 delete $orphans->{$path};
2232 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
2233 $orphans->{$path} = $key;
2238 for my $key (keys %$orphans) {
2239 my $disk = $orphans->{$key};
2240 my $unused = PVE
::LXC
::Config-
>add_unused_volume($conf, $disk);
2244 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
2252 my ($cfg, $vmid) = @_;
2254 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid, undef, 'rootdir');
2256 my $all_volumes = {};
2257 foreach my $storeid (keys %$info) {
2258 foreach my $item (@{$info->{$storeid}}) {
2259 my $volid = $item->{volid
};
2260 next if !($volid && $item->{size
});
2261 $item->{path
} = PVE
::Storage
::path
($cfg, $volid);
2262 $all_volumes->{$volid} = $item;
2266 return $all_volumes;
2270 my ($vmid, $nolock, $dryrun) = @_;
2272 my $cfg = PVE
::Storage
::config
();
2274 print "rescan volumes...\n";
2275 my $all_volumes = scan_volids
($cfg, $vmid);
2277 my $updatefn = sub {
2281 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2283 PVE
::LXC
::Config-
>check_lock($conf);
2286 foreach my $volid (keys %$all_volumes) {
2287 my $info = $all_volumes->{$volid};
2288 $vm_volids->{$volid} = $info if $info->{vmid
} == $vmid;
2291 my $upu = update_unused
($vmid, $conf, $vm_volids);
2292 my $upd = update_disksize
($vmid, $conf, $vm_volids);
2293 $changes = $upu || $upd;
2295 PVE
::LXC
::Config-
>write_config($vmid, $conf) if $changes && !$dryrun;
2298 if (defined($vmid)) {
2302 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2305 my $vmlist = config_list
();
2306 foreach my $vmid (keys %$vmlist) {
2310 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2317 # bash completion helper
2319 sub complete_os_templates
{
2320 my ($cmdname, $pname, $cvalue) = @_;
2322 my $cfg = PVE
::Storage
::config
();
2326 if ($cvalue =~ m/^([^:]+):/) {
2330 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
2331 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
2334 foreach my $id (keys %$data) {
2335 foreach my $item (@{$data->{$id}}) {
2336 push @$res, $item->{volid
} if defined($item->{volid
});
2343 my $complete_ctid_full = sub {
2346 my $idlist = vmstatus
();
2348 my $active_hash = list_active_containers
();
2352 foreach my $id (keys %$idlist) {
2353 my $d = $idlist->{$id};
2354 if (defined($running)) {
2355 next if $d->{template
};
2356 next if $running && !$active_hash->{$id};
2357 next if !$running && $active_hash->{$id};
2366 return &$complete_ctid_full();
2369 sub complete_ctid_stopped
{
2370 return &$complete_ctid_full(0);
2373 sub complete_ctid_running
{
2374 return &$complete_ctid_full(1);
2384 my $lxc = $conf->{lxc
};
2385 foreach my $entry (@$lxc) {
2386 my ($key, $value) = @$entry;
2388 next if $key ne 'lxc.idmap';
2390 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2391 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2392 push @$id_map, [$type, $ct, $host, $length];
2394 $rootuid = $host if $type eq 'u';
2395 $rootgid = $host if $type eq 'g';
2398 die "failed to parse idmap: $value\n";
2402 if (!@$id_map && $conf->{unprivileged
}) {
2403 # Should we read them from /etc/subuid?
2404 $id_map = [ ['u', '0', '100000', '65536'],
2405 ['g', '0', '100000', '65536'] ];
2406 $rootuid = $rootgid = 100000;
2409 return ($id_map, $rootuid, $rootgid);
2412 sub validate_id_maps
{
2415 # $mappings->{$type}->{$side} = [ { line => $line, start => $start, count => $count }, ... ]
2416 # $type: either "u" or "g"
2417 # $side: either "container" or "host"
2418 # $line: index of this mapping in @$id_map
2419 # $start, $count: interval of this mapping
2420 my $mappings = { u
=> {}, g
=> {} };
2421 for (my $i = 0; $i < scalar(@$id_map); $i++) {
2422 my ($type, $ct_start, $host_start, $count) = $id_map->[$i]->@*;
2423 my $sides = $mappings->{$type};
2424 push $sides->{host
}->@*, { line
=> $i, start
=> $host_start, count
=> $count };
2425 push $sides->{container
}->@*, { line
=> $i, start
=> $ct_start, count
=> $count };
2428 # find the first conflict between two consecutive mappings when sorted by their start id
2429 for my $type (qw(u g)) {
2430 for my $side (qw(container host)) {
2431 my @entries = sort { $a->{start
} <=> $b->{start
} } $mappings->{$type}->{$side}->@*;
2432 for my $idx (1..scalar(@entries) - 1) {
2433 my $previous = $entries[$idx - 1];
2434 my $current = $entries[$idx];
2435 if ($previous->{start
} + $previous->{count
} > $current->{start
}) {
2436 my $conflict = $current->{start
};
2437 my @previous_line = $id_map->[$previous->{line
}]->@*;
2438 my @current_line = $id_map->[$current->{line
}]->@*;
2439 die "invalid map entry '@current_line': $side ${type}id $conflict "
2440 ."is also mapped by entry '@previous_line'\n";
2447 sub map_ct_id_to_host
{
2448 my ($id, $id_map, $id_type) = @_;
2450 for my $mapping (@$id_map) {
2451 my ($type, $ct, $host, $length) = @$mapping;
2453 next if ($type ne $id_type);
2455 if ($id >= $ct && $id < ($ct + $length)) {
2456 return $host - $ct + $id;
2463 sub map_ct_uid_to_host
{
2464 my ($uid, $id_map) = @_;
2466 return map_ct_id_to_host
($uid, $id_map, 'u');
2469 sub map_ct_gid_to_host
{
2470 my ($gid, $id_map) = @_;
2472 return map_ct_id_to_host
($gid, $id_map, 'g');
2475 sub userns_command
{
2478 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2483 my sub print_ct_stderr_log
{
2485 my $log = eval { file_get_contents
("/run/pve/ct-$vmid.stderr") };
2488 while ($log =~ /^\h*(lxc-start:?\s+$vmid:?\s*\S+\s*)?(.*?)\h*$/gm) {
2490 print STDERR
"$line\n";
2493 my sub print_ct_warn_log
{
2495 my $log_fn = "/run/pve/ct-$vmid.warnings";
2496 my $log = eval { file_get_contents
($log_fn) };
2499 while ($log =~ /^\h*\s*(.*?)\h*$/gm) {
2500 PVE
::RESTEnvironment
::log_warn
($1);
2502 unlink $log_fn or warn "could not unlink '$log_fn' - $!\n";
2505 my sub monitor_state_change
($$) {
2506 my ($monitor_socket, $vmid) = @_;
2507 die "no monitor socket\n" if !defined($monitor_socket);
2510 my ($type, $name, $value) = PVE
::LXC
::Monitor
::read_lxc_message
($monitor_socket);
2512 die "monitor socket: got EOF\n" if !defined($type);
2514 next if $name ne "$vmid" || $type ne 'STATE';
2516 if ($value eq PVE
::LXC
::Monitor
::STATE_STARTING
) {
2517 alarm(0); # don't timeout after seeing the starting state
2518 } elsif ($value eq PVE
::LXC
::Monitor
::STATE_ABORTING
||
2519 $value eq PVE
::LXC
::Monitor
::STATE_STOPPING
||
2520 $value eq PVE
::LXC
::Monitor
::STATE_STOPPED
) {
2522 } elsif ($value eq PVE
::LXC
::Monitor
::STATE_RUNNING
) {
2525 warn "unexpected message from monitor socket - " .
2526 "type: '$type' - value: '$value'\n";
2530 my sub monitor_start
($$) {
2531 my ($monitor_socket, $vmid) = @_;
2533 my $success = eval {
2534 PVE
::Tools
::run_with_timeout
(10, \
&monitor_state_change
, $monitor_socket, $vmid)
2537 warn "problem with monitor socket, but continuing anyway: $err\n";
2538 } elsif (!$success) {
2539 print_ct_stderr_log
($vmid);
2540 die "startup for container '$vmid' failed\n";
2545 my ($vmid, $conf, $skiplock, $debug) = @_;
2547 # apply pending changes while starting
2548 if (scalar(keys %{$conf->{pending
}})) {
2549 my $storecfg = PVE
::Storage
::config
();
2550 PVE
::LXC
::Config-
>vmconfig_apply_pending($vmid, $conf, $storecfg);
2551 PVE
::LXC
::Config-
>write_config($vmid, $conf);
2552 $conf = PVE
::LXC
::Config-
>load_config($vmid); # update/reload
2555 update_lxc_config
($vmid, $conf);
2558 my ($id_map, undef, undef) = PVE
::LXC
::parse_id_maps
($conf);
2559 PVE
::LXC
::validate_id_maps
($id_map);
2561 warn "lxc.idmap: $@" if $@;
2563 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2566 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2570 my $storage_cfg = PVE
::Storage
::config
();
2571 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
2573 PVE
::Storage
::activate_volumes
($storage_cfg, $vollist);
2575 my $monitor_socket = eval { PVE
::LXC
::Monitor
::get_monitor_socket
() };
2578 unlink "/run/pve/ct-$vmid.stderr"; # systemd does not truncate log files
2580 my $is_debug = $debug || (!defined($debug) && $conf->{debug
});
2581 my $base_unit = $is_debug ?
'pve-container-debug' : 'pve-container';
2583 my $cmd = ['systemctl', 'start', "$base_unit\@$vmid"];
2585 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-start', 1);
2589 monitor_start
($monitor_socket, $vmid) if defined($monitor_socket);
2591 # if debug is requested, print the log it also when the start succeeded
2592 print_ct_stderr_log
($vmid) if $is_debug;
2594 print_ct_warn_log
($vmid); # always print warn log, if any
2597 unlink $skiplock_flag_fn;
2600 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'post-start');
2605 # Helper to stop a container completely and make sure it has stopped completely.
2606 # This is necessary because we want the post-stop hook to have completed its
2607 # unmount-all step, but post-stop happens after lxc puts the container into the
2609 # $kill - if true it will always do an immediate hard-stop
2610 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2611 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2613 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2615 # Open the container's command socket.
2616 my $path = "\0/var/lib/lxc/$vmid/command";
2617 my $sock = IO
::Socket
::UNIX-
>new(
2618 Type
=> SOCK_STREAM
(),
2622 return if $! == ECONNREFUSED
; # The container is not running
2623 die "failed to open container ${vmid}'s command socket: $!\n";
2626 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2627 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-stop');
2629 # Stop the container:
2631 my $cmd = ['lxc-stop', '-n', $vmid];
2634 push @$cmd, '--kill'; # doesn't allow timeouts
2636 # lxc-stop uses a default timeout
2637 push @$cmd, '--nokill' if !$kill_after_timeout;
2639 if (defined($shutdown_timeout)) {
2640 push @$cmd, '--timeout', $shutdown_timeout;
2641 # Give run_command 5 extra seconds
2642 $shutdown_timeout += 5;
2646 eval { run_command
($cmd, timeout
=> $shutdown_timeout) };
2648 # Wait until the command socket is closed.
2649 # In case the lxc-stop call failed, reading from the command socket may block forever,
2650 # so poll with another timeout to avoid freezing the shutdown task.
2654 my $poll = IO
::Poll-
>new();
2655 $poll->mask($sock => POLLIN
| POLLHUP
); # watch for input and EOF events
2656 $poll->poll($shutdown_timeout); # IO::Poll timeout is in seconds
2657 return if ($poll->events($sock) & POLLHUP
);
2659 my $result = <$sock>;
2660 return if !defined $result; # monitor is gone and the ct has stopped.
2663 die "container did not stop\n";
2667 my ($vmid, $timeout, $skiplock) = @_;
2669 PVE
::LXC
::Config-
>lock_config($vmid, sub {
2670 return if !check_running
($vmid);
2672 vm_stop
($vmid, 0, $timeout, 1); # kill if timeout exceeds
2674 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2675 vm_start
($vmid, $conf);
2682 return PVE
::Tools
::run_fork
(sub {
2683 # Unshare the mount namespace
2684 die "failed to unshare mount namespace: $!\n"
2685 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
2686 run_command
(['mount', '--make-rslave', '/']);
2691 my $copy_volume = sub {
2692 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2694 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
2695 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
2697 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
2698 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
2704 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2705 push @mounted, $src;
2707 mountpoint_mount
($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2708 push @mounted, $dest;
2721 '--one-file-system',
2722 "--bwlimit=$bwlimit",
2729 # Wait for rsync's children to release dest so that
2730 # consequent file operations (umount, remove) are possible
2731 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2733 foreach my $mount (reverse @mounted) {
2734 eval { run_command
(['/bin/umount', $mount], errfunc
=> sub{})};
2735 warn "Can't umount $mount\n" if $@;
2738 # If this fails they're used as mount points in a concurrent operation
2739 # (which should not happen but there's also no real need to get rid of them).
2746 # Should not be called after unsharing the mount namespace!
2748 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2750 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
2751 File
::Path
::make_path
("/var/lib/lxc/$vmid");
2752 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2753 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2755 # get id's for unprivileged container
2756 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
2758 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2759 # are visible in this namespace, otherwise the host only sees the empty
2760 # (not-mounted) directory.
2763 # Make sure $mp contains a correct size.
2764 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
2766 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
2768 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
2769 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
2770 chown($rootuid, $rootgid, $path);
2774 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2778 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
2779 if defined($new_volid);
2786 sub get_lxc_version
() {
2788 run_command
([qw(lxc-start --version)], outfunc
=> sub {
2790 # We only parse out major & minor version numbers.
2791 if ($line =~ /^(\d+)\.(\d+)(?:\D.*)?$/) {
2792 $version = [$1, $2];
2796 die "failed to get lxc version\n" if !defined($version);
2799 return $version->@*;
2804 if (PVE
::CGroup
::cgroup_mode
() == 2) {
2805 PVE
::LXC
::Command
::freeze
($vmid, 30);
2807 PVE
::LXC
::CGroup-
>new($vmid)->freeze_thaw(1);
2813 if (PVE
::CGroup
::cgroup_mode
() == 2) {
2814 PVE
::LXC
::Command
::unfreeze
($vmid, 30);
2816 PVE
::LXC
::CGroup-
>new($vmid)->freeze_thaw(0);
2820 sub create_ifaces_ipams_ips
{
2821 my ($conf, $vmid) = @_;
2823 return if !$have_sdn;
2825 for my $opt (keys %$conf) {
2826 next if $opt !~ m/^net(\d+)$/;
2827 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
2828 next if $net->{type
} ne 'veth';
2829 PVE
::Network
::SDN
::Vnets
::add_next_free_cidr
($net->{bridge
}, $conf->{hostname
}, $net->{hwaddr
}, $vmid, undef, 1);
2833 sub delete_ifaces_ipams_ips
{
2834 my ($conf, $vmid) = @_;
2836 return if !$have_sdn;
2838 for my $opt (keys %$conf) {
2839 next if $opt !~ m/^net(\d+)$/;
2840 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
2841 eval { PVE
::Network
::SDN
::Vnets
::del_ips_from_mac
($net->{bridge
}, $net->{hwaddr
}, $conf->{hostname
}) };