]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
cli: remove all output formatter magic from CLIHandler
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
340c9862 5use JSON;
e143e9d8 6
93ddd7bc 7use PVE::SafeSyslog;
e143e9d8
DM
8use PVE::Exception qw(raise raise_param_exc);
9use PVE::RESTHandler;
0da61ab3 10use PVE::PTY;
881eb755 11use PVE::INotify;
f53ad23a 12use PVE::CLIFormatter;
e143e9d8
DM
13
14use base qw(PVE::RESTHandler);
15
c1059f7c
TL
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.
21#
22# [class, name, fixed_params, API_pre-set params, output_sub ]
23#
24# In case of so called 'simple commands', the $cmddef can be also just an
25# array.
26#
27# Examples:
28# $cmddef = {
29# command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
30# do => {
31# this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
32# my ($res) = @_;
33# print "$res\n";
34# }],
35# that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
36# },
37# dothat => { alias => 'do that' },
38# }
e143e9d8
DM
39my $cmddef;
40my $exename;
891b798d 41my $cli_handler_class;
e143e9d8 42
37f010e7
TL
43my $standard_mappings = {
44 'pve-password' => {
45 name => 'password',
46 desc => '<password>',
47 interactive => 1,
48 func => sub {
49 my ($value) = @_;
50 return $value if $value;
51 return PVE::PTY::get_confirmed_password();
52 },
53 },
54};
55sub get_standard_mapping {
56 my ($name, $base) = @_;
57
58 my $std = $standard_mappings->{$name};
59 die "no such standard mapping '$name'\n" if !$std;
60
61 my $res = $base || {};
62
63 foreach my $opt (keys %$std) {
64 next if defined($res->{$opt});
65 $res->{$opt} = $std->{$opt};
66 }
67
68 return $res;
69}
70
4842b651
DC
71my $gen_param_mapping_func = sub {
72 my ($cli_handler_class) = @_;
73
74 my $param_mapping = $cli_handler_class->can('param_mapping');
75
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');
79
80 return $string_param_mapping if !$read_password;
81
82 $param_mapping = sub {
83 my ($name) = @_;
84
85 my $password_map = get_standard_mapping('pve-password', {
86 func => $read_password
87 });
88 my $map = $string_param_mapping ? $string_param_mapping->($name) : [];
89 return [@$map, $password_map];
90 };
91 }
92
93 return $param_mapping;
94};
95
d204696c
TL
96my $assert_initialized = sub {
97 my @caller = caller;
98 die "$caller[0]:$caller[2] - not initialized\n"
99 if !($cmddef && $exename && $cli_handler_class);
100};
101
918140af
TL
102my $abort = sub {
103 my ($reason, $cmd) = @_;
104 print_usage_short (\*STDERR, $reason, $cmd);
105 exit (-1);
106};
107
e143e9d8
DM
108my $expand_command_name = sub {
109 my ($def, $cmd) = @_;
110
5082a17b
WB
111 return $cmd if exists $def->{$cmd}; # command is already complete
112
ea5a5084 113 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias}) };
0b796806
TL
114 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
115
5082a17b
WB
116 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
117
118 return undef;
e143e9d8
DM
119};
120
50b89b88
TL
121my $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 ];
edf3d572
DM
124};
125
50b89b88
TL
126my $complete_command_names = sub { $get_commands->($cmddef) };
127
128# traverses the command definition using the $argv array, resolving one level
129# of aliases.
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
133sub resolve_cmd {
134 my ($argv, $is_alias) = @_;
135
136 my ($def, $cmd) = ($cmddef, $argv);
f9326469 137 my $cmdstr = $exename;
50b89b88
TL
138
139 if (ref($argv) eq 'ARRAY') {
5082a17b 140 my $expanded_last_arg;
50b89b88
TL
141 my $last_arg_id = scalar(@$argv) - 1;
142
143 for my $i (0..$last_arg_id) {
144 $cmd = $expand_command_name->($def, $argv->[$i]);
5082a17b
WB
145 if (defined($cmd)) {
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;
149 } else {
150 # Otherwise continue with the unexpanded version of it.
151 $cmd = $argv->[$i];
152 }
f9326469 153 $cmdstr .= " $cmd";
50b89b88 154 $def = $def->{$cmd};
57c0d0c6 155 last if !defined($def);
50b89b88
TL
156
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] ];
5082a17b 160 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
50b89b88
TL
161 }
162
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);
168 }
169 }
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] ];
5082a17b 173 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
50b89b88 174 }
f9326469 175 return ($cmd, $def, undef, undef, $cmdstr);
50b89b88
TL
176}
177
4c802a57
TL
178sub generate_usage_str {
179 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
180
181 $assert_initialized->();
182 die 'format required' if !$format;
183
184 $sortfunc //= sub { sort keys %{$_[0]} };
185 $separator //= '';
186 $indent //= '';
187
968bcf45 188 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
4c802a57 189
f9326469 190 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd($cmd);
24ccf353 191 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
4c802a57
TL
192
193 my $generate;
194 $generate = sub {
195 my ($indent, $separator, $def, $prefix) = @_;
196
197 my $str = '';
198 if (ref($def) eq 'HASH') {
199 my $oldclass = undef;
200 foreach my $cmd (&$sortfunc($def)) {
201
202 if (ref($def->{$cmd}) eq 'ARRAY') {
203 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
204
205 $str .= $separator if $oldclass && $oldclass ne $class;
206 $str .= $indent;
207 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
968bcf45 208 $fixed_param, $format, $param_cb);
4c802a57 209 $oldclass = $class;
50b89b88
TL
210
211 } elsif (defined($def->{$cmd}->{alias}) && ($format eq 'asciidoc')) {
212
213 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
214
215 } else {
216 next if $def->{$cmd}->{alias};
217
218 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
219 if ($substr) {
220 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
221 $str .= $substr;
222 }
4c802a57
TL
223 }
224
225 }
226 } else {
227 my ($class, $name, $arg_param, $fixed_param) = @$def;
228 $abort->("unknown command '$cmd'") if !$class;
229
230 $str .= $indent;
968bcf45 231 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format, $param_cb);
4c802a57
TL
232 }
233 return $str;
234 };
235
50b89b88 236 return $generate->($indent, $separator, $def, $cmdstr);
4c802a57
TL
237}
238
e143e9d8 239__PACKAGE__->register_method ({
3ef20687 240 name => 'help',
e143e9d8
DM
241 path => 'help',
242 method => 'GET',
243 description => "Get help about specified command.",
244 parameters => {
3ef20687 245 additionalProperties => 0,
e143e9d8 246 properties => {
6627ae09
TL
247 'extra-args' => PVE::JSONSchema::get_standard_option('extra-args', {
248 description => 'Shows help for a specific command',
edf3d572 249 completion => $complete_command_names,
6627ae09 250 }),
e143e9d8
DM
251 verbose => {
252 description => "Verbose output format.",
253 type => 'boolean',
254 optional => 1,
255 },
256 },
257 },
258 returns => { type => 'null' },
3ef20687 259
e143e9d8
DM
260 code => sub {
261 my ($param) = @_;
262
d204696c 263 $assert_initialized->();
e143e9d8 264
6627ae09 265 my $cmd = $param->{'extra-args'};
e143e9d8 266
6627ae09 267 my $verbose = defined($cmd) && $cmd;
e143e9d8
DM
268 $verbose = $param->{verbose} if defined($param->{verbose});
269
270 if (!$cmd) {
271 if ($verbose) {
272 print_usage_verbose();
3ef20687 273 } else {
e143e9d8
DM
274 print_usage_short(\*STDOUT);
275 }
276 return undef;
277 }
278
4c802a57
TL
279 my $str;
280 if ($verbose) {
281 $str = generate_usage_str('full', $cmd, '');
282 } else {
283 $str = generate_usage_str('short', $cmd, ' ' x 7);
284 }
285 $str =~ s/^\s+//;
e143e9d8 286
e143e9d8
DM
287 if ($verbose) {
288 print "$str\n";
289 } else {
290 print "USAGE: $str\n";
291 }
292
293 return undef;
294
295 }});
296
0a5a1eee 297sub print_simple_asciidoc_synopsis {
d204696c 298 $assert_initialized->();
fe3f1fde 299
4c802a57
TL
300 my $synopsis = "*${exename}* `help`\n\n";
301 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
302
303 return $synopsis;
304}
305
0a5a1eee 306sub print_asciidoc_synopsis {
d204696c 307 $assert_initialized->();
fe3f1fde 308
fe3f1fde
DM
309 my $synopsis = "";
310
311 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
312
4c802a57 313 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
314
315 $synopsis .= "\n";
316
317 return $synopsis;
318}
319
e143e9d8 320sub print_usage_verbose {
d204696c 321 $assert_initialized->();
891b798d 322
e143e9d8
DM
323 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
324
4c802a57 325 my $str = generate_usage_str('full');
e143e9d8 326
4c802a57 327 print "$str\n";
e143e9d8
DM
328}
329
330sub print_usage_short {
50b89b88 331 my ($fd, $msg, $cmd) = @_;
e143e9d8 332
d204696c 333 $assert_initialized->();
891b798d 334
e143e9d8
DM
335 print $fd "ERROR: $msg\n" if $msg;
336 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
337
50b89b88 338 print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub {
4c802a57
TL
339 my ($h) = @_;
340 return sort {
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;
50b89b88
TL
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;
4c802a57 347 } else {
50b89b88 348 # both are either from the same class or subcommands
4c802a57
TL
349 return $a cmp $b;
350 }
351 } keys %$h;
352 });
e143e9d8
DM
353}
354
d8053c08 355my $print_bash_completion = sub {
57e67ea3 356 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
357
358 my $debug = 0;
359
360 return if !(defined($cur) && defined($prev) && defined($bash_command));
361 return if !defined($ENV{COMP_LINE});
362 return if !defined($ENV{COMP_POINT});
363
364 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
365 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
366
58d9e664 367 my $args = PVE::Tools::split_args($cmdline);
5fa768fc 368 shift @$args; # no need for program name
d8053c08
DM
369 my $print_result = sub {
370 foreach my $p (@_) {
2c48a665 371 print "$p\n" if $p =~ m/^\Q$cur\E/;
d8053c08
DM
372 }
373 };
374
5fa768fc
TL
375 my ($cmd, $def) = ($simple_cmd, $cmddef);
376 if (!$simple_cmd) {
0ed80698 377 ($cmd, $def, $args, my $expanded) = resolve_cmd($args);
50b89b88 378
5082a17b
WB
379 if (defined($expanded) && $prev ne $expanded) {
380 print "$expanded\n";
50b89b88
TL
381 return;
382 }
5082a17b
WB
383
384 if (ref($def) eq 'HASH') {
385 &$print_result(@{$get_commands->($def)});
d8053c08
DM
386 return;
387 }
d8053c08 388 }
d8053c08
DM
389 return if !$def;
390
5fa768fc
TL
391 my $pos = scalar(@$args) - 1;
392 $pos += 1 if $cmdline =~ m/\s+$/;
393 print STDERR "pos: $pos\n" if $debug;
394 return if $pos < 0;
d8053c08
DM
395
396 my $skip_param = {};
397
398 my ($class, $name, $arg_param, $uri_param) = @$def;
399 $arg_param //= [];
400 $uri_param //= {};
401
d90a2fd0
DM
402 $arg_param = [ $arg_param ] if !ref($arg_param);
403
d8053c08
DM
404 map { $skip_param->{$_} = 1; } @$arg_param;
405 map { $skip_param->{$_} = 1; } keys %$uri_param;
406
d8053c08
DM
407 my $info = $class->map_method_by_name($name);
408
5fa768fc 409 my $prop = $info->{parameters}->{properties};
d8053c08
DM
410
411 my $print_parameter_completion = sub {
412 my ($pname) = @_;
413 my $d = $prop->{$pname};
414 if ($d->{completion}) {
415 my $vt = ref($d->{completion});
416 if ($vt eq 'CODE') {
58d9e664 417 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
418 &$print_result(@$res);
419 }
420 } elsif ($d->{type} eq 'boolean') {
421 &$print_result('0', '1');
422 } elsif ($d->{enum}) {
423 &$print_result(@{$d->{enum}});
424 }
425 };
426
427 # positional arguments
5fa768fc
TL
428 if ($pos < scalar(@$arg_param)) {
429 my $pname = $arg_param->[$pos];
d8053c08
DM
430 &$print_parameter_completion($pname);
431 return;
432 }
433
434 my @option_list = ();
435 foreach my $key (keys %$prop) {
436 next if $skip_param->{$key};
437 push @option_list, "--$key";
438 }
439
440 if ($cur =~ m/^-/) {
441 &$print_result(@option_list);
442 return;
443 }
444
445 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
446 my $pname = $1;
447 &$print_parameter_completion($pname);
448 return;
449 }
450
451 &$print_result(@option_list);
452};
453
1f130ba6
DM
454sub verify_api {
455 my ($class) = @_;
456
457 # simply verify all registered methods
458 PVE::RESTHandler::validate_method_schemas();
459}
460
8f3712f8
DM
461my $get_exe_name = sub {
462 my ($class) = @_;
3ef20687 463
8f3712f8
DM
464 my $name = $class;
465 $name =~ s/^.*:://;
466 $name =~ s/_/-/g;
467
468 return $name;
469};
470
c45707a0
DM
471sub generate_bash_completions {
472 my ($class) = @_;
473
474 # generate bash completion config
475
8f3712f8 476 $exename = &$get_exe_name($class);
c45707a0
DM
477
478 print <<__EOD__;
479# $exename bash completion
480
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
484COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
485
e4a1d8e2 486complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
487__EOD__
488}
489
fe3f1fde
DM
490sub generate_asciidoc_synopsys {
491 my ($class) = @_;
0a5a1eee
FG
492 $class->generate_asciidoc_synopsis();
493};
494
495sub generate_asciidoc_synopsis {
496 my ($class) = @_;
fe3f1fde
DM
497
498 $cli_handler_class = $class;
499
500 $exename = &$get_exe_name($class);
501
502 no strict 'refs';
503 my $def = ${"${class}::cmddef"};
57e67ea3 504 $cmddef = $def;
fe3f1fde
DM
505
506 if (ref($def) eq 'ARRAY') {
4c802a57 507 print_simple_asciidoc_synopsis();
fe3f1fde 508 } else {
fe3f1fde
DM
509 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
510
0a5a1eee 511 print_asciidoc_synopsis();
fe3f1fde
DM
512 }
513}
514
7b7f99c9
DM
515# overwrite this if you want to run/setup things early
516sub setup_environment {
517 my ($class) = @_;
518
519 # do nothing by default
520}
521
891b798d 522my $handle_cmd = sub {
968bcf45 523 my ($args, $preparefunc, $param_cb) = @_;
e143e9d8 524
6627ae09 525 $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ];
e143e9d8 526
f9326469 527 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd($args);
7b7f99c9 528
918140af
TL
529 $abort->("no command specified") if !$cmd;
530
531 # call verifyapi before setup_environment(), don't execute any real code in
532 # this case
533 if ($cmd eq 'verifyapi') {
e143e9d8
DM
534 PVE::RESTHandler::validate_method_schemas();
535 return;
7b7f99c9
DM
536 }
537
538 $cli_handler_class->setup_environment();
539
540 if ($cmd eq 'bashcomplete') {
50b89b88 541 &$print_bash_completion(undef, @$cmd_args);
d8053c08 542 return;
e143e9d8
DM
543 }
544
50b89b88 545 # checked special commands, if def is still a hash we got an incomplete sub command
131f316b 546 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
8e3e9929 547
50b89b88 548 &$preparefunc() if $preparefunc;
e143e9d8 549
b8dc4366 550 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
50b89b88 551 $abort->("unknown command '$cmd_str'") if !$class;
e143e9d8 552
4cbcd138 553 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $param_cb);
2026f4b5 554
a604bf22 555 if (defined $outsub) {
ec3cbded 556 my $result_schema = $class->map_method_by_name($name)->{returns};
4cbcd138 557 $outsub->($res, $result_schema);
a604bf22 558 }
891b798d 559};
2026f4b5 560
891b798d 561my $handle_simple_cmd = sub {
968bcf45 562 my ($args, $preparefunc, $param_cb) = @_;
2026f4b5 563
57e67ea3 564 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
565 die "no class specified" if !$class;
566
d8053c08 567 if (scalar(@$args) >= 1) {
2026f4b5
DM
568 if ($args->[0] eq 'help') {
569 my $str = "USAGE: $name help\n";
4c802a57 570 $str .= generate_usage_str('long');
2026f4b5
DM
571 print STDERR "$str\n\n";
572 return;
573 } elsif ($args->[0] eq 'verifyapi') {
574 PVE::RESTHandler::validate_method_schemas();
575 return;
2026f4b5 576 }
e143e9d8 577 }
2026f4b5 578
7b7f99c9
DM
579 $cli_handler_class->setup_environment();
580
581 if (scalar(@$args) >= 1) {
582 if ($args->[0] eq 'bashcomplete') {
583 shift @$args;
57e67ea3 584 &$print_bash_completion($name, @$args);
7b7f99c9
DM
585 return;
586 }
587 }
588
7fe1f565
DM
589 &$preparefunc() if $preparefunc;
590
4cbcd138 591 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $param_cb);
2026f4b5 592
a604bf22 593 if (defined $outsub) {
ec3cbded 594 my $result_schema = $class->map_method_by_name($name)->{returns};
4cbcd138 595 $outsub->($res, $result_schema);
a604bf22 596 }
891b798d
DM
597};
598
891b798d
DM
599sub run_cli_handler {
600 my ($class, %params) = @_;
601
602 $cli_handler_class = $class;
603
604 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
605
aa9b9af5 606 foreach my $key (keys %params) {
5ae87c41 607 next if $key eq 'prepare';
1042b82c
DM
608 next if $key eq 'no_init'; # not used anymore
609 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
610 die "unknown parameter '$key'";
611 }
612
5ae87c41 613 my $preparefunc = $params{prepare};
891b798d 614
968bcf45 615 my $param_cb = $gen_param_mapping_func->($cli_handler_class);
891b798d
DM
616
617 $exename = &$get_exe_name($class);
618
57d44151
DM
619 my $logid = $ENV{PVE_LOG_ID} || $exename;
620 initlog($logid);
891b798d 621
891b798d 622 no strict 'refs';
57e67ea3 623 $cmddef = ${"${class}::cmddef"};
891b798d 624
57e67ea3 625 if (ref($cmddef) eq 'ARRAY') {
968bcf45 626 $handle_simple_cmd->(\@ARGV, $preparefunc, $param_cb);
891b798d 627 } else {
968bcf45 628 $handle_cmd->(\@ARGV, $preparefunc, $param_cb);
891b798d
DM
629 }
630
631 exit 0;
e143e9d8
DM
632}
633
6341;