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