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