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 $gen_param_mapping_func = sub {
71 my ($cli_handler_class) = @_;
73 my $param_mapping = $cli_handler_class->can('param_mapping');
75 if (!$param_mapping) {
76 my $read_password = $cli_handler_class->can('read_password');
77 my $string_param_mapping = $cli_handler_class->can('string_param_file_mapping');
79 return $string_param_mapping if !$read_password;
81 $param_mapping = sub {
84 my $password_map = get_standard_mapping
('pve-password', {
85 func
=> $read_password
87 my $map = $string_param_mapping ?
$string_param_mapping->($name) : [];
88 return [@$map, $password_map];
92 return $param_mapping;
95 my $assert_initialized = sub {
97 die "$caller[0]:$caller[2] - not initialized\n"
98 if !($cmddef && $exename && $cli_handler_class);
102 my ($reason, $cmd) = @_;
103 print_usage_short
(\
*STDERR
, $reason, $cmd);
107 my $expand_command_name = sub {
108 my ($def, $cmd) = @_;
110 return $cmd if exists $def->{$cmd}; # command is already complete
112 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias
}) };
113 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
115 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
120 my $get_commands = sub {
121 my $def = shift // die "no command definition passed!";
122 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias
})) } sort keys %$def ];
125 my $complete_command_names = sub { $get_commands->($cmddef) };
127 # traverses the command definition using the $argv array, resolving one level
129 # Returns the matching (sub) command and its definition, and argument array for
130 # this (sub) command and a hash where we marked which (sub) commands got
131 # expanded (e.g. st => status) while traversing
133 my ($argv, $is_alias) = @_;
135 my ($def, $cmd) = ($cmddef, $argv);
136 my $cmdstr = $exename;
138 if (ref($argv) eq 'ARRAY') {
139 my $expanded_last_arg;
140 my $last_arg_id = scalar(@$argv) - 1;
142 for my $i (0..$last_arg_id) {
143 $cmd = $expand_command_name->($def, $argv->[$i]);
145 # If the argument was expanded (or was already complete) and it
146 # is the final argument, tell our caller about it:
147 $expanded_last_arg = $cmd if $i == $last_arg_id;
149 # Otherwise continue with the unexpanded version of it.
154 last if !defined($def);
156 if (ref($def) eq 'ARRAY') {
157 # could expand to a real command, rest of $argv are its arguments
158 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
159 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
162 if (defined($def->{alias
})) {
163 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
164 # replace aliased (sub)command with the expanded aliased command
165 splice @$argv, $i, 1, split(/ +/, $def->{alias
});
166 return resolve_cmd
($argv, 1);
169 # got either a special command (bashcomplete, verifyapi) or an unknown
170 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
171 my $cmd_args = [ @$argv[1..$last_arg_id] ];
172 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
174 return ($cmd, $def, undef, undef, $cmdstr);
177 sub generate_usage_str
{
178 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
180 $assert_initialized->();
181 die 'format required' if !$format;
183 $sortfunc //= sub { sort keys %{$_[0]} };
187 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
189 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd
($cmd);
190 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
194 my ($indent, $separator, $def, $prefix) = @_;
197 if (ref($def) eq 'HASH') {
198 my $oldclass = undef;
199 foreach my $cmd (&$sortfunc($def)) {
201 if (ref($def->{$cmd}) eq 'ARRAY') {
202 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
204 $str .= $separator if $oldclass && $oldclass ne $class;
206 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
207 $fixed_param, $format, $param_cb);
210 } elsif (defined($def->{$cmd}->{alias
}) && ($format eq 'asciidoc')) {
212 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
215 next if $def->{$cmd}->{alias
};
217 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
219 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
226 my ($class, $name, $arg_param, $fixed_param) = @$def;
227 $abort->("unknown command '$cmd'") if !$class;
230 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb);
235 return $generate->($indent, $separator, $def, $cmdstr);
238 __PACKAGE__-
>register_method ({
242 description
=> "Get help about specified command.",
244 additionalProperties
=> 0,
246 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args', {
247 description
=> 'Shows help for a specific command',
248 completion
=> $complete_command_names,
251 description
=> "Verbose output format.",
257 returns
=> { type
=> 'null' },
262 $assert_initialized->();
264 my $cmd = $param->{'extra-args'};
266 my $verbose = defined($cmd) && $cmd;
267 $verbose = $param->{verbose
} if defined($param->{verbose
});
271 print_usage_verbose
();
273 print_usage_short
(\
*STDOUT
);
280 $str = generate_usage_str
('full', $cmd, '');
282 $str = generate_usage_str
('short', $cmd, ' ' x
7);
289 print "USAGE: $str\n";
296 sub print_simple_asciidoc_synopsis
{
297 $assert_initialized->();
299 my $synopsis = "*${exename}* `help`\n\n";
300 $synopsis .= generate_usage_str
('asciidoc');
305 sub print_asciidoc_synopsis
{
306 $assert_initialized->();
310 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
312 $synopsis .= generate_usage_str
('asciidoc');
319 sub print_usage_verbose
{
320 $assert_initialized->();
322 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
324 my $str = generate_usage_str
('full');
329 sub print_usage_short
{
330 my ($fd, $msg, $cmd) = @_;
332 $assert_initialized->();
334 print $fd "ERROR: $msg\n" if $msg;
335 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
337 print {$fd} generate_usage_str
('short', $cmd, ' ' x
7, "\n", sub {
340 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
341 # $a and $b are both real commands order them by their class
342 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
343 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
344 # real command and subcommand mixed, put sub commands first
345 return ref($h->{$b}) eq 'ARRAY' ?
-1 : 1;
347 # both are either from the same class or subcommands
354 my $print_bash_completion = sub {
355 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
359 return if !(defined($cur) && defined($prev) && defined($bash_command));
360 return if !defined($ENV{COMP_LINE
});
361 return if !defined($ENV{COMP_POINT
});
363 my $cmdline = substr($ENV{COMP_LINE
}, 0, $ENV{COMP_POINT
});
364 print STDERR
"\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
366 my $args = PVE
::Tools
::split_args
($cmdline);
367 shift @$args; # no need for program name
368 my $print_result = sub {
370 print "$p\n" if $p =~ m/^\Q$cur\E/;
374 my ($cmd, $def) = ($simple_cmd, $cmddef);
376 ($cmd, $def, $args, my $expanded) = resolve_cmd
($args);
378 if (defined($expanded) && $prev ne $expanded) {
383 if (ref($def) eq 'HASH') {
384 &$print_result(@{$get_commands->($def)});
390 my $pos = scalar(@$args) - 1;
391 $pos += 1 if $cmdline =~ m/\s+$/;
392 print STDERR
"pos: $pos\n" if $debug;
397 my ($class, $name, $arg_param, $uri_param) = @$def;
401 $arg_param = [ $arg_param ] if !ref($arg_param);
403 map { $skip_param->{$_} = 1; } @$arg_param;
404 map { $skip_param->{$_} = 1; } keys %$uri_param;
406 my $info = $class->map_method_by_name($name);
408 my $prop = $info->{parameters
}->{properties
};
410 my $print_parameter_completion = sub {
412 my $d = $prop->{$pname};
413 if ($d->{completion
}) {
414 my $vt = ref($d->{completion
});
416 my $res = $d->{completion
}->($cmd, $pname, $cur, $args);
417 &$print_result(@$res);
419 } elsif ($d->{type
} eq 'boolean') {
420 &$print_result('0', '1');
421 } elsif ($d->{enum
}) {
422 &$print_result(@{$d->{enum
}});
426 # positional arguments
427 if ($pos < scalar(@$arg_param)) {
428 my $pname = $arg_param->[$pos];
429 &$print_parameter_completion($pname);
433 my @option_list = ();
434 foreach my $key (keys %$prop) {
435 next if $skip_param->{$key};
436 push @option_list, "--$key";
440 &$print_result(@option_list);
444 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
446 &$print_parameter_completion($pname);
450 &$print_result(@option_list);
456 return '' if !defined($data);
458 if (my $class = ref($data)) {
459 return to_json
($data, { utf8
=> 1, canonical
=> 1 });
465 # prints a formatted table with a title row.
466 # $data - the data to print (array of objects)
467 # $returnprops -json schema property description
468 # $props_to_print - ordered list of properties to print
469 # $sort_key can be used to sort after a column, if it isn't set we sort
470 # after the leftmost column (with no undef value in $data) this can be
471 # turned off by passing 0 as $sort_key
472 sub print_text_table
{
473 my ($data, $returnprops, $props_to_print, $sort_key) = @_;
476 if (defined($sort_key) && $sort_key eq 0) {
482 my $formatstring = '';
484 my $column_count = scalar(@$props_to_print);
486 for (my $i = 0; $i < $column_count; $i++) {
487 my $prop = $props_to_print->[$i];
488 my $propinfo = $returnprops->{$prop} // {};
490 my $title = $propinfo->{title
} // $prop;
491 my $cutoff = $propinfo->{print_width
} // $propinfo->{maxLength
};
493 # calculate maximal print width and cutoff
494 my $titlelen = length($title);
496 my $longest = $titlelen;
497 my $sortable = $autosort;
498 foreach my $entry (@$data) {
499 my $len = length(data_to_text
($entry->{$prop})) // 0;
500 $longest = $len if $len > $longest;
501 $sortable = 0 if !defined($entry->{$prop});
503 $cutoff = $longest if !defined($cutoff) || $cutoff > $longest;
504 $sort_key //= $prop if $sortable;
506 $colopts->{$prop} = {
508 default => $propinfo->{default} // '',
512 # skip alignment and cutoff on last column
513 $formatstring .= ($i == ($column_count - 1)) ?
"%s\n" : "%-${cutoff}s ";
516 printf $formatstring, map { $colopts->{$_}->{title
} } @$props_to_print;
518 if (defined($sort_key)) {
519 my $type = $returnprops->{$sort_key}->{type
} // 'string';
520 if ($type eq 'integer' || $type eq 'number') {
521 @$data = sort { $a->{$sort_key} <=> $b->{$sort_key} } @$data;
523 @$data = sort { $a->{$sort_key} cmp $b->{$sort_key} } @$data;
527 foreach my $entry (@$data) {
528 printf $formatstring, map {
529 substr(data_to_text
($entry->{$_}) // $colopts->{$_}->{default},
530 0, $colopts->{$_}->{cutoff
});
535 # prints the result of an API GET call returning an array as a table.
536 # takes formatting information from the results property of the call
537 # if $props_to_print is provided, prints only those columns. otherwise
538 # takes all fields of the results property, with a fallback
539 # to all fields occuring in items of $data.
541 my ($data, $result_schema, $props_to_print, $sort_key) = @_;
543 die "can only print object lists\n"
544 if !($result_schema->{type
} eq 'array' && $result_schema->{items
}->{type
} eq 'object');
546 my $returnprops = $result_schema->{items
}->{properties
};
548 if (!defined($props_to_print)) {
549 $props_to_print = [ sort keys %$returnprops ];
550 if (!scalar(@$props_to_print)) {
552 foreach my $obj (@{$data}) {
553 foreach my $key (keys %{$obj}) {
554 $all_props->{ $key } = 1;
557 $props_to_print = [ sort keys %{$all_props} ];
559 die "unable to detect list properties\n" if !scalar(@$props_to_print);
562 print_text_table
($data, $returnprops, $props_to_print, $sort_key);
565 sub print_api_result
{
566 my ($format, $data, $result_schema, $props_to_print, $sort_key) = @_;
568 return if $result_schema->{type
} eq 'null';
570 if ($format eq 'json') {
571 print to_json
($data, {utf8
=> 1, allow_nonref
=> 1, canonical
=> 1, pretty
=> 1 });
572 } elsif ($format eq 'text') {
573 my $type = $result_schema->{type
};
574 if ($type eq 'object') {
575 $props_to_print = [ sort keys %$data ] if !defined($props_to_print);
576 foreach my $key (@$props_to_print) {
577 print $key . ": " . data_to_text
($data->{$key}) . "\n";
579 } elsif ($type eq 'array') {
580 return if !scalar(@$data);
581 my $item_type = $result_schema->{items
}->{type
};
582 if ($item_type eq 'object') {
583 print_api_list
($data, $result_schema, $props_to_print, $sort_key);
585 foreach my $entry (@$data) {
586 print data_to_text
($entry) . "\n";
593 die "internal error: unknown output format"; # should not happen
600 # simply verify all registered methods
601 PVE
::RESTHandler
::validate_method_schemas
();
604 my $get_exe_name = sub {
614 sub generate_bash_completions
{
617 # generate bash completion config
619 $exename = &$get_exe_name($class);
622 # $exename bash completion
624 # see http://tiswww.case.edu/php/chet/bash/FAQ
625 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
626 # this modifies global var, but I found no better way
627 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
629 complete -o default -C '$exename bashcomplete' $exename
633 sub generate_asciidoc_synopsys
{
635 $class->generate_asciidoc_synopsis();
638 sub generate_asciidoc_synopsis
{
641 $cli_handler_class = $class;
643 $exename = &$get_exe_name($class);
646 my $def = ${"${class}::cmddef"};
649 if (ref($def) eq 'ARRAY') {
650 print_simple_asciidoc_synopsis
();
652 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['cmd'] ];
654 print_asciidoc_synopsis
();
658 # overwrite this if you want to run/setup things early
659 sub setup_environment
{
662 # do nothing by default
665 my $handle_cmd = sub {
666 my ($args, $preparefunc, $param_cb) = @_;
668 $cmddef->{help
} = [ __PACKAGE__
, 'help', ['extra-args'] ];
670 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd
($args);
672 $abort->("no command specified") if !$cmd;
674 # call verifyapi before setup_environment(), don't execute any real code in
676 if ($cmd eq 'verifyapi') {
677 PVE
::RESTHandler
::validate_method_schemas
();
681 $cli_handler_class->setup_environment();
683 if ($cmd eq 'bashcomplete') {
684 &$print_bash_completion(undef, @$cmd_args);
688 # checked special commands, if def is still a hash we got an incomplete sub command
689 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
691 &$preparefunc() if $preparefunc;
693 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
694 $abort->("unknown command '$cmd_str'") if !$class;
696 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb);
698 if (defined $outsub) {
699 my $result_schema = $class->map_method_by_name($name)->{returns
};
700 $outsub->($res, $result_schema);
704 my $handle_simple_cmd = sub {
705 my ($args, $preparefunc, $param_cb) = @_;
707 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
708 die "no class specified" if !$class;
710 if (scalar(@$args) >= 1) {
711 if ($args->[0] eq 'help') {
712 my $str = "USAGE: $name help\n";
713 $str .= generate_usage_str
('long');
714 print STDERR
"$str\n\n";
716 } elsif ($args->[0] eq 'verifyapi') {
717 PVE
::RESTHandler
::validate_method_schemas
();
722 $cli_handler_class->setup_environment();
724 if (scalar(@$args) >= 1) {
725 if ($args->[0] eq 'bashcomplete') {
727 &$print_bash_completion($name, @$args);
732 &$preparefunc() if $preparefunc;
734 my $res = $class->cli_handler($name, $name, \
@ARGV, $arg_param, $uri_param, $param_cb);
736 if (defined $outsub) {
737 my $result_schema = $class->map_method_by_name($name)->{returns
};
738 $outsub->($res, $result_schema);
742 sub run_cli_handler
{
743 my ($class, %params) = @_;
745 $cli_handler_class = $class;
747 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
749 foreach my $key (keys %params) {
750 next if $key eq 'prepare';
751 next if $key eq 'no_init'; # not used anymore
752 next if $key eq 'no_rpcenv'; # not used anymore
753 die "unknown parameter '$key'";
756 my $preparefunc = $params{prepare
};
758 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
760 $exename = &$get_exe_name($class);
765 $cmddef = ${"${class}::cmddef"};
767 if (ref($cmddef) eq 'ARRAY') {
768 $handle_simple_cmd->(\
@ARGV, $preparefunc, $param_cb);
770 $handle_cmd->(\
@ARGV, $preparefunc, $param_cb);