]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
fix #1682: handle relative years absolutely
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
5
93ddd7bc 6use PVE::SafeSyslog;
e143e9d8
DM
7use PVE::Exception qw(raise raise_param_exc);
8use PVE::RESTHandler;
881eb755 9use PVE::INotify;
e143e9d8
DM
10
11use base qw(PVE::RESTHandler);
12
c1059f7c
TL
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# }
e143e9d8
DM
36my $cmddef;
37my $exename;
891b798d 38my $cli_handler_class;
e143e9d8 39
d204696c
TL
40my $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
918140af
TL
46my $abort = sub {
47 my ($reason, $cmd) = @_;
48 print_usage_short (\*STDERR, $reason, $cmd);
49 exit (-1);
50};
51
e143e9d8
DM
52my $expand_command_name = sub {
53 my ($def, $cmd) = @_;
54
55 if (!$def->{$cmd}) {
7bac844e
TL
56 my @expanded = grep { /^\Q$cmd\E/ } keys %$def;
57 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
e143e9d8
DM
58 }
59 return $cmd;
60};
61
50b89b88
TL
62my $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 ];
edf3d572
DM
65};
66
50b89b88
TL
67my $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
74sub 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
4c802a57
TL
110sub 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
4e0214fa 120 my $read_password_func = $cli_handler_class->can('read_password');
c44ec0f6
DM
121 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
122 $cli_handler_class->can('string_param_file_mapping');
4c802a57 123
50b89b88 124 my ($subcmd, $def) = resolve_cmd($cmd);
4c802a57
TL
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,
4e0214fa 142 $read_password_func, $param_mapping_func);
4c802a57 143 $oldclass = $class;
50b89b88
TL
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 }
4c802a57
TL
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,
4e0214fa 166 $read_password_func, $param_mapping_func);
4c802a57
TL
167 }
168 return $str;
169 };
170
50b89b88
TL
171 my $cmdstr = $exename;
172 $cmdstr .= ' ' . join(' ', @$cmd) if defined($cmd);
173
174 return $generate->($indent, $separator, $def, $cmdstr);
4c802a57
TL
175}
176
e143e9d8 177__PACKAGE__->register_method ({
3ef20687 178 name => 'help',
e143e9d8
DM
179 path => 'help',
180 method => 'GET',
181 description => "Get help about specified command.",
182 parameters => {
3ef20687 183 additionalProperties => 0,
e143e9d8 184 properties => {
6627ae09
TL
185 'extra-args' => PVE::JSONSchema::get_standard_option('extra-args', {
186 description => 'Shows help for a specific command',
edf3d572 187 completion => $complete_command_names,
6627ae09 188 }),
e143e9d8
DM
189 verbose => {
190 description => "Verbose output format.",
191 type => 'boolean',
192 optional => 1,
193 },
194 },
195 },
196 returns => { type => 'null' },
3ef20687 197
e143e9d8
DM
198 code => sub {
199 my ($param) = @_;
200
d204696c 201 $assert_initialized->();
e143e9d8 202
6627ae09 203 my $cmd = $param->{'extra-args'};
e143e9d8 204
6627ae09 205 my $verbose = defined($cmd) && $cmd;
e143e9d8
DM
206 $verbose = $param->{verbose} if defined($param->{verbose});
207
208 if (!$cmd) {
209 if ($verbose) {
210 print_usage_verbose();
3ef20687 211 } else {
e143e9d8
DM
212 print_usage_short(\*STDOUT);
213 }
214 return undef;
215 }
216
4c802a57
TL
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+//;
e143e9d8 224
e143e9d8
DM
225 if ($verbose) {
226 print "$str\n";
227 } else {
228 print "USAGE: $str\n";
229 }
230
231 return undef;
232
233 }});
234
0a5a1eee 235sub print_simple_asciidoc_synopsis {
d204696c 236 $assert_initialized->();
fe3f1fde 237
4c802a57
TL
238 my $synopsis = "*${exename}* `help`\n\n";
239 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
240
241 return $synopsis;
242}
243
0a5a1eee 244sub print_asciidoc_synopsis {
d204696c 245 $assert_initialized->();
fe3f1fde 246
fe3f1fde
DM
247 my $synopsis = "";
248
249 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
250
4c802a57 251 $synopsis .= generate_usage_str('asciidoc');
fe3f1fde
DM
252
253 $synopsis .= "\n";
254
255 return $synopsis;
256}
257
e143e9d8 258sub print_usage_verbose {
d204696c 259 $assert_initialized->();
891b798d 260
e143e9d8
DM
261 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
262
4c802a57 263 my $str = generate_usage_str('full');
e143e9d8 264
4c802a57 265 print "$str\n";
e143e9d8
DM
266}
267
268sub print_usage_short {
50b89b88 269 my ($fd, $msg, $cmd) = @_;
e143e9d8 270
d204696c 271 $assert_initialized->();
891b798d 272
e143e9d8
DM
273 print $fd "ERROR: $msg\n" if $msg;
274 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
275
50b89b88 276 print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub {
4c802a57
TL
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;
50b89b88
TL
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;
4c802a57 285 } else {
50b89b88 286 # both are either from the same class or subcommands
4c802a57
TL
287 return $a cmp $b;
288 }
289 } keys %$h;
290 });
e143e9d8
DM
291}
292
d8053c08 293my $print_bash_completion = sub {
57e67ea3 294 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
d8053c08
DM
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
58d9e664 305 my $args = PVE::Tools::split_args($cmdline);
5fa768fc 306 shift @$args; # no need for program name
d8053c08
DM
307 my $print_result = sub {
308 foreach my $p (@_) {
309 print "$p\n" if $p =~ m/^$cur/;
310 }
311 };
312
5fa768fc
TL
313 my ($cmd, $def) = ($simple_cmd, $cmddef);
314 if (!$simple_cmd) {
50b89b88
TL
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";
d8053c08
DM
323 return;
324 }
d8053c08 325 }
d8053c08
DM
326 return if !$def;
327
5fa768fc
TL
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;
d8053c08
DM
332
333 my $skip_param = {};
334
335 my ($class, $name, $arg_param, $uri_param) = @$def;
336 $arg_param //= [];
337 $uri_param //= {};
338
d90a2fd0
DM
339 $arg_param = [ $arg_param ] if !ref($arg_param);
340
d8053c08
DM
341 map { $skip_param->{$_} = 1; } @$arg_param;
342 map { $skip_param->{$_} = 1; } keys %$uri_param;
343
d8053c08
DM
344 my $info = $class->map_method_by_name($name);
345
5fa768fc 346 my $prop = $info->{parameters}->{properties};
d8053c08
DM
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') {
58d9e664 354 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
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
5fa768fc
TL
365 $pos++ if $simple_cmd;
366 if ($pos < scalar(@$arg_param)) {
367 my $pname = $arg_param->[$pos];
d8053c08
DM
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
1f130ba6
DM
392sub verify_api {
393 my ($class) = @_;
394
395 # simply verify all registered methods
396 PVE::RESTHandler::validate_method_schemas();
397}
398
8f3712f8
DM
399my $get_exe_name = sub {
400 my ($class) = @_;
3ef20687 401
8f3712f8
DM
402 my $name = $class;
403 $name =~ s/^.*:://;
404 $name =~ s/_/-/g;
405
406 return $name;
407};
408
c45707a0
DM
409sub generate_bash_completions {
410 my ($class) = @_;
411
412 # generate bash completion config
413
8f3712f8 414 $exename = &$get_exe_name($class);
c45707a0
DM
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
422COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
423
e4a1d8e2 424complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
425__EOD__
426}
427
fe3f1fde
DM
428sub generate_asciidoc_synopsys {
429 my ($class) = @_;
0a5a1eee
FG
430 $class->generate_asciidoc_synopsis();
431};
432
433sub generate_asciidoc_synopsis {
434 my ($class) = @_;
fe3f1fde
DM
435
436 $cli_handler_class = $class;
437
438 $exename = &$get_exe_name($class);
439
440 no strict 'refs';
441 my $def = ${"${class}::cmddef"};
57e67ea3 442 $cmddef = $def;
fe3f1fde
DM
443
444 if (ref($def) eq 'ARRAY') {
4c802a57 445 print_simple_asciidoc_synopsis();
fe3f1fde 446 } else {
fe3f1fde
DM
447 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
448
0a5a1eee 449 print_asciidoc_synopsis();
fe3f1fde
DM
450 }
451}
452
7b7f99c9
DM
453# overwrite this if you want to run/setup things early
454sub setup_environment {
455 my ($class) = @_;
456
457 # do nothing by default
458}
459
891b798d 460my $handle_cmd = sub {
8d3eb3ce 461 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
e143e9d8 462
6627ae09 463 $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ];
e143e9d8 464
50b89b88
TL
465 my $cmd_str = join(' ', @$args);
466 my ($cmd, $def, $cmd_args) = resolve_cmd($args);
7b7f99c9 467
918140af
TL
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') {
e143e9d8
DM
473 PVE::RESTHandler::validate_method_schemas();
474 return;
7b7f99c9
DM
475 }
476
477 $cli_handler_class->setup_environment();
478
479 if ($cmd eq 'bashcomplete') {
50b89b88 480 &$print_bash_completion(undef, @$cmd_args);
d8053c08 481 return;
e143e9d8
DM
482 }
483
50b89b88
TL
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';
8e3e9929 486
50b89b88 487 &$preparefunc() if $preparefunc;
e143e9d8 488
b8dc4366 489 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
50b89b88 490 $abort->("unknown command '$cmd_str'") if !$class;
e143e9d8 491
50b89b88 492 my $prefix = "$exename $cmd_str";
8d3eb3ce 493 my $res = $class->cli_handler($prefix, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
2026f4b5
DM
494
495 &$outsub($res) if $outsub;
891b798d 496};
2026f4b5 497
891b798d 498my $handle_simple_cmd = sub {
8d3eb3ce 499 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
2026f4b5 500
57e67ea3 501 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
2026f4b5
DM
502 die "no class specified" if !$class;
503
d8053c08 504 if (scalar(@$args) >= 1) {
2026f4b5
DM
505 if ($args->[0] eq 'help') {
506 my $str = "USAGE: $name help\n";
4c802a57 507 $str .= generate_usage_str('long');
2026f4b5
DM
508 print STDERR "$str\n\n";
509 return;
510 } elsif ($args->[0] eq 'verifyapi') {
511 PVE::RESTHandler::validate_method_schemas();
512 return;
2026f4b5 513 }
e143e9d8 514 }
2026f4b5 515
7b7f99c9
DM
516 $cli_handler_class->setup_environment();
517
518 if (scalar(@$args) >= 1) {
519 if ($args->[0] eq 'bashcomplete') {
520 shift @$args;
57e67ea3 521 &$print_bash_completion($name, @$args);
7b7f99c9
DM
522 return;
523 }
524 }
525
7fe1f565
DM
526 &$preparefunc() if $preparefunc;
527
8d3eb3ce 528 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
2026f4b5
DM
529
530 &$outsub($res) if $outsub;
891b798d
DM
531};
532
891b798d
DM
533sub run_cli_handler {
534 my ($class, %params) = @_;
535
536 $cli_handler_class = $class;
537
538 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
539
aa9b9af5 540 foreach my $key (keys %params) {
5ae87c41 541 next if $key eq 'prepare';
1042b82c
DM
542 next if $key eq 'no_init'; # not used anymore
543 next if $key eq 'no_rpcenv'; # not used anymore
aa9b9af5
DM
544 die "unknown parameter '$key'";
545 }
546
5ae87c41 547 my $preparefunc = $params{prepare};
891b798d 548
8d3eb3ce 549 my $read_password_func = $class->can('read_password');
c44ec0f6
DM
550 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
551 $class->can('string_param_file_mapping');
891b798d
DM
552
553 $exename = &$get_exe_name($class);
554
555 initlog($exename);
556
891b798d 557 no strict 'refs';
57e67ea3 558 $cmddef = ${"${class}::cmddef"};
891b798d 559
57e67ea3 560 if (ref($cmddef) eq 'ARRAY') {
8d3eb3ce 561 &$handle_simple_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
891b798d 562 } else {
8d3eb3ce 563 &$handle_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
891b798d
DM
564 }
565
566 exit 0;
e143e9d8
DM
567}
568
5691;