]> git.proxmox.com Git - pve-container.git/blob - src/PVE/CLI/pct.pm
1c04329ff732499375878933d2590a111f6a23cb
[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 use Term::ReadLine;
10
11 use PVE::SafeSyslog;
12 use PVE::Tools qw(extract_param);
13 use PVE::Cluster;
14 use PVE::INotify;
15 use PVE::RPCEnvironment;
16 use PVE::JSONSchema qw(get_standard_option);
17 use PVE::CLIHandler;
18 use PVE::API2::LXC;
19 use PVE::API2::LXC::Config;
20 use PVE::API2::LXC::Status;
21 use PVE::API2::LXC::Snapshot;
22
23 use Data::Dumper;
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 read_password {
36 my $term = new Term::ReadLine ('pct');
37 my $attribs = $term->Attribs;
38 $attribs->{redisplay_function} = $attribs->{shadow_redisplay};
39 my $input = $term->readline('Enter password: ');
40 my $conf = $term->readline('Retype password: ');
41 die "Passwords do not match.\n" if ($input ne $conf);
42 return $input;
43 }
44
45 sub string_param_file_mapping {
46 my ($name) = @_;
47
48 my $mapping = {
49 'create_vm' => ['ssh-public-keys'],
50 };
51
52 return defined($mapping->{$name}) ? $mapping->{$name} : [];
53 }
54
55 __PACKAGE__->register_method ({
56 name => 'unlock',
57 path => 'unlock',
58 method => 'PUT',
59 description => "Unlock the VM.",
60 parameters => {
61 additionalProperties => 0,
62 properties => {
63 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
64 },
65 },
66 returns => { type => 'null'},
67 code => sub {
68 my ($param) = @_;
69
70 my $vmid = $param->{vmid};
71
72 PVE::LXC::Config->remove_lock($vmid);
73
74 return undef;
75 }});
76
77 __PACKAGE__->register_method ({
78 name => 'console',
79 path => 'console',
80 method => 'GET',
81 description => "Launch a console for the specified container.",
82 parameters => {
83 additionalProperties => 0,
84 properties => {
85 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
86 },
87 },
88 returns => { type => 'null' },
89
90 code => sub {
91 my ($param) = @_;
92
93 # test if container exists on this node
94 my $conf = PVE::LXC::Config->load_config($param->{vmid});
95
96 my $cmd = PVE::LXC::get_console_command($param->{vmid}, $conf);
97 exec(@$cmd);
98 }});
99
100 __PACKAGE__->register_method ({
101 name => 'enter',
102 path => 'enter',
103 method => 'GET',
104 description => "Launch a shell for the specified container.",
105 parameters => {
106 additionalProperties => 0,
107 properties => {
108 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
109 },
110 },
111 returns => { type => 'null' },
112
113 code => sub {
114 my ($param) = @_;
115
116 my $vmid = $param->{vmid};
117
118 # test if container exists on this node
119 PVE::LXC::Config->load_config($vmid);
120
121 die "Error: container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
122
123 exec('lxc-attach', '-n', $vmid);
124 }});
125
126 __PACKAGE__->register_method ({
127 name => 'exec',
128 path => 'exec',
129 method => 'GET',
130 description => "Launch a command inside the specified container.",
131 parameters => {
132 additionalProperties => 0,
133 properties => {
134 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
135 'extra-args' => get_standard_option('extra-args'),
136 },
137 },
138 returns => { type => 'null' },
139
140 code => sub {
141 my ($param) = @_;
142
143 # test if container exists on this node
144 PVE::LXC::Config->load_config($param->{vmid});
145
146 if (!@{$param->{'extra-args'}}) {
147 die "missing command";
148 }
149 exec('lxc-attach', '-n', $param->{vmid}, '--', @{$param->{'extra-args'}});
150 }});
151
152 __PACKAGE__->register_method ({
153 name => 'fsck',
154 path => 'fsck',
155 method => 'PUT',
156 description => "Run a filesystem check (fsck) on a container volume.",
157 parameters => {
158 additionalProperties => 0,
159 properties => {
160 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_stopped }),
161 force => {
162 optional => 1,
163 type => 'boolean',
164 description => "Force checking, even if the filesystem seems clean",
165 default => 0,
166 },
167 device => {
168 optional => 1,
169 type => 'string',
170 description => "A volume on which to run the filesystem check",
171 enum => [PVE::LXC::Config->mountpoint_names()],
172 },
173 },
174 },
175 returns => { type => 'null' },
176 code => sub {
177
178 my ($param) = @_;
179 my $vmid = $param->{'vmid'};
180 my $device = defined($param->{'device'}) ? $param->{'device'} : 'rootfs';
181
182 my $command = ['fsck', '-a', '-l'];
183 push(@$command, '-f') if $param->{force};
184
185 # critical path: all of this will be done while the container is locked
186 my $do_fsck = sub {
187
188 my $conf = PVE::LXC::Config->load_config($vmid);
189 my $storage_cfg = PVE::Storage::config();
190
191 defined($conf->{$device}) || die "cannot run command on unexisting mountpoint $device\n";
192
193 my $mount_point = $device eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($conf->{$device}) :
194 PVE::LXC::Config->parse_ct_mountpoint($conf->{$device});
195
196 my $volid = $mount_point->{volume};
197
198 my $path;
199 my $storage_id = PVE::Storage::parse_volume_id($volid, 1);
200
201 if ($storage_id) {
202 my (undef, undef, undef, undef, undef, undef, $format) =
203 PVE::Storage::parse_volname($storage_cfg, $volid);
204
205 die "unable to run fsck for '$volid' (format == $format)\n"
206 if $format ne 'raw';
207
208 $path = PVE::Storage::path($storage_cfg, $volid);
209
210 } else {
211 if (($volid =~ m|^/.+|) && (-b $volid)) {
212 # pass block devices directly
213 $path = $volid;
214 } else {
215 die "path '$volid' does not point to a block device\n";
216 }
217 }
218
219 push(@$command, $path);
220
221 PVE::LXC::check_running($vmid) &&
222 die "cannot run fsck on active container\n";
223
224 PVE::Tools::run_command($command);
225 };
226
227 PVE::LXC::Config->lock_config($vmid, $do_fsck);
228 return undef;
229 }});
230
231 __PACKAGE__->register_method({
232 name => 'mount',
233 path => 'mount',
234 method => 'POST',
235 description => "Mount the container's filesystem on the host. " .
236 "This will hold a lock on the container and is meant for emergency maintenance only " .
237 "as it will prevent further operations on the container other than start and stop.",
238 parameters => {
239 additionalProperties => 0,
240 properties => {
241 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
242 },
243 },
244 returns => { type => 'null' },
245 code => sub {
246 my ($param) = @_;
247
248 my $rpcenv = PVE::RPCEnvironment::get();
249
250 my $vmid = extract_param($param, 'vmid');
251 my $storecfg = PVE::Storage::config();
252 PVE::LXC::Config->lock_config($vmid, sub {
253 my $conf = PVE::LXC::Config->set_lock($vmid, 'mounted');
254 PVE::LXC::mount_all($vmid, $storecfg, $conf);
255 });
256 return undef;
257 }});
258
259 __PACKAGE__->register_method({
260 name => 'unmount',
261 path => 'unmount',
262 method => 'POST',
263 description => "Unmount the container's filesystem.",
264 parameters => {
265 additionalProperties => 0,
266 properties => {
267 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
268 },
269 },
270 returns => { type => 'null' },
271 code => sub {
272 my ($param) = @_;
273
274 my $rpcenv = PVE::RPCEnvironment::get();
275
276 my $vmid = extract_param($param, 'vmid');
277 my $storecfg = PVE::Storage::config();
278 PVE::LXC::Config->lock_config($vmid, sub {
279 my $conf = PVE::LXC::Config->load_config($vmid);
280 PVE::LXC::umount_all($vmid, $storecfg, $conf, 0);
281 PVE::LXC::Config->remove_lock($vmid, 'mounted');
282 });
283 return undef;
284 }});
285
286 # File creation with specified ownership and permissions.
287 # User and group can be names or decimal numbers.
288 # Permissions are explicit (not affected by umask) and can be numeric with the
289 # usual 0/0x prefixes for octal/hex.
290 sub create_file {
291 my ($path, $perms, $user, $group) = @_;
292 my ($uid, $gid);
293 if (defined($user)) {
294 if ($user =~ /^\d+$/) {
295 $uid = int($user);
296 } else {
297 $uid = getpwnam($user) or die "failed to get uid for: $user\n"
298 }
299 }
300 if (defined($group)) {
301 if ($group =~ /^\d+$/) {
302 $gid = int($group);
303 } else {
304 $gid = getgrnam($group) or die "failed to get gid for: $group\n"
305 }
306 }
307
308 if (defined($perms)) {
309 $! = 0;
310 my ($mode, $unparsed) = POSIX::strtoul($perms, 0);
311 die "invalid mode: '$perms'\n" if $perms eq '' || $unparsed > 0 || $!;
312 $perms = $mode;
313 }
314
315 my $fd;
316 if (sysopen($fd, $path, O_WRONLY | O_CREAT | O_EXCL, 0)) {
317 $perms = 0666 & ~umask if !defined($perms);
318 } else {
319 # If the path previously existed then we do not care about left-over
320 # file descriptors even if the permissions/ownership is changed.
321 sysopen($fd, $path, O_WRONLY | O_CREAT | O_TRUNC)
322 or die "failed to create file: $path: $!\n";
323 }
324
325 my $trunc = 0;
326
327 if (defined($perms)) {
328 $trunc = 1;
329 chmod($perms, $fd);
330 }
331
332 if (defined($uid) || defined($gid)) {
333 $trunc = 1;
334 my ($fuid, $fgid) = (stat($fd))[4,5] if !defined($uid) || !defined($gid);
335 $uid = $fuid if !defined($uid);
336 $gid = $fgid if !defined($gid);
337 chown($uid, $gid, $fd)
338 or die "failed to change file owner: $!\n";
339 }
340 return $fd;
341 }
342
343 __PACKAGE__->register_method({
344 name => 'pull',
345 path => 'pull',
346 method => 'PUT',
347 description => "Copy a file from the container to the local system.",
348 parameters => {
349 additionalProperties => 0,
350 properties => {
351 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
352 path => {
353 type => 'string',
354 description => "Path to a file inside the container to pull.",
355 },
356 destination => {
357 type => 'string',
358 description => "Destination",
359 },
360 user => {
361 type => 'string',
362 description => 'Owner user name or id.',
363 optional => 1,
364 },
365 group => {
366 type => 'string',
367 description => 'Owner group name or id.',
368 optional => 1,
369 },
370 perms => {
371 type => 'string',
372 description => 'File permissions to use.',
373 optional => 1,
374 },
375 },
376 },
377 returns => {
378 type => 'string',
379 description => "the task ID.",
380 },
381 code => sub {
382 my ($param) = @_;
383
384 my $rpcenv = PVE::RPCEnvironment::get();
385
386 my $vmid = extract_param($param, 'vmid');
387 my $path = extract_param($param, 'path');
388 my $dest = extract_param($param, 'destination');
389
390 my $perms = extract_param($param, 'perms');
391 my $user = extract_param($param, 'user');
392 my $group = extract_param($param, 'group');
393
394 my $code = sub {
395 my $running = PVE::LXC::check_running($vmid);
396 die "can only pull files from a running VM" if !$running;
397
398 my $realcmd = sub {
399 my $pid = PVE::LXC::find_lxc_pid($vmid);
400 # Avoid symlink issues by opening the files from inside the
401 # corresponding namespaces.
402 my $destfd = create_file($dest, $perms, $user, $group);
403
404 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
405 or die "failed to open the container's mount namespace\n";
406 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
407 or die "failed to enter the container's mount namespace\n";
408 close($mntnsfd);
409 chdir('/') or die "failed to change to container root directory\n";
410
411 open my $srcfd, '<', $path
412 or die "failed to open $path: $!\n";
413
414 copy($srcfd, $destfd);
415 };
416
417 # This avoids having to setns() back to our namespace.
418 return $rpcenv->fork_worker('pull_file', $vmid, undef, $realcmd);
419 };
420
421 return PVE::LXC::Config->lock_config($vmid, $code);
422 }});
423
424 __PACKAGE__->register_method({
425 name => 'push',
426 path => 'push',
427 method => 'PUT',
428 description => "Copy a local file to the container.",
429 parameters => {
430 additionalProperties => 0,
431 properties => {
432 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
433 file => {
434 type => 'string',
435 description => "Path to a local file.",
436 },
437 destination => {
438 type => 'string',
439 description => "Destination inside the container to write to.",
440 },
441 user => {
442 type => 'string',
443 description => 'Owner user name or id. When using a name it must exist inside the container.',
444 optional => 1,
445 },
446 group => {
447 type => 'string',
448 description => 'Owner group name or id. When using a name it must exist inside the container.',
449 optional => 1,
450 },
451 perms => {
452 type => 'string',
453 description => 'File permissions to use.',
454 optional => 1,
455 },
456 },
457 },
458 returns => {
459 type => 'string',
460 description => "the task ID.",
461 },
462 code => sub {
463 my ($param) = @_;
464
465 my $rpcenv = PVE::RPCEnvironment::get();
466
467 my $vmid = extract_param($param, 'vmid');
468 my $file = extract_param($param, 'file');
469 my $dest = extract_param($param, 'destination');
470
471 my $perms = extract_param($param, 'perms');
472 my $user = extract_param($param, 'user');
473 my $group = extract_param($param, 'group');
474
475 my $code = sub {
476 my $running = PVE::LXC::check_running($vmid);
477 die "can only push files to a running VM" if !$running;
478
479 my $conf = PVE::LXC::Config->load_config($vmid);
480 my $unprivileged = $conf->{unprivileged};
481
482 my $realcmd = sub {
483 my $pid = PVE::LXC::find_lxc_pid($vmid);
484 # We open the file then enter the container's mount - and for
485 # unprivileged containers - user namespace and then create the
486 # file. This avoids symlink attacks as a symlink cannot point
487 # outside the namespace and our own access is equivalent to the
488 # container-local's root user. Also the user-passed -user and
489 # -group parameters will use the container-local's user and
490 # group names.
491 sysopen my $srcfd, $file, O_RDONLY
492 or die "failed to open $file for reading\n";
493
494 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
495 or die "failed to open the container's mount namespace\n";
496 my $usernsfd;
497 if ($unprivileged) {
498 sysopen $usernsfd, "/proc/$pid/ns/user", O_RDONLY
499 or die "failed to open the container's user namespace\n";
500 }
501
502 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
503 or die "failed to enter the container's mount namespace\n";
504 close($mntnsfd);
505 chdir('/') or die "failed to change to container root directory\n";
506
507 if ($unprivileged) {
508 PVE::Tools::setns(fileno($usernsfd), PVE::Tools::CLONE_NEWUSER)
509 or die "failed to enter the container's user namespace\n";
510 close($usernsfd);
511 POSIX::setgid(0) or die "setgid failed: $!\n";
512 POSIX::setuid(0) or die "setuid failed: $!\n";
513 }
514
515 my $destfd = create_file($dest, $perms, $user, $group);
516 copy($srcfd, $destfd);
517 };
518
519 # This avoids having to setns() back to our namespace.
520 return $rpcenv->fork_worker('push_file', $vmid, undef, $realcmd);
521 };
522
523 return PVE::LXC::Config->lock_config($vmid, $code);
524 }});
525
526 our $cmddef = {
527 list=> [ 'PVE::API2::LXC', 'vmlist', [], { node => $nodename }, sub {
528 my $res = shift;
529 return if !scalar(@$res);
530 my $format = "%-10s %-10s %-12s %-20s\n";
531 printf($format, 'VMID', 'Status', 'Lock', 'Name');
532 foreach my $d (sort {$a->{vmid} <=> $b->{vmid} } @$res) {
533 printf($format, $d->{vmid}, $d->{status}, $d->{lock}, $d->{name});
534 }
535 }],
536 config => [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'],
537 { node => $nodename }, sub {
538 my $config = shift;
539 foreach my $k (sort (keys %$config)) {
540 next if $k eq 'digest';
541 my $v = $config->{$k};
542 if ($k eq 'description') {
543 $v = PVE::Tools::encode_text($v);
544 }
545 print "$k: $v\n";
546 }
547 }],
548 set => [ 'PVE::API2::LXC::Config', 'update_vm', ['vmid'], { node => $nodename }],
549
550 resize => [ "PVE::API2::LXC", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
551
552 create => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename }, $upid_exit ],
553 restore => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename, restore => 1 }, $upid_exit ],
554
555 start => [ 'PVE::API2::LXC::Status', 'vm_start', ['vmid'], { node => $nodename }, $upid_exit],
556 suspend => [ 'PVE::API2::LXC::Status', 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit],
557 resume => [ 'PVE::API2::LXC::Status', 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit],
558 shutdown => [ 'PVE::API2::LXC::Status', 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit],
559 stop => [ 'PVE::API2::LXC::Status', 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit],
560
561 clone => [ "PVE::API2::LXC", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
562 migrate => [ "PVE::API2::LXC", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit],
563
564 console => [ __PACKAGE__, 'console', ['vmid']],
565 enter => [ __PACKAGE__, 'enter', ['vmid']],
566 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
567 exec => [ __PACKAGE__, 'exec', ['vmid', 'extra-args']],
568 fsck => [ __PACKAGE__, 'fsck', ['vmid']],
569
570 mount => [ __PACKAGE__, 'mount', ['vmid']],
571 unmount => [ __PACKAGE__, 'unmount', ['vmid']],
572 push => [ __PACKAGE__, 'push', ['vmid', 'file', 'destination']],
573 pull => [ __PACKAGE__, 'pull', ['vmid', 'path', 'destination']],
574
575 destroy => [ 'PVE::API2::LXC', 'destroy_vm', ['vmid'],
576 { node => $nodename }, $upid_exit ],
577
578 snapshot => [ "PVE::API2::LXC::Snapshot", 'snapshot', ['vmid', 'snapname'],
579 { node => $nodename } , $upid_exit ],
580
581 delsnapshot => [ "PVE::API2::LXC::Snapshot", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
582
583 listsnapshot => [ "PVE::API2::LXC::Snapshot", 'list', ['vmid'], { node => $nodename },
584 sub {
585 my $res = shift;
586 foreach my $e (@$res) {
587 my $headline = $e->{description} || 'no-description';
588 $headline =~ s/\n.*//sg;
589 my $parent = $e->{parent} // 'no-parent';
590 printf("%-20s %-20s %s\n", $e->{name}, $parent, $headline);
591 }
592 }],
593
594 rollback => [ "PVE::API2::LXC::Snapshot", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
595
596 template => [ "PVE::API2::LXC", 'template', ['vmid'], { node => $nodename }],
597 };
598
599
600 1;
601
602 __END__
603
604 =head1 NAME
605
606 pct - Tool to manage Linux Containers (LXC) on Proxmox VE
607
608 =head1 SYNOPSIS
609
610 =include synopsis
611
612 =head1 DESCRIPTION
613
614 pct is a tool to manages Linux Containers (LXC). You can create
615 and destroy containers, and control execution
616 (start/stop/suspend/resume). Besides that, you can use pct to set
617 parameters in the associated config file, like network configuration or
618 memory.
619
620 =head1 EXAMPLES
621
622 Create a container based on a Debian template
623 (provided you downloaded the template via the webgui before)
624
625 pct create 100 /var/lib/vz/template/cache/debian-8.0-standard_8.0-1_amd64.tar.gz
626
627 Start a container
628
629 pct start 100
630
631 Start a login session via getty
632
633 pct console 100
634
635 Enter the lxc namespace and run a shell as root user
636
637 pct enter 100
638
639 Display the configuration
640
641 pct config 100
642
643 Add a network interface called eth0, bridged to the host bridge vmbr0,
644 set the address and gateway, while it's running
645
646 pct set 100 -net0 name=eth0,bridge=vmbr0,ip=192.168.15.147/24,gw=192.168.15.1
647
648 Reduce the memory of the container to 512MB
649
650 pct set -memory 512 100
651
652 =head1 FILES
653
654 /etc/pve/lxc/<vmid>.conf
655
656 Configuration file for the container <vmid>
657
658 =head1 SEE ALSO
659
660 L<B<qm(1)>>, L<B<pvesh(1)>>
661
662 =include pve_copyright