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