1 package PVE
::API2
::LXC
;
7 use PVE
::Tools
qw(extract_param run_command);
8 use PVE
::Exception
qw(raise raise_param_exc);
10 use PVE
::Cluster
qw(cfs_read_file);
11 use PVE
::AccessControl
;
15 use PVE
::RPCEnvironment
;
18 use PVE
::API2
::LXC
::Config
;
19 use PVE
::API2
::LXC
::Status
;
20 use PVE
::API2
::LXC
::Snapshot
;
22 use PVE
::JSONSchema
qw(get_standard_option);
23 use base
qw(PVE::RESTHandler);
25 use Data
::Dumper
; # fixme: remove
27 __PACKAGE__-
>register_method ({
28 subclass
=> "PVE::API2::LXC::Config",
29 path
=> '{vmid}/config',
32 __PACKAGE__-
>register_method ({
33 subclass
=> "PVE::API2::LXC::Status",
34 path
=> '{vmid}/status',
37 __PACKAGE__-
>register_method ({
38 subclass
=> "PVE::API2::LXC::Snapshot",
39 path
=> '{vmid}/snapshot',
42 __PACKAGE__-
>register_method ({
43 subclass
=> "PVE::API2::Firewall::CT",
44 path
=> '{vmid}/firewall',
47 my $destroy_disks = sub {
48 my ($storecfg, $vollist) = @_;
50 foreach my $volid (@$vollist) {
51 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
56 my $create_disks = sub {
57 my ($storecfg, $vmid, $settings, $conf) = @_;
62 PVE
::LXC
::foreach_mountpoint
($settings, sub {
63 my ($ms, $mountpoint) = @_;
65 my $volid = $mountpoint->{volume
};
66 my $mp = $mountpoint->{mp
};
68 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
72 if ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/) {
73 my ($storeid, $size) = ($1, $2);
75 $size = int($size*1024) * 1024;
77 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
78 # fixme: use better naming ct-$vmid-disk-X.raw?
80 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs') {
82 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
85 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
88 } elsif ($scfg->{type
} eq 'zfspool') {
90 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
92 } elsif ($scfg->{type
} eq 'drbd') {
94 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size);
96 } elsif ($scfg->{type
} eq 'rbd') {
98 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd
};
99 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size);
101 die "unable to create containers on storage type '$scfg->{type}'\n";
103 push @$vollist, $volid;
104 $conf->{$ms} = PVE
::LXC
::print_ct_mountpoint
({volume
=> $volid, size
=> $size, mp
=> $mp });
106 # use specified/existing volid
110 # free allocated images on error
112 syslog
('err', "VM $vmid creating disks failed");
113 &$destroy_disks($storecfg, $vollist);
119 __PACKAGE__-
>register_method({
123 description
=> "LXC container index (per node).",
125 description
=> "Only list CTs where you have VM.Audit permissons on /vms/<vmid>.",
129 protected
=> 1, # /proc files are only readable by root
131 additionalProperties
=> 0,
133 node
=> get_standard_option
('pve-node'),
142 links
=> [ { rel
=> 'child', href
=> "{vmid}" } ],
147 my $rpcenv = PVE
::RPCEnvironment
::get
();
148 my $authuser = $rpcenv->get_user();
150 my $vmstatus = PVE
::LXC
::vmstatus
();
153 foreach my $vmid (keys %$vmstatus) {
154 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
156 my $data = $vmstatus->{$vmid};
157 $data->{vmid
} = $vmid;
165 __PACKAGE__-
>register_method({
169 description
=> "Create or restore a container.",
171 user
=> 'all', # check inside
172 description
=> "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. " .
173 "For restore, it is enough if the user has 'VM.Backup' permission and the VM already exists. " .
174 "You also need 'Datastore.AllocateSpace' permissions on the storage.",
179 additionalProperties
=> 0,
180 properties
=> PVE
::LXC
::json_config_properties
({
181 node
=> get_standard_option
('pve-node'),
182 vmid
=> get_standard_option
('pve-vmid'),
184 description
=> "The OS template or backup file.",
191 description
=> "Sets root password inside container.",
194 storage
=> get_standard_option
('pve-storage-id', {
195 description
=> "Default Storage.",
202 description
=> "Allow to overwrite existing container.",
207 description
=> "Mark this as restore task.",
211 type
=> 'string', format
=> 'pve-poolid',
212 description
=> "Add the VM to the specified pool.",
222 my $rpcenv = PVE
::RPCEnvironment
::get
();
224 my $authuser = $rpcenv->get_user();
226 my $node = extract_param
($param, 'node');
228 my $vmid = extract_param
($param, 'vmid');
230 my $basecfg_fn = PVE
::LXC
::config_file
($vmid);
232 my $same_container_exists = -f
$basecfg_fn;
234 my $restore = extract_param
($param, 'restore');
237 # fixme: limit allowed parameters
241 my $force = extract_param
($param, 'force');
243 if (!($same_container_exists && $restore && $force)) {
244 PVE
::Cluster
::check_vmid_unused
($vmid);
247 my $password = extract_param
($param, 'password');
249 my $storage = extract_param
($param, 'storage') // 'local';
251 my $storage_cfg = cfs_read_file
("storage.cfg");
253 my $scfg = PVE
::Storage
::storage_check_node
($storage_cfg, $storage, $node);
255 raise_param_exc
({ storage
=> "storage '$storage' does not support container root directories"})
256 if !($scfg->{content
}->{images
} || $scfg->{content
}->{rootdir
});
258 my $pool = extract_param
($param, 'pool');
260 if (defined($pool)) {
261 $rpcenv->check_pool_exist($pool);
262 $rpcenv->check_perm_modify($authuser, "/pool/$pool");
265 $rpcenv->check($authuser, "/storage/$storage", ['Datastore.AllocateSpace']);
267 if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
269 } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
271 } elsif ($restore && $force && $same_container_exists &&
272 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
273 # OK: user has VM.Backup permissions, and want to restore an existing VM
278 PVE
::LXC
::check_ct_modify_config_perm
($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
280 PVE
::Storage
::activate_storage
($storage_cfg, $storage);
282 my $ostemplate = extract_param
($param, 'ostemplate');
286 if ($ostemplate eq '-') {
287 die "pipe requires cli environment\n"
288 if $rpcenv->{type
} ne 'cli';
289 die "pipe can only be used with restore tasks\n"
292 die "restore from pipe requires rootfs parameter\n" if !defined($param->{rootfs
});
294 $rpcenv->check_volume_access($authuser, $storage_cfg, $vmid, $ostemplate);
295 $archive = PVE
::Storage
::abs_filesystem_path
($storage_cfg, $ostemplate);
300 my $no_disk_param = {};
301 foreach my $opt (keys %$param) {
302 my $value = $param->{$opt};
303 if ($opt eq 'rootfs' || $opt =~ m/^mp\d+$/) {
304 # allow to use simple numbers (add default storage in that case)
305 $param->{$opt} = "$storage:$value" if $value =~ m/^\d+(\.\d+)?$/;
307 $no_disk_param->{$opt} = $value;
310 PVE
::LXC
::update_pct_config
($vmid, $conf, 0, $no_disk_param);
312 my $check_vmid_usage = sub {
314 die "can't overwrite running container\n"
315 if PVE
::LXC
::check_running
($vmid);
317 PVE
::Cluster
::check_vmid_unused
($vmid);
322 &$check_vmid_usage(); # final check after locking
324 PVE
::Cluster
::check_cfs_quorum
();
328 if (!defined($param->{rootfs
})) {
330 my (undef, $disksize) = PVE
::LXC
::Create
::recover_config
($archive);
331 die "unable to detect disk size - please specify rootfs (size)\n"
333 $param->{rootfs
} = "$storage:$disksize";
335 $param->{rootfs
} = "$storage:4"; # defaults to 4GB
339 $vollist = &$create_disks($storage_cfg, $vmid, $param, $conf);
341 PVE
::LXC
::Create
::create_rootfs
($storage_cfg, $vmid, $conf, $archive, $password, $restore);
343 $conf->{hostname
} ||= "CT$vmid";
344 $conf->{memory
} ||= 512;
345 $conf->{swap
} //= 512;
346 PVE
::LXC
::create_config
($vmid, $conf);
349 &$destroy_disks($storage_cfg, $vollist);
350 PVE
::LXC
::destroy_config
($vmid);
353 PVE
::AccessControl
::add_vm_to_pool
($vmid, $pool) if $pool;
356 my $realcmd = sub { PVE
::LXC
::lock_container
($vmid, 1, $code); };
358 &$check_vmid_usage(); # first check before locking
360 return $rpcenv->fork_worker($restore ?
'vzrestore' : 'vzcreate',
361 $vmid, $authuser, $realcmd);
365 __PACKAGE__-
>register_method({
370 description
=> "Directory index",
375 additionalProperties
=> 0,
377 node
=> get_standard_option
('pve-node'),
378 vmid
=> get_standard_option
('pve-vmid'),
386 subdir
=> { type
=> 'string' },
389 links
=> [ { rel
=> 'child', href
=> "{subdir}" } ],
395 my $conf = PVE
::LXC
::load_config
($param->{vmid
});
398 { subdir
=> 'config' },
399 { subdir
=> 'status' },
400 { subdir
=> 'vncproxy' },
401 { subdir
=> 'vncwebsocket' },
402 { subdir
=> 'spiceproxy' },
403 { subdir
=> 'migrate' },
404 # { subdir => 'initlog' },
406 { subdir
=> 'rrddata' },
407 { subdir
=> 'firewall' },
408 { subdir
=> 'snapshot' },
414 __PACKAGE__-
>register_method({
416 path
=> '{vmid}/rrd',
418 protected
=> 1, # fixme: can we avoid that?
420 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
422 description
=> "Read VM RRD statistics (returns PNG)",
424 additionalProperties
=> 0,
426 node
=> get_standard_option
('pve-node'),
427 vmid
=> get_standard_option
('pve-vmid'),
429 description
=> "Specify the time frame you are interested in.",
431 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
434 description
=> "The list of datasources you want to display.",
435 type
=> 'string', format
=> 'pve-configid-list',
438 description
=> "The RRD consolidation function",
440 enum
=> [ 'AVERAGE', 'MAX' ],
448 filename
=> { type
=> 'string' },
454 return PVE
::Cluster
::create_rrd_graph
(
455 "pve2-vm/$param->{vmid}", $param->{timeframe
},
456 $param->{ds
}, $param->{cf
});
460 __PACKAGE__-
>register_method({
462 path
=> '{vmid}/rrddata',
464 protected
=> 1, # fixme: can we avoid that?
466 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
468 description
=> "Read VM RRD statistics",
470 additionalProperties
=> 0,
472 node
=> get_standard_option
('pve-node'),
473 vmid
=> get_standard_option
('pve-vmid'),
475 description
=> "Specify the time frame you are interested in.",
477 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
480 description
=> "The RRD consolidation function",
482 enum
=> [ 'AVERAGE', 'MAX' ],
497 return PVE
::Cluster
::create_rrd_data
(
498 "pve2-vm/$param->{vmid}", $param->{timeframe
}, $param->{cf
});
501 __PACKAGE__-
>register_method({
502 name
=> 'destroy_vm',
507 description
=> "Destroy the container (also delete all uses files).",
509 check
=> [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
512 additionalProperties
=> 0,
514 node
=> get_standard_option
('pve-node'),
515 vmid
=> get_standard_option
('pve-vmid'),
524 my $rpcenv = PVE
::RPCEnvironment
::get
();
526 my $authuser = $rpcenv->get_user();
528 my $vmid = $param->{vmid
};
530 # test if container exists
531 my $conf = PVE
::LXC
::load_config
($vmid);
533 my $storage_cfg = cfs_read_file
("storage.cfg");
535 die "unable to remove CT $vmid - used in HA resources\n"
536 if PVE
::HA
::Config
::vm_is_ha_managed
($vmid);
539 # reload config after lock
540 $conf = PVE
::LXC
::load_config
($vmid);
541 PVE
::LXC
::check_lock
($conf);
543 PVE
::LXC
::destroy_lxc_container
($storage_cfg, $vmid, $conf);
544 PVE
::AccessControl
::remove_vm_access
($vmid);
545 PVE
::Firewall
::remove_vmfw_conf
($vmid);
548 my $realcmd = sub { PVE
::LXC
::lock_container
($vmid, 1, $code); };
550 return $rpcenv->fork_worker('vzdestroy', $vmid, $authuser, $realcmd);
555 __PACKAGE__-
>register_method ({
557 path
=> '{vmid}/vncproxy',
561 check
=> ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
563 description
=> "Creates a TCP VNC proxy connections.",
565 additionalProperties
=> 0,
567 node
=> get_standard_option
('pve-node'),
568 vmid
=> get_standard_option
('pve-vmid'),
572 description
=> "use websocket instead of standard VNC.",
577 additionalProperties
=> 0,
579 user
=> { type
=> 'string' },
580 ticket
=> { type
=> 'string' },
581 cert
=> { type
=> 'string' },
582 port
=> { type
=> 'integer' },
583 upid
=> { type
=> 'string' },
589 my $rpcenv = PVE
::RPCEnvironment
::get
();
591 my $authuser = $rpcenv->get_user();
593 my $vmid = $param->{vmid
};
594 my $node = $param->{node
};
596 my $authpath = "/vms/$vmid";
598 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($authuser, $authpath);
600 $sslcert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192)
603 my ($remip, $family);
605 if ($node ne PVE
::INotify
::nodename
()) {
606 ($remip, $family) = PVE
::Cluster
::remote_node_ip
($node);
608 $family = PVE
::Tools
::get_host_address_family
($node);
611 my $port = PVE
::Tools
::next_vnc_port
($family);
613 # NOTE: vncterm VNC traffic is already TLS encrypted,
614 # so we select the fastest chipher here (or 'none'?)
615 my $remcmd = $remip ?
616 ['/usr/bin/ssh', '-t', $remip] : [];
618 my $conf = PVE
::LXC
::load_config
($vmid, $node);
619 my $concmd = PVE
::LXC
::get_console_command
($vmid, $conf);
621 my $shcmd = [ '/usr/bin/dtach', '-A',
622 "/var/run/dtach/vzctlconsole$vmid",
623 '-r', 'winch', '-z', @$concmd];
628 syslog
('info', "starting lxc vnc proxy $upid\n");
632 my $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
633 '-timeout', $timeout, '-authpath', $authpath,
634 '-perm', 'VM.Console'];
636 if ($param->{websocket
}) {
637 $ENV{PVE_VNC_TICKET
} = $ticket; # pass ticket to vncterm
638 push @$cmd, '-notls', '-listen', 'localhost';
641 push @$cmd, '-c', @$remcmd, @$shcmd;
648 my $upid = $rpcenv->fork_worker('vncproxy', $vmid, $authuser, $realcmd);
650 PVE
::Tools
::wait_for_vnc_port
($port);
661 __PACKAGE__-
>register_method({
662 name
=> 'vncwebsocket',
663 path
=> '{vmid}/vncwebsocket',
666 description
=> "You also need to pass a valid ticket (vncticket).",
667 check
=> ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
669 description
=> "Opens a weksocket for VNC traffic.",
671 additionalProperties
=> 0,
673 node
=> get_standard_option
('pve-node'),
674 vmid
=> get_standard_option
('pve-vmid'),
676 description
=> "Ticket from previous call to vncproxy.",
681 description
=> "Port number returned by previous vncproxy call.",
691 port
=> { type
=> 'string' },
697 my $rpcenv = PVE
::RPCEnvironment
::get
();
699 my $authuser = $rpcenv->get_user();
701 my $authpath = "/vms/$param->{vmid}";
703 PVE
::AccessControl
::verify_vnc_ticket
($param->{vncticket
}, $authuser, $authpath);
705 my $port = $param->{port
};
707 return { port
=> $port };
710 __PACKAGE__-
>register_method ({
711 name
=> 'spiceproxy',
712 path
=> '{vmid}/spiceproxy',
717 check
=> ['perm', '/vms/{vmid}', [ 'VM.Console' ]],
719 description
=> "Returns a SPICE configuration to connect to the CT.",
721 additionalProperties
=> 0,
723 node
=> get_standard_option
('pve-node'),
724 vmid
=> get_standard_option
('pve-vmid'),
725 proxy
=> get_standard_option
('spice-proxy', { optional
=> 1 }),
728 returns
=> get_standard_option
('remote-viewer-config'),
732 my $vmid = $param->{vmid
};
733 my $node = $param->{node
};
734 my $proxy = $param->{proxy
};
736 my $authpath = "/vms/$vmid";
737 my $permissions = 'VM.Console';
739 my $conf = PVE
::LXC
::load_config
($vmid);
741 die "CT $vmid not running\n" if !PVE
::LXC
::check_running
($vmid);
743 my $concmd = PVE
::LXC
::get_console_command
($vmid, $conf);
745 my $shcmd = ['/usr/bin/dtach', '-A',
746 "/var/run/dtach/vzctlconsole$vmid",
747 '-r', 'winch', '-z', @$concmd];
749 my $title = "CT $vmid";
751 return PVE
::API2Tools
::run_spiceterm
($authpath, $permissions, $vmid, $node, $proxy, $title, $shcmd);
755 __PACKAGE__-
>register_method({
756 name
=> 'migrate_vm',
757 path
=> '{vmid}/migrate',
761 description
=> "Migrate the container to another node. Creates a new migration task.",
763 check
=> ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
766 additionalProperties
=> 0,
768 node
=> get_standard_option
('pve-node'),
769 vmid
=> get_standard_option
('pve-vmid'),
770 target
=> get_standard_option
('pve-node', { description
=> "Target node." }),
773 description
=> "Use online/live migration.",
780 description
=> "the task ID.",
785 my $rpcenv = PVE
::RPCEnvironment
::get
();
787 my $authuser = $rpcenv->get_user();
789 my $target = extract_param
($param, 'target');
791 my $localnode = PVE
::INotify
::nodename
();
792 raise_param_exc
({ target
=> "target is local node."}) if $target eq $localnode;
794 PVE
::Cluster
::check_cfs_quorum
();
796 PVE
::Cluster
::check_node_exists
($target);
798 my $targetip = PVE
::Cluster
::remote_node_ip
($target);
800 my $vmid = extract_param
($param, 'vmid');
803 PVE
::LXC
::load_config
($vmid);
805 # try to detect errors early
806 if (PVE
::LXC
::check_running
($vmid)) {
807 die "can't migrate running container without --online\n"
808 if !$param->{online
};
811 if (PVE
::HA
::Config
::vm_is_ha_managed
($vmid) && $rpcenv->{type
} ne 'ha') {
816 my $service = "ct:$vmid";
818 my $cmd = ['ha-manager', 'migrate', $service, $target];
820 print "Executing HA migrate for CT $vmid to node $target\n";
822 PVE
::Tools
::run_command
($cmd);
827 return $rpcenv->fork_worker('hamigrate', $vmid, $authuser, $hacmd);
834 # fixme: implement lxc container migration
835 die "lxc container migration not implemented\n";
840 return $rpcenv->fork_worker('vzmigrate', $vmid, $authuser, $realcmd);
844 __PACKAGE__-
>register_method({
845 name
=> 'vm_feature',
846 path
=> '{vmid}/feature',
850 description
=> "Check if feature for virtual machine is available.",
852 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
855 additionalProperties
=> 0,
857 node
=> get_standard_option
('pve-node'),
858 vmid
=> get_standard_option
('pve-vmid'),
860 description
=> "Feature to check.",
862 enum
=> [ 'snapshot' ],
864 snapname
=> get_standard_option
('pve-lxc-snapshot-name', {
872 hasFeature
=> { type
=> 'boolean' },
875 #items => { type => 'string' },
882 my $node = extract_param
($param, 'node');
884 my $vmid = extract_param
($param, 'vmid');
886 my $snapname = extract_param
($param, 'snapname');
888 my $feature = extract_param
($param, 'feature');
890 my $conf = PVE
::LXC
::load_config
($vmid);
893 my $snap = $conf->{snapshots
}->{$snapname};
894 die "snapshot '$snapname' does not exist\n" if !defined($snap);
897 my $storage_cfg = PVE
::Storage
::config
();
899 #my $nodelist = PVE::LXC::shared_nodes($conf, $storage_cfg);
900 my $hasFeature = PVE
::LXC
::has_feature
($feature, $conf, $storage_cfg, $snapname);
903 hasFeature
=> $hasFeature,
904 #nodes => [ keys %$nodelist ],
908 __PACKAGE__-
>register_method({
910 path
=> '{vmid}/template',
914 description
=> "Create a Template.",
916 description
=> "You need 'VM.Allocate' permissions on /vms/{vmid}",
917 check
=> [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
920 additionalProperties
=> 0,
922 node
=> get_standard_option
('pve-node'),
923 vmid
=> get_standard_option
('pve-vmid'),
926 returns
=> { type
=> 'null'},
930 my $rpcenv = PVE
::RPCEnvironment
::get
();
932 my $authuser = $rpcenv->get_user();
934 my $node = extract_param
($param, 'node');
936 my $vmid = extract_param
($param, 'vmid');
940 my $conf = PVE
::LXC
::load_config
($vmid);
941 PVE
::LXC
::check_lock
($conf);
943 die "unable to create template, because CT contains snapshots\n"
944 if $conf->{snapshots
} && scalar(keys %{$conf->{snapshots
}});
946 die "you can't convert a template to a template\n"
947 if PVE
::LXC
::is_template
($conf);
949 die "you can't convert a CT to template if the CT is running\n"
950 if PVE
::LXC
::check_running
($vmid);
953 PVE
::LXC
::template_create
($vmid, $conf);
956 $conf->{template
} = 1;
958 PVE
::LXC
::write_config
($vmid, $conf);
959 # and remove lxc config
960 PVE
::LXC
::update_lxc_config
(undef, $vmid, $conf);
962 return $rpcenv->fork_worker('vztemplate', $vmid, $authuser, $realcmd);
965 PVE
::LXC
::lock_container
($vmid, undef, $updatefn);