]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIHandler.pm
b684ca8408b790afb3d5f1c95797f0a7f64a5478
[pve-common.git] / src / PVE / CLIHandler.pm
1 package PVE::CLIHandler;
2
3 use strict;
4 use warnings;
5 use Data::Dumper;
6
7 use PVE::SafeSyslog;
8 use PVE::Exception qw(raise raise_param_exc);
9 use PVE::RESTHandler;
10 use PVE::PodParser;
11 use PVE::INotify;
12
13 use base qw(PVE::RESTHandler);
14
15 my $cmddef;
16 my $exename;
17 my $cli_handler_class;
18
19 my $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
39 my $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
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,
64 completion => $complete_command_names,
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
78 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
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
100 my $pwcallback = $cli_handler_class->can('read_password');
101 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
102
103 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
104 $verbose ? 'full' : 'short', $pwcallback,
105 $stringfilemap);
106 if ($verbose) {
107 print "$str\n";
108 } else {
109 print "USAGE: $str\n";
110 }
111
112 return undef;
113
114 }});
115
116 sub 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');
122 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
123
124 my $synopsis = "*${name}* `help`\n\n";
125
126 $synopsis .= $class->usage_str($name, $name, $arg_param, $uri_param,
127 'asciidoc', $pwcallback, $stringfilemap);
128
129 return $synopsis;
130 }
131
132 sub print_asciidoc_synopsys {
133
134 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
135
136 my $pwcallback = $cli_handler_class->can('read_password');
137 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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,
147 $uri_param, 'asciidoc', $pwcallback,
148 $stringfilemap);
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
160 sub print_simple_pod_manpage {
161 my ($podfn, $class, $name, $arg_param, $uri_param) = @_;
162
163 die "not initialized" if !$cli_handler_class;
164
165 my $pwcallback = $cli_handler_class->can('read_password');
166 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
167
168 my $synopsis = " $name help\n\n";
169 my $str = $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
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
179 sub print_pod_manpage {
180 my ($podfn) = @_;
181
182 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
183 die "no pod file specified" if !$podfn;
184
185 my $pwcallback = $cli_handler_class->can('read_password');
186 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
187
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}};
196 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
197 $uri_param, $style, $pwcallback,
198 $stringfilemap);
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
214 sub print_usage_verbose {
215
216 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
217
218 my $pwcallback = $cli_handler_class->can('read_password');
219 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
225 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
226 'full', $pwcallback, $stringfilemap);
227 print "$str\n\n";
228 }
229 }
230
231 sub sorted_commands {
232 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
233 }
234
235 sub print_usage_short {
236 my ($fd, $msg) = @_;
237
238 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
239
240 my $pwcallback = $cli_handler_class->can('read_password');
241 my $stringfilemap = $cli_handler_class->can('string_param_file_mapping');
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}};
249 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short', $pwcallback, $stringfilemap);
250 print $fd "\n" if $oldclass && $oldclass ne $class;
251 print $fd " $str";
252 $oldclass = $class;
253 }
254 }
255
256 my $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
268 my $args = PVE::Tools::split_args($cmdline);
269 my $pos = scalar(@$args) - 2;
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 }
290 $cmd = $args->[1];
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
304 $arg_param = [ $arg_param ] if !ref($arg_param);
305
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') {
322 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
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
360 sub verify_api {
361 my ($class) = @_;
362
363 # simply verify all registered methods
364 PVE::RESTHandler::validate_method_schemas();
365 }
366
367 my $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
377 sub generate_bash_completions {
378 my ($class) = @_;
379
380 # generate bash completion config
381
382 $exename = &$get_exe_name($class);
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
390 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
391
392 complete -o default -C '$exename bashcomplete' $exename
393 __EOD__
394 }
395
396 sub find_cli_class_source {
397 my ($name) = @_;
398
399 my $filename;
400
401 $name =~ s/-/_/g;
402
403 my $cpath = "PVE/CLI/${name}.pm";
404 my $spath = "PVE/Service/${name}.pm";
405 foreach my $p (@INC) {
406 foreach my $s (($cpath, $spath)) {
407 my $testfn = "$p/$s";
408 if (-f $testfn) {
409 $filename = $testfn;
410 last;
411 }
412 }
413 last if defined($filename);
414 }
415
416 return $filename;
417 }
418
419 sub generate_pod_manpage {
420 my ($class, $podfn) = @_;
421
422 $cli_handler_class = $class;
423
424 $exename = &$get_exe_name($class);
425
426 $podfn = find_cli_class_source($exename) if !defined($podfn);
427
428 die "unable to find source for class '$class'" if !$podfn;
429
430 no strict 'refs';
431 my $def = ${"${class}::cmddef"};
432
433 if (ref($def) eq 'ARRAY') {
434 print_simple_pod_manpage($podfn, @$def);
435 } else {
436 $cmddef = $def;
437
438 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
439
440 print_pod_manpage($podfn);
441 }
442 }
443
444 sub 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
465 my $handle_cmd = sub {
466 my ($def, $cmdname, $cmd, $args, $pwcallback, $podfn, $preparefunc, $stringfilemap) = @_;
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') {
480 $podfn = find_cli_class_source($exename) if !defined($podfn);
481 print_pod_manpage($podfn);
482 return;
483 } elsif ($cmd eq 'bashcomplete') {
484 &$print_bash_completion($cmddef, 0, @$args);
485 return;
486 }
487
488 &$preparefunc() if $preparefunc;
489
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";
500 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
501
502 &$outsub($res) if $outsub;
503 };
504
505 my $handle_simple_cmd = sub {
506 my ($def, $args, $pwcallback, $podfn, $preparefunc, $stringfilemap) = @_;
507
508 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
509 die "no class specified" if !$class;
510
511 if (scalar(@$args) >= 1) {
512 if ($args->[0] eq 'help') {
513 my $str = "USAGE: $name help\n";
514 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback, $stringfilemap);
515 print STDERR "$str\n\n";
516 return;
517 } elsif ($args->[0] eq 'bashcomplete') {
518 shift @$args;
519 &$print_bash_completion({ $name => $def }, $name, @$args);
520 return;
521 } elsif ($args->[0] eq 'verifyapi') {
522 PVE::RESTHandler::validate_method_schemas();
523 return;
524 } elsif ($args->[0] eq 'printmanpod') {
525 $podfn = find_cli_class_source($name) if !defined($podfn);
526 print_simple_pod_manpage($podfn, @$def);
527 return;
528 }
529 }
530
531 &$preparefunc() if $preparefunc;
532
533 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback, $stringfilemap);
534
535 &$outsub($res) if $outsub;
536 };
537
538 sub 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
545 run_cli_handler($class, podfn => $podfn, prepare => $preparefunc);
546 }
547
548 sub run_cli_handler {
549 my ($class, %params) = @_;
550
551 $cli_handler_class = $class;
552
553 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
554
555 foreach my $key (keys %params) {
556 next if $key eq 'podfn';
557 next if $key eq 'prepare';
558 next if $key eq 'no_init'; # used by lxc hooks
559 die "unknown parameter '$key'";
560 }
561
562 my $podfn = $params{podfn};
563 my $preparefunc = $params{prepare};
564 my $no_init = $params{no_init};
565
566 my $pwcallback = $class->can('read_password');
567 my $stringfilemap = $class->can('string_param_file_mapping');
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
576 PVE::INotify::inotify_init() if !$no_init;
577
578 my $rpcenv = PVE::RPCEnvironment->init('cli');
579 $rpcenv->init_request() if !$no_init;
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') {
588 &$handle_simple_cmd($def, \@ARGV, $pwcallback, $podfn, $preparefunc, $stringfilemap);
589 } else {
590 $cmddef = $def;
591 my $cmd = shift @ARGV;
592 &$handle_cmd($cmddef, $exename, $cmd, \@ARGV, $pwcallback, $podfn, $preparefunc, $stringfilemap);
593 }
594
595 exit 0;
596 }
597
598 1;