b32c2886e9fc9964da777680d21009790836cab6
[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 !($cmddef && $exename && $cli_handler_class);
117 my $pwcallback = $cli_handler_class->can('read_password');
118
119 my $synopsis = " $name help\n\n";
120 my $str = $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback);
121 $str =~ s/^USAGE://;
122 $str =~ s/\n/\n /g;
123 $synopsis .= $str;
124
125 my $parser = PVE::PodParser->new();
126 $parser->{include}->{synopsis} = $synopsis;
127 $parser->parse_from_file($podfn);
128 }
129
130 sub print_pod_manpage {
131 my ($podfn) = @_;
132
133 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
134 die "no pod file specified" if !$podfn;
135
136 my $pwcallback = $cli_handler_class->can('read_password');
137
138 my $synopsis = "";
139
140 $synopsis .= " $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
141
142 my $style = 'full'; # or should we use 'short'?
143 my $oldclass;
144 foreach my $cmd (sorted_commands()) {
145 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
146 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
147 $uri_param, $style, $pwcallback);
148 $str =~ s/^USAGE: //;
149
150 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
151 $str =~ s/\n/\n /g;
152 $synopsis .= " $str\n\n";
153 $oldclass = $class;
154 }
155
156 $synopsis .= "\n";
157
158 my $parser = PVE::PodParser->new();
159 $parser->{include}->{synopsis} = $synopsis;
160 $parser->parse_from_file($podfn);
161 }
162
163 sub print_usage_verbose {
164
165 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
166
167 my $pwcallback = $cli_handler_class->can('read_password');
168
169 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
170
171 foreach my $cmd (sort keys %$cmddef) {
172 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
173 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param,
174 'full', $pwcallback);
175 print "$str\n\n";
176 }
177 }
178
179 sub sorted_commands {
180 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
181 }
182
183 sub print_usage_short {
184 my ($fd, $msg) = @_;
185
186 die "not initialized" if !($cmddef && $exename && $cli_handler_class);
187
188 my $pwcallback = $cli_handler_class->can('read_password');
189
190 print $fd "ERROR: $msg\n" if $msg;
191 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
192
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, $uri_param, 'short', $pwcallback);
197 print $fd "\n" if $oldclass && $oldclass ne $class;
198 print $fd " $str";
199 $oldclass = $class;
200 }
201 }
202
203 my $print_bash_completion = sub {
204 my ($cmddef, $simple_cmd, $bash_command, $cur, $prev) = @_;
205
206 my $debug = 0;
207
208 return if !(defined($cur) && defined($prev) && defined($bash_command));
209 return if !defined($ENV{COMP_LINE});
210 return if !defined($ENV{COMP_POINT});
211
212 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
213 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
214
215 my $args = PVE::Tools::split_args($cmdline);
216 my $pos = scalar(@$args) - 2;
217 $pos += 1 if $cmdline =~ m/\s+$/;
218
219 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
220
221 return if $pos < 0;
222
223 my $print_result = sub {
224 foreach my $p (@_) {
225 print "$p\n" if $p =~ m/^$cur/;
226 }
227 };
228
229 my $cmd;
230 if ($simple_cmd) {
231 $cmd = $simple_cmd;
232 } else {
233 if ($pos == 0) {
234 &$print_result(keys %$cmddef);
235 return;
236 }
237 $cmd = $args->[1];
238 }
239
240 my $def = $cmddef->{$cmd};
241 return if !$def;
242
243 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
244
245 my $skip_param = {};
246
247 my ($class, $name, $arg_param, $uri_param) = @$def;
248 $arg_param //= [];
249 $uri_param //= {};
250
251 $arg_param = [ $arg_param ] if !ref($arg_param);
252
253 map { $skip_param->{$_} = 1; } @$arg_param;
254 map { $skip_param->{$_} = 1; } keys %$uri_param;
255
256 my $fpcount = scalar(@$arg_param);
257
258 my $info = $class->map_method_by_name($name);
259
260 my $schema = $info->{parameters};
261 my $prop = $schema->{properties};
262
263 my $print_parameter_completion = sub {
264 my ($pname) = @_;
265 my $d = $prop->{$pname};
266 if ($d->{completion}) {
267 my $vt = ref($d->{completion});
268 if ($vt eq 'CODE') {
269 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
270 &$print_result(@$res);
271 }
272 } elsif ($d->{type} eq 'boolean') {
273 &$print_result('0', '1');
274 } elsif ($d->{enum}) {
275 &$print_result(@{$d->{enum}});
276 }
277 };
278
279 # positional arguments
280 $pos += 1 if $simple_cmd;
281 if ($fpcount && $pos <= $fpcount) {
282 my $pname = $arg_param->[$pos -1];
283 &$print_parameter_completion($pname);
284 return;
285 }
286
287 my @option_list = ();
288 foreach my $key (keys %$prop) {
289 next if $skip_param->{$key};
290 push @option_list, "--$key";
291 }
292
293 if ($cur =~ m/^-/) {
294 &$print_result(@option_list);
295 return;
296 }
297
298 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
299 my $pname = $1;
300 &$print_parameter_completion($pname);
301 return;
302 }
303
304 &$print_result(@option_list);
305 };
306
307 sub verify_api {
308 my ($class) = @_;
309
310 # simply verify all registered methods
311 PVE::RESTHandler::validate_method_schemas();
312 }
313
314 my $get_exe_name = sub {
315 my ($class) = @_;
316
317 my $name = $class;
318 $name =~ s/^.*:://;
319 $name =~ s/_/-/g;
320
321 return $name;
322 };
323
324 sub generate_bash_completions {
325 my ($class) = @_;
326
327 # generate bash completion config
328
329 $exename = &$get_exe_name($class);
330
331 print <<__EOD__;
332 # $exename bash completion
333
334 # see http://tiswww.case.edu/php/chet/bash/FAQ
335 # and __ltrim_colon_completions() in /usr/share/bash-completion/bash_completion
336 # this modifies global var, but I found no better way
337 COMP_WORDBREAKS=\${COMP_WORDBREAKS//:}
338
339 complete -C '$exename bashcomplete' $exename
340 __EOD__
341 }
342
343 sub find_cli_class_source {
344 my ($name) = @_;
345
346 my $filename;
347
348 $name =~ s/-/_/g;
349
350 my $cpath = "PVE/CLI/${name}.pm";
351 my $spath = "PVE/Service/${name}.pm";
352 foreach my $p (@INC) {
353 foreach my $s (($cpath, $spath)) {
354 my $testfn = "$p/$s";
355 if (-f $testfn) {
356 $filename = $testfn;
357 last;
358 }
359 }
360 last if defined($filename);
361 }
362
363 return $filename;
364 }
365
366 sub generate_pod_manpage {
367 my ($class, $podfn) = @_;
368
369 $cli_handler_class = $class;
370
371 $exename = &$get_exe_name($class);
372
373 $podfn = find_cli_class_source($exename) if !defined($podfn);
374
375 die "unable to find source for class '$class'" if !$podfn;
376
377 no strict 'refs';
378 my $def = ${"${class}::cmddef"};
379
380 if (ref($def) eq 'ARRAY') {
381 print_simple_pod_manpage($podfn, @$def);
382 } else {
383 $cmddef = $def;
384
385 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
386
387 print_pod_manpage($podfn);
388 }
389 }
390
391 my $handle_cmd = sub {
392 my ($def, $cmdname, $cmd, $args, $pwcallback, $podfn, $preparefunc) = @_;
393
394 $cmddef = $def;
395 $exename = $cmdname;
396
397 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
398
399 if (!$cmd) {
400 print_usage_short (\*STDERR, "no command specified");
401 exit (-1);
402 } elsif ($cmd eq 'verifyapi') {
403 PVE::RESTHandler::validate_method_schemas();
404 return;
405 } elsif ($cmd eq 'printmanpod') {
406 $podfn = find_cli_class_source($exename) if !defined($podfn);
407 print_pod_manpage($podfn);
408 return;
409 } elsif ($cmd eq 'bashcomplete') {
410 &$print_bash_completion($cmddef, 0, @$args);
411 return;
412 }
413
414 &$preparefunc() if $preparefunc;
415
416 $cmd = &$expand_command_name($cmddef, $cmd);
417
418 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
419
420 if (!$class) {
421 print_usage_short (\*STDERR, "unknown command '$cmd'");
422 exit (-1);
423 }
424
425 my $prefix = "$exename $cmd";
426 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
427
428 &$outsub($res) if $outsub;
429 };
430
431 my $handle_simple_cmd = sub {
432 my ($def, $args, $pwcallback, $podfn, $preparefunc) = @_;
433
434 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
435 die "no class specified" if !$class;
436
437 if (scalar(@$args) >= 1) {
438 if ($args->[0] eq 'help') {
439 my $str = "USAGE: $name help\n";
440 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long', $pwcallback);
441 print STDERR "$str\n\n";
442 return;
443 } elsif ($args->[0] eq 'bashcomplete') {
444 shift @$args;
445 &$print_bash_completion({ $name => $def }, $name, @$args);
446 return;
447 } elsif ($args->[0] eq 'verifyapi') {
448 PVE::RESTHandler::validate_method_schemas();
449 return;
450 } elsif ($args->[0] eq 'printmanpod') {
451 $podfn = find_cli_class_source($name) if !defined($podfn);
452 print_simple_pod_manpage($podfn, @$def);
453 return;
454 }
455 }
456
457 &$preparefunc() if $preparefunc;
458
459 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
460
461 &$outsub($res) if $outsub;
462 };
463
464 sub run_cli {
465 my ($class, $pwcallback, $podfn, $preparefunc) = @_;
466
467 # Note: "depreciated function run_cli - use run_cli_handler instead";
468
469 die "password callback is no longer supported" if $pwcallback;
470
471 run_cli_handler($class, podfn => $podfn, preparefunc => $preparefunc);
472 }
473
474 sub run_cli_handler {
475 my ($class, %params) = @_;
476
477 $cli_handler_class = $class;
478
479 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
480
481 my $podfn = $params{podfn};
482 my $preparefunc = $params{preparefunc};
483
484 my $pwcallback = $class->can('read_password');
485
486 $exename = &$get_exe_name($class);
487
488 initlog($exename);
489
490 if ($class !~ m/^PVE::Service::/) {
491 die "please run as root\n" if $> != 0;
492
493 PVE::INotify::inotify_init();
494
495 my $rpcenv = PVE::RPCEnvironment->init('cli');
496 $rpcenv->init_request();
497 $rpcenv->set_language($ENV{LANG});
498 $rpcenv->set_user('root@pam');
499 }
500
501 no strict 'refs';
502 my $def = ${"${class}::cmddef"};
503
504 if (ref($def) eq 'ARRAY') {
505 &$handle_simple_cmd($def, \@ARGV, $pwcallback, $podfn, $preparefunc);
506 } else {
507 $cmddef = $def;
508 my $cmd = shift @ARGV;
509 &$handle_cmd($cmddef, $exename, $cmd, \@ARGV, $pwcallback, $podfn, $preparefunc);
510 }
511
512 exit 0;
513 }
514
515 1;