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