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