]>
git.proxmox.com Git - pve-container.git/blob - src/PVE/CLI/pct.pm
6296d6fc9aaa3b62d4d0b10ba5e6a1a45723d9f5
11 use PVE
::Tools
qw(extract_param);
15 use PVE
::RPCEnvironment
;
16 use PVE
::JSONSchema
qw(get_standard_option);
19 use PVE
::API2
::LXC
::Config
;
20 use PVE
::API2
::LXC
::Status
;
21 use PVE
::API2
::LXC
::Snapshot
;
25 use base
qw(PVE::CLIHandler);
27 my $nodename = PVE
::INotify
::nodename
();
31 my $status = PVE
::Tools
::upid_read_status
($upid);
32 exit($status eq 'OK' ?
0 : -1);
35 sub setup_environment
{
36 PVE
::RPCEnvironment-
>setup_default_cli_env();
39 __PACKAGE__-
>register_method ({
43 description
=> "Show CT status.",
45 additionalProperties
=> 0,
47 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
49 description
=> "Verbose output format",
55 returns
=> { type
=> 'null'},
60 my $conf = PVE
::LXC
::Config-
>load_config ($param->{vmid
});
62 my $vmstatus = PVE
::LXC
::vmstatus
($param->{vmid
});
63 my $stat = $vmstatus->{$param->{vmid
}};
64 if ($param->{verbose
}) {
65 foreach my $k (sort (keys %$stat)) {
71 my $status = $stat->{status
} || 'unknown';
72 print "status: $status\n";
83 PVE
::CLIHandler
::get_standard_mapping
('pve-password'),
88 return $mapping->{$name};
91 __PACKAGE__-
>register_method ({
95 description
=> "Unlock the VM.",
97 additionalProperties
=> 0,
99 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
102 returns
=> { type
=> 'null'},
106 my $vmid = $param->{vmid
};
108 PVE
::LXC
::Config-
>remove_lock($vmid);
113 __PACKAGE__-
>register_method ({
117 description
=> "Launch a console for the specified container.",
119 additionalProperties
=> 0,
121 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_running
}),
124 returns
=> { type
=> 'null' },
129 # test if container exists on this node
130 my $conf = PVE
::LXC
::Config-
>load_config($param->{vmid
});
132 my $cmd = PVE
::LXC
::get_console_command
($param->{vmid
}, $conf);
136 __PACKAGE__-
>register_method ({
140 description
=> "Launch a shell for the specified container.",
142 additionalProperties
=> 0,
144 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_running
}),
147 returns
=> { type
=> 'null' },
152 my $vmid = $param->{vmid
};
154 # test if container exists on this node
155 PVE
::LXC
::Config-
>load_config($vmid);
157 die "Error: container '$vmid' not running!\n" if !PVE
::LXC
::check_running
($vmid);
159 exec('lxc-attach', '-n', $vmid);
162 __PACKAGE__-
>register_method ({
166 description
=> "Launch a command inside the specified container.",
168 additionalProperties
=> 0,
170 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_running
}),
171 'extra-args' => get_standard_option
('extra-args'),
174 returns
=> { type
=> 'null' },
179 # test if container exists on this node
180 PVE
::LXC
::Config-
>load_config($param->{vmid
});
182 if (!@{$param->{'extra-args'}}) {
183 die "missing command";
185 exec('lxc-attach', '-n', $param->{vmid
}, '--', @{$param->{'extra-args'}});
188 __PACKAGE__-
>register_method ({
192 description
=> "Run a filesystem check (fsck) on a container volume.",
194 additionalProperties
=> 0,
196 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid_stopped
}),
200 description
=> "Force checking, even if the filesystem seems clean",
206 description
=> "A volume on which to run the filesystem check",
207 enum
=> [PVE
::LXC
::Config-
>mountpoint_names()],
211 returns
=> { type
=> 'null' },
215 my $vmid = $param->{'vmid'};
216 my $device = defined($param->{'device'}) ?
$param->{'device'} : 'rootfs';
218 my $command = ['fsck', '-a', '-l'];
219 push(@$command, '-f') if $param->{force
};
221 # critical path: all of this will be done while the container is locked
224 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
225 my $storage_cfg = PVE
::Storage
::config
();
227 defined($conf->{$device}) || die "cannot run command on non-existing mount point $device\n";
229 my $mount_point = $device eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{$device}) :
230 PVE
::LXC
::Config-
>parse_ct_mountpoint($conf->{$device});
232 my $volid = $mount_point->{volume
};
235 my $storage_id = PVE
::Storage
::parse_volume_id
($volid, 1);
238 my (undef, undef, undef, undef, undef, undef, $format) =
239 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
241 die "unable to run fsck for '$volid' (format == $format)\n"
244 $path = PVE
::Storage
::path
($storage_cfg, $volid);
247 if (($volid =~ m
|^/.+|) && (-b
$volid)) {
248 # pass block devices directly
251 die "path '$volid' does not point to a block device\n";
255 push(@$command, $path);
257 PVE
::LXC
::check_running
($vmid) &&
258 die "cannot run fsck on active container\n";
260 PVE
::Tools
::run_command
($command);
263 PVE
::LXC
::Config-
>lock_config($vmid, $do_fsck);
267 __PACKAGE__-
>register_method({
271 description
=> "Mount the container's filesystem on the host. " .
272 "This will hold a lock on the container and is meant for emergency maintenance only " .
273 "as it will prevent further operations on the container other than start and stop.",
275 additionalProperties
=> 0,
277 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
280 returns
=> { type
=> 'null' },
284 my $rpcenv = PVE
::RPCEnvironment
::get
();
286 my $vmid = extract_param
($param, 'vmid');
287 my $storecfg = PVE
::Storage
::config
();
288 PVE
::LXC
::Config-
>lock_config($vmid, sub {
289 my $conf = PVE
::LXC
::Config-
>set_lock($vmid, 'mounted');
290 PVE
::LXC
::mount_all
($vmid, $storecfg, $conf);
293 print "mounted CT $vmid in '/var/lib/lxc/$vmid/rootfs'\n";
297 __PACKAGE__-
>register_method({
301 description
=> "Unmount the container's filesystem.",
303 additionalProperties
=> 0,
305 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
308 returns
=> { type
=> 'null' },
312 my $rpcenv = PVE
::RPCEnvironment
::get
();
314 my $vmid = extract_param
($param, 'vmid');
315 my $storecfg = PVE
::Storage
::config
();
316 PVE
::LXC
::Config-
>lock_config($vmid, sub {
317 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
318 PVE
::LXC
::umount_all
($vmid, $storecfg, $conf, 0);
319 PVE
::LXC
::Config-
>remove_lock($vmid, 'mounted');
324 __PACKAGE__-
>register_method({
328 description
=> "Get the container's current disk usage.",
330 additionalProperties
=> 0,
332 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
335 returns
=> { type
=> 'null' },
339 my $rpcenv = PVE
::RPCEnvironment
::get
();
341 # JSONSchema's format_size is exact, this uses floating point numbers
344 return $size if $size < 1024.;
346 return sprintf('%.1fK', ${size
}) if $size < 1024.;
348 return sprintf('%.1fM', ${size
}) if $size < 1024.;
350 return sprintf('%.1fG', ${size
}) if $size < 1024.;
352 return sprintf('%.1fT', ${size
}) if $size < 1024.;
355 my $vmid = extract_param
($param, 'vmid');
356 PVE
::LXC
::Config-
>lock_config($vmid, sub {
357 my $pid = eval { PVE
::LXC
::find_lxc_pid
($vmid) };
358 my ($conf, $rootdir, $storecfg, $mounted);
360 $conf = PVE
::LXC
::Config-
>set_lock($vmid, 'mounted');
361 $rootdir = "/var/lib/lxc/$vmid/rootfs";
362 $storecfg = PVE
::Storage
::config
();
363 PVE
::LXC
::mount_all
($vmid, $storecfg, $conf);
366 $conf = PVE
::LXC
::Config-
>load_config($vmid);
367 $rootdir = "/proc/$pid/root";
370 my @list = [qw(MP Volume Size Used Avail Use% Path)];
371 my @len = map { length($_) } @{$list[0]};
374 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
375 my ($name, $mp) = @_;
376 my $path = $mp->{mp
};
378 my $df = PVE
::Tools
::df
("$rootdir/$path", 3);
379 my $total = $format->($df->{total
});
380 my $used = $format->($df->{used
});
381 my $avail = $format->($df->{avail
});
383 my $pc = sprintf('%.1f', $df->{used
}/$df->{total
});
385 my $entry = [ $name, $mp->{volume
}, $total, $used, $avail, $pc, $path ];
388 foreach my $i (0..5) {
389 $len[$i] = length($entry->[$i])
390 if $len[$i] < length($entry->[$i]);
394 my $format = "%-$len[0]s %-$len[1]s %$len[2]s %$len[3]s %$len[4]s %$len[5]s %s\n";
395 printf($format, @$_) foreach @list;
400 PVE
::LXC
::umount_all
($vmid, $storecfg, $conf, 0);
401 PVE
::LXC
::Config-
>remove_lock($vmid, 'mounted');
407 # File creation with specified ownership and permissions.
408 # User and group can be names or decimal numbers.
409 # Permissions are explicit (not affected by umask) and can be numeric with the
410 # usual 0/0x prefixes for octal/hex.
412 my ($path, $perms, $user, $group) = @_;
414 if (defined($user)) {
415 if ($user =~ /^\d+$/) {
418 $uid = getpwnam($user) or die "failed to get uid for: $user\n"
421 if (defined($group)) {
422 if ($group =~ /^\d+$/) {
425 $gid = getgrnam($group) or die "failed to get gid for: $group\n"
429 if (defined($perms)) {
431 my ($mode, $unparsed) = POSIX
::strtoul
($perms, 0);
432 die "invalid mode: '$perms'\n" if $perms eq '' || $unparsed > 0 || $!;
437 if (sysopen($fd, $path, O_WRONLY
| O_CREAT
| O_EXCL
, 0)) {
438 $perms = 0666 & ~umask if !defined($perms);
440 # If the path previously existed then we do not care about left-over
441 # file descriptors even if the permissions/ownership is changed.
442 sysopen($fd, $path, O_WRONLY
| O_CREAT
| O_TRUNC
)
443 or die "failed to create file: $path: $!\n";
448 if (defined($perms)) {
453 if (defined($uid) || defined($gid)) {
455 my ($fuid, $fgid) = (stat($fd))[4,5] if !defined($uid) || !defined($gid);
456 $uid = $fuid if !defined($uid);
457 $gid = $fgid if !defined($gid);
458 chown($uid, $gid, $fd)
459 or die "failed to change file owner: $!\n";
464 __PACKAGE__-
>register_method({
468 description
=> "Copy a file from the container to the local system.",
470 additionalProperties
=> 0,
472 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
475 description
=> "Path to a file inside the container to pull.",
479 description
=> "Destination",
483 description
=> 'Owner user name or id.',
488 description
=> 'Owner group name or id.',
493 description
=> "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
500 description
=> "the task ID.",
505 my $rpcenv = PVE
::RPCEnvironment
::get
();
507 my $vmid = extract_param
($param, 'vmid');
508 my $path = extract_param
($param, 'path');
509 my $dest = extract_param
($param, 'destination');
511 my $perms = extract_param
($param, 'perms');
512 # assume octal as default
513 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
514 my $user = extract_param
($param, 'user');
515 my $group = extract_param
($param, 'group');
518 my $running = PVE
::LXC
::check_running
($vmid);
519 die "can only pull files from a running VM" if !$running;
522 my $pid = PVE
::LXC
::find_lxc_pid
($vmid);
523 # Avoid symlink issues by opening the files from inside the
524 # corresponding namespaces.
525 my $destfd = create_file
($dest, $perms, $user, $group);
527 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
528 or die "failed to open the container's mount namespace\n";
529 PVE
::Tools
::setns
(fileno($mntnsfd), PVE
::Tools
::CLONE_NEWNS
)
530 or die "failed to enter the container's mount namespace\n";
532 chdir('/') or die "failed to change to container root directory\n";
534 open my $srcfd, '<', $path
535 or die "failed to open $path: $!\n";
537 copy
($srcfd, $destfd);
540 # This avoids having to setns() back to our namespace.
541 return $rpcenv->fork_worker('pull_file', $vmid, undef, $realcmd);
544 return PVE
::LXC
::Config-
>lock_config($vmid, $code);
547 __PACKAGE__-
>register_method({
551 description
=> "Copy a local file to the container.",
553 additionalProperties
=> 0,
555 vmid
=> get_standard_option
('pve-vmid', { completion
=> \
&PVE
::LXC
::complete_ctid
}),
558 description
=> "Path to a local file.",
562 description
=> "Destination inside the container to write to.",
566 description
=> 'Owner user name or id. When using a name it must exist inside the container.',
571 description
=> 'Owner group name or id. When using a name it must exist inside the container.',
576 description
=> "File permissions to use (octal by default, prefix with '0x' for hexadecimal).",
583 description
=> "the task ID.",
588 my $rpcenv = PVE
::RPCEnvironment
::get
();
590 my $vmid = extract_param
($param, 'vmid');
591 my $file = extract_param
($param, 'file');
592 my $dest = extract_param
($param, 'destination');
594 my $perms = extract_param
($param, 'perms');
595 # assume octal as default
596 $perms = "0$perms" if defined($perms) && $perms !~m/^0/;
597 my $user = extract_param
($param, 'user');
598 my $group = extract_param
($param, 'group');
601 my $running = PVE
::LXC
::check_running
($vmid);
602 die "can only push files to a running CT\n" if !$running;
604 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
605 my $unprivileged = $conf->{unprivileged
};
608 my $pid = PVE
::LXC
::find_lxc_pid
($vmid);
609 # We open the file then enter the container's mount - and for
610 # unprivileged containers - user namespace and then create the
611 # file. This avoids symlink attacks as a symlink cannot point
612 # outside the namespace and our own access is equivalent to the
613 # container-local's root user. Also the user-passed -user and
614 # -group parameters will use the container-local's user and
616 sysopen my $srcfd, $file, O_RDONLY
617 or die "failed to open $file for reading\n";
619 sysopen my $mntnsfd, "/proc/$pid/ns/mnt", O_RDONLY
620 or die "failed to open the container's mount namespace\n";
623 sysopen $usernsfd, "/proc/$pid/ns/user", O_RDONLY
624 or die "failed to open the container's user namespace\n";
627 PVE
::Tools
::setns
(fileno($mntnsfd), PVE
::Tools
::CLONE_NEWNS
)
628 or die "failed to enter the container's mount namespace\n";
630 chdir('/') or die "failed to change to container root directory\n";
633 PVE
::Tools
::setns
(fileno($usernsfd), PVE
::Tools
::CLONE_NEWUSER
)
634 or die "failed to enter the container's user namespace\n";
636 POSIX
::setgid
(0) or die "setgid failed: $!\n";
637 POSIX
::setuid
(0) or die "setuid failed: $!\n";
640 my $destfd = create_file
($dest, $perms, $user, $group);
641 copy
($srcfd, $destfd);
644 # This avoids having to setns() back to our namespace.
645 return $rpcenv->fork_worker('push_file', $vmid, undef, $realcmd);
648 return PVE
::LXC
::Config-
>lock_config($vmid, $code);
651 __PACKAGE__-
>register_method ({
655 description
=> "Print the list of assigned CPU sets.",
657 additionalProperties
=> 0,
660 returns
=> { type
=> 'null'},
664 my $cgv1 = PVE
::LXC
::get_cgroup_subsystems
();
665 if (!$cgv1->{cpuset
}) {
666 print "cpuset cgroup not available\n";
670 my $ctlist = PVE
::LXC
::config_list
();
676 foreach my $vmid (sort keys %$ctlist) {
677 next if ! -d
"/sys/fs/cgroup/cpuset/lxc/$vmid";
679 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup("lxc/$vmid"); };
684 my @cpuset_members = $cpuset->members();
688 my $last = $cpuset_members[-1];
690 for (my $id = 0; $id <= $last; $id++) {
691 my $empty = ' ' x
length("$id");
692 $line .= ' ' . ($cpuset->has($id) ?
$id : $empty);
694 $len = length($line) if length($line) > $len;
695 $id_len = length($vmid) if length($vmid) > $id_len;
697 $res->{$vmid} = $line;
700 my @vmlist = sort keys %$res;
702 if (scalar(@vmlist)) {
703 my $header = '-' x
($len + $id_len) . "\n";
706 foreach my $vmid (@vmlist) {
707 print sprintf("%${id_len}i%s\n", $vmid, $res->{$vmid});
712 print "no running containers\n";
719 list
=> [ 'PVE::API2::LXC', 'vmlist', [], { node
=> $nodename }, sub {
721 return if !scalar(@$res);
722 my $format = "%-10s %-10s %-12s %-20s\n";
723 printf($format, 'VMID', 'Status', 'Lock', 'Name');
724 foreach my $d (sort {$a->{vmid
} <=> $b->{vmid
} } @$res) {
725 printf($format, $d->{vmid
}, $d->{status
}, $d->{lock}, $d->{name
});
728 config
=> [ "PVE::API2::LXC::Config", 'vm_config', ['vmid'],
729 { node
=> $nodename }, sub {
731 foreach my $k (sort (keys %$config)) {
732 next if $k eq 'digest';
734 my $v = $config->{$k};
735 if ($k eq 'description') {
736 $v = PVE
::Tools
::encode_text
($v);
740 if (defined($config->{'lxc'})) {
741 my $lxc_list = $config->{'lxc'};
742 foreach my $lxc_opt (@$lxc_list) {
743 print "$lxc_opt->[0]: $lxc_opt->[1]\n"
747 set
=> [ 'PVE::API2::LXC::Config', 'update_vm', ['vmid'], { node
=> $nodename }],
749 resize
=> [ "PVE::API2::LXC", 'resize_vm', ['vmid', 'disk', 'size'], { node
=> $nodename } ],
751 create
=> [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node
=> $nodename }, $upid_exit ],
752 restore
=> [ 'PVE::API2::LXC', 'create_vm', ['vmid', 'ostemplate'], { node
=> $nodename, restore
=> 1 }, $upid_exit ],
754 start
=> [ 'PVE::API2::LXC::Status', 'vm_start', ['vmid'], { node
=> $nodename }, $upid_exit],
755 suspend
=> [ 'PVE::API2::LXC::Status', 'vm_suspend', ['vmid'], { node
=> $nodename }, $upid_exit],
756 resume
=> [ 'PVE::API2::LXC::Status', 'vm_resume', ['vmid'], { node
=> $nodename }, $upid_exit],
757 shutdown => [ 'PVE::API2::LXC::Status', 'vm_shutdown', ['vmid'], { node
=> $nodename }, $upid_exit],
758 stop
=> [ 'PVE::API2::LXC::Status', 'vm_stop', ['vmid'], { node
=> $nodename }, $upid_exit],
760 clone
=> [ "PVE::API2::LXC", 'clone_vm', ['vmid', 'newid'], { node
=> $nodename }, $upid_exit ],
761 migrate
=> [ "PVE::API2::LXC", 'migrate_vm', ['vmid', 'target'], { node
=> $nodename }, $upid_exit],
762 move_volume
=> [ "PVE::API2::LXC", 'move_volume', ['vmid', 'volume', 'storage'], { node
=> $nodename }, $upid_exit ],
764 status
=> [ __PACKAGE__
, 'status', ['vmid']],
765 console
=> [ __PACKAGE__
, 'console', ['vmid']],
766 enter
=> [ __PACKAGE__
, 'enter', ['vmid']],
767 unlock
=> [ __PACKAGE__
, 'unlock', ['vmid']],
768 exec => [ __PACKAGE__
, 'exec', ['vmid', 'extra-args']],
769 fsck
=> [ __PACKAGE__
, 'fsck', ['vmid']],
771 mount
=> [ __PACKAGE__
, 'mount', ['vmid']],
772 unmount
=> [ __PACKAGE__
, 'unmount', ['vmid']],
773 push => [ __PACKAGE__
, 'push', ['vmid', 'file', 'destination']],
774 pull
=> [ __PACKAGE__
, 'pull', ['vmid', 'path', 'destination']],
776 df
=> [ __PACKAGE__
, 'df', ['vmid']],
778 destroy
=> [ 'PVE::API2::LXC', 'destroy_vm', ['vmid'],
779 { node
=> $nodename }, $upid_exit ],
781 snapshot
=> [ "PVE::API2::LXC::Snapshot", 'snapshot', ['vmid', 'snapname'],
782 { node
=> $nodename } , $upid_exit ],
784 delsnapshot
=> [ "PVE::API2::LXC::Snapshot", 'delsnapshot', ['vmid', 'snapname'], { node
=> $nodename } , $upid_exit ],
786 listsnapshot
=> [ "PVE::API2::LXC::Snapshot", 'list', ['vmid'], { node
=> $nodename },
789 foreach my $e (@$res) {
790 my $headline = $e->{description
} || 'no-description';
791 $headline =~ s/\n.*//sg;
792 my $parent = $e->{parent
} // 'no-parent';
793 printf("%-20s %-20s %s\n", $e->{name
}, $parent, $headline);
797 rollback
=> [ "PVE::API2::LXC::Snapshot", 'rollback', ['vmid', 'snapname'], { node
=> $nodename } , $upid_exit ],
799 template
=> [ "PVE::API2::LXC", 'template', ['vmid'], { node
=> $nodename }],
801 cpusets
=> [ __PACKAGE__
, 'cpusets', []],