]>
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('string_param_file_mapping'); | |
122 | ||
123 | my ($subcmd, $def) = resolve_cmd($cmd); | |
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, | |
141 | $read_password_func, $param_mapping_func); | |
142 | $oldclass = $class; | |
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 | } | |
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, | |
165 | $read_password_func, $param_mapping_func); | |
166 | } | |
167 | return $str; | |
168 | }; | |
169 | ||
170 | my $cmdstr = $exename; | |
171 | $cmdstr .= ' ' . join(' ', @$cmd) if defined($cmd); | |
172 | ||
173 | return $generate->($indent, $separator, $def, $cmdstr); | |
174 | } | |
175 | ||
176 | __PACKAGE__->register_method ({ | |
177 | name => 'help', | |
178 | path => 'help', | |
179 | method => 'GET', | |
180 | description => "Get help about specified command.", | |
181 | parameters => { | |
182 | additionalProperties => 0, | |
183 | properties => { | |
184 | 'extra-args' => PVE::JSONSchema::get_standard_option('extra-args', { | |
185 | description => 'Shows help for a specific command', | |
186 | completion => $complete_command_names, | |
187 | }), | |
188 | verbose => { | |
189 | description => "Verbose output format.", | |
190 | type => 'boolean', | |
191 | optional => 1, | |
192 | }, | |
193 | }, | |
194 | }, | |
195 | returns => { type => 'null' }, | |
196 | ||
197 | code => sub { | |
198 | my ($param) = @_; | |
199 | ||
200 | $assert_initialized->(); | |
201 | ||
202 | my $cmd = $param->{'extra-args'}; | |
203 | ||
204 | my $verbose = defined($cmd) && $cmd; | |
205 | $verbose = $param->{verbose} if defined($param->{verbose}); | |
206 | ||
207 | if (!$cmd) { | |
208 | if ($verbose) { | |
209 | print_usage_verbose(); | |
210 | } else { | |
211 | print_usage_short(\*STDOUT); | |
212 | } | |
213 | return undef; | |
214 | } | |
215 | ||
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+//; | |
223 | ||
224 | if ($verbose) { | |
225 | print "$str\n"; | |
226 | } else { | |
227 | print "USAGE: $str\n"; | |
228 | } | |
229 | ||
230 | return undef; | |
231 | ||
232 | }}); | |
233 | ||
234 | sub print_simple_asciidoc_synopsis { | |
235 | $assert_initialized->(); | |
236 | ||
237 | my $synopsis = "*${exename}* `help`\n\n"; | |
238 | $synopsis .= generate_usage_str('asciidoc'); | |
239 | ||
240 | return $synopsis; | |
241 | } | |
242 | ||
243 | sub print_asciidoc_synopsis { | |
244 | $assert_initialized->(); | |
245 | ||
246 | my $synopsis = ""; | |
247 | ||
248 | $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n"; | |
249 | ||
250 | $synopsis .= generate_usage_str('asciidoc'); | |
251 | ||
252 | $synopsis .= "\n"; | |
253 | ||
254 | return $synopsis; | |
255 | } | |
256 | ||
257 | sub print_usage_verbose { | |
258 | $assert_initialized->(); | |
259 | ||
260 | print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n"; | |
261 | ||
262 | my $str = generate_usage_str('full'); | |
263 | ||
264 | print "$str\n"; | |
265 | } | |
266 | ||
267 | sub print_usage_short { | |
268 | my ($fd, $msg, $cmd) = @_; | |
269 | ||
270 | $assert_initialized->(); | |
271 | ||
272 | print $fd "ERROR: $msg\n" if $msg; | |
273 | print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n"; | |
274 | ||
275 | print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub { | |
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; | |
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; | |
284 | } else { | |
285 | # both are either from the same class or subcommands | |
286 | return $a cmp $b; | |
287 | } | |
288 | } keys %$h; | |
289 | }); | |
290 | } | |
291 | ||
292 | my $print_bash_completion = sub { | |
293 | my ($simple_cmd, $bash_command, $cur, $prev) = @_; | |
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 | ||
304 | my $args = PVE::Tools::split_args($cmdline); | |
305 | shift @$args; # no need for program name | |
306 | my $print_result = sub { | |
307 | foreach my $p (@_) { | |
308 | print "$p\n" if $p =~ m/^$cur/; | |
309 | } | |
310 | }; | |
311 | ||
312 | my ($cmd, $def) = ($simple_cmd, $cmddef); | |
313 | if (!$simple_cmd) { | |
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"; | |
322 | return; | |
323 | } | |
324 | } | |
325 | return if !$def; | |
326 | ||
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; | |
331 | ||
332 | my $skip_param = {}; | |
333 | ||
334 | my ($class, $name, $arg_param, $uri_param) = @$def; | |
335 | $arg_param //= []; | |
336 | $uri_param //= {}; | |
337 | ||
338 | $arg_param = [ $arg_param ] if !ref($arg_param); | |
339 | ||
340 | map { $skip_param->{$_} = 1; } @$arg_param; | |
341 | map { $skip_param->{$_} = 1; } keys %$uri_param; | |
342 | ||
343 | my $info = $class->map_method_by_name($name); | |
344 | ||
345 | my $prop = $info->{parameters}->{properties}; | |
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') { | |
353 | my $res = $d->{completion}->($cmd, $pname, $cur, $args); | |
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 | |
364 | $pos++ if $simple_cmd; | |
365 | if ($pos < scalar(@$arg_param)) { | |
366 | my $pname = $arg_param->[$pos]; | |
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 | ||
391 | sub verify_api { | |
392 | my ($class) = @_; | |
393 | ||
394 | # simply verify all registered methods | |
395 | PVE::RESTHandler::validate_method_schemas(); | |
396 | } | |
397 | ||
398 | my $get_exe_name = sub { | |
399 | my ($class) = @_; | |
400 | ||
401 | my $name = $class; | |
402 | $name =~ s/^.*:://; | |
403 | $name =~ s/_/-/g; | |
404 | ||
405 | return $name; | |
406 | }; | |
407 | ||
408 | sub generate_bash_completions { | |
409 | my ($class) = @_; | |
410 | ||
411 | # generate bash completion config | |
412 | ||
413 | $exename = &$get_exe_name($class); | |
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 | |
421 | COMP_WORDBREAKS=\${COMP_WORDBREAKS//:} | |
422 | ||
423 | complete -o default -C '$exename bashcomplete' $exename | |
424 | __EOD__ | |
425 | } | |
426 | ||
427 | sub generate_asciidoc_synopsys { | |
428 | my ($class) = @_; | |
429 | $class->generate_asciidoc_synopsis(); | |
430 | }; | |
431 | ||
432 | sub generate_asciidoc_synopsis { | |
433 | my ($class) = @_; | |
434 | ||
435 | $cli_handler_class = $class; | |
436 | ||
437 | $exename = &$get_exe_name($class); | |
438 | ||
439 | no strict 'refs'; | |
440 | my $def = ${"${class}::cmddef"}; | |
441 | $cmddef = $def; | |
442 | ||
443 | if (ref($def) eq 'ARRAY') { | |
444 | print_simple_asciidoc_synopsis(); | |
445 | } else { | |
446 | $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ]; | |
447 | ||
448 | print_asciidoc_synopsis(); | |
449 | } | |
450 | } | |
451 | ||
452 | # overwrite this if you want to run/setup things early | |
453 | sub setup_environment { | |
454 | my ($class) = @_; | |
455 | ||
456 | # do nothing by default | |
457 | } | |
458 | ||
459 | my $handle_cmd = sub { | |
460 | my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_; | |
461 | ||
462 | $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ]; | |
463 | ||
464 | my $cmd_str = join(' ', @$args); | |
465 | my ($cmd, $def, $cmd_args) = resolve_cmd($args); | |
466 | ||
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') { | |
472 | PVE::RESTHandler::validate_method_schemas(); | |
473 | return; | |
474 | } | |
475 | ||
476 | $cli_handler_class->setup_environment(); | |
477 | ||
478 | if ($cmd eq 'bashcomplete') { | |
479 | &$print_bash_completion(undef, @$cmd_args); | |
480 | return; | |
481 | } | |
482 | ||
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'; | |
485 | ||
486 | &$preparefunc() if $preparefunc; | |
487 | ||
488 | my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []}; | |
489 | $abort->("unknown command '$cmd_str'") if !$class; | |
490 | ||
491 | my $prefix = "$exename $cmd_str"; | |
492 | my $res = $class->cli_handler($prefix, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func); | |
493 | ||
494 | &$outsub($res) if $outsub; | |
495 | }; | |
496 | ||
497 | my $handle_simple_cmd = sub { | |
498 | my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_; | |
499 | ||
500 | my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef}; | |
501 | die "no class specified" if !$class; | |
502 | ||
503 | if (scalar(@$args) >= 1) { | |
504 | if ($args->[0] eq 'help') { | |
505 | my $str = "USAGE: $name help\n"; | |
506 | $str .= generate_usage_str('long'); | |
507 | print STDERR "$str\n\n"; | |
508 | return; | |
509 | } elsif ($args->[0] eq 'verifyapi') { | |
510 | PVE::RESTHandler::validate_method_schemas(); | |
511 | return; | |
512 | } | |
513 | } | |
514 | ||
515 | $cli_handler_class->setup_environment(); | |
516 | ||
517 | if (scalar(@$args) >= 1) { | |
518 | if ($args->[0] eq 'bashcomplete') { | |
519 | shift @$args; | |
520 | &$print_bash_completion($name, @$args); | |
521 | return; | |
522 | } | |
523 | } | |
524 | ||
525 | &$preparefunc() if $preparefunc; | |
526 | ||
527 | my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func); | |
528 | ||
529 | &$outsub($res) if $outsub; | |
530 | }; | |
531 | ||
532 | sub run_cli_handler { | |
533 | my ($class, %params) = @_; | |
534 | ||
535 | $cli_handler_class = $class; | |
536 | ||
537 | $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin'; | |
538 | ||
539 | foreach my $key (keys %params) { | |
540 | next if $key eq 'prepare'; | |
541 | next if $key eq 'no_init'; # not used anymore | |
542 | next if $key eq 'no_rpcenv'; # not used anymore | |
543 | die "unknown parameter '$key'"; | |
544 | } | |
545 | ||
546 | my $preparefunc = $params{prepare}; | |
547 | ||
548 | my $read_password_func = $class->can('read_password'); | |
549 | my $param_mapping_func = $class->can('string_param_file_mapping'); | |
550 | ||
551 | $exename = &$get_exe_name($class); | |
552 | ||
553 | initlog($exename); | |
554 | ||
555 | no strict 'refs'; | |
556 | $cmddef = ${"${class}::cmddef"}; | |
557 | ||
558 | if (ref($cmddef) eq 'ARRAY') { | |
559 | &$handle_simple_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func); | |
560 | } else { | |
561 | &$handle_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func); | |
562 | } | |
563 | ||
564 | exit 0; | |
565 | } | |
566 | ||
567 | 1; |