12 use PVE
::Tools
qw(extract_param);
16 use PVE
::RPCEnvironment
;
17 use PVE
::JSONSchema
qw(get_standard_option);
20 use PVE
::API2
::LXC
::Config
;
21 use PVE
::API2
::LXC
::Status
;
22 use PVE
::API2
::LXC
::Snapshot
;
26 use base
qw(PVE::CLIHandler);
28 my $nodename = PVE
::INotify
::nodename
();
32 my $status = PVE
::Tools
::upid_read_status
($upid);
33 exit($status eq 'OK' ?
0 : -1);
36 sub setup_environment
{
37 PVE
::RPCEnvironment-
>setup_default_cli_env();
40 __PACKAGE__-
>register_method ({
44 description
=> "Show CT status.",
46 additionalProperties
=> 0,
48 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
50 description
=> "Verbose output format",
56 returns
=> { type
=> 'null'},
61 my $conf = PVE
::LXC
::Config-
>load_config ($param->{vmid
});
63 my $vmstatus = PVE
::LXC
::vmstatus
($param->{vmid
});
64 my $stat = $vmstatus->{$param->{vmid
}};
65 if ($param->{verbose
}) {
66 foreach my $k (sort (keys %$stat)) {
72 my $status = $stat->{status
} || 'unknown';
73 print "status: $status\n";
80 my $term = new Term
::ReadLine
('pct');
81 my $attribs = $term->Attribs;
82 $attribs->{redisplay_function
} = $attribs->{shadow_redisplay
};
83 my $input = $term->readline('Enter password: ');
84 my $conf = $term->readline('Retype password: ');
85 die "Passwords do not match.\n" if ($input ne $conf);
89 sub string_param_file_mapping
{
93 'create_vm' => ['ssh-public-keys'],
96 return defined($mapping->{$name}) ?
$mapping->{$name} : [];
99 __PACKAGE__-
>register_method ({
103 description
=> "Unlock the VM.",
105 additionalProperties
=> 0,
107 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
110 returns
=> { type
=> 'null'},
114 my $vmid = $param->{vmid
};
116 PVE
::LXC
::Config-
>remove_lock($vmid);
121 __PACKAGE__-
>register_method ({
125 description
=> "Launch a console for the specified container.",
127 additionalProperties
=> 0,
129 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_running
}),
132 returns
=> { type
=> 'null' },
137 # test if container exists on this node
138 my $conf = PVE
::LXC
::Config-
>load_config($param->{vmid
});
140 my $cmd = PVE
::LXC
::get_console_command
($param->{vmid
}, $conf);
144 __PACKAGE__-
>register_method ({
148 description
=> "Launch a shell for the specified container.",
150 additionalProperties
=> 0,
152 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_running
}),
155 returns
=> { type
=> 'null' },
160 my $vmid = $param->{vmid
};
162 # test if container exists on this node
163 PVE
::LXC
::Config-
>load_config($vmid);
165 die "Error: container '$vmid' not running!\n" if !PVE
::LXC
::check_running
($vmid);
167 exec('lxc-attach', '-n', $vmid);
170 __PACKAGE__-
>register_method ({
174 description
=> "Launch a command inside the specified container.",
176 additionalProperties
=> 0,
178 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_running
}),
179 'extra-args' => get_standard_option
('extra-args'),
182 returns
=> { type
=> 'null' },
187 # test if container exists on this node
188 PVE
::LXC
::Config-
>load_config($param->{vmid
});
190 if (!@{$param->{'extra-args'}}) {
191 die "missing command";
193 exec('lxc-attach', '-n', $param->{vmid
}, '--', @{$param->{'extra-args'}});
196 __PACKAGE__-
>register_method ({
200 description
=> "Run a filesystem check (fsck) on a container volume.",
202 additionalProperties
=> 0,
204 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_stopped
}),
208 description
=> "Force checking, even if the filesystem seems clean",
214 description
=> "A volume on which to run the filesystem check",
215 enum
=> [PVE
::LXC
::Config-
>mountpoint_names()],
219 returns
=> { type
=> 'null' },
223 my $vmid = $param->{'vmid'};
224 my $device = defined($param->{'device'}) ?
$param->{'device'} : 'rootfs';
226 my $command = ['fsck', '-a', '-l'];
227 push(@$command, '-f') if $param->{force
};
229 # critical path: all of this will be done while the container is locked
232 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
233 my $storage_cfg = PVE
::Storage
::config
();
235 defined($conf->{$device}) || die "cannot run command on non-existing mount point $device\n";
237 my $mount_point = $device eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{$device}) :
238 PVE
::LXC
::Config-
>parse_ct_mountpoint($conf->{$device});
240 my $volid = $mount_point->{volume
};
243 my $storage_id = PVE
::Storage
::parse_volume_id
($volid, 1);
246 my (undef, undef, undef, undef, undef, undef, $format) =
247 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
249 die "unable to run fsck for '$volid' (format == $format)\n"
252 $path = PVE
::Storage
::path
($storage_cfg, $volid);
255 if (($volid =~ m
|^/.+|) && (-b
$volid)) {
256 # pass block devices directly
259 die "path '$volid' does not point to a block device\n";
263 push(@$command, $path);
265 PVE
::LXC
::check_running
($vmid) &&
266 die "cannot run fsck on active container\n";
268 PVE
::Tools
::run_command
($command);
271 PVE
::LXC
::Config-
>lock_config($vmid, $do_fsck);
275 __PACKAGE__-
>register_method({
279 description
=> "Mount the container's filesystem on the host. " .
280 "This will hold a lock on the container and is meant for emergency maintenance only " .
281 "as it will prevent further operations on the container other than start and stop.",
283 additionalProperties
=> 0,
285 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
288 returns
=> { type
=> 'null' },
292 my $rpcenv = PVE
::RPCEnvironment
::get
();
294 my $vmid = extract_param
($param, 'vmid');
295 my $storecfg = PVE
::Storage
::config
();
296 PVE
::LXC
::Config-
>lock_config($vmid, sub {
297 my $conf = PVE
::LXC
::Config-
>set_lock($vmid, 'mounted');
298 PVE
::LXC
::mount_all
($vmid, $storecfg, $conf);
301 print "mounted CT $vmid in '/var/lib/lxc/$vmid/rootfs'\n";
305 __PACKAGE__-
>register_method({
309 description
=> "Unmount the container's filesystem.",
311 additionalProperties
=> 0,
313 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
316 returns
=> { type
=> 'null' },
320 my $rpcenv = PVE
::RPCEnvironment
::get
();
322 my $vmid = extract_param
($param, 'vmid');
323 my $storecfg = PVE
::Storage
::config
();
324 PVE
::LXC
::Config-
>lock_config($vmid, sub {
325 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
326 PVE
::LXC
::umount_all
($vmid, $storecfg, $conf, 0);
327 PVE
::LXC
::Config-
>remove_lock($vmid, 'mounted');
332 __PACKAGE__-
>register_method({
336 description
=> "Get the container's current disk usage.",
338 additionalProperties
=> 0,
340 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
343 returns
=> { type
=> 'null' },
347 my $rpcenv = PVE
::RPCEnvironment
::get
();
349 # JSONSchema's format_size is exact, this uses floating point numbers
352 return $size if $size < 1024.;
354 return sprintf('%.1fK', ${size
}) if $size < 1024.;
356 return sprintf('%.1fM', ${size
}) if $size < 1024.;
358 return sprintf('%.1fG', ${size
}) if $size < 1024.;
360 return sprintf('%.1fT', ${size
}) if $size < 1024.;
363 my $vmid = extract_param
($param, 'vmid');
364 PVE
::LXC
::Config-
>lock_config($vmid, sub {
365 my $pid = eval { PVE
::LXC
::find_lxc_pid
($vmid) };
366 my ($conf, $rootdir, $storecfg, $mounted);
368 $conf = PVE
::LXC
::Config-
>set_lock($vmid, 'mounted');
369 $rootdir = "/var/lib/lxc/$vmid/rootfs";
370 $storecfg = PVE
::Storage
::config
();
371 PVE
::LXC
::mount_all
($vmid, $storecfg, $conf);
374 $conf = PVE
::LXC
::Config-
>load_config($vmid);
375 $rootdir = "/proc/$pid/root";
378 my @list = [qw(MP Volume Size Used Avail Use% Path)];
379 my @len = map { length($_) } @{$list[0]};
382 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
383 my ($name, $mp) = @_;
384 my $path = $mp->{mp
};
386 my $df = PVE
::Tools
::df
("$rootdir/$path", 3);
387 my $total = $format->($df->{total
});
388 my $used = $format->($df->{used
});
389 my $avail = $format->($df->{avail
});
391 my $pc = sprintf('%.1f', $df->{used
}/$df->{total
});
393 my $entry = [ $name, $mp->{volume
}, $total, $used, $avail, $pc, $path ];
396 foreach my $i (0..5) {
397 $len[$i] = length($entry->[$i])
398 if $len[$i] < length($entry->[$i]);
402 my $format = "%-$len[0]s %-$len[1]s %$len[2]s %$len[3]s %$len[4]s %$len[5]s %s\n";
403 printf($format, @$_) foreach @list;
408 PVE
::LXC
::umount_all
($vmid, $storecfg, $conf, 0);
409 PVE
::LXC
::Config-
>remove_lock($vmid, 'mounted');
415 # File creation with specified ownership and permissions.
416 # User and group can be names or decimal numbers.
417 # Permissions are explicit (not affected by umask) and can be numeric with the
418 # usual 0/0x prefixes for octal/hex.
420 my ($path, $perms, $user, $group) = @_;
422 if (defined($user)) {
423 if ($user =~ /^\d+$/) {
426 $uid = getpwnam($user) or die "failed to get uid for: $user\n"
429 if (defined($group)) {
430 if ($group =~ /^\d+$/) {
433 $gid = getgrnam($group) or die "failed to get gid for: $group\n"
437 if (defined($perms)) {
439 my ($mode, $unparsed) = POSIX
::strtoul
($perms, 0);
440 die "invalid mode: '$perms'\n" if $perms eq '' || $unparsed > 0 || $!;
445 if (sysopen($fd, $path, O_WRONLY
| O_CREAT
| O_EXCL
, 0)) {
446 $perms = 0666 & ~umask if !defined($perms);
448 # If the path previously existed then we do not care about left-over
449 # file descriptors even if the permissions/ownership is changed.
450 sysopen($fd, $path, O_WRONLY
| O_CREAT
| O_TRUNC
)
451 or die "failed to create file: $path: $!\n";
456 if (defined($perms)) {
461 if (defined($uid) || defined($gid)) {
463 my ($fuid, $fgid) = (stat($fd))[4,5] if !defined($uid) || !defined($gid);
464 $uid = $fuid if !defined($uid);
465 $gid = $fgid if !defined($gid);
466 chown($uid, $gid, $fd)
467 or die "failed to change file owner: $!\n";
472 __PACKAGE__-
>register_method({
476 description
=> "Copy a file from the container to the local system.",
478 additionalProperties
=> 0,
480 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
483 description
=> "Path to a file inside the container to pull.",
487 description
=> "Destination",
491 description
=> 'Owner user name or id.',
496 description
=> 'Owner group name or id.',
501 description
=> "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
508 description
=> "the task ID.",
513 my $rpcenv = PVE
::RPCEnvironment
::get
();
515 my $vmid = extract_param
($param, 'vmid');
516 my $path = extract_param
($param, 'path');
517 my $dest = extract_param
($param, 'destination');
519 my $perms = extract_param
($param, 'perms');
520 # assume octal as default
521 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
522 my $user = extract_param
($param, 'user');
523 my $group = extract_param
($param, 'group');
526 my $running = PVE
::LXC
::check_running
($vmid);
527 die "can only pull files from a running VM" if !$running;
530 my $pid = PVE
::LXC
::find_lxc_pid
($vmid);
531 # Avoid symlink issues by opening the files from inside the
532 # corresponding namespaces.
533 my $destfd = create_file
($dest, $perms, $user, $group);
535 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
536 or die "failed to open the container's mount namespace\n";
537 PVE
::Tools
::setns
(fileno($mntnsfd), PVE
::Tools
::CLONE_NEWNS
)
538 or die "failed to enter the container's mount namespace\n";
540 chdir('/') or die "failed to change to container root directory\n";
542 open my $srcfd, '<', $path
543 or die "failed to open $path: $!\n";
545 copy
($srcfd, $destfd);
548 # This avoids having to setns() back to our namespace.
549 return $rpcenv->fork_worker('pull_file', $vmid, undef, $realcmd);
552 return PVE
::LXC
::Config-
>lock_config($vmid, $code);
555 __PACKAGE__-
>register_method({
559 description
=> "Copy a local file to the container.",
561 additionalProperties
=> 0,
563 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
566 description
=> "Path to a local file.",
570 description
=> "Destination inside the container to write to.",
574 description
=> 'Owner user name or id. When using a name it must exist inside the container.',
579 description
=> 'Owner group name or id. When using a name it must exist inside the container.',
584 description
=> "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
591 description
=> "the task ID.",
596 my $rpcenv = PVE
::RPCEnvironment
::get
();
598 my $vmid = extract_param
($param, 'vmid');
599 my $file = extract_param
($param, 'file');
600 my $dest = extract_param
($param, 'destination');
602 my $perms = extract_param
($param, 'perms');
603 # assume octal as default
604 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
605 my $user = extract_param
($param, 'user');
606 my $group = extract_param
($param, 'group');
609 my $running = PVE
::LXC
::check_running
($vmid);
610 die "can only push files to a running CT\n" if !$running;
612 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
613 my $unprivileged = $conf->{unprivileged
};
616 my $pid = PVE
::LXC
::find_lxc_pid
($vmid);
617 # We open the file then enter the container's mount - and for
618 # unprivileged containers - user namespace and then create the
619 # file. This avoids symlink attacks as a symlink cannot point
620 # outside the namespace and our own access is equivalent to the
621 # container-local's root user. Also the user-passed -user and
622 # -group parameters will use the container-local's user and
624 sysopen my $srcfd, $file, O_RDONLY
625 or die "failed to open $file for reading\n";
627 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
628 or die "failed to open the container's mount namespace\n";
631 sysopen $usernsfd, "/proc/$pid/ns/user", O_RDONLY
632 or die "failed to open the container's user namespace\n";
635 PVE
::Tools
::setns
(fileno($mntnsfd), PVE
::Tools
::CLONE_NEWNS
)
636 or die "failed to enter the container's mount namespace\n";
638 chdir('/') or die "failed to change to container root directory\n";
641 PVE
::Tools
::setns
(fileno($usernsfd), PVE
::Tools
::CLONE_NEWUSER
)
642 or die "failed to enter the container's user namespace\n";
644 POSIX
::setgid
(0) or die "setgid failed: $!\n";
645 POSIX
::setuid
(0) or die "setuid failed: $!\n";
648 my $destfd = create_file
($dest, $perms, $user, $group);
649 copy
($srcfd, $destfd);
652 # This avoids having to setns() back to our namespace.
653 return $rpcenv->fork_worker('push_file', $vmid, undef, $realcmd);
656 return PVE
::LXC
::Config-
>lock_config($vmid, $code);
659 __PACKAGE__-
>register_method ({
663 description
=> "Print the list of assigned CPU sets.",
665 additionalProperties
=> 0,
668 returns
=> { type
=> 'null'},
672 my $ctlist = PVE
::LXC
::config_list
();
678 foreach my $vmid (sort keys %$ctlist) {
679 next if ! -d
"/sys/fs/cgroup/cpuset/lxc/$vmid";
681 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup("lxc/$vmid"); };
686 my @cpuset_members = $cpuset->members();
690 my $last = $cpuset_members[-1];
692 for (my $id = 0; $id <= $last; $id++) {
693 my $empty = ' ' x
length("$id");
694 $line .= ' ' . ($cpuset->has($id) ?
$id : $empty);
696 $len = length($line) if length($line) > $len;
697 $id_len = length($vmid) if length($vmid) > $id_len;
699 $res->{$vmid} = $line;
702 my @vmlist = sort keys %$res;
704 if (scalar(@vmlist)) {
705 my $header = '-' x
($len + $id_len) . "\n";
708 foreach my $vmid (@vmlist) {
709 print sprintf("%${id_len}i%s\n", $vmid, $res->{$vmid});
714 print "no running containers\n";
721 list
=> [ 'PVE::API2::LXC', 'vmlist', [], { node
=> $nodename }, sub {
723 return if !scalar(@$res);
724 my $format = "%-10s %-10s %-12s %-20s\n";
725 printf($format, 'VMID', 'Status', 'Lock', 'Name');
726 foreach my $d (sort {$a->{vmid
} <=> $b->{vmid
} } @$res) {
727 printf($format, $d->{vmid
}, $d->{status
}, $d->{lock}, $d->{name
});
730 config
=> [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'],
731 { node
=> $nodename }, sub {
733 foreach my $k (sort (keys %$config)) {
734 next if $k eq 'digest';
736 my $v = $config->{$k};
737 if ($k eq 'description') {
738 $v = PVE
::Tools
::encode_text
($v);
742 if (defined($config->{'lxc'})) {
743 my $lxc_list = $config->{'lxc'};
744 foreach my $lxc_opt (@$lxc_list) {
745 print "$lxc_opt->[0]: $lxc_opt->[1]\n"
749 set
=> [ 'PVE::API2::LXC::Config', 'update_vm', ['vmid'], { node
=> $nodename }],
751 resize
=> [ "PVE::API2::LXC", 'resize_vm', ['vmid', 'disk', 'size'], { node
=> $nodename } ],
753 create
=> [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node
=> $nodename }, $upid_exit ],
754 restore
=> [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node
=> $nodename, restore
=> 1 }, $upid_exit ],
756 start
=> [ 'PVE::API2::LXC::Status', 'vm_start', ['vmid'], { node
=> $nodename }, $upid_exit],
757 suspend
=> [ 'PVE::API2::LXC::Status', 'vm_suspend', ['vmid'], { node
=> $nodename }, $upid_exit],
758 resume
=> [ 'PVE::API2::LXC::Status', 'vm_resume', ['vmid'], { node
=> $nodename }, $upid_exit],
759 shutdown => [ 'PVE::API2::LXC::Status', 'vm_shutdown', ['vmid'], { node
=> $nodename }, $upid_exit],
760 stop
=> [ 'PVE::API2::LXC::Status', 'vm_stop', ['vmid'], { node
=> $nodename }, $upid_exit],
762 clone
=> [ "PVE::API2::LXC", 'clone_vm', ['vmid', 'newid'], { node
=> $nodename }, $upid_exit ],
763 migrate
=> [ "PVE::API2::LXC", 'migrate_vm', ['vmid', 'target'], { node
=> $nodename }, $upid_exit],
765 status
=> [ __PACKAGE__
, 'status', ['vmid']],
766 console
=> [ __PACKAGE__
, 'console', ['vmid']],
767 enter
=> [ __PACKAGE__
, 'enter', ['vmid']],
768 unlock
=> [ __PACKAGE__
, 'unlock', ['vmid']],
769 exec => [ __PACKAGE__
, 'exec', ['vmid', 'extra-args']],
770 fsck
=> [ __PACKAGE__
, 'fsck', ['vmid']],
772 mount
=> [ __PACKAGE__
, 'mount', ['vmid']],
773 unmount
=> [ __PACKAGE__
, 'unmount', ['vmid']],
774 push => [ __PACKAGE__
, 'push', ['vmid', 'file', 'destination']],
775 pull
=> [ __PACKAGE__
, 'pull', ['vmid', 'path', 'destination']],
777 df
=> [ __PACKAGE__
, 'df', ['vmid']],
779 destroy
=> [ 'PVE::API2::LXC', 'destroy_vm', ['vmid'],
780 { node
=> $nodename }, $upid_exit ],
782 snapshot
=> [ "PVE::API2::LXC::Snapshot", 'snapshot', ['vmid', 'snapname'],
783 { node
=> $nodename } , $upid_exit ],
785 delsnapshot
=> [ "PVE::API2::LXC::Snapshot", 'delsnapshot', ['vmid', 'snapname'], { node
=> $nodename } , $upid_exit ],
787 listsnapshot
=> [ "PVE::API2::LXC::Snapshot", 'list', ['vmid'], { node
=> $nodename },
790 foreach my $e (@$res) {
791 my $headline = $e->{description
} || 'no-description';
792 $headline =~ s/\n.*//sg;
793 my $parent = $e->{parent
} // 'no-parent';
794 printf("%-20s %-20s %s\n", $e->{name
}, $parent, $headline);
798 rollback
=> [ "PVE::API2::LXC::Snapshot", 'rollback', ['vmid', 'snapname'], { node
=> $nodename } , $upid_exit ],
800 template
=> [ "PVE::API2::LXC", 'template', ['vmid'], { node
=> $nodename }],
802 cpusets
=> [ __PACKAGE__
, 'cpusets', []],