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