]> git.proxmox.com Git - pve-container.git/blobdiff - src/PVE/API2/LXC.pm
use empty config to reserve container ID
[pve-container.git] / src / PVE / API2 / LXC.pm
index 7ed778b3af99160484f0ce55b7669568654d814d..1dd94052bd3900722bbb02d452634c246d92289a 100644 (file)
@@ -314,7 +314,22 @@ __PACKAGE__->register_method({
 
        my $code = sub {
            &$check_vmid_usage(); # final check after locking
-                   
+           my $old_conf;
+
+           my $config_fn = PVE::LXC::Config->config_file($vmid);
+           if (-f $config_fn) {
+               die "container exists" if !$restore; # just to be sure
+               $old_conf = PVE::LXC::Config->load_config($vmid);
+           } else {
+               eval {
+                   # try to create empty config on local node, we have an flock
+                   PVE::LXC::Config->write_config($vmid, {});
+               };
+
+               # another node was faster, abort
+               die "Could not reserve ID $vmid, already taken\n" if $@;
+           }
+
            PVE::Cluster::check_cfs_quorum();
            my $vollist = [];
 
@@ -355,10 +370,27 @@ __PACKAGE__->register_method({
 
                $vollist = PVE::LXC::create_disks($storage_cfg, $vmid, $mp_param, $conf);
 
+               if (defined($old_conf)) {
+                   # destroy old container volumes
+                   PVE::LXC::destroy_lxc_container($storage_cfg, $vmid, $old_conf, {});
+               }
+
+               eval {
+                   my $rootdir = PVE::LXC::mount_all($vmid, $storage_cfg, $conf, 1);
+                   PVE::LXC::Create::restore_archive($archive, $rootdir, $conf, $ignore_unpack_errors);
 
-               PVE::LXC::Create::create_rootfs($storage_cfg, $vmid, $conf,
-                                               $archive, $password, $restore,
-                                               $ignore_unpack_errors, $ssh_keys);
+                   if ($restore) {
+                       PVE::LXC::Create::restore_configuration($vmid, $rootdir, $conf);
+                   } else {
+                       my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir); # detect OS
+                       PVE::LXC::Config->write_config($vmid, $conf); # safe config (after OS detection)
+                       $lxc_setup->post_create_hook($password, $ssh_keys);
+                   }
+               };
+               my $err = $@;
+               PVE::LXC::umount_all($vmid, $storage_cfg, $conf, $err ? 1 : 0);
+               PVE::Storage::deactivate_volumes($storage_cfg, PVE::LXC::Config->get_vm_volumes($conf));
+               die $err if $err;
                # set some defaults
                $conf->{hostname} ||= "CT$vmid";
                $conf->{memory} ||= 512;