]> git.proxmox.com Git - pve-container.git/blame - src/PVE/CLI/pct.pm
bump version to 5.1.10
[pve-container.git] / src / PVE / CLI / pct.pm
CommitLineData
9beee926 1package PVE::CLI::pct;
179b842e 2
9beee926
DM
3use strict;
4use warnings;
5
b95bf64b
WB
6use Fcntl;
7use File::Copy 'copy';
89045484 8use POSIX;
b95bf64b 9
89045484 10use PVE::CLIHandler;
9beee926 11use PVE::Cluster;
89045484 12use PVE::CpuSet;
2c4baf7d 13use PVE::Exception qw(raise_param_exc);
89045484 14use PVE::GuestHelpers;
9beee926 15use PVE::INotify;
9beee926 16use PVE::JSONSchema qw(get_standard_option);
89045484
TL
17use PVE::LXC::CGroup;
18use PVE::RPCEnvironment;
19use PVE::SafeSyslog;
20use PVE::Tools qw(extract_param);
21
9beee926 22use PVE::API2::LXC::Config;
9beee926 23use PVE::API2::LXC::Snapshot;
89045484
TL
24use PVE::API2::LXC::Status;
25use PVE::API2::LXC;
9beee926 26
9beee926
DM
27use base qw(PVE::CLIHandler);
28
29my $nodename = PVE::INotify::nodename();
30
31my $upid_exit = sub {
32 my $upid = shift;
33 my $status = PVE::Tools::upid_read_status($upid);
e27fbd6b 34 exit(PVE::Tools::upid_status_is_error($status) ? -1 : 0);
9beee926
DM
35};
36
52e1f0cb
DM
37sub setup_environment {
38 PVE::RPCEnvironment->setup_default_cli_env();
39}
40
699ee9b2
DC
41__PACKAGE__->register_method ({
42 name => 'status',
43 path => 'status',
44 method => 'GET',
45 description => "Show CT status.",
46 parameters => {
47 additionalProperties => 0,
48 properties => {
49 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
50 verbose => {
51 description => "Verbose output format",
52 type => 'boolean',
53 optional => 1,
54 }
55 },
56 },
57 returns => { type => 'null'},
58 code => sub {
59 my ($param) = @_;
60
61 # test if CT exists
62 my $conf = PVE::LXC::Config->load_config ($param->{vmid});
63
64 my $vmstatus = PVE::LXC::vmstatus($param->{vmid});
65 my $stat = $vmstatus->{$param->{vmid}};
66 if ($param->{verbose}) {
67 foreach my $k (sort (keys %$stat)) {
68 my $v = $stat->{$k};
69 next if !defined($v);
43500db1 70 next if $k eq 'cpu';
699ee9b2
DC
71 print "$k: $v\n";
72 }
73 } else {
74 my $status = $stat->{status} || 'unknown';
75 print "status: $status\n";
76 }
77
78 return undef;
79 }});
80
6085e45b 81sub param_mapping {
34ddbf08
FG
82 my ($name) = @_;
83
84 my $mapping = {
6085e45b
DC
85 'create_vm' => [
86 PVE::CLIHandler::get_standard_mapping('pve-password'),
87 'ssh-public-keys',
88 ],
34ddbf08
FG
89 };
90
6085e45b 91 return $mapping->{$name};
34ddbf08
FG
92}
93
c72bd0ba
WL
94__PACKAGE__->register_method ({
95 name => 'unlock',
96 path => 'unlock',
97 method => 'PUT',
98 description => "Unlock the VM.",
99 parameters => {
100 additionalProperties => 0,
101 properties => {
102 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
103 },
104 },
105 returns => { type => 'null'},
106 code => sub {
107 my ($param) = @_;
108
109 my $vmid = $param->{vmid};
110
ad408fe1 111 PVE::LXC::Config->remove_lock($vmid);
c72bd0ba
WL
112
113 return undef;
114 }});
115
9beee926
DM
116__PACKAGE__->register_method ({
117 name => 'console',
118 path => 'console',
119 method => 'GET',
120 description => "Launch a console for the specified container.",
121 parameters => {
3c841167 122 additionalProperties => 0,
9beee926
DM
123 properties => {
124 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
65213b67
TM
125 escape => {
126 description => "Escape sequence prefix. For example to use <Ctrl+b q> as the escape sequence pass '^b'.",
127 default => '^a',
128 type => 'string',
129 pattern => '\^?[a-z]',
130 optional => 1,
131 },
9beee926
DM
132 },
133 },
134 returns => { type => 'null' },
135
136 code => sub {
137 my ($param) = @_;
138
139 # test if container exists on this node
67afe46e 140 my $conf = PVE::LXC::Config->load_config($param->{vmid});
9beee926 141
65213b67 142 my $cmd = PVE::LXC::get_console_command($param->{vmid}, $conf, $param->{escape});
9beee926
DM
143 exec(@$cmd);
144 }});
145
83f594f6
FG
146# TODO: Evaluate if still needed with PVE9
147sub clean_environment {
148 # These env variables are currently needed by PVE to work correctly with rust libraries,
149 # but can break ssl inside of containers.
150 # An explanation why they are needed and the code that sets them can be found here:
151 # https://git.proxmox.com/?p=proxmox-perl-rs.git;a=blob;f=common/pkg/Proxmox/Lib/SslProbe.pm
152 delete $ENV{SSL_CERT_FILE};
153 delete $ENV{SSL_CERT_DIR};
154};
155
9beee926
DM
156__PACKAGE__->register_method ({
157 name => 'enter',
158 path => 'enter',
159 method => 'GET',
160 description => "Launch a shell for the specified container.",
161 parameters => {
3c841167 162 additionalProperties => 0,
9beee926
DM
163 properties => {
164 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
069553d8
FG
165 # FIXME: passing the environment into the container potentially leaks hosts secrets, or causes
166 # unexpected behavior. Change to opt-in for pve 9
167 'keep-env' => {
168 type => 'boolean',
169 description => "Keep the current environment. This option will disabled by default with PVE 9."
170 ." If you rely on a preserved environment, please use this option to be future-proof.",
171 optional => 1,
172 default => 1,
173 },
9beee926
DM
174 },
175 },
176 returns => { type => 'null' },
177
178 code => sub {
179 my ($param) = @_;
069553d8 180 my $keep_env = $param->{'keep-env'} // 1; # FIXME: switch to default 0 with pve 9, see above
9beee926 181
d4b3eead
TL
182 my $vmid = $param->{vmid};
183
1330491c
TL
184 PVE::LXC::Config->load_config($vmid); # test if container exists on this node
185 die "container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
9beee926 186
83f594f6 187 clean_environment();
069553d8
FG
188
189 my @lxc_attach_cmd = ('lxc-attach', '-n', $vmid);
190 push @lxc_attach_cmd, $keep_env ? '--keep-env' : '--clear-env';
191 exec(@lxc_attach_cmd);
9beee926
DM
192 }});
193
194__PACKAGE__->register_method ({
195 name => 'exec',
196 path => 'exec',
197 method => 'GET',
198 description => "Launch a command inside the specified container.",
199 parameters => {
3c841167 200 additionalProperties => 0,
9beee926 201 properties => {
4b09527c 202 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
069553d8
FG
203 'keep-env' => {
204 type => 'boolean',
205 description => "Keep the current environment. This option will disabled by default with PVE 9."
206 ." If you rely on a preserved environment, please use this option to be future-proof.",
207 optional => 1,
208 default => 1, # FIXME: switch to default 0 with pve 9, see enter method
209 },
9beee926
DM
210 'extra-args' => get_standard_option('extra-args'),
211 },
212 },
213 returns => { type => 'null' },
9beee926
DM
214 code => sub {
215 my ($param) = @_;
069553d8 216 my $keep_env = $param->{'keep-env'} // 1; # FIXME: switch to default 0 with pve 9, see enter method
9beee926 217
8d43ef79
TL
218 my $vmid = $param->{vmid};
219 PVE::LXC::Config->load_config($vmid); # test if container exists on this node
1330491c 220 die "container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
9b813f83 221
a0af6336
TL
222 die "missing command" if !@{$param->{'extra-args'}};
223
83f594f6 224 clean_environment();
069553d8
FG
225
226 my @lxc_attach_cmd = ('lxc-attach', '-n', $vmid);
227 push @lxc_attach_cmd, $keep_env ? '--keep-env' : '--clear-env';
228 push @lxc_attach_cmd, '--', @{$param->{'extra-args'}};
229 exec(@lxc_attach_cmd);
9beee926
DM
230 }});
231
5ef9e3d1 232__PACKAGE__->register_method ({
f8327ed5
EK
233 name => 'fsck',
234 path => 'fsck',
235 method => 'PUT',
5ef9e3d1 236 description => "Run a filesystem check (fsck) on a container volume.",
f8327ed5
EK
237 parameters => {
238 additionalProperties => 0,
239 properties => {
240 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
241 force => {
242 optional => 1,
243 type => 'boolean',
244 description => "Force checking, even if the filesystem seems clean",
245 default => 0,
246 },
247 device => {
248 optional => 1,
249 type => 'string',
250 description => "A volume on which to run the filesystem check",
5e5d76cf 251 enum => [PVE::LXC::Config->valid_volume_keys()],
f8327ed5
EK
252 },
253 },
254 },
255 returns => { type => 'null' },
256 code => sub {
f8327ed5 257 my ($param) = @_;
3c841167 258
f8327ed5
EK
259 my $vmid = $param->{'vmid'};
260 my $device = defined($param->{'device'}) ? $param->{'device'} : 'rootfs';
261
262 my $command = ['fsck', '-a', '-l'];
263 push(@$command, '-f') if $param->{force};
264
265 # critical path: all of this will be done while the container is locked
266 my $do_fsck = sub {
267
67afe46e 268 my $conf = PVE::LXC::Config->load_config($vmid);
f8327ed5
EK
269 my $storage_cfg = PVE::Storage::config();
270
235dbdf3 271 defined($conf->{$device}) || die "cannot run command on non-existing mount point $device\n";
f8327ed5 272
e4034859 273 my $mount_point = PVE::LXC::Config->parse_volume($device, $conf->{$device});
44a9face 274
d8cde2e8
TL
275 die "cannot run fsck when container is running\n"
276 if PVE::LXC::check_running($vmid);
277
f8327ed5
EK
278 my $volid = $mount_point->{volume};
279
280 my $path;
281 my $storage_id = PVE::Storage::parse_volume_id($volid, 1);
282
283 if ($storage_id) {
f8327ed5 284 my (undef, undef, undef, undef, undef, undef, $format) =
da9e487b 285 PVE::Storage::parse_volname($storage_cfg, $volid);
f8327ed5 286
da9e487b
DM
287 die "unable to run fsck for '$volid' (format == $format)\n"
288 if $format ne 'raw';
f8327ed5 289
5dfa868b 290 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
bcf1163d 291 $path = PVE::Storage::map_volume($storage_cfg, $volid);
f8327ed5
EK
292
293 } else {
da9e487b 294 if (($volid =~ m|^/.+|) && (-b $volid)) {
f8327ed5
EK
295 # pass block devices directly
296 $path = $volid;
297 } else {
da9e487b 298 die "path '$volid' does not point to a block device\n";
f8327ed5
EK
299 }
300 }
301
302 push(@$command, $path);
305fc1ae
FE
303 eval { PVE::Tools::run_command($command); };
304 my $err = $@;
d8cde2e8 305
5dfa868b
FE
306 if ($storage_id) {
307 eval { PVE::Storage::unmap_volume($storage_cfg, $volid); };
308 warn $@ if $@;
309 eval { PVE::Storage::deactivate_volumes($storage_cfg, [$volid]); };
310 warn $@ if $@;
311 }
305fc1ae
FE
312
313 die $err if $err;
f8327ed5
EK
314 };
315
67afe46e 316 PVE::LXC::Config->lock_config($vmid, $do_fsck);
f8327ed5
EK
317 return undef;
318 }});
319
c93be6ed
WB
320__PACKAGE__->register_method({
321 name => 'mount',
322 path => 'mount',
323 method => 'POST',
324 description => "Mount the container's filesystem on the host. " .
325 "This will hold a lock on the container and is meant for emergency maintenance only " .
326 "as it will prevent further operations on the container other than start and stop.",
327 parameters => {
328 additionalProperties => 0,
329 properties => {
330 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
331 },
332 },
333 returns => { type => 'null' },
334 code => sub {
335 my ($param) = @_;
336
337 my $rpcenv = PVE::RPCEnvironment::get();
338
339 my $vmid = extract_param($param, 'vmid');
340 my $storecfg = PVE::Storage::config();
67afe46e
FG
341 PVE::LXC::Config->lock_config($vmid, sub {
342 my $conf = PVE::LXC::Config->set_lock($vmid, 'mounted');
c93be6ed
WB
343 PVE::LXC::mount_all($vmid, $storecfg, $conf);
344 });
8632d8eb
TL
345
346 print "mounted CT $vmid in '/var/lib/lxc/$vmid/rootfs'\n";
c93be6ed
WB
347 return undef;
348 }});
349
350__PACKAGE__->register_method({
351 name => 'unmount',
352 path => 'unmount',
353 method => 'POST',
354 description => "Unmount the container's filesystem.",
355 parameters => {
356 additionalProperties => 0,
357 properties => {
358 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
359 },
360 },
361 returns => { type => 'null' },
362 code => sub {
363 my ($param) = @_;
364
365 my $rpcenv = PVE::RPCEnvironment::get();
366
367 my $vmid = extract_param($param, 'vmid');
368 my $storecfg = PVE::Storage::config();
67afe46e
FG
369 PVE::LXC::Config->lock_config($vmid, sub {
370 my $conf = PVE::LXC::Config->load_config($vmid);
c93be6ed 371 PVE::LXC::umount_all($vmid, $storecfg, $conf, 0);
67afe46e 372 PVE::LXC::Config->remove_lock($vmid, 'mounted');
c93be6ed
WB
373 });
374 return undef;
375 }});
376
c6b59656
WB
377__PACKAGE__->register_method({
378 name => 'df',
379 path => 'df',
380 method => 'GET',
381 description => "Get the container's current disk usage.",
382 parameters => {
383 additionalProperties => 0,
384 properties => {
385 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
386 },
387 },
388 returns => { type => 'null' },
389 code => sub {
390 my ($param) = @_;
391
392 my $rpcenv = PVE::RPCEnvironment::get();
393
394 # JSONSchema's format_size is exact, this uses floating point numbers
395 my $format = sub {
396 my ($size) = @_;
397 return $size if $size < 1024.;
398 $size /= 1024.;
399 return sprintf('%.1fK', ${size}) if $size < 1024.;
400 $size /= 1024.;
401 return sprintf('%.1fM', ${size}) if $size < 1024.;
402 $size /= 1024.;
403 return sprintf('%.1fG', ${size}) if $size < 1024.;
404 $size /= 1024.;
405 return sprintf('%.1fT', ${size}) if $size < 1024.;
406 };
407
408 my $vmid = extract_param($param, 'vmid');
409 PVE::LXC::Config->lock_config($vmid, sub {
410 my $pid = eval { PVE::LXC::find_lxc_pid($vmid) };
411 my ($conf, $rootdir, $storecfg, $mounted);
412 if ($@ || !$pid) {
413 $conf = PVE::LXC::Config->set_lock($vmid, 'mounted');
414 $rootdir = "/var/lib/lxc/$vmid/rootfs";
415 $storecfg = PVE::Storage::config();
416 PVE::LXC::mount_all($vmid, $storecfg, $conf);
417 $mounted = 1;
418 } else {
419 $conf = PVE::LXC::Config->load_config($vmid);
420 $rootdir = "/proc/$pid/root";
421 }
422
423 my @list = [qw(MP Volume Size Used Avail Use% Path)];
424 my @len = map { length($_) } @{$list[0]};
425
426 eval {
015740e6 427 PVE::LXC::Config->foreach_volume($conf, sub {
c6b59656
WB
428 my ($name, $mp) = @_;
429 my $path = $mp->{mp};
430
431 my $df = PVE::Tools::df("$rootdir/$path", 3);
432 my $total = $format->($df->{total});
433 my $used = $format->($df->{used});
434 my $avail = $format->($df->{avail});
435
ccc2bd7b 436 my $pc = sprintf('%.1f', 100 * $df->{used} / $df->{total});
c6b59656
WB
437
438 my $entry = [ $name, $mp->{volume}, $total, $used, $avail, $pc, $path ];
439 push @list, $entry;
440
441 foreach my $i (0..5) {
442 $len[$i] = length($entry->[$i])
443 if $len[$i] < length($entry->[$i]);
444 }
445 });
446
447 my $format = "%-$len[0]s %-$len[1]s %$len[2]s %$len[3]s %$len[4]s %$len[5]s %s\n";
448 printf($format, @$_) foreach @list;
449 };
450 warn $@ if $@;
451
452 if ($mounted) {
453 PVE::LXC::umount_all($vmid, $storecfg, $conf, 0);
454 PVE::LXC::Config->remove_lock($vmid, 'mounted');
455 }
456 });
457 return undef;
458 }});
459
b95bf64b
WB
460# File creation with specified ownership and permissions.
461# User and group can be names or decimal numbers.
462# Permissions are explicit (not affected by umask) and can be numeric with the
463# usual 0/0x prefixes for octal/hex.
464sub create_file {
465 my ($path, $perms, $user, $group) = @_;
466 my ($uid, $gid);
467 if (defined($user)) {
468 if ($user =~ /^\d+$/) {
469 $uid = int($user);
470 } else {
d7c03854
OB
471 $uid = getpwnam($user);
472 die "failed to get uid for: $user\n" if !defined($uid);
b95bf64b
WB
473 }
474 }
475 if (defined($group)) {
476 if ($group =~ /^\d+$/) {
477 $gid = int($group);
478 } else {
d7c03854
OB
479 $gid = getgrnam($group);
480 die "failed to get gid for: $group\n" if !defined($gid);
b95bf64b
WB
481 }
482 }
483
484 if (defined($perms)) {
485 $! = 0;
486 my ($mode, $unparsed) = POSIX::strtoul($perms, 0);
487 die "invalid mode: '$perms'\n" if $perms eq '' || $unparsed > 0 || $!;
488 $perms = $mode;
489 }
490
491 my $fd;
492 if (sysopen($fd, $path, O_WRONLY | O_CREAT | O_EXCL, 0)) {
493 $perms = 0666 & ~umask if !defined($perms);
494 } else {
495 # If the path previously existed then we do not care about left-over
496 # file descriptors even if the permissions/ownership is changed.
497 sysopen($fd, $path, O_WRONLY | O_CREAT | O_TRUNC)
498 or die "failed to create file: $path: $!\n";
499 }
500
501 my $trunc = 0;
502
503 if (defined($perms)) {
504 $trunc = 1;
505 chmod($perms, $fd);
506 }
507
508 if (defined($uid) || defined($gid)) {
509 $trunc = 1;
bf8c472f
TL
510 if (!defined($uid) || !defined($gid)) {
511 my ($fuid, $fgid) = (stat($fd))[4,5];
512 $uid //= $fuid;
513 $gid //= $fgid;
514 }
515 chown($uid, $gid, $fd) or die "failed to change file owner: $!\n";
b95bf64b
WB
516 }
517 return $fd;
518}
519
6827e44d
AA
520__PACKAGE__->register_method ({
521 name => 'rescan',
522 path => 'rescan',
523 method => 'POST',
524 description => "Rescan all storages and update disk sizes and unused disk images.",
525 parameters => {
526 additionalProperties => 0,
527 properties => {
528 vmid => get_standard_option('pve-vmid', {
529 optional => 1,
530 completion => \&PVE::LXC::complete_ctid,
531 }),
532 dryrun => {
533 type => 'boolean',
534 optional => 1,
535 default => 0,
536 description => 'Do not actually write changes out to conifg.',
537 },
538 },
539 },
540 returns => { type => 'null'},
541 code => sub {
542 my ($param) = @_;
543
544 my $dryrun = $param->{dryrun};
545
546 print "NOTE: running in dry-run mode, won't write changes out!\n" if $dryrun;
547
548 PVE::LXC::rescan($param->{vmid}, 0, $dryrun);
549
550 return undef;
551 }});
552
b95bf64b
WB
553__PACKAGE__->register_method({
554 name => 'pull',
555 path => 'pull',
556 method => 'PUT',
557 description => "Copy a file from the container to the local system.",
558 parameters => {
559 additionalProperties => 0,
560 properties => {
561 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
562 path => {
563 type => 'string',
564 description => "Path to a file inside the container to pull.",
565 },
566 destination => {
567 type => 'string',
568 description => "Destination",
569 },
570 user => {
571 type => 'string',
572 description => 'Owner user name or id.',
573 optional => 1,
574 },
575 group => {
576 type => 'string',
577 description => 'Owner group name or id.',
578 optional => 1,
579 },
580 perms => {
581 type => 'string',
893e40de 582 description => "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
b95bf64b
WB
583 optional => 1,
584 },
585 },
586 },
587 returns => {
588 type => 'string',
589 description => "the task ID.",
590 },
591 code => sub {
592 my ($param) = @_;
593
594 my $rpcenv = PVE::RPCEnvironment::get();
595
596 my $vmid = extract_param($param, 'vmid');
597 my $path = extract_param($param, 'path');
598 my $dest = extract_param($param, 'destination');
599
600 my $perms = extract_param($param, 'perms');
fa0ab908
DM
601 # assume octal as default
602 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
b95bf64b
WB
603 my $user = extract_param($param, 'user');
604 my $group = extract_param($param, 'group');
605
606 my $code = sub {
607 my $running = PVE::LXC::check_running($vmid);
608 die "can only pull files from a running VM" if !$running;
609
610 my $realcmd = sub {
611 my $pid = PVE::LXC::find_lxc_pid($vmid);
612 # Avoid symlink issues by opening the files from inside the
613 # corresponding namespaces.
614 my $destfd = create_file($dest, $perms, $user, $group);
615
616 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
617 or die "failed to open the container's mount namespace\n";
618 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
619 or die "failed to enter the container's mount namespace\n";
620 close($mntnsfd);
621 chdir('/') or die "failed to change to container root directory\n";
622
623 open my $srcfd, '<', $path
624 or die "failed to open $path: $!\n";
625
626 copy($srcfd, $destfd);
627 };
628
629 # This avoids having to setns() back to our namespace.
630 return $rpcenv->fork_worker('pull_file', $vmid, undef, $realcmd);
631 };
632
67afe46e 633 return PVE::LXC::Config->lock_config($vmid, $code);
b95bf64b
WB
634 }});
635
636__PACKAGE__->register_method({
637 name => 'push',
638 path => 'push',
639 method => 'PUT',
640 description => "Copy a local file to the container.",
641 parameters => {
642 additionalProperties => 0,
643 properties => {
644 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
645 file => {
646 type => 'string',
647 description => "Path to a local file.",
648 },
649 destination => {
650 type => 'string',
651 description => "Destination inside the container to write to.",
652 },
653 user => {
654 type => 'string',
655 description => 'Owner user name or id. When using a name it must exist inside the container.',
656 optional => 1,
657 },
658 group => {
659 type => 'string',
660 description => 'Owner group name or id. When using a name it must exist inside the container.',
661 optional => 1,
662 },
663 perms => {
664 type => 'string',
893e40de 665 description => "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
b95bf64b
WB
666 optional => 1,
667 },
668 },
669 },
670 returns => {
671 type => 'string',
672 description => "the task ID.",
673 },
674 code => sub {
675 my ($param) = @_;
676
677 my $rpcenv = PVE::RPCEnvironment::get();
678
679 my $vmid = extract_param($param, 'vmid');
680 my $file = extract_param($param, 'file');
681 my $dest = extract_param($param, 'destination');
682
683 my $perms = extract_param($param, 'perms');
fa0ab908
DM
684 # assume octal as default
685 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
b95bf64b
WB
686 my $user = extract_param($param, 'user');
687 my $group = extract_param($param, 'group');
688
689 my $code = sub {
690 my $running = PVE::LXC::check_running($vmid);
5a883bff 691 die "can only push files to a running CT\n" if !$running;
b95bf64b 692
67afe46e 693 my $conf = PVE::LXC::Config->load_config($vmid);
b95bf64b
WB
694 my $unprivileged = $conf->{unprivileged};
695
696 my $realcmd = sub {
697 my $pid = PVE::LXC::find_lxc_pid($vmid);
698 # We open the file then enter the container's mount - and for
699 # unprivileged containers - user namespace and then create the
700 # file. This avoids symlink attacks as a symlink cannot point
701 # outside the namespace and our own access is equivalent to the
702 # container-local's root user. Also the user-passed -user and
703 # -group parameters will use the container-local's user and
704 # group names.
705 sysopen my $srcfd, $file, O_RDONLY
706 or die "failed to open $file for reading\n";
707
708 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
709 or die "failed to open the container's mount namespace\n";
710 my $usernsfd;
711 if ($unprivileged) {
712 sysopen $usernsfd, "/proc/$pid/ns/user", O_RDONLY
713 or die "failed to open the container's user namespace\n";
714 }
715
716 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
717 or die "failed to enter the container's mount namespace\n";
718 close($mntnsfd);
719 chdir('/') or die "failed to change to container root directory\n";
720
721 if ($unprivileged) {
722 PVE::Tools::setns(fileno($usernsfd), PVE::Tools::CLONE_NEWUSER)
723 or die "failed to enter the container's user namespace\n";
724 close($usernsfd);
725 POSIX::setgid(0) or die "setgid failed: $!\n";
726 POSIX::setuid(0) or die "setuid failed: $!\n";
727 }
728
729 my $destfd = create_file($dest, $perms, $user, $group);
730 copy($srcfd, $destfd);
731 };
732
733 # This avoids having to setns() back to our namespace.
734 return $rpcenv->fork_worker('push_file', $vmid, undef, $realcmd);
735 };
736
67afe46e 737 return PVE::LXC::Config->lock_config($vmid, $code);
b95bf64b
WB
738 }});
739
c87b1505
DM
740__PACKAGE__->register_method ({
741 name => 'cpusets',
742 path => 'cpusets',
743 method => 'GET',
744 description => "Print the list of assigned CPU sets.",
745 parameters => {
746 additionalProperties => 0,
747 properties => {},
748 },
749 returns => { type => 'null'},
750 code => sub {
751 my ($param) = @_;
752
753 my $ctlist = PVE::LXC::config_list();
754
755 my $len = 0;
756 my $id_len = 0;
757 my $res = {};
758
759 foreach my $vmid (sort keys %$ctlist) {
fdc5f2ad 760 my $cgroup = PVE::LXC::CGroup->new($vmid);
c87b1505 761
fdc5f2ad 762 my ($cpuset, $path);
7dad5464 763 if (defined($path = $cgroup->get_path('cpuset', 1))) {
66f7024e 764 $cpuset = eval { PVE::CpuSet->new_from_path($path, 1); };
7dad5464 765 } elsif (defined($path = $cgroup->get_path(undef, 1))) {
66f7024e 766 $cpuset = eval { PVE::CpuSet->new_from_path($path, 1); };
fdc5f2ad
WB
767 } else {
768 # Container not running.
769 next;
770 }
c87b1505
DM
771 if (my $err = $@) {
772 warn $err;
773 next;
774 }
fdc5f2ad 775
c87b1505
DM
776 my @cpuset_members = $cpuset->members();
777
778 my $line = ': ';
779
780 my $last = $cpuset_members[-1];
781
782 for (my $id = 0; $id <= $last; $id++) {
783 my $empty = ' ' x length("$id");
784 $line .= ' ' . ($cpuset->has($id) ? $id : $empty);
785 }
786 $len = length($line) if length($line) > $len;
787 $id_len = length($vmid) if length($vmid) > $id_len;
788
789 $res->{$vmid} = $line;
790 }
791
486fe362 792 my @vmlist = sort keys %$res;
c87b1505 793
486fe362
DM
794 if (scalar(@vmlist)) {
795 my $header = '-' x ($len + $id_len) . "\n";
796
797 print $header;
798 foreach my $vmid (@vmlist) {
799 print sprintf("%${id_len}i%s\n", $vmid, $res->{$vmid});
800 }
801 print $header;
802
803 } else {
804 print "no running containers\n";
c87b1505 805 }
c87b1505
DM
806
807 return undef;
808 }});
809
e08ac1a0
OB
810__PACKAGE__->register_method ({
811 name => 'fstrim',
812 path => 'fstrim',
813 method => 'POST',
22be1b3f 814 description => "Run fstrim on a chosen CT and its mountpoints, except bind or read-only mountpoints.",
e08ac1a0
OB
815 parameters => {
816 additionalProperties => 0,
817 properties => {
818 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
4590b2e4 819 'ignore-mountpoints' => {
8a4db933 820 description => 'Skip all mountpoints, only do fstrim on the container root.',
4590b2e4
OB
821 optional => 1,
822 type => 'boolean',
823 },
e08ac1a0
OB
824 },
825 },
826 returns => { type => 'null' },
827 code => sub {
828
829 my ($param) = @_;
830 my $vmid = $param->{'vmid'};
831
832 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
833
834 my $storecfg = PVE::Storage::config();
835 my $conf = PVE::LXC::Config->set_lock($vmid, 'fstrim');
e08ac1a0
OB
836 eval {
837 my $path = "";
a179d3a7 838 PVE::LXC::mount_all($vmid, $storecfg, $conf);
015740e6 839 PVE::LXC::Config->foreach_volume($conf, sub {
e08ac1a0
OB
840 my ($name, $mp) = @_;
841 $path = $mp->{mp};
22be1b3f 842 return if $mp->{type} eq 'bind' || $mp->{ro};
4590b2e4 843 return if $param->{'ignore-mountpoints'} && $name =~ /^mp\d+/;
e08ac1a0 844 my $cmd = ["fstrim", "-v", "$rootdir$path"];
9d9ac8a9 845 PVE::Tools::run_command($cmd, noerr => 1);
e08ac1a0
OB
846 });
847 };
a179d3a7 848 warn $@ if $@;
e08ac1a0
OB
849
850 PVE::LXC::umount_all($vmid, $storecfg, $conf, 0);
851 PVE::LXC::Config->remove_lock($vmid, 'fstrim');
852
853 return undef;
854 }});
855
2c4baf7d
FG
856
857__PACKAGE__->register_method({
858 name => 'remote_migrate_vm',
859 path => 'remote_migrate_vm',
860 method => 'POST',
861 description => "Migrate container to a remote cluster. Creates a new migration task. EXPERIMENTAL feature!",
862 permissions => {
863 check => ['perm', '/vms/{vmid}', [ 'VM.Migrate' ]],
864 },
865 parameters => {
866 additionalProperties => 0,
867 properties => {
868 node => get_standard_option('pve-node'),
359e2fa0 869 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
2c4baf7d
FG
870 'target-vmid' => get_standard_option('pve-vmid', { optional => 1 }),
871 'target-endpoint' => get_standard_option('proxmox-remote', {
872 description => "Remote target endpoint",
873 }),
874 online => {
875 type => 'boolean',
876 description => "Use online/live migration.",
877 optional => 1,
878 },
879 restart => {
880 type => 'boolean',
881 description => "Use restart migration",
882 optional => 1,
883 },
884 timeout => {
885 type => 'integer',
886 description => "Timeout in seconds for shutdown for restart migration",
887 optional => 1,
888 default => 180,
889 },
890 delete => {
891 type => 'boolean',
892 description => "Delete the original CT and related data after successful migration. By default the original CT is kept on the source cluster in a stopped state.",
893 optional => 1,
894 default => 0,
895 },
896 'target-storage' => get_standard_option('pve-targetstorage', {
2c4baf7d
FG
897 optional => 0,
898 }),
899 'target-bridge' => {
900 type => 'string',
901 description => "Mapping from source to target bridges. Providing only a single bridge ID maps all source bridges to that bridge. Providing the special value '1' will map each source bridge to itself.",
902 format => 'bridge-pair-list',
903 },
904 bwlimit => {
905 description => "Override I/O bandwidth limit (in KiB/s).",
906 optional => 1,
907 type => 'integer',
908 minimum => '0',
909 default => 'migrate limit from datacenter or storage config',
910 },
911 },
912 },
913 returns => {
914 type => 'string',
915 description => "the task ID.",
916 },
917 code => sub {
918 my ($param) = @_;
919
920 my $rpcenv = PVE::RPCEnvironment::get();
921 my $authuser = $rpcenv->get_user();
922
923 my $source_vmid = $param->{vmid};
924 my $target_endpoint = $param->{'target-endpoint'};
925 my $target_vmid = $param->{'target-vmid'} // $source_vmid;
926
927 my $remote = PVE::JSONSchema::parse_property_string('proxmox-remote', $target_endpoint);
928
929 # TODO: move this as helper somewhere appropriate?
930 my $conn_args = {
931 protocol => 'https',
932 host => $remote->{host},
933 port => $remote->{port} // 8006,
934 apitoken => $remote->{apitoken},
935 };
936
937 $conn_args->{cached_fingerprints} = { uc($remote->{fingerprint}) => 1 }
938 if defined($remote->{fingerprint});
939
940 my $api_client = PVE::APIClient::LWP->new(%$conn_args);
941 my $resources = $api_client->get("/cluster/resources", { type => 'vm' });
942 if (grep { defined($_->{vmid}) && $_->{vmid} eq $target_vmid } @$resources) {
943 raise_param_exc({ target_vmid => "Guest with ID '$target_vmid' already exists on remote cluster" });
944 }
945
946 my $storages = $api_client->get("/nodes/localhost/storage", { enabled => 1 });
947
948 my $storecfg = PVE::Storage::config();
949 my $target_storage = $param->{'target-storage'};
950 my $storagemap = eval { PVE::JSONSchema::parse_idmap($target_storage, 'pve-storage-id') };
951 raise_param_exc({ 'target-storage' => "failed to parse storage map: $@" })
952 if $@;
953
954 my $check_remote_storage = sub {
955 my ($storage) = @_;
956 my $found = [ grep { $_->{storage} eq $storage } @$storages ];
957 die "remote: storage '$storage' does not exist!\n"
958 if !@$found;
959
960 $found = @$found[0];
961
962 my $content_types = [ PVE::Tools::split_list($found->{content}) ];
963 die "remote: storage '$storage' cannot store CT rootdir\n"
964 if !grep { $_ eq 'rootdir' } @$content_types;
965 };
966
967 foreach my $target_sid (values %{$storagemap->{entries}}) {
968 $check_remote_storage->($target_sid);
969 }
970
971 $check_remote_storage->($storagemap->{default})
972 if $storagemap->{default};
973
974 return PVE::API2::LXC->remote_migrate_vm($param);
975 }});
976
9beee926
DM
977our $cmddef = {
978 list=> [ 'PVE::API2::LXC', 'vmlist', [], { node => $nodename }, sub {
979 my $res = shift;
980 return if !scalar(@$res);
d0226204
WB
981 my $format = "%-10s %-10s %-12s %-20s\n";
982 printf($format, 'VMID', 'Status', 'Lock', 'Name');
9beee926 983 foreach my $d (sort {$a->{vmid} <=> $b->{vmid} } @$res) {
7790ecf6
FE
984 my $lock = $d->{lock} || '';
985 printf($format, $d->{vmid}, $d->{status}, $lock, $d->{name});
9beee926
DM
986 }
987 }],
f30ad07e
TL
988 config => [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'], { node => $nodename }, sub {
989 my $config = shift;
990 for my $k (sort (keys %$config)) {
991 next if $k eq 'digest' || $k eq 'lxc';
992 my $v = $config->{$k};
993 if ($k eq 'description') {
994 $v = PVE::Tools::encode_text($v);
995 }
996 print "$k: $v\n";
997 }
998 if (defined(my $lxc_list = $config->{'lxc'})) {
999 for my $lxc_opt (@$lxc_list) {
1000 print "$lxc_opt->[0]: $lxc_opt->[1]\n"
1001 }
1002 }
1003 }],
f9fc67e9
OB
1004
1005 pending => [ "PVE::API2::LXC", "vm_pending", ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
9beee926 1006 set => [ 'PVE::API2::LXC::Config', 'update_vm', ['vmid'], { node => $nodename }],
40626217 1007
985b18ed 1008 resize => [ "PVE::API2::LXC", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
721b6d63 1009
9beee926
DM
1010 create => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename }, $upid_exit ],
1011 restore => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename, restore => 1 }, $upid_exit ],
721b6d63 1012 destroy => [ 'PVE::API2::LXC', 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
9beee926
DM
1013
1014 start => [ 'PVE::API2::LXC::Status', 'vm_start', ['vmid'], { node => $nodename }, $upid_exit],
1015 suspend => [ 'PVE::API2::LXC::Status', 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit],
1016 resume => [ 'PVE::API2::LXC::Status', 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit],
1017 shutdown => [ 'PVE::API2::LXC::Status', 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit],
1018 stop => [ 'PVE::API2::LXC::Status', 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit],
f5fe1125
OB
1019 reboot => [ 'PVE::API2::LXC::Status', 'vm_reboot', ['vmid'], { node => $nodename }, $upid_exit],
1020
c4a33727 1021 clone => [ "PVE::API2::LXC", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
9beee926 1022 migrate => [ "PVE::API2::LXC", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit],
93c2e6f7
AL
1023 'move-volume' => [ "PVE::API2::LXC", 'move_volume', ['vmid', 'volume', 'storage', 'target-vmid', 'target-volume'], { node => $nodename }, $upid_exit ],
1024 move_volume => { alias => 'move-volume' },
2c4baf7d 1025 'remote-migrate' => [ __PACKAGE__, 'remote_migrate_vm', ['vmid', 'target-vmid', 'target-endpoint'], { node => $nodename }, $upid_exit ],
721b6d63
TL
1026
1027 snapshot => [ "PVE::API2::LXC::Snapshot", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
1028 delsnapshot => [ "PVE::API2::LXC::Snapshot", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
1029 listsnapshot => [ "PVE::API2::LXC::Snapshot", 'list', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::print_snapshot_tree ],
1030 rollback => [ "PVE::API2::LXC::Snapshot", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
1031 template => [ "PVE::API2::LXC", 'template', ['vmid'], { node => $nodename }],
1032
699ee9b2 1033 status => [ __PACKAGE__, 'status', ['vmid']],
9beee926
DM
1034 console => [ __PACKAGE__, 'console', ['vmid']],
1035 enter => [ __PACKAGE__, 'enter', ['vmid']],
c72bd0ba 1036 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
9beee926 1037 exec => [ __PACKAGE__, 'exec', ['vmid', 'extra-args']],
f8327ed5 1038 fsck => [ __PACKAGE__, 'fsck', ['vmid']],
b95bf64b 1039
c93be6ed
WB
1040 mount => [ __PACKAGE__, 'mount', ['vmid']],
1041 unmount => [ __PACKAGE__, 'unmount', ['vmid']],
b95bf64b
WB
1042 push => [ __PACKAGE__, 'push', ['vmid', 'file', 'destination']],
1043 pull => [ __PACKAGE__, 'pull', ['vmid', 'path', 'destination']],
c6b59656
WB
1044
1045 df => [ __PACKAGE__, 'df', ['vmid']],
6827e44d 1046 rescan => [ __PACKAGE__, 'rescan', []],
c87b1505 1047 cpusets => [ __PACKAGE__, 'cpusets', []],
e08ac1a0 1048 fstrim => [ __PACKAGE__, 'fstrim', ['vmid']],
9beee926
DM
1049};
1050
9beee926 10511;