]> git.proxmox.com Git - pve-client.git/blob - PVE/APIClient/CLIHandler.pm
update files from pve-common
[pve-client.git] / PVE / APIClient / CLIHandler.pm
1 package PVE::APIClient::CLIHandler;
2
3 use strict;
4 use warnings;
5
6 use PVE::APIClient::SafeSyslog;
7 use PVE::APIClient::Exception qw(raise raise_param_exc);
8 use PVE::APIClient::RESTHandler;
9 use PVE::APIClient::PTY;
10
11
12 use base qw(PVE::APIClient::RESTHandler);
13
14 # $cmddef defines which (sub)commands are available in a specific CLI class.
15 # A real command is always an array consisting of its class, name, array of
16 # position fixed (required) parameters and hash of predefined parameters when
17 # mapping a CLI command t o an API call. Optionally an output method can be
18 # passed at the end, e.g., for formatting or transformation purpose.
19 #
20 # [class, name, fixed_params, API_pre-set params, output_sub ]
21 #
22 # In case of so called 'simple commands', the $cmddef can be also just an
23 # array.
24 #
25 # Examples:
26 # $cmddef = {
27 # command => [ 'PVE::APIClient::API2::Class', 'command', [ 'arg1', 'arg2' ], { node => $nodename } ],
28 # do => {
29 # this => [ 'PVE::APIClient::API2::OtherClass', 'method', [ 'arg1' ], undef, sub {
30 # my ($res) = @_;
31 # print "$res\n";
32 # }],
33 # that => [ 'PVE::APIClient::API2::OtherClass', 'subroutine' [] ],
34 # },
35 # dothat => { alias => 'do that' },
36 # }
37 my $cmddef;
38 my $exename;
39 my $cli_handler_class;
40
41 my $standard_mappings = {
42 'pve-password' => {
43 name => 'password',
44 desc => '<password>',
45 interactive => 1,
46 func => sub {
47 my ($value) = @_;
48 return $value if $value;
49 return PVE::APIClient::PTY::get_confirmed_password();
50 },
51 },
52 };
53 sub get_standard_mapping {
54 my ($name, $base) = @_;
55
56 my $std = $standard_mappings->{$name};
57 die "no such standard mapping '$name'\n" if !$std;
58
59 my $res = $base || {};
60
61 foreach my $opt (keys %$std) {
62 next if defined($res->{$opt});
63 $res->{$opt} = $std->{$opt};
64 }
65
66 return $res;
67 }
68
69 my $assert_initialized = sub {
70 my @caller = caller;
71 die "$caller[0]:$caller[2] - not initialized\n"
72 if !($cmddef && $exename && $cli_handler_class);
73 };
74
75 my $abort = sub {
76 my ($reason, $cmd) = @_;
77 print_usage_short (\*STDERR, $reason, $cmd);
78 exit (-1);
79 };
80
81 my $expand_command_name = sub {
82 my ($def, $cmd) = @_;
83
84 return $cmd if exists $def->{$cmd}; # command is already complete
85
86 my $is_alias = sub { ref($_[0]) eq 'HASH' && exists($_[0]->{alias}) };
87 my @expanded = grep { /^\Q$cmd\E/ && !$is_alias->($def->{$_}) } keys %$def;
88
89 return $expanded[0] if scalar(@expanded) == 1; # enforce exact match
90
91 return undef;
92 };
93
94 my $get_commands = sub {
95 my $def = shift // die "no command definition passed!";
96 return [ grep { !(ref($def->{$_}) eq 'HASH' && defined($def->{$_}->{alias})) } sort keys %$def ];
97 };
98
99 my $complete_command_names = sub { $get_commands->($cmddef) };
100
101 # traverses the command definition using the $argv array, resolving one level
102 # of aliases.
103 # Returns the matching (sub) command and its definition, and argument array for
104 # this (sub) command and a hash where we marked which (sub) commands got
105 # expanded (e.g. st => status) while traversing
106 sub resolve_cmd {
107 my ($argv, $is_alias) = @_;
108
109 my ($def, $cmd) = ($cmddef, $argv);
110 my $cmdstr = $exename;
111
112 if (ref($argv) eq 'ARRAY') {
113 my $expanded_last_arg;
114 my $last_arg_id = scalar(@$argv) - 1;
115
116 for my $i (0..$last_arg_id) {
117 $cmd = $expand_command_name->($def, $argv->[$i]);
118 if (defined($cmd)) {
119 # If the argument was expanded (or was already complete) and it
120 # is the final argument, tell our caller about it:
121 $expanded_last_arg = $cmd if $i == $last_arg_id;
122 } else {
123 # Otherwise continue with the unexpanded version of it.
124 $cmd = $argv->[$i];
125 }
126 $cmdstr .= " $cmd";
127 $def = $def->{$cmd};
128 last if !defined($def);
129
130 if (ref($def) eq 'ARRAY') {
131 # could expand to a real command, rest of $argv are its arguments
132 my $cmd_args = [ @$argv[$i+1..$last_arg_id] ];
133 return ($cmd, $def, $cmd_args, $expanded_last_arg, $cmdstr);
134 }
135
136 if (defined($def->{alias})) {
137 die "alias loop detected for '$cmd'" if $is_alias; # avoids cycles
138 # replace aliased (sub)command with the expanded aliased command
139 splice @$argv, $i, 1, split(/ +/, $def->{alias});
140 return resolve_cmd($argv, 1);
141 }
142 }
143 # got either a special command (bashcomplete, verifyapi) or an unknown
144 # cmd, just return first entry as cmd and the rest of $argv as cmd_arg
145 my $cmd_args = [ @$argv[1..$last_arg_id] ];
146 return ($argv->[0], $def, $cmd_args, $expanded_last_arg, $cmdstr);
147 }
148 return ($cmd, $def, undef, undef, $cmdstr);
149 }
150
151 sub generate_usage_str {
152 my ($format, $cmd, $indent, $separator, $sortfunc) = @_;
153
154 $assert_initialized->();
155 die 'format required' if !$format;
156
157 $sortfunc //= sub { sort keys %{$_[0]} };
158 $separator //= '';
159 $indent //= '';
160
161 my $read_password_func = $cli_handler_class->can('read_password');
162 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
163 $cli_handler_class->can('string_param_file_mapping');
164
165 my ($subcmd, $def, undef, undef, $cmdstr) = resolve_cmd($cmd);
166 $abort->("unknown command '$cmdstr'") if !defined($def) && ref($cmd) eq 'ARRAY';
167
168 my $generate;
169 $generate = sub {
170 my ($indent, $separator, $def, $prefix) = @_;
171
172 my $str = '';
173 if (ref($def) eq 'HASH') {
174 my $oldclass = undef;
175 foreach my $cmd (&$sortfunc($def)) {
176
177 if (ref($def->{$cmd}) eq 'ARRAY') {
178 my ($class, $name, $arg_param, $fixed_param) = @{$def->{$cmd}};
179
180 $str .= $separator if $oldclass && $oldclass ne $class;
181 $str .= $indent;
182 $str .= $class->usage_str($name, "$prefix $cmd", $arg_param,
183 $fixed_param, $format,
184 $read_password_func, $param_mapping_func);
185 $oldclass = $class;
186
187 } elsif (defined($def->{$cmd}->{alias}) && ($format eq 'asciidoc')) {
188
189 $str .= "*$prefix $cmd*\n\nAn alias for '$exename $def->{$cmd}->{alias}'.\n\n";
190
191 } else {
192 next if $def->{$cmd}->{alias};
193
194 my $substr = $generate->($indent, $separator, $def->{$cmd}, "$prefix $cmd");
195 if ($substr) {
196 $substr .= $separator if $substr !~ /\Q$separator\E{2}/;
197 $str .= $substr;
198 }
199 }
200
201 }
202 } else {
203 my ($class, $name, $arg_param, $fixed_param) = @$def;
204 $abort->("unknown command '$cmd'") if !$class;
205
206 $str .= $indent;
207 $str .= $class->usage_str($name, $prefix, $arg_param, $fixed_param, $format,
208 $read_password_func, $param_mapping_func);
209 }
210 return $str;
211 };
212
213 return $generate->($indent, $separator, $def, $cmdstr);
214 }
215
216 __PACKAGE__->register_method ({
217 name => 'help',
218 path => 'help',
219 method => 'GET',
220 description => "Get help about specified command.",
221 parameters => {
222 additionalProperties => 0,
223 properties => {
224 'extra-args' => PVE::APIClient::JSONSchema::get_standard_option('extra-args', {
225 description => 'Shows help for a specific command',
226 completion => $complete_command_names,
227 }),
228 verbose => {
229 description => "Verbose output format.",
230 type => 'boolean',
231 optional => 1,
232 },
233 },
234 },
235 returns => { type => 'null' },
236
237 code => sub {
238 my ($param) = @_;
239
240 $assert_initialized->();
241
242 my $cmd = $param->{'extra-args'};
243
244 my $verbose = defined($cmd) && $cmd;
245 $verbose = $param->{verbose} if defined($param->{verbose});
246
247 if (!$cmd) {
248 if ($verbose) {
249 print_usage_verbose();
250 } else {
251 print_usage_short(\*STDOUT);
252 }
253 return undef;
254 }
255
256 my $str;
257 if ($verbose) {
258 $str = generate_usage_str('full', $cmd, '');
259 } else {
260 $str = generate_usage_str('short', $cmd, ' ' x 7);
261 }
262 $str =~ s/^\s+//;
263
264 if ($verbose) {
265 print "$str\n";
266 } else {
267 print "USAGE: $str\n";
268 }
269
270 return undef;
271
272 }});
273
274 sub print_simple_asciidoc_synopsis {
275 $assert_initialized->();
276
277 my $synopsis = "*${exename}* `help`\n\n";
278 $synopsis .= generate_usage_str('asciidoc');
279
280 return $synopsis;
281 }
282
283 sub print_asciidoc_synopsis {
284 $assert_initialized->();
285
286 my $synopsis = "";
287
288 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
289
290 $synopsis .= generate_usage_str('asciidoc');
291
292 $synopsis .= "\n";
293
294 return $synopsis;
295 }
296
297 sub print_usage_verbose {
298 $assert_initialized->();
299
300 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
301
302 my $str = generate_usage_str('full');
303
304 print "$str\n";
305 }
306
307 sub print_usage_short {
308 my ($fd, $msg, $cmd) = @_;
309
310 $assert_initialized->();
311
312 print $fd "ERROR: $msg\n" if $msg;
313 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
314
315 print {$fd} generate_usage_str('short', $cmd, ' ' x 7, "\n", sub {
316 my ($h) = @_;
317 return sort {
318 if (ref($h->{$a}) eq 'ARRAY' && ref($h->{$b}) eq 'ARRAY') {
319 # $a and $b are both real commands order them by their class
320 return $h->{$a}->[0] cmp $h->{$b}->[0] || $a cmp $b;
321 } elsif (ref($h->{$a}) eq 'ARRAY' xor ref($h->{$b}) eq 'ARRAY') {
322 # real command and subcommand mixed, put sub commands first
323 return ref($h->{$b}) eq 'ARRAY' ? -1 : 1;
324 } else {
325 # both are either from the same class or subcommands
326 return $a cmp $b;
327 }
328 } keys %$h;
329 });
330 }
331
332 my $print_bash_completion = sub {
333 my ($simple_cmd, $bash_command, $cur, $prev) = @_;
334
335 my $debug = 0;
336
337 return if !(defined($cur) && defined($prev) && defined($bash_command));
338 return if !defined($ENV{COMP_LINE});
339 return if !defined($ENV{COMP_POINT});
340
341 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
342 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
343
344 my $args = PVE::APIClient::Tools::split_args($cmdline);
345 shift @$args; # no need for program name
346 my $print_result = sub {
347 foreach my $p (@_) {
348 print "$p\n" if $p =~ m/^\Q$cur\E/;
349 }
350 };
351
352 my ($cmd, $def) = ($simple_cmd, $cmddef);
353 if (!$simple_cmd) {
354 ($cmd, $def, $args, my $expanded) = resolve_cmd($args);
355
356 if (defined($expanded) && $prev ne $expanded) {
357 print "$expanded\n";
358 return;
359 }
360
361 if (ref($def) eq 'HASH') {
362 &$print_result(@{$get_commands->($def)});
363 return;
364 }
365 }
366 return if !$def;
367
368 my $pos = scalar(@$args) - 1;
369 $pos += 1 if $cmdline =~ m/\s+$/;
370 print STDERR "pos: $pos\n" if $debug;
371 return if $pos < 0;
372
373 my $skip_param = {};
374
375 my ($class, $name, $arg_param, $uri_param) = @$def;
376 $arg_param //= [];
377 $uri_param //= {};
378
379 $arg_param = [ $arg_param ] if !ref($arg_param);
380
381 map { $skip_param->{$_} = 1; } @$arg_param;
382 map { $skip_param->{$_} = 1; } keys %$uri_param;
383
384 my $info = $class->map_method_by_name($name);
385
386 my $prop = $info->{parameters}->{properties};
387
388 my $print_parameter_completion = sub {
389 my ($pname) = @_;
390 my $d = $prop->{$pname};
391 if ($d->{completion}) {
392 my $vt = ref($d->{completion});
393 if ($vt eq 'CODE') {
394 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
395 &$print_result(@$res);
396 }
397 } elsif ($d->{type} eq 'boolean') {
398 &$print_result('0', '1');
399 } elsif ($d->{enum}) {
400 &$print_result(@{$d->{enum}});
401 }
402 };
403
404 # positional arguments
405 if ($pos < scalar(@$arg_param)) {
406 my $pname = $arg_param->[$pos];
407 &$print_parameter_completion($pname);
408 return;
409 }
410
411 my @option_list = ();
412 foreach my $key (keys %$prop) {
413 next if $skip_param->{$key};
414 push @option_list, "--$key";
415 }
416
417 if ($cur =~ m/^-/) {
418 &$print_result(@option_list);
419 return;
420 }
421
422 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
423 my $pname = $1;
424 &$print_parameter_completion($pname);
425 return;
426 }
427
428 &$print_result(@option_list);
429 };
430
431 # prints a formatted table with a title row.
432 # $formatopts is an array of hashes, with the following keys:
433 # 'key' - key of $data element to print
434 # 'title' - column title, defaults to 'key' - won't get cutoff
435 # 'cutoff' - maximal (print) length of this column values, if set
436 # the last column will never be cutoff
437 # 'default' - optional default value for the column
438 # formatopts element order defines column order (left to right)
439 sub print_text_table {
440 my ($formatopts, $data) = @_;
441
442 my ($formatstring, @keys, @titles, %cutoffs, %defaults);
443 my $last_col = $formatopts->[$#{$formatopts}];
444
445 foreach my $col ( @$formatopts ) {
446 my ($key, $title, $cutoff, $default) = @$col{qw(key title cutoff default)};
447 $title //= $key;
448
449 push @keys, $key;
450 push @titles, $title;
451 $defaults{$key} = $default;
452
453 # calculate maximal print width and cutoff
454 my $titlelen = length($title);
455
456 my $longest = $titlelen;
457 foreach my $entry (@$data) {
458 my $len = length($entry->{$key}) // 0;
459 $longest = $len if $len > $longest;
460 }
461
462 $cutoff = (defined($cutoff) && $cutoff < $longest) ? $cutoff : $longest;
463 $cutoffs{$key} = $cutoff;
464
465 my $printalign = $cutoff > $titlelen ? '-' : '';
466 if ($col == $last_col) {
467 $formatstring .= "%${printalign}${titlelen}s\n";
468 } else {
469 $formatstring .= "%${printalign}${cutoff}s ";
470 }
471 }
472
473 printf $formatstring, @titles;
474
475 foreach my $entry (sort { $a->{$keys[0]} cmp $b->{$keys[0]} } @$data) {
476 printf $formatstring, map { substr(($entry->{$_} // $defaults{$_}), 0 , $cutoffs{$_}) } @keys;
477 }
478 }
479
480 sub print_entry {
481 my $entry = shift;
482
483 #TODO: handle objects/hashes as well
484 foreach my $item (sort keys %$entry) {
485 if (ref($entry->{$item}) eq 'ARRAY') {
486 printf "%s: [ %s ]\n", $item, join(", ", @{$entry->{$item}});
487 } else {
488 printf "%s: %s\n", $item, $entry->{$item};
489 }
490 }
491 }
492
493 # prints the result of an API GET call returning an array
494 # and to have the results key of the API call defined.
495 sub print_api_list {
496 my ($props_to_print, $data, $returninfo) = @_;
497
498 die "can only print array result" if $returninfo->{type} ne 'array';
499
500 my $returnprops = $returninfo->{items}->{properties};
501
502 my $formatopts = [];
503 foreach my $prop ( @$props_to_print ) {
504 my $propinfo = $returnprops->{$prop};
505 my $colopts = {
506 key => $prop,
507 title => $propinfo->{title},
508 default => $propinfo->{default},
509 cutoff => $propinfo->{print_width} // $propinfo->{maxLength},
510 };
511 push @$formatopts, $colopts;
512 }
513
514 print_text_table($formatopts, $data);
515 }
516
517 sub verify_api {
518 my ($class) = @_;
519
520 # simply verify all registered methods
521 PVE::APIClient::RESTHandler::validate_method_schemas();
522 }
523
524 my $get_exe_name = sub {
525 my ($class) = @_;
526
527 my $name = $class;
528 $name =~ s/^.*:://;
529 $name =~ s/_/-/g;
530
531 return $name;
532 };
533
534 sub generate_bash_completions {
535 my ($class) = @_;
536
537 # generate bash completion config
538
539 $exename = &$get_exe_name($class);
540
541 print <<__EOD__;
542 # $exename bash completion
543
544 # see http://tiswww.case.edu/php/chet/bash/FAQ
545 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
546 # this modifies global var, but I found no better way
547 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
548
549 complete -o default -C '$exename bashcomplete' $exename
550 __EOD__
551 }
552
553 sub generate_asciidoc_synopsys {
554 my ($class) = @_;
555 $class->generate_asciidoc_synopsis();
556 };
557
558 sub generate_asciidoc_synopsis {
559 my ($class) = @_;
560
561 $cli_handler_class = $class;
562
563 $exename = &$get_exe_name($class);
564
565 no strict 'refs';
566 my $def = ${"${class}::cmddef"};
567 $cmddef = $def;
568
569 if (ref($def) eq 'ARRAY') {
570 print_simple_asciidoc_synopsis();
571 } else {
572 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
573
574 print_asciidoc_synopsis();
575 }
576 }
577
578 # overwrite this if you want to run/setup things early
579 sub setup_environment {
580 my ($class) = @_;
581
582 # do nothing by default
583 }
584
585 my $handle_cmd = sub {
586 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
587
588 $cmddef->{help} = [ __PACKAGE__, 'help', ['extra-args'] ];
589
590 my ($cmd, $def, $cmd_args, undef, $cmd_str) = resolve_cmd($args);
591
592 $abort->("no command specified") if !$cmd;
593
594 # call verifyapi before setup_environment(), don't execute any real code in
595 # this case
596 if ($cmd eq 'verifyapi') {
597 PVE::APIClient::RESTHandler::validate_method_schemas();
598 return;
599 }
600
601 $cli_handler_class->setup_environment();
602
603 if ($cmd eq 'bashcomplete') {
604 &$print_bash_completion(undef, @$cmd_args);
605 return;
606 }
607
608 # checked special commands, if def is still a hash we got an incomplete sub command
609 $abort->("incomplete command '$cmd_str'", $args) if ref($def) eq 'HASH';
610
611 &$preparefunc() if $preparefunc;
612
613 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def || []};
614 $abort->("unknown command '$cmd_str'") if !$class;
615
616 my $res = $class->cli_handler($cmd_str, $name, $cmd_args, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
617
618 if (defined $outsub) {
619 my $returninfo = $class->map_method_by_name($name)->{returns};
620 $outsub->($res, $returninfo);
621 }
622 };
623
624 my $handle_simple_cmd = sub {
625 my ($args, $read_password_func, $preparefunc, $param_mapping_func) = @_;
626
627 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef};
628 die "no class specified" if !$class;
629
630 if (scalar(@$args) >= 1) {
631 if ($args->[0] eq 'help') {
632 my $str = "USAGE: $name help\n";
633 $str .= generate_usage_str('long');
634 print STDERR "$str\n\n";
635 return;
636 } elsif ($args->[0] eq 'verifyapi') {
637 PVE::APIClient::RESTHandler::validate_method_schemas();
638 return;
639 }
640 }
641
642 $cli_handler_class->setup_environment();
643
644 if (scalar(@$args) >= 1) {
645 if ($args->[0] eq 'bashcomplete') {
646 shift @$args;
647 &$print_bash_completion($name, @$args);
648 return;
649 }
650 }
651
652 &$preparefunc() if $preparefunc;
653
654 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $read_password_func, $param_mapping_func);
655
656 if (defined $outsub) {
657 my $returninfo = $class->map_method_by_name($name)->{returns};
658 $outsub->($res, $returninfo);
659 }
660 };
661
662 sub run_cli_handler {
663 my ($class, %params) = @_;
664
665 $cli_handler_class = $class;
666
667 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
668
669 foreach my $key (keys %params) {
670 next if $key eq 'prepare';
671 next if $key eq 'no_init'; # not used anymore
672 next if $key eq 'no_rpcenv'; # not used anymore
673 die "unknown parameter '$key'";
674 }
675
676 my $preparefunc = $params{prepare};
677
678 my $read_password_func = $class->can('read_password');
679 my $param_mapping_func = $cli_handler_class->can('param_mapping') ||
680 $class->can('string_param_file_mapping');
681
682 $exename = &$get_exe_name($class);
683
684 initlog($exename);
685
686 no strict 'refs';
687 $cmddef = ${"${class}::cmddef"};
688
689 if (ref($cmddef) eq 'ARRAY') {
690 &$handle_simple_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
691 } else {
692 &$handle_cmd(\@ARGV, $read_password_func, $preparefunc, $param_mapping_func);
693 }
694
695 exit 0;
696 }
697
698 1;