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.
22 # [class, name, fixed_params, API_pre-set params, output_sub ]
24 # In case of so called 'simple commands', the $cmddef can be also just an
29 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
31 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
35 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
37 # dothat => { alias => 'do that' },
41 my $cli_handler_class;
43 my $standard_mappings = {
50 return $value if $value;
51 return PVE
::PTY
::get_confirmed_password
();
55 sub get_standard_mapping
{
56 my ($name, $base) = @_;
58 my $std = $standard_mappings->{$name};
59 die "no such standard mapping '$name'\n" if !$std;
61 my $res = $base || {};
63 foreach my $opt (keys %$std) {
64 next if defined($res->{$opt});
65 $res->{$opt} = $std->{$opt};
71 my $gen_param_mapping_func = sub {
72 my ($cli_handler_class) = @_;
74 my $param_mapping = $cli_handler_class->can('param_mapping');
76 if (!$param_mapping) {
77 my $read_password = $cli_handler_class->can('read_password');
78 my $string_param_mapping = $cli_handler_class->can('string_param_file_mapping');
80 return $string_param_mapping if !$read_password;
82 $param_mapping = sub {
85 my $password_map = get_standard_mapping
('pve-password', {
86 func
=> $read_password
88 my $map = $string_param_mapping ?
$string_param_mapping->($name) : [];
89 return [@$map, $password_map];
93 return $param_mapping;
96 my $assert_initialized = sub {
98 die "$caller[0]:$caller[2] - not initialized\n"
99 if !($cmddef && $exename && $cli_handler_class);
103 my ($reason, $cmd) = @_;
104 print_usage_short
(\
*STDERR
, $reason, $cmd);
108 my $expand_command_name = sub {
109 my ($def, $cmd) = @_;
111 return $cmd if exists $def->{$cmd}; # command is already complete
113 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
114 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
116 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
121 my $get_commands = sub {
122 my $def = shift // die "no command definition passed!";
123 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
126 my $complete_command_names = sub { $get_commands->($cmddef) };
128 # traverses the command definition using the $argv array, resolving one level
130 # Returns the matching (sub) command and its definition, and argument array for
131 # this (sub) command and a hash where we marked which (sub) commands got
132 # expanded (e.g. st => status) while traversing
134 my ($argv, $is_alias) = @_;
136 my ($def, $cmd) = ($cmddef, $argv);
137 my $cmdstr = $exename;
139 if (ref($argv) eq 'ARRAY') {
140 my $expanded_last_arg;
141 my $last_arg_id = scalar(@$argv) - 1;
143 for my $i (0..$last_arg_id) {
144 $cmd = $expand_command_name->($def, $argv->[$i]);
146 # If the argument was expanded (or was already complete) and it
147 # is the final argument, tell our caller about it:
148 $expanded_last_arg = $cmd if $i == $last_arg_id;
150 # Otherwise continue with the unexpanded version of it.
155 last if !defined($def);
157 if (ref($def) eq 'ARRAY') {
158 # could expand to a real command, rest of $argv are its arguments
159 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
160 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
163 if (defined($def->{alias
})) {
164 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
165 # replace aliased (sub)command with the expanded aliased command
166 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
167 return resolve_cmd
($argv, 1);
170 # got either a special command (bashcomplete, verifyapi) or an unknown
171 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
172 my $cmd_args = [ @$argv[1..$last_arg_id] ];
173 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
175 return ($cmd, $def, undef, undef, $cmdstr);
178 sub generate_usage_str
{
179 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
181 $assert_initialized->();
182 die 'format required' if !$format;
184 $sortfunc //= sub { sort keys %{$_[0]} };
188 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
190 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
191 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
195 my ($indent, $separator, $def, $prefix) = @_;
198 if (ref($def) eq 'HASH') {
199 my $oldclass = undef;
200 foreach my $cmd (&$sortfunc($def)) {
202 if (ref($def->{$cmd}) eq 'ARRAY') {
203 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
205 $str .= $separator if $oldclass && $oldclass ne $class;
207 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
208 $fixed_param, $format, $param_cb);
211 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
213 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
216 next if $def->{$cmd}->{alias
};
218 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
220 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
227 my ($class, $name, $arg_param, $fixed_param) = @$def;
228 $abort->("unknown command '$cmd'") if !$class;
231 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb);
236 return $generate->($indent, $separator, $def, $cmdstr);
239 __PACKAGE__-
>register_method ({
243 description
=> "Get help about specified command.",
245 additionalProperties
=> 0,
247 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
248 description
=> 'Shows help for a specific command',
249 completion
=> $complete_command_names,
252 description
=> "Verbose output format.",
258 returns
=> { type
=> 'null' },
263 $assert_initialized->();
265 my $cmd = $param->{'extra-args'};
267 my $verbose = defined($cmd) && $cmd;
268 $verbose = $param->{verbose
} if defined($param->{verbose
});
272 print_usage_verbose
();
274 print_usage_short
(\
*STDOUT
);
281 $str = generate_usage_str
('full', $cmd, '');
283 $str = generate_usage_str
('short', $cmd, ' ' x
7);
290 print "USAGE: $str\n";
297 sub print_simple_asciidoc_synopsis
{
298 $assert_initialized->();
300 my $synopsis = "*${exename}* `help`\n\n";
301 $synopsis .= generate_usage_str
('asciidoc');
306 sub print_asciidoc_synopsis
{
307 $assert_initialized->();
311 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
313 $synopsis .= generate_usage_str
('asciidoc');
320 sub print_usage_verbose
{
321 $assert_initialized->();
323 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
325 my $str = generate_usage_str
('full');
330 sub print_usage_short
{
331 my ($fd, $msg, $cmd) = @_;
333 $assert_initialized->();
335 print $fd "ERROR: $msg\n" if $msg;
336 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
338 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
341 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
342 # $a and $b are both real commands order them by their class
343 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
344 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
345 # real command and subcommand mixed, put sub commands first
346 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
348 # both are either from the same class or subcommands
355 my $print_bash_completion = sub {
356 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
360 return if !(defined($cur) && defined($prev) && defined($bash_command));
361 return if !defined($ENV{COMP_LINE
});
362 return if !defined($ENV{COMP_POINT
});
364 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
365 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
367 my $args = PVE
::Tools
::split_args
($cmdline);
368 shift @$args; # no need for program name
369 my $print_result = sub {
371 print "$p\n" if $p =~ m/^\Q$cur\E/;
375 my ($cmd, $def) = ($simple_cmd, $cmddef);
377 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
379 if (defined($expanded) && $prev ne $expanded) {
384 if (ref($def) eq 'HASH') {
385 &$print_result(@{$get_commands->($def)});
391 my $pos = scalar(@$args) - 1;
392 $pos += 1 if $cmdline =~ m/\s+$/;
393 print STDERR
"pos: $pos\n" if $debug;
398 my ($class, $name, $arg_param, $uri_param) = @$def;
402 $arg_param = [ $arg_param ] if !ref($arg_param);
404 map { $skip_param->{$_} = 1; } @$arg_param;
405 map { $skip_param->{$_} = 1; } keys %$uri_param;
407 my $info = $class->map_method_by_name($name);
409 my $prop = $info->{parameters
}->{properties
};
411 my $print_parameter_completion = sub {
413 my $d = $prop->{$pname};
414 if ($d->{completion
}) {
415 my $vt = ref($d->{completion
});
417 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
418 &$print_result(@$res);
420 } elsif ($d->{type
} eq 'boolean') {
421 &$print_result('0', '1');
422 } elsif ($d->{enum
}) {
423 &$print_result(@{$d->{enum
}});
427 # positional arguments
428 if ($pos < scalar(@$arg_param)) {
429 my $pname = $arg_param->[$pos];
430 &$print_parameter_completion($pname);
434 my @option_list = ();
435 foreach my $key (keys %$prop) {
436 next if $skip_param->{$key};
437 push @option_list, "--$key";
441 &$print_result(@option_list);
445 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
447 &$print_parameter_completion($pname);
451 &$print_result(@option_list);
457 # simply verify all registered methods
458 PVE
::RESTHandler
::validate_method_schemas
();
461 my $get_exe_name = sub {
471 sub generate_bash_completions
{
474 # generate bash completion config
476 $exename = &$get_exe_name($class);
479 # $exename bash completion
481 # see http://tiswww.case.edu/php/chet/bash/FAQ
482 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
483 # this modifies global var, but I found no better way
484 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
486 complete -o default -C '$exename bashcomplete' $exename
490 sub generate_asciidoc_synopsys
{
492 $class->generate_asciidoc_synopsis();
495 sub generate_asciidoc_synopsis
{
498 $cli_handler_class = $class;
500 $exename = &$get_exe_name($class);
503 my $def = ${"${class}::cmddef"};
506 if (ref($def) eq 'ARRAY') {
507 print_simple_asciidoc_synopsis
();
509 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
511 print_asciidoc_synopsis
();
515 # overwrite this if you want to run/setup things early
516 sub setup_environment
{
519 # do nothing by default
522 my $handle_cmd = sub {
523 my ($args, $preparefunc, $param_cb) = @_;
525 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
527 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
529 $abort->("no command specified") if !$cmd;
531 # call verifyapi before setup_environment(), don't execute any real code in
533 if ($cmd eq 'verifyapi') {
534 PVE
::RESTHandler
::validate_method_schemas
();
538 $cli_handler_class->setup_environment();
540 if ($cmd eq 'bashcomplete') {
541 &$print_bash_completion(undef, @$cmd_args);
545 # checked special commands, if def is still a hash we got an incomplete sub command
546 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
548 &$preparefunc() if $preparefunc;
550 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
551 $abort->("unknown command '$cmd_str'") if !$class;
553 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb);
555 if (defined $outsub) {
556 my $result_schema = $class->map_method_by_name($name)->{returns
};
557 $outsub->($res, $result_schema);
561 my $handle_simple_cmd = sub {
562 my ($args, $preparefunc, $param_cb) = @_;
564 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
565 die "no class specified" if !$class;
567 if (scalar(@$args) >= 1) {
568 if ($args->[0] eq 'help') {
569 my $str = "USAGE: $name help\n";
570 $str .= generate_usage_str
('long');
571 print STDERR
"$str\n\n";
573 } elsif ($args->[0] eq 'verifyapi') {
574 PVE
::RESTHandler
::validate_method_schemas
();
579 $cli_handler_class->setup_environment();
581 if (scalar(@$args) >= 1) {
582 if ($args->[0] eq 'bashcomplete') {
584 &$print_bash_completion($name, @$args);
589 &$preparefunc() if $preparefunc;
591 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $param_cb);
593 if (defined $outsub) {
594 my $result_schema = $class->map_method_by_name($name)->{returns
};
595 $outsub->($res, $result_schema);
599 sub run_cli_handler
{
600 my ($class, %params) = @_;
602 $cli_handler_class = $class;
604 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
606 foreach my $key (keys %params) {
607 next if $key eq 'prepare';
608 next if $key eq 'no_init'; # not used anymore
609 next if $key eq 'no_rpcenv'; # not used anymore
610 die "unknown parameter '$key'";
613 my $preparefunc = $params{prepare
};
615 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
617 $exename = &$get_exe_name($class);
622 $cmddef = ${"${class}::cmddef"};
624 if (ref($cmddef) eq 'ARRAY') {
625 $handle_simple_cmd->(\
@ARGV, $preparefunc, $param_cb);
627 $handle_cmd->(\
@ARGV, $preparefunc, $param_cb);