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