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