]> git.proxmox.com Git - pve-common.git/blame - src/PVE/CLIHandler.pm
schema_get_type_text: return format_description if available
[pve-common.git] / src / PVE / CLIHandler.pm
CommitLineData
e143e9d8
DM
1package PVE::CLIHandler;
2
3use strict;
4use warnings;
d8053c08 5use Data::Dumper;
e143e9d8 6
93ddd7bc 7use PVE::SafeSyslog;
e143e9d8
DM
8use PVE::Exception qw(raise raise_param_exc);
9use PVE::RESTHandler;
10use PVE::PodParser;
881eb755 11use PVE::INotify;
e143e9d8
DM
12
13use base qw(PVE::RESTHandler);
14
15my $cmddef;
16my $exename;
891b798d 17my $cli_handler_class;
e143e9d8
DM
18
19my $expand_command_name = sub {
20 my ($def, $cmd) = @_;
21
22 if (!$def->{$cmd}) {
23 my $expanded;
24 for my $k (keys(%$def)) {
25 if ($k =~ m/^$cmd/) {
26 if ($expanded) {
27 $expanded = undef; # more than one match
28 last;
29 } else {
30 $expanded = $k;
31 }
32 }
33 }
34 $cmd = $expanded if $expanded;
35 }
36 return $cmd;
37};
38
edf3d572
DM
39my $complete_command_names = sub {
40 my $res = [];
41
42 return if ref($cmddef) ne 'HASH';
43
44 foreach my $cmd (keys %$cmddef) {
45 next if $cmd eq 'help';
46 push @$res, $cmd;
47 }
48
49 return $res;
50};
51
e143e9d8
DM
52__PACKAGE__->register_method ({
53 name => 'help',
54 path => 'help',
55 method => 'GET',
56 description => "Get help about specified command.",
57 parameters => {
58 additionalProperties => 0,
59 properties => {
60 cmd => {
61 description => "Command name",
62 type => 'string',
63 optional => 1,
edf3d572 64 completion => $complete_command_names,
e143e9d8
DM
65 },
66 verbose => {
67 description => "Verbose output format.",
68 type => 'boolean',
69 optional => 1,
70 },
71 },
72 },
73 returns => { type => 'null' },
74
75 code => sub {
76 my ($param) = @_;
77
891b798d 78 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
e143e9d8
DM
79
80 my $cmd = $param->{cmd};
81
82 my $verbose = defined($cmd) && $cmd;
83 $verbose = $param->{verbose} if defined($param->{verbose});
84
85 if (!$cmd) {
86 if ($verbose) {
87 print_usage_verbose();
88 } else {
89 print_usage_short(\*STDOUT);
90 }
91 return undef;
92 }
93
94 $cmd = &$expand_command_name($cmddef, $cmd);
95
96 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd} || []};
97
98 raise_param_exc({ cmd => "no such command '$cmd'"}) if !$class;
99
891b798d 100 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 101 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8 102
891b798d 103 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a
FG
104 $verbose ? 'full' : 'short', $pwcallback,
105 $stringfilemap);
e143e9d8
DM
106 if ($verbose) {
107 print "$str\n";
108 } else {
109 print "USAGE: $str\n";
110 }
111
112 return undef;
113
114 }});
115
fe3f1fde
DM
116sub print_simple_asciidoc_synopsys {
117 my ($class, $name, $arg_param, $uri_param) = @_;
118
119 die "not initialized" if !$cli_handler_class;
120
121 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 122 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
123
124 my $synopsis = "*${name}* `help`\n\n";
125
4845032a
FG
126 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
127 'asciidoc', $pwcallback, $stringfilemap);
fe3f1fde
DM
128
129 return $synopsis;
130}
131
132sub print_asciidoc_synopsys {
133
134 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
135
136 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 137 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
fe3f1fde
DM
138
139 my $synopsis = "";
140
141 $synopsis .= "*${exename}* `<COMMAND> [ARGS] [OPTIONS]`\n\n";
142
143 my $oldclass;
144 foreach my $cmd (sort keys %$cmddef) {
145 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
146 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
4845032a
FG
147 $uri_param, 'asciidoc', $pwcallback,
148 $stringfilemap);
fe3f1fde
DM
149 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
150
151 $synopsis .= "$str\n\n";
152 $oldclass = $class;
153 }
154
155 $synopsis .= "\n";
156
157 return $synopsis;
158}
159
7fe1f565
DM
160sub print_simple_pod_manpage {
161 my ($podfn, $class, $name, $arg_param, $uri_param) = @_;
162
2fff84d9
DM
163 die "not initialized" if !$cli_handler_class;
164
891b798d 165 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 166 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
891b798d 167
7fe1f565 168 my $synopsis = " $name help\n\n";
4845032a 169 my $str = $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
7fe1f565
DM
170 $str =~ s/^USAGE://;
171 $str =~ s/\n/\n /g;
172 $synopsis .= $str;
173
174 my $parser = PVE::PodParser->new();
175 $parser->{include}->{synopsis} = $synopsis;
176 $parser->parse_from_file($podfn);
177}
178
e143e9d8
DM
179sub print_pod_manpage {
180 my ($podfn) = @_;
181
891b798d 182 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
e143e9d8
DM
183 die "no pod file specified" if !$podfn;
184
891b798d 185 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 186 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
891b798d 187
e143e9d8
DM
188 my $synopsis = "";
189
190 $synopsis .= " $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
191
192 my $style = 'full'; # or should we use 'short'?
193 my $oldclass;
194 foreach my $cmd (sorted_commands()) {
195 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
891b798d 196 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
4845032a
FG
197 $uri_param, $style, $pwcallback,
198 $stringfilemap);
e143e9d8
DM
199 $str =~ s/^USAGE: //;
200
201 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
202 $str =~ s/\n/\n /g;
203 $synopsis .= " $str\n\n";
204 $oldclass = $class;
205 }
206
207 $synopsis .= "\n";
208
209 my $parser = PVE::PodParser->new();
210 $parser->{include}->{synopsis} = $synopsis;
211 $parser->parse_from_file($podfn);
212}
213
214sub print_usage_verbose {
215
891b798d
DM
216 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
217
218 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 219 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
220
221 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
222
223 foreach my $cmd (sort keys %$cmddef) {
224 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
891b798d 225 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
4845032a 226 'full', $pwcallback, $stringfilemap);
e143e9d8
DM
227 print "$str\n\n";
228 }
229}
230
231sub sorted_commands {
232 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
233}
234
235sub print_usage_short {
236 my ($fd, $msg) = @_;
237
891b798d
DM
238 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
239
240 my $pwcallback = $cli_handler_class->can('read_password');
4845032a 241 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
e143e9d8
DM
242
243 print $fd "ERROR: $msg\n" if $msg;
244 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
245
246 my $oldclass;
247 foreach my $cmd (sorted_commands()) {
248 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
4845032a 249 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
e143e9d8
DM
250 print $fd "\n" if $oldclass && $oldclass ne $class;
251 print $fd " $str";
252 $oldclass = $class;
253 }
254}
255
d8053c08
DM
256my $print_bash_completion = sub {
257 my ($cmddef, $simple_cmd, $bash_command, $cur, $prev) = @_;
258
259 my $debug = 0;
260
261 return if !(defined($cur) && defined($prev) && defined($bash_command));
262 return if !defined($ENV{COMP_LINE});
263 return if !defined($ENV{COMP_POINT});
264
265 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
266 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
267
58d9e664
DM
268 my $args = PVE::Tools::split_args($cmdline);
269 my $pos = scalar(@$args) - 2;
d8053c08
DM
270 $pos += 1 if $cmdline =~ m/\s+$/;
271
272 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
273
274 return if $pos < 0;
275
276 my $print_result = sub {
277 foreach my $p (@_) {
278 print "$p\n" if $p =~ m/^$cur/;
279 }
280 };
281
282 my $cmd;
283 if ($simple_cmd) {
284 $cmd = $simple_cmd;
285 } else {
286 if ($pos == 0) {
287 &$print_result(keys %$cmddef);
288 return;
289 }
58d9e664 290 $cmd = $args->[1];
d8053c08
DM
291 }
292
293 my $def = $cmddef->{$cmd};
294 return if !$def;
295
296 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
297
298 my $skip_param = {};
299
300 my ($class, $name, $arg_param, $uri_param) = @$def;
301 $arg_param //= [];
302 $uri_param //= {};
303
d90a2fd0
DM
304 $arg_param = [ $arg_param ] if !ref($arg_param);
305
d8053c08
DM
306 map { $skip_param->{$_} = 1; } @$arg_param;
307 map { $skip_param->{$_} = 1; } keys %$uri_param;
308
309 my $fpcount = scalar(@$arg_param);
310
311 my $info = $class->map_method_by_name($name);
312
313 my $schema = $info->{parameters};
314 my $prop = $schema->{properties};
315
316 my $print_parameter_completion = sub {
317 my ($pname) = @_;
318 my $d = $prop->{$pname};
319 if ($d->{completion}) {
320 my $vt = ref($d->{completion});
321 if ($vt eq 'CODE') {
58d9e664 322 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
d8053c08
DM
323 &$print_result(@$res);
324 }
325 } elsif ($d->{type} eq 'boolean') {
326 &$print_result('0', '1');
327 } elsif ($d->{enum}) {
328 &$print_result(@{$d->{enum}});
329 }
330 };
331
332 # positional arguments
333 $pos += 1 if $simple_cmd;
334 if ($fpcount && $pos <= $fpcount) {
335 my $pname = $arg_param->[$pos -1];
336 &$print_parameter_completion($pname);
337 return;
338 }
339
340 my @option_list = ();
341 foreach my $key (keys %$prop) {
342 next if $skip_param->{$key};
343 push @option_list, "--$key";
344 }
345
346 if ($cur =~ m/^-/) {
347 &$print_result(@option_list);
348 return;
349 }
350
351 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
352 my $pname = $1;
353 &$print_parameter_completion($pname);
354 return;
355 }
356
357 &$print_result(@option_list);
358};
359
1f130ba6
DM
360sub verify_api {
361 my ($class) = @_;
362
363 # simply verify all registered methods
364 PVE::RESTHandler::validate_method_schemas();
365}
366
8f3712f8
DM
367my $get_exe_name = sub {
368 my ($class) = @_;
369
370 my $name = $class;
371 $name =~ s/^.*:://;
372 $name =~ s/_/-/g;
373
374 return $name;
375};
376
c45707a0
DM
377sub generate_bash_completions {
378 my ($class) = @_;
379
380 # generate bash completion config
381
8f3712f8 382 $exename = &$get_exe_name($class);
c45707a0
DM
383
384 print <<__EOD__;
385# $exename bash completion
386
387# see http://tiswww.case.edu/php/chet/bash/FAQ
388# and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
389# this modifies global var, but I found no better way
390COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
391
e4a1d8e2 392complete -o default -C '$exename bashcomplete' $exename
c45707a0
DM
393__EOD__
394}
395
7fe1f565 396sub find_cli_class_source {
8f3712f8 397 my ($name) = @_;
7fe1f565
DM
398
399 my $filename;
400
8f3712f8
DM
401 $name =~ s/-/_/g;
402
403 my $cpath = "PVE/CLI/${name}.pm";
404 my $spath = "PVE/Service/${name}.pm";
7fe1f565 405 foreach my $p (@INC) {
edf3d572
DM
406 foreach my $s (($cpath, $spath)) {
407 my $testfn = "$p/$s";
408 if (-f $testfn) {
409 $filename = $testfn;
410 last;
411 }
7fe1f565 412 }
edf3d572 413 last if defined($filename);
7fe1f565
DM
414 }
415
416 return $filename;
417}
418
1f130ba6
DM
419sub generate_pod_manpage {
420 my ($class, $podfn) = @_;
421
891b798d
DM
422 $cli_handler_class = $class;
423
8f3712f8 424 $exename = &$get_exe_name($class);
1f130ba6 425
7fe1f565 426 $podfn = find_cli_class_source($exename) if !defined($podfn);
1f130ba6
DM
427
428 die "unable to find source for class '$class'" if !$podfn;
429
7fe1f565
DM
430 no strict 'refs';
431 my $def = ${"${class}::cmddef"};
432
bb958629 433 if (ref($def) eq 'ARRAY') {
7fe1f565
DM
434 print_simple_pod_manpage($podfn, @$def);
435 } else {
436 $cmddef = $def;
edf3d572
DM
437
438 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
439
7fe1f565
DM
440 print_pod_manpage($podfn);
441 }
1f130ba6
DM
442}
443
fe3f1fde
DM
444sub generate_asciidoc_synopsys {
445 my ($class) = @_;
446
447 $cli_handler_class = $class;
448
449 $exename = &$get_exe_name($class);
450
451 no strict 'refs';
452 my $def = ${"${class}::cmddef"};
453
454 if (ref($def) eq 'ARRAY') {
455 print_simple_asciidoc_synopsys(@$def);
456 } else {
457 $cmddef = $def;
458
459 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
460
461 print_asciidoc_synopsys();
462 }
463}
464
891b798d 465my $handle_cmd = sub {
408976c6 466 my ($def, $cmdname, $cmd, $args, $pwcallback, $podfn, $preparefunc, $stringfilemap) = @_;
e143e9d8
DM
467
468 $cmddef = $def;
469 $exename = $cmdname;
470
471 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
472
473 if (!$cmd) {
474 print_usage_short (\*STDERR, "no command specified");
475 exit (-1);
476 } elsif ($cmd eq 'verifyapi') {
477 PVE::RESTHandler::validate_method_schemas();
478 return;
479 } elsif ($cmd eq 'printmanpod') {
edf3d572 480 $podfn = find_cli_class_source($exename) if !defined($podfn);
e143e9d8
DM
481 print_pod_manpage($podfn);
482 return;
d8053c08
DM
483 } elsif ($cmd eq 'bashcomplete') {
484 &$print_bash_completion($cmddef, 0, @$args);
485 return;
e143e9d8
DM
486 }
487
8e3e9929
WB
488 &$preparefunc() if $preparefunc;
489
e143e9d8
DM
490 $cmd = &$expand_command_name($cmddef, $cmd);
491
492 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
493
494 if (!$class) {
495 print_usage_short (\*STDERR, "unknown command '$cmd'");
496 exit (-1);
497 }
498
499 my $prefix = "$exename $cmd";
408976c6 500 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
501
502 &$outsub($res) if $outsub;
891b798d 503};
2026f4b5 504
891b798d 505my $handle_simple_cmd = sub {
408976c6 506 my ($def, $args, $pwcallback, $podfn, $preparefunc, $stringfilemap) = @_;
2026f4b5
DM
507
508 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
509 die "no class specified" if !$class;
510
d8053c08 511 if (scalar(@$args) >= 1) {
2026f4b5
DM
512 if ($args->[0] eq 'help') {
513 my $str = "USAGE: $name help\n";
4845032a 514 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
2026f4b5
DM
515 print STDERR "$str\n\n";
516 return;
d8053c08
DM
517 } elsif ($args->[0] eq 'bashcomplete') {
518 shift @$args;
519 &$print_bash_completion({ $name => $def }, $name, @$args);
520 return;
2026f4b5
DM
521 } elsif ($args->[0] eq 'verifyapi') {
522 PVE::RESTHandler::validate_method_schemas();
523 return;
524 } elsif ($args->[0] eq 'printmanpod') {
7fe1f565
DM
525 $podfn = find_cli_class_source($name) if !defined($podfn);
526 print_simple_pod_manpage($podfn, @$def);
2026f4b5
DM
527 return;
528 }
e143e9d8 529 }
2026f4b5 530
7fe1f565
DM
531 &$preparefunc() if $preparefunc;
532
408976c6 533 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
2026f4b5
DM
534
535 &$outsub($res) if $outsub;
891b798d
DM
536};
537
538sub run_cli {
539 my ($class, $pwcallback, $podfn, $preparefunc) = @_;
540
541 # Note: "depreciated function run_cli - use run_cli_handler instead";
542
543 die "password callback is no longer supported" if $pwcallback;
544
5ae87c41 545 run_cli_handler($class, podfn => $podfn, prepare => $preparefunc);
891b798d
DM
546}
547
548sub run_cli_handler {
549 my ($class, %params) = @_;
550
551 $cli_handler_class = $class;
552
553 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
554
aa9b9af5
DM
555 foreach my $key (keys %params) {
556 next if $key eq 'podfn';
5ae87c41 557 next if $key eq 'prepare';
5ffbe2f1 558 next if $key eq 'no_init'; # used by lxc hooks
aa9b9af5
DM
559 die "unknown parameter '$key'";
560 }
561
891b798d 562 my $podfn = $params{podfn};
5ae87c41 563 my $preparefunc = $params{prepare};
5ffbe2f1 564 my $no_init = $params{no_init};
891b798d
DM
565
566 my $pwcallback = $class->can('read_password');
408976c6 567 my $stringfilemap = $class->can('string_param_file_mapping');
891b798d
DM
568
569 $exename = &$get_exe_name($class);
570
571 initlog($exename);
572
573 if ($class !~ m/^PVE::Service::/) {
574 die "please run as root\n" if $> != 0;
575
5ffbe2f1 576 PVE::INotify::inotify_init() if !$no_init;
891b798d
DM
577
578 my $rpcenv = PVE::RPCEnvironment->init('cli');
5ffbe2f1 579 $rpcenv->init_request() if !$no_init;
891b798d
DM
580 $rpcenv->set_language($ENV{LANG});
581 $rpcenv->set_user('root@pam');
582 }
583
584 no strict 'refs';
585 my $def = ${"${class}::cmddef"};
586
587 if (ref($def) eq 'ARRAY') {
408976c6 588 &$handle_simple_cmd($def, \@ARGV, $pwcallback, $podfn, $preparefunc, $stringfilemap);
891b798d
DM
589 } else {
590 $cmddef = $def;
591 my $cmd = shift @ARGV;
408976c6 592 &$handle_cmd($cmddef, $exename, $cmd, \@ARGV, $pwcallback, $podfn, $preparefunc, $stringfilemap);
891b798d
DM
593 }
594
595 exit 0;
e143e9d8
DM
596}
597
5981;