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