rename $can_read_pass to $read_password_func
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
5
93ddd7bc 6use PVE::SafeSyslog;
e143e9d8
DM
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::RESTHandler;
881eb755 9use PVE::INotify;
e143e9d8
DM
10
11use base qw(PVE::RESTHandler);
12
c1059f7c
TL
13# $cmddef defines which (sub)commands are available in a specific CLI class.
14# A real command is always an array consisting of its class, name, array of
15# position fixed (required) parameters and hash of predefined parameters when
16# mapping a CLI command t o an API call. Optionally an output method can be
17# passed at the end, e.g., for formatting or transformation purpose.
18#
19# [class, name, fixed_params, API_pre-set params, output_sub ]
20#
21# In case of so called 'simple commands', the $cmddef can be also just an
22# array.
23#
24# Examples:
25# $cmddef = {
26# command => [ 'PVE::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
27# do => {
28# this => [ 'PVE::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
29# my ($res) = @_;
30# print "$res\n";
31# }],
32# that => [ 'PVE::API2::OtherClass', 'subroutine' [] ],
33# },
34# dothat => { alias => 'do that' },
35# }
e143e9d8
DM
36my $cmddef;
37my $exename;
891b798d 38my $cli_handler_class;
e143e9d8 39
d204696c
TL
40my $assert_initialized = sub {
41 my @caller = caller;
42 die "$caller[0]:$caller[2] - not initialized\n"
43 if !($cmddef && $exename && $cli_handler_class);
44};
45
918140af
TL
46my $abort = sub {
47 my ($reason, $cmd) = @_;
48 print_usage_short (\*STDERR, $reason, $cmd);
49 exit (-1);
50};
51
e143e9d8
DM
52my $expand_command_name = sub {
53 my ($def, $cmd) = @_;
54
55 if (!$def->{$cmd}) {
7bac844e
TL
56 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
57 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
e143e9d8
DM
58 }
59 return $cmd;
60};
61
50b89b88
TL
62my $get_commands = sub {
63 my $def = shift // die "no command definition passed!";
64 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias})) } sort keys %$def ];
edf3d572
DM
65};
66
50b89b88
TL
67my $complete_command_names = sub { $get_commands->($cmddef) };
68
69# traverses the command definition using the $argv array, resolving one level
70# of aliases.
71# Returns the matching (sub) command and its definition, and argument array for
72# this (sub) command and a hash where we marked which (sub) commands got
73# expanded (e.g. st => status) while traversing
74sub resolve_cmd {
75 my ($argv, $is_alias) = @_;
76
77 my ($def, $cmd) = ($cmddef, $argv);
78
79 if (ref($argv) eq 'ARRAY') {
80 my $expanded = {};
81 my $last_arg_id = scalar(@$argv) - 1;
82
83 for my $i (0..$last_arg_id) {
84 $cmd = $expand_command_name->($def, $argv->[$i]);
85 $expanded->{$argv->[$i]} = $cmd if $cmd ne $argv->[$i];
86 last if !defined($def->{$cmd});
87 $def = $def->{$cmd};
88
89 if (ref($def) eq 'ARRAY') {
90 # could expand to a real command, rest of $argv are its arguments
91 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
92 return ($cmd, $def, $cmd_args, $expanded);
93 }
94
95 if (defined($def->{alias})) {
96 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
97 # replace aliased (sub)command with the expanded aliased command
98 splice @$argv, $i, 1, split(/ +/, $def->{alias});
99 return resolve_cmd($argv, 1);
100 }
101 }
102 # got either a special command (bashcomplete, verifyapi) or an unknown
103 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
104 my $cmd_args = [ @$argv[1..$last_arg_id] ];
105 return ($argv->[0], $def, $cmd_args, $expanded);
106 }
107 return ($cmd, $def);
108}
109
4c802a57
TL
110sub generate_usage_str {
111 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
112
113 $assert_initialized->();
114 die 'format required' if !$format;
115
116 $sortfunc //= sub { sort keys %{$_[0]} };
117 $separator //= '';
118 $indent //= '';
119
4e0214fa 120 my $read_password_func = $cli_handler_class->can('read_password');
94e0f954 121 my $param_mapping_func = $cli_handler_class->can('string_param_file_mapping');
4c802a57 122
50b89b88 123 my ($subcmd, $def) = resolve_cmd($cmd);
4c802a57
TL
124
125 my $generate;
126 $generate = sub {
127 my ($indent, $separator, $def, $prefix) = @_;
128
129 my $str = '';
130 if (ref($def) eq 'HASH') {
131 my $oldclass = undef;
132 foreach my $cmd (&$sortfunc($def)) {
133
134 if (ref($def->{$cmd}) eq 'ARRAY') {
135 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
136
137 $str .= $separator if $oldclass && $oldclass ne $class;
138 $str .= $indent;
139 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
140 $fixed_param, $format,
4e0214fa 141 $read_password_func, $param_mapping_func);
4c802a57 142 $oldclass = $class;
50b89b88
TL
143
144 } elsif (defined($def->{$cmd}->{alias}) && ($format eq 'asciidoc')) {
145
146 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
147
148 } else {
149 next if $def->{$cmd}->{alias};
150
151 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
152 if ($substr) {
153 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
154 $str .= $substr;
155 }
4c802a57
TL
156 }
157
158 }
159 } else {
160 my ($class, $name, $arg_param, $fixed_param) = @$def;
161 $abort->("unknown command '$cmd'") if !$class;
162
163 $str .= $indent;
164 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
4e0214fa 165 $read_password_func, $param_mapping_func);
4c802a57
TL
166 }
167 return $str;
168 };
169
50b89b88
TL
170 my $cmdstr = $exename;
171 $cmdstr .= ' ' . join(' ', @$cmd) if defined($cmd);
172
173 return $generate->($indent, $separator, $def, $cmdstr);
4c802a57
TL
174}
175
e143e9d8 176__PACKAGE__->register_method ({
3ef20687 177 name => 'help',
e143e9d8
DM
178 path => 'help',
179 method => 'GET',
180 description => "Get help about specified command.",
181 parameters => {
3ef20687 182 additionalProperties => 0,
e143e9d8 183 properties => {
6627ae09
TL
184 'extra-args' => PVE::JSONSchema::get_standard_option('extra-args', {
185 description => 'Shows help for a specific command',
edf3d572 186 completion => $complete_command_names,
6627ae09 187 }),
e143e9d8
DM
188 verbose => {
189 description => "Verbose output format.",
190 type => 'boolean',
191 optional => 1,
192 },
193 },
194 },
195 returns => { type => 'null' },
3ef20687 196
e143e9d8
DM
197 code => sub {
198 my ($param) = @_;
199
d204696c 200 $assert_initialized->();
e143e9d8 201
6627ae09 202 my $cmd = $param->{'extra-args'};
e143e9d8 203
6627ae09 204 my $verbose = defined($cmd) && $cmd;
e143e9d8
DM
205 $verbose = $param->{verbose} if defined($param->{verbose});
206
207 if (!$cmd) {
208 if ($verbose) {
209 print_usage_verbose();
3ef20687 210 } else {
e143e9d8
DM
211 print_usage_short(\*STDOUT);
212 }
213 return undef;
214 }
215
4c802a57
TL
216 my $str;
217 if ($verbose) {
218 $str = generate_usage_str('full', $cmd, '');
219 } else {
220 $str = generate_usage_str('short', $cmd, ' ' x 7);
221 }
222 $str =~ s/^\s+//;
e143e9d8 223
e143e9d8
DM
224 if ($verbose) {
225 print "$str\n";
226 } else {
227 print "USAGE: $str\n";
228 }
229
230 return undef;
231
232 }});
233
0a5a1eee 234sub print_simple_asciidoc_synopsis {
d204696c 235 $assert_initialized->();
fe3f1fde 236
4c802a57
TL
237 my $synopsis = "*${exename}* `help`\n\n";
238 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
239
240 return $synopsis;
241}
242
0a5a1eee 243sub print_asciidoc_synopsis {
d204696c 244 $assert_initialized->();
fe3f1fde 245
fe3f1fde
DM
246 my $synopsis = "";
247
248 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
249
4c802a57 250 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
251
252 $synopsis .= "\n";
253
254 return $synopsis;
255}
256
e143e9d8 257sub print_usage_verbose {
d204696c 258 $assert_initialized->();
891b798d 259
e143e9d8
DM
260 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
261
4c802a57 262 my $str = generate_usage_str('full');
e143e9d8 263
4c802a57 264 print "$str\n";
e143e9d8
DM
265}
266
267sub print_usage_short {
50b89b88 268 my ($fd, $msg, $cmd) = @_;
e143e9d8 269
d204696c 270 $assert_initialized->();
891b798d 271
e143e9d8
DM
272 print $fd "ERROR: $msg\n" if $msg;
273 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
274
50b89b88 275 print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub {
4c802a57
TL
276 my ($h) = @_;
277 return sort {
278 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
279 # $a and $b are both real commands order them by their class
280 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
50b89b88
TL
281 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
282 # real command and subcommand mixed, put sub commands first
283 return ref($h->{$b}) eq 'ARRAY' ? -1 : 1;
4c802a57 284 } else {
50b89b88 285 # both are either from the same class or subcommands
4c802a57
TL
286 return $a cmp $b;
287 }
288 } keys %$h;
289 });
e143e9d8
DM
290}
291
d8053c08 292my $print_bash_completion = sub {
57e67ea3 293 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
294
295 my $debug = 0;
296
297 return if !(defined($cur) && defined($prev) && defined($bash_command));
298 return if !defined($ENV{COMP_LINE});
299 return if !defined($ENV{COMP_POINT});
300
301 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
302 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
303
58d9e664 304 my $args = PVE::Tools::split_args($cmdline);
5fa768fc 305 shift @$args; # no need for program name
d8053c08
DM
306 my $print_result = sub {
307 foreach my $p (@_) {
308 print "$p\n" if $p =~ m/^$cur/;
309 }
310 };
311
5fa768fc
TL
312 my ($cmd, $def) = ($simple_cmd, $cmddef);
313 if (!$simple_cmd) {
50b89b88
TL
314 ($cmd, $def, $args, my $expaned) = resolve_cmd($args);
315
316 if (ref($def) eq 'HASH') {
317 &$print_result(@{$get_commands->($def)});
318 return;
319 }
320 if (my $expanded_cmd = $expaned->{$cur}) {
321 print "$expanded_cmd\n";
d8053c08
DM
322 return;
323 }
d8053c08 324 }
d8053c08
DM
325 return if !$def;
326
5fa768fc
TL
327 my $pos = scalar(@$args) - 1;
328 $pos += 1 if $cmdline =~ m/\s+$/;
329 print STDERR "pos: $pos\n" if $debug;
330 return if $pos < 0;
d8053c08
DM
331
332 my $skip_param = {};
333
334 my ($class, $name, $arg_param, $uri_param) = @$def;
335 $arg_param //= [];
336 $uri_param //= {};
337
d90a2fd0
DM
338 $arg_param = [ $arg_param ] if !ref($arg_param);
339
d8053c08
DM
340 map { $skip_param->{$_} = 1; } @$arg_param;
341 map { $skip_param->{$_} = 1; } keys %$uri_param;
342
d8053c08
DM
343 my $info = $class->map_method_by_name($name);
344
5fa768fc 345 my $prop = $info->{parameters}->{properties};
d8053c08
DM
346
347 my $print_parameter_completion = sub {
348 my ($pname) = @_;
349 my $d = $prop->{$pname};
350 if ($d->{completion}) {
351 my $vt = ref($d->{completion});
352 if ($vt eq 'CODE') {
58d9e664 353 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
354 &$print_result(@$res);
355 }
356 } elsif ($d->{type} eq 'boolean') {
357 &$print_result('0', '1');
358 } elsif ($d->{enum}) {
359 &$print_result(@{$d->{enum}});
360 }
361 };
362
363 # positional arguments
5fa768fc
TL
364 $pos++ if $simple_cmd;
365 if ($pos < scalar(@$arg_param)) {
366 my $pname = $arg_param->[$pos];
d8053c08
DM
367 &$print_parameter_completion($pname);
368 return;
369 }
370
371 my @option_list = ();
372 foreach my $key (keys %$prop) {
373 next if $skip_param->{$key};
374 push @option_list, "--$key";
375 }
376
377 if ($cur =~ m/^-/) {
378 &$print_result(@option_list);
379 return;
380 }
381
382 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
383 my $pname = $1;
384 &$print_parameter_completion($pname);
385 return;
386 }
387
388 &$print_result(@option_list);
389};
390
1f130ba6
DM
391sub verify_api {
392 my ($class) = @_;
393
394 # simply verify all registered methods
395 PVE::RESTHandler::validate_method_schemas();
396}
397
8f3712f8
DM
398my $get_exe_name = sub {
399 my ($class) = @_;
3ef20687 400
8f3712f8
DM
401 my $name = $class;
402 $name =~ s/^.*:://;
403 $name =~ s/_/-/g;
404
405 return $name;
406};
407
c45707a0
DM
408sub generate_bash_completions {
409 my ($class) = @_;
410
411 # generate bash completion config
412
8f3712f8 413 $exename = &$get_exe_name($class);
c45707a0
DM
414
415 print <<__EOD__;
416# $exename bash completion
417
418# see http://tiswww.case.edu/php/chet/bash/FAQ
419# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
420# this modifies global var, but I found no better way
421COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
422
e4a1d8e2 423complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
424__EOD__
425}
426
fe3f1fde
DM
427sub generate_asciidoc_synopsys {
428 my ($class) = @_;
0a5a1eee
FG
429 $class->generate_asciidoc_synopsis();
430};
431
432sub generate_asciidoc_synopsis {
433 my ($class) = @_;
fe3f1fde
DM
434
435 $cli_handler_class = $class;
436
437 $exename = &$get_exe_name($class);
438
439 no strict 'refs';
440 my $def = ${"${class}::cmddef"};
57e67ea3 441 $cmddef = $def;
fe3f1fde
DM
442
443 if (ref($def) eq 'ARRAY') {
4c802a57 444 print_simple_asciidoc_synopsis();
fe3f1fde 445 } else {
fe3f1fde
DM
446 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
447
0a5a1eee 448 print_asciidoc_synopsis();
fe3f1fde
DM
449 }
450}
451
7b7f99c9
DM
452# overwrite this if you want to run/setup things early
453sub setup_environment {
454 my ($class) = @_;
455
456 # do nothing by default
457}
458
891b798d 459my $handle_cmd = sub {
8d3eb3ce 460 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
e143e9d8 461
6627ae09 462 $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ];
e143e9d8 463
50b89b88
TL
464 my $cmd_str = join(' ', @$args);
465 my ($cmd, $def, $cmd_args) = resolve_cmd($args);
7b7f99c9 466
918140af
TL
467 $abort->("no command specified") if !$cmd;
468
469 # call verifyapi before setup_environment(), don't execute any real code in
470 # this case
471 if ($cmd eq 'verifyapi') {
e143e9d8
DM
472 PVE::RESTHandler::validate_method_schemas();
473 return;
7b7f99c9
DM
474 }
475
476 $cli_handler_class->setup_environment();
477
478 if ($cmd eq 'bashcomplete') {
50b89b88 479 &$print_bash_completion(undef, @$cmd_args);
d8053c08 480 return;
e143e9d8
DM
481 }
482
50b89b88
TL
483 # checked special commands, if def is still a hash we got an incomplete sub command
484 $abort->("incomplete command '$exename $cmd_str'") if ref($def) eq 'HASH';
8e3e9929 485
50b89b88 486 &$preparefunc() if $preparefunc;
e143e9d8 487
b8dc4366 488 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
50b89b88 489 $abort->("unknown command '$cmd_str'") if !$class;
e143e9d8 490
50b89b88 491 my $prefix = "$exename $cmd_str";
8d3eb3ce 492 my $res = $class->cli_handler($prefix, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
2026f4b5
DM
493
494 &$outsub($res) if $outsub;
891b798d 495};
2026f4b5 496
891b798d 497my $handle_simple_cmd = sub {
8d3eb3ce 498 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
2026f4b5 499
57e67ea3 500 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
501 die "no class specified" if !$class;
502
d8053c08 503 if (scalar(@$args) >= 1) {
2026f4b5
DM
504 if ($args->[0] eq 'help') {
505 my $str = "USAGE: $name help\n";
4c802a57 506 $str .= generate_usage_str('long');
2026f4b5
DM
507 print STDERR "$str\n\n";
508 return;
509 } elsif ($args->[0] eq 'verifyapi') {
510 PVE::RESTHandler::validate_method_schemas();
511 return;
2026f4b5 512 }
e143e9d8 513 }
2026f4b5 514
7b7f99c9
DM
515 $cli_handler_class->setup_environment();
516
517 if (scalar(@$args) >= 1) {
518 if ($args->[0] eq 'bashcomplete') {
519 shift @$args;
57e67ea3 520 &$print_bash_completion($name, @$args);
7b7f99c9
DM
521 return;
522 }
523 }
524
7fe1f565
DM
525 &$preparefunc() if $preparefunc;
526
8d3eb3ce 527 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
2026f4b5
DM
528
529 &$outsub($res) if $outsub;
891b798d
DM
530};
531
891b798d
DM
532sub run_cli_handler {
533 my ($class, %params) = @_;
534
535 $cli_handler_class = $class;
536
537 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
538
aa9b9af5 539 foreach my $key (keys %params) {
5ae87c41 540 next if $key eq 'prepare';
1042b82c
DM
541 next if $key eq 'no_init'; # not used anymore
542 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
543 die "unknown parameter '$key'";
544 }
545
5ae87c41 546 my $preparefunc = $params{prepare};
891b798d 547
8d3eb3ce 548 my $read_password_func = $class->can('read_password');
b01af861 549 my $param_mapping_func = $class->can('string_param_file_mapping');
891b798d
DM
550
551 $exename = &$get_exe_name($class);
552
553 initlog($exename);
554
891b798d 555 no strict 'refs';
57e67ea3 556 $cmddef = ${"${class}::cmddef"};
891b798d 557
57e67ea3 558 if (ref($cmddef) eq 'ARRAY') {
8d3eb3ce 559 &$handle_simple_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
891b798d 560 } else {
8d3eb3ce 561 &$handle_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
891b798d
DM
562 }
563
564 exit 0;
e143e9d8
DM
565}
566
5671;