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