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