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