1 package PVE
::CLIHandler
;
8 use PVE
::Exception
qw(raise raise_param_exc);
12 use PVE
::CLIFormatter
;
14 use base
qw(PVE::RESTHandler);
16 # $cmddef defines which (sub)commands are available in a specific CLI class.
17 # A real command is always an array consisting of its class, name, array of
18 # position fixed (required) parameters and hash of predefined parameters when
19 # mapping a CLI command t o an API call. Optionally an output method can be
20 # passed at the end, e.g., for formatting or transformation purpose, and
21 # a schema of additional properties/arguments which are added to
22 # the method schema and gets passed to the formatter.
24 # [class, name, fixed_params, API_pre-set params, output_sub ]
26 # In case of so called 'simple commands', the $cmddef can be also just an
31 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
33 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
37 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
39 # dothat => { alias => 'do that' },
43 my $cli_handler_class;
45 my $standard_mappings = {
52 return $value if $value;
53 return PVE
::PTY
::get_confirmed_password
();
57 sub get_standard_mapping
{
58 my ($name, $base) = @_;
60 my $std = $standard_mappings->{$name};
61 die "no such standard mapping '$name'\n" if !$std;
63 my $res = $base || {};
65 foreach my $opt (keys %$std) {
66 next if defined($res->{$opt});
67 $res->{$opt} = $std->{$opt};
73 my $gen_param_mapping_func = sub {
74 my ($cli_handler_class) = @_;
76 my $param_mapping = $cli_handler_class->can('param_mapping');
78 if (!$param_mapping) {
79 my $read_password = $cli_handler_class->can('read_password');
80 my $string_param_mapping = $cli_handler_class->can('string_param_file_mapping');
82 return $string_param_mapping if !$read_password;
84 $param_mapping = sub {
87 my $password_map = get_standard_mapping
('pve-password', {
88 func
=> $read_password
90 my $map = $string_param_mapping ?
$string_param_mapping->($name) : [];
91 return [@$map, $password_map];
95 return $param_mapping;
98 my $assert_initialized = sub {
100 die "$caller[0]:$caller[2] - not initialized\n"
101 if !($cmddef && $exename && $cli_handler_class);
105 my ($reason, $cmd) = @_;
106 print_usage_short
(\
*STDERR
, $reason, $cmd);
110 my $expand_command_name = sub {
111 my ($def, $cmd, $enforce_exact) = @_;
113 return $cmd if exists $def->{$cmd}; # command is already complete
115 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
116 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
118 return @expanded if !$enforce_exact;
120 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
125 my $get_commands = sub {
126 my $def = shift // die "no command definition passed!";
127 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
130 my $complete_command_names = sub { $get_commands->($cmddef) };
132 # traverses the command definition using the $argv array, resolving one level
134 # Returns the matching (sub) command and its definition, and argument array for
135 # this (sub) command and a hash where we marked which (sub) commands got
136 # expanded (e.g. st => status) while traversing
138 my ($argv, $is_alias) = @_;
140 my ($def, $cmd) = ($cmddef, $argv);
141 my $cmdstr = $exename;
143 if (ref($argv) eq 'ARRAY') {
144 my $expanded_last_arg;
145 my $last_arg_id = scalar(@$argv) - 1;
147 for my $i (0..$last_arg_id) {
148 $cmd = $expand_command_name->($def, $argv->[$i], 1);
150 # If the argument was expanded (or was already complete) and it
151 # is the final argument, tell our caller about it:
152 $expanded_last_arg = $cmd if $i == $last_arg_id;
154 # Otherwise continue with the unexpanded version of it.
158 if (!defined($def->{$cmd})) {
159 # $cmd still could be a valid prefix for bash_completion
160 # in that case keep $def as it is, else set it to undef
161 $def = undef if !$expand_command_name->($def, $cmd);
166 if (ref($def) eq 'ARRAY') {
167 # could expand to a real command, rest of $argv are its arguments
168 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
169 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
172 if (defined($def->{alias
})) {
173 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
174 # replace aliased (sub)command with the expanded aliased command
175 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
176 return resolve_cmd
($argv, 1);
179 # got either a special command (bashcomplete, verifyapi) or an unknown
180 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
181 my $cmd_args = [ @$argv[1..$last_arg_id] ];
182 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
184 return ($cmd, $def, undef, undef, $cmdstr);
187 sub generate_usage_str
{
188 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
190 $assert_initialized->();
191 die 'format required' if !$format;
193 $sortfunc //= sub { sort keys %{$_[0]} };
197 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
199 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
203 my ($indent, $separator, $def, $prefix) = @_;
206 if (ref($def) eq 'HASH') {
207 my $oldclass = undef;
208 foreach my $cmd (&$sortfunc($def)) {
210 if (ref($def->{$cmd}) eq 'ARRAY') {
211 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @{$def->{$cmd}};
213 $str .= $separator if $oldclass && $oldclass ne $class;
215 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
216 $fixed_param, $format, $param_cb, $formatter_properties);
219 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
221 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
224 next if $def->{$cmd}->{alias
};
226 my $substr = $generate->($indent, '', $def->{$cmd}, "$prefix $cmd");
228 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
235 my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @$def;
236 $abort->("unknown command '$cmd'") if !$class;
239 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb, $formatter_properties);
244 return $generate->($indent, $separator, $def, $cmdstr);
247 __PACKAGE__-
>register_method ({
251 description
=> "Get help about specified command.",
253 additionalProperties
=> 0,
255 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
256 description
=> 'Shows help for a specific command',
257 completion
=> $complete_command_names,
260 description
=> "Verbose output format.",
266 returns
=> { type
=> 'null' },
271 $assert_initialized->();
273 my $cmd = $param->{'extra-args'};
275 my $verbose = defined($cmd) && $cmd;
276 $verbose = $param->{verbose
} if defined($param->{verbose
});
280 print_usage_verbose
();
282 print_usage_short
(\
*STDOUT
);
289 $str = generate_usage_str
('full', $cmd, '');
291 $str = generate_usage_str
('short', $cmd, ' ' x
7);
298 print "USAGE: $str\n";
305 sub print_simple_asciidoc_synopsis
{
306 $assert_initialized->();
308 my $synopsis = "*${exename}* `help`\n\n";
309 $synopsis .= generate_usage_str
('asciidoc');
314 sub print_asciidoc_synopsis
{
315 $assert_initialized->();
319 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
321 $synopsis .= generate_usage_str
('asciidoc');
328 sub print_usage_verbose
{
329 $assert_initialized->();
331 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
333 my $str = generate_usage_str
('full');
338 sub print_usage_short
{
339 my ($fd, $msg, $cmd) = @_;
341 $assert_initialized->();
343 print $fd "ERROR: $msg\n" if $msg;
344 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
346 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, $cmd ?
'' : "\n", sub {
349 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
350 # $a and $b are both real commands order them by their class
351 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
352 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
353 # real command and subcommand mixed, put sub commands first
354 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
356 # both are either from the same class or subcommands
363 my $print_bash_completion = sub {
364 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
368 return if !(defined($cur) && defined($prev) && defined($bash_command));
369 return if !defined($ENV{COMP_LINE
});
370 return if !defined($ENV{COMP_POINT
});
372 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
373 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
375 my $args = PVE
::Tools
::split_args
($cmdline);
376 shift @$args; # no need for program name
377 my $print_result = sub {
379 print "$p\n" if $p =~ m/^\Q$cur\E/;
383 my ($cmd, $def) = ($simple_cmd, $cmddef);
385 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
387 if (defined($expanded) && $prev ne $expanded) {
392 if (ref($def) eq 'HASH') {
393 &$print_result(@{$get_commands->($def)});
399 my $pos = scalar(@$args) - 1;
400 $pos += 1 if $cmdline =~ m/\s+$/;
401 print STDERR
"pos: $pos\n" if $debug;
406 my ($class, $name, $arg_param, $uri_param, undef, $formatter_properties) = @$def;
410 $arg_param = [ $arg_param ] if !ref($arg_param);
412 map { $skip_param->{$_} = 1; } @$arg_param;
413 map { $skip_param->{$_} = 1; } keys %$uri_param;
415 my $info = $class->map_method_by_name($name);
417 my $prop = { %{$info->{parameters
}->{properties
}} }; # copy
418 $prop = { %$prop, %$formatter_properties } if $formatter_properties;
420 my $print_parameter_completion = sub {
422 my $d = $prop->{$pname};
423 if ($d->{completion
}) {
424 my $vt = ref($d->{completion
});
426 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
427 &$print_result(@$res);
429 } elsif ($d->{type
} eq 'boolean') {
430 &$print_result('0', '1');
431 } elsif ($d->{enum
}) {
432 &$print_result(@{$d->{enum
}});
436 # positional arguments
437 if ($pos < scalar(@$arg_param)) {
438 my $pname = $arg_param->[$pos];
439 &$print_parameter_completion($pname);
443 my @option_list = ();
444 foreach my $key (keys %$prop) {
445 next if $skip_param->{$key};
446 push @option_list, "--$key";
450 &$print_result(@option_list);
454 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
456 &$print_parameter_completion($pname);
460 &$print_result(@option_list);
466 # simply verify all registered methods
467 PVE
::RESTHandler
::validate_method_schemas
();
470 my $get_exe_name = sub {
480 sub generate_bash_completions
{
483 # generate bash completion config
485 $exename = &$get_exe_name($class);
488 # $exename bash completion
490 # see http://tiswww.case.edu/php/chet/bash/FAQ
491 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
492 # this modifies global var, but I found no better way
493 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
495 complete -o default -C '$exename bashcomplete' $exename
499 sub generate_zsh_completions
{
502 # generate zsh completion config
504 $exename = &$get_exe_name($class);
507 #compdef _$exename $exename
509 function _$exename() {
510 local cwords line point cmd curr prev
515 curr=\${words[cwords]}
516 prev=\${words[cwords-1]}
517 compadd \$(COMP_CWORD="\$cwords" COMP_LINE="\$line" COMP_POINT="\$point" \\
518 $exename bashcomplete "\$cmd" "\$curr" "\$prev")
523 sub generate_asciidoc_synopsys
{
525 $class->generate_asciidoc_synopsis();
528 sub generate_asciidoc_synopsis
{
531 $cli_handler_class = $class;
533 $exename = &$get_exe_name($class);
536 my $def = ${"${class}::cmddef"};
539 if (ref($def) eq 'ARRAY') {
540 print_simple_asciidoc_synopsis
();
542 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
544 print_asciidoc_synopsis
();
548 # overwrite this if you want to run/setup things early
549 sub setup_environment
{
552 # do nothing by default
555 my $handle_cmd = sub {
556 my ($args, $preparefunc, $param_cb) = @_;
558 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
560 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
562 $abort->("no command specified") if !$cmd;
564 # call verifyapi before setup_environment(), don't execute any real code in
566 if ($cmd eq 'verifyapi') {
567 PVE
::RESTHandler
::validate_method_schemas
();
571 $cli_handler_class->setup_environment();
573 if ($cmd eq 'bashcomplete') {
574 &$print_bash_completion(undef, @$cmd_args);
578 # checked special commands, if def is still a hash we got an incomplete sub command
579 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
581 &$preparefunc() if $preparefunc;
583 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$def || []};
584 $abort->("unknown command '$cmd_str'") if !$class;
586 my ($res, $formatter_params) = $class->cli_handler(
587 $cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb, $formatter_properties);
589 if (defined $outsub) {
590 my $result_schema = $class->map_method_by_name($name)->{returns
};
591 $outsub->($res, $result_schema, $formatter_params);
595 my $handle_simple_cmd = sub {
596 my ($args, $preparefunc, $param_cb) = @_;
598 my ($class, $name, $arg_param, $uri_param, $outsub, $formatter_properties) = @{$cmddef};
599 die "no class specified" if !$class;
601 if (scalar(@$args) >= 1) {
602 if ($args->[0] eq 'help') {
603 my $str = "USAGE: $name help\n";
604 $str .= generate_usage_str
('long');
605 print STDERR
"$str\n\n";
607 } elsif ($args->[0] eq 'verifyapi') {
608 PVE
::RESTHandler
::validate_method_schemas
();
613 $cli_handler_class->setup_environment();
615 if (scalar(@$args) >= 1) {
616 if ($args->[0] eq 'bashcomplete') {
618 &$print_bash_completion($name, @$args);
623 &$preparefunc() if $preparefunc;
625 my ($res, $formatter_params) = $class->cli_handler(
626 $name, $name, \
@ARGV, $arg_param, $uri_param, $param_cb, $formatter_properties);
628 if (defined $outsub) {
629 my $result_schema = $class->map_method_by_name($name)->{returns
};
630 $outsub->($res, $result_schema, $formatter_params);
634 sub run_cli_handler
{
635 my ($class, %params) = @_;
637 $cli_handler_class = $class;
639 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
641 foreach my $key (keys %params) {
642 next if $key eq 'prepare';
643 next if $key eq 'no_init'; # not used anymore
644 next if $key eq 'no_rpcenv'; # not used anymore
645 die "unknown parameter '$key'";
648 my $preparefunc = $params{prepare
};
650 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
652 $exename = &$get_exe_name($class);
654 my $logid = $ENV{PVE_LOG_ID
} || $exename;
658 $cmddef = ${"${class}::cmddef"};
660 if (ref($cmddef) eq 'ARRAY') {
661 $handle_simple_cmd->(\
@ARGV, $preparefunc, $param_cb);
663 $handle_cmd->(\
@ARGV, $preparefunc, $param_cb);