]> git.proxmox.com Git - pve-container.git/blob - src/PVE/CLI/pct.pm
pct config: fix indentation and rework to shorter code
[pve-container.git] / src / PVE / CLI / pct.pm
1 package PVE::CLI::pct;
2
3 use strict;
4 use warnings;
5
6 use POSIX;
7 use Fcntl;
8 use File::Copy 'copy';
9
10 use PVE::GuestHelpers;
11 use PVE::SafeSyslog;
12 use PVE::Tools qw(extract_param);
13 use PVE::CpuSet;
14 use PVE::Cluster;
15 use PVE::INotify;
16 use PVE::RPCEnvironment;
17 use PVE::JSONSchema qw(get_standard_option);
18 use PVE::CLIHandler;
19 use PVE::API2::LXC;
20 use PVE::API2::LXC::Config;
21 use PVE::API2::LXC::Status;
22 use PVE::API2::LXC::Snapshot;
23 use PVE::LXC::CGroup;
24
25 use base qw(PVE::CLIHandler);
26
27 my $nodename = PVE::INotify::nodename();
28
29 my $upid_exit = sub {
30 my $upid = shift;
31 my $status = PVE::Tools::upid_read_status($upid);
32 exit($status eq 'OK' ? 0 : -1);
33 };
34
35 sub setup_environment {
36 PVE::RPCEnvironment->setup_default_cli_env();
37 }
38
39 __PACKAGE__->register_method ({
40 name => 'status',
41 path => 'status',
42 method => 'GET',
43 description => "Show CT status.",
44 parameters => {
45 additionalProperties => 0,
46 properties => {
47 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
48 verbose => {
49 description => "Verbose output format",
50 type => 'boolean',
51 optional => 1,
52 }
53 },
54 },
55 returns => { type => 'null'},
56 code => sub {
57 my ($param) = @_;
58
59 # test if CT exists
60 my $conf = PVE::LXC::Config->load_config ($param->{vmid});
61
62 my $vmstatus = PVE::LXC::vmstatus($param->{vmid});
63 my $stat = $vmstatus->{$param->{vmid}};
64 if ($param->{verbose}) {
65 foreach my $k (sort (keys %$stat)) {
66 my $v = $stat->{$k};
67 next if !defined($v);
68 print "$k: $v\n";
69 }
70 } else {
71 my $status = $stat->{status} || 'unknown';
72 print "status: $status\n";
73 }
74
75 return undef;
76 }});
77
78 sub param_mapping {
79 my ($name) = @_;
80
81 my $mapping = {
82 'create_vm' => [
83 PVE::CLIHandler::get_standard_mapping('pve-password'),
84 'ssh-public-keys',
85 ],
86 };
87
88 return $mapping->{$name};
89 }
90
91 __PACKAGE__->register_method ({
92 name => 'unlock',
93 path => 'unlock',
94 method => 'PUT',
95 description => "Unlock the VM.",
96 parameters => {
97 additionalProperties => 0,
98 properties => {
99 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
100 },
101 },
102 returns => { type => 'null'},
103 code => sub {
104 my ($param) = @_;
105
106 my $vmid = $param->{vmid};
107
108 PVE::LXC::Config->remove_lock($vmid);
109
110 return undef;
111 }});
112
113 __PACKAGE__->register_method ({
114 name => 'console',
115 path => 'console',
116 method => 'GET',
117 description => "Launch a console for the specified container.",
118 parameters => {
119 additionalProperties => 0,
120 properties => {
121 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
122 escape => {
123 description => "Escape sequence prefix. For example to use <Ctrl+b q> as the escape sequence pass '^b'.",
124 default => '^a',
125 type => 'string',
126 pattern => '\^?[a-z]',
127 optional => 1,
128 },
129 },
130 },
131 returns => { type => 'null' },
132
133 code => sub {
134 my ($param) = @_;
135
136 # test if container exists on this node
137 my $conf = PVE::LXC::Config->load_config($param->{vmid});
138
139 my $cmd = PVE::LXC::get_console_command($param->{vmid}, $conf, $param->{escape});
140 exec(@$cmd);
141 }});
142
143 __PACKAGE__->register_method ({
144 name => 'enter',
145 path => 'enter',
146 method => 'GET',
147 description => "Launch a shell for the specified container.",
148 parameters => {
149 additionalProperties => 0,
150 properties => {
151 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
152 },
153 },
154 returns => { type => 'null' },
155
156 code => sub {
157 my ($param) = @_;
158
159 my $vmid = $param->{vmid};
160
161 PVE::LXC::Config->load_config($vmid); # test if container exists on this node
162 die "container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
163
164 exec('lxc-attach', '-n', $vmid);
165 }});
166
167 __PACKAGE__->register_method ({
168 name => 'exec',
169 path => 'exec',
170 method => 'GET',
171 description => "Launch a command inside the specified container.",
172 parameters => {
173 additionalProperties => 0,
174 properties => {
175 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
176 'extra-args' => get_standard_option('extra-args'),
177 },
178 },
179 returns => { type => 'null' },
180 code => sub {
181 my ($param) = @_;
182
183 my $vmid = $param->{vmid};
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);
186
187 die "missing command" if !@{$param->{'extra-args'}};
188
189 exec('lxc-attach', '-n', $vmid, '--', @{$param->{'extra-args'}});
190 }});
191
192 __PACKAGE__->register_method ({
193 name => 'fsck',
194 path => 'fsck',
195 method => 'PUT',
196 description => "Run a filesystem check (fsck) on a container volume.",
197 parameters => {
198 additionalProperties => 0,
199 properties => {
200 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
201 force => {
202 optional => 1,
203 type => 'boolean',
204 description => "Force checking, even if the filesystem seems clean",
205 default => 0,
206 },
207 device => {
208 optional => 1,
209 type => 'string',
210 description => "A volume on which to run the filesystem check",
211 enum => [PVE::LXC::Config->valid_volume_keys()],
212 },
213 },
214 },
215 returns => { type => 'null' },
216 code => sub {
217 my ($param) = @_;
218
219 my $vmid = $param->{'vmid'};
220 my $device = defined($param->{'device'}) ? $param->{'device'} : 'rootfs';
221
222 my $command = ['fsck', '-a', '-l'];
223 push(@$command, '-f') if $param->{force};
224
225 # critical path: all of this will be done while the container is locked
226 my $do_fsck = sub {
227
228 my $conf = PVE::LXC::Config->load_config($vmid);
229 my $storage_cfg = PVE::Storage::config();
230
231 defined($conf->{$device}) || die "cannot run command on non-existing mount point $device\n";
232
233 my $mount_point = PVE::LXC::Config->parse_volume($device, $conf->{$device});
234
235 die "cannot run fsck when container is running\n"
236 if PVE::LXC::check_running($vmid);
237
238 my $volid = $mount_point->{volume};
239
240 my $path;
241 my $storage_id = PVE::Storage::parse_volume_id($volid, 1);
242
243 if ($storage_id) {
244 my (undef, undef, undef, undef, undef, undef, $format) =
245 PVE::Storage::parse_volname($storage_cfg, $volid);
246
247 die "unable to run fsck for '$volid' (format == $format)\n"
248 if $format ne 'raw';
249
250 $path = PVE::Storage::map_volume($storage_cfg, $volid);
251
252 } else {
253 if (($volid =~ m|^/.+|) && (-b $volid)) {
254 # pass block devices directly
255 $path = $volid;
256 } else {
257 die "path '$volid' does not point to a block device\n";
258 }
259 }
260
261 push(@$command, $path);
262 PVE::Tools::run_command($command);
263
264 PVE::Storage::unmap_volume($storage_cfg, $volid) if $storage_id;
265 };
266
267 PVE::LXC::Config->lock_config($vmid, $do_fsck);
268 return undef;
269 }});
270
271 __PACKAGE__->register_method({
272 name => 'mount',
273 path => 'mount',
274 method => 'POST',
275 description => "Mount the container's filesystem on the host. " .
276 "This will hold a lock on the container and is meant for emergency maintenance only " .
277 "as it will prevent further operations on the container other than start and stop.",
278 parameters => {
279 additionalProperties => 0,
280 properties => {
281 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
282 },
283 },
284 returns => { type => 'null' },
285 code => sub {
286 my ($param) = @_;
287
288 my $rpcenv = PVE::RPCEnvironment::get();
289
290 my $vmid = extract_param($param, 'vmid');
291 my $storecfg = PVE::Storage::config();
292 PVE::LXC::Config->lock_config($vmid, sub {
293 my $conf = PVE::LXC::Config->set_lock($vmid, 'mounted');
294 PVE::LXC::mount_all($vmid, $storecfg, $conf);
295 });
296
297 print "mounted CT $vmid in '/var/lib/lxc/$vmid/rootfs'\n";
298 return undef;
299 }});
300
301 __PACKAGE__->register_method({
302 name => 'unmount',
303 path => 'unmount',
304 method => 'POST',
305 description => "Unmount the container's filesystem.",
306 parameters => {
307 additionalProperties => 0,
308 properties => {
309 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
310 },
311 },
312 returns => { type => 'null' },
313 code => sub {
314 my ($param) = @_;
315
316 my $rpcenv = PVE::RPCEnvironment::get();
317
318 my $vmid = extract_param($param, 'vmid');
319 my $storecfg = PVE::Storage::config();
320 PVE::LXC::Config->lock_config($vmid, sub {
321 my $conf = PVE::LXC::Config->load_config($vmid);
322 PVE::LXC::umount_all($vmid, $storecfg, $conf, 0);
323 PVE::LXC::Config->remove_lock($vmid, 'mounted');
324 });
325 return undef;
326 }});
327
328 __PACKAGE__->register_method({
329 name => 'df',
330 path => 'df',
331 method => 'GET',
332 description => "Get the container's current disk usage.",
333 parameters => {
334 additionalProperties => 0,
335 properties => {
336 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
337 },
338 },
339 returns => { type => 'null' },
340 code => sub {
341 my ($param) = @_;
342
343 my $rpcenv = PVE::RPCEnvironment::get();
344
345 # JSONSchema's format_size is exact, this uses floating point numbers
346 my $format = sub {
347 my ($size) = @_;
348 return $size if $size < 1024.;
349 $size /= 1024.;
350 return sprintf('%.1fK', ${size}) if $size < 1024.;
351 $size /= 1024.;
352 return sprintf('%.1fM', ${size}) if $size < 1024.;
353 $size /= 1024.;
354 return sprintf('%.1fG', ${size}) if $size < 1024.;
355 $size /= 1024.;
356 return sprintf('%.1fT', ${size}) if $size < 1024.;
357 };
358
359 my $vmid = extract_param($param, 'vmid');
360 PVE::LXC::Config->lock_config($vmid, sub {
361 my $pid = eval { PVE::LXC::find_lxc_pid($vmid) };
362 my ($conf, $rootdir, $storecfg, $mounted);
363 if ($@ || !$pid) {
364 $conf = PVE::LXC::Config->set_lock($vmid, 'mounted');
365 $rootdir = "/var/lib/lxc/$vmid/rootfs";
366 $storecfg = PVE::Storage::config();
367 PVE::LXC::mount_all($vmid, $storecfg, $conf);
368 $mounted = 1;
369 } else {
370 $conf = PVE::LXC::Config->load_config($vmid);
371 $rootdir = "/proc/$pid/root";
372 }
373
374 my @list = [qw(MP Volume Size Used Avail Use% Path)];
375 my @len = map { length($_) } @{$list[0]};
376
377 eval {
378 PVE::LXC::Config->foreach_volume($conf, sub {
379 my ($name, $mp) = @_;
380 my $path = $mp->{mp};
381
382 my $df = PVE::Tools::df("$rootdir/$path", 3);
383 my $total = $format->($df->{total});
384 my $used = $format->($df->{used});
385 my $avail = $format->($df->{avail});
386
387 my $pc = sprintf('%.1f', $df->{used}/$df->{total});
388
389 my $entry = [ $name, $mp->{volume}, $total, $used, $avail, $pc, $path ];
390 push @list, $entry;
391
392 foreach my $i (0..5) {
393 $len[$i] = length($entry->[$i])
394 if $len[$i] < length($entry->[$i]);
395 }
396 });
397
398 my $format = "%-$len[0]s %-$len[1]s %$len[2]s %$len[3]s %$len[4]s %$len[5]s %s\n";
399 printf($format, @$_) foreach @list;
400 };
401 warn $@ if $@;
402
403 if ($mounted) {
404 PVE::LXC::umount_all($vmid, $storecfg, $conf, 0);
405 PVE::LXC::Config->remove_lock($vmid, 'mounted');
406 }
407 });
408 return undef;
409 }});
410
411 # File creation with specified ownership and permissions.
412 # User and group can be names or decimal numbers.
413 # Permissions are explicit (not affected by umask) and can be numeric with the
414 # usual 0/0x prefixes for octal/hex.
415 sub create_file {
416 my ($path, $perms, $user, $group) = @_;
417 my ($uid, $gid);
418 if (defined($user)) {
419 if ($user =~ /^\d+$/) {
420 $uid = int($user);
421 } else {
422 $uid = getpwnam($user);
423 die "failed to get uid for: $user\n" if !defined($uid);
424 }
425 }
426 if (defined($group)) {
427 if ($group =~ /^\d+$/) {
428 $gid = int($group);
429 } else {
430 $gid = getgrnam($group);
431 die "failed to get gid for: $group\n" if !defined($gid);
432 }
433 }
434
435 if (defined($perms)) {
436 $! = 0;
437 my ($mode, $unparsed) = POSIX::strtoul($perms, 0);
438 die "invalid mode: '$perms'\n" if $perms eq '' || $unparsed > 0 || $!;
439 $perms = $mode;
440 }
441
442 my $fd;
443 if (sysopen($fd, $path, O_WRONLY | O_CREAT | O_EXCL, 0)) {
444 $perms = 0666 & ~umask if !defined($perms);
445 } else {
446 # If the path previously existed then we do not care about left-over
447 # file descriptors even if the permissions/ownership is changed.
448 sysopen($fd, $path, O_WRONLY | O_CREAT | O_TRUNC)
449 or die "failed to create file: $path: $!\n";
450 }
451
452 my $trunc = 0;
453
454 if (defined($perms)) {
455 $trunc = 1;
456 chmod($perms, $fd);
457 }
458
459 if (defined($uid) || defined($gid)) {
460 $trunc = 1;
461 my ($fuid, $fgid) = (stat($fd))[4,5] if !defined($uid) || !defined($gid);
462 $uid = $fuid if !defined($uid);
463 $gid = $fgid if !defined($gid);
464 chown($uid, $gid, $fd)
465 or die "failed to change file owner: $!\n";
466 }
467 return $fd;
468 }
469
470 __PACKAGE__->register_method ({
471 name => 'rescan',
472 path => 'rescan',
473 method => 'POST',
474 description => "Rescan all storages and update disk sizes and unused disk images.",
475 parameters => {
476 additionalProperties => 0,
477 properties => {
478 vmid => get_standard_option('pve-vmid', {
479 optional => 1,
480 completion => \&PVE::LXC::complete_ctid,
481 }),
482 dryrun => {
483 type => 'boolean',
484 optional => 1,
485 default => 0,
486 description => 'Do not actually write changes out to conifg.',
487 },
488 },
489 },
490 returns => { type => 'null'},
491 code => sub {
492 my ($param) = @_;
493
494 my $dryrun = $param->{dryrun};
495
496 print "NOTE: running in dry-run mode, won't write changes out!\n" if $dryrun;
497
498 PVE::LXC::rescan($param->{vmid}, 0, $dryrun);
499
500 return undef;
501 }});
502
503 __PACKAGE__->register_method({
504 name => 'pull',
505 path => 'pull',
506 method => 'PUT',
507 description => "Copy a file from the container to the local system.",
508 parameters => {
509 additionalProperties => 0,
510 properties => {
511 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
512 path => {
513 type => 'string',
514 description => "Path to a file inside the container to pull.",
515 },
516 destination => {
517 type => 'string',
518 description => "Destination",
519 },
520 user => {
521 type => 'string',
522 description => 'Owner user name or id.',
523 optional => 1,
524 },
525 group => {
526 type => 'string',
527 description => 'Owner group name or id.',
528 optional => 1,
529 },
530 perms => {
531 type => 'string',
532 description => "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
533 optional => 1,
534 },
535 },
536 },
537 returns => {
538 type => 'string',
539 description => "the task ID.",
540 },
541 code => sub {
542 my ($param) = @_;
543
544 my $rpcenv = PVE::RPCEnvironment::get();
545
546 my $vmid = extract_param($param, 'vmid');
547 my $path = extract_param($param, 'path');
548 my $dest = extract_param($param, 'destination');
549
550 my $perms = extract_param($param, 'perms');
551 # assume octal as default
552 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
553 my $user = extract_param($param, 'user');
554 my $group = extract_param($param, 'group');
555
556 my $code = sub {
557 my $running = PVE::LXC::check_running($vmid);
558 die "can only pull files from a running VM" if !$running;
559
560 my $realcmd = sub {
561 my $pid = PVE::LXC::find_lxc_pid($vmid);
562 # Avoid symlink issues by opening the files from inside the
563 # corresponding namespaces.
564 my $destfd = create_file($dest, $perms, $user, $group);
565
566 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
567 or die "failed to open the container's mount namespace\n";
568 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
569 or die "failed to enter the container's mount namespace\n";
570 close($mntnsfd);
571 chdir('/') or die "failed to change to container root directory\n";
572
573 open my $srcfd, '<', $path
574 or die "failed to open $path: $!\n";
575
576 copy($srcfd, $destfd);
577 };
578
579 # This avoids having to setns() back to our namespace.
580 return $rpcenv->fork_worker('pull_file', $vmid, undef, $realcmd);
581 };
582
583 return PVE::LXC::Config->lock_config($vmid, $code);
584 }});
585
586 __PACKAGE__->register_method({
587 name => 'push',
588 path => 'push',
589 method => 'PUT',
590 description => "Copy a local file to the container.",
591 parameters => {
592 additionalProperties => 0,
593 properties => {
594 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
595 file => {
596 type => 'string',
597 description => "Path to a local file.",
598 },
599 destination => {
600 type => 'string',
601 description => "Destination inside the container to write to.",
602 },
603 user => {
604 type => 'string',
605 description => 'Owner user name or id. When using a name it must exist inside the container.',
606 optional => 1,
607 },
608 group => {
609 type => 'string',
610 description => 'Owner group name or id. When using a name it must exist inside the container.',
611 optional => 1,
612 },
613 perms => {
614 type => 'string',
615 description => "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
616 optional => 1,
617 },
618 },
619 },
620 returns => {
621 type => 'string',
622 description => "the task ID.",
623 },
624 code => sub {
625 my ($param) = @_;
626
627 my $rpcenv = PVE::RPCEnvironment::get();
628
629 my $vmid = extract_param($param, 'vmid');
630 my $file = extract_param($param, 'file');
631 my $dest = extract_param($param, 'destination');
632
633 my $perms = extract_param($param, 'perms');
634 # assume octal as default
635 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
636 my $user = extract_param($param, 'user');
637 my $group = extract_param($param, 'group');
638
639 my $code = sub {
640 my $running = PVE::LXC::check_running($vmid);
641 die "can only push files to a running CT\n" if !$running;
642
643 my $conf = PVE::LXC::Config->load_config($vmid);
644 my $unprivileged = $conf->{unprivileged};
645
646 my $realcmd = sub {
647 my $pid = PVE::LXC::find_lxc_pid($vmid);
648 # We open the file then enter the container's mount - and for
649 # unprivileged containers - user namespace and then create the
650 # file. This avoids symlink attacks as a symlink cannot point
651 # outside the namespace and our own access is equivalent to the
652 # container-local's root user. Also the user-passed -user and
653 # -group parameters will use the container-local's user and
654 # group names.
655 sysopen my $srcfd, $file, O_RDONLY
656 or die "failed to open $file for reading\n";
657
658 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
659 or die "failed to open the container's mount namespace\n";
660 my $usernsfd;
661 if ($unprivileged) {
662 sysopen $usernsfd, "/proc/$pid/ns/user", O_RDONLY
663 or die "failed to open the container's user namespace\n";
664 }
665
666 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
667 or die "failed to enter the container's mount namespace\n";
668 close($mntnsfd);
669 chdir('/') or die "failed to change to container root directory\n";
670
671 if ($unprivileged) {
672 PVE::Tools::setns(fileno($usernsfd), PVE::Tools::CLONE_NEWUSER)
673 or die "failed to enter the container's user namespace\n";
674 close($usernsfd);
675 POSIX::setgid(0) or die "setgid failed: $!\n";
676 POSIX::setuid(0) or die "setuid failed: $!\n";
677 }
678
679 my $destfd = create_file($dest, $perms, $user, $group);
680 copy($srcfd, $destfd);
681 };
682
683 # This avoids having to setns() back to our namespace.
684 return $rpcenv->fork_worker('push_file', $vmid, undef, $realcmd);
685 };
686
687 return PVE::LXC::Config->lock_config($vmid, $code);
688 }});
689
690 __PACKAGE__->register_method ({
691 name => 'cpusets',
692 path => 'cpusets',
693 method => 'GET',
694 description => "Print the list of assigned CPU sets.",
695 parameters => {
696 additionalProperties => 0,
697 properties => {},
698 },
699 returns => { type => 'null'},
700 code => sub {
701 my ($param) = @_;
702
703 my $ctlist = PVE::LXC::config_list();
704
705 my $len = 0;
706 my $id_len = 0;
707 my $res = {};
708
709 foreach my $vmid (sort keys %$ctlist) {
710 my $cgroup = PVE::LXC::CGroup->new($vmid);
711
712 my ($cpuset, $path);
713 if (defined($path = $cgroup->get_path('cpuset'))) {
714 $cpuset = eval { PVE::CpuSet->new_from_path($path); };
715 } elsif (defined($path = $cgroup->get_path())) {
716 $cpuset = eval { PVE::CpuSet->new_from_path($path); };
717 } else {
718 # Container not running.
719 next;
720 }
721 if (my $err = $@) {
722 warn $err;
723 next;
724 }
725
726 my @cpuset_members = $cpuset->members();
727
728 my $line = ': ';
729
730 my $last = $cpuset_members[-1];
731
732 for (my $id = 0; $id <= $last; $id++) {
733 my $empty = ' ' x length("$id");
734 $line .= ' ' . ($cpuset->has($id) ? $id : $empty);
735 }
736 $len = length($line) if length($line) > $len;
737 $id_len = length($vmid) if length($vmid) > $id_len;
738
739 $res->{$vmid} = $line;
740 }
741
742 my @vmlist = sort keys %$res;
743
744 if (scalar(@vmlist)) {
745 my $header = '-' x ($len + $id_len) . "\n";
746
747 print $header;
748 foreach my $vmid (@vmlist) {
749 print sprintf("%${id_len}i%s\n", $vmid, $res->{$vmid});
750 }
751 print $header;
752
753 } else {
754 print "no running containers\n";
755 }
756
757 return undef;
758 }});
759
760 __PACKAGE__->register_method ({
761 name => 'fstrim',
762 path => 'fstrim',
763 method => 'POST',
764 description => "Run fstrim on a chosen CT and its mountpoints.",
765 parameters => {
766 additionalProperties => 0,
767 properties => {
768 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
769 'ignore-mountpoints' => {
770 description => 'Skip all mountpoints, only do fstrim on the container root.',
771 optional => 1,
772 type => 'boolean',
773 },
774 },
775 },
776 returns => { type => 'null' },
777 code => sub {
778
779 my ($param) = @_;
780 my $vmid = $param->{'vmid'};
781
782 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
783
784 my $storecfg = PVE::Storage::config();
785 my $conf = PVE::LXC::Config->set_lock($vmid, 'fstrim');
786 eval {
787 my $path = "";
788 PVE::LXC::mount_all($vmid, $storecfg, $conf);
789 PVE::LXC::Config->foreach_volume($conf, sub {
790 my ($name, $mp) = @_;
791 $path = $mp->{mp};
792 return if $param->{'ignore-mountpoints'} && $name =~ /^mp\d+/;
793 my $cmd = ["fstrim", "-v", "$rootdir$path"];
794 PVE::Tools::run_command($cmd);
795 });
796 };
797 warn $@ if $@;
798
799 PVE::LXC::umount_all($vmid, $storecfg, $conf, 0);
800 PVE::LXC::Config->remove_lock($vmid, 'fstrim');
801
802 return undef;
803 }});
804
805 our $cmddef = {
806 list=> [ 'PVE::API2::LXC', 'vmlist', [], { node => $nodename }, sub {
807 my $res = shift;
808 return if !scalar(@$res);
809 my $format = "%-10s %-10s %-12s %-20s\n";
810 printf($format, 'VMID', 'Status', 'Lock', 'Name');
811 foreach my $d (sort {$a->{vmid} <=> $b->{vmid} } @$res) {
812 my $lock = $d->{lock} || '';
813 printf($format, $d->{vmid}, $d->{status}, $lock, $d->{name});
814 }
815 }],
816 config => [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'], { node => $nodename }, sub {
817 my $config = shift;
818 for my $k (sort (keys %$config)) {
819 next if $k eq 'digest' || $k eq 'lxc';
820 my $v = $config->{$k};
821 if ($k eq 'description') {
822 $v = PVE::Tools::encode_text($v);
823 }
824 print "$k: $v\n";
825 }
826 if (defined(my $lxc_list = $config->{'lxc'})) {
827 for my $lxc_opt (@$lxc_list) {
828 print "$lxc_opt->[0]: $lxc_opt->[1]\n"
829 }
830 }
831 }],
832
833 pending => [ "PVE::API2::LXC", "vm_pending", ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
834 set => [ 'PVE::API2::LXC::Config', 'update_vm', ['vmid'], { node => $nodename }],
835
836 resize => [ "PVE::API2::LXC", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
837
838 create => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename }, $upid_exit ],
839 restore => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename, restore => 1 }, $upid_exit ],
840 destroy => [ 'PVE::API2::LXC', 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
841
842 start => [ 'PVE::API2::LXC::Status', 'vm_start', ['vmid'], { node => $nodename }, $upid_exit],
843 suspend => [ 'PVE::API2::LXC::Status', 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit],
844 resume => [ 'PVE::API2::LXC::Status', 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit],
845 shutdown => [ 'PVE::API2::LXC::Status', 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit],
846 stop => [ 'PVE::API2::LXC::Status', 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit],
847 reboot => [ 'PVE::API2::LXC::Status', 'vm_reboot', ['vmid'], { node => $nodename }, $upid_exit],
848
849 clone => [ "PVE::API2::LXC", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
850 migrate => [ "PVE::API2::LXC", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit],
851 move_volume => [ "PVE::API2::LXC", 'move_volume', ['vmid', 'volume', 'storage'], { node => $nodename }, $upid_exit ],
852
853 snapshot => [ "PVE::API2::LXC::Snapshot", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
854 delsnapshot => [ "PVE::API2::LXC::Snapshot", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
855 listsnapshot => [ "PVE::API2::LXC::Snapshot", 'list', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::print_snapshot_tree ],
856 rollback => [ "PVE::API2::LXC::Snapshot", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
857 template => [ "PVE::API2::LXC", 'template', ['vmid'], { node => $nodename }],
858
859 status => [ __PACKAGE__, 'status', ['vmid']],
860 console => [ __PACKAGE__, 'console', ['vmid']],
861 enter => [ __PACKAGE__, 'enter', ['vmid']],
862 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
863 exec => [ __PACKAGE__, 'exec', ['vmid', 'extra-args']],
864 fsck => [ __PACKAGE__, 'fsck', ['vmid']],
865
866 mount => [ __PACKAGE__, 'mount', ['vmid']],
867 unmount => [ __PACKAGE__, 'unmount', ['vmid']],
868 push => [ __PACKAGE__, 'push', ['vmid', 'file', 'destination']],
869 pull => [ __PACKAGE__, 'pull', ['vmid', 'path', 'destination']],
870
871 df => [ __PACKAGE__, 'df', ['vmid']],
872 rescan => [ __PACKAGE__, 'rescan', []],
873 cpusets => [ __PACKAGE__, 'cpusets', []],
874 fstrim => [ __PACKAGE__, 'fstrim', ['vmid']],
875 };
876
877
878 1;