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