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
();
54 sub get_standard_mapping
{
55 my ($name, $base) = @_;
57 my $std = $standard_mappings->{$name};
58 die "no such standard mapping '$name'\n" if !$std;
60 my $res = $base || {};
62 foreach my $opt (keys %$std) {
63 next if defined($res->{$opt});
64 $res->{$opt} = $std->{$opt};
70 my $assert_initialized = sub {
72 die "$caller[0]:$caller[2] - not initialized\n"
73 if !($cmddef && $exename && $cli_handler_class);
77 my ($reason, $cmd) = @_;
78 print_usage_short
(\
*STDERR
, $reason, $cmd);
82 my $expand_command_name = sub {
85 return $cmd if exists $def->{$cmd}; # command is already complete
87 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
88 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
90 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
95 my $get_commands = sub {
96 my $def = shift // die "no command definition passed!";
97 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
100 my $complete_command_names = sub { $get_commands->($cmddef) };
102 # traverses the command definition using the $argv array, resolving one level
104 # Returns the matching (sub) command and its definition, and argument array for
105 # this (sub) command and a hash where we marked which (sub) commands got
106 # expanded (e.g. st => status) while traversing
108 my ($argv, $is_alias) = @_;
110 my ($def, $cmd) = ($cmddef, $argv);
111 my $cmdstr = $exename;
113 if (ref($argv) eq 'ARRAY') {
114 my $expanded_last_arg;
115 my $last_arg_id = scalar(@$argv) - 1;
117 for my $i (0..$last_arg_id) {
118 $cmd = $expand_command_name->($def, $argv->[$i]);
120 # If the argument was expanded (or was already complete) and it
121 # is the final argument, tell our caller about it:
122 $expanded_last_arg = $cmd if $i == $last_arg_id;
124 # Otherwise continue with the unexpanded version of it.
129 last if !defined($def);
131 if (ref($def) eq 'ARRAY') {
132 # could expand to a real command, rest of $argv are its arguments
133 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
134 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
137 if (defined($def->{alias
})) {
138 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
139 # replace aliased (sub)command with the expanded aliased command
140 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
141 return resolve_cmd
($argv, 1);
144 # got either a special command (bashcomplete, verifyapi) or an unknown
145 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
146 my $cmd_args = [ @$argv[1..$last_arg_id] ];
147 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
149 return ($cmd, $def, undef, undef, $cmdstr);
152 sub generate_usage_str
{
153 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
155 $assert_initialized->();
156 die 'format required' if !$format;
158 $sortfunc //= sub { sort keys %{$_[0]} };
162 my $read_password_func = $cli_handler_class->can('read_password');
163 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
164 $cli_handler_class->can('string_param_file_mapping');
166 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
167 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
171 my ($indent, $separator, $def, $prefix) = @_;
174 if (ref($def) eq 'HASH') {
175 my $oldclass = undef;
176 foreach my $cmd (&$sortfunc($def)) {
178 if (ref($def->{$cmd}) eq 'ARRAY') {
179 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
181 $str .= $separator if $oldclass && $oldclass ne $class;
183 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
184 $fixed_param, $format,
185 $read_password_func, $param_mapping_func);
188 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
190 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
193 next if $def->{$cmd}->{alias
};
195 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
197 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
204 my ($class, $name, $arg_param, $fixed_param) = @$def;
205 $abort->("unknown command '$cmd'") if !$class;
208 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
209 $read_password_func, $param_mapping_func);
214 return $generate->($indent, $separator, $def, $cmdstr);
217 __PACKAGE__-
>register_method ({
221 description
=> "Get help about specified command.",
223 additionalProperties
=> 0,
225 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
226 description
=> 'Shows help for a specific command',
227 completion
=> $complete_command_names,
230 description
=> "Verbose output format.",
236 returns
=> { type
=> 'null' },
241 $assert_initialized->();
243 my $cmd = $param->{'extra-args'};
245 my $verbose = defined($cmd) && $cmd;
246 $verbose = $param->{verbose
} if defined($param->{verbose
});
250 print_usage_verbose
();
252 print_usage_short
(\
*STDOUT
);
259 $str = generate_usage_str
('full', $cmd, '');
261 $str = generate_usage_str
('short', $cmd, ' ' x
7);
268 print "USAGE: $str\n";
275 sub print_simple_asciidoc_synopsis
{
276 $assert_initialized->();
278 my $synopsis = "*${exename}* `help`\n\n";
279 $synopsis .= generate_usage_str
('asciidoc');
284 sub print_asciidoc_synopsis
{
285 $assert_initialized->();
289 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
291 $synopsis .= generate_usage_str
('asciidoc');
298 sub print_usage_verbose
{
299 $assert_initialized->();
301 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
303 my $str = generate_usage_str
('full');
308 sub print_usage_short
{
309 my ($fd, $msg, $cmd) = @_;
311 $assert_initialized->();
313 print $fd "ERROR: $msg\n" if $msg;
314 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
316 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
319 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
320 # $a and $b are both real commands order them by their class
321 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
322 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
323 # real command and subcommand mixed, put sub commands first
324 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
326 # both are either from the same class or subcommands
333 my $print_bash_completion = sub {
334 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
338 return if !(defined($cur) && defined($prev) && defined($bash_command));
339 return if !defined($ENV{COMP_LINE
});
340 return if !defined($ENV{COMP_POINT
});
342 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
343 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
345 my $args = PVE
::Tools
::split_args
($cmdline);
346 shift @$args; # no need for program name
347 my $print_result = sub {
349 print "$p\n" if $p =~ m/^\Q$cur\E/;
353 my ($cmd, $def) = ($simple_cmd, $cmddef);
355 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
357 if (defined($expanded) && $prev ne $expanded) {
362 if (ref($def) eq 'HASH') {
363 &$print_result(@{$get_commands->($def)});
369 my $pos = scalar(@$args) - 1;
370 $pos += 1 if $cmdline =~ m/\s+$/;
371 print STDERR
"pos: $pos\n" if $debug;
376 my ($class, $name, $arg_param, $uri_param) = @$def;
380 $arg_param = [ $arg_param ] if !ref($arg_param);
382 map { $skip_param->{$_} = 1; } @$arg_param;
383 map { $skip_param->{$_} = 1; } keys %$uri_param;
385 my $info = $class->map_method_by_name($name);
387 my $prop = $info->{parameters
}->{properties
};
389 my $print_parameter_completion = sub {
391 my $d = $prop->{$pname};
392 if ($d->{completion
}) {
393 my $vt = ref($d->{completion
});
395 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
396 &$print_result(@$res);
398 } elsif ($d->{type
} eq 'boolean') {
399 &$print_result('0', '1');
400 } elsif ($d->{enum
}) {
401 &$print_result(@{$d->{enum
}});
405 # positional arguments
406 if ($pos < scalar(@$arg_param)) {
407 my $pname = $arg_param->[$pos];
408 &$print_parameter_completion($pname);
412 my @option_list = ();
413 foreach my $key (keys %$prop) {
414 next if $skip_param->{$key};
415 push @option_list, "--$key";
419 &$print_result(@option_list);
423 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
425 &$print_parameter_completion($pname);
429 &$print_result(@option_list);
435 return undef if !defined($data);
437 if (my $class = ref($data)) {
438 return to_json
($data, { utf8
=> 1, canonical
=> 1 });
444 # prints a formatted table with a title row.
445 # $formatopts is an array of hashes, with the following keys:
446 # 'key' - key of $data element to print
447 # 'title' - column title, defaults to 'key' - won't get cutoff
448 # 'cutoff' - maximal (print) length of this column values, if set
449 # the last column will never be cutoff
450 # 'default' - optional default value for the column
451 # formatopts element order defines column order (left to right)
452 # sorts the output according to the leftmost column not containing any undef
453 sub print_text_table
{
454 my ($formatopts, $data) = @_;
456 my ($formatstring, @keys, @titles, %cutoffs, %defaults, $sort_key);
457 my $last_col = $formatopts->[$#{$formatopts}];
459 foreach my $col ( @$formatopts ) {
460 my ($key, $title, $cutoff) = @$col{qw(key title cutoff)};
464 push @titles, $title;
465 $defaults{$key} = $col->{default} // '';
467 # calculate maximal print width and cutoff
468 my $titlelen = length($title);
470 my $longest = $titlelen;
472 foreach my $entry (@$data) {
473 my $len = length(data_to_text
($entry->{$key})) // 0;
474 $longest = $len if $len > $longest;
475 $sortable = 0 if !defined($entry->{$key});
478 $sort_key //= $key if $sortable;
479 $cutoff = (defined($cutoff) && $cutoff < $longest) ?
$cutoff : $longest;
480 $cutoffs{$key} = $cutoff;
482 my $printalign = $cutoff > $titlelen ?
'-' : '';
483 if ($col == $last_col) {
484 $formatstring .= "%${printalign}${titlelen}s\n";
486 $formatstring .= "%${printalign}${cutoff}s ";
490 printf $formatstring, @titles;
492 if (defined($sort_key)){
493 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
495 foreach my $entry (@$data) {
496 printf $formatstring, map { substr((data_to_text
($entry->{$_}) // $defaults{$_}), 0 , $cutoffs{$_}) } @keys;
500 # prints the result of an API GET call returning an array
501 # and to have the results key of the API call defined.
503 my ($data, $result_schema, $props_to_print) = @_;
505 die "can only print object lists\n"
506 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
508 my $returnprops = $result_schema->{items
}->{properties
};
510 if (!defined($props_to_print)) {
511 $props_to_print = [ sort keys %$returnprops ];
512 if (!scalar(@$props_to_print)) {
513 $props_to_print = [ sort keys %{$data->[0]} ];
515 die "unable to detect list properties\n" if !scalar(@$props_to_print);
519 foreach my $prop ( @$props_to_print ) {
520 my $propinfo = $returnprops->{$prop};
523 title
=> $propinfo->{title
},
524 default => $propinfo->{default},
525 cutoff
=> $propinfo->{print_width
} // $propinfo->{maxLength
},
527 push @$formatopts, $colopts;
530 print_text_table
($formatopts, $data);
533 sub print_api_result
{
534 my ($format, $data, $result_schema) = @_;
536 return if $result_schema->{type
} eq 'null';
538 if ($format eq 'json') {
539 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
540 } elsif ($format eq 'text') {
541 my $type = $result_schema->{type
};
542 if ($type eq 'object') {
543 foreach my $key (sort keys %$data) {
544 print $key . ": " . data_to_text
($data->{$key}) . "\n";
546 } elsif ($type eq 'array') {
547 return if !scalar(@$data);
548 my $item_type = $result_schema->{items
}->{type
};
549 if ($item_type eq 'object') {
550 print_api_list
($data, $result_schema);
552 foreach my $entry (@$data) {
553 print data_to_text
($entry) . "\n";
560 die "internal error: unknown output format"; # should not happen
567 # simply verify all registered methods
568 PVE
::RESTHandler
::validate_method_schemas
();
571 my $get_exe_name = sub {
581 sub generate_bash_completions
{
584 # generate bash completion config
586 $exename = &$get_exe_name($class);
589 # $exename bash completion
591 # see http://tiswww.case.edu/php/chet/bash/FAQ
592 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
593 # this modifies global var, but I found no better way
594 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
596 complete -o default -C '$exename bashcomplete' $exename
600 sub generate_asciidoc_synopsys
{
602 $class->generate_asciidoc_synopsis();
605 sub generate_asciidoc_synopsis
{
608 $cli_handler_class = $class;
610 $exename = &$get_exe_name($class);
613 my $def = ${"${class}::cmddef"};
616 if (ref($def) eq 'ARRAY') {
617 print_simple_asciidoc_synopsis
();
619 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
621 print_asciidoc_synopsis
();
625 # overwrite this if you want to run/setup things early
626 sub setup_environment
{
629 # do nothing by default
632 my $handle_cmd = sub {
633 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
635 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
637 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
639 $abort->("no command specified") if !$cmd;
641 # call verifyapi before setup_environment(), don't execute any real code in
643 if ($cmd eq 'verifyapi') {
644 PVE
::RESTHandler
::validate_method_schemas
();
648 $cli_handler_class->setup_environment();
650 if ($cmd eq 'bashcomplete') {
651 &$print_bash_completion(undef, @$cmd_args);
655 # checked special commands, if def is still a hash we got an incomplete sub command
656 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
658 &$preparefunc() if $preparefunc;
660 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
661 $abort->("unknown command '$cmd_str'") if !$class;
663 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
665 if (defined $outsub) {
666 my $result_schema = $class->map_method_by_name($name)->{returns
};
667 $outsub->($res, $result_schema);
671 my $handle_simple_cmd = sub {
672 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
674 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
675 die "no class specified" if !$class;
677 if (scalar(@$args) >= 1) {
678 if ($args->[0] eq 'help') {
679 my $str = "USAGE: $name help\n";
680 $str .= generate_usage_str
('long');
681 print STDERR
"$str\n\n";
683 } elsif ($args->[0] eq 'verifyapi') {
684 PVE
::RESTHandler
::validate_method_schemas
();
689 $cli_handler_class->setup_environment();
691 if (scalar(@$args) >= 1) {
692 if ($args->[0] eq 'bashcomplete') {
694 &$print_bash_completion($name, @$args);
699 &$preparefunc() if $preparefunc;
701 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
703 if (defined $outsub) {
704 my $result_schema = $class->map_method_by_name($name)->{returns
};
705 $outsub->($res, $result_schema);
709 sub run_cli_handler
{
710 my ($class, %params) = @_;
712 $cli_handler_class = $class;
714 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
716 foreach my $key (keys %params) {
717 next if $key eq 'prepare';
718 next if $key eq 'no_init'; # not used anymore
719 next if $key eq 'no_rpcenv'; # not used anymore
720 die "unknown parameter '$key'";
723 my $preparefunc = $params{prepare
};
725 my $read_password_func = $class->can('read_password');
726 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
727 $class->can('string_param_file_mapping');
729 $exename = &$get_exe_name($class);
734 $cmddef = ${"${class}::cmddef"};
736 if (ref($cmddef) eq 'ARRAY') {
737 &$handle_simple_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
739 &$handle_cmd(\
@ARGV, $read_password_func, $preparefunc, $param_mapping_func);