]> git.proxmox.com Git - pve-container.git/blame - src/PVE/CLI/pct.pm
Implement pct push/pull
[pve-container.git] / src / PVE / CLI / pct.pm
CommitLineData
9beee926
DM
1package PVE::CLI::pct;
2
3use strict;
4use warnings;
5
b95bf64b
WB
6use POSIX;
7use Fcntl;
8use File::Copy 'copy';
9
9beee926
DM
10use PVE::SafeSyslog;
11use PVE::Tools qw(extract_param);
12use PVE::Cluster;
13use PVE::INotify;
14use PVE::RPCEnvironment;
15use PVE::JSONSchema qw(get_standard_option);
16use PVE::CLIHandler;
17use PVE::API2::LXC;
18use PVE::API2::LXC::Config;
19use PVE::API2::LXC::Status;
20use PVE::API2::LXC::Snapshot;
21
22use Data::Dumper;
23
24use base qw(PVE::CLIHandler);
25
26my $nodename = PVE::INotify::nodename();
27
28my $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
c72bd0ba
WL
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
3cc56749 51 PVE::LXC::lock_config($vmid, sub {
c72bd0ba
WL
52 my $conf = PVE::LXC::load_config($vmid);
53 delete $conf->{lock};
54 PVE::LXC::write_config($vmid, $conf);
55 });
56
57 return undef;
58 }});
59
9beee926
DM
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::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
d4b3eead
TL
99 my $vmid = $param->{vmid};
100
9beee926 101 # test if container exists on this node
d4b3eead
TL
102 PVE::LXC::load_config($vmid);
103
104 die "Error: container '$vmid' not running!\n" if !PVE::LXC::check_running($vmid);
9beee926 105
d4b3eead 106 exec('lxc-attach', '-n', $vmid);
9beee926
DM
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 => {
4b09527c 117 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid_running }),
9beee926
DM
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::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
5ef9e3d1 135__PACKAGE__->register_method ({
f8327ed5
EK
136 name => 'fsck',
137 path => 'fsck',
138 method => 'PUT',
5ef9e3d1 139 description => "Run a filesystem check (fsck) on a container volume.",
f8327ed5
EK
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::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
44a9face
DM
176 my $mount_point = $device eq 'rootfs' ? PVE::LXC::parse_ct_rootfs($conf->{$device}) :
177 PVE::LXC::parse_ct_mountpoint($conf->{$device});
178
f8327ed5
EK
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) {
f8327ed5 185 my (undef, undef, undef, undef, undef, undef, $format) =
da9e487b 186 PVE::Storage::parse_volname($storage_cfg, $volid);
f8327ed5 187
da9e487b
DM
188 die "unable to run fsck for '$volid' (format == $format)\n"
189 if $format ne 'raw';
f8327ed5
EK
190
191 $path = PVE::Storage::path($storage_cfg, $volid);
192
193 } else {
da9e487b 194 if (($volid =~ m|^/.+|) && (-b $volid)) {
f8327ed5
EK
195 # pass block devices directly
196 $path = $volid;
197 } else {
da9e487b 198 die "path '$volid' does not point to a block device\n";
f8327ed5
EK
199 }
200 }
201
202 push(@$command, $path);
203
da9e487b
DM
204 PVE::LXC::check_running($vmid) &&
205 die "cannot run fsck on active container\n";
206
f8327ed5
EK
207 PVE::Tools::run_command($command);
208 };
209
3cc56749 210 PVE::LXC::lock_config($vmid, $do_fsck);
f8327ed5
EK
211 return undef;
212 }});
213
b95bf64b
WB
214# File creation with specified ownership and permissions.
215# User and group can be names or decimal numbers.
216# Permissions are explicit (not affected by umask) and can be numeric with the
217# usual 0/0x prefixes for octal/hex.
218sub create_file {
219 my ($path, $perms, $user, $group) = @_;
220 my ($uid, $gid);
221 if (defined($user)) {
222 if ($user =~ /^\d+$/) {
223 $uid = int($user);
224 } else {
225 $uid = getpwnam($user) or die "failed to get uid for: $user\n"
226 }
227 }
228 if (defined($group)) {
229 if ($group =~ /^\d+$/) {
230 $gid = int($group);
231 } else {
232 $gid = getgrnam($group) or die "failed to get gid for: $group\n"
233 }
234 }
235
236 if (defined($perms)) {
237 $! = 0;
238 my ($mode, $unparsed) = POSIX::strtoul($perms, 0);
239 die "invalid mode: '$perms'\n" if $perms eq '' || $unparsed > 0 || $!;
240 $perms = $mode;
241 }
242
243 my $fd;
244 if (sysopen($fd, $path, O_WRONLY | O_CREAT | O_EXCL, 0)) {
245 $perms = 0666 & ~umask if !defined($perms);
246 } else {
247 # If the path previously existed then we do not care about left-over
248 # file descriptors even if the permissions/ownership is changed.
249 sysopen($fd, $path, O_WRONLY | O_CREAT | O_TRUNC)
250 or die "failed to create file: $path: $!\n";
251 }
252
253 my $trunc = 0;
254
255 if (defined($perms)) {
256 $trunc = 1;
257 chmod($perms, $fd);
258 }
259
260 if (defined($uid) || defined($gid)) {
261 $trunc = 1;
262 my ($fuid, $fgid) = (stat($fd))[4,5] if !defined($uid) || !defined($gid);
263 $uid = $fuid if !defined($uid);
264 $gid = $fgid if !defined($gid);
265 chown($uid, $gid, $fd)
266 or die "failed to change file owner: $!\n";
267 }
268 return $fd;
269}
270
271__PACKAGE__->register_method({
272 name => 'pull',
273 path => 'pull',
274 method => 'PUT',
275 description => "Copy a file from the container to the local system.",
276 parameters => {
277 additionalProperties => 0,
278 properties => {
279 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
280 path => {
281 type => 'string',
282 description => "Path to a file inside the container to pull.",
283 },
284 destination => {
285 type => 'string',
286 description => "Destination",
287 },
288 user => {
289 type => 'string',
290 description => 'Owner user name or id.',
291 optional => 1,
292 },
293 group => {
294 type => 'string',
295 description => 'Owner group name or id.',
296 optional => 1,
297 },
298 perms => {
299 type => 'string',
300 description => 'File permissions to use.',
301 optional => 1,
302 },
303 },
304 },
305 returns => {
306 type => 'string',
307 description => "the task ID.",
308 },
309 code => sub {
310 my ($param) = @_;
311
312 my $rpcenv = PVE::RPCEnvironment::get();
313
314 my $vmid = extract_param($param, 'vmid');
315 my $path = extract_param($param, 'path');
316 my $dest = extract_param($param, 'destination');
317
318 my $perms = extract_param($param, 'perms');
319 my $user = extract_param($param, 'user');
320 my $group = extract_param($param, 'group');
321
322 my $code = sub {
323 my $running = PVE::LXC::check_running($vmid);
324 die "can only pull files from a running VM" if !$running;
325
326 my $realcmd = sub {
327 my $pid = PVE::LXC::find_lxc_pid($vmid);
328 # Avoid symlink issues by opening the files from inside the
329 # corresponding namespaces.
330 my $destfd = create_file($dest, $perms, $user, $group);
331
332 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
333 or die "failed to open the container's mount namespace\n";
334 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
335 or die "failed to enter the container's mount namespace\n";
336 close($mntnsfd);
337 chdir('/') or die "failed to change to container root directory\n";
338
339 open my $srcfd, '<', $path
340 or die "failed to open $path: $!\n";
341
342 copy($srcfd, $destfd);
343 };
344
345 # This avoids having to setns() back to our namespace.
346 return $rpcenv->fork_worker('pull_file', $vmid, undef, $realcmd);
347 };
348
349 return PVE::LXC::lock_config($vmid, $code);
350 }});
351
352__PACKAGE__->register_method({
353 name => 'push',
354 path => 'push',
355 method => 'PUT',
356 description => "Copy a local file to the container.",
357 parameters => {
358 additionalProperties => 0,
359 properties => {
360 vmid => get_standard_option('pve-vmid', { completion => \&PVE::LXC::complete_ctid }),
361 file => {
362 type => 'string',
363 description => "Path to a local file.",
364 },
365 destination => {
366 type => 'string',
367 description => "Destination inside the container to write to.",
368 },
369 user => {
370 type => 'string',
371 description => 'Owner user name or id. When using a name it must exist inside the container.',
372 optional => 1,
373 },
374 group => {
375 type => 'string',
376 description => 'Owner group name or id. When using a name it must exist inside the container.',
377 optional => 1,
378 },
379 perms => {
380 type => 'string',
381 description => 'File permissions to use.',
382 optional => 1,
383 },
384 },
385 },
386 returns => {
387 type => 'string',
388 description => "the task ID.",
389 },
390 code => sub {
391 my ($param) = @_;
392
393 my $rpcenv = PVE::RPCEnvironment::get();
394
395 my $vmid = extract_param($param, 'vmid');
396 my $file = extract_param($param, 'file');
397 my $dest = extract_param($param, 'destination');
398
399 my $perms = extract_param($param, 'perms');
400 my $user = extract_param($param, 'user');
401 my $group = extract_param($param, 'group');
402
403 my $code = sub {
404 my $running = PVE::LXC::check_running($vmid);
405 die "can only push files to a running VM" if !$running;
406
407 my $conf = PVE::LXC::load_config($vmid);
408 my $unprivileged = $conf->{unprivileged};
409
410 my $realcmd = sub {
411 my $pid = PVE::LXC::find_lxc_pid($vmid);
412 # We open the file then enter the container's mount - and for
413 # unprivileged containers - user namespace and then create the
414 # file. This avoids symlink attacks as a symlink cannot point
415 # outside the namespace and our own access is equivalent to the
416 # container-local's root user. Also the user-passed -user and
417 # -group parameters will use the container-local's user and
418 # group names.
419 sysopen my $srcfd, $file, O_RDONLY
420 or die "failed to open $file for reading\n";
421
422 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
423 or die "failed to open the container's mount namespace\n";
424 my $usernsfd;
425 if ($unprivileged) {
426 sysopen $usernsfd, "/proc/$pid/ns/user", O_RDONLY
427 or die "failed to open the container's user namespace\n";
428 }
429
430 PVE::Tools::setns(fileno($mntnsfd), PVE::Tools::CLONE_NEWNS)
431 or die "failed to enter the container's mount namespace\n";
432 close($mntnsfd);
433 chdir('/') or die "failed to change to container root directory\n";
434
435 if ($unprivileged) {
436 PVE::Tools::setns(fileno($usernsfd), PVE::Tools::CLONE_NEWUSER)
437 or die "failed to enter the container's user namespace\n";
438 close($usernsfd);
439 POSIX::setgid(0) or die "setgid failed: $!\n";
440 POSIX::setuid(0) or die "setuid failed: $!\n";
441 }
442
443 my $destfd = create_file($dest, $perms, $user, $group);
444 copy($srcfd, $destfd);
445 };
446
447 # This avoids having to setns() back to our namespace.
448 return $rpcenv->fork_worker('push_file', $vmid, undef, $realcmd);
449 };
450
451 return PVE::LXC::lock_config($vmid, $code);
452 }});
453
9beee926
DM
454our $cmddef = {
455 list=> [ 'PVE::API2::LXC', 'vmlist', [], { node => $nodename }, sub {
456 my $res = shift;
457 return if !scalar(@$res);
458 my $format = "%-10s %-10s %-20s\n";
459 printf($format, 'VMID', 'Status', 'Name');
460 foreach my $d (sort {$a->{vmid} <=> $b->{vmid} } @$res) {
461 printf($format, $d->{vmid}, $d->{status}, $d->{name});
462 }
463 }],
464 config => [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'],
465 { node => $nodename }, sub {
466 my $config = shift;
467 foreach my $k (sort (keys %$config)) {
468 next if $k eq 'digest';
469 my $v = $config->{$k};
470 if ($k eq 'description') {
471 $v = PVE::Tools::encode_text($v);
472 }
473 print "$k: $v\n";
474 }
475 }],
476 set => [ 'PVE::API2::LXC::Config', 'update_vm', ['vmid'], { node => $nodename }],
40626217 477
985b18ed 478 resize => [ "PVE::API2::LXC", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
9beee926
DM
479
480 create => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename }, $upid_exit ],
481 restore => [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node => $nodename, restore => 1 }, $upid_exit ],
482
483 start => [ 'PVE::API2::LXC::Status', 'vm_start', ['vmid'], { node => $nodename }, $upid_exit],
484 suspend => [ 'PVE::API2::LXC::Status', 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit],
485 resume => [ 'PVE::API2::LXC::Status', 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit],
486 shutdown => [ 'PVE::API2::LXC::Status', 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit],
487 stop => [ 'PVE::API2::LXC::Status', 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit],
488
c4a33727 489 clone => [ "PVE::API2::LXC", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
9beee926
DM
490 migrate => [ "PVE::API2::LXC", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit],
491
492 console => [ __PACKAGE__, 'console', ['vmid']],
493 enter => [ __PACKAGE__, 'enter', ['vmid']],
c72bd0ba 494 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
9beee926 495 exec => [ __PACKAGE__, 'exec', ['vmid', 'extra-args']],
f8327ed5 496 fsck => [ __PACKAGE__, 'fsck', ['vmid']],
b95bf64b
WB
497
498 push => [ __PACKAGE__, 'push', ['vmid', 'file', 'destination']],
499 pull => [ __PACKAGE__, 'pull', ['vmid', 'path', 'destination']],
9beee926
DM
500
501 destroy => [ 'PVE::API2::LXC', 'destroy_vm', ['vmid'],
502 { node => $nodename }, $upid_exit ],
503
504 snapshot => [ "PVE::API2::LXC::Snapshot", 'snapshot', ['vmid', 'snapname'],
505 { node => $nodename } , $upid_exit ],
506
507 delsnapshot => [ "PVE::API2::LXC::Snapshot", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
508
509 listsnapshot => [ "PVE::API2::LXC::Snapshot", 'list', ['vmid'], { node => $nodename },
510 sub {
511 my $res = shift;
512 foreach my $e (@$res) {
513 my $headline = $e->{description} || 'no-description';
514 $headline =~ s/\n.*//sg;
515 my $parent = $e->{parent} // 'no-parent';
516 printf("%-20s %-20s %s\n", $e->{name}, $parent, $headline);
517 }
518 }],
519
520 rollback => [ "PVE::API2::LXC::Snapshot", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
521
522 template => [ "PVE::API2::LXC", 'template', ['vmid'], { node => $nodename }],
523};
524
525
5261;
527
528__END__
529
530=head1 NAME
531
532pct - Tool to manage Linux Containers (LXC) on Proxmox VE
533
534=head1 SYNOPSIS
535
536=include synopsis
537
538=head1 DESCRIPTION
539
540pct is a tool to manages Linux Containers (LXC). You can create
541and destroy containers, and control execution
542(start/stop/suspend/resume). Besides that, you can use pct to set
543parameters in the associated config file, like network configuration or
544memory.
545
546=head1 EXAMPLES
547
548Create a container based on a Debian template
549(provided you downloaded the template via the webgui before)
550
551pct create 100 /var/lib/vz/template/cache/debian-8.0-standard_8.0-1_amd64.tar.gz
552
553Start a container
554
555pct start 100
556
557Start a login session via getty
558
559pct console 100
560
561Enter the lxc namespace and run a shell as root user
562
563pct enter 100
564
565Display the configuration
566
567pct config 100
568
569Add a network interface called eth0, bridged to the host bridge vmbr0,
570set the address and gateway, while it's running
571
572pct set 100 -net0 name=eth0,bridge=vmbr0,ip=192.168.15.147/24,gw=192.168.15.1
573
574Reduce the memory of the container to 512MB
575
576pct set -memory 512 100
577
578=head1 FILES
579
580/etc/pve/lxc/<vmid>.conf
581
582Configuration file for the container <vmid>
583
584=head1 SEE ALSO
585
586L<B<qm(1)>>, L<B<pvesh(1)>>
587
588=include pve_copyright