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