]> git.proxmox.com Git - pve-container.git/blobdiff - src/PVE/API2/LXC.pm
destroy: check if container is still running
[pve-container.git] / src / PVE / API2 / LXC.pm
index 2c4262256b0e64db88a025db1883a25b3f321f5e..a4e80ec7ac4592f088ef4b6707dd52a9f0f00511 100644 (file)
@@ -15,6 +15,7 @@ use PVE::RESTHandler;
 use PVE::RPCEnvironment;
 use PVE::LXC;
 use PVE::LXC::Create;
+use PVE::LXC::Migrate;
 use PVE::API2::LXC::Config;
 use PVE::API2::LXC::Status;
 use PVE::API2::LXC::Snapshot;
@@ -44,78 +45,6 @@ __PACKAGE__->register_method ({
     path => '{vmid}/firewall',
 });
 
-my $destroy_disks = sub {
-    my ($storecfg, $vollist) = @_;
-
-    foreach my $volid (@$vollist) {
-       eval { PVE::Storage::vdisk_free($storecfg, $volid); };
-       warn $@ if $@;
-    }
-};
-my $create_disks = sub {
-    my ($storecfg, $vmid, $settings, $conf) = @_;
-
-    my $vollist = [];
-
-    eval {
-       PVE::LXC::foreach_mountpoint($settings, sub {
-           my ($ms, $mountpoint) = @_;
-
-           my $volid = $mountpoint->{volume};
-           my $mp = $mountpoint->{mp};
-
-           my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
-
-           return if !$storage;
-
-           if ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/) {
-               my ($storeid, $size) = ($1, $2);
-
-               $size = int($size*1024) * 1024;
-
-               my $scfg = PVE::Storage::storage_config($storecfg, $storage);
-               # fixme: use better naming ct-$vmid-disk-X.raw?
-
-               if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
-                   if ($size > 0) {
-                       $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
-                                                          undef, $size);
-                   } else {
-                       $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
-                                                          undef, 0);
-                   }
-               } elsif ($scfg->{type} eq 'zfspool') {
-
-                   $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
-                                              undef, $size);
-               } elsif ($scfg->{type} eq 'drbd') {
-
-                   $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size);
-
-               } 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);
-               } else {
-                   die "unable to create containers on storage type '$scfg->{type}'\n";
-               }
-               push @$vollist, $volid;
-               $conf->{$ms} = PVE::LXC::print_ct_mountpoint({volume => $volid, size => $size, mp => $mp });
-           } else {
-               # use specified/existing volid
-           }
-       });
-    };
-    # free allocated images on error
-    if (my $err = $@) {
-        syslog('err', "VM $vmid creating disks failed");
-       &$destroy_disks($storecfg, $vollist);
-        die $err;
-    }
-    return $vollist;
-};
-
 __PACKAGE__->register_method({
     name => 'vmlist',
     path => '',
@@ -179,11 +108,12 @@ __PACKAGE__->register_method({
        additionalProperties => 0,
        properties => PVE::LXC::json_config_properties({
            node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
            ostemplate => {
                description => "The OS template or backup file.",
                type => 'string',
                maxLength => 255,
+               completion => \&PVE::LXC::complete_os_templates,
            },
            password => {
                optional => 1,
@@ -195,6 +125,7 @@ __PACKAGE__->register_method({
                description => "Default Storage.",
                default => 'local',
                optional => 1,
+               completion => \&PVE::Storage::complete_storage_enabled,
            }),
            force => {
                optional => 1,
@@ -242,19 +173,13 @@ __PACKAGE__->register_method({
 
        if (!($same_container_exists && $restore && $force)) {
            PVE::Cluster::check_vmid_unused($vmid);
+       } else {
+           my $conf = PVE::LXC::load_config($vmid);
+           PVE::LXC::check_protection($conf, "unable to restore CT $vmid");
        }
 
        my $password = extract_param($param, 'password');
 
-       my $storage = extract_param($param, 'storage') // 'local';
-       
-       my $storage_cfg = cfs_read_file("storage.cfg");
-
-       my $scfg = PVE::Storage::storage_check_node($storage_cfg, $storage, $node);
-
-       raise_param_exc({ storage => "storage '$storage' does not support container root directories"})
-           if !($scfg->{content}->{images} || $scfg->{content}->{rootdir});
-
        my $pool = extract_param($param, 'pool');
 
        if (defined($pool)) {
@@ -262,8 +187,6 @@ __PACKAGE__->register_method({
            $rpcenv->check_perm_modify($authuser, "/pool/$pool");
        }
 
-       $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace']);
-       
        if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
            # OK
        } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
@@ -277,7 +200,9 @@ __PACKAGE__->register_method({
 
        PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
 
-       PVE::Storage::activate_storage($storage_cfg, $storage);
+       my $storage = extract_param($param, 'storage') // 'local';
+
+       my $storage_cfg = cfs_read_file("storage.cfg");
 
        my $ostemplate = extract_param($param, 'ostemplate');
 
@@ -295,6 +220,19 @@ __PACKAGE__->register_method({
            $archive = PVE::Storage::abs_filesystem_path($storage_cfg, $ostemplate);
        }
 
+       my $check_and_activate_storage = sub {
+           my ($sid) = @_;
+
+           my $scfg = PVE::Storage::storage_check_node($storage_cfg, $sid, $node);
+
+           raise_param_exc({ storage => "storage '$sid' does not support container directories"})
+               if !$scfg->{content}->{rootdir};
+
+           $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
+
+           PVE::Storage::activate_storage($storage_cfg, $sid);
+       };
+
        my $conf = {};
 
        my $no_disk_param = {};
@@ -307,11 +245,27 @@ __PACKAGE__->register_method({
                $no_disk_param->{$opt} = $value;
            }
        }
+
+       # check storage access, activate storage
+       PVE::LXC::foreach_mountpoint($param, sub {
+           my ($ms, $mountpoint) = @_;
+
+           my $volid = $mountpoint->{volume};
+           my $mp = $mountpoint->{mp};
+
+           my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
+
+           &$check_and_activate_storage($sid) if $sid;
+       });
+
+       # check/activate default storage
+       &$check_and_activate_storage($storage) if !defined($param->{rootfs});
+
        PVE::LXC::update_pct_config($vmid, $conf, 0, $no_disk_param);
 
        my $check_vmid_usage = sub {
            if ($force) {
-               die "cant overwrite running container\n"
+               die "can't overwrite running container\n"
                    if PVE::LXC::check_running($vmid);
            } else {
                PVE::Cluster::check_vmid_unused($vmid);
@@ -330,13 +284,14 @@ __PACKAGE__->register_method({
                        my (undef, $disksize) = PVE::LXC::Create::recover_config($archive);
                        die "unable to detect disk size - please specify rootfs (size)\n"
                            if !$disksize;
+                       $disksize /= 1024 * 1024 * 1024; # create_disks expects GB as unit size
                        $param->{rootfs} = "$storage:$disksize";
                    } else {
                        $param->{rootfs} = "$storage:4"; # defaults to 4GB
                    }
                }
 
-               $vollist = &$create_disks($storage_cfg, $vmid, $param, $conf);
+               $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $param, $conf);
 
                PVE::LXC::Create::create_rootfs($storage_cfg, $vmid, $conf, $archive, $password, $restore);
                # set some defaults
@@ -346,7 +301,7 @@ __PACKAGE__->register_method({
                PVE::LXC::create_config($vmid, $conf);
            };
            if (my $err = $@) {
-               &$destroy_disks($storage_cfg, $vollist);
+               PVE::LXC::destroy_disks($storage_cfg, $vollist);
                PVE::LXC::destroy_config($vmid);
                die $err;
            }
@@ -406,6 +361,7 @@ __PACKAGE__->register_method({
            { subdir => 'rrddata' },
            { subdir => 'firewall' },
            { subdir => 'snapshot' },
+           { subdir => 'resize' },
            ];
 
        return $res;
@@ -512,7 +468,7 @@ __PACKAGE__->register_method({
        additionalProperties => 0,
        properties => {
            node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
        },
     },
     returns => {
@@ -532,14 +488,22 @@ __PACKAGE__->register_method({
 
        my $storage_cfg = cfs_read_file("storage.cfg");
 
+       PVE::LXC::check_protection($conf, "can't remove CT $vmid");
+
        die "unable to remove CT $vmid - used in HA resources\n"
            if PVE::HA::Config::vm_is_ha_managed($vmid);
 
+       my $running_error_msg = "unable to destroy CT $vmid - container is running\n";
+
+       die $running_error_msg if PVE::LXC::check_running($vmid); # check early
+
        my $code = sub {
            # reload config after lock
            $conf = PVE::LXC::load_config($vmid);
            PVE::LXC::check_lock($conf);
 
+           die $running_error_msg if PVE::LXC::check_running($vmid);
+
            PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $conf);
            PVE::AccessControl::remove_vm_access($vmid);
            PVE::Firewall::remove_vmfw_conf($vmid);
@@ -766,8 +730,11 @@ __PACKAGE__->register_method({
        additionalProperties => 0,
        properties => {
            node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
-           target => get_standard_option('pve-node', { description => "Target node." }),
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
+           target => get_standard_option('pve-node', {
+               description => "Target node.",
+               completion => \&PVE::Cluster::complete_migration_target,
+           }),
            online => {
                type => 'boolean',
                description => "Use online/live migration.",
@@ -804,7 +771,7 @@ __PACKAGE__->register_method({
 
        # try to detect errors early
        if (PVE::LXC::check_running($vmid)) {
-           die "cant migrate running container without --online\n"
+           die "can't migrate running container without --online\n"
                if !$param->{online};
        }
 
@@ -831,8 +798,7 @@ __PACKAGE__->register_method({
            my $realcmd = sub {
                my $upid = shift;
 
-               # fixme: implement lxc container migration
-               die "lxc container migration not implemented\n";
+               PVE::LXC::Migrate->migrate($target, $targetip, $vmid, $param);
 
                return;
            };
@@ -920,7 +886,7 @@ __PACKAGE__->register_method({
        additionalProperties => 0,
        properties => {
            node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
        },
     },
     returns => { type => 'null'},
@@ -967,4 +933,158 @@ __PACKAGE__->register_method({
        return undef;
     }});
 
+__PACKAGE__->register_method({
+    name => 'resize_vm',
+    path => '{vmid}/resize',
+    method => 'PUT',
+    protected => 1,
+    proxyto => 'node',
+    description => "Resize a container mountpoint.",
+    permissions => {
+       check => ['perm', '/vms/{vmid}', ['VM.Config.Disk'], any => 1],
+    },
+    parameters => {
+       additionalProperties => 0,
+       properties => PVE::LXC::json_config_properties(
+           {
+               node => get_standard_option('pve-node'),
+               vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
+               disk => {
+                   type => 'string',
+                   description => "The disk you want to resize.",
+                   enum => [PVE::LXC::mountpoint_names()],
+               },
+               size => {
+                   type => 'string',
+                   pattern => '\+?\d+(\.\d+)?[KMGT]?',
+                   description => "The new size. With the '+' sign the value is added to the actual size of the volume and without it, the value is taken as an absolute one. Shrinking disk size is not supported.",
+               },
+               digest => {
+                   type => 'string',
+                   description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
+                   maxLength => 40,
+                   optional => 1,
+               }
+           }),
+    },
+    returns => {
+       type => 'string',
+       description => "the task ID.",
+    },
+    code => sub {
+       my ($param) = @_;
+
+       my $rpcenv = PVE::RPCEnvironment::get();
+
+       my $authuser = $rpcenv->get_user();
+
+       my $node = extract_param($param, 'node');
+
+       my $vmid = extract_param($param, 'vmid');
+
+       my $digest = extract_param($param, 'digest');
+
+       my $sizestr = extract_param($param, 'size');
+       my $ext = ($sizestr =~ s/^\+//);
+       my $newsize = PVE::JSONSchema::parse_size($sizestr);
+       die "invalid size string" if !defined($newsize);
+
+       die "no options specified\n" if !scalar(keys %$param);
+
+       PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
+
+       my $storage_cfg = cfs_read_file("storage.cfg");
+
+       my $query_loopdev = sub {
+           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;
+       };
+
+       my $code = sub {
+
+           my $conf = PVE::LXC::load_config($vmid);
+           PVE::LXC::check_lock($conf);
+
+           PVE::Tools::assert_if_modified($digest, $conf->{digest});
+
+           my $running = PVE::LXC::check_running($vmid);
+
+           my $disk = $param->{disk};
+           my $mp = PVE::LXC::parse_ct_mountpoint($conf->{$disk});
+           my $volid = $mp->{volume};
+
+           my (undef, undef, $owner, undef, undef, undef, $format) =
+               PVE::Storage::parse_volname($storage_cfg, $volid);
+
+           die "can't resize mountpoint owned by another container ($owner)"
+               if $vmid != $owner;
+
+           die "can't resize volume: $disk if snapshot exists\n"
+               if %{$conf->{snapshots}} && $format eq 'qcow2';
+
+           my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
+
+           $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
+
+           my $size = PVE::Storage::volume_size_info($storage_cfg, $volid, 5);
+           $newsize += $size if $ext;
+           $newsize = int($newsize);
+
+           die "unable to shrink disk size\n" if $newsize < $size;
+
+           return if $size == $newsize;
+
+           PVE::Cluster::log_msg('info', $authuser, "update CT $vmid: resize --disk $disk --size $sizestr");
+           my $realcmd = sub {
+               # Note: PVE::Storage::volume_resize doesn't do anything if $running=1, so
+               # we pass 0 here (parameter only makes sense for qemu)
+               PVE::Storage::volume_resize($storage_cfg, $volid, $newsize, 0);
+
+               $mp->{size} = $newsize;
+               $conf->{$disk} = PVE::LXC::print_ct_mountpoint($mp, $disk eq 'rootfs');
+
+               PVE::LXC::write_config($vmid, $conf);
+
+               if ($format eq 'raw') {
+                   my $path = PVE::Storage::path($storage_cfg, $volid, undef);
+                   if ($running) {
+
+                       $mp->{mp} = '/';
+                       my $use_loopdev = (PVE::LXC::mountpoint_mount_path($mp, $storage_cfg))[1];
+                       $path = &$query_loopdev($path) if $use_loopdev;
+                       die "internal error: CT running but mountpoint not attached to a loop device"
+                           if !$path;
+                       PVE::Tools::run_command(['losetup', '--set-capacity', $path]) if $use_loopdev;
+
+                       # In order for resize2fs to know that we need online-resizing a mountpoint needs
+                       # to be visible to it in its namespace.
+                       # To not interfere with the rest of the system we unshare the current mount namespace,
+                       # mount over /tmp and then run resize2fs.
+
+                       # interestingly we don't need to e2fsck on mounted systems...
+                       my $quoted = PVE::Tools::shellquote($path);
+                       my $cmd = "mount --make-rprivate / && mount $quoted /tmp && resize2fs $quoted";
+                       PVE::Tools::run_command(['unshare', '-m', '--', 'sh', '-c', $cmd]);
+                   } else {
+                       PVE::Tools::run_command(['e2fsck', '-f', '-y', $path]);
+                       PVE::Tools::run_command(['resize2fs', $path]);
+                   }
+               }
+           };
+
+           return $rpcenv->fork_worker('resize', $vmid, $authuser, $realcmd);
+       };
+
+       return PVE::LXC::lock_container($vmid, undef, $code);;
+    }});
+
 1;