1 package PVE
::CLIHandler
;
8 use PVE
::Exception
qw(raise raise_param_exc);
13 use base
qw(PVE::RESTHandler);
15 # $cmddef defines which (sub)commands are available in a specific CLI class.
16 # A real command is always an array consisting of its class, name, array of
17 # position fixed (required) parameters and hash of predefined parameters when
18 # mapping a CLI command t o an API call. Optionally an output method can be
19 # passed at the end, e.g., for formatting or transformation purpose.
21 # [class, name, fixed_params, API_pre-set params, output_sub ]
23 # In case of so called 'simple commands', the $cmddef can be also just an
28 # command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
30 # this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
34 # that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
36 # dothat => { alias => 'do that' },
40 my $cli_handler_class;
42 my $standard_mappings = {
49 return $value if $value;
50 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_mapping_func = $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,
209 $param_mapping_func);
212 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
214 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
217 next if $def->{$cmd}->{alias
};
219 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
221 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
228 my ($class, $name, $arg_param, $fixed_param) = @$def;
229 $abort->("unknown command '$cmd'") if !$class;
232 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
233 $param_mapping_func);
238 return $generate->($indent, $separator, $def, $cmdstr);
241 __PACKAGE__-
>register_method ({
245 description
=> "Get help about specified command.",
247 additionalProperties
=> 0,
249 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
250 description
=> 'Shows help for a specific command',
251 completion
=> $complete_command_names,
254 description
=> "Verbose output format.",
260 returns
=> { type
=> 'null' },
265 $assert_initialized->();
267 my $cmd = $param->{'extra-args'};
269 my $verbose = defined($cmd) && $cmd;
270 $verbose = $param->{verbose
} if defined($param->{verbose
});
274 print_usage_verbose
();
276 print_usage_short
(\
*STDOUT
);
283 $str = generate_usage_str
('full', $cmd, '');
285 $str = generate_usage_str
('short', $cmd, ' ' x
7);
292 print "USAGE: $str\n";
299 sub print_simple_asciidoc_synopsis
{
300 $assert_initialized->();
302 my $synopsis = "*${exename}* `help`\n\n";
303 $synopsis .= generate_usage_str
('asciidoc');
308 sub print_asciidoc_synopsis
{
309 $assert_initialized->();
313 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
315 $synopsis .= generate_usage_str
('asciidoc');
322 sub print_usage_verbose
{
323 $assert_initialized->();
325 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
327 my $str = generate_usage_str
('full');
332 sub print_usage_short
{
333 my ($fd, $msg, $cmd) = @_;
335 $assert_initialized->();
337 print $fd "ERROR: $msg\n" if $msg;
338 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
340 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
343 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
344 # $a and $b are both real commands order them by their class
345 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
346 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
347 # real command and subcommand mixed, put sub commands first
348 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
350 # both are either from the same class or subcommands
357 my $print_bash_completion = sub {
358 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
362 return if !(defined($cur) && defined($prev) && defined($bash_command));
363 return if !defined($ENV{COMP_LINE
});
364 return if !defined($ENV{COMP_POINT
});
366 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
367 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
369 my $args = PVE
::Tools
::split_args
($cmdline);
370 shift @$args; # no need for program name
371 my $print_result = sub {
373 print "$p\n" if $p =~ m/^\Q$cur\E/;
377 my ($cmd, $def) = ($simple_cmd, $cmddef);
379 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
381 if (defined($expanded) && $prev ne $expanded) {
386 if (ref($def) eq 'HASH') {
387 &$print_result(@{$get_commands->($def)});
393 my $pos = scalar(@$args) - 1;
394 $pos += 1 if $cmdline =~ m/\s+$/;
395 print STDERR
"pos: $pos\n" if $debug;
400 my ($class, $name, $arg_param, $uri_param) = @$def;
404 $arg_param = [ $arg_param ] if !ref($arg_param);
406 map { $skip_param->{$_} = 1; } @$arg_param;
407 map { $skip_param->{$_} = 1; } keys %$uri_param;
409 my $info = $class->map_method_by_name($name);
411 my $prop = $info->{parameters
}->{properties
};
413 my $print_parameter_completion = sub {
415 my $d = $prop->{$pname};
416 if ($d->{completion
}) {
417 my $vt = ref($d->{completion
});
419 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
420 &$print_result(@$res);
422 } elsif ($d->{type
} eq 'boolean') {
423 &$print_result('0', '1');
424 } elsif ($d->{enum
}) {
425 &$print_result(@{$d->{enum
}});
429 # positional arguments
430 if ($pos < scalar(@$arg_param)) {
431 my $pname = $arg_param->[$pos];
432 &$print_parameter_completion($pname);
436 my @option_list = ();
437 foreach my $key (keys %$prop) {
438 next if $skip_param->{$key};
439 push @option_list, "--$key";
443 &$print_result(@option_list);
447 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
449 &$print_parameter_completion($pname);
453 &$print_result(@option_list);
459 return '' if !defined($data);
461 if (my $class = ref($data)) {
462 return to_json
($data, { utf8
=> 1, canonical
=> 1 });
468 # prints a formatted table with a title row.
469 # $data - the data to print (array of objects)
470 # $returnprops -json schema property description
471 # $props_to_print - ordered list of properties to print
472 # $sort_key can be used to sort after a column, if it isn't set we sort
473 # after the leftmost column (with no undef value in $data) this can be
474 # turned off by passing 0 as $sort_key
475 sub print_text_table
{
476 my ($data, $returnprops, $props_to_print, $sort_key) = @_;
479 if (defined($sort_key) && $sort_key eq 0) {
485 my $formatstring = '';
487 my $column_count = scalar(@$props_to_print);
489 for (my $i = 0; $i < $column_count; $i++) {
490 my $prop = $props_to_print->[$i];
491 my $propinfo = $returnprops->{$prop} // {};
493 my $title = $propinfo->{title
} // $prop;
494 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
496 # calculate maximal print width and cutoff
497 my $titlelen = length($title);
499 my $longest = $titlelen;
500 my $sortable = $autosort;
501 foreach my $entry (@$data) {
502 my $len = length(data_to_text
($entry->{$prop})) // 0;
503 $longest = $len if $len > $longest;
504 $sortable = 0 if !defined($entry->{$prop});
506 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
507 $sort_key //= $prop if $sortable;
509 $colopts->{$prop} = {
511 default => $propinfo->{default} // '',
515 # skip alignment and cutoff on last column
516 $formatstring .= ($i == ($column_count - 1)) ?
"%s\n" : "%-${cutoff}s ";
519 printf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
521 if (defined($sort_key)) {
522 my $type = $returnprops->{$sort_key}->{type
} // 'string';
523 if ($type eq 'integer' || $type eq 'number') {
524 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
526 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
530 foreach my $entry (@$data) {
531 printf $formatstring, map {
532 substr(data_to_text
($entry->{$_}) // $colopts->{$_}->{default},
533 0, $colopts->{$_}->{cutoff
});
538 # prints the result of an API GET call returning an array as a table.
539 # takes formatting information from the results property of the call
540 # if $props_to_print is provided, prints only those columns. otherwise
541 # takes all fields of the results property, with a fallback
542 # to all fields occuring in items of $data.
544 my ($data, $result_schema, $props_to_print, $sort_key) = @_;
546 die "can only print object lists\n"
547 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
549 my $returnprops = $result_schema->{items
}->{properties
};
551 if (!defined($props_to_print)) {
552 $props_to_print = [ sort keys %$returnprops ];
553 if (!scalar(@$props_to_print)) {
555 foreach my $obj (@{$data}) {
556 foreach my $key (keys %{$obj}) {
557 $all_props->{ $key } = 1;
560 $props_to_print = [ sort keys %{$all_props} ];
562 die "unable to detect list properties\n" if !scalar(@$props_to_print);
565 print_text_table
($data, $returnprops, $props_to_print, $sort_key);
568 sub print_api_result
{
569 my ($format, $data, $result_schema, $props_to_print, $sort_key) = @_;
571 return if $result_schema->{type
} eq 'null';
573 if ($format eq 'json') {
574 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
575 } elsif ($format eq 'text') {
576 my $type = $result_schema->{type
};
577 if ($type eq 'object') {
578 $props_to_print = [ sort keys %$data ] if !defined($props_to_print);
579 foreach my $key (@$props_to_print) {
580 print $key . ": " . data_to_text
($data->{$key}) . "\n";
582 } elsif ($type eq 'array') {
583 return if !scalar(@$data);
584 my $item_type = $result_schema->{items
}->{type
};
585 if ($item_type eq 'object') {
586 print_api_list
($data, $result_schema, $props_to_print, $sort_key);
588 foreach my $entry (@$data) {
589 print data_to_text
($entry) . "\n";
596 die "internal error: unknown output format"; # should not happen
603 # simply verify all registered methods
604 PVE
::RESTHandler
::validate_method_schemas
();
607 my $get_exe_name = sub {
617 sub generate_bash_completions
{
620 # generate bash completion config
622 $exename = &$get_exe_name($class);
625 # $exename bash completion
627 # see http://tiswww.case.edu/php/chet/bash/FAQ
628 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
629 # this modifies global var, but I found no better way
630 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
632 complete -o default -C '$exename bashcomplete' $exename
636 sub generate_asciidoc_synopsys
{
638 $class->generate_asciidoc_synopsis();
641 sub generate_asciidoc_synopsis
{
644 $cli_handler_class = $class;
646 $exename = &$get_exe_name($class);
649 my $def = ${"${class}::cmddef"};
652 if (ref($def) eq 'ARRAY') {
653 print_simple_asciidoc_synopsis
();
655 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
657 print_asciidoc_synopsis
();
661 # overwrite this if you want to run/setup things early
662 sub setup_environment
{
665 # do nothing by default
668 my $handle_cmd = sub {
669 my ($args, $preparefunc, $param_mapping_func) = @_;
671 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
673 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
675 $abort->("no command specified") if !$cmd;
677 # call verifyapi before setup_environment(), don't execute any real code in
679 if ($cmd eq 'verifyapi') {
680 PVE
::RESTHandler
::validate_method_schemas
();
684 $cli_handler_class->setup_environment();
686 if ($cmd eq 'bashcomplete') {
687 &$print_bash_completion(undef, @$cmd_args);
691 # checked special commands, if def is still a hash we got an incomplete sub command
692 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
694 &$preparefunc() if $preparefunc;
696 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
697 $abort->("unknown command '$cmd_str'") if !$class;
699 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_mapping_func);
701 if (defined $outsub) {
702 my $result_schema = $class->map_method_by_name($name)->{returns
};
703 $outsub->($res, $result_schema);
707 my $handle_simple_cmd = sub {
708 my ($args, $preparefunc, $param_mapping_func) = @_;
710 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
711 die "no class specified" if !$class;
713 if (scalar(@$args) >= 1) {
714 if ($args->[0] eq 'help') {
715 my $str = "USAGE: $name help\n";
716 $str .= generate_usage_str
('long');
717 print STDERR
"$str\n\n";
719 } elsif ($args->[0] eq 'verifyapi') {
720 PVE
::RESTHandler
::validate_method_schemas
();
725 $cli_handler_class->setup_environment();
727 if (scalar(@$args) >= 1) {
728 if ($args->[0] eq 'bashcomplete') {
730 &$print_bash_completion($name, @$args);
735 &$preparefunc() if $preparefunc;
737 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $param_mapping_func);
739 if (defined $outsub) {
740 my $result_schema = $class->map_method_by_name($name)->{returns
};
741 $outsub->($res, $result_schema);
745 sub run_cli_handler
{
746 my ($class, %params) = @_;
748 $cli_handler_class = $class;
750 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
752 foreach my $key (keys %params) {
753 next if $key eq 'prepare';
754 next if $key eq 'no_init'; # not used anymore
755 next if $key eq 'no_rpcenv'; # not used anymore
756 die "unknown parameter '$key'";
759 my $preparefunc = $params{prepare
};
761 my $param_mapping_func = $gen_param_mapping_func->($cli_handler_class);
763 $exename = &$get_exe_name($class);
768 $cmddef = ${"${class}::cmddef"};
770 if (ref($cmddef) eq 'ARRAY') {
771 $handle_simple_cmd->(\
@ARGV, $preparefunc, $param_mapping_func);
773 $handle_cmd->(\
@ARGV, $preparefunc, $param_mapping_func);