]> git.proxmox.com Git - pve-container.git/blobdiff - src/PVE/LXC.pm
Fix #881: uninitialized value on valid lxc.cgroup keys
[pve-container.git] / src / PVE / LXC.pm
index e3160e48bb4c3e9faf5981218fdd9ea4c44dddb2..f761f33b564e28b822bfb6d861f9ee9478774aa7 100644 (file)
@@ -26,6 +26,12 @@ my $nodename = PVE::INotify::nodename();
 
 my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
 
+our $COMMON_TAR_FLAGS = [ '--sparse', '--numeric-owner', '--acls',
+                          '--xattrs',
+                          '--xattrs-include=user.*',
+                          '--xattrs-include=security.capability',
+                          '--warning=no-xattr-write' ];
+
 cfs_register_file('/lxc/', \&parse_pct_config, \&write_pct_config);
 
 my $rootfs_desc = {
@@ -48,6 +54,18 @@ my $rootfs_desc = {
        description => 'Volume size (read only value).',
        optional => 1,
     },
+    acl => {
+       type => 'boolean',
+       format_description => 'acl',
+       description => 'Explicitly enable or disable ACL support.',
+       optional => 1,
+    },
+    ro => {
+       type => 'boolean',
+       format_description => 'ro',
+       description => 'Read-only mountpoint (not supported with bind mounts)',
+       optional => 1,
+    },
 };
 
 PVE::JSONSchema::register_standard_option('pve-ct-rootfs', {
@@ -92,7 +110,7 @@ my $confdesc = {
     ostype => {
        optional => 1,
        type => 'string',
-       enum => ['debian', 'ubuntu', 'centos', 'archlinux'],
+       enum => ['debian', 'ubuntu', 'centos', 'fedora', 'opensuse', 'archlinux'],
        description => "OS type. Corresponds to lxc setup scripts in /usr/share/lxc/config/<ostype>.common.conf.",
     },
     console => {
@@ -112,7 +130,7 @@ my $confdesc = {
     cpulimit => {
        optional => 1,
        type => 'number',
-       description => "Limit of CPU usage. Note if the computer has 2 CPUs, it has total of '2' CPU time. Value '0' indicates no CPU limit.",
+       description => "Limit of CPU usage. Note if the computer has 2 CPUs, it has total of '2' CPU time. Value '0' indicates no CPU limit.",
        minimum => 0,
        maximum => 128,
        default => 0,
@@ -120,7 +138,7 @@ my $confdesc = {
     cpuunits => {
        optional => 1,
        type => 'integer',
-       description => "CPU weight for a VM. Argument is used in the kernel fair scheduler. The larger the number is, the more CPU time this VM gets. Number is relative to weights of all the other running VMs.\n\nNOTE: You can disable fair-scheduler configuration by setting this to 0.",
+       description => "CPU weight for a VM. Argument is used in the kernel fair scheduler. The larger the number is, the more CPU time this VM gets. Number is relative to the weights of all the other running VMs.\n\nNOTE: You can disable fair-scheduler configuration by setting this to 0.",
        minimum => 0,
        maximum => 500000,
        default => 1024,
@@ -153,12 +171,12 @@ my $confdesc = {
     searchdomain => {
        optional => 1,
        type => 'string', format => 'dns-name-list',
-       description => "Sets DNS search domains for a container. Create will automatically use the setting from the host if you neither set searchdomain or nameserver.",
+       description => "Sets DNS search domains for a container. Create will automatically use the setting from the host if you neither set searchdomain nor nameserver.",
     },
     nameserver => {
        optional => 1,
        type => 'string', format => 'address-list',
-       description => "Sets DNS server IP address for a container. Create will automatically use the setting from the host if you neither set searchdomain or nameserver.",
+       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.",
     },
     rootfs => get_standard_option('pve-ct-rootfs'),
     parent => {
@@ -183,7 +201,13 @@ my $confdesc = {
     protection => {
        optional => 1,
        type => 'boolean',
-       description => "Sets the protection flag of the container. This will prevent the remove operation. This will prevent the CT or CT's disk remove/update operation.",
+       description => "Sets the protection flag of the container. This will prevent the CT or CT's disk remove/update operation.",
+       default => 0,
+    },
+    unprivileged => {
+       optional => 1,
+       type => 'boolean',
+       description => "Makes the container run as unprivileged user. (Should not be modified manually.)",
        default => 0,
     },
 };
@@ -219,9 +243,10 @@ my $valid_lxc_conf_keys = {
     'lxc.mount' => 1,
     'lxc.mount.entry' => 1,
     'lxc.mount.auto' => 1,
-    'lxc.rootfs' => 1,
+    'lxc.rootfs' => 'lxc.rootfs is auto generated from rootfs',
     'lxc.rootfs.mount' => 1,
-    'lxc.rootfs.options' => 1,
+    'lxc.rootfs.options' => 'lxc.rootfs.options is not supported' .
+                            ', please use mountpoint options in the "rootfs" key',
     # lxc.cgroup.*
     'lxc.cap.drop' => 1,
     'lxc.cap.keep' => 1,
@@ -245,10 +270,6 @@ my $valid_lxc_conf_keys = {
     'lxc.start.order' => 1,
     'lxc.group' => 1,
     'lxc.environment' => 1,
-    'lxc.' => 1,
-    'lxc.' => 1,
-    'lxc.' => 1,
-    'lxc.' => 1,
 };
 
 my $netconf_desc = {
@@ -324,7 +345,14 @@ my $netconf_desc = {
        format_description => 'VlanNo',
        minimum => '2',
        maximum => '4094',
-       description => "VLAN tag foro this interface.",
+       description => "VLAN tag for this interface.",
+       optional => 1,
+    },
+    trunks => {
+       type => 'string',
+       pattern => qr/\d+(?:;\d+)*/,
+       format_description => 'vlanid[;vlanid...]',
+       description => "VLAN ids to pass through the interface",
        optional => 1,
     },
 };
@@ -345,7 +373,6 @@ my $mp_desc = {
        type => 'string',
        format_description => 'Path',
        description => 'Path to the mountpoint as seen from inside the container.',
-       optional => 1,
     },
 };
 PVE::JSONSchema::register_format('pve-ct-mountpoint', $mp_desc);
@@ -490,8 +517,11 @@ sub parse_pct_config {
        if ($line =~ m/^(lxc\.[a-z0-9_\-\.]+)(:|\s*=)\s*(.*?)\s*$/) {
            my $key = $1;
            my $value = $3;
-           if ($valid_lxc_conf_keys->{$key} || $key =~ m/^lxc\.cgroup\./) {
+           my $validity = $valid_lxc_conf_keys->{$key} || 0;
+           if ($validity eq 1 || $key =~ m/^lxc\.cgroup\./) {
                push @{$conf->{lxc}}, [$key, $value];
+           } elsif (my $errmsg = $validity) {
+               warn "vm $vmid - $key: $errmsg\n";
            } else {
                warn "vm $vmid - unable to parse config: $line\n";
            }
@@ -554,7 +584,7 @@ sub load_config {
     my $cfspath = cfs_config_path($vmid, $node);
 
     my $conf = PVE::Cluster::cfs_read_file($cfspath);
-    die "container $vmid does not exists\n" if !defined($conf);
+    die "container $vmid does not exist\n" if !defined($conf);
 
     return $conf;
 }
@@ -583,7 +613,7 @@ sub write_config {
 }
 
 # flock: we use one file handle per process, so lock file
-# can be called multiple times and succeeds for the same process.
+# can be called multiple times and will succeed for the same process.
 
 my $lock_handles =  {};
 my $lockdir = "/run/lock/lxc";
@@ -737,31 +767,9 @@ sub check_running {
 }
 
 sub get_container_disk_usage {
-    my ($vmid) = @_;
-
-    my $cmd = ['lxc-attach', '-n', $vmid, '--', 'df',  '-P', '-B', '1', '/'];
-
-    my $res = {
-       total => 0,
-       used => 0,
-       avail => 0,
-    };
+    my ($vmid, $pid) = @_;
 
-    my $parser = sub {
-       my $line = shift;
-       if (my ($fsid, $total, $used, $avail) = $line =~
-           m/^(\S+.*)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+%\s.*$/) {
-           $res = {
-               total => $total,
-               used => $used,
-               avail => $avail,
-           };
-       }
-    };
-    eval { PVE::Tools::run_command($cmd, timeout => 1, outfunc => $parser); };
-    warn $@ if $@;
-
-    return $res;
+    return PVE::Tools::df("/proc/$pid/root/", 1);
 }
 
 my $last_proc_vmid_stat;
@@ -799,9 +807,10 @@ sub vmstatus {
     foreach my $vmid (keys %$list) {
        my $d = $list->{$vmid};
 
-       my $running = defined($active_hash->{$vmid});
+       eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
+       warn $@ if $@; # ignore errors (consider them stopped)
 
-       $d->{status} = $running ? 'running' : 'stopped';
+       $d->{status} = $d->{pid} ? 'running' : 'stopped';
 
        my $cfspath = cfs_config_path($vmid);
        my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
@@ -809,17 +818,17 @@ sub vmstatus {
        $d->{name} = $conf->{'hostname'} || "CT$vmid";
        $d->{name} =~ s/[\s]//g;
 
-       $d->{cpus} = $conf->{cpulimit} // 0;
+       $d->{cpus} = $conf->{cpulimit} || $cpucount;
 
-       if ($running) {
-           my $res = get_container_disk_usage($vmid);
+       if ($d->{pid}) {
+           my $res = get_container_disk_usage($vmid, $d->{pid});
            $d->{disk} = $res->{used};
            $d->{maxdisk} = $res->{total};
        } else {
            $d->{disk} = 0;
            # use 4GB by default ??
            if (my $rootfs = $conf->{rootfs}) {
-               my $rootinfo = parse_ct_mountpoint($rootfs);
+               my $rootinfo = parse_ct_rootfs($rootfs);
                $d->{maxdisk} = int(($rootinfo->{size} || 4)*1024*1024)*1024;
            } else {
                $d->{maxdisk} = 4*1024*1024*1024;
@@ -845,9 +854,10 @@ sub vmstatus {
 
     foreach my $vmid (keys %$list) {
        my $d = $list->{$vmid};
-       next if $d->{status} ne 'running';
+       my $pid = $d->{pid};
+
+       next if !$pid; # skip stopped CTs
 
-       my $pid = find_lxc_pid($vmid);
        my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
        $d->{uptime} = time - $ctime; # the method lxcfs uses
 
@@ -910,13 +920,22 @@ sub vmstatus {
     return $list;
 }
 
-sub parse_ct_mountpoint {
-    my ($data, $noerr) = @_;
+sub classify_mountpoint {
+    my ($vol) = @_;
+    if ($vol =~ m!^/!) {
+       return 'device' if $vol =~ m!^/dev/!;
+       return 'bind';
+    }
+    return 'volume';
+}
+
+my $parse_ct_mountpoint_full = sub {
+    my ($desc, $data, $noerr) = @_;
 
     $data //= '';
 
     my $res;
-    eval { $res = PVE::JSONSchema::parse_property_string($mp_desc, $data) };
+    eval { $res = PVE::JSONSchema::parse_property_string($desc, $data) };
     if ($@) {
        return undef if $noerr;
        die $@;
@@ -931,12 +950,31 @@ sub parse_ct_mountpoint {
        $res->{size} = $size;
     }
 
+    $res->{type} = classify_mountpoint($res->{volume});
+
+    return $res;
+};
+
+sub parse_ct_rootfs {
+    my ($data, $noerr) = @_;
+
+    my $res =  &$parse_ct_mountpoint_full($rootfs_desc, $data, $noerr);
+
+    $res->{mp} = '/' if defined($res);
+
     return $res;
 }
 
+sub parse_ct_mountpoint {
+    my ($data, $noerr) = @_;
+
+    return &$parse_ct_mountpoint_full($mp_desc, $data, $noerr);
+}
+
 sub print_ct_mountpoint {
     my ($info, $nomp) = @_;
-    my $skip = $nomp ? ['mp'] : [];
+    my $skip = [ 'type' ];
+    push @$skip, 'mp' if $nomp;
     return PVE::JSONSchema::print_property_string($info, $mp_desc, $skip);
 }
 
@@ -990,7 +1028,7 @@ sub find_lxc_console_pids {
 
        my @args = split(/\0/, $cmdline);
 
-       # serach for lxc-console -n <vmid>
+       # search for lxc-console -n <vmid>
        return if scalar(@args) != 3;
        return if $args[1] ne '-n';
        return if $args[2] !~ m/^\d+$/;
@@ -1064,11 +1102,25 @@ sub update_lxc_config {
     die "missing 'arch' - internal error" if !$conf->{arch};
     $raw .= "lxc.arch = $conf->{arch}\n";
 
+    my $unprivileged = $conf->{unprivileged};
+    my $custom_idmap = grep { $_->[0] eq 'lxc.id_map' } @{$conf->{lxc}};
+
     my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
-    if ($ostype =~ /^(?:debian | ubuntu | centos | archlinux)$/x) {
+    if ($ostype =~ /^(?:debian | ubuntu | centos | fedora | opensuse | archlinux)$/x) {
        $raw .= "lxc.include = /usr/share/lxc/config/$ostype.common.conf\n";
+       if ($unprivileged || $custom_idmap) {
+           $raw .= "lxc.include = /usr/share/lxc/config/$ostype.userns.conf\n"
+       }
     } else {
-       die "implement me";
+       die "implement me (ostype $ostype)";
+    }
+
+    $raw .= "lxc.monitor.unshare = 1\n";
+
+    # Should we read them from /etc/subuid?
+    if ($unprivileged && !$custom_idmap) {
+       $raw .= "lxc.id_map = u 0 100000 65536\n";
+       $raw .= "lxc.id_map = g 0 100000 65536\n";
     }
 
     if (!has_dev_console($conf)) {
@@ -1079,7 +1131,7 @@ sub update_lxc_config {
     my $ttycount = get_tty_count($conf);
     $raw .= "lxc.tty = $ttycount\n";
 
-    # some init scripts expects a linux terminal (turnkey).
+    # some init scripts expect a linux terminal (turnkey).
     $raw .= "lxc.environment = TERM=linux\n";
     
     my $utsname = $conf->{hostname} || "CT$vmid";
@@ -1103,13 +1155,9 @@ sub update_lxc_config {
     my $shares = $conf->{cpuunits} || 1024;
     $raw .= "lxc.cgroup.cpu.shares = $shares\n";
 
-    my $mountpoint = parse_ct_mountpoint($conf->{rootfs});
-    $mountpoint->{mp} = '/';
-    
-    my ($path, $use_loopdev) = mountpoint_mount_path($mountpoint, $storage_cfg);
-    $path = "loop:$path" if $use_loopdev;
+    my $mountpoint = parse_ct_rootfs($conf->{rootfs});
 
-    $raw .= "lxc.rootfs = $path\n";
+    $raw .= "lxc.rootfs = $dir/rootfs\n";
 
     my $netcount = 0;
     foreach my $k (keys %$conf) {
@@ -1167,9 +1215,6 @@ sub verify_searchdomain_list {
 sub add_unused_volume {
     my ($config, $volid) = @_;
 
-    # skip bind mounts and block devices
-    return if $volid =~ m|^/|;
-
     my $key;
     for (my $ind = $MAX_UNUSED_DISKS - 1; $ind >= 0; $ind--) {
        my $test = "unused$ind";
@@ -1180,7 +1225,7 @@ sub add_unused_volume {
        }
     }
 
-    die "To many unused volume - please delete them first.\n" if !$key;
+    die "Too many unused volumes - please delete them first.\n" if !$key;
 
     $config->{$key} = $volid;
 
@@ -1212,6 +1257,11 @@ sub update_pct_config {
 
     if (defined($delete)) {
        foreach my $opt (@$delete) {
+           if (!exists($conf->{$opt})) {
+               warn "no such option: $opt\n";
+               next;
+           }
+
            if ($opt eq 'hostname' || $opt eq 'memory' || $opt eq 'rootfs') {
                die "unable to delete required option '$opt'\n";
            } elsif ($opt eq 'swap') {
@@ -1239,10 +1289,14 @@ sub update_pct_config {
                next if $hotplug_error->($opt);
                check_protection($conf, "can't remove CT $vmid drive '$opt'");
                my $mountpoint = parse_ct_mountpoint($conf->{$opt});
-               add_unused_volume($conf, $mountpoint->{volume});
+               if ($mountpoint->{type} eq 'volume') {
+                   add_unused_volume($conf, $mountpoint->{volume})
+               }
                delete $conf->{$opt};
+           } elsif ($opt eq 'unprivileged') {
+               die "unable to delete read-only option: '$opt'\n";
            } else {
-               die "implement me"
+               die "implement me (delete: $opt)"
            }
            write_config($vmid, $conf) if $running;
        }
@@ -1313,6 +1367,8 @@ sub update_pct_config {
         } elsif ($opt eq 'rootfs') {
            check_protection($conf, "can't update CT $vmid drive '$opt'");
            die "implement me: $opt";
+       } elsif ($opt eq 'unprivileged') {
+           die "unable to modify read-only option: '$opt'\n";
        } else {
            die "implement me: $opt";
        }
@@ -1402,10 +1458,7 @@ sub get_primary_ips {
 sub delete_mountpoint_volume {
     my ($storage_cfg, $vmid, $volume) = @_;
 
-    # skip bind mounts and block devices
-    if ($volume =~ m|^/|) {
-           return;
-    }
+    return if classify_mountpoint($volume) ne 'volume';
 
     my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
     PVE::Storage::vdisk_free($storage_cfg, $volume) if $vmid == $owner;
@@ -1497,7 +1550,7 @@ sub update_net {
                    write_config($vmid, $conf);
                }
 
-               PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall});
+               PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks});
                foreach (qw(bridge tag firewall)) {
                    $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
                }
@@ -1519,7 +1572,7 @@ sub hotplug_net {
     my $eth = $newnet->{name};
 
     PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
-    PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall});
+    PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks});
 
     # attach peer in container
     my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
@@ -1651,8 +1704,8 @@ sub update_ipconfig {
 # Internal snapshots
 
 # NOTE: Snapshot create/delete involves several non-atomic
-# action, and can take a long time.
-# So we try to avoid locking the file and use 'lock' variable
+# actions, and can take a long time.
+# So we try to avoid locking the file and use the 'lock' variable
 # inside the config file instead.
 
 my $snapshot_copy_config = sub {
@@ -1691,7 +1744,8 @@ my $snapshot_prepare = sub {
            if defined($conf->{snapshots}->{$snapname});
 
        my $storecfg = PVE::Storage::config();
-       die "snapshot feature is not available\n" if !has_feature('snapshot', $conf, $storecfg);
+       my $feature = $snapname eq 'vzdump' ? 'vzdump' : 'snapshot';
+       die "snapshot feature is not available\n" if !has_feature($feature, $conf, $storecfg);
 
        $snap = $conf->{snapshots}->{$snapname} = {};
 
@@ -1741,11 +1795,14 @@ sub has_feature {
     my ($feature, $conf, $storecfg, $snapname) = @_;
     
     my $err;
+    my $vzdump = $feature eq 'vzdump';
+    $feature = 'snapshot' if $vzdump;
 
     foreach_mountpoint($conf, sub {
        my ($ms, $mountpoint) = @_;
 
        return if $err; # skip further test
+       return if $vzdump && $ms ne 'rootfs' && !$mountpoint->{backup};
        
        $err = 1 if !PVE::Storage::volume_has_feature($storecfg, $feature, $mountpoint->{volume}, $snapname);
 
@@ -1765,24 +1822,31 @@ sub snapshot_create {
     my $conf = load_config($vmid);
 
     my $running = check_running($vmid);
+    
+    my $unfreeze = 0;
+    
     eval {
        if ($running) {
            PVE::Tools::run_command(['/usr/bin/lxc-freeze', '-n', $vmid]);
+           $unfreeze = 1;
            PVE::Tools::run_command(['/bin/sync']);
        };
 
        my $storecfg = PVE::Storage::config();
-       my $rootinfo = parse_ct_mountpoint($conf->{rootfs});
+       my $rootinfo = parse_ct_rootfs($conf->{rootfs});
        my $volid = $rootinfo->{volume};
 
-       if ($running) {
-           PVE::Tools::run_command(['/usr/bin/lxc-unfreeze', '-n', $vmid]);
-       };
-
        PVE::Storage::volume_snapshot($storecfg, $volid, $snapname);
        &$snapshot_commit($vmid, $snapname);
     };
-    if(my $err = $@) {
+    my $err = $@;
+    
+    if ($unfreeze) {
+       eval { PVE::Tools::run_command(['/usr/bin/lxc-unfreeze', '-n', $vmid]); };
+       warn $@ if $@;
+    }
+    
+    if ($err) {
        snapshot_delete($vmid, $snapname, 1);
        die "$err\n";
     }
@@ -1817,17 +1881,29 @@ sub snapshot_delete {
 
     my $storecfg = PVE::Storage::config();
 
-    my $del_snap =  sub {
+    my $unlink_parent = sub {
 
-       check_lock($conf);
+       my ($confref, $new_parent) = @_;
 
-       if ($conf->{parent} eq $snapname) {
-           if ($conf->{snapshots}->{$snapname}->{snapname}) {
-               $conf->{parent} = $conf->{snapshots}->{$snapname}->{parent};
+       if ($confref->{parent} && $confref->{parent} eq $snapname) {
+           if ($new_parent) {
+               $confref->{parent} = $new_parent;
            } else {
-               delete $conf->{parent};
+               delete $confref->{parent};
            }
        }
+    };
+
+    my $del_snap =  sub {
+
+       check_lock($conf);
+
+       my $parent = $conf->{snapshots}->{$snapname}->{parent};
+       foreach my $snapkey (keys %{$conf->{snapshots}}) {
+           &$unlink_parent($conf->{snapshots}->{$snapkey}, $parent);
+       }
+
+       &$unlink_parent($conf, $parent);
 
        delete $conf->{snapshots}->{$snapname};
 
@@ -1835,7 +1911,7 @@ sub snapshot_delete {
     };
 
     my $rootfs = $conf->{snapshots}->{$snapname}->{rootfs};
-    my $rootinfo = parse_ct_mountpoint($rootfs);
+    my $rootinfo = parse_ct_rootfs($rootfs);
     my $volid = $rootinfo->{volume};
 
     eval {
@@ -1865,7 +1941,7 @@ sub snapshot_rollback {
     die "snapshot '$snapname' does not exist\n" if !defined($snap);
 
     my $rootfs = $snap->{rootfs};
-    my $rootinfo = parse_ct_mountpoint($rootfs);
+    my $rootinfo = parse_ct_rootfs($rootfs);
     my $volid = $rootinfo->{volume};
 
     PVE::Storage::volume_rollback_is_possible($storecfg, $volid, $snapname);
@@ -1915,7 +1991,7 @@ sub template_create {
 
     my $storecfg = PVE::Storage::config();
 
-    my $rootinfo = parse_ct_mountpoint($conf->{rootfs});
+    my $rootinfo = parse_ct_rootfs($conf->{rootfs});
     my $volid = $rootinfo->{volume};
 
     die "Template feature is not available for '$volid'\n"
@@ -1967,14 +2043,12 @@ sub foreach_mountpoint_full {
     foreach my $key (mountpoint_names($reverse)) {
        my $value = $conf->{$key};
        next if !defined($value);
-       my $mountpoint = parse_ct_mountpoint($value, 1);
+       my $mountpoint = $key eq 'rootfs' ? parse_ct_rootfs($value, 1) : parse_ct_mountpoint($value, 1);
        next if !defined($mountpoint);
 
-       # just to be sure: rootfs is /
-       my $path = $key eq 'rootfs' ? '/' : $mountpoint->{mp};
-       $mountpoint->{mp} = sanitize_mountpoint($path);
+       $mountpoint->{mp} = sanitize_mountpoint($mountpoint->{mp});
 
-       $path = $mountpoint->{volume};
+       my $path = $mountpoint->{volume};
        $mountpoint->{volume} = sanitize_mountpoint($path) if $path =~ m|^/|;
 
        &$func($key, $mountpoint);
@@ -2062,23 +2136,13 @@ sub mount_all {
        foreach_mountpoint($conf, sub {
            my ($ms, $mountpoint) = @_;
 
-           my $volid = $mountpoint->{volume};
-           my $mount = $mountpoint->{mp};
-
-           return if !$volid || !$mount;
-
-           my $image_path = PVE::Storage::path($storage_cfg, $volid);
-           my ($vtype, undef, undef, undef, undef, $isBase, $format) =
-               PVE::Storage::parse_volname($storage_cfg, $volid);
-
-           die "unable to mount base volume - internal error" if $isBase;
-
            mountpoint_mount($mountpoint, $rootdir, $storage_cfg);
         });
     };
     if (my $err = $@) {
-       warn "mounting container failed - $err";
+       warn "mounting container failed\n";
        umount_all($vmid, $storage_cfg, $conf, 1);
+       die $err;
     }
 
     return $rootdir;
@@ -2100,12 +2164,27 @@ my $check_mount_path = sub {
     }
 };
 
+sub query_loopdev {
+    my ($path) = @_;
+    my $found;
+    my $parser = sub {
+       my $line = shift;
+       if ($line =~ m@^(/dev/loop\d+):@) {
+           $found = $1;
+       }
+    };
+    my $cmd = ['losetup', '--associated', $path];
+    PVE::Tools::run_command($cmd, outfunc => $parser);
+    return $found;
+}
+
 # use $rootdir = undef to just return the corresponding mount path
 sub mountpoint_mount {
     my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
 
     my $volid = $mountpoint->{volume};
     my $mount = $mountpoint->{mp};
+    my $type = $mountpoint->{type};
     
     return if !$volid || !$mount;
 
@@ -2123,6 +2202,17 @@ sub mountpoint_mount {
 
     die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
 
+    my $optstring = '';
+    if (defined($mountpoint->{acl})) {
+       $optstring .= ($mountpoint->{acl} ? 'acl' : 'noacl');
+    }
+    if ($mountpoint->{ro}) {
+       $optstring .= ',' if $optstring;
+       $optstring .= 'ro';
+    }
+
+    my @extra_opts = ('-o', $optstring);
+
     if ($storage) {
 
        my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
@@ -2139,22 +2229,25 @@ sub mountpoint_mount {
                    if ($scfg->{type} eq 'zfspool') {
                        my $path_arg = $path;
                        $path_arg =~ s!^/+!!;
-                       PVE::Tools::run_command(['mount', '-o', 'ro', '-t', 'zfs', $path_arg, $mount_path]);
+                       PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
                    } else {
                        die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
                    }
                } else {
-                   PVE::Tools::run_command(['mount', '-o', 'bind', $path, $mount_path]);
+                   if ($mountpoint->{ro}) {
+                       die "read-only bind mounts not supported\n";
+                   }
+                   PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $path, $mount_path]);
                }
            }
            return wantarray ? ($path, 0) : $path;
        } elsif ($format eq 'raw' || $format eq 'iso') {
            my $use_loopdev = 0;
-           my @extra_opts;
            if ($scfg->{path}) {
                push @extra_opts, '-o', 'loop';
                $use_loopdev = 1;
-           } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'rbd') {
+           } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
+                    $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
                # do nothing
            } else {
                die "unsupported storage type '$scfg->{type}'\n";
@@ -2172,12 +2265,19 @@ sub mountpoint_mount {
        } else {
            die "unsupported image format '$format'\n";
        }
-    } elsif ($volid =~ m|^/dev/.+|) {
-       PVE::Tools::run_command(['mount', $volid, $mount_path]) if $mount_path;
+    } elsif ($type eq 'device') {
+       PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
        return wantarray ? ($volid, 0) : $volid;
-    } elsif ($volid !~ m|^/dev/.+| && $volid =~ m|^/.+| && -d $volid) {
+    } elsif ($type eq 'bind') {
+       if ($mountpoint->{ro}) {
+           die "read-only bind mounts not supported\n";
+           # Theoretically we'd have to execute both:
+           # mount -o bind $a $b
+           # mount -o bind,remount,ro $a $b
+       }
+       die "directory '$volid' does not exist\n" if ! -d $volid;
        &$check_mount_path($volid);
-       PVE::Tools::run_command(['mount', '-o', 'bind', $volid, $mount_path]) if $mount_path;
+       PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $volid, $mount_path]) if $mount_path;
        return wantarray ? ($volid, 0) : $volid;
     }
     
@@ -2196,7 +2296,7 @@ sub get_vm_volumes {
 
        my $volid = $mountpoint->{volume};
 
-        return if !$volid || $volid =~ m|^/|;
+        return if !$volid || $mountpoint->{type} ne 'volume';
 
         my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
         return if !$sid;
@@ -2208,13 +2308,15 @@ sub get_vm_volumes {
 }
 
 sub mkfs {
-    my ($dev) = @_;
+    my ($dev, $rootuid, $rootgid) = @_;
 
-    PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp', $dev]);
+    PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
+                            '-E', "root_owner=$rootuid:$rootgid",
+                            $dev]);
 }
 
 sub format_disk {
-    my ($storage_cfg, $volid) = @_;
+    my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
 
     if ($volid =~ m!^/dev/.+!) {
        mkfs($volid);
@@ -2235,7 +2337,7 @@ sub format_disk {
     die "cannot format volume '$volid' (format == $format)\n"
        if $format ne 'raw';
 
-    mkfs($path);
+    mkfs($path, $rootuid, $rootgid);
 }
 
 sub destroy_disks {
@@ -2253,6 +2355,9 @@ sub create_disks {
     my $vollist = [];
 
     eval {
+       my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
+       my $chown_vollist = [];
+
        foreach_mountpoint($settings, sub {
            my ($ms, $mountpoint) = @_;
 
@@ -2261,9 +2366,7 @@ sub create_disks {
 
            my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
 
-           return if !$storage;
-
-           if ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/) {
+           if ($storage && ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/)) {
                my ($storeid, $size_gb) = ($1, $2);
 
                my $size_kb = int(${size_gb}*1024) * 1024;
@@ -2275,35 +2378,46 @@ sub create_disks {
                    if ($size_kb > 0) {
                        $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
                                                           undef, $size_kb);
-                       format_disk($storecfg, $volid);
+                       format_disk($storecfg, $volid, $rootuid, $rootgid);
                    } else {
                        $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
                                                           undef, 0);
+                       push @$chown_vollist, $volid;
                    }
                } elsif ($scfg->{type} eq 'zfspool') {
 
                    $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
                                                       undef, $size_kb);
-               } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm') {
+                   push @$chown_vollist, $volid;
+               } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
 
                    $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
-                   format_disk($storecfg, $volid);
+                   format_disk($storecfg, $volid, $rootuid, $rootgid);
 
                } elsif ($scfg->{type} eq 'rbd') {
 
                    die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd};
                    $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
-                   format_disk($storecfg, $volid);
+                   format_disk($storecfg, $volid, $rootuid, $rootgid);
                } else {
                    die "unable to create containers on storage type '$scfg->{type}'\n";
                }
                push @$vollist, $volid;
-                my $new_mountpoint = { volume => $volid, size => $size_kb*1024, mp => $mp };
-               $conf->{$ms} = print_ct_mountpoint($new_mountpoint, $ms eq 'rootfs');
+               $mountpoint->{volume} = $volid;
+               $mountpoint->{size} = $size_kb * 1024;
+               $conf->{$ms} = print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
            } else {
-               # use specified/existing volid
+                # use specified/existing volid/dir/device
+                $conf->{$ms} = print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
            }
        });
+
+       PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
+       foreach my $volid (@$chown_vollist) {
+           my $path = PVE::Storage::path($storecfg, $volid, undef);
+           chown($rootuid, $rootgid, $path);
+       }
+       PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
     };
     # free allocated images on error
     if (my $err = $@) {
@@ -2373,4 +2487,45 @@ sub complete_ctid_running {
     return &$complete_ctid_full(1);
 }
 
+sub parse_id_maps {
+    my ($conf) = @_;
+
+    my $id_map = [];
+    my $rootuid = 0;
+    my $rootgid = 0;
+
+    my $lxc = $conf->{lxc};
+    foreach my $entry (@$lxc) {
+       my ($key, $value) = @$entry;
+       next if $key ne 'lxc.id_map';
+       if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
+           my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
+           push @$id_map, [$type, $ct, $host, $length];
+           if ($ct == 0) {
+               $rootuid = $host if $type eq 'u';
+               $rootgid = $host if $type eq 'g';
+           }
+       } else {
+           die "failed to parse id_map: $value\n";
+       }
+    }
+
+    if (!@$id_map && $conf->{unprivileged}) {
+       # Should we read them from /etc/subuid?
+       $id_map = [ ['u', '0', '100000', '65536'],
+                   ['g', '0', '100000', '65536'] ];
+       $rootuid = $rootgid = 100000;
+    }
+
+    return ($id_map, $rootuid, $rootgid);
+}
+
+sub userns_command {
+    my ($id_map) = @_;
+    if (@$id_map) {
+       return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
+    }
+    return [];
+}
+
 1;