]> 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 c047e0ca12aeb87e3eb0e0517c39df29439f8b3a..a4e80ec7ac4592f088ef4b6707dd52a9f0f00511 100644 (file)
@@ -9,49 +9,41 @@ use PVE::Exception qw(raise raise_param_exc);
 use PVE::INotify;
 use PVE::Cluster qw(cfs_read_file);
 use PVE::AccessControl;
+use PVE::Firewall;
 use PVE::Storage;
 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;
 use PVE::HA::Config;
 use PVE::JSONSchema qw(get_standard_option);
 use base qw(PVE::RESTHandler);
 
 use Data::Dumper; # fixme: remove
 
-my $get_container_storage = sub {
-    my ($stcfg, $vmid, $lxc_conf) = @_;
-
-    my $path = $lxc_conf->{'lxc.rootfs'};
-    my ($vtype, $volid) = PVE::Storage::path_to_volume_id($stcfg, $path);
-    my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1) if $volid;
-    return wantarray ? ($sid, $volname, $path) : $sid;
-};
-
-my $check_ct_modify_config_perm = sub {
-    my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
-
-    return 1 if $authuser ne 'root@pam';
-
-    foreach my $opt (@$key_list) {
+__PACKAGE__->register_method ({
+    subclass => "PVE::API2::LXC::Config",
+    path => '{vmid}/config',                         
+});
 
-       if ($opt eq 'cpus' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
-           $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
-       } elsif ($opt eq 'disk') {
-           $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
-       } elsif ($opt eq 'memory' || $opt eq 'swap') {
-           $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
-       } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
-                $opt eq 'searchdomain' || $opt eq 'hostname') {
-           $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
-       } else {
-           $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
-       }
-    }
+__PACKAGE__->register_method ({
+    subclass => "PVE::API2::LXC::Status",
+    path => '{vmid}/status',
+});
 
-    return 1;
-};
+__PACKAGE__->register_method ({
+    subclass => "PVE::API2::LXC::Snapshot",
+    path => '{vmid}/snapshot',
+});
 
+__PACKAGE__->register_method ({
+    subclass => "PVE::API2::Firewall::CT",
+    path => '{vmid}/firewall',
+});
 
 __PACKAGE__->register_method({
     name => 'vmlist',
@@ -116,21 +108,24 @@ __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,
                type => 'string',
                description => "Sets root password inside container.",
+               minLength => 5,
            },
            storage => get_standard_option('pve-storage-id', {
-               description => "Target storage.",
+               description => "Default Storage.",
                default => 'local',
                optional => 1,
+               completion => \&PVE::Storage::complete_storage_enabled,
            }),
            force => {
                optional => 1,
@@ -169,27 +164,24 @@ __PACKAGE__->register_method({
 
        my $restore = extract_param($param, 'restore');
 
+       if ($restore) {
+           # fixme: limit allowed parameters
+
+       }
+       
        my $force = extract_param($param, 'force');
 
        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 $pool = extract_param($param, 'pool');
 
-       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}->{rootdir};
-
-       my $private = PVE::Storage::get_private_dir($storage_cfg, $storage, $vmid);
-
        if (defined($pool)) {
            $rpcenv->check_pool_exist($pool);
            $rpcenv->check_perm_modify($authuser, "/pool/$pool");
@@ -206,175 +198,125 @@ __PACKAGE__->register_method({
            raise_perm_exc();
        }
 
-       &$check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
+       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');
 
        my $archive;
 
        if ($ostemplate eq '-') {
-           die "archive pipe not implemented\n"
-           # $archive = '-';
+           die "pipe requires cli environment\n" 
+               if $rpcenv->{type} ne 'cli'; 
+           die "pipe can only be used with restore tasks\n" 
+               if !$restore;
+           $archive = '-';
+           die "restore from pipe requires rootfs parameter\n" if !defined($param->{rootfs});
        } else {
            $rpcenv->check_volume_access($authuser, $storage_cfg, $vmid, $ostemplate);
            $archive = PVE::Storage::abs_filesystem_path($storage_cfg, $ostemplate);
        }
 
-       my $memory = $param->{memory} || 512;
-       my $hostname = $param->{hostname} || "T$vmid";
-       my $conf = {};
+       my $check_and_activate_storage = sub {
+           my ($sid) = @_;
 
-       $conf->{'lxc.utsname'} = $param->{hostname} || "CT$vmid";
-       $conf->{'lxc.cgroup.memory.limit_in_bytes'} = "${memory}M";
+           my $scfg = PVE::Storage::storage_check_node($storage_cfg, $sid, $node);
 
-       my $code = sub {
-           my $temp_conf_fn = PVE::LXC::write_temp_config($vmid, $conf);
+           raise_param_exc({ storage => "storage '$sid' does not support container directories"})
+               if !$scfg->{content}->{rootdir};
 
-           my $cmd = ['lxc-create', '-f', $temp_conf_fn, '-t', 'pve', '-n', $vmid,
-                      '--', '--archive', $archive];
+           $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
 
-           eval { PVE::Tools::run_command($cmd); };
-           my $err = $@;
-
-           unlink $temp_conf_fn;
-
-           die $err if $err;
+           PVE::Storage::activate_storage($storage_cfg, $sid);
        };
 
-       my $realcmd = sub { PVE::LXC::lock_container($vmid, 1, $code); };
-
-       return $rpcenv->fork_worker($param->{restore} ? 'vzrestore' : 'vzcreate',
-                                   $vmid, $authuser, $realcmd);
-
-    }});
-
-my $vm_config_perm_list = [
-           'VM.Config.Disk',
-           'VM.Config.CPU',
-           'VM.Config.Memory',
-           'VM.Config.Network',
-           'VM.Config.Options',
-    ];
-
-__PACKAGE__->register_method({
-    name => 'update_vm',
-    path => '{vmid}/config',
-    method => 'PUT',
-    protected => 1,
-    proxyto => 'node',
-    description => "Set container options.",
-    permissions => {
-       check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
-    },
-    parameters => {
-       additionalProperties => 0,
-       properties => PVE::LXC::json_config_properties(
-           {
-               node => get_standard_option('pve-node'),
-               vmid => get_standard_option('pve-vmid'),
-               delete => {
-                   type => 'string', format => 'pve-configid-list',
-                   description => "A list of settings you want to delete.",
-                   optional => 1,
-               },
-               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 => 'null'},
-    code => sub {
-       my ($param) = @_;
-
-       my $rpcenv = PVE::RPCEnvironment::get();
-
-       my $authuser = $rpcenv->get_user();
+       my $conf = {};
 
-       my $node = extract_param($param, 'node');
+       my $no_disk_param = {};
+       foreach my $opt (keys %$param) {
+           my $value = $param->{$opt};
+           if ($opt eq 'rootfs' || $opt =~ m/^mp\d+$/) {
+               # allow to use simple numbers (add default storage in that case)
+               $param->{$opt} = "$storage:$value" if $value =~ m/^\d+(\.\d+)?$/;
+           } else {
+               $no_disk_param->{$opt} = $value;
+           }
+       }
 
-       my $vmid = extract_param($param, 'vmid');
+       # check storage access, activate storage
+       PVE::LXC::foreach_mountpoint($param, sub {
+           my ($ms, $mountpoint) = @_;
 
-       my $digest = extract_param($param, 'digest');
+           my $volid = $mountpoint->{volume};
+           my $mp = $mountpoint->{mp};
 
-       die "no options specified\n" if !scalar(keys %$param);
+           my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
 
-       my $delete_str = extract_param($param, 'delete');
-       my @delete = PVE::Tools::split_list($delete_str);
+           &$check_and_activate_storage($sid) if $sid;
+       });
 
-       &$check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, [@delete]);
+       # check/activate default storage
+       &$check_and_activate_storage($storage) if !defined($param->{rootfs});
 
-       foreach my $opt (@delete) {
-           raise_param_exc({ delete => "you can't use '-$opt' and " .
-                                 "-delete $opt' at the same time" })
-               if defined($param->{$opt});
+       PVE::LXC::update_pct_config($vmid, $conf, 0, $no_disk_param);
 
-           if (!PVE::LXC::option_exists($opt)) {
-               raise_param_exc({ delete => "unknown option '$opt'" });
+       my $check_vmid_usage = sub {
+           if ($force) {
+               die "can't overwrite running container\n"
+                   if PVE::LXC::check_running($vmid);
+           } else {
+               PVE::Cluster::check_vmid_unused($vmid);
            }
-       }
-
-       &$check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
+       };
 
        my $code = sub {
+           &$check_vmid_usage(); # final check after locking
+                   
+           PVE::Cluster::check_cfs_quorum();
+           my $vollist = [];
+
+           eval {
+               if (!defined($param->{rootfs})) {
+                   if ($restore) {
+                       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
+                   }
+               }
 
-           my $conf = PVE::LXC::load_config($vmid);
+               $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $param, $conf);
 
-           PVE::Tools::assert_if_modified($digest, $conf->{digest});
-
-           # die if running
-
-           foreach my $opt (@delete) {
-               if ($opt eq 'hostname' || $opt eq 'memory') {
-                   die "unable to delete required option '$opt'\n";
-               } elsif ($opt eq 'swap') {
-                   delete $conf->{'lxc.cgroup.memory.memsw.usage_in_bytes'};
-               } elsif ($opt eq 'description') {
-                   delete $conf->{'pve.comment'};
-               } elsif ($opt =~ m/^net\d$/) {
-                   delete $conf->{$opt};
-               } else {
-                   die "implement me"
-               }
+               PVE::LXC::Create::create_rootfs($storage_cfg, $vmid, $conf, $archive, $password, $restore);
+               # set some defaults
+               $conf->{hostname} ||= "CT$vmid";
+               $conf->{memory} ||= 512;
+               $conf->{swap} //= 512;
+               PVE::LXC::create_config($vmid, $conf);
+           };
+           if (my $err = $@) {
+               PVE::LXC::destroy_disks($storage_cfg, $vollist);
+               PVE::LXC::destroy_config($vmid);
+               die $err;
            }
+           PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
+       };
 
-           foreach my $opt (keys %$param) {
-               my $value = $param->{$opt};
-               if ($opt eq 'hostname') {
-                   $conf->{'lxc.utsname'} = $value;
-               } elsif ($opt eq 'memory') {
-                   $conf->{'lxc.cgroup.memory.limit_in_bytes'} = $value*1024*1024;
-               } elsif ($opt eq 'swap') {
-                   $conf->{'lxc.cgroup.memory.memsw.usage_in_bytes'} = $value*1024*1024;
-               } elsif ($opt eq 'description') {
-                   $conf->{'pve.comment'} = PVE::Tools::encode_text($value);
-               } elsif ($opt =~ m/^net(\d+)$/) {
-                   my $netid = $1;
-                   my $net = PVE::LXC::parse_lxc_network($value);
-                   $net->{'veth.pair'} = "veth${vmid}.$netid";
-                   $conf->{$opt} = $net;
-               } else {
-                   die "implement me"
-               }
-           }
+       my $realcmd = sub { PVE::LXC::lock_container($vmid, 1, $code); };
 
-           PVE::LXC::write_config($vmid, $conf);
-       };
+       &$check_vmid_usage(); # first check before locking
 
-       PVE::LXC::lock_container($vmid, undef, $code);
+       return $rpcenv->fork_worker($restore ? 'vzrestore' : 'vzcreate',
+                                   $vmid, $authuser, $realcmd);
 
-       return undef;
     }});
 
-__PACKAGE__->register_method ({
-    subclass => "PVE::API2::Firewall::CT",
-    path => '{vmid}/firewall',
-});
-
 __PACKAGE__->register_method({
     name => 'vmdiridx',
     path => '{vmid}',
@@ -418,6 +360,8 @@ __PACKAGE__->register_method({
            { subdir => 'rrd' },
            { subdir => 'rrddata' },
            { subdir => 'firewall' },
+           { subdir => 'snapshot' },
+           { subdir => 'resize' },
            ];
 
        return $res;
@@ -510,74 +454,6 @@ __PACKAGE__->register_method({
            "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
     }});
 
-
-__PACKAGE__->register_method({
-    name => 'vm_config',
-    path => '{vmid}/config',
-    method => 'GET',
-    proxyto => 'node',
-    description => "Get container configuration.",
-    permissions => {
-       check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
-    },
-    parameters => {
-       additionalProperties => 0,
-       properties => {
-           node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
-       },
-    },
-    returns => {
-       type => "object",
-       properties => {
-           digest => {
-               type => 'string',
-               description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
-           }
-       },
-    },
-    code => sub {
-       my ($param) = @_;
-
-       my $lxc_conf = PVE::LXC::load_config($param->{vmid});
-
-       # NOTE: we only return selected/converted values
-
-       my $conf = { digest => $lxc_conf->{digest} };
-
-       my $stcfg = PVE::Cluster::cfs_read_file("storage.cfg");
-
-       my ($sid, undef, $path) = &$get_container_storage($stcfg, $param->{vmid}, $lxc_conf);
-       $conf->{storage} = $sid || $path;
-
-       my $properties = PVE::LXC::json_config_properties();
-
-       foreach my $k (keys %$properties) {
-
-           if ($k eq 'description') {
-               if (my $raw = $lxc_conf->{'pve.comment'}) {
-                   $conf->{$k} = PVE::Tools::decode_text($raw);
-               }
-           } elsif ($k eq 'hostname') {
-               $conf->{$k} = $lxc_conf->{'lxc.utsname'} if $lxc_conf->{'lxc.utsname'};
-           } elsif ($k eq 'memory') {
-               if (my $value = $lxc_conf->{'lxc.cgroup.memory.limit_in_bytes'}) {
-                   $conf->{$k} = int($value / (1024*1024));
-               }
-           } elsif ($k eq 'swap') {
-               if (my $value = $lxc_conf->{'lxc.cgroup.memory.memsw.usage_in_bytes'}) {
-                   $conf->{$k} = int($value / (1024*1024));
-               }
-           } elsif ($k =~ m/^net\d$/) {
-               my $net = $lxc_conf->{$k};
-               next if !$net;
-               $conf->{$k} = PVE::LXC::print_lxc_network($net);
-           }
-       }
-
-       return $conf;
-    }});
-
 __PACKAGE__->register_method({
     name => 'destroy_vm',
     path => '{vmid}',
@@ -592,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 => {
@@ -608,24 +484,41 @@ __PACKAGE__->register_method({
        my $vmid = $param->{vmid};
 
        # test if container exists
-       my $conf = PVE::LXC::load_config($param->{vmid});
+       my $conf = PVE::LXC::load_config($vmid);
 
-       my $realcmd = sub {
-           my $cmd = ['lxc-destroy', '-n', $vmid ];
+       my $storage_cfg = cfs_read_file("storage.cfg");
 
-           run_command($cmd);
+       PVE::LXC::check_protection($conf, "can't remove CT $vmid");
 
-           PVE::AccessControl::remove_vm_from_pool($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);
        };
 
+       my $realcmd = sub { PVE::LXC::lock_container($vmid, 1, $code); };
+       
        return $rpcenv->fork_worker('vzdestroy', $vmid, $authuser, $realcmd);
     }});
 
 my $sslcert;
 
 __PACKAGE__->register_method ({
-    name => 'vncproxy', 
-    path => '{vmid}/vncproxy', 
+    name => 'vncproxy',
+    path => '{vmid}/vncproxy',
     method => 'POST',
     protected => 1,
     permissions => {
@@ -644,7 +537,7 @@ __PACKAGE__->register_method ({
            },
        },
     },
-    returns => { 
+    returns => {
        additionalProperties => 0,
        properties => {
            user => { type => 'string' },
@@ -671,37 +564,41 @@ __PACKAGE__->register_method ({
        $sslcert = PVE::Tools::file_get_contents("/etc/pve/pve-root-ca.pem", 8192)
            if !$sslcert;
 
-       my $port = PVE::Tools::next_vnc_port();
+       my ($remip, $family);
 
-       my $remip;
-       
        if ($node ne PVE::INotify::nodename()) {
-           $remip = PVE::Cluster::remote_node_ip($node);
+           ($remip, $family) = PVE::Cluster::remote_node_ip($node);
+       } else {
+           $family = PVE::Tools::get_host_address_family($node);
        }
 
+       my $port = PVE::Tools::next_vnc_port($family);
+
        # NOTE: vncterm VNC traffic is already TLS encrypted,
        # so we select the fastest chipher here (or 'none'?)
-       my $remcmd = $remip ? 
+       my $remcmd = $remip ?
            ['/usr/bin/ssh', '-t', $remip] : [];
 
-       my $shcmd = [ '/usr/bin/dtach', '-A', 
-                     "/var/run/dtach/vzctlconsole$vmid", 
-                     '-r', 'winch', '-z', 
-                     'lxc-console', '-n', $vmid ];
+       my $conf = PVE::LXC::load_config($vmid, $node);
+       my $concmd = PVE::LXC::get_console_command($vmid, $conf);
+
+       my $shcmd = [ '/usr/bin/dtach', '-A',
+                     "/var/run/dtach/vzctlconsole$vmid",
+                     '-r', 'winch', '-z', @$concmd];
 
        my $realcmd = sub {
            my $upid = shift;
 
-           syslog ('info', "starting openvz vnc proxy $upid\n");
+           syslog ('info', "starting lxc vnc proxy $upid\n");
 
-           my $timeout = 10; 
+           my $timeout = 10;
 
            my $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
-                      '-timeout', $timeout, '-authpath', $authpath, 
+                      '-timeout', $timeout, '-authpath', $authpath,
                       '-perm', 'VM.Console'];
 
            if ($param->{websocket}) {
-               $ENV{PVE_VNC_TICKET} = $ticket; # pass ticket to vncterm 
+               $ENV{PVE_VNC_TICKET} = $ticket; # pass ticket to vncterm
                push @$cmd, '-notls', '-listen', 'localhost';
            }
 
@@ -719,9 +616,9 @@ __PACKAGE__->register_method ({
        return {
            user => $authuser,
            ticket => $ticket,
-           port => $port, 
-           upid => $upid, 
-           cert => $sslcert, 
+           port => $port,
+           upid => $upid,
+           cert => $sslcert,
        };
     }});
 
@@ -729,7 +626,7 @@ __PACKAGE__->register_method({
     name => 'vncwebsocket',
     path => '{vmid}/vncwebsocket',
     method => 'GET',
-    permissions => { 
+    permissions => {
        description => "You also need to pass a valid ticket (vncticket).",
        check => ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
     },
@@ -770,13 +667,13 @@ __PACKAGE__->register_method({
        PVE::AccessControl::verify_vnc_ticket($param->{vncticket}, $authuser, $authpath);
 
        my $port = $param->{port};
-       
+
        return { port => $port };
     }});
 
 __PACKAGE__->register_method ({
-    name => 'spiceproxy', 
-    path => '{vmid}/spiceproxy', 
+    name => 'spiceproxy',
+    path => '{vmid}/spiceproxy',
     method => 'POST',
     protected => 1,
     proxyto => 'node',
@@ -803,110 +700,51 @@ __PACKAGE__->register_method ({
        my $authpath = "/vms/$vmid";
        my $permissions = 'VM.Console';
 
-       my $shcmd = ['/usr/bin/dtach', '-A', 
-                    "/var/run/dtach/vzctlconsole$vmid", 
-                    '-r', 'winch', '-z', 
-                    'lxc-console', '-n', $vmid];
+       my $conf = PVE::LXC::load_config($vmid);
 
-       my $title = "CT $vmid";
+       die "CT $vmid not running\n" if !PVE::LXC::check_running($vmid);
 
-       return PVE::API2Tools::run_spiceterm($authpath, $permissions, $vmid, $node, $proxy, $title, $shcmd);
-    }});
+       my $concmd = PVE::LXC::get_console_command($vmid, $conf);
 
-__PACKAGE__->register_method({
-    name => 'vmcmdidx',
-    path => '{vmid}/status',
-    method => 'GET',
-    proxyto => 'node',
-    description => "Directory index",
-    permissions => {
-       user => 'all',
-    },
-    parameters => {
-       additionalProperties => 0,
-       properties => {
-           node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
-       },
-    },
-    returns => {
-       type => 'array',
-       items => {
-           type => "object",
-           properties => {
-               subdir => { type => 'string' },
-           },
-       },
-       links => [ { rel => 'child', href => "{subdir}" } ],
-    },
-    code => sub {
-       my ($param) = @_;
-
-       # test if VM exists
-       my $conf = PVE::OpenVZ::load_config($param->{vmid});
+       my $shcmd = ['/usr/bin/dtach', '-A',
+                    "/var/run/dtach/vzctlconsole$vmid",
+                    '-r', 'winch', '-z', @$concmd];
 
-       my $res = [
-           { subdir => 'current' },
-           { subdir => 'start' },
-           { subdir => 'stop' },
-           { subdir => 'shutdown' },
-           { subdir => 'migrate' },
-           ];
+       my $title = "CT $vmid";
 
-       return $res;
+       return PVE::API2Tools::run_spiceterm($authpath, $permissions, $vmid, $node, $proxy, $title, $shcmd);
     }});
 
-__PACKAGE__->register_method({
-    name => 'vm_status',
-    path => '{vmid}/status/current',
-    method => 'GET',
-    proxyto => 'node',
-    protected => 1, # openvz /proc entries are only readable by root
-    description => "Get virtual machine status.",
-    permissions => {
-       check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
-    },
-    parameters => {
-       additionalProperties => 0,
-       properties => {
-           node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
-       },
-    },
-    returns => { type => 'object' },
-    code => sub {
-       my ($param) = @_;
-
-       # test if VM exists
-       my $conf = PVE::LXC::load_config($param->{vmid});
-
-       my $vmstatus =  PVE::LXC::vmstatus($param->{vmid});
-       my $status = $vmstatus->{$param->{vmid}};
-
-       $status->{ha} = PVE::HA::Config::vm_is_ha_managed($param->{vmid}) ? 1 : 0;
-
-       return $status;
-    }});
 
 __PACKAGE__->register_method({
-    name => 'vm_start',
-    path => '{vmid}/status/start',
+    name => 'migrate_vm',
+    path => '{vmid}/migrate',
     method => 'POST',
     protected => 1,
     proxyto => 'node',
-    description => "Start the container.",
+    description => "Migrate the container to another node. Creates a new migration task.",
     permissions => {
-       check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
+       check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
     },
     parameters => {
        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 }),
+           target => get_standard_option('pve-node', {
+               description => "Target node.",
+               completion => \&PVE::Cluster::complete_migration_target,
+           }),
+           online => {
+               type => 'boolean',
+               description => "Use online/live migration.",
+               optional => 1,
+           },
        },
     },
     returns => {
        type => 'string',
+       description => "the task ID.",
     },
     code => sub {
        my ($param) = @_;
@@ -915,11 +753,27 @@ __PACKAGE__->register_method({
 
        my $authuser = $rpcenv->get_user();
 
-       my $node = extract_param($param, 'node');
+       my $target = extract_param($param, 'target');
+
+       my $localnode = PVE::INotify::nodename();
+       raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
+
+       PVE::Cluster::check_cfs_quorum();
+
+       PVE::Cluster::check_node_exists($target);
+
+       my $targetip = PVE::Cluster::remote_node_ip($target);
 
        my $vmid = extract_param($param, 'vmid');
 
-       die "CT $vmid already running\n" if PVE::LXC::check_running($vmid);
+       # test if VM exists
+       PVE::LXC::load_config($vmid);
+
+       # try to detect errors early
+       if (PVE::LXC::check_running($vmid)) {
+           die "can't migrate running container without --online\n"
+               if !$param->{online};
+       }
 
        if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
 
@@ -928,143 +782,114 @@ __PACKAGE__->register_method({
 
                my $service = "ct:$vmid";
 
-               my $cmd = ['ha-manager', 'enable', $service];
+               my $cmd = ['ha-manager', 'migrate', $service, $target];
 
-               print "Executing HA start for CT $vmid\n";
+               print "Executing HA migrate for CT $vmid to node $target\n";
 
                PVE::Tools::run_command($cmd);
 
                return;
            };
 
-           return $rpcenv->fork_worker('hastart', $vmid, $authuser, $hacmd);
+           return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
 
        } else {
 
            my $realcmd = sub {
                my $upid = shift;
 
-               syslog('info', "starting CT $vmid: $upid\n");
-
-               my $conf = PVE::LXC::load_config($vmid);
-               my $stcfg = cfs_read_file("storage.cfg");
-               if (my $sid = &$get_container_storage($stcfg, $vmid, $conf)) {
-                   PVE::Storage::activate_storage($stcfg, $sid);
-               }
-
-               my $cmd = ['lxc-start', '-n', $vmid];
-
-               run_command($cmd);
+               PVE::LXC::Migrate->migrate($target, $targetip, $vmid, $param);
 
                return;
            };
 
-           return $rpcenv->fork_worker('vzstart', $vmid, $authuser, $realcmd);
+           return $rpcenv->fork_worker('vzmigrate', $vmid, $authuser, $realcmd);
        }
     }});
 
 __PACKAGE__->register_method({
-    name => 'vm_stop',
-    path => '{vmid}/status/stop',
-    method => 'POST',
-    protected => 1,
+    name => 'vm_feature',
+    path => '{vmid}/feature',
+    method => 'GET',
     proxyto => 'node',
-    description => "Stop the container.",
+    protected => 1,
+    description => "Check if feature for virtual machine is available.",
     permissions => {
-       check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
+       check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
     },
     parameters => {
-       additionalProperties => 0,
+       additionalProperties => 0,
        properties => {
            node => get_standard_option('pve-node'),
            vmid => get_standard_option('pve-vmid'),
+            feature => {
+                description => "Feature to check.",
+                type => 'string',
+                enum => [ 'snapshot' ],
+            },
+            snapname => get_standard_option('pve-lxc-snapshot-name', {
+                optional => 1,
+            }),
        },
     },
     returns => {
-       type => 'string',
+       type => "object",
+       properties => {
+           hasFeature => { type => 'boolean' },
+           #nodes => {
+               #type => 'array',
+               #items => { type => 'string' },
+           #}
+       },
     },
     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');
 
-       die "CT $vmid not running\n" if !PVE::LXC::check_running($vmid);
-
-       if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
-
-           my $hacmd = sub {
-               my $upid = shift;
-
-               my $service = "ct:$vmid";
-
-               my $cmd = ['ha-manager', 'disable', $service];
-
-               print "Executing HA stop for CT $vmid\n";
-
-               PVE::Tools::run_command($cmd);
-
-               return;
-           };
-
-           return $rpcenv->fork_worker('hastop', $vmid, $authuser, $hacmd);
+       my $snapname = extract_param($param, 'snapname');
 
-       } else {
-
-           my $realcmd = sub {
-               my $upid = shift;
+       my $feature = extract_param($param, 'feature');
 
-               syslog('info', "stoping CT $vmid: $upid\n");
+       my $conf = PVE::LXC::load_config($vmid);
 
-               my $cmd = ['lxc-stop', '-n', $vmid, '--kill'];
-
-               run_command($cmd);
-
-               return;
-           };
-
-           return $rpcenv->fork_worker('vzstop', $vmid, $authuser, $realcmd);
+       if($snapname){
+           my $snap = $conf->{snapshots}->{$snapname};
+           die "snapshot '$snapname' does not exist\n" if !defined($snap);
+           $conf = $snap;
        }
+       my $storage_cfg = PVE::Storage::config();
+       #Maybe include later
+       #my $nodelist = PVE::LXC::shared_nodes($conf, $storage_cfg);
+       my $hasFeature = PVE::LXC::has_feature($feature, $conf, $storage_cfg, $snapname);
+
+       return {
+           hasFeature => $hasFeature,
+           #nodes => [ keys %$nodelist ],
+       };
     }});
 
 __PACKAGE__->register_method({
-    name => 'vm_shutdown',
-    path => '{vmid}/status/shutdown',
+    name => 'template',
+    path => '{vmid}/template',
     method => 'POST',
     protected => 1,
     proxyto => 'node',
-    description => "Shutdown the container.",
+    description => "Create a Template.",
     permissions => {
-       check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
+       description => "You need 'VM.Allocate' permissions on /vms/{vmid}",
+       check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
     },
     parameters => {
-       additionalProperties => 0,
+       additionalProperties => 0,
        properties => {
            node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
-           timeout => {
-               description => "Wait maximal timeout seconds.",
-               type => 'integer',
-               minimum => 0,
-               optional => 1,
-               default => 60,
-           },
-           forceStop => {
-               description => "Make sure the Container stops.",
-               type => 'boolean',
-               optional => 1,
-               default => 0,
-           }
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
        },
     },
-    returns => {
-       type => 'string',
-    },
+    returns => { type => 'null'},
     code => sub {
        my ($param) = @_;
 
@@ -1076,163 +901,71 @@ __PACKAGE__->register_method({
 
        my $vmid = extract_param($param, 'vmid');
 
-       my $timeout = extract_param($param, 'timeout');
+       my $updatefn =  sub {
 
-       die "CT $vmid not running\n" if !PVE::LXC::check_running($vmid);
-
-       my $realcmd = sub {
-           my $upid = shift;
-
-           syslog('info', "shutdown CT $vmid: $upid\n");
-
-           my $cmd = ['lxc-stop', '-n', $vmid];
+           my $conf = PVE::LXC::load_config($vmid);
+           PVE::LXC::check_lock($conf);
 
-           $timeout = 60 if !defined($timeout);
+           die "unable to create template, because CT contains snapshots\n"
+               if $conf->{snapshots} && scalar(keys %{$conf->{snapshots}});
 
-           push @$cmd, '--timeout', $timeout;
+           die "you can't convert a template to a template\n"
+               if PVE::LXC::is_template($conf);
 
-           eval { run_command($cmd, timeout => $timeout+5); };
-           my $err = $@;
-           return if !$err;
+           die "you can't convert a CT to template if the CT is running\n"
+               if PVE::LXC::check_running($vmid);
 
-           die $err if !$param->{forceStop};
+           my $realcmd = sub {
+               PVE::LXC::template_create($vmid, $conf);
+           };
 
-           warn "shutdown failed - forcing stop now\n";
+           $conf->{template} = 1;
 
-           push @$cmd, '--kill';
-           run_command($cmd);
+           PVE::LXC::write_config($vmid, $conf);
+           # and remove lxc config
+           PVE::LXC::update_lxc_config(undef, $vmid, $conf);
 
-           return;
+           return $rpcenv->fork_worker('vztemplate', $vmid, $authuser, $realcmd);
        };
 
-       my $upid = $rpcenv->fork_worker('vzshutdown', $vmid, $authuser, $realcmd);
-
-       return $upid;
-    }});
-
-__PACKAGE__->register_method({
-    name => 'vm_suspend',
-    path => '{vmid}/status/suspend',
-    method => 'POST',
-    protected => 1,
-    proxyto => 'node',
-    description => "Suspend the container.",
-    permissions => {
-        check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
-    },
-    parameters => {
-        additionalProperties => 0,
-        properties => {
-            node => get_standard_option('pve-node'),
-            vmid => get_standard_option('pve-vmid'),
-        },
-    },
-    returns => {
-        type => 'string',
-    },
-    code => sub {
-        my ($param) = @_;
-
-        my $rpcenv = PVE::RPCEnvironment::get();
-
-        my $authuser = $rpcenv->get_user();
+       PVE::LXC::lock_container($vmid, undef, $updatefn);
 
-        my $node = extract_param($param, 'node');
-
-        my $vmid = extract_param($param, 'vmid');
-
-        die "CT $vmid not running\n" if !PVE::LXC::check_running($vmid);
-
-        my $realcmd = sub {
-            my $upid = shift;
-
-            syslog('info', "suspend CT $vmid: $upid\n");
-
-           my $cmd = ['lxc-checkpoint', '-n', $vmid, '-s', '-D', '/var/liv/vz/dump'];
-
-           run_command($cmd);
-
-            return;
-        };
-
-        my $upid = $rpcenv->fork_worker('vzsuspend', $vmid, $authuser, $realcmd);
-
-        return $upid;
-    }});
-
-__PACKAGE__->register_method({
-    name => 'vm_resume',
-    path => '{vmid}/status/resume',
-    method => 'POST',
-    protected => 1,
-    proxyto => 'node',
-    description => "Resume the container.",
-    permissions => {
-        check => ['perm', '/vms/{vmid}', [ 'VM.PowerMgmt' ]],
-    },
-    parameters => {
-        additionalProperties => 0,
-        properties => {
-            node => get_standard_option('pve-node'),
-            vmid => get_standard_option('pve-vmid'),
-        },
-    },
-    returns => {
-        type => 'string',
-    },
-    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');
-
-        die "CT $vmid already running\n" if PVE::LXC::check_running($vmid);
-
-        my $realcmd = sub {
-            my $upid = shift;
-
-            syslog('info', "resume CT $vmid: $upid\n");
-
-           my $cmd = ['lxc-checkpoint', '-n', $vmid, '-r', '--foreground',
-                      '-D', '/var/liv/vz/dump'];
-
-           run_command($cmd);
-
-            return;
-        };
-
-        my $upid = $rpcenv->fork_worker('vzresume', $vmid, $authuser, $realcmd);
-
-        return $upid;
+       return undef;
     }});
 
 __PACKAGE__->register_method({
-    name => 'migrate_vm',
-    path => '{vmid}/migrate',
-    method => 'POST',
+    name => 'resize_vm',
+    path => '{vmid}/resize',
+    method => 'PUT',
     protected => 1,
     proxyto => 'node',
-    description => "Migrate the container to another node. Creates a new migration task.",
+    description => "Resize a container mountpoint.",
     permissions => {
-       check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
+       check => ['perm', '/vms/{vmid}', ['VM.Config.Disk'], any => 1],
     },
     parameters => {
-       additionalProperties => 0,
-       properties => {
-           node => get_standard_option('pve-node'),
-           vmid => get_standard_option('pve-vmid'),
-           target => get_standard_option('pve-node', { description => "Target node." }),
-           online => {
-               type => 'boolean',
-               description => "Use online/live migration.",
-               optional => 1,
-           },
-       },
+       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',
@@ -1245,59 +978,113 @@ __PACKAGE__->register_method({
 
        my $authuser = $rpcenv->get_user();
 
-       my $target = extract_param($param, 'target');
+       my $node = extract_param($param, 'node');
 
-       my $localnode = PVE::INotify::nodename();
-       raise_param_exc({ target => "target is local node."}) if $target eq $localnode;
+       my $vmid = extract_param($param, 'vmid');
 
-       PVE::Cluster::check_cfs_quorum();
+       my $digest = extract_param($param, 'digest');
 
-       PVE::Cluster::check_node_exists($target);
+       my $sizestr = extract_param($param, 'size');
+       my $ext = ($sizestr =~ s/^\+//);
+       my $newsize = PVE::JSONSchema::parse_size($sizestr);
+       die "invalid size string" if !defined($newsize);
 
-       my $targetip = PVE::Cluster::remote_node_ip($target);
+       die "no options specified\n" if !scalar(keys %$param);
 
-       my $vmid = extract_param($param, 'vmid');
+       PVE::LXC::check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
 
-       # test if VM exists
-       PVE::LXC::load_config($vmid);
+       my $storage_cfg = cfs_read_file("storage.cfg");
 
-       # try to detect errors early
-       if (PVE::LXC::check_running($vmid)) {
-           die "cant migrate running container without --online\n"
-               if !$param->{online};
-       }
+       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;
+       };
 
-       if (PVE::HA::Config::vm_is_ha_managed($vmid) && $rpcenv->{type} ne 'ha') {
+       my $code = sub {
 
-           my $hacmd = sub {
-               my $upid = shift;
+           my $conf = PVE::LXC::load_config($vmid);
+           PVE::LXC::check_lock($conf);
 
-               my $service = "ct:$vmid";
+           PVE::Tools::assert_if_modified($digest, $conf->{digest});
 
-               my $cmd = ['ha-manager', 'migrate', $service, $target];
+           my $running = PVE::LXC::check_running($vmid);
 
-               print "Executing HA migrate for CT $vmid to node $target\n";
+           my $disk = $param->{disk};
+           my $mp = PVE::LXC::parse_ct_mountpoint($conf->{$disk});
+           my $volid = $mp->{volume};
 
-               PVE::Tools::run_command($cmd);
+           my (undef, undef, $owner, undef, undef, undef, $format) =
+               PVE::Storage::parse_volname($storage_cfg, $volid);
 
-               return;
-           };
+           die "can't resize mountpoint owned by another container ($owner)"
+               if $vmid != $owner;
 
-           return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
+           die "can't resize volume: $disk if snapshot exists\n"
+               if %{$conf->{snapshots}} && $format eq 'qcow2';
 
-       } else {
+           my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
 
-           my $realcmd = sub {
-               my $upid = shift;
+           $rpcenv->check($authuser, "/storage/$storeid", ['Datastore.AllocateSpace']);
 
-               # fixme: implement lxc container migration
-               die "lxc container migration not implemented\n";
+           my $size = PVE::Storage::volume_size_info($storage_cfg, $volid, 5);
+           $newsize += $size if $ext;
+           $newsize = int($newsize);
 
-               return;
+           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('vzmigrate', $vmid, $authuser, $realcmd);
-       }
+           return $rpcenv->fork_worker('resize', $vmid, $authuser, $realcmd);
+       };
+
+       return PVE::LXC::lock_container($vmid, undef, $code);;
     }});
 
 1;