1 package PVE
::CLIHandler
;
7 use Scalar
::Util
qw(weaken);
10 use PVE
::Exception
qw(raise raise_param_exc);
15 use PVE
::CLIFormatter
;
17 use base
qw(PVE::RESTHandler);
19 # $cmddef defines which (sub)commands are available in a specific CLI class.
20 # A real command is always an array consisting of its class, name, array of
21 # position fixed (required) parameters and hash of predefined parameters when
22 # mapping a CLI command t o an API call. Optionally an output method can be
23 # passed at the end, e.g., for formatting or transformation purpose, and
24 # a schema of additional properties/arguments which are added to
25 # the method schema and gets passed to the formatter.
27 # [class, name, fixed_params, API_pre-set params, output_sub ]
29 # In case of so called 'simple commands', the $cmddef can be also just an
34 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
36 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
40 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
42 # dothat => { alias => 'do that' },
46 my $cli_handler_class;
48 my $standard_mappings = {
55 return $value if $value;
56 return PVE
::PTY
::get_confirmed_password
();
60 sub get_standard_mapping
{
61 my ($name, $base) = @_;
63 my $std = $standard_mappings->{$name};
64 die "no such standard mapping '$name'\n" if !$std;
66 my $res = $base || {};
68 foreach my $opt (keys %$std) {
69 next if defined($res->{$opt});
70 $res->{$opt} = $std->{$opt};
76 my $gen_param_mapping_func = sub {
77 my ($cli_handler_class) = @_;
79 my $param_mapping = $cli_handler_class->can('param_mapping');
81 if (!$param_mapping) {
82 my $read_password = $cli_handler_class->can('read_password');
83 my $string_param_mapping = $cli_handler_class->can('string_param_file_mapping');
85 return $string_param_mapping if !$read_password;
87 $param_mapping = sub {
90 my $password_map = get_standard_mapping
('pve-password', {
91 func
=> $read_password
93 my $map = $string_param_mapping ?
$string_param_mapping->($name) : [];
94 return [@$map, $password_map];
98 return $param_mapping;
101 my $assert_initialized = sub {
103 die "$caller[0]:$caller[2] - not initialized\n"
104 if !($cmddef && $exename && $cli_handler_class);
108 my ($reason, $cmd) = @_;
109 print_usage_short
(\
*STDERR
, $reason, $cmd);
113 my $expand_command_name = sub {
114 my ($def, $cmd, $enforce_exact) = @_;
116 return $cmd if exists $def->{$cmd}; # command is already complete
118 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
119 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
121 return @expanded if !$enforce_exact;
123 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
128 my $get_commands = sub {
129 my $def = shift // die "no command definition passed!";
130 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
133 my $complete_command_names = sub { $get_commands->($cmddef) };
135 # traverses the command definition using the $argv array, resolving one level
137 # Returns the matching (sub) command and its definition, and argument array for
138 # this (sub) command and a hash where we marked which (sub) commands got
139 # expanded (e.g. st => status) while traversing
141 my ($argv, $is_alias) = @_;
143 my ($def, $cmd) = ($cmddef, $argv);
144 my $cmdstr = $exename;
146 if (ref($argv) eq 'ARRAY') {
147 my $expanded_last_arg;
148 my $last_arg_id = scalar(@$argv) - 1;
150 for my $i (0..$last_arg_id) {
151 $cmd = $expand_command_name->($def, $argv->[$i], 1);
153 # If the argument was expanded (or was already complete) and it
154 # is the final argument, tell our caller about it:
155 $expanded_last_arg = $cmd if $i == $last_arg_id;
157 # Otherwise continue with the unexpanded version of it.
161 if (!defined($def->{$cmd})) {
162 # $cmd still could be a valid prefix for bash_completion
163 # in that case keep $def as it is, else set it to undef
164 $def = undef if !$expand_command_name->($def, $cmd);
169 if (ref($def) eq 'ARRAY') {
170 # could expand to a real command, rest of $argv are its arguments
171 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
172 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
175 if (defined($def->{alias
})) {
176 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
177 # replace aliased (sub)command with the expanded aliased command
178 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
179 return resolve_cmd
($argv, 1);
182 # got either a special command (bashcomplete, verifyapi) or an unknown
183 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
184 my $cmd_args = [ @$argv[1..$last_arg_id] ];
185 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
187 return ($cmd, $def, undef, undef, $cmdstr);
190 sub generate_usage_str
{
191 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
193 $assert_initialized->();
194 die 'format required' if !$format;
196 $sortfunc //= sub { sort keys %{$_[0]} };
200 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
202 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
205 $generate_weak = sub {
206 my ($indent, $separator, $def, $prefix) = @_;
209 if (ref($def) eq 'HASH') {
210 my $oldclass = undef;
211 foreach my $cmd ($sortfunc->($def)) {
213 if (ref($def->{$cmd}) eq 'ARRAY') {
214 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @{$def->{$cmd}};
216 $str .= $separator if $oldclass && $oldclass ne $class;
218 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
219 $fixed_param, $format, $param_cb, $formatter_properties);
222 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
224 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
227 next if $def->{$cmd}->{alias
};
229 my $substr = $generate_weak->($indent, '', $def->{$cmd}, "$prefix $cmd");
231 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
238 $abort->("unknown command '$cmd->[0]'") if !$def;
239 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @$def;
242 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
246 my $generate = $generate_weak;
247 weaken
($generate_weak);
249 return $generate->($indent, $separator, $def, $cmdstr);
252 __PACKAGE__-
>register_method ({
256 description
=> "Get help about specified command.",
258 additionalProperties
=> 0,
260 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
261 description
=> 'Shows help for a specific command',
262 completion
=> $complete_command_names,
265 description
=> "Verbose output format.",
271 returns
=> { type
=> 'null' },
276 $assert_initialized->();
278 my $cmd = $param->{'extra-args'};
280 my $verbose = defined($cmd) && $cmd;
281 $verbose = $param->{verbose
} if defined($param->{verbose
});
285 print_usage_verbose
();
287 print_usage_short
(\
*STDOUT
);
294 $str = generate_usage_str
('full', $cmd, '');
296 $str = generate_usage_str
('short', $cmd, ' ' x
7);
303 print "USAGE: $str\n";
310 sub print_simple_asciidoc_synopsis
{
311 $assert_initialized->();
313 my $synopsis = "*${exename}* `help`\n\n";
314 $synopsis .= generate_usage_str
('asciidoc');
319 sub print_asciidoc_synopsis
{
320 $assert_initialized->();
324 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
326 $synopsis .= generate_usage_str
('asciidoc');
333 sub print_usage_verbose
{
334 $assert_initialized->();
336 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
338 my $str = generate_usage_str
('full');
343 sub print_usage_short
{
344 my ($fd, $msg, $cmd) = @_;
346 $assert_initialized->();
348 print $fd "ERROR: $msg\n" if $msg;
349 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
351 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, $cmd ?
'' : "\n", sub {
354 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
355 # $a and $b are both real commands order them by their class
356 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
357 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
358 # real command and subcommand mixed, put sub commands first
359 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
361 # both are either from the same class or subcommands
368 my $print_bash_completion = sub {
369 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
373 return if !(defined($cur) && defined($prev) && defined($bash_command));
374 return if !defined($ENV{COMP_LINE
});
375 return if !defined($ENV{COMP_POINT
});
377 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
378 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
380 my $args = PVE
::Tools
::split_args
($cmdline);
381 shift @$args; # no need for program name
382 my $print_result = sub {
384 print "$p\n" if $p =~ m/^\Q$cur\E/;
388 my ($cmd, $def) = ($simple_cmd, $cmddef);
390 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
392 if (defined($expanded) && $prev ne $expanded) {
397 if (ref($def) eq 'HASH') {
398 &$print_result(@{$get_commands->($def)});
404 my $pos = scalar(@$args) - 1;
405 $pos += 1 if $cmdline =~ m/\s+$/;
406 print STDERR
"pos: $pos\n" if $debug;
411 my ($class, $name, $arg_param, $uri_param, undef, $formatter_properties) = @$def;
415 $arg_param = [ $arg_param ] if !ref($arg_param);
417 map { $skip_param->{$_} = 1; } @$arg_param;
418 map { $skip_param->{$_} = 1; } keys %$uri_param;
420 my $info = $class->map_method_by_name($name);
422 my $prop = { %{$info->{parameters
}->{properties
}} }; # copy
423 $prop = { %$prop, %$formatter_properties } if $formatter_properties;
425 my $print_parameter_completion = sub {
427 my $d = $prop->{$pname};
428 if ($d->{completion
}) {
429 my $vt = ref($d->{completion
});
431 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
432 &$print_result(@$res);
434 } elsif ($d->{type
} eq 'boolean') {
435 &$print_result('0', '1');
436 } elsif ($d->{enum
}) {
437 &$print_result(@{$d->{enum
}});
441 # positional arguments
442 if ($pos < scalar(@$arg_param)) {
443 my $pname = $arg_param->[$pos];
444 &$print_parameter_completion($pname);
448 my @option_list = ();
449 foreach my $key (keys %$prop) {
450 next if $skip_param->{$key};
451 push @option_list, "--$key";
455 &$print_result(@option_list);
459 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
461 &$print_parameter_completion($pname);
465 &$print_result(@option_list);
471 # simply verify all registered methods
472 PVE
::RESTHandler
::validate_method_schemas
();
475 my $get_exe_name = sub {
485 sub generate_bash_completions
{
488 # generate bash completion config
490 $exename = &$get_exe_name($class);
493 # $exename bash completion
495 # see http://tiswww.case.edu/php/chet/bash/FAQ
496 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
497 # this modifies global var, but I found no better way
498 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
500 complete -o default -C '$exename bashcomplete' $exename
504 sub generate_zsh_completions
{
507 # generate zsh completion config
509 $exename = &$get_exe_name($class);
512 #compdef _$exename $exename
514 function _$exename() {
515 local cwords line point cmd curr prev
520 curr=\${words[cwords]}
521 prev=\${words[cwords-1]}
522 compadd -- \$(COMP_CWORD="\$cwords" COMP_LINE="\$line" COMP_POINT="\$point" \\
523 $exename bashcomplete "\$cmd" "\$curr" "\$prev")
528 sub generate_asciidoc_synopsys
{
530 $class->generate_asciidoc_synopsis();
533 sub generate_asciidoc_synopsis
{
536 $cli_handler_class = $class;
538 $exename = &$get_exe_name($class);
541 my $def = ${"${class}::cmddef"};
544 if (ref($def) eq 'ARRAY') {
545 print_simple_asciidoc_synopsis
();
547 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
549 print_asciidoc_synopsis
();
553 # overwrite this if you want to run/setup things early
554 sub setup_environment
{
557 # do nothing by default
560 my $handle_cmd = sub {
561 my ($args, $preparefunc, $param_cb) = @_;
563 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
565 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
567 $abort->("no command specified") if !$cmd;
569 # call verifyapi before setup_environment(), don't execute any real code in
571 if ($cmd eq 'verifyapi') {
572 PVE
::RESTHandler
::validate_method_schemas
();
576 $cli_handler_class->setup_environment();
578 if ($cmd eq 'bashcomplete') {
579 &$print_bash_completion(undef, @$cmd_args);
583 # checked special commands, if def is still a hash we got an incomplete sub command
584 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
586 &$preparefunc() if $preparefunc;
588 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$def || []};
589 $abort->("unknown command '$cmd_str'") if !$class;
591 my ($res, $formatter_params) = $class->cli_handler(
592 $cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb, $formatter_properties);
594 if (defined $outsub) {
595 my $result_schema = $class->map_method_by_name($name)->{returns
};
596 $outsub->($res, $result_schema, $formatter_params);
600 my $handle_simple_cmd = sub {
601 my ($args, $preparefunc, $param_cb) = @_;
603 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$cmddef};
604 die "no class specified" if !$class;
606 if (scalar(@$args) >= 1) {
607 if ($args->[0] eq 'help') {
608 my $str = "USAGE: $name help\n";
609 $str .= generate_usage_str
('long');
610 print STDERR
"$str\n\n";
612 } elsif ($args->[0] eq 'verifyapi') {
613 PVE
::RESTHandler
::validate_method_schemas
();
618 $cli_handler_class->setup_environment();
620 if (scalar(@$args) >= 1) {
621 if ($args->[0] eq 'bashcomplete') {
623 &$print_bash_completion($name, @$args);
628 &$preparefunc() if $preparefunc;
630 my ($res, $formatter_params) = $class->cli_handler(
631 $name, $name, \
@ARGV, $arg_param, $uri_param, $param_cb, $formatter_properties);
633 if (defined $outsub) {
634 my $result_schema = $class->map_method_by_name($name)->{returns
};
635 $outsub->($res, $result_schema, $formatter_params);
639 sub run_cli_handler
{
640 my ($class, %params) = @_;
642 $cli_handler_class = $class;
644 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
646 foreach my $key (keys %params) {
647 next if $key eq 'prepare';
648 next if $key eq 'no_init'; # not used anymore
649 next if $key eq 'no_rpcenv'; # not used anymore
650 die "unknown parameter '$key'";
653 my $preparefunc = $params{prepare
};
655 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
657 $exename = &$get_exe_name($class);
659 my $logid = $ENV{PVE_LOG_ID
} || $exename;
663 $cmddef = ${"${class}::cmddef"};
665 if (ref($cmddef) eq 'ARRAY') {
666 $handle_simple_cmd->(\
@ARGV, $preparefunc, $param_cb);
668 $handle_cmd->(\
@ARGV, $preparefunc, $param_cb);